\n * ```\n * ```typescript\n * \n * ```\n */\nvar Calendar = /** @class */ (function (_super) {\n __extends(Calendar, _super);\n /**\n * Initialized new instance of Calendar Class.\n * Constructor for creating the widget\n * @param {CalendarModel} options?\n * @param {string|HTMLElement} element?\n */\n function Calendar(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * To Initialize the control rendering.\n * @returns void\n * @private\n */\n Calendar.prototype.render = function () {\n this.validateDate();\n this.minMaxUpdate();\n _super.prototype.render.call(this);\n if (this.getModuleName() === 'calendar') {\n var form = closest(this.element, 'form');\n if (form) {\n EventHandler.add(form, 'reset', this.formResetHandler.bind(this));\n }\n }\n };\n Calendar.prototype.formResetHandler = function () {\n this.value = null;\n };\n Calendar.prototype.validateDate = function () {\n if (typeof this.value === 'string') {\n this.setProperties({ value: this.checkDateValue(new Date('' + this.value)) }, true); // persist the value property.\n }\n _super.prototype.validateDate.call(this, this.value);\n if (!isNullOrUndefined(this.value) && this.min <= this.max && this.value >= this.min && this.value <= this.max) {\n this.currentDate = new Date('' + this.value);\n }\n if (isNaN(+this.value)) {\n this.setProperties({ value: null }, true);\n }\n };\n Calendar.prototype.minMaxUpdate = function () {\n if (this.getModuleName() === 'calendar') {\n if (!isNullOrUndefined(this.value) && this.value <= this.min && this.min <= this.max) {\n this.setProperties({ value: this.min }, true);\n this.changedArgs = { value: this.value };\n }\n else {\n if (!isNullOrUndefined(this.value) && this.value >= this.max && this.min <= this.max) {\n this.setProperties({ value: this.max }, true);\n this.changedArgs = { value: this.value };\n }\n }\n }\n if (this.getModuleName() !== 'calendar' && !isNullOrUndefined(this.value)) {\n if (!isNullOrUndefined(this.value) && this.value < this.min && this.min <= this.max) {\n _super.prototype.minMaxUpdate.call(this, this.min);\n }\n else {\n if (!isNullOrUndefined(this.value) && this.value > this.max && this.min <= this.max) {\n _super.prototype.minMaxUpdate.call(this, this.max);\n }\n }\n }\n else {\n _super.prototype.minMaxUpdate.call(this, this.value);\n }\n };\n Calendar.prototype.todayButtonClick = function () {\n if (this.showTodayButton) {\n var tempValue = new Date();\n if (this.value) {\n tempValue.setHours(this.value.getHours());\n tempValue.setMinutes(this.value.getMinutes());\n tempValue.setSeconds(this.value.getSeconds());\n tempValue.setMilliseconds(this.value.getMilliseconds());\n }\n else {\n tempValue = new Date(tempValue.getFullYear(), tempValue.getMonth(), tempValue.getDate(), 0, 0, 0, 0);\n }\n this.setProperties({ value: tempValue }, true);\n _super.prototype.todayButtonClick.call(this, new Date(+this.value));\n }\n };\n Calendar.prototype.keyActionHandle = function (e) {\n _super.prototype.keyActionHandle.call(this, e, this.value);\n };\n /**\n * Initialize the event handler\n * @private\n */\n Calendar.prototype.preRender = function () {\n var _this = this;\n this.changeHandler = function (e) {\n _this.triggerChange(e);\n };\n _super.prototype.preRender.call(this, this.value);\n };\n ;\n Calendar.prototype.createContent = function () {\n this.previousDate = this.value;\n _super.prototype.createContent.call(this);\n };\n Calendar.prototype.minMaxDate = function (localDate) {\n return _super.prototype.minMaxDate.call(this, localDate);\n };\n Calendar.prototype.renderMonths = function (e) {\n _super.prototype.renderMonths.call(this, e, this.value);\n };\n Calendar.prototype.renderDays = function (currentDate, e) {\n return _super.prototype.renderDays.call(this, currentDate, e, this.value);\n };\n Calendar.prototype.renderYears = function (e) {\n _super.prototype.renderYears.call(this, e, this.value);\n };\n Calendar.prototype.renderDecades = function (e) {\n _super.prototype.renderDecades.call(this, e, this.value);\n };\n Calendar.prototype.renderTemplate = function (elements, count, classNm, e) {\n _super.prototype.renderTemplate.call(this, elements, count, classNm, e, this.value);\n this.changedArgs = { value: this.value };\n this.changeHandler();\n };\n Calendar.prototype.clickHandler = function (e) {\n var eve = e.currentTarget;\n if (eve.classList.contains(OTHERMONTH)) {\n this.value = this.getIdValue(e, null);\n }\n _super.prototype.clickHandler.call(this, e, this.value);\n };\n Calendar.prototype.switchView = function (view, e) {\n _super.prototype.switchView.call(this, view, e);\n };\n /**\n * To get component name\n * @private\n */\n Calendar.prototype.getModuleName = function () {\n _super.prototype.getModuleName.call(this);\n return 'calendar';\n };\n /**\n * Gets the properties to be maintained upon browser refresh.\n * @returns string\n */\n Calendar.prototype.getPersistData = function () {\n _super.prototype.getPersistData.call(this);\n var keyEntity = ['value'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Called internally if any of the property value changed.\n * returns void\n * @private\n */\n Calendar.prototype.onPropertyChanged = function (newProp, oldProp) {\n this.effect = '';\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'value':\n if (typeof newProp.value === 'string') {\n this.setProperties({ value: new Date('' + newProp.value) }, true);\n }\n else {\n newProp.value = new Date('' + newProp.value);\n }\n if (isNaN(+this.value)) {\n this.setProperties({ value: oldProp.value }, true);\n }\n this.validateDate();\n this.minMaxUpdate();\n _super.prototype.setValueUpdate.call(this);\n break;\n default:\n _super.prototype.onPropertyChanged.call(this, newProp, oldProp);\n }\n }\n };\n /**\n * Destroys the widget.\n * @returns void\n */\n Calendar.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n if (this.getModuleName() === 'calendar') {\n var form = closest(this.element, 'form');\n if (form) {\n EventHandler.remove(form, 'reset', this.formResetHandler.bind(this));\n }\n }\n };\n /**\n * This method is used to navigate to the month/year/decade view of the Calendar.\n * @param {string} view - Specifies the view of the Calendar.\n * @param {Date} date - Specifies the focused date in a view.\n * @returns void\n */\n Calendar.prototype.navigateTo = function (view, date) {\n this.minMaxUpdate();\n _super.prototype.navigateTo.call(this, view, date);\n };\n /**\n * Gets the current view of the Calendar.\n * @returns string\n */\n Calendar.prototype.currentView = function () {\n return _super.prototype.currentView.call(this);\n };\n Calendar.prototype.selectDate = function (e, date, element) {\n _super.prototype.selectDate.call(this, e, date, element, this.value);\n this.changedArgs = { value: this.value };\n this.changeHandler(e);\n };\n Calendar.prototype.changeEvent = function (e) {\n this.trigger('change', this.changedArgs);\n this.previousDate = new Date(+this.value);\n };\n Calendar.prototype.triggerChange = function (e) {\n this.changedArgs.event = e || null;\n this.changedArgs.isInteracted = !isNullOrUndefined(e);\n if (!isNullOrUndefined(this.value)) {\n this.setProperties({ value: this.value }, true);\n }\n if (+this.value !== Number.NaN && +this.value !== +this.previousDate) {\n this.changeEvent(e);\n }\n };\n __decorate([\n Property(null)\n ], Calendar.prototype, \"value\", void 0);\n __decorate([\n Event()\n ], Calendar.prototype, \"change\", void 0);\n Calendar = __decorate([\n NotifyPropertyChanges\n ], Calendar);\n return Calendar;\n}(CalendarBase));\nexport { Calendar };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, Event, Collection, L10n, Browser, Complex, compile } from '@syncfusion/ej2-base';\nimport { addClass, removeClass, detach, attributes, prepend, setStyleAttribute } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, ChildProperty } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, formatUnit, append } from '@syncfusion/ej2-base';\nimport { EventHandler } from '@syncfusion/ej2-base';\nimport { Draggable } from '@syncfusion/ej2-base';\nimport { Popup, PositionData, getZindexPartial } from '../popup/popup';\nimport { Button } from '@syncfusion/ej2-buttons';\nvar ButtonProps = /** @class */ (function (_super) {\n __extends(ButtonProps, _super);\n function ButtonProps() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], ButtonProps.prototype, \"buttonModel\", void 0);\n __decorate([\n Property()\n ], ButtonProps.prototype, \"click\", void 0);\n return ButtonProps;\n}(ChildProperty));\nexport { ButtonProps };\n/**\n * Configures the animation properties for both open and close the dialog.\n */\nvar AnimationSettings = /** @class */ (function (_super) {\n __extends(AnimationSettings, _super);\n function AnimationSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Fade')\n ], AnimationSettings.prototype, \"effect\", void 0);\n __decorate([\n Property(400)\n ], AnimationSettings.prototype, \"duration\", void 0);\n __decorate([\n Property(0)\n ], AnimationSettings.prototype, \"delay\", void 0);\n return AnimationSettings;\n}(ChildProperty));\nexport { AnimationSettings };\nvar ROOT = 'e-dialog';\nvar RTL = 'e-rtl';\nvar DLG_HEADER_CONTENT = 'e-dlg-header-content';\nvar DLG_HEADER = 'e-dlg-header';\nvar DLG_FOOTER_CONTENT = 'e-footer-content';\nvar MODAL_DLG = 'e-dlg-modal';\nvar DLG_CONTENT = 'e-dlg-content';\nvar DLG_CLOSE_ICON = 'e-icon-dlg-close';\nvar DLG_OVERLAY = 'e-dlg-overlay';\nvar DLG_CONTAINER = 'e-dlg-container';\nvar SCROLL_DISABLED = 'e-scroll-disabled';\nvar DLG_PRIMARY_BUTTON = 'e-primary';\nvar ICON = 'e-icons';\nvar POPUP_ROOT = 'e-popup';\nvar DEVICE = 'e-device';\nvar FULLSCREEN = 'e-dlg-fullscreen';\nvar DLG_CLOSE_ICON_BTN = 'e-dlg-closeicon-btn';\nvar DLG_HIDE = 'e-popup-close';\nvar DLG_SHOW = 'e-popup-open';\n/**\n * Represents the dialog component that displays the information and get input from the user.\n * Two types of dialog components are `Modal and Modeless (non-modal)` depending on its interaction with parent application.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar Dialog = /** @class */ (function (_super) {\n __extends(Dialog, _super);\n /**\n * Constructor for creating the widget\n * @hidden\n */\n function Dialog(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * Initialize the control rendering\n * @private\n */\n Dialog.prototype.render = function () {\n this.initialize();\n this.initRender();\n this.wireEvents();\n };\n /**\n * Initialize the event handler\n * @private\n */\n Dialog.prototype.preRender = function () {\n var _this = this;\n this.headerContent = null;\n var classArray = [];\n for (var j = 0; j < this.element.classList.length; j++) {\n if (!isNullOrUndefined(this.element.classList[j].match('e-control')) ||\n !isNullOrUndefined(this.element.classList[j].match(ROOT))) {\n classArray.push(this.element.classList[j]);\n }\n }\n removeClass([this.element], classArray);\n this.clonedEle = this.element.cloneNode(true);\n this.closeIconClickEventHandler = function (event) {\n _this.hide(event);\n };\n this.dlgOverlayClickEventHandler = function (event) {\n _this.trigger('overlayClick', event);\n };\n var localeText = { close: 'Close' };\n this.l10n = new L10n('dialog', localeText, this.locale);\n if (isNullOrUndefined(this.target)) {\n var prevOnChange = this.isProtectedOnChange;\n this.isProtectedOnChange = true;\n this.target = document.body;\n this.isProtectedOnChange = prevOnChange;\n }\n };\n ;\n /* istanbul ignore next */\n Dialog.prototype.keyDown = function (event) {\n var _this = this;\n if (event.keyCode === 9) {\n if (this.isModal) {\n var buttonObj = void 0;\n if (!isNullOrUndefined(this.btnObj)) {\n buttonObj = this.btnObj[this.btnObj.length - 1];\n }\n if (!isNullOrUndefined(buttonObj) && document.activeElement === buttonObj.element && !event.shiftKey) {\n event.preventDefault();\n this.focusableElements(this.element).focus();\n }\n if (document.activeElement === this.focusableElements(this.element) && event.shiftKey) {\n event.preventDefault();\n if (!isNullOrUndefined(buttonObj)) {\n buttonObj.element.focus();\n }\n }\n }\n }\n var element = document.activeElement;\n var isTagName = (['input', 'textarea'].indexOf(element.tagName.toLowerCase()) > -1);\n var isContentEdit = false;\n if (!isTagName) {\n isContentEdit = element.hasAttribute('contenteditable') && element.getAttribute('contenteditable') === 'true';\n }\n if (event.keyCode === 27 && this.closeOnEscape) {\n this.hide(event);\n }\n if ((event.keyCode === 13 && !event.ctrlKey && element.tagName.toLowerCase() !== 'textarea' &&\n isTagName && !isNullOrUndefined(this.primaryButtonEle)) ||\n (event.keyCode === 13 && event.ctrlKey && (element.tagName.toLowerCase() === 'textarea' ||\n isContentEdit)) && !isNullOrUndefined(this.primaryButtonEle)) {\n var buttonIndex_1;\n var firstPrimary = this.buttons.some(function (data, index) {\n buttonIndex_1 = index;\n var buttonModel = data.buttonModel;\n return !isNullOrUndefined(buttonModel) && buttonModel.isPrimary === true;\n });\n if (firstPrimary && typeof (this.buttons[buttonIndex_1].click) === 'function') {\n setTimeout(function () {\n _this.buttons[buttonIndex_1].click.call(_this, event);\n });\n }\n }\n };\n /**\n * Initialize the control rendering\n * @private\n */\n Dialog.prototype.initialize = function () {\n if (!isNullOrUndefined(this.target)) {\n this.targetEle = ((typeof this.target) === 'string') ?\n document.querySelector(this.target) : this.target;\n }\n addClass([this.element], ROOT);\n if (Browser.isDevice) {\n addClass([this.element], DEVICE);\n }\n this.setCSSClass();\n this.setMaxHeight();\n };\n /**\n * Initialize the rendering\n * @private\n */\n Dialog.prototype.initRender = function () {\n var _this = this;\n this.initialRender = true;\n attributes(this.element, { role: 'dialog' });\n if (this.zIndex === 1000) {\n this.setzIndex(this.element, false);\n this.calculatezIndex = true;\n }\n else {\n this.calculatezIndex = false;\n }\n this.setTargetContent();\n if (this.header !== '' && !isNullOrUndefined(this.header)) {\n this.setHeader();\n }\n if (this.showCloseIcon) {\n this.renderCloseIcon();\n }\n this.setContent();\n if (this.footerTemplate !== '' && !isNullOrUndefined(this.footerTemplate)) {\n this.setFooterTemplate();\n }\n else if (!isNullOrUndefined(this.buttons[0].buttonModel)) {\n this.setButton();\n }\n if (this.allowDragging && (!isNullOrUndefined(this.headerContent))) {\n this.setAllowDragging();\n }\n attributes(this.element, { 'aria-modal': (this.isModal ? 'true' : 'false') });\n if (this.isModal) {\n this.setIsModal();\n }\n if (!isNullOrUndefined(this.targetEle)) {\n this.isModal ? this.targetEle.appendChild(this.dlgContainer) : this.targetEle.appendChild(this.element);\n }\n this.popupObj = new Popup(this.element, {\n height: this.height,\n width: this.width,\n zIndex: this.zIndex,\n relateTo: this.target,\n actionOnScroll: 'none',\n open: function (event) {\n _this.focusContent();\n var eventArgs = {\n container: _this.isModal ? _this.dlgContainer : _this.element,\n element: _this.element,\n target: _this.target\n };\n _this.trigger('open', eventArgs);\n },\n close: function (event) {\n _this.unBindEvent(_this.element);\n if (_this.isModal) {\n _this.dlgContainer.style.display = 'none';\n }\n _this.trigger('close', _this.closeArgs);\n if (!isNullOrUndefined(_this.storeActiveElement)) {\n _this.storeActiveElement.focus();\n }\n }\n });\n this.positionChange();\n this.setEnableRTL();\n addClass([this.element], DLG_HIDE);\n if (this.isModal) {\n this.setOverlayZindex();\n }\n if (this.visible) {\n this.show();\n }\n else {\n if (this.isModal) {\n this.dlgOverlay.style.display = 'none';\n }\n }\n this.initialRender = false;\n };\n Dialog.prototype.setOverlayZindex = function (zIndexValue) {\n var zIndex;\n if (isNullOrUndefined(zIndexValue)) {\n zIndex = parseInt(this.element.style.zIndex, 10) ? parseInt(this.element.style.zIndex, 10) : this.zIndex;\n }\n else {\n zIndex = zIndexValue;\n }\n this.dlgOverlay.style.zIndex = (zIndex - 1).toString();\n this.dlgContainer.style.zIndex = zIndex.toString();\n };\n Dialog.prototype.positionChange = function () {\n if (this.isModal) {\n if (typeof (this.position.X) === 'number' && typeof (this.position.Y) === 'number') {\n this.setPopupPosition();\n }\n else {\n this.element.style.top = '0px';\n this.element.style.left = '0px';\n this.dlgContainer.classList.add('e-dlg-' + this.position.X + '-' + this.position.Y);\n }\n }\n else {\n this.setPopupPosition();\n }\n };\n Dialog.prototype.setPopupPosition = function () {\n this.popupObj.setProperties({\n position: {\n X: this.position.X, Y: this.position.Y\n }\n });\n };\n Dialog.prototype.setAllowDragging = function () {\n var _this = this;\n var handleContent = '.' + DLG_HEADER_CONTENT;\n this.dragObj = new Draggable(this.element, {\n clone: false,\n abort: '.e-dlg-closeicon-btn',\n handle: handleContent,\n dragStart: function (event) {\n _this.trigger('dragStart', event);\n },\n dragStop: function (event) {\n if (_this.isModal) {\n if (!isNullOrUndefined(_this.position)) {\n _this.dlgContainer.classList.remove('e-dlg-' + _this.position.X + '-' + _this.position.Y);\n }\n // Reset the dialog position after drag completion.\n _this.element.style.position = 'relative';\n }\n _this.trigger('dragStop', event);\n },\n drag: function (event) {\n _this.trigger('drag', event);\n }\n });\n if (!isNullOrUndefined(this.targetEle)) {\n this.dragObj.dragArea = this.targetEle;\n }\n };\n Dialog.prototype.setButton = function () {\n this.buttonContent = [];\n this.btnObj = [];\n var primaryBtnFlag = true;\n for (var i = 0; i < this.buttons.length; i++) {\n var btn = this.createElement('button', { attrs: { type: 'button' } });\n this.buttonContent.push(btn.outerHTML);\n }\n this.setFooterTemplate();\n for (var i = 0; i < this.buttons.length; i++) {\n this.btnObj[i] = new Button(this.buttons[i].buttonModel);\n if (typeof (this.buttons[i].click) === 'function') {\n EventHandler.add(this.ftrTemplateContent.children[i], 'click', this.buttons[i].click, this);\n }\n this.btnObj[i].appendTo(this.ftrTemplateContent.children[i]);\n this.btnObj[i].element.classList.add('e-flat');\n this.primaryButtonEle = this.element.getElementsByClassName('e-primary')[0];\n }\n };\n Dialog.prototype.setContent = function () {\n attributes(this.element, { 'aria-describedby': this.element.id + '_dialog-content' });\n this.contentEle = this.createElement('div', { className: DLG_CONTENT, id: this.element.id + '_dialog-content' });\n if (this.innerContentElement) {\n this.contentEle.appendChild(this.innerContentElement);\n }\n else if (!isNullOrUndefined(this.content) && this.content !== '' || !this.initialRender) {\n if (typeof (this.content) === 'string') {\n this.contentEle.innerHTML = this.content;\n }\n else if (this.content instanceof HTMLElement) {\n this.contentEle.appendChild(this.content);\n }\n else {\n this.setTemplate(this.content, this.contentEle);\n }\n }\n if (!isNullOrUndefined(this.headerContent)) {\n this.element.insertBefore(this.contentEle, this.element.children[1]);\n }\n else {\n this.element.insertBefore(this.contentEle, this.element.children[0]);\n }\n if (this.height === 'auto') {\n this.setMaxHeight();\n }\n };\n Dialog.prototype.setTemplate = function (template, toElement) {\n var templateFn = compile(template);\n var fromElements = [];\n for (var _i = 0, _a = templateFn({}); _i < _a.length; _i++) {\n var item = _a[_i];\n fromElements.push(item);\n }\n append([].slice.call(fromElements), toElement);\n };\n Dialog.prototype.setMaxHeight = function () {\n var display = this.element.style.display;\n this.element.style.display = 'none';\n this.element.style.maxHeight = (!isNullOrUndefined(this.target)) ?\n (this.targetEle.offsetHeight - 20) + 'px' : (window.innerHeight - 20) + 'px';\n this.element.style.display = display;\n };\n Dialog.prototype.setEnableRTL = function () {\n this.enableRtl ? addClass([this.element], RTL) : removeClass([this.element], RTL);\n };\n Dialog.prototype.setTargetContent = function () {\n if (isNullOrUndefined(this.content) || this.content === '') {\n var isContent = this.element.innerHTML.replace(/\\s/g, '') !== '';\n if (this.element.children.length > 0 || isContent) {\n this.innerContentElement = document.createDocumentFragment();\n while (this.element.childNodes.length !== 0) {\n this.innerContentElement.appendChild(this.element.childNodes[0]);\n }\n }\n }\n };\n Dialog.prototype.setHeader = function () {\n if (this.headerEle) {\n this.headerEle.innerHTML = '';\n }\n else {\n this.headerEle = this.createElement('div', { id: this.element.id + '_title', className: DLG_HEADER });\n }\n this.createHeaderContent();\n this.headerContent.appendChild(this.headerEle);\n this.setTemplate(this.header, this.headerEle);\n attributes(this.element, { 'aria-labelledby': this.element.id + '_title' });\n this.element.insertBefore(this.headerContent, this.element.children[0]);\n };\n Dialog.prototype.setFooterTemplate = function () {\n if (this.ftrTemplateContent) {\n this.ftrTemplateContent.innerHTML = '';\n }\n else {\n this.ftrTemplateContent = this.createElement('div', {\n className: DLG_FOOTER_CONTENT\n });\n }\n if (this.footerTemplate !== '' && !isNullOrUndefined(this.footerTemplate)) {\n this.setTemplate(this.footerTemplate, this.ftrTemplateContent);\n }\n else {\n this.ftrTemplateContent.innerHTML = this.buttonContent.join('');\n }\n this.element.appendChild(this.ftrTemplateContent);\n };\n Dialog.prototype.createHeaderContent = function () {\n if (isNullOrUndefined(this.headerContent)) {\n this.headerContent = this.createElement('div', { className: DLG_HEADER_CONTENT });\n }\n };\n Dialog.prototype.renderCloseIcon = function () {\n this.closeIcon = this.createElement('button', { className: DLG_CLOSE_ICON_BTN, attrs: { type: 'button' } });\n this.closeIconBtnObj = new Button({ cssClass: 'e-flat', iconCss: DLG_CLOSE_ICON + ' ' + ICON });\n this.closeIconTitle();\n if (!isNullOrUndefined(this.headerContent)) {\n prepend([this.closeIcon], this.headerContent);\n }\n else {\n this.createHeaderContent();\n prepend([this.closeIcon], this.headerContent);\n this.element.insertBefore(this.headerContent, this.element.children[0]);\n }\n this.closeIconBtnObj.appendTo(this.closeIcon);\n };\n Dialog.prototype.closeIconTitle = function () {\n this.l10n.setLocale(this.locale);\n var closeIconTitle = this.l10n.getConstant('close');\n this.closeIcon.setAttribute('title', closeIconTitle);\n };\n Dialog.prototype.setCSSClass = function (oldCSSClass) {\n if (this.cssClass) {\n addClass([this.element], this.cssClass.split(' '));\n }\n if (oldCSSClass) {\n removeClass([this.element], oldCSSClass.split(' '));\n }\n };\n Dialog.prototype.setIsModal = function () {\n this.dlgContainer = this.createElement('div', { className: DLG_CONTAINER });\n this.element.classList.remove(DLG_SHOW);\n this.element.parentNode.insertBefore(this.dlgContainer, this.element);\n this.dlgContainer.appendChild(this.element);\n addClass([this.element], MODAL_DLG);\n this.dlgOverlay = this.createElement('div', { className: DLG_OVERLAY });\n this.dlgOverlay.style.zIndex = (this.zIndex - 1).toString();\n this.dlgContainer.appendChild(this.dlgOverlay);\n };\n Dialog.prototype.getValidFocusNode = function (items) {\n var node;\n for (var u = 0; u < items.length; u++) {\n node = items[u];\n if ((node.clientHeight > 0 || (node.tagName.toLowerCase() === 'a' && node.hasAttribute('href'))) && node.tabIndex > -1 &&\n !node.disabled && !this.disableElement(node, '[disabled],[aria-disabled=\"true\"],[type=\"hidden\"]')) {\n return node;\n }\n }\n return node;\n };\n Dialog.prototype.focusableElements = function (content) {\n if (!isNullOrUndefined(content)) {\n var value = 'input,select,textarea,button,a,[contenteditable=\"true\"],[tabindex]';\n var items = content.querySelectorAll(value);\n return this.getValidFocusNode(items);\n }\n return null;\n };\n Dialog.prototype.getAutoFocusNode = function (container) {\n var node = container.querySelector('.' + DLG_CLOSE_ICON_BTN);\n var value = '[autofocus]';\n var items = container.querySelectorAll(value);\n var validNode = this.getValidFocusNode(items);\n if (!isNullOrUndefined(validNode)) {\n node = validNode;\n }\n else {\n validNode = this.focusableElements(this.contentEle);\n if (!isNullOrUndefined(validNode)) {\n return node = validNode;\n }\n else if (!isNullOrUndefined(this.primaryButtonEle)) {\n return this.element.querySelector('.' + DLG_PRIMARY_BUTTON);\n }\n }\n return node;\n };\n Dialog.prototype.disableElement = function (element, t) {\n var elementMatch = element ? element.matches || element.webkitMatchesSelector || element.msMatchesSelector : null;\n if (elementMatch) {\n for (; element; element = element.parentNode) {\n if (element instanceof Element && elementMatch.call(element, t)) {\n /* istanbul ignore next */\n return element;\n }\n }\n }\n return null;\n };\n Dialog.prototype.focusContent = function () {\n var element = this.getAutoFocusNode(this.element);\n var node = !isNullOrUndefined(element) ? element : this.element;\n node.focus();\n this.bindEvent(this.element);\n };\n Dialog.prototype.bindEvent = function (element) {\n EventHandler.add(element, 'keydown', this.keyDown, this);\n };\n Dialog.prototype.unBindEvent = function (element) {\n EventHandler.remove(element, 'keydown', this.keyDown);\n };\n /**\n * Module required function\n * @private\n */\n Dialog.prototype.getModuleName = function () {\n return 'dialog';\n };\n /**\n * Called internally if any of the property value changed\n * @private\n */\n Dialog.prototype.onPropertyChanged = function (newProp, oldProp) {\n if (!this.element.classList.contains(ROOT)) {\n return;\n }\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'content':\n if (!isNullOrUndefined(this.content) && this.content !== '') {\n if (!isNullOrUndefined(this.contentEle) && this.contentEle.getAttribute('role') !== 'dialog') {\n this.contentEle.innerHTML = '';\n typeof (this.content) === 'string' ?\n this.contentEle.innerHTML = this.content : this.contentEle.appendChild(this.content);\n this.setMaxHeight();\n }\n else {\n this.setContent();\n }\n }\n else if (!isNullOrUndefined(this.contentEle)) {\n detach(this.contentEle);\n this.contentEle = null;\n }\n break;\n case 'header':\n if (this.header === '' || isNullOrUndefined(this.header)) {\n if (this.headerEle) {\n detach(this.headerEle);\n this.headerEle = null;\n }\n }\n else {\n this.setHeader();\n }\n break;\n case 'footerTemplate':\n if (this.footerTemplate === '' || isNullOrUndefined(this.footerTemplate)) {\n if (!this.ftrTemplateContent) {\n return;\n }\n detach(this.ftrTemplateContent);\n this.ftrTemplateContent = null;\n this.buttons = [{}];\n }\n else {\n this.setFooterTemplate();\n this.buttons = [{}];\n }\n break;\n case 'showCloseIcon':\n if (this.element.getElementsByClassName(DLG_CLOSE_ICON).length > 0) {\n if (!this.showCloseIcon && (this.header === '' || isNullOrUndefined(this.header))) {\n detach(this.headerContent);\n this.headerContent = null;\n }\n else if (!this.showCloseIcon) {\n detach(this.closeIcon);\n }\n }\n else {\n this.renderCloseIcon();\n this.wireEvents();\n }\n break;\n case 'locale':\n if (this.showCloseIcon) {\n this.closeIconTitle();\n }\n break;\n case 'visible':\n this.visible ? this.show() : this.hide();\n break;\n case 'isModal':\n this.updateIsModal();\n break;\n case 'height':\n setStyleAttribute(this.element, { 'height': formatUnit(newProp.height) });\n break;\n case 'width':\n setStyleAttribute(this.element, { 'width': formatUnit(newProp.width) });\n break;\n case 'zIndex':\n this.popupObj.zIndex = this.zIndex;\n if (this.isModal) {\n this.setOverlayZindex(this.zIndex);\n }\n break;\n case 'cssClass':\n this.setCSSClass(oldProp.cssClass);\n break;\n case 'buttons':\n if (!isNullOrUndefined(this.buttons[0].buttonModel)) {\n if (!isNullOrUndefined(this.ftrTemplateContent)) {\n detach(this.ftrTemplateContent);\n this.ftrTemplateContent = null;\n }\n this.footerTemplate = '';\n this.setButton();\n }\n break;\n case 'allowDragging':\n if (this.allowDragging && (!isNullOrUndefined(this.headerContent))) {\n this.setAllowDragging();\n }\n else {\n this.dragObj.destroy();\n }\n break;\n case 'target':\n this.popupObj.relateTo = newProp.target;\n break;\n case 'position':\n if (this.isModal) {\n var positionX = isNullOrUndefined(oldProp.position.X) ? this.position.X : oldProp.position.X;\n var positionY = isNullOrUndefined(oldProp.position.Y) ? this.position.Y : oldProp.position.Y;\n if (this.dlgContainer.classList.contains('e-dlg-' + positionX + '-' + positionY)) {\n this.dlgContainer.classList.remove('e-dlg-' + positionX + '-' + positionY);\n }\n }\n this.positionChange();\n break;\n case 'enableRtl':\n this.setEnableRTL();\n break;\n }\n }\n };\n Dialog.prototype.updateIsModal = function () {\n this.element.setAttribute('aria-modal', this.isModal ? 'true' : 'false');\n if (this.isModal) {\n this.setIsModal();\n this.element.style.top = '0px';\n this.element.style.left = '0px';\n if (!isNullOrUndefined(this.targetEle)) {\n this.targetEle.appendChild(this.dlgContainer);\n }\n }\n else {\n removeClass([this.element], MODAL_DLG);\n removeClass([document.body], SCROLL_DISABLED);\n detach(this.dlgOverlay);\n while (this.dlgContainer.firstChild) {\n this.dlgContainer.parentElement.insertBefore(this.dlgContainer.firstChild, this.dlgContainer);\n }\n this.dlgContainer.parentElement.removeChild(this.dlgContainer);\n }\n if (this.visible) {\n this.show();\n }\n this.positionChange();\n };\n Dialog.prototype.setzIndex = function (zIndexElement, setPopupZindex) {\n var prevOnChange = this.isProtectedOnChange;\n this.isProtectedOnChange = true;\n this.zIndex = getZindexPartial(zIndexElement);\n this.isProtectedOnChange = prevOnChange;\n if (setPopupZindex) {\n this.popupObj.zIndex = this.zIndex;\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n Dialog.prototype.getPersistData = function () {\n return this.addOnPersist([]);\n };\n /**\n * To destroy the widget\n * @method destroy\n * @return {void}\n * @memberof dialog\n */\n Dialog.prototype.destroy = function () {\n if (this.element.classList.contains(ROOT)) {\n this.unWireEvents();\n _super.prototype.destroy.call(this);\n var classArray = [\n ROOT, RTL, MODAL_DLG\n ];\n removeClass([this.element, this.element], classArray);\n if (this.popupObj.element.classList.contains(POPUP_ROOT)) {\n this.popupObj.destroy();\n }\n /* istanbul ignore next */\n if (!isNullOrUndefined(this.btnObj)) {\n for (var i = void 0; i < this.btnObj.length; i++) {\n this.btnObj[i].destroy();\n }\n }\n if (this.isModal) {\n detach(this.dlgOverlay);\n this.dlgContainer.parentNode.insertBefore(this.element, this.dlgContainer);\n detach(this.dlgContainer);\n }\n this.element.innerHTML = '';\n while (this.element.attributes.length > 0) {\n this.element.removeAttribute(this.element.attributes[0].name);\n }\n for (var k = 0; k < this.clonedEle.attributes.length; k++) {\n this.element.setAttribute(this.clonedEle.attributes[k].name, this.clonedEle.attributes[k].value);\n }\n }\n };\n /**\n * Binding event to the element while widget creation\n * @hidden\n */\n Dialog.prototype.wireEvents = function () {\n if (this.showCloseIcon) {\n EventHandler.add(this.closeIcon, 'click', this.closeIconClickEventHandler, this);\n }\n if (this.isModal) {\n EventHandler.add(this.dlgOverlay, 'click', this.dlgOverlayClickEventHandler, this);\n }\n };\n /**\n * Unbinding event to the element while widget destroy\n * @hidden\n */\n Dialog.prototype.unWireEvents = function () {\n if (this.showCloseIcon) {\n EventHandler.remove(this.closeIcon, 'click', this.closeIconClickEventHandler);\n }\n if (this.isModal) {\n EventHandler.remove(this.dlgOverlay, 'click', this.dlgOverlayClickEventHandler);\n }\n if (!isNullOrUndefined(this.buttons[0].buttonModel)) {\n for (var i = 0; i < this.buttons.length; i++) {\n if (typeof (this.buttons[i].click) === 'function') {\n EventHandler.remove(this.ftrTemplateContent.children[i], 'click', this.buttons[i].click);\n }\n }\n }\n };\n /**\n * Refreshes the dialog's position when the user changes its header and footer height/width dynamically.\n * @return {void}\n */\n Dialog.prototype.refreshPosition = function () {\n this.popupObj.refreshPosition();\n };\n /**\n * Opens the dialog if it is in hidden state.\n * To open the dialog with full screen width, set the parameter to true.\n * @param { boolean } isFullScreen - Enable the fullScreen Dialog.\n * @return {void}\n */\n Dialog.prototype.show = function (isFullScreen) {\n if (!this.element.classList.contains(ROOT)) {\n return;\n }\n if (!this.element.classList.contains(DLG_SHOW) || (!isNullOrUndefined(isFullScreen))) {\n if (!isNullOrUndefined(isFullScreen)) {\n this.fullScreen(isFullScreen);\n }\n var eventArgs = {\n cancel: false,\n element: this.element,\n container: this.isModal ? this.dlgContainer : this.element,\n target: this.target\n };\n this.trigger('beforeOpen', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.storeActiveElement = document.activeElement;\n this.element.tabIndex = -1;\n if (this.isModal && (!isNullOrUndefined(this.dlgOverlay))) {\n this.dlgOverlay.style.display = 'block';\n this.dlgContainer.style.display = 'flex';\n if (!isNullOrUndefined(this.targetEle)) {\n if (this.targetEle === document.body) {\n this.dlgContainer.style.position = 'fixed';\n }\n else {\n this.dlgContainer.style.position = 'absolute';\n }\n this.dlgOverlay.style.position = 'absolute';\n this.element.style.position = 'relative';\n addClass([this.targetEle], SCROLL_DISABLED);\n }\n else {\n addClass([document.body], SCROLL_DISABLED);\n }\n }\n var openAnimation = {\n name: this.animationSettings.effect + 'In',\n duration: this.animationSettings.duration,\n delay: this.animationSettings.delay\n };\n var zIndexElement = (this.isModal) ? this.element.parentElement : this.element;\n if (this.calculatezIndex) {\n this.setzIndex(zIndexElement, true);\n setStyleAttribute(this.element, { 'zIndex': this.zIndex });\n if (this.isModal) {\n this.setOverlayZindex(this.zIndex);\n }\n }\n this.animationSettings.effect === 'None' ? this.popupObj.show() : this.popupObj.show(openAnimation);\n this.dialogOpen = true;\n var prevOnChange = this.isProtectedOnChange;\n this.isProtectedOnChange = true;\n this.visible = true;\n this.isProtectedOnChange = prevOnChange;\n }\n };\n /**\n * Closes the dialog if it is in visible state.\n * @return {void}\n */\n Dialog.prototype.hide = function (event) {\n if (!this.element.classList.contains(ROOT)) {\n return;\n }\n var eventArgs = {\n cancel: false,\n isInteraction: event ? true : false,\n element: this.element,\n target: this.target,\n container: this.isModal ? this.dlgContainer : this.element,\n event: event\n };\n this.trigger('beforeClose', eventArgs);\n this.closeArgs = eventArgs;\n if (eventArgs.cancel) {\n return;\n }\n if (this.isModal) {\n this.dlgOverlay.style.display = 'none';\n !isNullOrUndefined(this.targetEle) ? removeClass([this.targetEle], SCROLL_DISABLED) :\n removeClass([document.body], SCROLL_DISABLED);\n }\n var closeAnimation = {\n name: this.animationSettings.effect + 'Out',\n duration: this.animationSettings.duration,\n delay: this.animationSettings.delay\n };\n this.animationSettings.effect === 'None' ? this.popupObj.hide() : this.popupObj.hide(closeAnimation);\n this.dialogOpen = false;\n var prevOnChange = this.isProtectedOnChange;\n this.isProtectedOnChange = true;\n this.visible = false;\n this.isProtectedOnChange = prevOnChange;\n };\n /**\n * Specifies to view the Full screen Dialog.\n * @private\n */\n Dialog.prototype.fullScreen = function (args) {\n var top = this.element.offsetTop;\n var left = this.element.offsetLeft;\n if (args) {\n addClass([this.element], FULLSCREEN);\n var display = this.element.style.display;\n this.element.style.display = 'none';\n this.element.style.maxHeight = (!isNullOrUndefined(this.target)) ?\n (this.targetEle.offsetHeight) + 'px' : (window.innerHeight) + 'px';\n this.element.style.display = display;\n addClass([document.body], SCROLL_DISABLED);\n if (this.allowDragging && !isNullOrUndefined(this.dragObj)) {\n this.dragObj.destroy();\n }\n }\n else {\n removeClass([this.element], FULLSCREEN);\n removeClass([document.body], SCROLL_DISABLED);\n if (this.allowDragging && (!isNullOrUndefined(this.headerContent))) {\n this.setAllowDragging();\n }\n }\n return args;\n };\n __decorate([\n Property('')\n ], Dialog.prototype, \"content\", void 0);\n __decorate([\n Property(false)\n ], Dialog.prototype, \"showCloseIcon\", void 0);\n __decorate([\n Property(false)\n ], Dialog.prototype, \"isModal\", void 0);\n __decorate([\n Property('')\n ], Dialog.prototype, \"header\", void 0);\n __decorate([\n Property(true)\n ], Dialog.prototype, \"visible\", void 0);\n __decorate([\n Property('auto')\n ], Dialog.prototype, \"height\", void 0);\n __decorate([\n Property('100%')\n ], Dialog.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], Dialog.prototype, \"cssClass\", void 0);\n __decorate([\n Property(1000)\n ], Dialog.prototype, \"zIndex\", void 0);\n __decorate([\n Property(null)\n ], Dialog.prototype, \"target\", void 0);\n __decorate([\n Property('')\n ], Dialog.prototype, \"footerTemplate\", void 0);\n __decorate([\n Property(false)\n ], Dialog.prototype, \"allowDragging\", void 0);\n __decorate([\n Collection([{}], ButtonProps)\n ], Dialog.prototype, \"buttons\", void 0);\n __decorate([\n Property(true)\n ], Dialog.prototype, \"closeOnEscape\", void 0);\n __decorate([\n Complex({}, AnimationSettings)\n ], Dialog.prototype, \"animationSettings\", void 0);\n __decorate([\n Complex({ X: 'center', Y: 'center' }, PositionData)\n ], Dialog.prototype, \"position\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"beforeClose\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"dragStart\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"dragStop\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"drag\", void 0);\n __decorate([\n Event()\n ], Dialog.prototype, \"overlayClick\", void 0);\n Dialog = __decorate([\n NotifyPropertyChanges\n ], Dialog);\n return Dialog;\n}(Component));\nexport { Dialog };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, ChildProperty, Event, append, compile } from '@syncfusion/ej2-base';\nimport { EventHandler, Touch, Browser, Animation as PopupAnimation } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, getUniqueID, formatUnit } from '@syncfusion/ej2-base';\nimport { attributes, closest, removeClass, addClass, remove } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, Complex } from '@syncfusion/ej2-base';\nimport { Popup } from '../popup/popup';\nimport { calculatePosition } from '../common/position';\nimport { isCollide, fit } from '../common/collision';\nvar TOUCHEND_HIDE_DELAY = 1500;\nvar TAPHOLD_THRESHOLD = 500;\nvar SHOW_POINTER_TIP_GAP = 0;\nvar HIDE_POINTER_TIP_GAP = 8;\nvar MOUSE_TRAIL_GAP = 2;\nvar POINTER_ADJUST = 2;\nvar ROOT = 'e-tooltip';\nvar RTL = 'e-rtl';\nvar DEVICE = 'e-bigger';\nvar ICON = 'e-icons';\nvar CLOSE = 'e-tooltip-close';\nvar TOOLTIP_WRAP = 'e-tooltip-wrap';\nvar CONTENT = 'e-tip-content';\nvar ARROW_TIP = 'e-arrow-tip';\nvar ARROW_TIP_OUTER = 'e-arrow-tip-outer';\nvar ARROW_TIP_INNER = 'e-arrow-tip-inner';\nvar TIP_BOTTOM = 'e-tip-bottom';\nvar TIP_TOP = 'e-tip-top';\nvar TIP_LEFT = 'e-tip-left';\nvar TIP_RIGHT = 'e-tip-right';\nvar POPUP_ROOT = 'e-popup';\nvar POPUP_OPEN = 'e-popup-open';\nvar POPUP_CLOSE = 'e-popup-close';\nvar Animation = /** @class */ (function (_super) {\n __extends(Animation, _super);\n function Animation() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property({ effect: 'FadeIn', duration: 150, delay: 0 })\n ], Animation.prototype, \"open\", void 0);\n __decorate([\n Property({ effect: 'FadeOut', duration: 150, delay: 0 })\n ], Animation.prototype, \"close\", void 0);\n return Animation;\n}(ChildProperty));\nexport { Animation };\n/**\n * Represents the Tooltip component that displays a piece of information about the target element on mouse hover.\n * ```html\n *
Show Tooltip
\n * ```\n * ```typescript\n * \n * ```\n */\nvar Tooltip = /** @class */ (function (_super) {\n __extends(Tooltip, _super);\n /**\n * Constructor for creating the Tooltip Component\n */\n function Tooltip(options, element) {\n return _super.call(this, options, element) || this;\n }\n Tooltip.prototype.initialize = function () {\n this.formatPosition();\n addClass([this.element], ROOT);\n };\n Tooltip.prototype.formatPosition = function () {\n if (this.position.indexOf('Top') === 0 || this.position.indexOf('Bottom') === 0) {\n _a = this.position.split(/(?=[A-Z])/), this.tooltipPositionY = _a[0], this.tooltipPositionX = _a[1];\n }\n else {\n _b = this.position.split(/(?=[A-Z])/), this.tooltipPositionX = _b[0], this.tooltipPositionY = _b[1];\n }\n var _a, _b;\n };\n Tooltip.prototype.renderArrow = function () {\n this.setTipClass(this.position);\n var tip = this.createElement('div', { className: ARROW_TIP + ' ' + this.tipClass });\n tip.appendChild(this.createElement('div', { className: ARROW_TIP_OUTER + ' ' + this.tipClass }));\n tip.appendChild(this.createElement('div', { className: ARROW_TIP_INNER + ' ' + this.tipClass }));\n this.tooltipEle.appendChild(tip);\n };\n Tooltip.prototype.setTipClass = function (position) {\n if (position.indexOf('Right') === 0) {\n this.tipClass = TIP_LEFT;\n }\n else if (position.indexOf('Bottom') === 0) {\n this.tipClass = TIP_TOP;\n }\n else if (position.indexOf('Left') === 0) {\n this.tipClass = TIP_RIGHT;\n }\n else {\n this.tipClass = TIP_BOTTOM;\n }\n };\n Tooltip.prototype.renderPopup = function (target) {\n var elePos = this.mouseTrail ? { top: 0, left: 0 } : this.getTooltipPosition(target);\n this.popupObj = new Popup(this.tooltipEle, {\n height: this.height,\n width: this.width,\n position: {\n X: elePos.left,\n Y: elePos.top\n },\n enableRtl: this.enableRtl,\n open: this.openPopupHandler.bind(this),\n close: this.closePopupHandler.bind(this)\n });\n };\n Tooltip.prototype.getTooltipPosition = function (target) {\n this.tooltipEle.style.display = 'none';\n var pos = calculatePosition(target, this.tooltipPositionX, this.tooltipPositionY);\n this.tooltipEle.style.display = '';\n var offsetPos = this.calculateTooltipOffset(this.position);\n var elePos = this.collisionFlipFit(target, pos.left + offsetPos.left, pos.top + offsetPos.top);\n return elePos;\n };\n Tooltip.prototype.reposition = function (target) {\n var elePos = this.getTooltipPosition(target);\n this.popupObj.position = { X: elePos.left, Y: elePos.top };\n this.popupObj.dataBind();\n };\n Tooltip.prototype.openPopupHandler = function () {\n this.trigger('afterOpen', this.tooltipEventArgs);\n };\n Tooltip.prototype.closePopupHandler = function () {\n this.clear();\n this.trigger('afterClose', this.tooltipEventArgs);\n };\n Tooltip.prototype.calculateTooltipOffset = function (position) {\n var pos = { top: 0, left: 0 };\n var tooltipEleWidth = this.tooltipEle.offsetWidth;\n var tooltipEleHeight = this.tooltipEle.offsetHeight;\n var arrowEle = this.tooltipEle.querySelector('.' + ARROW_TIP);\n var tipWidth = arrowEle ? arrowEle.offsetWidth : 0;\n var tipHeight = arrowEle ? arrowEle.offsetHeight : 0;\n var tipAdjust = (this.showTipPointer ? SHOW_POINTER_TIP_GAP : HIDE_POINTER_TIP_GAP);\n var tipHeightAdjust = (tipHeight / 2) + POINTER_ADJUST + (this.tooltipEle.offsetHeight - this.tooltipEle.clientHeight);\n var tipWidthAdjust = (tipWidth / 2) + POINTER_ADJUST + (this.tooltipEle.offsetWidth - this.tooltipEle.clientWidth);\n if (this.mouseTrail) {\n tipAdjust += MOUSE_TRAIL_GAP;\n }\n switch (position) {\n case 'RightTop':\n pos.left += tipWidth + tipAdjust;\n pos.top -= tooltipEleHeight - tipHeightAdjust;\n break;\n case 'RightCenter':\n pos.left += tipWidth + tipAdjust;\n pos.top -= (tooltipEleHeight / 2);\n break;\n case 'RightBottom':\n pos.left += tipWidth + tipAdjust;\n pos.top -= (tipHeightAdjust);\n break;\n case 'BottomRight':\n pos.top += (tipHeight + tipAdjust);\n pos.left -= (tipWidthAdjust);\n break;\n case 'BottomCenter':\n pos.top += (tipHeight + tipAdjust);\n pos.left -= (tooltipEleWidth / 2);\n break;\n case 'BottomLeft':\n pos.top += (tipHeight + tipAdjust);\n pos.left -= (tooltipEleWidth - tipWidthAdjust);\n break;\n case 'LeftBottom':\n pos.left -= (tipWidth + tooltipEleWidth + tipAdjust);\n pos.top -= (tipHeightAdjust);\n break;\n case 'LeftCenter':\n pos.left -= (tipWidth + tooltipEleWidth + tipAdjust);\n pos.top -= (tooltipEleHeight / 2);\n break;\n case 'LeftTop':\n pos.left -= (tipWidth + tooltipEleWidth + tipAdjust);\n pos.top -= (tooltipEleHeight - tipHeightAdjust);\n break;\n case 'TopLeft':\n pos.top -= (tooltipEleHeight + tipHeight + tipAdjust);\n pos.left -= (tooltipEleWidth - tipWidthAdjust);\n break;\n case 'TopRight':\n pos.top -= (tooltipEleHeight + tipHeight + tipAdjust);\n pos.left -= (tipWidthAdjust);\n break;\n default:\n pos.top -= (tooltipEleHeight + tipHeight + tipAdjust);\n pos.left -= (tooltipEleWidth / 2);\n break;\n }\n pos.left += this.offsetX;\n pos.top += this.offsetY;\n return pos;\n };\n Tooltip.prototype.updateTipPosition = function (position) {\n var selEle = this.tooltipEle.querySelectorAll('.' + ARROW_TIP + ',.' + ARROW_TIP_OUTER + ',.' + ARROW_TIP_INNER);\n var removeList = [TIP_BOTTOM, TIP_TOP, TIP_LEFT, TIP_RIGHT];\n removeClass(selEle, removeList);\n this.setTipClass(position);\n addClass(selEle, this.tipClass);\n };\n Tooltip.prototype.adjustArrow = function (target, position, tooltipPositionX, tooltipPositionY) {\n if (this.showTipPointer === false) {\n return;\n }\n this.updateTipPosition(position);\n var leftValue;\n var topValue;\n var tooltipWidth = this.tooltipEle.clientWidth;\n var tooltipHeight = this.tooltipEle.clientHeight;\n var arrowEle = this.tooltipEle.querySelector('.' + ARROW_TIP);\n var arrowInnerELe = this.tooltipEle.querySelector('.' + ARROW_TIP_INNER);\n var tipWidth = arrowEle.offsetWidth;\n var tipHeight = arrowEle.offsetHeight;\n if (this.tipClass === TIP_BOTTOM || this.tipClass === TIP_TOP) {\n if (this.tipClass === TIP_BOTTOM) {\n topValue = '99.9%';\n // Arrow icon aligned -2px height from ArrowOuterTip div\n arrowInnerELe.style.top = '-' + (tipHeight - 2) + 'px';\n }\n else {\n topValue = -(tipHeight - 1) + 'px';\n // Arrow icon aligned -6px height from ArrowOuterTip div\n arrowInnerELe.style.top = '-' + (tipHeight - 6) + 'px';\n }\n var tipPosExclude = tooltipPositionX !== 'Center' || (tooltipWidth > target.offsetWidth) || this.mouseTrail;\n if ((tipPosExclude && tooltipPositionX === 'Left') || (!tipPosExclude && this.tipPointerPosition === 'End')) {\n leftValue = (tooltipWidth - tipWidth - POINTER_ADJUST) + 'px';\n }\n else if ((tipPosExclude && tooltipPositionX === 'Right') || (!tipPosExclude && this.tipPointerPosition === 'Start')) {\n leftValue = POINTER_ADJUST + 'px';\n }\n else {\n leftValue = ((tooltipWidth / 2) - (tipWidth / 2)) + 'px';\n }\n }\n else {\n if (this.tipClass === TIP_RIGHT) {\n leftValue = '99.9%';\n // Arrow icon aligned -2px left from ArrowOuterTip div\n arrowInnerELe.style.left = '-' + (tipWidth - 2) + 'px';\n }\n else {\n leftValue = -(tipWidth - 1) + 'px';\n // Arrow icon aligned -2px from ArrowOuterTip width\n arrowInnerELe.style.left = (-(tipWidth) + (tipWidth - 2)) + 'px';\n }\n var tipPosExclude = tooltipPositionY !== 'Center' || (tooltipHeight > target.offsetHeight) || this.mouseTrail;\n if ((tipPosExclude && tooltipPositionY === 'Top') || (!tipPosExclude && this.tipPointerPosition === 'End')) {\n topValue = (tooltipHeight - tipHeight - POINTER_ADJUST) + 'px';\n }\n else if ((tipPosExclude && tooltipPositionY === 'Bottom') || (!tipPosExclude && this.tipPointerPosition === 'Start')) {\n topValue = POINTER_ADJUST + 'px';\n }\n else {\n topValue = ((tooltipHeight / 2) - (tipHeight / 2)) + 'px';\n }\n }\n arrowEle.style.top = topValue;\n arrowEle.style.left = leftValue;\n };\n Tooltip.prototype.renderContent = function (target) {\n var tooltipContent = this.tooltipEle.querySelector('.' + CONTENT);\n if (target && !isNullOrUndefined(target.getAttribute('title'))) {\n target.setAttribute('data-content', target.getAttribute('title'));\n target.removeAttribute('title');\n }\n if (!isNullOrUndefined(this.content)) {\n tooltipContent.innerHTML = '';\n if (this.content instanceof HTMLElement) {\n tooltipContent.appendChild(this.content);\n }\n else if (typeof this.content === 'string') {\n tooltipContent.innerHTML = this.content;\n }\n else {\n var templateFunction = compile(this.content);\n append(templateFunction(), tooltipContent);\n }\n }\n else {\n if (target && !isNullOrUndefined(target.getAttribute('data-content'))) {\n tooltipContent.innerHTML = target.getAttribute('data-content');\n }\n }\n };\n Tooltip.prototype.renderCloseIcon = function () {\n if (!this.isSticky) {\n return;\n }\n var tipClose = this.createElement('div', { className: ICON + ' ' + CLOSE });\n this.tooltipEle.appendChild(tipClose);\n EventHandler.add(tipClose, Browser.touchStartEvent, this.onStickyClose, this);\n };\n Tooltip.prototype.addDescribedBy = function (target, id) {\n var describedby = (target.getAttribute('aria-describedby') || '').split(/\\s+/);\n if (describedby.indexOf(id) < 0) {\n describedby.push(id);\n }\n attributes(target, { 'aria-describedby': describedby.join(' ').trim(), 'data-tooltip-id': id });\n };\n Tooltip.prototype.removeDescribedBy = function (target) {\n var id = target.getAttribute('data-tooltip-id');\n var describedby = (target.getAttribute('aria-describedby') || '').split(/\\s+/);\n var index = describedby.indexOf(id);\n if (index !== -1) {\n describedby.splice(index, 1);\n }\n target.removeAttribute('data-tooltip-id');\n var orgdescribedby = describedby.join(' ').trim();\n if (orgdescribedby) {\n target.setAttribute('aria-describedby', orgdescribedby);\n }\n else {\n target.removeAttribute('aria-describedby');\n }\n };\n Tooltip.prototype.tapHoldHandler = function (evt) {\n clearTimeout(this.autoCloseTimer);\n this.targetHover(evt.originalEvent);\n };\n Tooltip.prototype.touchEndHandler = function (e) {\n var _this = this;\n if (this.isSticky) {\n return;\n }\n var close = function () {\n _this.close();\n };\n this.autoCloseTimer = setTimeout(close, TOUCHEND_HIDE_DELAY);\n };\n Tooltip.prototype.targetClick = function (e) {\n var target;\n if (this.target) {\n target = closest(e.target, this.target);\n }\n else {\n target = this.element;\n }\n if (isNullOrUndefined(target)) {\n return;\n }\n if (target.getAttribute('data-tooltip-id') === null) {\n this.targetHover(e);\n }\n else if (!this.isSticky) {\n this.hideTooltip(this.animation.close, e, target);\n }\n };\n Tooltip.prototype.targetHover = function (e) {\n var target;\n if (this.target) {\n target = closest(e.target, this.target);\n }\n else {\n target = this.element;\n }\n if (isNullOrUndefined(target) || target.getAttribute('data-tooltip-id') !== null) {\n return;\n }\n var targetList = [].slice.call(document.querySelectorAll('[data-tooltip-id= ' + this.ctrlId + '_content]'));\n for (var _i = 0, targetList_1 = targetList; _i < targetList_1.length; _i++) {\n var target_1 = targetList_1[_i];\n this.restoreElement(target_1);\n }\n this.showTooltip(target, this.animation.open, e);\n this.wireMouseEvents(e, target);\n };\n Tooltip.prototype.showTooltip = function (target, showAnimation, e) {\n var _this = this;\n clearTimeout(this.showTimer);\n clearTimeout(this.hideTimer);\n this.tooltipEventArgs = e ? { type: e.type, cancel: false, target: target, event: e, element: this.tooltipEle } :\n { type: null, cancel: false, target: target, event: null, element: this.tooltipEle };\n this.trigger('beforeRender', this.tooltipEventArgs);\n if (this.tooltipEventArgs.cancel) {\n this.isHidden = true;\n this.clear();\n return;\n }\n this.isHidden = false;\n if (isNullOrUndefined(this.tooltipEle)) {\n this.ctrlId = this.element.getAttribute('id') ? getUniqueID(this.element.getAttribute('id')) : getUniqueID('tooltip');\n this.tooltipEle = this.createElement('div', {\n className: TOOLTIP_WRAP + ' ' + POPUP_ROOT, attrs: {\n role: 'tooltip', 'aria-hidden': 'false', 'id': this.ctrlId + '_content'\n }, styles: 'width:' + formatUnit(this.width) + ';height:' + formatUnit(this.height) + ';position:absolute;'\n });\n if (this.cssClass) {\n addClass([this.tooltipEle], this.cssClass.split(' '));\n }\n if (Browser.isDevice) {\n addClass([this.tooltipEle], DEVICE);\n }\n if (this.width !== 'auto') {\n this.tooltipEle.style.maxWidth = formatUnit(this.width);\n }\n this.tooltipEle.appendChild(this.createElement('div', { className: CONTENT }));\n document.body.appendChild(this.tooltipEle);\n this.addDescribedBy(target, this.ctrlId + '_content');\n this.renderContent(target);\n addClass([this.tooltipEle], POPUP_OPEN);\n if (this.showTipPointer) {\n this.renderArrow();\n }\n this.renderCloseIcon();\n this.renderPopup(target);\n }\n else {\n this.adjustArrow(target, this.position, this.tooltipPositionX, this.tooltipPositionY);\n this.addDescribedBy(target, this.ctrlId + '_content');\n this.renderContent(target);\n PopupAnimation.stop(this.tooltipEle);\n this.reposition(target);\n }\n removeClass([this.tooltipEle], POPUP_OPEN);\n addClass([this.tooltipEle], POPUP_CLOSE);\n this.tooltipEventArgs = e ? { type: e.type, cancel: false, target: target, event: e, element: this.tooltipEle } :\n { type: null, cancel: false, target: target, event: null, element: this.tooltipEle };\n this.trigger('beforeOpen', this.tooltipEventArgs);\n if (this.tooltipEventArgs.cancel) {\n this.isHidden = true;\n this.clear();\n return;\n }\n var openAnimation = {\n name: showAnimation.effect, duration: showAnimation.duration, delay: showAnimation.delay, timingFunction: 'easeOut'\n };\n if (showAnimation.effect === 'None') {\n openAnimation = undefined;\n }\n if (this.openDelay > 0) {\n var show = function () {\n if (_this.popupObj) {\n _this.popupObj.show(openAnimation, target);\n }\n };\n this.showTimer = setTimeout(show, this.openDelay);\n }\n else {\n this.popupObj.show(openAnimation, target);\n }\n };\n Tooltip.prototype.checkCollision = function (target, x, y) {\n var elePos = {\n left: x, top: y, position: this.position,\n horizontal: this.tooltipPositionX, vertical: this.tooltipPositionY\n };\n var affectedPos = isCollide(this.tooltipEle, (this.target ? this.element : null), x, y);\n if (affectedPos.length > 0) {\n elePos.horizontal = affectedPos.indexOf('left') >= 0 ? 'Right' : affectedPos.indexOf('right') >= 0 ? 'Left' :\n this.tooltipPositionX;\n elePos.vertical = affectedPos.indexOf('top') >= 0 ? 'Bottom' : affectedPos.indexOf('bottom') >= 0 ? 'Top' :\n this.tooltipPositionY;\n }\n return elePos;\n };\n Tooltip.prototype.collisionFlipFit = function (target, x, y) {\n var elePos = this.checkCollision(target, x, y);\n var newpos = elePos.position;\n if (this.tooltipPositionY !== elePos.vertical) {\n newpos = ((this.position.indexOf('Bottom') === 0 || this.position.indexOf('Top') === 0) ?\n elePos.vertical + this.tooltipPositionX : this.tooltipPositionX + elePos.vertical);\n }\n if (this.tooltipPositionX !== elePos.horizontal) {\n if (newpos.indexOf('Left') === 0) {\n elePos.vertical = (newpos === 'LeftTop' || newpos === 'LeftCenter') ? 'Top' : 'Bottom';\n newpos = (elePos.vertical + 'Left');\n }\n if (newpos.indexOf('Right') === 0) {\n elePos.vertical = (newpos === 'RightTop' || newpos === 'RightCenter') ? 'Top' : 'Bottom';\n newpos = (elePos.vertical + 'Right');\n }\n elePos.horizontal = this.tooltipPositionX;\n }\n this.tooltipEventArgs = {\n type: null, cancel: false, target: target, event: null,\n element: this.tooltipEle, collidedPosition: newpos\n };\n this.trigger('beforeCollision', this.tooltipEventArgs);\n if (elePos.position !== newpos) {\n var pos = calculatePosition(target, this.tooltipPositionX, elePos.vertical);\n this.adjustArrow(target, newpos, elePos.horizontal, elePos.vertical);\n var offsetPos = this.calculateTooltipOffset(newpos);\n elePos.position = newpos;\n elePos.left = pos.left + offsetPos.left;\n elePos.top = pos.top + offsetPos.top;\n }\n else {\n this.adjustArrow(target, newpos, elePos.horizontal, elePos.vertical);\n }\n var eleOffset = { left: elePos.left, top: elePos.top };\n var left = fit(this.tooltipEle, (this.target ? this.element : null), { X: true, Y: false }, eleOffset).left;\n if (this.showTipPointer && (newpos.indexOf('Bottom') === 0 || newpos.indexOf('Top') === 0)) {\n var arrowEle = this.tooltipEle.querySelector('.' + ARROW_TIP);\n var arrowleft = parseInt(arrowEle.style.left, 10) - (left - elePos.left);\n if (arrowleft < 0) {\n arrowleft = 0;\n }\n else if ((arrowleft + arrowEle.offsetWidth) > this.tooltipEle.clientWidth) {\n arrowleft = this.tooltipEle.clientWidth - arrowEle.offsetWidth;\n }\n arrowEle.style.left = arrowleft.toString() + 'px';\n }\n eleOffset.left = left;\n return eleOffset;\n };\n Tooltip.prototype.hideTooltip = function (hideAnimation, e, targetElement) {\n var _this = this;\n var target;\n if (e) {\n target = this.target ? (targetElement || e.target) : this.element;\n this.tooltipEventArgs = {\n type: e.type, cancel: false, target: target, event: e, element: this.tooltipEle\n };\n }\n else {\n target = document.querySelector('[data-tooltip-id= ' + this.ctrlId + '_content]');\n this.tooltipEventArgs = {\n type: null, cancel: false, target: target, event: null, element: this.tooltipEle\n };\n }\n if (isNullOrUndefined(target)) {\n return;\n }\n this.trigger('beforeClose', this.tooltipEventArgs);\n if (!this.tooltipEventArgs.cancel) {\n this.restoreElement(target);\n this.isHidden = true;\n var closeAnimation_1 = {\n name: hideAnimation.effect, duration: hideAnimation.duration, delay: hideAnimation.delay, timingFunction: 'easeIn'\n };\n if (hideAnimation.effect === 'None') {\n closeAnimation_1 = undefined;\n }\n if (this.closeDelay > 0) {\n var hide = function () {\n if (_this.popupObj) {\n _this.popupObj.hide(closeAnimation_1);\n }\n };\n this.hideTimer = setTimeout(hide, this.closeDelay);\n }\n else {\n this.popupObj.hide(closeAnimation_1);\n }\n }\n else {\n this.isHidden = false;\n }\n };\n Tooltip.prototype.restoreElement = function (target) {\n this.unwireMouseEvents(target);\n if (!isNullOrUndefined(target.getAttribute('data-content'))) {\n target.setAttribute('title', target.getAttribute('data-content'));\n target.removeAttribute('data-content');\n }\n this.removeDescribedBy(target);\n };\n Tooltip.prototype.clear = function () {\n if (this.tooltipEle) {\n removeClass([this.tooltipEle], POPUP_CLOSE);\n addClass([this.tooltipEle], POPUP_OPEN);\n }\n if (this.isHidden) {\n if (this.popupObj) {\n this.popupObj.destroy();\n }\n if (this.tooltipEle) {\n remove(this.tooltipEle);\n }\n this.tooltipEle = null;\n this.popupObj = null;\n }\n };\n Tooltip.prototype.onMouseOut = function (e) {\n this.hideTooltip(this.animation.close, e);\n };\n Tooltip.prototype.onStickyClose = function (e) {\n this.close();\n };\n Tooltip.prototype.onMouseMove = function (event) {\n var eventPageX = 0;\n var eventPageY = 0;\n if (event.type.indexOf('touch') > -1) {\n event.preventDefault();\n eventPageX = event.touches[0].pageX;\n eventPageY = event.touches[0].pageY;\n }\n else {\n eventPageX = event.pageX;\n eventPageY = event.pageY;\n }\n PopupAnimation.stop(this.tooltipEle);\n removeClass([this.tooltipEle], POPUP_CLOSE);\n addClass([this.tooltipEle], POPUP_OPEN);\n this.adjustArrow(event.target, this.position, this.tooltipPositionX, this.tooltipPositionY);\n var pos = this.calculateTooltipOffset(this.position);\n var x = eventPageX + pos.left + this.offsetX;\n var y = eventPageY + pos.top + this.offsetY;\n var elePos = this.checkCollision(event.target, x, y);\n if (this.tooltipPositionX !== elePos.horizontal || this.tooltipPositionY !== elePos.vertical) {\n var newpos = (this.position.indexOf('Bottom') === 0 || this.position.indexOf('Top') === 0) ?\n elePos.vertical + elePos.horizontal : elePos.horizontal + elePos.vertical;\n elePos.position = newpos;\n this.adjustArrow(event.target, elePos.position, elePos.horizontal, elePos.vertical);\n var colpos = this.calculateTooltipOffset(elePos.position);\n elePos.left = eventPageX + colpos.left - this.offsetX;\n elePos.top = eventPageY + colpos.top - this.offsetY;\n }\n this.tooltipEle.style.left = elePos.left + 'px';\n this.tooltipEle.style.top = elePos.top + 'px';\n };\n Tooltip.prototype.keyDown = function (event) {\n if (this.tooltipEle && event.keyCode === 27) {\n this.close();\n }\n };\n Tooltip.prototype.touchEnd = function (e) {\n if (this.tooltipEle && closest(e.target, '.' + ROOT) === null) {\n this.close();\n }\n };\n Tooltip.prototype.scrollHandler = function (e) {\n if (this.tooltipEle) {\n this.close();\n }\n };\n /**\n * Core method that initializes the control rendering.\n * @private\n */\n Tooltip.prototype.render = function () {\n this.initialize();\n this.wireEvents(this.opensOn);\n };\n /**\n * Initializes the values of private members.\n * @private\n */\n Tooltip.prototype.preRender = function () {\n this.tipClass = TIP_BOTTOM;\n this.tooltipPositionX = 'Center';\n this.tooltipPositionY = 'Top';\n this.isHidden = true;\n };\n /**\n * Binding events to the Tooltip element.\n * @hidden\n */\n Tooltip.prototype.wireEvents = function (trigger) {\n var triggerList = this.getTriggerList(trigger);\n for (var _i = 0, triggerList_1 = triggerList; _i < triggerList_1.length; _i++) {\n var opensOn = triggerList_1[_i];\n if (opensOn === 'Custom') {\n return;\n }\n if (opensOn === 'Focus') {\n this.wireFocusEvents();\n }\n if (opensOn === 'Click') {\n EventHandler.add(this.element, Browser.touchStartEvent, this.targetClick, this);\n }\n if (opensOn === 'Hover') {\n if (Browser.isDevice) {\n this.touchModule = new Touch(this.element, {\n tapHoldThreshold: TAPHOLD_THRESHOLD,\n tapHold: this.tapHoldHandler.bind(this)\n });\n EventHandler.add(this.element, Browser.touchEndEvent, this.touchEndHandler, this);\n }\n else {\n EventHandler.add(this.element, 'mouseover', this.targetHover, this);\n }\n }\n }\n EventHandler.add(document, 'touchend', this.touchEnd, this);\n EventHandler.add(document, 'scroll', this.scrollHandler, this);\n EventHandler.add(document, 'keydown', this.keyDown, this);\n };\n Tooltip.prototype.getTriggerList = function (trigger) {\n if (trigger === 'Auto') {\n trigger = (Browser.isDevice) ? 'Hover' : 'Hover Focus';\n }\n return trigger.split(' ');\n };\n Tooltip.prototype.wireFocusEvents = function () {\n if (!isNullOrUndefined(this.target)) {\n var targetList = [].slice.call(this.element.querySelectorAll(this.target));\n for (var _i = 0, targetList_2 = targetList; _i < targetList_2.length; _i++) {\n var target = targetList_2[_i];\n EventHandler.add(target, 'focus', this.targetHover, this);\n }\n }\n else {\n EventHandler.add(this.element, 'focus', this.targetHover, this);\n }\n };\n Tooltip.prototype.wireMouseEvents = function (e, target) {\n if (this.tooltipEle) {\n if (!this.isSticky) {\n if (e.type === 'focus') {\n EventHandler.add(target, 'blur', this.onMouseOut, this);\n }\n if (e.type === 'mouseover') {\n EventHandler.add(target, 'mouseleave', this.onMouseOut, this);\n }\n }\n if (this.mouseTrail) {\n EventHandler.add(target, 'mousemove touchstart mouseenter', this.onMouseMove, this);\n }\n }\n };\n /**\n * Unbinding events from the element on widget destroy.\n * @hidden\n */\n Tooltip.prototype.unwireEvents = function (trigger) {\n var triggerList = this.getTriggerList(trigger);\n for (var _i = 0, triggerList_2 = triggerList; _i < triggerList_2.length; _i++) {\n var opensOn = triggerList_2[_i];\n if (opensOn === 'Custom') {\n return;\n }\n if (opensOn === 'Focus') {\n this.unwireFocusEvents();\n }\n if (opensOn === 'Click') {\n EventHandler.remove(this.element, Browser.touchStartEvent, this.targetClick);\n }\n if (opensOn === 'Hover') {\n if (Browser.isDevice) {\n if (this.touchModule) {\n this.touchModule.destroy();\n }\n EventHandler.remove(this.element, Browser.touchEndEvent, this.touchEndHandler);\n }\n else {\n EventHandler.remove(this.element, 'mouseover', this.targetHover);\n }\n }\n }\n EventHandler.remove(document, 'touchend', this.touchEnd);\n EventHandler.remove(document, 'scroll', this.scrollHandler);\n EventHandler.remove(document, 'keydown', this.keyDown);\n };\n Tooltip.prototype.unwireFocusEvents = function () {\n if (!isNullOrUndefined(this.target)) {\n var targetList = [].slice.call(this.element.querySelectorAll(this.target));\n for (var _i = 0, targetList_3 = targetList; _i < targetList_3.length; _i++) {\n var target = targetList_3[_i];\n EventHandler.remove(target, 'focus', this.targetHover);\n }\n }\n else {\n EventHandler.remove(this.element, 'focus', this.targetHover);\n }\n };\n Tooltip.prototype.unwireMouseEvents = function (target) {\n if (!this.isSticky) {\n var triggerList = this.getTriggerList(this.opensOn);\n for (var _i = 0, triggerList_3 = triggerList; _i < triggerList_3.length; _i++) {\n var opensOn = triggerList_3[_i];\n if (opensOn === 'Focus') {\n EventHandler.remove(target, 'blur', this.onMouseOut);\n }\n if (opensOn === 'Hover' && !Browser.isDevice) {\n EventHandler.remove(target, 'mouseleave', this.onMouseOut);\n }\n }\n }\n if (this.mouseTrail) {\n EventHandler.remove(target, 'mousemove touchstart mouseenter', this.onMouseMove);\n }\n };\n /**\n * Core method to return the component name.\n * @private\n */\n Tooltip.prototype.getModuleName = function () {\n return 'tooltip';\n };\n /**\n * Returns the properties to be maintained in the persisted state.\n * @private\n */\n Tooltip.prototype.getPersistData = function () {\n return this.addOnPersist([]);\n };\n /**\n * Called internally, if any of the property value changed.\n * @private\n */\n Tooltip.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'width':\n if (this.tooltipEle) {\n this.tooltipEle.style.width = formatUnit(newProp.width);\n }\n break;\n case 'height':\n if (this.tooltipEle) {\n this.tooltipEle.style.height = formatUnit(newProp.height);\n }\n break;\n case 'content':\n if (this.tooltipEle) {\n this.renderContent();\n }\n break;\n case 'opensOn':\n this.unwireEvents(oldProp.opensOn);\n this.wireEvents(newProp.opensOn);\n break;\n case 'position':\n this.formatPosition();\n var target = document.querySelector('[data-tooltip-id= ' + this.ctrlId + '_content]');\n if (this.tooltipEle && target) {\n var arrowInnerELe = this.tooltipEle.querySelector('.' + ARROW_TIP_INNER);\n arrowInnerELe.style.top = arrowInnerELe.style.left = null;\n this.reposition(target);\n }\n break;\n case 'tipPointerPosition':\n var trgt = document.querySelector('[data-tooltip-id= ' + this.ctrlId + '_content]');\n if (this.tooltipEle && trgt) {\n this.reposition(trgt);\n }\n break;\n case 'offsetX':\n if (this.tooltipEle) {\n var x = newProp.offsetX - oldProp.offsetX;\n this.tooltipEle.style.left = (parseInt(this.tooltipEle.style.left, 10) + (x)).toString() + 'px';\n }\n break;\n case 'offsetY':\n if (this.tooltipEle) {\n var y = newProp.offsetY - oldProp.offsetY;\n this.tooltipEle.style.top = (parseInt(this.tooltipEle.style.top, 10) + (y)).toString() + 'px';\n }\n break;\n case 'cssClass':\n if (this.tooltipEle) {\n if (oldProp.cssClass) {\n removeClass([this.tooltipEle], oldProp.cssClass.split(' '));\n }\n if (newProp.cssClass) {\n addClass([this.tooltipEle], newProp.cssClass.split(' '));\n }\n }\n break;\n case 'enableRtl':\n if (this.tooltipEle) {\n if (this.enableRtl) {\n addClass([this.tooltipEle], RTL);\n }\n else {\n removeClass([this.tooltipEle], RTL);\n }\n }\n break;\n }\n }\n };\n /**\n * It is used to show the Tooltip on the specified target with specific animation settings.\n * @param element Target element where the Tooltip is to be displayed.\n * @param animation Sets the specific animation, while showing the Tooltip on the screen.\n * @return {void}\n */\n Tooltip.prototype.open = function (element, animation) {\n if (animation === void 0) { animation = this.animation.open; }\n if (element.style.display === 'none') {\n return;\n }\n this.showTooltip(element, animation);\n };\n /**\n * It is used to hide the Tooltip with specific animation effect.\n * @param animation Sets the specific animation when hiding Tooltip from the screen.\n * @return {void}\n */\n Tooltip.prototype.close = function (animation) {\n if (animation === void 0) { animation = this.animation.close; }\n this.hideTooltip(animation);\n };\n /**\n * It is used to refresh the Tooltip content and its position.\n * @param target Target element where the Tooltip content or position needs to be refreshed.\n * @return {void}\n */\n Tooltip.prototype.refresh = function (target) {\n if (this.tooltipEle) {\n this.renderContent(target);\n }\n if (this.popupObj && target) {\n this.reposition(target);\n }\n };\n /**\n * It is used to destroy the Tooltip component.\n * @method destroy\n * @return {void}\n * @memberof Tooltip\n */\n Tooltip.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n removeClass([this.element], ROOT);\n this.unwireEvents(this.opensOn);\n if (this.popupObj) {\n this.popupObj.destroy();\n }\n if (this.tooltipEle) {\n remove(this.tooltipEle);\n }\n this.tooltipEle = null;\n this.popupObj = null;\n };\n __decorate([\n Property('auto')\n ], Tooltip.prototype, \"width\", void 0);\n __decorate([\n Property('auto')\n ], Tooltip.prototype, \"height\", void 0);\n __decorate([\n Property()\n ], Tooltip.prototype, \"content\", void 0);\n __decorate([\n Property()\n ], Tooltip.prototype, \"target\", void 0);\n __decorate([\n Property('TopCenter')\n ], Tooltip.prototype, \"position\", void 0);\n __decorate([\n Property(0)\n ], Tooltip.prototype, \"offsetX\", void 0);\n __decorate([\n Property(0)\n ], Tooltip.prototype, \"offsetY\", void 0);\n __decorate([\n Property(true)\n ], Tooltip.prototype, \"showTipPointer\", void 0);\n __decorate([\n Property('Auto')\n ], Tooltip.prototype, \"tipPointerPosition\", void 0);\n __decorate([\n Property('Auto')\n ], Tooltip.prototype, \"opensOn\", void 0);\n __decorate([\n Property(false)\n ], Tooltip.prototype, \"mouseTrail\", void 0);\n __decorate([\n Property(false)\n ], Tooltip.prototype, \"isSticky\", void 0);\n __decorate([\n Complex({}, Animation)\n ], Tooltip.prototype, \"animation\", void 0);\n __decorate([\n Property(0)\n ], Tooltip.prototype, \"openDelay\", void 0);\n __decorate([\n Property(0)\n ], Tooltip.prototype, \"closeDelay\", void 0);\n __decorate([\n Property()\n ], Tooltip.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], Tooltip.prototype, \"enableRtl\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"beforeRender\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"afterOpen\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"beforeClose\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"afterClose\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"beforeCollision\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"destroyed\", void 0);\n Tooltip = __decorate([\n NotifyPropertyChanges\n ], Tooltip);\n return Tooltip;\n}(Component));\nexport { Tooltip };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, EventHandler, Property, Event, Browser, L10n } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { attributes, addClass, removeClass, setStyleAttribute, detach } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, getValue, formatUnit, setValue, merge } from '@syncfusion/ej2-base';\nimport { Internationalization, getNumericObject } from '@syncfusion/ej2-base';\nimport { Input } from '../input/input';\nvar ROOT = 'e-control-wrapper e-numeric';\nvar SPINICON = 'e-input-group-icon';\nvar SPINUP = 'e-spin-up';\nvar SPINDOWN = 'e-spin-down';\nvar ERROR = 'e-error';\nvar INCREMENT = 'increment';\nvar DECREMENT = 'decrement';\nvar INTREGEXP = new RegExp('^(-)?(\\\\d*)$');\nvar DECIMALSEPARATOR = '.';\nvar COMPONENT = 'e-numerictextbox';\nvar CONTROL = 'e-control';\n/**\n * Represents the NumericTextBox component that allows the user to enter only numeric values.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar NumericTextBox = /** @class */ (function (_super) {\n __extends(NumericTextBox, _super);\n function NumericTextBox(options, element) {\n return _super.call(this, options, element) || this;\n }\n NumericTextBox.prototype.preRender = function () {\n this.isPrevFocused = false;\n this.decimalSeparator = '.';\n this.intRegExp = new RegExp('/^(-)?(\\d*)$/');\n this.isCalled = false;\n var ejInstance = getValue('ej2_instances', this.element);\n this.cloneElement = this.element.cloneNode(true);\n removeClass([this.cloneElement], [CONTROL, COMPONENT]);\n this.angularTagName = null;\n if (this.element.tagName === 'EJS-NUMERICTEXTBOX') {\n this.angularTagName = this.element.tagName;\n var input = this.createElement('input');\n var index = 0;\n for (index; index < this.element.attributes.length; index++) {\n input.setAttribute(this.element.attributes[index].nodeName, this.element.attributes[index].nodeValue);\n input.innerHTML = this.element.innerHTML;\n }\n if (this.element.hasAttribute('id')) {\n this.element.removeAttribute('id');\n }\n this.element.classList.remove('e-control', 'e-numerictextbox');\n this.element.appendChild(input);\n this.element = input;\n setValue('ej2_instances', ejInstance, this.element);\n }\n attributes(this.element, { 'role': 'spinbutton', 'tabindex': '0', 'autocomplete': 'off', 'aria-live': 'assertive' });\n var localeText = { incrementTitle: 'Increment value', decrementTitle: 'Decrement value', placeholder: '' };\n this.l10n = new L10n('numerictextbox', localeText, this.locale);\n this.isValidState = true;\n this.inputStyle = null;\n this.inputName = null;\n this.cultureInfo = {};\n this.initCultureInfo();\n this.initCultureFunc();\n this.checkAttributes();\n this.prevValue = this.value;\n this.validateMinMax();\n this.validateStep();\n if (this.placeholder === null) {\n this.updatePlaceholder();\n }\n };\n /**\n * To Initialize the control rendering\n * @private\n */\n NumericTextBox.prototype.render = function () {\n if (this.element.tagName.toLowerCase() === 'input') {\n this.createWrapper();\n if (this.showSpinButton) {\n this.spinBtnCreation();\n }\n if (!isNullOrUndefined(this.width)) {\n setStyleAttribute(this.container, { 'width': formatUnit(this.width) });\n }\n if (!this.container.classList.contains('e-input-group')) {\n this.container.classList.add('e-input-group');\n }\n this.changeValue(this.value === null || isNaN(this.value) ? null : this.strictMode ? this.trimValue(this.value) : this.value);\n this.wireEvents();\n if (this.value !== null && !isNaN(this.value)) {\n if (this.decimals) {\n this.setProperties({ value: this.roundNumber(this.value, this.decimals) }, true);\n }\n }\n }\n };\n NumericTextBox.prototype.checkAttributes = function () {\n var attributes = ['value', 'min', 'max', 'step', 'disabled', 'readonly', 'style', 'name'];\n for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {\n var prop = attributes_1[_i];\n if (!isNullOrUndefined(this.element.getAttribute(prop))) {\n switch (prop) {\n case 'disabled':\n var enabled = this.element.getAttribute(prop) === 'disabled' ||\n this.element.getAttribute(prop) === 'true' ? false : true;\n this.setProperties({ enabled: enabled }, true);\n break;\n case 'readonly':\n var readonly = this.element.getAttribute(prop) === 'readonly'\n || this.element.getAttribute(prop) === 'true' ? true : false;\n this.setProperties({ readonly: readonly }, true);\n break;\n case 'style':\n this.inputStyle = this.element.getAttribute(prop);\n break;\n case 'name':\n this.inputName = this.element.getAttribute(prop);\n break;\n default:\n var value = this.instance.getNumberParser({ format: 'n' })(this.element.getAttribute(prop));\n if ((value !== null && !isNaN(value)) || (prop === 'value')) {\n this.setProperties(setValue(prop, value, {}), true);\n }\n break;\n }\n }\n }\n };\n NumericTextBox.prototype.updatePlaceholder = function () {\n this.setProperties({ placeholder: this.l10n.getConstant('placeholder') }, true);\n };\n NumericTextBox.prototype.initCultureFunc = function () {\n this.instance = new Internationalization(this.locale);\n };\n NumericTextBox.prototype.initCultureInfo = function () {\n this.cultureInfo.format = this.format;\n if (getValue('currency', this) !== null) {\n setValue('currency', this.currency, this.cultureInfo);\n this.setProperties({ currencyCode: this.currency }, true);\n }\n };\n /* Wrapper creation */\n NumericTextBox.prototype.createWrapper = function () {\n var inputObj = Input.createInput({\n element: this.element,\n floatLabelType: this.floatLabelType,\n properties: {\n readonly: this.readonly,\n placeholder: this.placeholder,\n cssClass: this.cssClass,\n enableRtl: this.enableRtl,\n showClearButton: this.showClearButton,\n enabled: this.enabled\n }\n }, this.createElement);\n this.inputWrapper = inputObj;\n this.container = inputObj.container;\n this.container.setAttribute('class', ROOT + ' ' + this.container.getAttribute('class'));\n if (this.readonly) {\n attributes(this.element, { 'aria-readonly': 'true' });\n }\n this.hiddenInput = (this.createElement('input', { attrs: { type: 'hidden', 'validateHidden': 'true' } }));\n this.inputName = this.inputName !== null ? this.inputName : this.element.id;\n this.element.removeAttribute('name');\n attributes(this.hiddenInput, { 'name': this.inputName });\n this.container.insertBefore(this.hiddenInput, this.container.childNodes[1]);\n if (this.inputStyle !== null) {\n attributes(this.container, { 'style': this.inputStyle });\n }\n };\n /* Spinner creation */\n NumericTextBox.prototype.spinBtnCreation = function () {\n this.spinDown = Input.appendSpan(SPINICON + ' ' + SPINDOWN, this.container, this.createElement);\n attributes(this.spinDown, {\n 'title': this.l10n.getConstant('decrementTitle'),\n 'aria-label': this.l10n.getConstant('decrementTitle')\n });\n this.spinUp = Input.appendSpan(SPINICON + ' ' + SPINUP, this.container, this.createElement);\n attributes(this.spinUp, {\n 'title': this.l10n.getConstant('incrementTitle'),\n 'aria-label': this.l10n.getConstant('incrementTitle')\n });\n this.wireSpinBtnEvents();\n };\n NumericTextBox.prototype.validateMinMax = function () {\n if (!(typeof (this.min) === 'number' && !isNaN(this.min))) {\n this.setProperties({ min: -(Number.MAX_VALUE) }, true);\n }\n if (!(typeof (this.max) === 'number' && !isNaN(this.max))) {\n this.setProperties({ max: Number.MAX_VALUE }, true);\n }\n if (this.decimals !== null) {\n if (this.min !== -(Number.MAX_VALUE)) {\n this.setProperties({ min: this.instance.getNumberParser({ format: 'n' })(this.formattedValue(this.decimals, this.min)) }, true);\n }\n if (this.max !== (Number.MAX_VALUE)) {\n this.setProperties({ max: this.instance.getNumberParser({ format: 'n' })(this.formattedValue(this.decimals, this.max)) }, true);\n }\n }\n this.setProperties({ min: this.min > this.max ? this.max : this.min }, true);\n attributes(this.element, { 'aria-valuemin': this.min.toString(), 'aria-valuemax': this.max.toString() });\n };\n NumericTextBox.prototype.formattedValue = function (decimals, value) {\n return this.instance.getNumberFormat({\n maximumFractionDigits: decimals,\n minimumFractionDigits: decimals, useGrouping: false\n })(value);\n };\n NumericTextBox.prototype.validateStep = function () {\n if (this.decimals !== null) {\n this.setProperties({ step: this.instance.getNumberParser({ format: 'n' })(this.formattedValue(this.decimals, this.step)) }, true);\n }\n };\n NumericTextBox.prototype.action = function (operation, event) {\n this.isInteract = true;\n var value = this.isFocused ? this.instance.getNumberParser({ format: 'n' })(this.element.value) : this.value;\n this.changeValue(this.performAction(value, this.step, operation));\n this.raiseChangeEvent(event);\n };\n NumericTextBox.prototype.checkErrorClass = function () {\n if (this.isValidState) {\n removeClass([this.container], ERROR);\n }\n else {\n addClass([this.container], ERROR);\n }\n attributes(this.element, { 'aria-invalid': this.isValidState ? 'false' : 'true' });\n };\n NumericTextBox.prototype.bindClearEvent = function () {\n if (this.showClearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler, this);\n }\n };\n NumericTextBox.prototype.resetHandler = function (e) {\n e.preventDefault();\n if (!(this.inputWrapper.clearButton.classList.contains('e-clear-icon-hide'))) {\n this.clear(e);\n }\n };\n NumericTextBox.prototype.clear = function (event) {\n this.setProperties({ value: null }, true);\n this.setElementValue('');\n };\n NumericTextBox.prototype.wireEvents = function () {\n EventHandler.add(this.element, 'focus', this.focusIn, this);\n EventHandler.add(this.element, 'blur', this.focusOut, this);\n EventHandler.add(this.element, 'keydown', this.keyDownHandler, this);\n EventHandler.add(this.element, 'keyup', this.keyUpHandler, this);\n EventHandler.add(this.element, 'input', this.inputHandler, this);\n EventHandler.add(this.element, 'keypress', this.keyPressHandler, this);\n EventHandler.add(this.element, 'change', this.changeHandler, this);\n EventHandler.add(this.element, 'paste', this.pasteHandler, this);\n if (this.enabled) {\n this.bindClearEvent();\n }\n };\n NumericTextBox.prototype.wireSpinBtnEvents = function () {\n /* bind spin button events */\n EventHandler.add(this.spinUp, Browser.touchStartEvent, this.mouseDownOnSpinner, this);\n EventHandler.add(this.spinDown, Browser.touchStartEvent, this.mouseDownOnSpinner, this);\n EventHandler.add(this.spinUp, Browser.touchEndEvent, this.mouseUpOnSpinner, this);\n EventHandler.add(this.spinDown, Browser.touchEndEvent, this.mouseUpOnSpinner, this);\n EventHandler.add(this.spinUp, Browser.touchMoveEvent, this.touchMoveOnSpinner, this);\n EventHandler.add(this.spinDown, Browser.touchMoveEvent, this.touchMoveOnSpinner, this);\n };\n NumericTextBox.prototype.unwireEvents = function () {\n EventHandler.remove(this.element, 'focus', this.focusIn);\n EventHandler.remove(this.element, 'blur', this.focusOut);\n EventHandler.remove(this.element, 'keyup', this.keyUpHandler);\n EventHandler.remove(this.element, 'input', this.inputHandler);\n EventHandler.remove(this.element, 'keydown', this.keyDownHandler);\n EventHandler.remove(this.element, 'keypress', this.keyPressHandler);\n EventHandler.remove(this.element, 'change', this.changeHandler);\n EventHandler.remove(this.element, 'paste', this.pasteHandler);\n };\n NumericTextBox.prototype.unwireSpinBtnEvents = function () {\n /* unbind spin button events */\n EventHandler.remove(this.spinUp, Browser.touchStartEvent, this.mouseDownOnSpinner);\n EventHandler.remove(this.spinDown, Browser.touchStartEvent, this.mouseDownOnSpinner);\n EventHandler.remove(this.spinUp, Browser.touchEndEvent, this.mouseUpOnSpinner);\n EventHandler.remove(this.spinDown, Browser.touchEndEvent, this.mouseUpOnSpinner);\n EventHandler.remove(this.spinUp, Browser.touchMoveEvent, this.touchMoveOnSpinner);\n EventHandler.remove(this.spinDown, Browser.touchMoveEvent, this.touchMoveOnSpinner);\n };\n NumericTextBox.prototype.changeHandler = function (event) {\n if (!this.element.value.length) {\n this.setProperties({ value: null }, true);\n }\n var parsedInput = this.instance.getNumberParser({ format: 'n' })(this.element.value);\n this.updateValue(parsedInput, event);\n };\n NumericTextBox.prototype.raiseChangeEvent = function (event) {\n if (this.prevValue !== this.value) {\n var eventArgs = {};\n this.changeEventArgs = { value: this.value, previousValue: this.prevValue, isInteraction: this.isInteract, event: event };\n if (event) {\n this.changeEventArgs.event = event;\n }\n merge(eventArgs, this.changeEventArgs);\n this.prevValue = this.value;\n this.isInteract = false;\n this.trigger('change', eventArgs);\n }\n };\n NumericTextBox.prototype.pasteHandler = function () {\n var _this = this;\n var beforeUpdate = this.element.value;\n setTimeout(function () {\n if (!_this.numericRegex().test(_this.element.value)) {\n _this.setElementValue(beforeUpdate);\n }\n });\n };\n NumericTextBox.prototype.preventHandler = function () {\n var _this = this;\n var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);\n setTimeout(function () {\n if (_this.element.selectionStart > 0) {\n var currentPos = _this.element.selectionStart;\n var prevPos = _this.element.selectionStart - 1;\n var start = 0;\n var ignoreKeyCode = void 0;\n var valArray = _this.element.value.split('');\n var numericObject = getNumericObject(_this.locale);\n var decimalSeparator = getValue('decimal', numericObject);\n ignoreKeyCode = decimalSeparator.charCodeAt(0);\n if (_this.element.value[prevPos] === ' ' && _this.element.selectionStart > 0 && !iOS) {\n if (isNullOrUndefined(_this.prevVal)) {\n _this.element.value = _this.element.value.trim();\n }\n else if (prevPos !== 0) {\n _this.element.value = _this.prevVal;\n }\n else if (prevPos === 0) {\n _this.element.value = _this.element.value.trim();\n }\n _this.element.setSelectionRange(prevPos, prevPos);\n }\n else if (isNaN(parseFloat(_this.element.value[_this.element.selectionStart - 1])) &&\n _this.element.value[_this.element.selectionStart - 1].charCodeAt(0) !== 45) {\n if ((valArray.indexOf(_this.element.value[_this.element.selectionStart - 1]) !==\n valArray.lastIndexOf(_this.element.value[_this.element.selectionStart - 1]) &&\n _this.element.value[_this.element.selectionStart - 1].charCodeAt(0) === ignoreKeyCode) ||\n _this.element.value[_this.element.selectionStart - 1].charCodeAt(0) !== ignoreKeyCode) {\n _this.element.value = _this.element.value.substring(0, prevPos) +\n _this.element.value.substring(currentPos, _this.element.value.length);\n _this.element.setSelectionRange(prevPos, prevPos);\n if (isNaN(parseFloat(_this.element.value[_this.element.selectionStart - 1])) && _this.element.selectionStart > 0\n && _this.element.value.length) {\n _this.preventHandler();\n }\n }\n }\n else if (isNaN(parseFloat(_this.element.value[_this.element.selectionStart - 2])) && _this.element.selectionStart > 1 &&\n _this.element.value[_this.element.selectionStart - 2].charCodeAt(0) !== 45) {\n if ((valArray.indexOf(_this.element.value[_this.element.selectionStart - 2]) !==\n valArray.lastIndexOf(_this.element.value[_this.element.selectionStart - 2]) &&\n _this.element.value[_this.element.selectionStart - 2].charCodeAt(0) === ignoreKeyCode) ||\n _this.element.value[_this.element.selectionStart - 2].charCodeAt(0) !== ignoreKeyCode) {\n _this.element.setSelectionRange(prevPos, prevPos);\n _this.nextEle = _this.element.value[_this.element.selectionStart];\n _this.cursorPosChanged = true;\n _this.preventHandler();\n }\n }\n if (_this.cursorPosChanged === true && _this.element.value[_this.element.selectionStart] === _this.nextEle &&\n isNaN(parseFloat(_this.element.value[_this.element.selectionStart - 1]))) {\n _this.element.setSelectionRange(_this.element.selectionStart + 1, _this.element.selectionStart + 1);\n _this.cursorPosChanged = false;\n _this.nextEle = null;\n }\n if (_this.element.value.trim() === '') {\n _this.element.setSelectionRange(start, start);\n }\n if (_this.element.selectionStart > 0) {\n if ((_this.element.value[_this.element.selectionStart - 1].charCodeAt(0) === 45) && _this.element.selectionStart > 1) {\n if (isNullOrUndefined(_this.prevVal)) {\n _this.element.value = _this.element.value;\n }\n else {\n _this.element.value = _this.prevVal;\n }\n _this.element.setSelectionRange(_this.element.selectionStart, _this.element.selectionStart);\n }\n }\n _this.prevVal = _this.element.value;\n }\n });\n };\n NumericTextBox.prototype.keyUpHandler = function (event) {\n var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);\n if (!iOS && Browser.isDevice) {\n this.preventHandler();\n }\n };\n ;\n NumericTextBox.prototype.inputHandler = function (event) {\n var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);\n var fireFox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n if ((fireFox || iOS) && Browser.isDevice) {\n this.preventHandler();\n }\n };\n ;\n NumericTextBox.prototype.keyDownHandler = function (event) {\n if (!this.readonly) {\n switch (event.keyCode) {\n case 38:\n event.preventDefault();\n this.action(INCREMENT, event);\n break;\n case 40:\n event.preventDefault();\n this.action(DECREMENT, event);\n break;\n default: break;\n }\n }\n };\n ;\n NumericTextBox.prototype.performAction = function (value, step, operation) {\n if (value === null || isNaN(value)) {\n value = 0;\n }\n var updatedValue = operation === INCREMENT ? value + step : value - step;\n updatedValue = this.correctRounding(value, step, updatedValue);\n return this.strictMode ? this.trimValue(updatedValue) : updatedValue;\n };\n ;\n NumericTextBox.prototype.correctRounding = function (value, step, result) {\n var floatExp = new RegExp('[,.](.*)');\n var valueText = value.toString();\n var stepText = step.toString();\n var floatValue = floatExp.test(value.toString());\n var floatStep = floatExp.test(step.toString());\n if (floatValue || floatStep) {\n var valueCount = floatValue ? floatExp.exec(value.toString())[0].length : 0;\n var stepCount = floatStep ? floatExp.exec(step.toString())[0].length : 0;\n var max = Math.max(valueCount, stepCount);\n return value = this.roundValue(result, max);\n }\n return result;\n };\n ;\n NumericTextBox.prototype.roundValue = function (result, precision) {\n precision = precision || 0;\n var divide = Math.pow(10, precision);\n return result *= divide, result = Math.round(result) / divide;\n };\n ;\n NumericTextBox.prototype.updateValue = function (value, event) {\n if (event) {\n this.isInteract = true;\n }\n if (value !== null && !isNaN(value)) {\n if (this.decimals) {\n value = this.roundNumber(value, this.decimals);\n }\n }\n this.changeValue(value === null || isNaN(value) ? null : this.strictMode ? this.trimValue(value) : value);\n this.raiseChangeEvent(event);\n };\n NumericTextBox.prototype.updateCurrency = function (prop, propVal) {\n setValue(prop, propVal, this.cultureInfo);\n this.updateValue(this.value);\n };\n NumericTextBox.prototype.changeValue = function (value) {\n if (!(value || value === 0)) {\n value = null;\n this.setProperties({ value: value }, true);\n }\n else {\n var numberOfDecimals = void 0;\n var decimalPart = value.toString().split('.')[1];\n numberOfDecimals = !decimalPart || !decimalPart.length ? 0 : decimalPart.length;\n if (this.decimals !== null) {\n numberOfDecimals = numberOfDecimals < this.decimals ? numberOfDecimals : this.decimals;\n }\n this.setProperties({ value: this.roundNumber(value, numberOfDecimals) }, true);\n }\n this.modifyText();\n if (!this.strictMode) {\n this.validateState();\n }\n };\n ;\n NumericTextBox.prototype.modifyText = function () {\n if (this.value || this.value === 0) {\n var value = this.formatNumber();\n var elementValue = this.isFocused ? value : this.instance.getNumberFormat(this.cultureInfo)(this.value);\n this.setElementValue(elementValue);\n attributes(this.element, { 'aria-valuenow': value });\n this.hiddenInput.value = value;\n }\n else {\n this.setElementValue('');\n this.element.removeAttribute('aria-valuenow');\n this.hiddenInput.value = null;\n }\n };\n ;\n NumericTextBox.prototype.setElementValue = function (val, element) {\n Input.setValue(val, (element ? element : this.element), this.floatLabelType, this.showClearButton);\n };\n NumericTextBox.prototype.validateState = function () {\n this.isValidState = true;\n if (this.value || this.value === 0) {\n this.isValidState = !(this.value > this.max || this.value < this.min);\n }\n this.checkErrorClass();\n };\n NumericTextBox.prototype.formatNumber = function () {\n var numberOfDecimals;\n var currentValue = this.value;\n var decimalPart = currentValue.toString().split('.')[1];\n numberOfDecimals = !decimalPart || !decimalPart.length ? 0 : decimalPart.length;\n if (this.decimals !== null) {\n numberOfDecimals = numberOfDecimals < this.decimals ? numberOfDecimals : this.decimals;\n }\n return this.instance.getNumberFormat({\n maximumFractionDigits: numberOfDecimals,\n minimumFractionDigits: numberOfDecimals, useGrouping: false\n })(this.value);\n };\n ;\n NumericTextBox.prototype.trimValue = function (value) {\n if (value > this.max) {\n return this.max;\n }\n if (value < this.min) {\n return this.min;\n }\n return value;\n };\n ;\n NumericTextBox.prototype.roundNumber = function (value, precision) {\n var result = value;\n var decimals = precision || 0;\n var result1 = result.toString().split('e');\n result = Math.round(Number(result1[0] + 'e' + (result1[1] ? (Number(result1[1]) + decimals) : decimals)));\n var result2 = result.toString().split('e');\n result = Number(result2[0] + 'e' + (result2[1] ? (Number(result2[1]) - decimals) : -decimals));\n return Number(result.toFixed(decimals));\n };\n ;\n NumericTextBox.prototype.cancelEvent = function (event) {\n event.preventDefault();\n return false;\n };\n NumericTextBox.prototype.keyPressHandler = function (event) {\n if (!Browser.isDevice && Browser.info.version === '11.0' && event.keyCode === 13) {\n var parsedInput = this.instance.getNumberParser({ format: 'n' })(this.element.value);\n this.updateValue(parsedInput, event);\n return true;\n }\n if (event.which === 0 || event.metaKey || event.ctrlKey || event.keyCode === 8 || event.keyCode === 13) {\n return true;\n }\n var currentChar = String.fromCharCode(event.which);\n var text = this.element.value;\n text = text.substring(0, this.element.selectionStart) + currentChar + text.substring(this.element.selectionEnd);\n if (!this.numericRegex().test(text)) {\n event.preventDefault();\n event.stopPropagation();\n return false;\n }\n else {\n return true;\n }\n };\n ;\n NumericTextBox.prototype.numericRegex = function () {\n var numericObject = getNumericObject(this.locale);\n var decimalSeparator = getValue('decimal', numericObject);\n var fractionRule = '*';\n if (decimalSeparator === DECIMALSEPARATOR) {\n decimalSeparator = '\\\\' + decimalSeparator;\n }\n if (this.decimals === 0 && this.validateDecimalOnType) {\n return INTREGEXP;\n }\n if (this.decimals && this.validateDecimalOnType) {\n fractionRule = '{0,' + this.decimals + '}';\n }\n return new RegExp('^(-)?(((\\\\d+(' + decimalSeparator + '\\\\d' + fractionRule +\n ')?)|(' + decimalSeparator + '\\\\d' + fractionRule + ')))?$');\n };\n ;\n NumericTextBox.prototype.mouseWheel = function (event) {\n event.preventDefault();\n var delta;\n var rawEvent = event;\n if (rawEvent.wheelDelta) {\n delta = rawEvent.wheelDelta / 120;\n }\n else if (rawEvent.detail) {\n delta = -rawEvent.detail / 3;\n }\n if (delta > 0) {\n this.action(INCREMENT, event);\n }\n else if (delta < 0) {\n this.action(DECREMENT, event);\n }\n this.cancelEvent(event);\n };\n NumericTextBox.prototype.focusIn = function (event) {\n var _this = this;\n if (!this.enabled || this.readonly) {\n return;\n }\n this.isFocused = true;\n removeClass([this.container], ERROR);\n this.prevValue = this.value;\n if ((this.value || this.value === 0)) {\n var formatValue_1 = this.formatNumber();\n this.setElementValue(formatValue_1);\n if (!this.isPrevFocused) {\n var delay = (Browser.isDevice && Browser.isIos) ? 600 : 0;\n setTimeout(function () {\n _this.element.setSelectionRange(0, formatValue_1.length);\n }, delay);\n }\n }\n if (!Browser.isDevice) {\n EventHandler.add(this.element, 'mousewheel DOMMouseScroll', this.mouseWheel, this);\n }\n };\n ;\n NumericTextBox.prototype.focusOut = function (event) {\n var _this = this;\n if (this.isPrevFocused) {\n event.preventDefault();\n if (Browser.isDevice) {\n var value_1 = this.element.value;\n this.element.focus();\n this.isPrevFocused = false;\n var ele_1 = this.element;\n setTimeout(function () {\n _this.setElementValue(value_1, ele_1);\n }, 200);\n }\n }\n else {\n this.isFocused = false;\n if (!this.element.value.length) {\n this.setProperties({ value: null }, true);\n }\n var parsedInput = this.instance.getNumberParser({ format: 'n' })(this.element.value);\n this.updateValue(parsedInput);\n if (!Browser.isDevice) {\n EventHandler.remove(this.element, 'mousewheel DOMMouseScroll', this.mouseWheel);\n }\n }\n };\n ;\n NumericTextBox.prototype.mouseDownOnSpinner = function (event) {\n var _this = this;\n if (this.isFocused) {\n this.isPrevFocused = true;\n event.preventDefault();\n }\n if (!this.getElementData(event)) {\n return;\n }\n var result = this.getElementData(event);\n var target = event.currentTarget;\n var action = (target.classList.contains(SPINUP)) ? INCREMENT : DECREMENT;\n EventHandler.add(target, 'mouseleave', this.mouseUpClick, this);\n this.timeOut = setInterval(function () { _this.isCalled = true; _this.action(action, event); }, 150);\n EventHandler.add(document, 'mouseup', this.mouseUpClick, this);\n };\n NumericTextBox.prototype.touchMoveOnSpinner = function (event) {\n var target = document.elementFromPoint(event.clientX, event.clientY);\n if (!(target.classList.contains(SPINICON))) {\n clearInterval(this.timeOut);\n }\n };\n NumericTextBox.prototype.mouseUpOnSpinner = function (event) {\n if (this.isPrevFocused) {\n this.element.focus();\n if (!Browser.isDevice) {\n this.isPrevFocused = false;\n }\n }\n if (!Browser.isDevice) {\n event.preventDefault();\n }\n if (!this.getElementData(event)) {\n return;\n }\n var target = event.currentTarget;\n var action = (target.classList.contains(SPINUP)) ? INCREMENT : DECREMENT;\n EventHandler.remove(target, 'mouseleave', this.mouseUpClick);\n if (!this.isCalled) {\n this.action(action, event);\n }\n this.isCalled = false;\n EventHandler.remove(document, 'mouseup', this.mouseUpClick);\n };\n NumericTextBox.prototype.getElementData = function (event) {\n if ((event.which && event.which === 3) || (event.button && event.button === 2)\n || !this.enabled || this.readonly) {\n return false;\n }\n clearInterval(this.timeOut);\n return true;\n };\n NumericTextBox.prototype.floatLabelTypeUpdate = function () {\n Input.removeFloating(this.inputWrapper);\n var hiddenInput = this.hiddenInput;\n this.hiddenInput.remove();\n Input.addFloating(this.element, this.floatLabelType, this.placeholder, this.createElement);\n this.container.insertBefore(hiddenInput, this.container.childNodes[1]);\n };\n NumericTextBox.prototype.mouseUpClick = function (event) {\n event.stopPropagation();\n clearInterval(this.timeOut);\n this.isCalled = false;\n EventHandler.remove(this.spinUp, 'mouseleave', this.mouseUpClick);\n EventHandler.remove(this.spinDown, 'mouseleave', this.mouseUpClick);\n };\n /**\n * Increments the NumericTextBox value with the specified step value.\n * @param {number} step - Specifies the value used to increment the NumericTextBox value.\n * if its not given then numeric value will be incremented based on the step property value.\n */\n NumericTextBox.prototype.increment = function (step) {\n if (step === void 0) { step = this.step; }\n this.isInteract = false;\n this.changeValue(this.performAction(this.value, step, INCREMENT));\n this.raiseChangeEvent();\n };\n /**\n * Decrements the NumericTextBox value with specified step value.\n * @param {number} step - Specifies the value used to decrement the NumericTextBox value.\n * if its not given then numeric value will be decremented based on the step property value.\n */\n NumericTextBox.prototype.decrement = function (step) {\n if (step === void 0) { step = this.step; }\n this.isInteract = false;\n this.changeValue(this.performAction(this.value, step, DECREMENT));\n this.raiseChangeEvent();\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers.\n * Also it maintains the initial input element from the DOM.\n * @method destroy\n * @return {void}\n */\n NumericTextBox.prototype.destroy = function () {\n this.unwireEvents();\n detach(this.hiddenInput);\n if (this.showSpinButton) {\n this.unwireSpinBtnEvents();\n detach(this.spinUp);\n detach(this.spinDown);\n }\n this.container.parentElement.appendChild(this.cloneElement);\n detach(this.container);\n _super.prototype.destroy.call(this);\n };\n /**\n * Returns the value of NumericTextBox with the format applied to the NumericTextBox.\n */\n NumericTextBox.prototype.getText = function () {\n return this.element.value;\n };\n /**\n * Gets the properties to be maintained in the persisted state.\n * @return {string}\n */\n NumericTextBox.prototype.getPersistData = function () {\n var keyEntity = ['value'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Calls internally if any of the property value is changed.\n * @private\n */\n NumericTextBox.prototype.onPropertyChanged = function (newProp, oldProp) {\n var elementVal;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'width':\n setStyleAttribute(this.container, { 'width': formatUnit(newProp.width) });\n break;\n case 'cssClass':\n Input.setCssClass(newProp.cssClass, [this.container], oldProp.cssClass);\n break;\n case 'enabled':\n Input.setEnabled(newProp.enabled, this.element);\n break;\n case 'enableRtl':\n Input.setEnableRtl(newProp.enableRtl, [this.container]);\n break;\n case 'readonly':\n Input.setReadonly(newProp.readonly, this.element);\n if (this.readonly) {\n attributes(this.element, { 'aria-readonly': 'true' });\n }\n else {\n this.element.removeAttribute('aria-readonly');\n }\n break;\n case 'placeholder':\n Input.setPlaceholder(newProp.placeholder, this.element);\n break;\n case 'step':\n this.step = newProp.step;\n this.validateStep();\n break;\n case 'showSpinButton':\n if (newProp.showSpinButton) {\n this.spinBtnCreation();\n }\n else {\n detach(this.spinUp);\n detach(this.spinDown);\n }\n break;\n case 'showClearButton':\n Input.setClearButton(newProp.showClearButton, this.element, this.inputWrapper, undefined, this.createElement);\n this.bindClearEvent();\n break;\n case 'floatLabelType':\n this.floatLabelType = newProp.floatLabelType;\n this.floatLabelTypeUpdate();\n break;\n case 'value':\n this.updateValue(newProp.value);\n break;\n case 'min':\n case 'max':\n setValue(prop, getValue(prop, newProp), this);\n this.validateMinMax();\n this.updateValue(this.value);\n break;\n case 'strictMode':\n this.strictMode = newProp.strictMode;\n this.updateValue(this.value);\n this.validateState();\n break;\n case 'locale':\n this.initCultureFunc();\n this.l10n.setLocale(this.locale);\n if (!isNullOrUndefined(this.spinDown)) {\n attributes(this.spinDown, {\n 'title': this.l10n.getConstant('decrementTitle'),\n 'aria-label': this.l10n.getConstant('decrementTitle')\n });\n }\n if (!isNullOrUndefined(this.spinUp)) {\n attributes(this.spinUp, {\n 'title': this.l10n.getConstant('incrementTitle'),\n 'aria-label': this.l10n.getConstant('incrementTitle')\n });\n }\n this.updatePlaceholder();\n Input.setPlaceholder(this.placeholder, this.element);\n this.updateValue(this.value);\n break;\n case 'currency':\n var propVal = getValue(prop, newProp);\n this.setProperties({ currencyCode: propVal }, true);\n this.updateCurrency(prop, propVal);\n break;\n case 'currencyCode':\n var propValue = getValue(prop, newProp);\n this.setProperties({ currency: propValue }, true);\n this.updateCurrency('currency', propValue);\n break;\n case 'format':\n setValue(prop, getValue(prop, newProp), this);\n this.initCultureInfo();\n this.updateValue(this.value);\n break;\n case 'decimals':\n this.decimals = newProp.decimals;\n this.updateValue(this.value);\n }\n }\n };\n /**\n * Gets the component name\n * @private\n */\n NumericTextBox.prototype.getModuleName = function () {\n return 'numerictextbox';\n };\n __decorate([\n Property('')\n ], NumericTextBox.prototype, \"cssClass\", void 0);\n __decorate([\n Property(null)\n ], NumericTextBox.prototype, \"value\", void 0);\n __decorate([\n Property(-(Number.MAX_VALUE))\n ], NumericTextBox.prototype, \"min\", void 0);\n __decorate([\n Property(Number.MAX_VALUE)\n ], NumericTextBox.prototype, \"max\", void 0);\n __decorate([\n Property(1)\n ], NumericTextBox.prototype, \"step\", void 0);\n __decorate([\n Property(null)\n ], NumericTextBox.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], NumericTextBox.prototype, \"placeholder\", void 0);\n __decorate([\n Property(true)\n ], NumericTextBox.prototype, \"showSpinButton\", void 0);\n __decorate([\n Property(false)\n ], NumericTextBox.prototype, \"readonly\", void 0);\n __decorate([\n Property(true)\n ], NumericTextBox.prototype, \"enabled\", void 0);\n __decorate([\n Property(false)\n ], NumericTextBox.prototype, \"enableRtl\", void 0);\n __decorate([\n Property(false)\n ], NumericTextBox.prototype, \"showClearButton\", void 0);\n __decorate([\n Property(false)\n ], NumericTextBox.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property('n2')\n ], NumericTextBox.prototype, \"format\", void 0);\n __decorate([\n Property(null)\n ], NumericTextBox.prototype, \"decimals\", void 0);\n __decorate([\n Property(null)\n ], NumericTextBox.prototype, \"currency\", void 0);\n __decorate([\n Property(null)\n ], NumericTextBox.prototype, \"currencyCode\", void 0);\n __decorate([\n Property(true)\n ], NumericTextBox.prototype, \"strictMode\", void 0);\n __decorate([\n Property(false)\n ], NumericTextBox.prototype, \"validateDecimalOnType\", void 0);\n __decorate([\n Property('Never')\n ], NumericTextBox.prototype, \"floatLabelType\", void 0);\n __decorate([\n Event()\n ], NumericTextBox.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], NumericTextBox.prototype, \"destroyed\", void 0);\n __decorate([\n Event()\n ], NumericTextBox.prototype, \"change\", void 0);\n NumericTextBox = __decorate([\n NotifyPropertyChanges\n ], NumericTextBox);\n return NumericTextBox;\n}(Component));\nexport { NumericTextBox };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { selectAll, select, createElement, Base } from '@syncfusion/ej2-base';\nimport { extend, isNullOrUndefined, EventHandler } from '@syncfusion/ej2-base';\nimport { Property, NotifyPropertyChanges, Event } from '@syncfusion/ej2-base';\n/**\n * global declarations\n */\nvar VALIDATE_EMAIL = new RegExp('^[A-Za-z0-9._%+-]{3,}@[a-zA-Z]{3,}([.]{1}[a-zA-Z]{2,5}' +\n '|[.]{1}[a-zA-Z]{2,4}[.]{1}[a-zA-Z]{2,4})$');\nvar VALIDATE_URL = new RegExp('^((ftp|http|https):\\/\\/)?www\\.([A-z]{2,})\\.([A-z]{2,})$');\nvar VALIDATE_DATE_ISO = new RegExp('^([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$');\nvar VALIDATE_DIGITS = new RegExp('^[0-9]*$');\nvar VALIDATE_PHONE = new RegExp('^[+]?[0-9]{9,13}$');\nvar VALIDATE_CREDITCARD = new RegExp('^\\\\d{13,16}$');\n/**\n * ErrorOption values\n * @private\n */\nexport var ErrorOption;\n(function (ErrorOption) {\n ErrorOption[ErrorOption[\"Message\"] = 0] = \"Message\";\n ErrorOption[ErrorOption[\"Label\"] = 1] = \"Label\";\n})(ErrorOption || (ErrorOption = {}));\n/**\n * FormValidator class enables you to validate the form fields based on your defined rules\n * ```html\n *
\n * \n * ```\n */\nvar FormValidator = /** @class */ (function (_super) {\n __extends(FormValidator, _super);\n // Initializes the FormValidator \n function FormValidator(element, options) {\n var _this = _super.call(this, options, element) || this;\n _this.validated = [];\n _this.errorRules = [];\n _this.allowSubmit = false;\n _this.required = 'required';\n _this.infoElement = null;\n _this.inputElement = null;\n _this.selectQuery = 'input:not([type=reset]):not([type=button]), select, textarea';\n /**\n * Specifies the default messages for validation rules.\n * @default : { List of validation message };\n */\n _this.defaultMessages = {\n required: 'This field is required.',\n email: 'Please enter a valid email address.',\n url: 'Please enter a valid URL.',\n date: 'Please enter a valid date.',\n dateIso: 'Please enter a valid date ( ISO ).',\n creditcard: 'Please enter valid card number',\n number: 'Please enter a valid number.',\n digits: 'Please enter only digits.',\n maxLength: 'Please enter no more than {0} characters.',\n minLength: 'Please enter at least {0} characters.',\n rangeLength: 'Please enter a value between {0} and {1} characters long.',\n range: 'Please enter a value between {0} and {1}.',\n max: 'Please enter a value less than or equal to {0}.',\n min: 'Please enter a value greater than or equal to {0}.',\n regex: 'Please enter a correct value.',\n tel: 'Please enter a valid phone number.',\n pattern: 'Please enter a correct pattern value.',\n equalTo: 'Please enter the valid match text',\n };\n if (typeof _this.rules === 'undefined') {\n _this.rules = {};\n }\n element = typeof element === 'string' ? select(element, document) : element;\n // Set novalidate to prevent default HTML5 form validation\n if (_this.element != null) {\n _this.element.setAttribute('novalidate', '');\n _this.inputElements = selectAll(_this.selectQuery, _this.element);\n _this.createHTML5Rules();\n _this.wireEvents();\n }\n else {\n return undefined;\n }\n return _this;\n }\n FormValidator_1 = FormValidator;\n /**\n * Add validation rules to the corresponding input element based on `name` attribute.\n * @param {string} name `name` of form field.\n * @param {Object} rules Validation rules for the corresponding element.\n * @return {void}\n */\n FormValidator.prototype.addRules = function (name, rules) {\n if (name) {\n if (this.rules.hasOwnProperty(name)) {\n extend(this.rules[name], rules, {});\n }\n else {\n this.rules[name] = rules;\n }\n }\n };\n /**\n * Remove validation to the corresponding field based on name attribute.\n * When no parameter is passed, remove all the validations in the form.\n * @param {string} name Input name attribute value.\n * @param {string[]} rules List of validation rules need to be remove from the corresponding element.\n * @return {void}\n */\n FormValidator.prototype.removeRules = function (name, rules) {\n if (!name && !rules) {\n this.rules = {};\n }\n else if (this.rules[name] && !rules) {\n delete this.rules[name];\n }\n else if (!isNullOrUndefined(this.rules[name] && rules)) {\n for (var i = 0; i < rules.length; i++) {\n delete this.rules[name][rules[i]];\n }\n }\n else {\n return;\n }\n };\n /**\n * Validate the current form values using defined rules.\n * Returns `true` when the form is valid otherwise `false`\n * @param {string} selected - Optional parameter to validate specified element.\n * @return {boolean}\n */\n FormValidator.prototype.validate = function (selected) {\n var rules = Object.keys(this.rules);\n if (selected && rules.length) {\n this.validateRules(selected);\n //filter the selected element it don't have any valid input element\n return rules.indexOf(selected) !== -1 && this.errorRules.filter(function (data) {\n return data.name === selected;\n }).length === 0;\n }\n else {\n for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {\n var name_1 = rules_1[_i];\n this.validateRules(name_1);\n }\n return this.errorRules.length === 0;\n }\n };\n /**\n * Reset the value of all the fields in form.\n * @return {void}\n */\n FormValidator.prototype.reset = function () {\n this.element.reset();\n this.clearForm();\n };\n /**\n * Get input element by name.\n * @param {string} name - Input element name attribute value.\n * @return {HTMLInputElement}\n */\n FormValidator.prototype.getInputElement = function (name) {\n this.inputElement = (select('[name=' + name + ']', this.element));\n return this.inputElement;\n };\n /**\n * Destroy the form validator object and error elements.\n * @return {void}\n */\n FormValidator.prototype.destroy = function () {\n this.reset();\n this.unwireEvents();\n this.rules = {};\n var elements = selectAll('.' + this.errorClass + ', .' + this.validClass, this.element);\n for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {\n var element = elements_1[_i];\n element.remove();\n }\n _super.prototype.destroy.call(this);\n };\n /**\n * @private\n */\n FormValidator.prototype.onPropertyChanged = function (newProp, oldProp) {\n // No code are needed\n };\n ;\n /**\n * @private\n */\n FormValidator.prototype.getModuleName = function () {\n return 'formValidator';\n };\n FormValidator.prototype.clearForm = function () {\n this.errorRules = [];\n this.validated = [];\n var elements = selectAll(this.selectQuery, this.element);\n for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {\n var element = elements_2[_i];\n var input = element;\n input.removeAttribute('aria-invalid');\n input.classList.remove(this.errorClass);\n if (input.name.length > 0) {\n this.getInputElement(input.name);\n this.getErrorElement(input.name);\n this.hideMessage(input.name);\n }\n input.classList.remove(this.validClass);\n }\n };\n FormValidator.prototype.createHTML5Rules = function () {\n var defRules = ['required', 'validateHidden', 'regex', 'rangeLength', 'maxLength', 'minLength', 'dateIso', 'digits',\n 'pattern', 'data-val-required', 'type', 'data-validation', 'min', 'max', 'range', 'equalTo', 'data-val-minlength-min',\n 'data-val-equalto-other', 'data-val-maxlength-max', 'data-val-range-min', 'data-val-regex-pattern', 'data-val-length-max',\n 'data-val-creditcard', 'data-val-phone'];\n var acceptedTypes = ['hidden', 'email', 'url', 'date', 'number', 'tel'];\n for (var _i = 0, _a = (this.inputElements); _i < _a.length; _i++) {\n var input = _a[_i];\n // Default attribute rules \n var allRule = {};\n for (var _b = 0, defRules_1 = defRules; _b < defRules_1.length; _b++) {\n var rule = defRules_1[_b];\n if (input.getAttribute(rule) !== null) {\n switch (rule) {\n case 'required':\n this.defRule(input, allRule, rule, input.required);\n break;\n case 'data-validation':\n rule = input.getAttribute(rule);\n this.defRule(input, allRule, rule, true);\n break;\n case 'type':\n if (acceptedTypes.indexOf(input.type) !== -1) {\n this.defRule(input, allRule, input.type, true);\n }\n break;\n case 'rangeLength':\n case 'range':\n this.defRule(input, allRule, rule, JSON.parse(input.getAttribute(rule)));\n break;\n case 'equalTo':\n var id = input.getAttribute(rule);\n this.defRule(input, allRule, rule, id);\n break;\n default:\n if (input.getAttribute('data-val') === 'true') {\n this.annotationRule(input, allRule, rule, input.getAttribute(rule));\n }\n else {\n this.defRule(input, allRule, rule, input.getAttribute(rule));\n }\n }\n }\n }\n //adding pattern type validation\n if (Object.keys(allRule).length !== 0) {\n this.addRules(input.name, allRule);\n }\n }\n };\n FormValidator.prototype.annotationRule = function (input, ruleCon, ruleName, value) {\n var annotationRule = ruleName.split('-');\n var rulesList = ['required', 'creditcard', 'phone', 'maxlength', 'minlength', 'range', 'regex', 'equalto'];\n var ruleFirstName = annotationRule[annotationRule.length - 1];\n var ruleSecondName = annotationRule[annotationRule.length - 2];\n if (rulesList.indexOf(ruleFirstName) !== -1) {\n switch (ruleFirstName) {\n case 'required':\n this.defRule(input, ruleCon, 'required', value);\n break;\n case 'creditcard':\n this.defRule(input, ruleCon, 'creditcard', value);\n break;\n case 'phone':\n this.defRule(input, ruleCon, 'tel', value);\n break;\n }\n }\n else if (rulesList.indexOf(ruleSecondName) !== -1) {\n switch (ruleSecondName) {\n case 'maxlength':\n this.defRule(input, ruleCon, 'maxLength', value);\n break;\n case 'minlength':\n this.defRule(input, ruleCon, 'minLength', value);\n break;\n case 'range':\n var minvalue = input.getAttribute('data-val-range-min');\n var maxvalue = input.getAttribute('data-val-range-max');\n this.defRule(input, ruleCon, 'range', [minvalue, maxvalue]);\n break;\n case 'equalto':\n var id = input.getAttribute(ruleName).split('.');\n this.defRule(input, ruleCon, 'equalTo', id[id.length - 1]);\n break;\n case 'regex':\n this.defRule(input, ruleCon, 'regex', value);\n break;\n }\n }\n };\n FormValidator.prototype.defRule = function (input, ruleCon, ruleName, value) {\n var message = input.getAttribute('data-' + ruleName + '-message');\n var annotationMessage = input.getAttribute('data-val-' + ruleName);\n if (message) {\n value = [value, message];\n }\n else if (annotationMessage) {\n value = [value, annotationMessage];\n }\n ruleCon[ruleName] = value;\n };\n // Wire events to the form elements\n FormValidator.prototype.wireEvents = function () {\n for (var _i = 0, _a = (this.inputElements); _i < _a.length; _i++) {\n var input = _a[_i];\n if (FormValidator_1.isCheckable(input)) {\n EventHandler.add(input, 'click', this.clickHandler, this);\n }\n else if (input.tagName === 'SELECT') {\n EventHandler.add(input, 'change', this.changeHandler, this);\n }\n else {\n EventHandler.add(input, 'focusout', this.focusOutHandler, this);\n EventHandler.add(input, 'keyup', this.keyUpHandler, this);\n }\n }\n EventHandler.add(this.element, 'submit', this.submitHandler, this);\n EventHandler.add(this.element, 'reset', this.resetHandler, this);\n };\n // UnWire events to the form elements\n FormValidator.prototype.unwireEvents = function () {\n for (var _i = 0, _a = (this.inputElements); _i < _a.length; _i++) {\n var input = _a[_i];\n EventHandler.clearEvents(input);\n }\n EventHandler.remove(this.element, 'submit', this.submitHandler);\n EventHandler.remove(this.element, 'reset', this.resetHandler);\n };\n // Handle input element focusout event\n FormValidator.prototype.focusOutHandler = function (e) {\n this.trigger('focusout', e);\n //FormValidator.triggerCallback(this.focusout, e);\n var element = e.target;\n if (this.rules[element.name]) {\n if (this.rules[element.name][this.required] || element.value.length > 0) {\n this.validate(element.name);\n }\n else if (this.validated.indexOf(element.name) === -1) {\n this.validated.push(element.name);\n }\n }\n };\n // Handle input element keyup event\n FormValidator.prototype.keyUpHandler = function (e) {\n this.trigger('keyup', e);\n var element = e.target;\n // List of keys need to prevent while validation\n var excludeKeys = [16, 17, 18, 20, 35, 36, 37, 38, 39, 40, 45, 144, 225];\n if (e.which === 9 && (!this.rules[element.name] || (this.rules[element.name] && !this.rules[element.name][this.required]))) {\n return;\n }\n if (this.validated.indexOf(element.name) !== -1 && this.rules[element.name] && excludeKeys.indexOf(e.which) === -1) {\n this.validate(element.name);\n }\n };\n // Handle input click event\n FormValidator.prototype.clickHandler = function (e) {\n this.trigger('click', e);\n var element = e.target;\n // If element type is not submit allow validation\n if (element.type !== 'submit') {\n this.validate(element.name);\n }\n else if (element.getAttribute('formnovalidate') !== null) {\n // Prevent form validation, if submit button has formnovalidate attribute\n this.allowSubmit = true;\n }\n };\n // Handle input change event\n FormValidator.prototype.changeHandler = function (e) {\n this.trigger('change', e);\n var element = e.target;\n this.validate(element.name);\n };\n // Handle form submit event\n FormValidator.prototype.submitHandler = function (e) {\n this.trigger('submit', e);\n //FormValidator.triggerCallback(this.submit, e);\n // Prevent form submit if validation failed\n if (!this.allowSubmit && !this.validate()) {\n e.preventDefault();\n }\n else {\n this.allowSubmit = false;\n }\n };\n // Handle form reset\n FormValidator.prototype.resetHandler = function () {\n this.clearForm();\n };\n // Validate each rule based on input element name\n FormValidator.prototype.validateRules = function (name) {\n if (!this.rules[name]) {\n return;\n }\n var rules = Object.keys(this.rules[name]);\n var hiddenType = false;\n var validateHiddenType = false;\n var vhPos = rules.indexOf('validateHidden');\n var hPos = rules.indexOf('hidden');\n this.getInputElement(name);\n if (hPos !== -1) {\n hiddenType = true;\n }\n if (vhPos !== -1) {\n validateHiddenType = true;\n }\n if (!hiddenType || (hiddenType && validateHiddenType)) {\n if (vhPos !== -1) {\n rules.splice(vhPos, 1);\n }\n if (hPos !== -1) {\n rules.splice((hPos - 1), 1);\n }\n this.getErrorElement(name);\n for (var _i = 0, rules_2 = rules; _i < rules_2.length; _i++) {\n var rule = rules_2[_i];\n var errorMessage = this.getErrorMessage(this.rules[name][rule], rule);\n var errorRule = { name: name, message: errorMessage };\n var eventArgs = {\n inputName: name,\n element: this.inputElement,\n message: errorMessage\n };\n if (!this.isValid(name, rule) && !this.inputElement.classList.contains(this.ignore)) {\n this.removeErrorRules(name);\n this.errorRules.push(errorRule);\n // Set aria attributes to invalid elements\n this.inputElement.setAttribute('aria-invalid', 'true');\n this.inputElement.setAttribute('aria-describedby', this.inputElement.id + '-info');\n this.inputElement.classList.add(this.errorClass);\n this.inputElement.classList.remove(this.validClass);\n if (!this.infoElement) {\n this.createErrorElement(name, errorRule.message, this.inputElement);\n }\n else {\n this.showMessage(errorRule);\n }\n eventArgs.errorElement = this.infoElement;\n eventArgs.status = 'failure';\n this.inputElement.classList.add(this.errorClass);\n this.inputElement.classList.remove(this.validClass);\n this.optionalValidationStatus(name, eventArgs);\n this.trigger('validationComplete', eventArgs);\n // Set aria-required to required rule elements\n if (rule === 'required') {\n this.inputElement.setAttribute('aria-required', 'true');\n }\n break;\n }\n else {\n this.hideMessage(name);\n eventArgs.status = 'success';\n this.trigger('validationComplete', eventArgs);\n }\n }\n }\n else {\n return;\n }\n };\n // Update the optional validation status\n FormValidator.prototype.optionalValidationStatus = function (name, refer) {\n if (!this.rules[name][this.required] && !this.inputElement.value.length) {\n this.infoElement.innerHTML = this.inputElement.value;\n this.infoElement.setAttribute('aria-invalid', 'false');\n refer.status = '';\n this.hideMessage(name);\n }\n };\n // Check the input element whether it's value satisfy the validation rule or not\n FormValidator.prototype.isValid = function (name, rule) {\n var params = this.rules[name][rule];\n var param = (params instanceof Array && typeof params[1] === 'string') ? params[0] : params;\n var currentRule = this.rules[name][rule];\n var args = { value: this.inputElement.value, param: param, element: this.inputElement, formElement: this.element };\n this.trigger('validationBegin', args);\n if (currentRule && typeof currentRule[0] === 'function') {\n var fn = currentRule[0];\n return fn.call(this, { element: this.inputElement, value: this.inputElement.value });\n }\n else if (FormValidator_1.isCheckable(this.inputElement)) {\n if (rule !== 'required') {\n return true;\n }\n return selectAll('input[name=' + name + ']:checked', this.element).length > 0;\n }\n else {\n return FormValidator_1.checkValidator[rule](args);\n }\n };\n // Return default error message or custom error message \n FormValidator.prototype.getErrorMessage = function (ruleValue, rule) {\n var message = (ruleValue instanceof Array && typeof ruleValue[1] === 'string') ? ruleValue[1] : this.defaultMessages[rule];\n var formats = message.match(/{(\\d)}/g);\n if (!isNullOrUndefined(formats)) {\n for (var i = 0; i < formats.length; i++) {\n var value = ruleValue instanceof Array ? ruleValue[i] : ruleValue;\n message = message.replace(formats[i], value);\n }\n }\n return message;\n };\n // Create error element based on name and error message\n FormValidator.prototype.createErrorElement = function (name, message, input) {\n var errorElement = createElement(this.errorElement, {\n className: this.errorClass,\n innerHTML: message,\n attrs: { for: name }\n });\n // Create message design if errorOption is message\n if (this.errorOption === ErrorOption.Message) {\n errorElement.classList.remove(this.errorClass);\n errorElement.classList.add('e-message');\n errorElement = createElement(this.errorContainer, { className: this.errorClass, innerHTML: errorElement.outerHTML });\n }\n errorElement.id = this.inputElement.name + '-info';\n // Append error message into MVC error message element\n if (this.element.querySelector('[data-valmsg-for=\"' + input.id + '\"]')) {\n this.element.querySelector('[data-valmsg-for=\"' + input.id + '\"]').appendChild(errorElement);\n }\n else if (input.hasAttribute('data-msg-containerid') === true) {\n // Append error message into custom div element\n var containerId = input.getAttribute('data-msg-containerid');\n var divElement = this.element.querySelector('#' + containerId);\n divElement.appendChild(errorElement);\n }\n else if (this.customPlacement != null) {\n // Call custom placement function if customPlacement is not null\n this.customPlacement.call(this, this.inputElement, errorElement);\n }\n else {\n this.inputElement.parentNode.insertBefore(errorElement, this.inputElement.nextSibling);\n }\n errorElement.style.display = 'block';\n this.getErrorElement(name);\n this.validated.push(name);\n this.checkRequired(name);\n };\n // Get error element by name\n FormValidator.prototype.getErrorElement = function (name) {\n this.infoElement = select(this.errorElement + '.' + this.errorClass, this.inputElement.parentElement);\n if (!this.infoElement) {\n this.infoElement = select(this.errorElement + '.' + this.errorClass + '[for=\"' + name + '\"]');\n }\n return this.infoElement;\n };\n // Remove existing rule from errorRules object\n FormValidator.prototype.removeErrorRules = function (name) {\n for (var i = 0; i < this.errorRules.length; i++) {\n var rule = this.errorRules[i];\n if (rule.name === name) {\n this.errorRules.splice(i, 1);\n }\n }\n };\n // Show error message to the input element\n FormValidator.prototype.showMessage = function (errorRule) {\n this.infoElement.style.display = 'block';\n this.infoElement.innerHTML = errorRule.message;\n this.checkRequired(errorRule.name);\n };\n // Hide error message based on input name\n FormValidator.prototype.hideMessage = function (name) {\n if (this.infoElement) {\n this.infoElement.style.display = 'none';\n this.removeErrorRules(name);\n this.inputElement.classList.add(this.validClass);\n this.inputElement.classList.remove(this.errorClass);\n this.inputElement.setAttribute('aria-invalid', 'false');\n }\n };\n // Check whether the input element have required rule and its value is not empty\n FormValidator.prototype.checkRequired = function (name) {\n if (!this.rules[name][this.required] && !this.inputElement.value.length) {\n this.infoElement.innerHTML = this.inputElement.value;\n this.infoElement.setAttribute('aria-invalid', 'false');\n this.hideMessage(name);\n }\n };\n // Return boolean result if the input have chekcable or submit types\n FormValidator.isCheckable = function (input) {\n var inputType = input.getAttribute('type');\n return inputType && (inputType === 'checkbox' || inputType === 'radio' || inputType === 'submit');\n };\n // List of function to validate the rules\n FormValidator.checkValidator = {\n required: function (option) {\n return option.value.length > 0;\n },\n email: function (option) {\n return VALIDATE_EMAIL.test(option.value);\n },\n url: function (option) {\n return VALIDATE_URL.test(option.value);\n },\n dateIso: function (option) {\n return VALIDATE_DATE_ISO.test(option.value);\n },\n tel: function (option) {\n return VALIDATE_PHONE.test(option.value);\n },\n creditcard: function (option) {\n return VALIDATE_CREDITCARD.test(option.value);\n },\n number: function (option) {\n return !isNaN(Number(option.value)) && option.value.indexOf(' ') === -1;\n },\n digits: function (option) {\n return VALIDATE_DIGITS.test(option.value);\n },\n maxLength: function (option) {\n return option.value.length <= option.param;\n },\n minLength: function (option) {\n return option.value.length >= option.param;\n },\n rangeLength: function (option) {\n var param = option.param;\n return option.value.length >= param[0] && option.value.length <= param[1];\n },\n range: function (option) {\n var param = option.param;\n return !isNaN(Number(option.value)) && Number(option.value) >= param[0] && Number(option.value) <= param[1];\n },\n date: function (option) {\n return !isNaN(new Date(option.value).getTime());\n },\n max: function (option) {\n if (!isNaN(Number(option.value))) {\n // Maximum rule validation for number\n return +option.value <= option.param;\n }\n // Maximum rule validation for date\n return new Date(option.value).getTime() <= new Date(JSON.parse(JSON.stringify(option.param))).getTime();\n },\n min: function (option) {\n if (!isNaN(Number(option.value))) {\n // Minimum rule validation for number\n return +option.value >= option.param;\n }\n // Minimum rule validation for date\n return new Date(option.value).getTime() >= new Date(JSON.parse(JSON.stringify(option.param))).getTime();\n },\n regex: function (option) {\n return new RegExp(option.param).test(option.value);\n },\n equalTo: function (option) {\n var compareTo = option.formElement.querySelector('#' + option.param);\n option.param = compareTo.value;\n return option.param === option.value;\n },\n };\n __decorate([\n Property('e-hidden')\n ], FormValidator.prototype, \"ignore\", void 0);\n __decorate([\n Property()\n ], FormValidator.prototype, \"rules\", void 0);\n __decorate([\n Property('e-error')\n ], FormValidator.prototype, \"errorClass\", void 0);\n __decorate([\n Property('e-valid')\n ], FormValidator.prototype, \"validClass\", void 0);\n __decorate([\n Property('label')\n ], FormValidator.prototype, \"errorElement\", void 0);\n __decorate([\n Property('div')\n ], FormValidator.prototype, \"errorContainer\", void 0);\n __decorate([\n Property(ErrorOption.Label)\n ], FormValidator.prototype, \"errorOption\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"focusout\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"keyup\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"click\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"submit\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"validationBegin\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"validationComplete\", void 0);\n __decorate([\n Event()\n ], FormValidator.prototype, \"customPlacement\", void 0);\n FormValidator = FormValidator_1 = __decorate([\n NotifyPropertyChanges\n ], FormValidator);\n return FormValidator;\n var FormValidator_1;\n}(Base));\nexport { FormValidator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Event, Property, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, formatUnit, getValue, setValue, addClass, detach } from '@syncfusion/ej2-base';\nimport { removeClass } from '@syncfusion/ej2-base';\nimport { Input } from '../../input/input';\nimport { regularExpressions, createMask, applyMask, wireEvents, unwireEvents, unstrippedValue, strippedValue } from '../base/index';\nimport { setMaskValue, setElementValue, bindClearEvent } from '../base/index';\nimport { maskInputBlurHandler } from '../base/mask-base';\nvar ROOT = 'e-widget e-control-wrapper e-mask';\nvar INPUT = 'e-input';\nvar COMPONENT = 'e-maskedtextbox';\nvar CONTROL = 'e-control';\n/**\n * The MaskedTextBox allows the user to enter the valid input only based on the provided mask.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar MaskedTextBox = /** @class */ (function (_super) {\n __extends(MaskedTextBox, _super);\n function MaskedTextBox(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * Gets the component name\n * @private\n */\n MaskedTextBox.prototype.getModuleName = function () {\n return 'maskedtextbox';\n };\n /**\n * Initializes the event handler\n * @private\n */\n MaskedTextBox.prototype.preRender = function () {\n this.promptMask = '';\n this.hiddenMask = '';\n this.escapeMaskValue = '';\n this.regExpCollec = regularExpressions;\n this.customRegExpCollec = [];\n this.undoCollec = [];\n this.redoCollec = [];\n this.changeEventArgs = {};\n this.focusEventArgs = {};\n this.maskKeyPress = false;\n this.isFocus = false;\n this.isInitial = false;\n this.isIosInvalid = false;\n var ejInstance = getValue('ej2_instances', this.element);\n this.cloneElement = this.element.cloneNode(true);\n removeClass([this.cloneElement], [CONTROL, COMPONENT]);\n this.angularTagName = null;\n if (this.element.tagName === 'EJS-MASKEDTEXTBOX') {\n this.angularTagName = this.element.tagName;\n var input = this.createElement('input');\n for (var i = 0; i < this.element.attributes.length; i++) {\n input.setAttribute(this.element.attributes[i].nodeName, this.element.attributes[i].nodeValue);\n input.innerHTML = this.element.innerHTML;\n }\n if (this.element.hasAttribute('id')) {\n this.element.removeAttribute('id');\n }\n this.element.classList.remove('e-control', 'e-maskedtextbox');\n this.element.classList.add('e-mask-container');\n this.element.appendChild(input);\n this.element = input;\n setValue('ej2_instances', ejInstance, this.element);\n }\n };\n /**\n * Gets the properties to be maintained in the persisted state.\n * @return {string}\n */\n MaskedTextBox.prototype.getPersistData = function () {\n var keyEntity = ['value'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Initializes the component rendering.\n * @private\n */\n MaskedTextBox.prototype.render = function () {\n if (this.element.tagName.toLowerCase() === 'input') {\n if (this.floatLabelType === 'Never') {\n addClass([this.element], INPUT);\n }\n this.createWrapper();\n if (this.element.name === '') {\n this.element.setAttribute('name', this.element.id);\n }\n this.isInitial = true;\n this.resetMaskedTextBox();\n this.isInitial = false;\n this.setMaskPlaceholder(true, false);\n this.setWidth(this.width);\n this.preEleVal = this.element.value;\n }\n };\n MaskedTextBox.prototype.resetMaskedTextBox = function () {\n this.promptMask = '';\n this.hiddenMask = '';\n this.escapeMaskValue = '';\n this.customRegExpCollec = [];\n this.undoCollec = [];\n this.redoCollec = [];\n if (this.promptChar.length > 1) {\n this.promptChar = this.promptChar[0];\n }\n createMask.call(this);\n applyMask.call(this);\n if (this.mask === null || this.mask === '' && this.value !== undefined) {\n setElementValue.call(this, this.value);\n }\n var val = strippedValue.call(this, this.element);\n this.prevValue = val;\n this.value = val;\n if (!this.isInitial) {\n unwireEvents.call(this);\n }\n wireEvents.call(this);\n };\n MaskedTextBox.prototype.setMaskPlaceholder = function (setVal, dynamicPlaceholder) {\n if (dynamicPlaceholder || this.placeholder) {\n Input.setPlaceholder(this.placeholder, this.element);\n if (this.element.value === this.promptMask && setVal && this.floatLabelType !== 'Always') {\n setElementValue.call(this, '');\n }\n if (this.floatLabelType === 'Never') {\n maskInputBlurHandler.call(this);\n }\n }\n };\n MaskedTextBox.prototype.setCssClass = function (cssClass, element) {\n if (cssClass) {\n addClass(element, cssClass);\n }\n };\n MaskedTextBox.prototype.setWidth = function (width) {\n if (!isNullOrUndefined(width)) {\n this.element.style.width = formatUnit(width);\n this.inputObj.container.style.width = formatUnit(width);\n }\n };\n MaskedTextBox.prototype.createWrapper = function () {\n this.inputObj = Input.createInput({\n element: this.element,\n floatLabelType: this.floatLabelType,\n properties: {\n enableRtl: this.enableRtl,\n cssClass: this.cssClass,\n enabled: this.enabled,\n placeholder: this.placeholder,\n showClearButton: this.showClearButton\n }\n }, this.createElement);\n this.inputObj.container.setAttribute('class', ROOT + ' ' + this.inputObj.container.getAttribute('class'));\n };\n /**\n * Calls internally if any of the property value is changed.\n * @hidden\n */\n MaskedTextBox.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'value':\n setMaskValue.call(this, this.value);\n if (this.placeholder) {\n this.setMaskPlaceholder(false, false);\n }\n break;\n case 'placeholder':\n this.setMaskPlaceholder(true, true);\n break;\n case 'width':\n this.setWidth(newProp.width);\n break;\n case 'cssClass':\n this.setCssClass(newProp.cssClass, [this.inputObj.container]);\n break;\n case 'enabled':\n Input.setEnabled(newProp.enabled, this.element);\n break;\n case 'enableRtl':\n Input.setEnableRtl(newProp.enableRtl, [this.inputObj.container]);\n break;\n case 'customCharacters':\n this.customCharacters = newProp.customCharacters;\n this.resetMaskedTextBox();\n break;\n case 'showClearButton':\n Input.setClearButton(newProp.showClearButton, this.element, this.inputObj, undefined, this.createElement);\n bindClearEvent.call(this);\n break;\n case 'floatLabelType':\n this.floatLabelType = newProp.floatLabelType;\n Input.removeFloating(this.inputObj);\n Input.addFloating(this.element, this.floatLabelType, this.placeholder, this.createElement);\n break;\n case 'mask':\n var strippedValue_1 = this.value;\n this.mask = newProp.mask;\n this.updateValue(strippedValue_1);\n break;\n case 'promptChar':\n if (newProp.promptChar.length > 1) {\n newProp.promptChar = newProp.promptChar[0];\n }\n if (newProp.promptChar) {\n this.promptChar = newProp.promptChar;\n }\n else {\n this.promptChar = '_';\n }\n var value = this.element.value.replace(new RegExp('[' + oldProp.promptChar + ']', 'g'), this.promptChar);\n if (this.promptMask === this.element.value) {\n value = this.promptMask.replace(new RegExp('[' + oldProp.promptChar + ']', 'g'), this.promptChar);\n }\n this.promptMask = this.promptMask.replace(new RegExp('[' + oldProp.promptChar + ']', 'g'), this.promptChar);\n this.undoCollec = this.redoCollec = [];\n setElementValue.call(this, value);\n break;\n }\n }\n };\n MaskedTextBox.prototype.updateValue = function (strippedVal) {\n this.resetMaskedTextBox();\n setMaskValue.call(this, strippedVal);\n };\n /**\n * Gets the value of the MaskedTextBox with the masked format.\n * By using `value` property, you can get the raw value of maskedtextbox without literals and prompt characters.\n * @return {string}\n */\n MaskedTextBox.prototype.getMaskedValue = function () {\n return unstrippedValue.call(this, this.element);\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers.\n * Also it maintains the initial input element from the DOM.\n * @method destroy\n * @return {void}\n */\n MaskedTextBox.prototype.destroy = function () {\n unwireEvents.call(this);\n this.inputObj.container.parentElement.appendChild(this.cloneElement);\n detach(this.inputObj.container);\n _super.prototype.destroy.call(this);\n };\n __decorate([\n Property(null)\n ], MaskedTextBox.prototype, \"cssClass\", void 0);\n __decorate([\n Property(null)\n ], MaskedTextBox.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], MaskedTextBox.prototype, \"placeholder\", void 0);\n __decorate([\n Property('Never')\n ], MaskedTextBox.prototype, \"floatLabelType\", void 0);\n __decorate([\n Property(true)\n ], MaskedTextBox.prototype, \"enabled\", void 0);\n __decorate([\n Property(false)\n ], MaskedTextBox.prototype, \"showClearButton\", void 0);\n __decorate([\n Property(false)\n ], MaskedTextBox.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(false)\n ], MaskedTextBox.prototype, \"enableRtl\", void 0);\n __decorate([\n Property(null)\n ], MaskedTextBox.prototype, \"mask\", void 0);\n __decorate([\n Property('_')\n ], MaskedTextBox.prototype, \"promptChar\", void 0);\n __decorate([\n Property(null)\n ], MaskedTextBox.prototype, \"value\", void 0);\n __decorate([\n Property(null)\n ], MaskedTextBox.prototype, \"customCharacters\", void 0);\n __decorate([\n Event()\n ], MaskedTextBox.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], MaskedTextBox.prototype, \"destroyed\", void 0);\n __decorate([\n Event()\n ], MaskedTextBox.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], MaskedTextBox.prototype, \"focus\", void 0);\n MaskedTextBox = __decorate([\n NotifyPropertyChanges\n ], MaskedTextBox);\n return MaskedTextBox;\n}(Component));\nexport { MaskedTextBox };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, EventHandler, Property, Event, Complex } from '@syncfusion/ej2-base';\nimport { L10n, Internationalization } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, ChildProperty } from '@syncfusion/ej2-base';\nimport { attributes, addClass, removeClass, setStyleAttribute, detach } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, formatUnit, Browser } from '@syncfusion/ej2-base';\nimport { Tooltip } from '@syncfusion/ej2-popups';\n/**\n * Configures the ticks data of the Slider.\n */\nvar TicksData = /** @class */ (function (_super) {\n __extends(TicksData, _super);\n function TicksData() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('None')\n ], TicksData.prototype, \"placement\", void 0);\n __decorate([\n Property(10)\n ], TicksData.prototype, \"largeStep\", void 0);\n __decorate([\n Property(1)\n ], TicksData.prototype, \"smallStep\", void 0);\n __decorate([\n Property(false)\n ], TicksData.prototype, \"showSmallTicks\", void 0);\n __decorate([\n Property(null)\n ], TicksData.prototype, \"format\", void 0);\n return TicksData;\n}(ChildProperty));\nexport { TicksData };\n/**\n * It illustrates the limit data in slider.\n */\nvar LimitData = /** @class */ (function (_super) {\n __extends(LimitData, _super);\n function LimitData() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], LimitData.prototype, \"enabled\", void 0);\n __decorate([\n Property(null)\n ], LimitData.prototype, \"minStart\", void 0);\n __decorate([\n Property(null)\n ], LimitData.prototype, \"minEnd\", void 0);\n __decorate([\n Property(null)\n ], LimitData.prototype, \"maxStart\", void 0);\n __decorate([\n Property(null)\n ], LimitData.prototype, \"maxEnd\", void 0);\n __decorate([\n Property(false)\n ], LimitData.prototype, \"startHandleFixed\", void 0);\n __decorate([\n Property(false)\n ], LimitData.prototype, \"endHandleFixed\", void 0);\n return LimitData;\n}(ChildProperty));\nexport { LimitData };\n/**\n * It illustrates the tooltip data in slider.\n */\nvar TooltipData = /** @class */ (function (_super) {\n __extends(TooltipData, _super);\n function TooltipData() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], TooltipData.prototype, \"cssClass\", void 0);\n __decorate([\n Property('Before')\n ], TooltipData.prototype, \"placement\", void 0);\n __decorate([\n Property('Focus')\n ], TooltipData.prototype, \"showOn\", void 0);\n __decorate([\n Property(false)\n ], TooltipData.prototype, \"isVisible\", void 0);\n __decorate([\n Property(null)\n ], TooltipData.prototype, \"format\", void 0);\n return TooltipData;\n}(ChildProperty));\nexport { TooltipData };\nvar bootstrapTooltipOffset = 6;\nvar classNames = {\n root: 'e-slider',\n rtl: 'e-rtl',\n sliderHiddenInput: 'e-slider-input',\n controlWrapper: 'e-control-wrapper',\n sliderHandle: 'e-handle',\n rangeBar: 'e-range',\n sliderButton: 'e-slider-button',\n firstButton: 'e-first-button',\n secondButton: 'e-second-button',\n scale: 'e-scale',\n tick: 'e-tick',\n large: 'e-large',\n tickValue: 'e-tick-value',\n sliderTooltip: 'e-slider-tooltip',\n sliderHover: 'e-slider-hover',\n sliderFirstHandle: 'e-handle-first',\n sliderSecondHandle: 'e-handle-second',\n sliderDisabled: 'e-disabled',\n sliderContainer: 'e-slider-container',\n horizontalTooltipBefore: 'e-slider-horizontal-before',\n horizontalTooltipAfter: 'e-slider-horizontal-after',\n verticalTooltipBefore: 'e-slider-vertical-before',\n verticalTooltipAfter: 'e-slider-vertical-after',\n materialTooltip: 'e-material-tooltip',\n materialTooltipOpen: 'e-material-tooltip-open',\n materialTooltipActive: 'e-tooltip-active',\n materialSlider: 'e-material-slider',\n sliderTrack: 'e-slider-track',\n sliderHandleFocused: 'e-handle-focused',\n verticalSlider: 'e-vertical',\n horizontalSlider: 'e-horizontal',\n sliderHandleStart: 'e-handle-start',\n sliderTooltipStart: 'e-material-tooltip-start',\n sliderTabHandle: 'e-tab-handle',\n sliderButtonIcon: 'e-button-icon',\n sliderSmallSize: 'e-small-size',\n sliderTickPosition: 'e-tick-pos',\n sliderFirstTick: 'e-first-tick',\n sliderLastTick: 'e-last-tick',\n sliderButtonClass: 'e-slider-btn',\n sliderTooltipWrapper: 'e-tooltip-wrap',\n sliderTabTrack: 'e-tab-track',\n sliderTabRange: 'e-tab-range',\n sliderActiveHandle: 'e-handle-active',\n sliderMaterialHandle: 'e-material-handle',\n sliderMaterialRange: 'e-material-range',\n sliderMaterialDefault: 'e-material-default',\n materialTooltipShow: 'e-material-tooltip-show',\n materialTooltipHide: 'e-material-tooltip-hide',\n readonly: 'e-read-only',\n limits: 'e-limits',\n limitBarDefault: 'e-limit-bar',\n limitBarFirst: 'e-limit-first',\n limitBarSecond: 'e-limit-second',\n dragHorizontal: 'e-drag-horizontal',\n dragVertical: 'e-drag-vertical'\n};\n/**\n * The Slider component allows the user to select a value or range\n * of values in-between a min and max range, by dragging the handle over the slider bar.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar Slider = /** @class */ (function (_super) {\n __extends(Slider, _super);\n function Slider(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.horDir = 'left';\n _this.verDir = 'bottom';\n _this.transition = {\n handle: 'left .4s cubic-bezier(.25, .8, .25, 1), right .4s cubic-bezier(.25, .8, .25, 1), ' +\n 'top .4s cubic-bezier(.25, .8, .25, 1) , bottom .4s cubic-bezier(.25, .8, .25, 1)',\n rangeBar: 'all .4s cubic-bezier(.25, .8, .25, 1)'\n };\n _this.transitionOnMaterialTooltip = {\n handle: 'left 1ms ease-out, right 1ms ease-out, bottom 1ms ease-out',\n rangeBar: 'left 1ms ease-out, right 1ms ease-out, bottom 1ms ease-out, width 1ms ease-out, height 1ms ease-out'\n };\n _this.scaleTransform = 'transform .4s cubic-bezier(.25, .8, .25, 1)';\n _this.customAriaText = null;\n _this.drag = true;\n return _this;\n }\n Slider.prototype.preRender = function () {\n var localeText = { incrementTitle: 'Increase', decrementTitle: 'Decrease' };\n this.l10n = new L10n('slider', localeText, this.locale);\n this.isElementFocused = false;\n this.tickElementCollection = [];\n this.tooltipFormatInfo = {};\n this.ticksFormatInfo = {};\n this.initCultureInfo();\n this.initCultureFunc();\n };\n Slider.prototype.initCultureFunc = function () {\n this.internationalization = new Internationalization(this.locale);\n };\n Slider.prototype.initCultureInfo = function () {\n this.tooltipFormatInfo.format = (!isNullOrUndefined(this.tooltip.format)) ? this.tooltip.format : null;\n this.ticksFormatInfo.format = (!isNullOrUndefined(this.ticks.format)) ? this.ticks.format : null;\n };\n Slider.prototype.formatString = function (value, formatInfo) {\n var formatValue = null;\n var formatString = null;\n if ((value || value === 0)) {\n formatValue = this.formatNumber(value);\n var numberOfDecimals = this.numberOfDecimals(value);\n formatString = this.internationalization.getNumberFormat(formatInfo)(this.makeRoundNumber(value, numberOfDecimals));\n }\n return { elementVal: formatValue, formatString: formatString };\n };\n ;\n Slider.prototype.formatNumber = function (value) {\n var numberOfDecimals = this.numberOfDecimals(value);\n return this.internationalization.getNumberFormat({\n maximumFractionDigits: numberOfDecimals,\n minimumFractionDigits: numberOfDecimals, useGrouping: false\n })(value);\n };\n ;\n Slider.prototype.numberOfDecimals = function (value) {\n var decimalPart = value.toString().split('.')[1];\n var numberOfDecimals = !decimalPart || !decimalPart.length ? 0 : decimalPart.length;\n return numberOfDecimals;\n };\n Slider.prototype.makeRoundNumber = function (value, precision) {\n var decimals = precision || 0;\n return Number(value.toFixed(decimals));\n };\n ;\n Slider.prototype.fractionalToInteger = function (value) {\n value = (this.numberOfDecimals(value) === 0) ? Number(value).toFixed(this.noOfDecimals) : value;\n var tens = 1;\n for (var i = 0; i < this.noOfDecimals; i++) {\n tens *= 10;\n }\n value = Number((value * tens).toFixed(0));\n return value;\n };\n /**\n * To Initialize the control rendering\n * @private\n */\n Slider.prototype.render = function () {\n this.initialize();\n this.initRender();\n this.wireEvents();\n this.setZindex();\n };\n Slider.prototype.initialize = function () {\n addClass([this.element], classNames.root);\n this.setCSSClass();\n };\n Slider.prototype.setCSSClass = function (oldCSSClass) {\n if (oldCSSClass) {\n removeClass([this.element], oldCSSClass.split(' '));\n }\n if (this.cssClass) {\n addClass([this.element], this.cssClass.split(' '));\n }\n };\n Slider.prototype.setEnabled = function () {\n var tooltipElement = this.type !== 'Range' ? [this.firstTooltipElement] :\n [this.firstTooltipElement, this.secondTooltipElement];\n if (!this.enabled) {\n addClass([this.sliderContainer], [classNames.sliderDisabled]);\n if (this.tooltip.isVisible && this.tooltip.showOn === 'Always') {\n tooltipElement.forEach(function (tooltipElement) {\n tooltipElement.classList.add(classNames.sliderDisabled);\n });\n }\n this.unwireEvents();\n }\n else {\n removeClass([this.sliderContainer], [classNames.sliderDisabled]);\n if (this.tooltip.isVisible && this.tooltip.showOn === 'Always') {\n tooltipElement.forEach(function (tooltipElement) {\n tooltipElement.classList.remove(classNames.sliderDisabled);\n });\n }\n this.wireEvents();\n }\n };\n Slider.prototype.getTheme = function (container) {\n var theme = window.getComputedStyle(container, ':after').getPropertyValue('content');\n return theme.replace(/['\"]+/g, '');\n };\n /**\n * Initialize the rendering\n * @private\n */\n Slider.prototype.initRender = function () {\n this.sliderContainer = this.createElement('div', { className: classNames.sliderContainer + ' ' + classNames.controlWrapper });\n this.element.parentNode.insertBefore(this.sliderContainer, this.element);\n this.sliderContainer.appendChild(this.element);\n this.sliderTrack = this.createElement('div', { className: classNames.sliderTrack });\n this.element.appendChild(this.sliderTrack);\n this.element.tabIndex = -1;\n this.isMaterial = this.getTheme(this.sliderContainer) === 'material';\n this.isBootstrap = this.getTheme(this.sliderContainer) === 'bootstrap';\n this.setHandler();\n this.createRangeBar();\n if (this.limits.enabled) {\n this.createLimitBar();\n }\n this.setOrientClass();\n this.hiddenInput = (this.createElement('input', {\n attrs: {\n type: 'hidden', value: (isNullOrUndefined(this.value) ? this.min.toString() : this.value.toString()),\n name: this.element.getAttribute('name') || this.element.getAttribute('id') ||\n '_' + (Math.random() * 1000).toFixed(0) + 'slider', class: classNames.sliderHiddenInput\n }\n }));\n this.hiddenInput.tabIndex = -1;\n this.sliderContainer.appendChild(this.hiddenInput);\n if (this.showButtons) {\n this.setButtons();\n }\n this.setEnableRTL();\n if (this.type === 'Range') {\n this.rangeValueUpdate();\n }\n else {\n this.value = isNullOrUndefined(this.value) ? parseFloat(formatUnit(this.min.toString())) : this.value;\n }\n this.previousVal = this.type !== 'Range' ? this.checkHandleValue(parseFloat(formatUnit(this.value.toString()))) :\n [this.checkHandleValue(parseFloat(formatUnit(this.value[0].toString()))),\n this.checkHandleValue(parseFloat(formatUnit(this.value[1].toString())))];\n this.previousChanged = this.previousVal;\n if (!isNullOrUndefined(this.element.hasAttribute('name'))) {\n this.element.removeAttribute('name');\n }\n this.setValue();\n if (this.limits.enabled) {\n this.setLimitBar();\n }\n if (this.ticks.placement !== 'None') {\n this.renderScale();\n }\n if (this.tooltip.isVisible) {\n this.renderTooltip();\n }\n if (!this.enabled) {\n addClass([this.sliderContainer], [classNames.sliderDisabled]);\n }\n else {\n removeClass([this.sliderContainer], [classNames.sliderDisabled]);\n }\n if (this.readonly) {\n addClass([this.sliderContainer], [classNames.readonly]);\n }\n else {\n removeClass([this.sliderContainer], [classNames.readonly]);\n }\n };\n Slider.prototype.createRangeBar = function () {\n if (this.type !== 'Default') {\n this.rangeBar = (this.createElement('div', { attrs: { class: classNames.rangeBar } }));\n this.element.appendChild(this.rangeBar);\n if (this.drag && this.type === 'Range') {\n if (this.orientation === 'Horizontal') {\n this.rangeBar.classList.add(classNames.dragHorizontal);\n }\n else {\n this.rangeBar.classList.add(classNames.dragVertical);\n }\n }\n }\n };\n Slider.prototype.createLimitBar = function () {\n var firstElementClassName = this.type !== 'Range' ? classNames.limitBarDefault :\n classNames.limitBarFirst;\n firstElementClassName += ' ' + classNames.limits;\n this.limitBarFirst = (this.createElement('div', {\n attrs: { class: firstElementClassName }\n }));\n this.element.appendChild(this.limitBarFirst);\n if (this.type === 'Range') {\n this.limitBarSecond = (this.createElement('div', {\n attrs: {\n class: classNames.limitBarSecond + ' ' + classNames.limits\n }\n }));\n this.element.appendChild(this.limitBarSecond);\n }\n };\n Slider.prototype.setOrientClass = function () {\n if (this.orientation !== 'Vertical') {\n this.sliderContainer.classList.remove(classNames.verticalSlider);\n this.sliderContainer.classList.add(classNames.horizontalSlider);\n this.firstHandle.setAttribute('aria-orientation', 'horizontal');\n if (this.type === 'Range') {\n this.secondHandle.setAttribute('aria-orientation', 'horizontal');\n }\n }\n else {\n this.sliderContainer.classList.remove(classNames.horizontalSlider);\n this.sliderContainer.classList.add(classNames.verticalSlider);\n this.firstHandle.setAttribute('aria-orientation', 'vertical');\n if (this.type === 'Range') {\n this.secondHandle.setAttribute('aria-orientation', 'vertical');\n }\n }\n };\n Slider.prototype.setAriaAttributes = function (element) {\n var _this = this;\n var min = this.min;\n var max = this.max;\n if (!isNullOrUndefined(this.customValues) && this.customValues.length > 0) {\n min = this.customValues[0];\n max = this.customValues[this.customValues.length - 1];\n }\n if (this.type !== 'Range') {\n attributes(element, {\n 'aria-valuemin': min.toString(), 'aria-valuemax': max.toString()\n });\n }\n else {\n var range = !isNullOrUndefined(this.customValues) && this.customValues.length > 0 ?\n [[min.toString(), (this.customValues[this.value[1]]).toString()],\n [(this.customValues[this.value[0]]).toString(), max.toString()]] :\n [[min.toString(), this.value[1].toString()], [this.value[0].toString(), max.toString()]];\n range.forEach(function (range, index) {\n var element = index === 0 ? _this.firstHandle : _this.secondHandle;\n if (element) {\n attributes(element, {\n 'aria-valuemin': range[0], 'aria-valuemax': range[1]\n });\n }\n });\n }\n };\n Slider.prototype.createSecondHandle = function () {\n this.secondHandle = this.createElement('div', {\n attrs: {\n class: classNames.sliderHandle, 'role': 'slider', 'aria-labelledby': this.element.id + '_title', tabIndex: '0'\n }\n });\n this.secondHandle.classList.add(classNames.sliderSecondHandle);\n this.element.appendChild(this.secondHandle);\n if (this.isMaterial && this.tooltip.isVisible) {\n this.secondMaterialHandle = this.createElement('div', {\n attrs: {\n class: classNames.sliderHandle + ' ' +\n classNames.sliderMaterialHandle\n }\n });\n this.element.appendChild(this.secondMaterialHandle);\n }\n };\n Slider.prototype.createFirstHandle = function () {\n this.firstHandle = this.createElement('div', {\n attrs: {\n class: classNames.sliderHandle, 'role': 'slider', 'aria-labelledby': this.element.id + '_title', tabIndex: '0'\n }\n });\n this.firstHandle.classList.add(classNames.sliderFirstHandle);\n this.element.appendChild(this.firstHandle);\n if (this.isMaterial && this.tooltip.isVisible) {\n this.firstMaterialHandle = this.createElement('div', {\n attrs: {\n class: classNames.sliderHandle + ' ' +\n classNames.sliderMaterialHandle\n }\n });\n this.element.appendChild(this.firstMaterialHandle);\n }\n };\n Slider.prototype.wireFirstHandleEvt = function (destroy) {\n if (!destroy) {\n EventHandler.add(this.firstHandle, 'mousedown touchstart', this.handleFocus, this);\n EventHandler.add(this.firstHandle, 'transitionend', this.transitionEnd, this);\n EventHandler.add(this.firstHandle, 'mouseenter touchenter', this.handleOver, this);\n EventHandler.add(this.firstHandle, 'mouseleave touchend', this.handleLeave, this);\n }\n else {\n EventHandler.remove(this.firstHandle, 'mousedown touchstart', this.handleFocus);\n EventHandler.remove(this.firstHandle, 'transitionend', this.transitionEnd);\n EventHandler.remove(this.firstHandle, 'mouseenter touchenter', this.handleOver);\n EventHandler.remove(this.firstHandle, 'mouseleave touchend', this.handleLeave);\n }\n };\n Slider.prototype.wireSecondHandleEvt = function (destroy) {\n if (!destroy) {\n EventHandler.add(this.secondHandle, 'mousedown touchstart', this.handleFocus, this);\n EventHandler.add(this.secondHandle, 'transitionend', this.transitionEnd, this);\n EventHandler.add(this.secondHandle, 'mouseenter touchenter', this.handleOver, this);\n EventHandler.add(this.secondHandle, 'mouseleave touchend', this.handleLeave, this);\n }\n else {\n EventHandler.remove(this.secondHandle, 'mousedown touchstart', this.handleFocus);\n EventHandler.remove(this.secondHandle, 'transitionend', this.transitionEnd);\n EventHandler.remove(this.secondHandle, 'mouseenter touchenter', this.handleOver);\n EventHandler.remove(this.secondHandle, 'mouseleave touchend', this.handleLeave);\n }\n };\n Slider.prototype.handleStart = function () {\n var pos = (this.activeHandle === 1) ? this.handlePos1 : this.handlePos2;\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n if (pos === 0 && this.type !== 'Range') {\n this.getHandle().classList.add(classNames.sliderHandleStart);\n if (this.isMaterial && this.tooltip.isVisible) {\n this.firstMaterialHandle.classList.add(classNames.sliderHandleStart);\n if (tooltipElement) {\n tooltipElement.classList.add(classNames.sliderTooltipStart);\n }\n }\n }\n };\n Slider.prototype.transitionEnd = function (e) {\n this.handleStart();\n this.getHandle().style.transition = 'none';\n if (this.type !== 'Default') {\n this.rangeBar.style.transition = 'none';\n }\n if (this.tooltip.isVisible) {\n var tooltipObj = this.activeHandle === 1 ? this.firstTooltipObj : this.secondTooltipObj;\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n if (!this.isMaterial) {\n tooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'FadeOut', duration: 500 } };\n this.tooltipAnimation();\n }\n else {\n if (!tooltipElement.classList.contains(classNames.materialTooltipOpen) && e.propertyName !== 'transform') {\n this.openMaterialTooltip();\n }\n else {\n if (this.type === 'Default') {\n tooltipElement.style.transition = this.transition.handle;\n }\n this.refreshTooltip();\n }\n }\n }\n if (this.tooltip.showOn !== 'Always') {\n this.closeTooltip();\n }\n };\n Slider.prototype.handleFocusOut = function () {\n if (this.firstHandle.classList.contains(classNames.sliderHandleFocused)) {\n this.firstHandle.classList.remove(classNames.sliderHandleFocused);\n }\n if (this.type === 'Range') {\n if (this.secondHandle.classList.contains(classNames.sliderHandleFocused)) {\n this.secondHandle.classList.remove(classNames.sliderHandleFocused);\n }\n }\n };\n Slider.prototype.handleFocus = function (e) {\n if (e.currentTarget === this.firstHandle) {\n this.firstHandle.classList.add(classNames.sliderHandleFocused);\n }\n else {\n this.secondHandle.classList.add(classNames.sliderHandleFocused);\n }\n };\n Slider.prototype.handleOver = function (e) {\n if (this.tooltip.isVisible && this.tooltip.showOn === 'Hover') {\n this.tooltipValue();\n var tooltipObj = e.currentTarget === this.firstHandle ? this.firstTooltipObj : this.secondTooltipObj;\n tooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'FadeOut', duration: 500 } };\n if (e.currentTarget === this.firstHandle) {\n this.firstTooltipObj.open(this.firstHandle);\n }\n else {\n this.secondTooltipObj.open(this.secondHandle);\n }\n }\n };\n Slider.prototype.handleLeave = function (e) {\n if (this.tooltip.isVisible && this.tooltip.showOn === 'Hover' &&\n !e.currentTarget.classList.contains(classNames.sliderHandleFocused) &&\n !e.currentTarget.classList.contains(classNames.sliderTabHandle)) {\n this.tooltipValue();\n var tooltipObj = e.currentTarget === this.firstHandle ? this.firstTooltipObj : this.secondTooltipObj;\n if (e.currentTarget === this.firstHandle) {\n this.firstTooltipObj.close();\n }\n else {\n this.secondTooltipObj.close();\n }\n tooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'FadeOut', duration: 500 } };\n }\n };\n Slider.prototype.setHandler = function () {\n if (this.min > this.max) {\n this.min = this.max;\n }\n this.createFirstHandle();\n if (this.type === 'Range') {\n this.createSecondHandle();\n }\n };\n Slider.prototype.setEnableRTL = function () {\n this.enableRtl && this.orientation !== 'Vertical' ? addClass([this.sliderContainer], classNames.rtl) :\n removeClass([this.sliderContainer], classNames.rtl);\n var preDir = (this.orientation !== 'Vertical') ? this.horDir : this.verDir;\n if (this.enableRtl) {\n this.horDir = 'right';\n this.verDir = 'bottom';\n }\n else {\n this.horDir = 'left';\n this.verDir = 'bottom';\n }\n var currDir = (this.orientation !== 'Vertical') ? this.horDir : this.verDir;\n if (preDir !== currDir) {\n if (this.orientation === 'Horizontal') {\n setStyleAttribute(this.firstHandle, { 'right': '', 'left': 'auto' });\n if (this.type === 'Range') {\n setStyleAttribute(this.secondHandle, { 'top': '', 'left': 'auto' });\n }\n }\n }\n };\n Slider.prototype.tooltipValue = function () {\n var text;\n var value1;\n var value2;\n var args = {\n value: this.value,\n text: ''\n };\n this.setTooltipContent();\n args.text = text = this.firstTooltipObj.content;\n this.trigger('tooltipChange', args);\n this.addTooltipClass(args.text);\n if (text !== args.text) {\n this.customAriaText = args.text;\n this.firstTooltipObj.content = args.text;\n this.setAriaAttrValue(this.firstHandle);\n if (this.type === 'Range') {\n this.secondTooltipObj.content = args.text;\n this.setAriaAttrValue(this.secondHandle);\n }\n }\n };\n Slider.prototype.setTooltipContent = function () {\n var content;\n if (this.type === 'Range') {\n content = this.formatContent(this.tooltipFormatInfo, false);\n this.firstTooltipObj.content = content;\n this.secondTooltipObj.content = content;\n }\n else {\n if (!isNullOrUndefined(this.handleVal1)) {\n content = this.formatContent(this.tooltipFormatInfo, false);\n this.firstTooltipObj.content = content;\n }\n }\n };\n Slider.prototype.formatContent = function (formatInfo, ariaContent) {\n var content = '';\n var handle1 = this.handleVal1;\n var handle2 = this.handleVal2;\n if (!isNullOrUndefined(this.customValues) && this.customValues.length > 0) {\n handle1 = this.customValues[this.handleVal1];\n handle2 = this.customValues[this.handleVal2];\n }\n if (!ariaContent) {\n if (this.type === 'Range') {\n if (this.enableRtl && this.orientation !== 'Vertical') {\n content = (!isNullOrUndefined(formatInfo.format)) ? (this.formatString(handle2, formatInfo)\n .formatString + ' - ' + this.formatString(handle1, formatInfo).formatString) :\n (handle2.toString() + ' - ' + handle1.toString());\n }\n else {\n content = (!isNullOrUndefined(formatInfo.format)) ? (this.formatString(handle1, formatInfo)\n .formatString + ' - ' + this.formatString(handle2, formatInfo).formatString) :\n (handle1.toString() + ' - ' + handle2.toString());\n }\n }\n else {\n if (!isNullOrUndefined(handle1)) {\n content = (!isNullOrUndefined(formatInfo.format)) ?\n this.formatString(handle1, formatInfo).formatString : handle1.toString();\n }\n }\n return content;\n }\n else {\n if (this.type === 'Range') {\n if (this.enableRtl && this.orientation !== 'Vertical') {\n content = (!isNullOrUndefined(this.tooltip) && !isNullOrUndefined(this.tooltip.format)) ?\n (this.formatString(handle2, formatInfo).elementVal + ' - ' +\n this.formatString(handle1, formatInfo).elementVal) :\n (handle2.toString() + ' - ' + handle1.toString());\n }\n else {\n content = (!isNullOrUndefined(this.tooltip) && !isNullOrUndefined(this.tooltip.format)) ?\n (this.formatString(handle1, formatInfo).elementVal + ' - ' +\n this.formatString(handle2, formatInfo).elementVal) :\n (handle1.toString() + ' - ' + handle2.toString());\n }\n }\n else {\n if (!isNullOrUndefined(handle1)) {\n content = (!isNullOrUndefined(this.tooltip) && !isNullOrUndefined(this.tooltip.format)) ?\n this.formatString(handle1, formatInfo).elementVal : handle1.toString();\n }\n }\n return content;\n }\n };\n Slider.prototype.addTooltipClass = function (content) {\n var _this = this;\n if (this.isMaterial && this.tooltip.isVisible) {\n var count_1 = content.toString().length;\n var tooltipElement = this.type !== 'Range' ? [this.firstTooltipElement] :\n [this.firstTooltipElement, this.secondTooltipElement];\n tooltipElement.forEach(function (element, index) {\n if (!element) {\n var cssClass = count_1 > 4 ? classNames.sliderMaterialRange : classNames.sliderMaterialDefault;\n !index ? _this.firstTooltipObj.cssClass = classNames.sliderTooltip + ' ' + cssClass :\n _this.secondTooltipObj.cssClass = classNames.sliderTooltip + ' ' + cssClass;\n }\n else {\n if (count_1 > 4) {\n element.classList.remove(classNames.sliderMaterialDefault);\n if (!element.classList.contains(classNames.sliderMaterialRange)) {\n element.classList.add(classNames.sliderMaterialRange);\n element.style.transform = 'scale(1)';\n }\n }\n else {\n element.classList.remove(classNames.sliderMaterialRange);\n if (!element.classList.contains(classNames.sliderMaterialDefault)) {\n element.classList.add(classNames.sliderMaterialDefault);\n element.style.transform = _this.getTooltipTransformProperties(_this.previousTooltipClass).rotate;\n }\n }\n }\n });\n }\n };\n Slider.prototype.tooltipPlacement = function () {\n var tooltipPosition;\n if (this.orientation === 'Horizontal') {\n this.tooltip.placement === 'Before' ? tooltipPosition = 'TopCenter' : tooltipPosition = 'BottomCenter';\n }\n else {\n this.tooltip.placement === 'Before' ? tooltipPosition = 'LeftCenter' : tooltipPosition = 'RightCenter';\n }\n this.firstTooltipObj.position = tooltipPosition;\n if (this.type === 'Range') {\n this.secondTooltipObj.position = tooltipPosition;\n }\n if (this.isMaterial) {\n this.firstTooltipObj.showTipPointer = true;\n this.setProperties({ tooltip: { showOn: 'Always' } }, true);\n this.firstTooltipObj.height = 30;\n if (this.type === 'Range') {\n this.secondTooltipObj.showTipPointer = true;\n this.secondTooltipObj.height = 30;\n }\n }\n };\n Slider.prototype.tooltipBeforeOpen = function (args) {\n var tooltipElement = args.target === this.firstHandle ? this.firstTooltipElement = args.element :\n this.secondTooltipElement = args.element;\n if (this.tooltip.cssClass !== '') {\n addClass([tooltipElement], this.tooltip.cssClass.split(' '));\n }\n args.target.removeAttribute('aria-describedby');\n if (this.isMaterial && this.tooltip.isVisible) {\n var transformProperties = this.getTooltipTransformProperties(this.previousTooltipClass);\n tooltipElement.firstChild.classList.add(classNames.materialTooltipHide);\n this.handleStart();\n if (tooltipElement.firstElementChild.innerText.length > 4) {\n tooltipElement.style.transform = transformProperties.translate + \" scale(0.01)\";\n }\n else {\n tooltipElement.style.transform = transformProperties.translate + \" \" + transformProperties.rotate + \" scale(0.01)\";\n }\n }\n if (this.isBootstrap) {\n switch (this.bootstrapCollisionArgs.collidedPosition) {\n case 'TopCenter':\n this.firstTooltipObj.setProperties({ 'offsetY': -(bootstrapTooltipOffset) }, false);\n if (this.type === 'Range') {\n this.secondTooltipObj.setProperties({ 'offsetY': -(bootstrapTooltipOffset) }, false);\n }\n break;\n case 'BottomCenter':\n this.firstTooltipObj.setProperties({ 'offsetY': bootstrapTooltipOffset }, false);\n if (this.type === 'Range') {\n this.secondTooltipObj.setProperties({ 'offsetY': bootstrapTooltipOffset }, false);\n }\n break;\n case 'LeftCenter':\n this.firstTooltipObj.setProperties({ 'offsetX': -(bootstrapTooltipOffset) }, false);\n if (this.type === 'Range') {\n this.secondTooltipObj.setProperties({ 'offsetX': -(bootstrapTooltipOffset) }, false);\n }\n break;\n case 'RightCenter':\n this.firstTooltipObj.setProperties({ 'offsetX': bootstrapTooltipOffset }, false);\n if (this.type === 'Range') {\n this.secondTooltipObj.setProperties({ 'offsetX': bootstrapTooltipOffset }, false);\n }\n break;\n default:\n break;\n }\n }\n };\n Slider.prototype.wireMaterialTooltipEvent = function (destroy) {\n if (this.isMaterial && this.tooltip.isVisible) {\n if (!destroy) {\n EventHandler.add(this.firstTooltipElement, 'mousedown touchstart', this.sliderDown, this);\n if (this.type === 'Range') {\n EventHandler.add(this.secondTooltipElement, 'mousedown touchstart', this.sliderDown, this);\n }\n }\n else {\n EventHandler.remove(this.firstTooltipElement, 'mousedown touchstart', this.sliderDown);\n if (this.type === 'Range') {\n EventHandler.remove(this.secondTooltipElement, 'mousedown touchstart', this.sliderDown);\n }\n }\n }\n };\n Slider.prototype.tooltipPositionCalculation = function (position) {\n var cssClass;\n switch (position) {\n case 'TopCenter':\n cssClass = classNames.horizontalTooltipBefore;\n break;\n case 'BottomCenter':\n cssClass = classNames.horizontalTooltipAfter;\n break;\n case 'LeftCenter':\n cssClass = classNames.verticalTooltipBefore;\n break;\n case 'RightCenter':\n cssClass = classNames.verticalTooltipAfter;\n break;\n }\n return cssClass;\n };\n Slider.prototype.getTooltipTransformProperties = function (className) {\n if (this.firstTooltipElement) {\n var position = void 0;\n if (this.orientation === 'Horizontal') {\n position = (this.firstTooltipElement.clientHeight + 14) - (this.firstTooltipElement.clientHeight / 2);\n }\n else {\n position = (this.firstTooltipElement.clientWidth + 14) - (this.firstTooltipElement.clientWidth / 2);\n }\n var transformProperties = this.orientation === 'Horizontal' ?\n (className === classNames.horizontalTooltipBefore ? { rotate: 'rotate(45deg)', translate: \"translateY(\" + position + \"px)\" } :\n { rotate: 'rotate(225deg)', translate: \"translateY(\" + -(position) + \"px)\" }) :\n (className === classNames.verticalTooltipBefore ? { rotate: 'rotate(-45deg)', translate: \"translateX(\" + position + \"px)\" } :\n { rotate: 'rotate(-225deg)', translate: \"translateX(\" + (-position) + \"px)\" });\n return transformProperties;\n }\n return undefined;\n };\n Slider.prototype.openMaterialTooltip = function () {\n var _this = this;\n this.refreshTooltip();\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n var handle = this.activeHandle === 1 ? this.firstMaterialHandle : this.secondMaterialHandle;\n if (tooltipElement.firstChild.classList.contains(classNames.materialTooltipHide)) {\n tooltipElement.firstChild.classList.remove(classNames.materialTooltipHide);\n }\n tooltipElement.firstChild.classList.add(classNames.materialTooltipShow);\n this.getHandle().style.cursor = 'default';\n tooltipElement.style.transition = this.scaleTransform;\n tooltipElement.classList.add(classNames.materialTooltipOpen);\n handle.style.transform = 'scale(0)';\n if (tooltipElement.firstElementChild.innerText.length > 4) {\n tooltipElement.style.transform = 'scale(1)';\n }\n else {\n tooltipElement.style.transform = this.getTooltipTransformProperties(this.previousTooltipClass).rotate;\n }\n if (this.type === 'Default') {\n setTimeout(function () { tooltipElement.style.transition = _this.transition.handle; }, 2500);\n }\n else {\n setTimeout(function () { tooltipElement.style.transition = 'none'; }, 2500);\n }\n };\n Slider.prototype.checkTooltipPosition = function (args) {\n var tooltipPosition = args.target === this.firstHandle ? this.firstHandleTooltipPosition :\n this.secondHandleTooltipPosition;\n if (this.isMaterial && (tooltipPosition === undefined || tooltipPosition !== args.collidedPosition)) {\n var tooltipClass = this.tooltipPositionCalculation(args.collidedPosition);\n args.element.classList.remove(this.previousTooltipClass);\n args.element.classList.add(tooltipClass);\n this.previousTooltipClass = tooltipClass;\n if (args.element.style.transform && args.element.classList.contains(classNames.materialTooltipOpen) &&\n args.element.firstElementChild.innerText.length < 4) {\n args.element.style.transform = this.getTooltipTransformProperties(this.previousTooltipClass).rotate;\n }\n if (args.target === this.firstHandle) {\n this.firstHandleTooltipPosition = args.collidedPosition;\n }\n else {\n this.secondHandleTooltipPosition = args.collidedPosition;\n }\n }\n this.bootstrapCollisionArgs = args;\n };\n Slider.prototype.renderTooltip = function () {\n if (this.tooltip.showOn === 'Auto') {\n this.setProperties({ tooltip: { showOn: 'Hover' } }, true);\n }\n var tooltipPointer = this.isBootstrap ? true : false;\n this.firstTooltipObj = new Tooltip({\n showTipPointer: tooltipPointer,\n cssClass: classNames.sliderTooltip,\n animation: { open: { effect: 'None' }, close: { effect: 'None' } },\n opensOn: 'Custom',\n beforeOpen: this.tooltipBeforeOpen.bind(this),\n beforeCollision: this.checkTooltipPosition.bind(this),\n afterClose: this.tooltipAfterClose.bind(this)\n });\n this.firstTooltipObj.appendTo(this.firstHandle);\n if (this.type === 'Range') {\n this.secondTooltipObj = new Tooltip({\n showTipPointer: tooltipPointer,\n cssClass: classNames.sliderTooltip,\n animation: { open: { effect: 'None' }, close: { effect: 'None' } },\n opensOn: 'Custom',\n beforeOpen: this.tooltipBeforeOpen.bind(this),\n beforeCollision: this.checkTooltipPosition.bind(this),\n afterClose: this.tooltipAfterClose.bind(this)\n });\n this.secondTooltipObj.appendTo(this.secondHandle);\n }\n this.tooltipPlacement();\n this.firstHandle.style.transition = 'none';\n if (this.type !== 'Default') {\n this.rangeBar.style.transition = 'none';\n }\n if (this.type === 'Range') {\n this.secondHandle.style.transition = 'none';\n }\n if (this.isMaterial) {\n this.sliderContainer.classList.add(classNames.materialSlider);\n this.tooltipValue();\n this.firstTooltipObj.open(this.firstHandle);\n if (this.type === 'Range') {\n this.secondTooltipObj.open(this.secondHandle);\n }\n }\n };\n Slider.prototype.tooltipAfterClose = function (args) {\n if (args.element === this.firstTooltipElement) {\n this.firstTooltipElement = undefined;\n }\n else {\n this.secondTooltipElement = undefined;\n }\n };\n Slider.prototype.setButtons = function () {\n this.firstBtn = this.createElement('div', { className: classNames.sliderButton + ' ' + classNames.firstButton });\n this.firstBtn.appendChild(this.createElement('span', { className: classNames.sliderButtonIcon }));\n this.firstBtn.tabIndex = -1;\n this.secondBtn = this.createElement('div', { className: classNames.sliderButton + ' ' + classNames.secondButton });\n this.secondBtn.appendChild(this.createElement('span', { className: classNames.sliderButtonIcon }));\n this.secondBtn.tabIndex = -1;\n this.sliderContainer.classList.add(classNames.sliderButtonClass);\n this.sliderContainer.appendChild(this.firstBtn);\n this.sliderContainer.appendChild(this.secondBtn);\n this.sliderContainer.appendChild(this.element);\n this.buttonTitle();\n };\n Slider.prototype.buttonTitle = function () {\n var enabledRTL = this.enableRtl && this.orientation !== 'Vertical';\n this.l10n.setLocale(this.locale);\n var decrementTitle = this.l10n.getConstant('decrementTitle');\n var incrementTitle = this.l10n.getConstant('incrementTitle');\n attributes(enabledRTL ? this.secondBtn : this.firstBtn, { 'aria-label': decrementTitle, title: decrementTitle });\n attributes(enabledRTL ? this.firstBtn : this.secondBtn, { 'aria-label': incrementTitle, title: incrementTitle });\n };\n Slider.prototype.buttonFocusOut = function () {\n if (this.isMaterial) {\n this.getHandle().classList.remove('e-large-thumb-size');\n }\n };\n Slider.prototype.repeatButton = function (args) {\n var buttonElement = args.target.parentElement;\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n if (!tooltipElement && this.tooltip.isVisible) {\n this.openTooltip();\n }\n var hVal = this.handleValueUpdate();\n var enabledRTL = this.enableRtl && this.orientation !== 'Vertical';\n var value;\n if (args.target.parentElement.classList.contains(classNames.firstButton)\n || args.target.classList.contains(classNames.firstButton)) {\n enabledRTL ? (value = this.add(hVal, parseFloat(this.step.toString()), true)) :\n (value = this.add(hVal, parseFloat(this.step.toString()), false));\n }\n else if (args.target.parentElement.classList.contains(classNames.secondButton)\n || (args.target.classList.contains(classNames.secondButton))) {\n enabledRTL ? (value = this.add(hVal, parseFloat(this.step.toString()), false)) :\n (value = this.add(hVal, parseFloat(this.step.toString()), true));\n }\n if (this.limits.enabled) {\n value = this.getLimitCorrectedValues(value);\n }\n if (value >= this.min && value <= this.max) {\n this.changeHandleValue(value);\n this.refreshTooltipOnMove();\n }\n };\n Slider.prototype.repeatHandlerMouse = function (args) {\n args.preventDefault();\n if (args.type === ('mousedown') || args.type === ('touchstart')) {\n this.buttonClick(args);\n this.repeatInterval = setInterval(this.repeatButton.bind(this), 180, args);\n }\n };\n Slider.prototype.materialChange = function () {\n if (!this.getHandle().classList.contains('e-large-thumb-size')) {\n this.getHandle().classList.add('e-large-thumb-size');\n }\n };\n Slider.prototype.repeatHandlerUp = function (e) {\n this.changeEvent('changed');\n if (this.tooltip.isVisible && this.tooltip.showOn !== 'Always' && !this.isMaterial) {\n this.closeTooltip();\n }\n clearInterval(this.repeatInterval);\n this.getHandle().focus();\n };\n Slider.prototype.customTickCounter = function (bigNum) {\n var tickCount = 4;\n if (!isNullOrUndefined(this.customValues) && this.customValues.length > 0) {\n if (bigNum > 4) {\n tickCount = 3;\n }\n if (bigNum > 7) {\n tickCount = 2;\n }\n if (bigNum > 14) {\n tickCount = 1;\n }\n if (bigNum > 28) {\n tickCount = 0;\n }\n }\n return tickCount;\n };\n Slider.prototype.renderScale = function () {\n var orien = this.orientation === 'Vertical' ? 'v' : 'h';\n var spanText;\n this.noOfDecimals = this.numberOfDecimals(this.step);\n this.ul = this.createElement('ul', {\n className: classNames.scale + ' ' + 'e-' + orien + '-scale ' + classNames.tick + '-' + this.ticks.placement.toLowerCase(),\n attrs: { role: 'presentation', tabIndex: '-1', 'aria-hidden': 'true' }\n });\n this.ul.style.zIndex = '-1';\n if (Browser.isAndroid && orien === 'h') {\n this.ul.classList.add(classNames.sliderTickPosition);\n }\n var smallStep = this.ticks.smallStep;\n if (!this.ticks.showSmallTicks) {\n this.ticks.largeStep > 0 ? (smallStep = this.ticks.largeStep) :\n (smallStep = (parseFloat(formatUnit(this.max))) - (parseFloat(formatUnit(this.min))));\n }\n else if (smallStep <= 0) {\n smallStep = parseFloat(formatUnit(this.step));\n }\n var min = this.fractionalToInteger(this.min);\n var max = this.fractionalToInteger(this.max);\n var steps = this.fractionalToInteger(smallStep);\n var bigNum = !isNullOrUndefined(this.customValues) && this.customValues.length > 0 && this.customValues.length - 1;\n var customStep = this.customTickCounter(bigNum);\n var count = !isNullOrUndefined(this.customValues) && this.customValues.length > 0 ?\n (bigNum * customStep) + bigNum : Math.abs((max - min) / steps);\n this.element.appendChild(this.ul);\n var li;\n var start = parseFloat(this.min.toString());\n if (orien === 'v') {\n start = parseFloat(this.max.toString());\n }\n var left = 0;\n var islargeTick;\n var tickWidth = 100 / count;\n if (tickWidth === Infinity) {\n tickWidth = 5;\n }\n for (var i = 0, y = !isNullOrUndefined(this.customValues) && this.customValues.length > 0 ?\n this.customValues.length - 1 : 0, k = 0; i <= count; i++) {\n li = (this.createElement('li', {\n attrs: {\n class: classNames.tick, role: 'presentation', tabIndex: '-1',\n 'aria-hidden': 'true'\n }\n }));\n if (!isNullOrUndefined(this.customValues) && this.customValues.length > 0) {\n islargeTick = i % (customStep + 1) === 0;\n if (islargeTick) {\n if (orien === 'h') {\n start = this.customValues[k];\n k++;\n }\n else {\n start = this.customValues[y];\n y--;\n }\n li.setAttribute('title', start.toString());\n }\n }\n else {\n li.setAttribute('title', start.toString());\n if (this.numberOfDecimals(this.max) === 0 && this.numberOfDecimals(this.min) === 0 &&\n this.numberOfDecimals(this.step) === 0) {\n if (orien === 'h') {\n islargeTick = ((start - parseFloat(this.min.toString())) % this.ticks.largeStep === 0) ? true : false;\n }\n else {\n islargeTick = (Math.abs(start - parseFloat(this.max.toString())) % this.ticks.largeStep === 0) ? true : false;\n }\n }\n else {\n var largestep = this.fractionalToInteger(this.ticks.largeStep);\n var startValue = this.fractionalToInteger(start);\n islargeTick = ((startValue - min) % largestep === 0) ? true : false;\n }\n }\n if (islargeTick) {\n li.classList.add(classNames.large);\n }\n (orien === 'h') ? (li.style.width = tickWidth + '%') : (li.style.height = tickWidth + '%');\n var repeat = islargeTick ? (this.ticks.placement === 'Both' ? 2 : 1) : 0;\n if (islargeTick) {\n for (var j = 0; j < repeat; j++) {\n this.createTick(li, start);\n }\n }\n else if (isNullOrUndefined(this.customValues)) {\n this.formatTicksValue(li, start);\n }\n this.ul.appendChild(li);\n this.tickElementCollection.push(li);\n var decimalPoints = void 0;\n if (isNullOrUndefined(this.customValues)) {\n if (this.numberOfDecimals(smallStep) > this.numberOfDecimals(start)) {\n decimalPoints = this.numberOfDecimals(smallStep);\n }\n else {\n decimalPoints = this.numberOfDecimals(start);\n }\n if (orien === 'h') {\n start = this.makeRoundNumber(start + smallStep, decimalPoints);\n }\n else {\n start = this.makeRoundNumber(start - smallStep, decimalPoints);\n }\n left = this.makeRoundNumber(left + smallStep, decimalPoints);\n }\n }\n this.tickesAlignment(orien, tickWidth);\n };\n Slider.prototype.tickesAlignment = function (orien, tickWidth) {\n this.firstChild = this.ul.firstElementChild;\n this.lastChild = this.ul.lastElementChild;\n this.firstChild.classList.add(classNames.sliderFirstTick);\n this.lastChild.classList.add(classNames.sliderLastTick);\n this.sliderContainer.classList.add(classNames.scale + '-' + this.ticks.placement.toLowerCase());\n if (orien === 'h') {\n this.firstChild.style.width = tickWidth / 2 + '%';\n this.lastChild.style.width = tickWidth / 2 + '%';\n }\n else {\n this.firstChild.style.height = tickWidth / 2 + '%';\n this.lastChild.style.height = tickWidth / 2 + '%';\n }\n var eventArgs = { ticksWrapper: this.ul, tickElements: this.tickElementCollection };\n this.trigger('renderedTicks', eventArgs);\n this.scaleAlignment();\n };\n Slider.prototype.createTick = function (li, start) {\n var span = this.createElement('span', {\n className: classNames.tickValue + ' ' + classNames.tick + '-' + this.ticks.placement.toLowerCase(),\n attrs: { role: 'presentation', tabIndex: '-1', 'aria-hidden': 'true' }\n });\n li.appendChild(span);\n span.innerHTML = isNullOrUndefined(this.customValues) ? this.formatTicksValue(li, start) : start;\n };\n Slider.prototype.formatTicksValue = function (li, start) {\n var tickText = this.formatNumber(start);\n var text = !isNullOrUndefined(this.ticks) && !isNullOrUndefined(this.ticks.format) ?\n this.formatString(start, this.ticksFormatInfo).formatString : tickText;\n var eventArgs = { value: start, text: text, tickElement: li };\n this.trigger('renderingTicks', eventArgs);\n li.setAttribute('title', eventArgs.text.toString());\n return eventArgs.text.toString();\n };\n Slider.prototype.scaleAlignment = function () {\n this.tickValuePosition();\n var smallTick = 12;\n var largeTick = 20;\n var half = largeTick / 2;\n var orien = this.orientation === 'Vertical' ? 'v' : 'h';\n if (this.orientation === 'Vertical') {\n (this.element.getBoundingClientRect().width <= 15) ?\n this.sliderContainer.classList.add(classNames.sliderSmallSize) :\n this.sliderContainer.classList.remove(classNames.sliderSmallSize);\n }\n else {\n (this.element.getBoundingClientRect().height <= 15) ?\n this.sliderContainer.classList.add(classNames.sliderSmallSize) :\n this.sliderContainer.classList.remove(classNames.sliderSmallSize);\n }\n };\n Slider.prototype.tickValuePosition = function () {\n var first = this.firstChild.getBoundingClientRect();\n var firstChild;\n var smallStep = this.ticks.smallStep;\n var count = Math.abs((parseFloat(formatUnit(this.max))) - (parseFloat(formatUnit(this.min)))) / smallStep;\n if (this.firstChild.children.length > 0) {\n firstChild = this.firstChild.children[0].getBoundingClientRect();\n }\n var tickElements = [this.sliderContainer.querySelectorAll('.' + classNames.tick + '.' +\n classNames.large + ' .' + classNames.tickValue)];\n var other;\n if (this.ticks.placement === 'Both') {\n other = [].slice.call(tickElements[0], 2);\n }\n else {\n other = [].slice.call(tickElements[0], 1);\n }\n var tickWidth = this.orientation === 'Vertical' ?\n (first.height * 2) : (first.width * 2);\n for (var i = 0; i < this.firstChild.children.length; i++) {\n if (this.orientation === 'Vertical') {\n this.firstChild.children[i].style.top = -(firstChild.height / 2) + 'px';\n }\n else {\n if (!this.enableRtl) {\n this.firstChild.children[i].style.left = -(firstChild.width / 2) + 'px';\n }\n else {\n this.firstChild.children[i].style.left = (tickWidth -\n this.firstChild.children[i].getBoundingClientRect().width) / 2 + 'px';\n }\n }\n }\n for (var i = 0; i < other.length; i++) {\n var otherChild = other[i].getBoundingClientRect();\n if (this.orientation === 'Vertical') {\n setStyleAttribute(other[i], { top: (tickWidth - otherChild.height) / 2 + 'px' });\n }\n else {\n setStyleAttribute(other[i], { left: (tickWidth - otherChild.width) / 2 + 'px' });\n }\n }\n if (this.enableRtl && this.lastChild.children.length && count !== 0) {\n this.lastChild.children[0].style.left = -(this.lastChild.getBoundingClientRect().width / 2) + 'px';\n if (this.ticks.placement === 'Both') {\n this.lastChild.children[1].style.left = -(this.lastChild.getBoundingClientRect().width / 2) + 'px';\n }\n }\n if (count === 0) {\n if (this.orientation === 'Horizontal') {\n if (!this.enableRtl) {\n this.firstChild.classList.remove(classNames.sliderLastTick);\n this.firstChild.style.left = this.firstHandle.style.left;\n }\n else {\n this.firstChild.classList.remove(classNames.sliderLastTick);\n this.firstChild.style.right = this.firstHandle.style.right;\n this.firstChild.children[0].style.left =\n (this.firstChild.getBoundingClientRect().width / 2) + 2 + 'px';\n if (this.ticks.placement === 'Both') {\n this.firstChild.children[1].style.left =\n (this.firstChild.getBoundingClientRect().width / 2) + 2 + 'px';\n }\n }\n }\n if (this.orientation === 'Vertical') {\n this.firstChild.classList.remove(classNames.sliderLastTick);\n }\n }\n };\n Slider.prototype.setAriaAttrValue = function (element) {\n var ariaValueText;\n var isTickFormatted = ((!isNullOrUndefined(this.ticks) && !isNullOrUndefined(this.ticks.format))) ? true : false;\n var text = !isTickFormatted ?\n this.formatContent(this.ticksFormatInfo, false) : this.formatContent(this.tooltipFormatInfo, false);\n var valuenow = isTickFormatted ? this.formatContent(this.ticksFormatInfo, true) :\n this.formatContent(this.tooltipFormatInfo, true);\n text = (!this.customAriaText) ? (text) : (this.customAriaText);\n if (text.split(' - ').length === 2) {\n ariaValueText = text.split(' - ');\n }\n else {\n ariaValueText = [text, text];\n }\n this.setAriaAttributes(element);\n if (this.type !== 'Range') {\n attributes(element, { 'aria-valuenow': valuenow, 'aria-valuetext': text });\n }\n else {\n (!this.enableRtl) ? ((element === this.firstHandle) ?\n attributes(element, { 'aria-valuenow': valuenow.split(' - ')[0], 'aria-valuetext': ariaValueText[0] }) :\n attributes(element, { 'aria-valuenow': valuenow.split(' - ')[1], 'aria-valuetext': ariaValueText[1] })) :\n ((element === this.firstHandle) ?\n attributes(element, { 'aria-valuenow': valuenow.split(' - ')[1], 'aria-valuetext': ariaValueText[1] }) :\n attributes(element, { 'aria-valuenow': valuenow.split(' - ')[0], 'aria-valuetext': ariaValueText[0] }));\n }\n };\n Slider.prototype.handleValueUpdate = function () {\n var hVal;\n if (this.type === 'Range') {\n if (this.activeHandle === 1) {\n hVal = this.handleVal1;\n }\n else {\n hVal = this.handleVal2;\n }\n }\n else {\n hVal = this.handleVal1;\n }\n return hVal;\n };\n Slider.prototype.getLimitCorrectedValues = function (value) {\n if (this.type === 'MinRange' || this.type === 'Default') {\n value = (this.getLimitValueAndPosition(value, this.limits.minStart, this.limits.minEnd))[0];\n }\n else {\n if (this.activeHandle === 1) {\n value = (this.getLimitValueAndPosition(value, this.limits.minStart, this.limits.minEnd))[0];\n }\n else {\n value = (this.getLimitValueAndPosition(value, this.limits.maxStart, this.limits.maxEnd))[0];\n }\n }\n return value;\n };\n Slider.prototype.focusSliderElement = function () {\n if (!this.isElementFocused) {\n this.element.focus();\n this.isElementFocused = true;\n }\n };\n Slider.prototype.buttonClick = function (args) {\n this.focusSliderElement();\n var value;\n var enabledRTL = this.enableRtl && this.orientation !== 'Vertical';\n var hVal = this.handleValueUpdate();\n if ((args.keyCode === 40) || (args.keyCode === 37)\n || args.currentTarget.classList.contains(classNames.firstButton)) {\n enabledRTL ? (value = this.add(hVal, parseFloat(this.step.toString()), true)) :\n (value = this.add(hVal, parseFloat(this.step.toString()), false));\n }\n else if ((args.keyCode === 38) || (args.keyCode === 39) ||\n args.currentTarget.classList.contains(classNames.secondButton)) {\n enabledRTL ? (value = this.add(hVal, parseFloat(this.step.toString()), false)) :\n (value = this.add(hVal, parseFloat(this.step.toString()), true));\n }\n else if ((args.keyCode === 33\n || args.currentTarget.classList.contains(classNames.firstButton))) {\n enabledRTL ? (value = this.add(hVal, parseFloat(this.ticks.largeStep.toString()), false)) :\n (value = this.add(hVal, parseFloat(this.ticks.largeStep.toString()), true));\n }\n else if ((args.keyCode === 34) ||\n args.currentTarget.classList.contains(classNames.secondButton)) {\n enabledRTL ? (value = this.add(hVal, parseFloat(this.ticks.largeStep.toString()), true)) :\n (value = this.add(hVal, parseFloat(this.ticks.largeStep.toString()), false));\n }\n else if ((args.keyCode === 36)) {\n value = parseFloat(this.min.toString());\n }\n else if ((args.keyCode === 35)) {\n value = parseFloat(this.max.toString());\n }\n if (this.limits.enabled) {\n value = this.getLimitCorrectedValues(value);\n }\n this.changeHandleValue(value);\n if (this.isMaterial && !this.tooltip.isVisible &&\n !this.getHandle().classList.contains(classNames.sliderTabHandle)) {\n this.materialChange();\n }\n this.tooltipAnimation();\n this.getHandle().focus();\n if (args.currentTarget.classList.contains(classNames.firstButton)) {\n EventHandler.add(this.firstBtn, 'mouseup touchend', this.buttonUp, this);\n }\n if (args.currentTarget.classList.contains(classNames.secondButton)) {\n EventHandler.add(this.secondBtn, 'mouseup touchend', this.buttonUp, this);\n }\n };\n Slider.prototype.tooltipAnimation = function () {\n if (this.tooltip.isVisible) {\n var tooltipObj = this.activeHandle === 1 ? this.firstTooltipObj : this.secondTooltipObj;\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n if (this.isMaterial) {\n !tooltipElement.classList.contains(classNames.materialTooltipOpen) ? this.openMaterialTooltip() : this.refreshTooltip();\n }\n else {\n tooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'FadeOut', duration: 500 } };\n this.openTooltip();\n }\n }\n };\n Slider.prototype.buttonUp = function (args) {\n if (this.tooltip.isVisible) {\n if (!this.isMaterial) {\n var tooltipObj = this.activeHandle === 1 ? this.firstTooltipObj : this.secondTooltipObj;\n tooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'None' } };\n }\n }\n if (args.currentTarget.classList.contains(classNames.firstButton)) {\n EventHandler.remove(this.firstBtn, 'mouseup touchend', this.buttonUp);\n }\n if (args.currentTarget.classList.contains(classNames.secondButton)) {\n EventHandler.remove(this.secondBtn, 'mouseup touchend', this.buttonUp);\n }\n };\n Slider.prototype.setRangeBar = function () {\n if (this.orientation === 'Horizontal') {\n if (this.type === 'MinRange') {\n this.enableRtl ? (this.rangeBar.style.right = '0px') : (this.rangeBar.style.left = '0px');\n setStyleAttribute(this.rangeBar, { 'width': isNullOrUndefined(this.handlePos1) ? 0 : this.handlePos1 + 'px' });\n }\n else {\n this.enableRtl ? (this.rangeBar.style.right =\n this.handlePos1 + 'px') : (this.rangeBar.style.left = this.handlePos1 + 'px');\n setStyleAttribute(this.rangeBar, { 'width': this.handlePos2 - this.handlePos1 + 'px' });\n }\n }\n else {\n if (this.type === 'MinRange') {\n this.rangeBar.style.bottom = '0px';\n setStyleAttribute(this.rangeBar, { 'height': isNullOrUndefined(this.handlePos1) ? 0 : this.handlePos1 + 'px' });\n }\n else {\n this.rangeBar.style.bottom = this.handlePos1 + 'px';\n setStyleAttribute(this.rangeBar, { 'height': this.handlePos2 - this.handlePos1 + 'px' });\n }\n }\n };\n Slider.prototype.checkValidValueAndPos = function (value) {\n value = this.checkHandleValue(value);\n value = this.checkHandlePosition(value);\n return value;\n };\n Slider.prototype.setLimitBarPositions = function (fromMinPostion, fromMaxpostion, toMinPostion, toMaxpostion) {\n if (this.orientation === 'Horizontal') {\n if (!this.enableRtl) {\n this.limitBarFirst.style.left = fromMinPostion + 'px';\n this.limitBarFirst.style.width = (fromMaxpostion - fromMinPostion) + 'px';\n }\n else {\n this.limitBarFirst.style.right = fromMinPostion + 'px';\n this.limitBarFirst.style.width = (fromMaxpostion - fromMinPostion) + 'px';\n }\n }\n else {\n this.limitBarFirst.style.bottom = fromMinPostion + 'px';\n this.limitBarFirst.style.height = (fromMaxpostion - fromMinPostion) + 'px';\n }\n if (this.type === 'Range') {\n if (this.orientation === 'Horizontal') {\n if (!this.enableRtl) {\n this.limitBarSecond.style.left = toMinPostion + 'px';\n this.limitBarSecond.style.width = (toMaxpostion - toMinPostion) + 'px';\n }\n else {\n this.limitBarSecond.style.right = toMinPostion + 'px';\n this.limitBarSecond.style.width = (toMaxpostion - toMinPostion) + 'px';\n }\n }\n else {\n this.limitBarSecond.style.bottom = toMinPostion + 'px';\n this.limitBarSecond.style.height = (toMaxpostion - toMinPostion) + 'px';\n }\n }\n };\n Slider.prototype.setLimitBar = function () {\n if (this.type === 'Default' || this.type === 'MinRange') {\n var fromPosition = (this.getLimitValueAndPosition(this.limits.minStart, this.limits.minStart, this.limits.minEnd, true))[0];\n fromPosition = this.checkValidValueAndPos(fromPosition);\n var toPosition = (this.getLimitValueAndPosition(this.limits.minEnd, this.limits.minStart, this.limits.minEnd, true))[0];\n toPosition = this.checkValidValueAndPos(toPosition);\n this.setLimitBarPositions(fromPosition, toPosition);\n }\n else if (this.type === 'Range') {\n var fromMinPostion = (this.getLimitValueAndPosition(this.limits.minStart, this.limits.minStart, this.limits.minEnd, true))[0];\n fromMinPostion = this.checkValidValueAndPos(fromMinPostion);\n var fromMaxpostion = (this.getLimitValueAndPosition(this.limits.minEnd, this.limits.minStart, this.limits.minEnd, true))[0];\n fromMaxpostion = this.checkValidValueAndPos(fromMaxpostion);\n var toMinPostion = (this.getLimitValueAndPosition(this.limits.maxStart, this.limits.maxStart, this.limits.maxEnd, true))[0];\n toMinPostion = this.checkValidValueAndPos(toMinPostion);\n var toMaxpostion = (this.getLimitValueAndPosition(this.limits.maxEnd, this.limits.maxStart, this.limits.maxEnd, true))[0];\n toMaxpostion = this.checkValidValueAndPos(toMaxpostion);\n this.setLimitBarPositions(fromMinPostion, fromMaxpostion, toMinPostion, toMaxpostion);\n }\n };\n Slider.prototype.getLimitValueAndPosition = function (currentValue, minValue, maxValue, limitBar) {\n if (isNullOrUndefined(minValue)) {\n minValue = this.min;\n if (isNullOrUndefined(currentValue) && limitBar) {\n currentValue = minValue;\n }\n }\n if (isNullOrUndefined(maxValue)) {\n maxValue = this.max;\n if (isNullOrUndefined(currentValue) && limitBar) {\n currentValue = maxValue;\n }\n }\n if (currentValue < minValue) {\n currentValue = minValue;\n }\n if (currentValue > maxValue) {\n currentValue = maxValue;\n }\n return [currentValue, this.checkHandlePosition(currentValue)];\n };\n Slider.prototype.setValue = function () {\n if (!isNullOrUndefined(this.customValues) && this.customValues.length > 0) {\n this.min = 0;\n this.max = this.customValues.length - 1;\n }\n this.setAriaAttributes(this.firstHandle);\n this.handleVal1 = isNullOrUndefined(this.value) ? this.checkHandleValue(parseFloat(this.min.toString())) :\n this.checkHandleValue(parseFloat(this.value.toString()));\n this.handlePos1 = this.checkHandlePosition(this.handleVal1);\n this.preHandlePos1 = this.handlePos1;\n isNullOrUndefined(this.activeHandle) ? (this.type === 'Range' ? this.activeHandle = 2 : this.activeHandle = 1) :\n this.activeHandle = this.activeHandle;\n if (this.type === 'Default' || this.type === 'MinRange') {\n if (this.limits.enabled) {\n var values = this.getLimitValueAndPosition(this.handleVal1, this.limits.minStart, this.limits.minEnd);\n this.handleVal1 = values[0];\n this.handlePos1 = values[1];\n this.preHandlePos1 = this.handlePos1;\n }\n this.setHandlePosition();\n this.handleStart();\n this.value = this.handleVal1;\n this.setAriaAttrValue(this.firstHandle);\n this.changeEvent('changed');\n }\n else {\n this.validateRangeValue();\n }\n if (this.type !== 'Default') {\n this.setRangeBar();\n }\n if (this.limits.enabled) {\n this.setLimitBar();\n }\n };\n Slider.prototype.rangeValueUpdate = function () {\n if (this.value === null || typeof (this.value) !== 'object') {\n this.value = [parseFloat(formatUnit(this.min)), parseFloat(formatUnit(this.max))];\n }\n };\n Slider.prototype.validateRangeValue = function () {\n this.rangeValueUpdate();\n this.setRangeValue();\n };\n Slider.prototype.modifyZindex = function () {\n if (this.type === 'Range') {\n if (this.activeHandle === 1) {\n this.firstHandle.style.zIndex = (this.zIndex + 4) + '';\n this.secondHandle.style.zIndex = (this.zIndex + 3) + '';\n if (this.isMaterial && this.tooltip.isVisible && this.firstTooltipElement && this.secondTooltipElement) {\n this.firstTooltipElement.style.zIndex = (this.zIndex + 4) + '';\n this.secondTooltipElement.style.zIndex = (this.zIndex + 3) + '';\n }\n }\n else {\n this.firstHandle.style.zIndex = (this.zIndex + 3) + '';\n this.secondHandle.style.zIndex = (this.zIndex + 4) + '';\n if (this.isMaterial && this.tooltip.isVisible && this.firstTooltipElement && this.secondTooltipElement) {\n this.firstTooltipElement.style.zIndex = (this.zIndex + 3) + '';\n this.secondTooltipElement.style.zIndex = (this.zIndex + 4) + '';\n }\n }\n }\n else if (this.isMaterial && this.tooltip.isVisible && this.firstTooltipElement) {\n this.firstTooltipElement.style.zIndex = (this.zIndex + 4) + '';\n }\n };\n Slider.prototype.setHandlePosition = function () {\n var _this = this;\n var pos = (this.activeHandle === 1) ? this.handlePos1 : this.handlePos2;\n var val = (this.activeHandle === 1) ? this.handleVal1 : this.handleVal2;\n var handle;\n var tooltipElement;\n if (this.isMaterial && this.tooltip.isVisible) {\n tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n handle = [this.getHandle(), (this.activeHandle === 1 ? this.firstMaterialHandle : this.secondMaterialHandle)];\n }\n else {\n handle = [this.getHandle()];\n }\n if (this.tooltip.isVisible && pos === 0 && this.type !== 'Range') {\n handle[0].classList.add(classNames.sliderHandleStart);\n if (this.isMaterial) {\n handle[1].classList.add(classNames.sliderHandleStart);\n if (tooltipElement) {\n tooltipElement.classList.add(classNames.sliderTooltipStart);\n }\n }\n }\n else {\n handle[0].classList.remove(classNames.sliderHandleStart);\n if (this.tooltip.isVisible && this.isMaterial) {\n handle[1].classList.remove(classNames.sliderHandleStart);\n if (tooltipElement) {\n tooltipElement.classList.remove(classNames.sliderTooltipStart);\n }\n }\n }\n handle.forEach(function (handle) {\n if (_this.orientation === 'Horizontal') {\n _this.enableRtl ? (handle.style.right =\n pos + \"px\") : (handle.style.left = pos + \"px\");\n }\n else {\n handle.style.bottom = pos + \"px\";\n }\n });\n this.changeEvent('change');\n };\n Slider.prototype.getHandle = function () {\n return (this.activeHandle === 1) ? this.firstHandle : this.secondHandle;\n };\n Slider.prototype.setRangeValue = function () {\n var temp = this.activeHandle;\n this.updateRangeValue();\n this.activeHandle = 1;\n this.setHandlePosition();\n this.activeHandle = 2;\n this.setHandlePosition();\n this.activeHandle = 1;\n };\n Slider.prototype.changeEvent = function (eventName) {\n var previous = eventName === 'change' ? this.previousVal : this.previousChanged;\n if (this.type !== 'Range') {\n this.setProperties({ 'value': this.handleVal1 }, true);\n if (previous !== this.value) {\n this.trigger(eventName, this.changeEventArgs(eventName));\n this.setPreviousVal(eventName, this.value);\n }\n this.setAriaAttrValue(this.firstHandle);\n }\n else {\n var value = this.value = [this.handleVal1, this.handleVal2];\n this.setProperties({ 'value': value }, true);\n if (previous.length === this.value.length\n && this.value[0] !== previous[0] || this.value[1] !== previous[1]) {\n this.trigger(eventName, this.changeEventArgs(eventName));\n this.setPreviousVal(eventName, this.value);\n }\n this.setAriaAttrValue(this.getHandle());\n }\n this.hiddenInput.value = this.value.toString();\n };\n Slider.prototype.changeEventArgs = function (eventName) {\n var eventArgs;\n if (this.tooltip.isVisible && this.firstTooltipObj) {\n this.tooltipValue();\n eventArgs = {\n value: this.value,\n previousValue: eventName === 'change' ? this.previousVal : this.previousChanged,\n action: eventName, text: this.firstTooltipObj.content\n };\n }\n else {\n eventArgs = {\n value: this.value,\n previousValue: eventName === 'change' ? this.previousVal : this.previousChanged,\n action: eventName, text: isNullOrUndefined(this.ticksFormatInfo.format) ? this.value.toString() :\n (this.type !== 'Range' ? this.formatString(this.value, this.ticksFormatInfo).formatString :\n (this.formatString(this.value[0], this.ticksFormatInfo).formatString + ' - ' +\n this.formatString(this.value[1], this.ticksFormatInfo).formatString))\n };\n }\n return eventArgs;\n };\n Slider.prototype.setPreviousVal = function (eventName, value) {\n if (eventName === 'change') {\n this.previousVal = value;\n }\n else {\n this.previousChanged = value;\n }\n };\n Slider.prototype.updateRangeValue = function () {\n var values = this.value.toString().split(',').map(Number);\n if ((this.enableRtl && this.orientation !== 'Vertical') || this.rtl) {\n this.value = [values[1], values[0]];\n }\n else {\n this.value = [values[0], values[1]];\n }\n if (this.enableRtl && this.orientation !== 'Vertical') {\n this.handleVal1 = this.checkHandleValue(this.value[1]);\n this.handleVal2 = this.checkHandleValue(this.value[0]);\n }\n else {\n this.handleVal1 = this.checkHandleValue(this.value[0]);\n this.handleVal2 = this.checkHandleValue(this.value[1]);\n }\n this.handlePos1 = this.checkHandlePosition(this.handleVal1);\n this.handlePos2 = this.checkHandlePosition(this.handleVal2);\n if (this.handlePos1 > this.handlePos2) {\n this.handlePos1 = this.handlePos2;\n this.handleVal1 = this.handleVal2;\n }\n this.preHandlePos1 = this.handlePos1;\n this.preHandlePos2 = this.handlePos2;\n if (this.limits.enabled) {\n this.activeHandle = 1;\n var values_1 = this.getLimitValueAndPosition(this.handleVal1, this.limits.minStart, this.limits.minEnd);\n this.handleVal1 = values_1[0];\n this.handlePos1 = values_1[1];\n this.preHandlePos1 = this.handlePos1;\n this.activeHandle = 2;\n values_1 = this.getLimitValueAndPosition(this.handleVal2, this.limits.maxStart, this.limits.maxEnd);\n this.handleVal2 = values_1[0];\n this.handlePos2 = values_1[1];\n this.preHandlePos2 = this.handlePos2;\n }\n };\n Slider.prototype.checkHandlePosition = function (value) {\n var pos;\n value = (100 *\n (value - (parseFloat(formatUnit(this.min))))) / ((parseFloat(formatUnit(this.max))) - (parseFloat(formatUnit(this.min))));\n if (this.orientation === 'Horizontal') {\n pos = this.element.getBoundingClientRect().width * (value / 100);\n }\n else {\n pos = this.element.getBoundingClientRect().height * (value / 100);\n }\n if (((parseFloat(formatUnit(this.max))) === (parseFloat(formatUnit(this.min))))) {\n if (this.orientation === 'Horizontal') {\n pos = this.element.getBoundingClientRect().width;\n }\n else {\n pos = this.element.getBoundingClientRect().height;\n }\n }\n return pos;\n };\n Slider.prototype.checkHandleValue = function (value) {\n if (this.min > this.max) {\n this.min = this.max;\n }\n if (this.min === this.max) {\n return (parseFloat(formatUnit(this.max)));\n }\n var handle = this.tempStartEnd();\n if (value < handle.start) {\n value = handle.start;\n }\n else if (value > handle.end) {\n value = handle.end;\n }\n return value;\n };\n Slider.prototype.onResize = function () {\n var _this = this;\n this.firstHandle.style.transition = 'none';\n if (this.type !== 'Default') {\n this.rangeBar.style.transition = 'none';\n }\n if (this.type === 'Range') {\n this.secondHandle.style.transition = 'none';\n }\n this.handlePos1 = this.checkHandlePosition(this.handleVal1);\n if (this.handleVal2) {\n this.handlePos2 = this.checkHandlePosition(this.handleVal2);\n }\n if (this.orientation === 'Horizontal') {\n this.enableRtl ? this.firstHandle.style.right =\n this.handlePos1 + \"px\" : this.firstHandle.style.left = this.handlePos1 + \"px\";\n if (this.isMaterial && this.tooltip.isVisible && this.firstMaterialHandle) {\n this.enableRtl ? this.firstMaterialHandle.style.right =\n this.handlePos1 + \"px\" : this.firstMaterialHandle.style.left = this.handlePos1 + \"px\";\n }\n if (this.type === 'MinRange') {\n this.enableRtl ? (this.rangeBar.style.right = '0px') : (this.rangeBar.style.left = '0px');\n setStyleAttribute(this.rangeBar, { 'width': isNullOrUndefined(this.handlePos1) ? 0 : this.handlePos1 + 'px' });\n }\n else if (this.type === 'Range') {\n this.enableRtl ? this.secondHandle.style.right =\n this.handlePos2 + \"px\" : this.secondHandle.style.left = this.handlePos2 + \"px\";\n if (this.isMaterial && this.tooltip.isVisible && this.secondMaterialHandle) {\n this.enableRtl ? this.secondMaterialHandle.style.right =\n this.handlePos2 + \"px\" : this.secondMaterialHandle.style.left = this.handlePos2 + \"px\";\n }\n this.enableRtl ? (this.rangeBar.style.right =\n this.handlePos1 + 'px') : (this.rangeBar.style.left = this.handlePos1 + 'px');\n setStyleAttribute(this.rangeBar, { 'width': this.handlePos2 - this.handlePos1 + 'px' });\n }\n }\n else {\n this.firstHandle.style.bottom = this.handlePos1 + \"px\";\n if (this.isMaterial && this.tooltip.isVisible && this.firstMaterialHandle) {\n this.firstMaterialHandle.style.bottom = this.handlePos1 + \"px\";\n }\n if (this.type === 'MinRange') {\n this.rangeBar.style.bottom = '0px';\n setStyleAttribute(this.rangeBar, { 'height': isNullOrUndefined(this.handlePos1) ? 0 : this.handlePos1 + 'px' });\n }\n else if (this.type === 'Range') {\n this.secondHandle.style.bottom = this.handlePos2 + \"px\";\n if (this.isMaterial && this.tooltip.isVisible && this.secondMaterialHandle) {\n this.secondMaterialHandle.style.bottom = this.handlePos2 + \"px\";\n }\n this.rangeBar.style.bottom = this.handlePos1 + 'px';\n setStyleAttribute(this.rangeBar, { 'height': this.handlePos2 - this.handlePos1 + 'px' });\n }\n }\n if (this.limits.enabled) {\n this.setLimitBar();\n }\n if (this.ticks.placement !== 'None' && this.ul) {\n this.removeElement(this.ul);\n this.renderScale();\n }\n if (!this.tooltip.isVisible) {\n setTimeout(function () {\n _this.firstHandle.style.transition = _this.scaleTransform;\n if (_this.type === 'Range') {\n _this.secondHandle.style.transition = _this.scaleTransform;\n }\n });\n }\n this.refreshTooltip();\n };\n Slider.prototype.changeHandleValue = function (value) {\n var position = null;\n if (this.activeHandle === 1) {\n if (!(this.limits.enabled && this.limits.startHandleFixed)) {\n this.handleVal1 = this.checkHandleValue(value);\n this.handlePos1 = this.checkHandlePosition(this.handleVal1);\n if (this.type === 'Range' && this.handlePos1 > this.handlePos2) {\n this.handlePos1 = this.handlePos2;\n this.handleVal1 = this.handleVal2;\n }\n if (this.handlePos1 !== this.preHandlePos1) {\n position = this.preHandlePos1 = this.handlePos1;\n }\n }\n this.modifyZindex();\n }\n else {\n if (!(this.limits.enabled && this.limits.endHandleFixed)) {\n this.handleVal2 = this.checkHandleValue(value);\n this.handlePos2 = this.checkHandlePosition(this.handleVal2);\n if (this.type === 'Range' && this.handlePos2 < this.handlePos1) {\n this.handlePos2 = this.handlePos1;\n this.handleVal2 = this.handleVal1;\n }\n if (this.handlePos2 !== this.preHandlePos2) {\n position = this.preHandlePos2 = this.handlePos2;\n }\n }\n this.modifyZindex();\n }\n if (position !== null) {\n if (this.type !== 'Default') {\n this.setRangeBar();\n }\n this.setHandlePosition();\n }\n };\n Slider.prototype.tempStartEnd = function () {\n if (this.min > this.max) {\n return {\n start: this.max,\n end: this.min\n };\n }\n else {\n return {\n start: this.min,\n end: this.max\n };\n }\n };\n Slider.prototype.xyToPosition = function (position) {\n var pos;\n if (this.min === this.max) {\n return 100;\n }\n if (this.orientation === 'Horizontal') {\n var left = position.x - this.element.getBoundingClientRect().left;\n var num = this.element.offsetWidth / 100;\n this.val = (left / num);\n }\n else {\n var top_1 = position.y - this.element.getBoundingClientRect().top;\n var num = this.element.offsetHeight / 100;\n this.val = 100 - (top_1 / num);\n }\n var val = this.stepValueCalculation(this.val);\n if (val < 0) {\n val = 0;\n }\n else if (val > 100) {\n val = 100;\n }\n if (this.enableRtl && this.orientation !== 'Vertical') {\n val = 100 - val;\n }\n if (this.orientation === 'Horizontal') {\n pos = this.element.getBoundingClientRect().width * (val / 100);\n }\n else {\n pos = this.element.getBoundingClientRect().height * (val / 100);\n }\n return pos;\n };\n Slider.prototype.stepValueCalculation = function (value) {\n if (this.step === 0) {\n this.step = 1;\n }\n var percentStep = (parseFloat(formatUnit(this.step))) / ((parseFloat(formatUnit(this.max)) - parseFloat(formatUnit(this.min))) / 100);\n var remain = value % Math.abs(percentStep);\n if (remain !== 0) {\n if ((percentStep / 2) > remain) {\n value -= remain;\n }\n else {\n value += Math.abs(percentStep) - remain;\n }\n }\n return value;\n };\n Slider.prototype.add = function (a, b, addition) {\n var precision;\n var x = Math.pow(10, precision || 3);\n var val;\n if (addition) {\n val = (Math.round(a * x) + Math.round(b * x)) / x;\n }\n else {\n val = (Math.round(a * x) - Math.round(b * x)) / x;\n }\n return val;\n };\n Slider.prototype.round = function (a) {\n var f = this.step.toString().split('.');\n return f[1] ? parseFloat(a.toFixed(f[1].length)) : Math.round(a);\n };\n Slider.prototype.positionToValue = function (pos) {\n var val;\n var diff = parseFloat(formatUnit(this.max)) - parseFloat(formatUnit(this.min));\n if (this.orientation === 'Horizontal') {\n val = (pos / this.element.getBoundingClientRect().width) * diff;\n }\n else {\n val = (pos / this.element.getBoundingClientRect().height) * diff;\n }\n var total = this.add(val, parseFloat(this.min.toString()), true);\n return (total);\n };\n Slider.prototype.sliderBarClick = function (evt) {\n evt.preventDefault();\n var pos;\n if (evt.type === 'mousedown' || evt.type === 'click') {\n pos = { x: evt.clientX, y: evt.clientY };\n }\n else if (evt.type === 'touchstart') {\n pos = { x: evt.changedTouches[0].clientX, y: evt.changedTouches[0].clientY };\n }\n var handlepos = this.xyToPosition(pos);\n var handleVal = this.positionToValue(handlepos);\n if (this.type === 'Range' && (this.handlePos2 - handlepos) < (handlepos - this.handlePos1)) {\n this.activeHandle = 2;\n if (!(this.limits.enabled && this.limits.endHandleFixed)) {\n if (this.limits.enabled) {\n var value = this.getLimitValueAndPosition(handleVal, this.limits.maxStart, this.limits.maxEnd);\n handleVal = value[0];\n handlepos = value[1];\n }\n this.secondHandle.classList.add(classNames.sliderActiveHandle);\n this.handlePos2 = this.preHandlePos2 = handlepos;\n this.handleVal2 = handleVal;\n }\n this.modifyZindex();\n this.secondHandle.focus();\n }\n else {\n this.activeHandle = 1;\n if (!(this.limits.enabled && this.limits.startHandleFixed)) {\n if (this.limits.enabled) {\n var value = this.getLimitValueAndPosition(handleVal, this.limits.minStart, this.limits.minEnd);\n handleVal = value[0];\n handlepos = value[1];\n }\n this.firstHandle.classList.add(classNames.sliderActiveHandle);\n this.handlePos1 = this.preHandlePos1 = handlepos;\n this.handleVal1 = handleVal;\n }\n this.modifyZindex();\n this.firstHandle.focus();\n }\n if (this.isMaterial && this.tooltip.isVisible) {\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n tooltipElement.classList.add(classNames.materialTooltipActive);\n }\n var focusedElement = this.element.querySelector('.' + classNames.sliderTabHandle);\n if (focusedElement && this.getHandle() !== focusedElement) {\n focusedElement.classList.remove(classNames.sliderTabHandle);\n }\n var handle = this.activeHandle === 1 ? this.firstHandle : this.secondHandle;\n if (evt.target === handle) {\n if (this.isMaterial && !this.tooltip.isVisible &&\n !this.getHandle().classList.contains(classNames.sliderTabHandle)) {\n this.materialChange();\n }\n this.tooltipAnimation();\n return;\n }\n if (!this.checkRepeatedValue(handleVal)) {\n return;\n }\n var transition = this.isMaterial && this.tooltip.isVisible ?\n this.transitionOnMaterialTooltip : this.transition;\n this.getHandle().style.transition = transition.handle;\n if (this.type !== 'Default') {\n this.rangeBar.style.transition = transition.rangeBar;\n }\n this.setHandlePosition();\n if (this.type !== 'Default') {\n this.setRangeBar();\n }\n };\n Slider.prototype.refreshTooltipOnMove = function () {\n if (this.tooltip.isVisible) {\n this.tooltipValue();\n this.activeHandle === 1 ? this.firstTooltipObj.refresh(this.firstHandle) :\n this.secondTooltipObj.refresh(this.secondHandle);\n }\n };\n Slider.prototype.sliderDown = function (event) {\n event.preventDefault();\n this.focusSliderElement();\n if (this.type === 'Range' && this.drag && event.target === this.rangeBar) {\n var xPostion = void 0;\n var yPostion = void 0;\n if (event.type === 'mousedown') {\n _a = [event.clientX, event.clientY], xPostion = _a[0], yPostion = _a[1];\n }\n else if (event.type === 'touchstart') {\n _b = [event.changedTouches[0].clientX, event.changedTouches[0].clientY], xPostion = _b[0], yPostion = _b[1];\n }\n if (this.orientation === 'Horizontal') {\n this.firstPartRemain = xPostion - this.rangeBar.getBoundingClientRect().left;\n this.secondPartRemain = this.rangeBar.getBoundingClientRect().right - xPostion;\n }\n else {\n this.firstPartRemain = yPostion - this.rangeBar.getBoundingClientRect().top;\n this.secondPartRemain = this.rangeBar.getBoundingClientRect().bottom - yPostion;\n }\n this.minDiff = this.handleVal2 - this.handleVal1;\n this.getHandle().focus();\n EventHandler.add(document, 'mousemove touchmove', this.dragRangeBarMove, this);\n EventHandler.add(document, 'mouseup touchend', this.dragRangeBarUp, this);\n }\n else {\n this.sliderBarClick(event);\n EventHandler.add(document, 'mousemove touchmove', this.sliderBarMove, this);\n EventHandler.add(document, 'mouseup touchend', this.sliderBarUp, this);\n }\n var _a, _b;\n };\n Slider.prototype.handleValueAdjust = function (handleValue, assignValue, handleNumber) {\n if (handleNumber === 1) {\n this.handleVal1 = assignValue;\n this.handleVal2 = this.handleVal1 + this.minDiff;\n }\n else if (handleNumber === 2) {\n this.handleVal2 = assignValue;\n this.handleVal1 = this.handleVal2 - this.minDiff;\n }\n this.handlePos1 = this.checkHandlePosition(this.handleVal1);\n this.handlePos2 = this.checkHandlePosition(this.handleVal2);\n };\n Slider.prototype.dragRangeBarMove = function (event) {\n if (event.type !== 'touchmove') {\n event.preventDefault();\n }\n var pos;\n this.rangeBar.style.transition = 'none';\n this.firstHandle.style.transition = 'none';\n this.secondHandle.style.transition = 'none';\n var xPostion;\n var yPostion;\n if (event.type === 'mousemove') {\n _a = [event.clientX, event.clientY], xPostion = _a[0], yPostion = _a[1];\n }\n else {\n _b = [event.changedTouches[0].clientX, event.changedTouches[0].clientY], xPostion = _b[0], yPostion = _b[1];\n }\n if (!(this.limits.enabled && this.limits.startHandleFixed) && !(this.limits.enabled && this.limits.endHandleFixed)) {\n if (!this.enableRtl) {\n pos = { x: xPostion - this.firstPartRemain, y: yPostion + this.secondPartRemain };\n }\n else {\n pos = { x: xPostion + this.secondPartRemain, y: yPostion + this.secondPartRemain };\n }\n this.handlePos1 = this.xyToPosition(pos);\n this.handleVal1 = this.positionToValue(this.handlePos1);\n if (!this.enableRtl) {\n pos = { x: xPostion + this.secondPartRemain, y: yPostion - this.firstPartRemain };\n }\n else {\n pos = { x: xPostion - this.firstPartRemain, y: yPostion - this.firstPartRemain };\n }\n this.handlePos2 = this.xyToPosition(pos);\n this.handleVal2 = this.positionToValue(this.handlePos2);\n if (this.limits.enabled) {\n var value = this.getLimitValueAndPosition(this.handleVal1, this.limits.minStart, this.limits.minEnd);\n this.handleVal1 = value[0];\n this.handlePos1 = value[1];\n if (this.handleVal1 === this.limits.minEnd) {\n this.handleValueAdjust(this.handleVal1, this.limits.minEnd, 1);\n }\n if (this.handleVal1 === this.limits.minStart) {\n this.handleValueAdjust(this.handleVal1, this.limits.minStart, 1);\n }\n value = this.getLimitValueAndPosition(this.handleVal2, this.limits.maxStart, this.limits.maxEnd);\n this.handleVal2 = value[0];\n this.handlePos2 = value[1];\n if (this.handleVal2 === this.limits.maxStart) {\n this.handleValueAdjust(this.handleVal2, this.limits.maxStart, 2);\n }\n if (this.handleVal2 === this.limits.maxEnd) {\n this.handleValueAdjust(this.handleVal2, this.limits.maxEnd, 2);\n }\n }\n if (this.handleVal2 === this.max) {\n this.handleValueAdjust(this.handleVal2, this.max, 2);\n }\n if (this.handleVal1 === this.min) {\n this.handleValueAdjust(this.handleVal1, this.min, 1);\n }\n }\n this.activeHandle = 1;\n this.setHandlePosition();\n if (this.tooltip.isVisible) {\n if (this.isMaterial) {\n !this.firstTooltipElement.classList.contains(classNames.materialTooltipOpen) ? this.openMaterialTooltip() :\n this.refreshTooltipOnMove();\n }\n else {\n !this.firstTooltipElement ? this.openTooltip() : this.refreshTooltipOnMove();\n }\n }\n this.activeHandle = 2;\n this.setHandlePosition();\n if (this.tooltip.isVisible) {\n if (this.isMaterial) {\n !this.secondTooltipElement.classList.contains(classNames.materialTooltipOpen) ? this.openMaterialTooltip() :\n this.refreshTooltipOnMove();\n }\n else {\n !this.secondTooltipElement ? this.openTooltip() : this.refreshTooltipOnMove();\n }\n }\n this.setRangeBar();\n var _a, _b;\n };\n Slider.prototype.sliderBarUp = function () {\n this.changeEvent('changed');\n this.handleFocusOut();\n this.firstHandle.classList.remove(classNames.sliderActiveHandle);\n if (this.type === 'Range') {\n this.secondHandle.classList.remove(classNames.sliderActiveHandle);\n }\n if (this.tooltip.isVisible) {\n if (this.tooltip.showOn !== 'Always') {\n this.closeTooltip();\n }\n if (!this.isMaterial) {\n var tooltipObj = this.activeHandle === 1 ? this.firstTooltipObj : this.secondTooltipObj;\n tooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'None' } };\n }\n }\n if (this.isMaterial) {\n this.getHandle().classList.remove('e-large-thumb-size');\n if (this.tooltip.isVisible) {\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n tooltipElement.classList.remove(classNames.materialTooltipActive);\n }\n }\n EventHandler.remove(document, 'mousemove touchmove', this.sliderBarMove);\n EventHandler.remove(document, 'mouseup touchend', this.sliderBarUp);\n };\n Slider.prototype.sliderBarMove = function (evt) {\n if (evt.type !== 'touchmove') {\n evt.preventDefault();\n }\n var pos;\n if (evt.type === 'mousemove') {\n pos = { x: evt.clientX, y: evt.clientY };\n }\n else {\n pos = { x: evt.changedTouches[0].clientX, y: evt.changedTouches[0].clientY };\n }\n var handlepos = this.xyToPosition(pos);\n var handleVal = this.positionToValue(handlepos);\n handlepos = Math.round(handlepos);\n if (this.type !== 'Range' && this.activeHandle === 1) {\n if (!(this.limits.enabled && this.limits.startHandleFixed)) {\n if (this.limits.enabled) {\n var valueAndPostion = this.getLimitValueAndPosition(handleVal, this.limits.minStart, this.limits.minEnd);\n handlepos = valueAndPostion[1];\n handleVal = valueAndPostion[0];\n }\n this.handlePos1 = handlepos;\n this.handleVal1 = handleVal;\n }\n this.firstHandle.classList.add(classNames.sliderActiveHandle);\n }\n if (this.type === 'Range') {\n if (this.activeHandle === 1) {\n this.firstHandle.classList.add(classNames.sliderActiveHandle);\n if (!(this.limits.enabled && this.limits.startHandleFixed)) {\n if (handlepos > this.handlePos2) {\n handlepos = this.handlePos2;\n handleVal = this.handleVal2;\n }\n if (handlepos !== this.preHandlePos1) {\n if (this.limits.enabled) {\n var value = this.getLimitValueAndPosition(handleVal, this.limits.minStart, this.limits.minEnd);\n handleVal = value[0];\n handlepos = value[1];\n }\n this.handlePos1 = this.preHandlePos1 = handlepos;\n this.handleVal1 = handleVal;\n this.activeHandle = 1;\n }\n }\n }\n else if (this.activeHandle === 2) {\n this.secondHandle.classList.add(classNames.sliderActiveHandle);\n if (!(this.limits.enabled && this.limits.endHandleFixed)) {\n if (handlepos < this.handlePos1) {\n handlepos = this.handlePos1;\n handleVal = this.handleVal1;\n }\n if (handlepos !== this.preHandlePos2) {\n if (this.limits.enabled) {\n var value = this.getLimitValueAndPosition(handleVal, this.limits.maxStart, this.limits.maxEnd);\n handleVal = value[0];\n handlepos = value[1];\n }\n this.handlePos2 = this.preHandlePos2 = handlepos;\n this.handleVal2 = handleVal;\n this.activeHandle = 2;\n }\n }\n }\n }\n if (!this.checkRepeatedValue(handleVal)) {\n return;\n }\n this.getHandle().style.transition = this.scaleTransform;\n if (this.type !== 'Default') {\n this.rangeBar.style.transition = 'none';\n }\n this.setHandlePosition();\n if (this.isMaterial && !this.tooltip.isVisible &&\n !this.getHandle().classList.contains(classNames.sliderTabHandle)) {\n this.materialChange();\n }\n var tooltipElement = this.activeHandle === 1 ? this.firstTooltipElement : this.secondTooltipElement;\n if (this.tooltip.isVisible) {\n if (this.isMaterial) {\n !tooltipElement.classList.contains(classNames.materialTooltipOpen) ? this.openMaterialTooltip() :\n this.refreshTooltipOnMove();\n }\n else {\n !tooltipElement ? this.openTooltip() : this.refreshTooltipOnMove();\n }\n }\n if (this.type !== 'Default') {\n this.setRangeBar();\n }\n };\n Slider.prototype.dragRangeBarUp = function (event) {\n this.changeEvent('changed');\n if (this.tooltip.isVisible) {\n if (this.tooltip.showOn !== 'Always' && !this.isMaterial) {\n this.activeHandle = 1;\n this.firstTooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'FadeOut', duration: 500 } };\n this.closeTooltip();\n this.activeHandle = 2;\n this.secondTooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'FadeOut', duration: 500 } };\n this.closeTooltip();\n }\n }\n EventHandler.remove(document, 'mousemove touchmove', this.dragRangeBarMove);\n EventHandler.remove(document, 'mouseup touchend', this.dragRangeBarUp);\n };\n Slider.prototype.checkRepeatedValue = function (currentValue) {\n if (this.type === 'Range') {\n var previousVal = this.enableRtl && this.orientation !== 'Vertical' ? (this.activeHandle === 1 ?\n this.previousVal[1] : this.previousVal[0]) :\n (this.activeHandle === 1 ? this.previousVal[0] : this.previousVal[1]);\n if (currentValue === previousVal) {\n return 0;\n }\n }\n else {\n if (currentValue === this.previousVal) {\n return 0;\n }\n }\n return 1;\n };\n Slider.prototype.refreshTooltip = function () {\n if (this.tooltip.isVisible && this.firstTooltipObj) {\n this.tooltipValue();\n this.firstTooltipObj.refresh(this.firstHandle);\n if (this.type === 'Range') {\n this.secondTooltipObj.refresh(this.secondHandle);\n }\n }\n };\n Slider.prototype.openTooltip = function () {\n if (this.tooltip.isVisible && this.firstTooltipObj) {\n this.tooltipValue();\n if (this.isMaterial) {\n this.openMaterialTooltip();\n }\n else {\n if (this.activeHandle === 1) {\n this.firstTooltipObj.open(this.firstHandle);\n }\n else {\n this.secondTooltipObj.open(this.secondHandle);\n }\n }\n }\n };\n Slider.prototype.keyDown = function (event) {\n switch (event.keyCode) {\n case 37:\n case 38:\n case 39:\n case 40:\n case 33:\n case 34:\n case 36:\n case 35:\n event.preventDefault();\n this.buttonClick(event);\n if (this.tooltip.isVisible && this.tooltip.showOn !== 'Always' && !this.isMaterial) {\n this.closeTooltip();\n }\n break;\n }\n };\n Slider.prototype.wireButtonEvt = function (destroy) {\n if (!destroy) {\n EventHandler.add(this.firstBtn, 'mouseleave touchleave', this.buttonFocusOut, this);\n EventHandler.add(this.secondBtn, 'mouseleave touchleave', this.buttonFocusOut, this);\n EventHandler.add(this.firstBtn, 'mousedown touchstart', this.repeatHandlerMouse, this);\n EventHandler.add(this.firstBtn, 'mouseup mouseleave touchup touchend', this.repeatHandlerUp, this);\n EventHandler.add(this.secondBtn, 'mousedown touchstart', this.repeatHandlerMouse, this);\n EventHandler.add(this.secondBtn, 'mouseup mouseleave touchup touchend', this.repeatHandlerUp, this);\n EventHandler.add(this.firstBtn, 'focusout', this.sliderFocusOut, this);\n EventHandler.add(this.secondBtn, 'focusout', this.sliderFocusOut, this);\n }\n else {\n EventHandler.remove(this.firstBtn, 'mouseleave touchleave', this.buttonFocusOut);\n EventHandler.remove(this.secondBtn, 'mouseleave touchleave', this.buttonFocusOut);\n EventHandler.remove(this.firstBtn, 'mousedown touchstart', this.repeatHandlerMouse);\n EventHandler.remove(this.firstBtn, 'mouseup mouseleave touchup touchend', this.repeatHandlerUp);\n EventHandler.remove(this.secondBtn, 'mousedown touchstart', this.repeatHandlerMouse);\n EventHandler.remove(this.secondBtn, 'mouseup mouseleave touchup touchend', this.repeatHandlerUp);\n EventHandler.remove(this.firstBtn, 'focusout', this.sliderFocusOut);\n EventHandler.remove(this.secondBtn, 'focusout', this.sliderFocusOut);\n }\n };\n Slider.prototype.wireEvents = function () {\n this.onresize = this.onResize.bind(this);\n window.addEventListener('resize', this.onresize);\n if (this.enabled && !this.readonly) {\n EventHandler.add(this.element, 'mousedown touchstart', this.sliderDown, this);\n EventHandler.add(this.sliderContainer, 'keydown', this.keyDown, this);\n EventHandler.add(this.sliderContainer, 'keyup', this.keyUp, this);\n EventHandler.add(this.element, 'focusout', this.sliderFocusOut, this);\n EventHandler.add(this.sliderContainer, 'mouseover mouseout touchstart touchend', this.hover, this);\n this.wireFirstHandleEvt(false);\n if (this.type === 'Range') {\n this.wireSecondHandleEvt(false);\n }\n if (this.showButtons) {\n this.wireButtonEvt(false);\n }\n this.wireMaterialTooltipEvent(false);\n }\n };\n Slider.prototype.unwireEvents = function () {\n EventHandler.remove(this.element, 'mousedown touchstart', this.sliderDown);\n EventHandler.remove(this.sliderContainer, 'keydown', this.keyDown);\n EventHandler.remove(this.sliderContainer, 'keyup', this.keyUp);\n EventHandler.remove(this.element, 'focusout', this.sliderFocusOut);\n EventHandler.remove(this.sliderContainer, 'mouseover mouseout touchstart touchend', this.hover);\n this.wireFirstHandleEvt(true);\n if (this.type === 'Range') {\n this.wireSecondHandleEvt(true);\n }\n if (this.showButtons) {\n this.wireButtonEvt(true);\n }\n this.wireMaterialTooltipEvent(true);\n };\n Slider.prototype.keyUp = function (event) {\n if (event.keyCode === 9 && event.target.classList.contains(classNames.sliderHandle)) {\n this.focusSliderElement();\n if (!event.target.classList.contains(classNames.sliderTabHandle)) {\n if (this.element.querySelector('.' + classNames.sliderTabHandle)) {\n this.element.querySelector('.' + classNames.sliderTabHandle).classList.remove(classNames.sliderTabHandle);\n }\n event.target.classList.add(classNames.sliderTabHandle);\n var parentElement = event.target.parentElement;\n if (parentElement === this.element) {\n parentElement.querySelector('.' + classNames.sliderTrack).classList.add(classNames.sliderTabTrack);\n if (this.type === 'Range' || this.type === 'MinRange') {\n parentElement.querySelector('.' + classNames.rangeBar).classList.add(classNames.sliderTabRange);\n }\n }\n if (this.type === 'Range') {\n (event.target.previousSibling).classList.contains(classNames.sliderHandle) ?\n this.activeHandle = 2 : this.activeHandle = 1;\n }\n this.getHandle().focus();\n this.tooltipAnimation();\n if (this.tooltip.isVisible && this.tooltip.showOn !== 'Always' && !this.isMaterial) {\n this.closeTooltip();\n }\n }\n }\n this.changeEvent('changed');\n };\n Slider.prototype.hover = function (event) {\n if (!isNullOrUndefined(event)) {\n if (event.type === 'mouseover' || event.type === 'touchmove' || event.type === 'mousemove' ||\n event.type === 'pointermove' || event.type === 'touchstart') {\n this.sliderContainer.classList.add(classNames.sliderHover);\n }\n else {\n this.sliderContainer.classList.remove(classNames.sliderHover);\n }\n }\n };\n Slider.prototype.sliderFocusOut = function (event) {\n var _this = this;\n if (event.relatedTarget !== this.secondHandle && event.relatedTarget !== this.firstHandle &&\n event.relatedTarget !== this.element && event.relatedTarget !== this.firstBtn && event.relatedTarget !== this.secondBtn) {\n if (this.isMaterial && this.tooltip.isVisible) {\n var transformProperties_1 = this.getTooltipTransformProperties(this.previousTooltipClass);\n var tooltipElement = this.type !== 'Range' ? [this.firstTooltipElement] :\n [this.firstTooltipElement, this.secondTooltipElement];\n var hiddenHandle_1 = this.type !== 'Range' ? [this.firstHandle] : [this.firstHandle, this.secondHandle];\n var handle_1 = this.type !== 'Range' ? [this.firstMaterialHandle] :\n [this.firstMaterialHandle, this.secondMaterialHandle];\n tooltipElement.forEach(function (tooltipElement, index) {\n if (tooltipElement) {\n tooltipElement.style.transition = _this.scaleTransform;\n tooltipElement.firstChild.classList.remove(classNames.materialTooltipShow);\n tooltipElement.firstChild.classList.add(classNames.materialTooltipHide);\n hiddenHandle_1[index].style.cursor = '-webkit-grab';\n hiddenHandle_1[index].style.cursor = 'grab';\n handle_1[index].style.transform = 'scale(1)';\n tooltipElement.classList.remove(classNames.materialTooltipOpen);\n if (tooltipElement.firstElementChild.innerText.length > 4) {\n tooltipElement.style.transform = transformProperties_1.translate + ' ' + 'scale(0.01)';\n }\n else {\n tooltipElement.style.transform = transformProperties_1.translate + ' ' +\n transformProperties_1.rotate + ' ' + 'scale(0.01)';\n }\n setTimeout(function () { tooltipElement.style.transition = 'none'; }, 2500);\n }\n });\n }\n if (this.element.querySelector('.' + classNames.sliderTabHandle)) {\n this.element.querySelector('.' + classNames.sliderTabHandle).classList.remove(classNames.sliderTabHandle);\n }\n if (this.element.querySelector('.' + classNames.sliderTabTrack)) {\n this.element.querySelector('.' + classNames.sliderTabTrack).classList.remove(classNames.sliderTabTrack);\n if ((this.type === 'Range' || this.type === 'MinRange') &&\n this.element.querySelector('.' + classNames.sliderTabRange)) {\n this.element.querySelector('.' + classNames.sliderTabRange).classList.remove(classNames.sliderTabRange);\n }\n }\n this.hiddenInput.focus();\n this.hiddenInput.blur();\n this.isElementFocused = false;\n }\n };\n Slider.prototype.closeTooltip = function () {\n if (this.tooltip.isVisible) {\n this.tooltipValue();\n if (this.activeHandle === 1) {\n this.firstTooltipObj.close();\n }\n else {\n this.secondTooltipObj.close();\n }\n }\n };\n Slider.prototype.removeElement = function (element) {\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n };\n Slider.prototype.changeSliderType = function (type) {\n if (this.isMaterial && this.firstMaterialHandle) {\n this.sliderContainer.classList.remove(classNames.materialSlider);\n this.removeElement(this.firstMaterialHandle);\n this.firstTooltipElement = undefined;\n this.firstHandleTooltipPosition = undefined;\n if (this.secondMaterialHandle) {\n this.removeElement(this.secondMaterialHandle);\n this.secondTooltipElement = undefined;\n this.secondHandleTooltipPosition = undefined;\n }\n }\n if (this.tooltip.isVisible && this.isMaterial) {\n this.sliderContainer.classList.add(classNames.materialSlider);\n }\n this.removeElement(this.firstHandle);\n if (type !== 'Default') {\n if (type === 'Range') {\n this.removeElement(this.secondHandle);\n }\n this.removeElement(this.rangeBar);\n }\n if (this.tooltip.isVisible && !isNullOrUndefined(this.firstTooltipObj)) {\n this.firstTooltipObj.destroy();\n if (type === 'Range' && !isNullOrUndefined(this.secondTooltipObj)) {\n this.secondTooltipObj.destroy();\n }\n }\n if (this.limits.enabled && type === 'MinRange' || type === 'Default') {\n if (!isNullOrUndefined(this.limitBarFirst)) {\n this.removeElement(this.limitBarFirst);\n }\n }\n if (type === 'Range') {\n if (this.limits.enabled) {\n if (!isNullOrUndefined(this.limitBarFirst) && !isNullOrUndefined(this.limitBarSecond)) {\n this.removeElement(this.limitBarFirst);\n this.removeElement(this.limitBarSecond);\n }\n }\n }\n this.createRangeBar();\n if (this.limits.enabled) {\n this.createLimitBar();\n }\n this.setHandler();\n this.setOrientClass();\n this.wireFirstHandleEvt(false);\n if (this.type === 'Range') {\n this.wireSecondHandleEvt(false);\n }\n this.setValue();\n if (this.tooltip.isVisible) {\n this.renderTooltip();\n this.wireMaterialTooltipEvent(false);\n }\n this.updateConfig();\n };\n Slider.prototype.changeRtl = function () {\n if (!this.enableRtl && this.type === 'Range') {\n this.value = [this.handleVal2, this.handleVal1];\n }\n this.updateConfig();\n if (this.tooltip.isVisible) {\n this.firstTooltipObj.refresh(this.firstHandle);\n if (this.type === 'Range') {\n this.secondTooltipObj.refresh(this.secondHandle);\n }\n }\n if (this.showButtons) {\n var enabledRTL = this.enableRtl && this.orientation !== 'Vertical';\n attributes(enabledRTL ? this.secondBtn : this.firstBtn, { 'aria-label': 'Decrease', title: 'Decrease' });\n attributes(enabledRTL ? this.firstBtn : this.secondBtn, { 'aria-label': 'Increase', title: 'Increase' });\n }\n };\n Slider.prototype.changeOrientation = function () {\n this.changeSliderType(this.type);\n };\n Slider.prototype.updateConfig = function () {\n this.setEnableRTL();\n this.setValue();\n if (this.tooltip.isVisible) {\n this.refreshTooltip();\n }\n if (this.ticks.placement !== 'None') {\n if (this.ul) {\n this.removeElement(this.ul);\n this.renderScale();\n }\n }\n this.limitsPropertyChange();\n };\n Slider.prototype.limitsPropertyChange = function () {\n if (this.limits.enabled) {\n if (isNullOrUndefined(this.limitBarFirst) && this.type !== 'Range') {\n this.createLimitBar();\n }\n if (isNullOrUndefined(this.limitBarFirst) && isNullOrUndefined(this.limitBarSecond) && this.type === 'Range') {\n this.createLimitBar();\n }\n this.setLimitBar();\n this.setValue();\n }\n else {\n if (!isNullOrUndefined(this.limitBarFirst)) {\n detach(this.limitBarFirst);\n }\n if (!isNullOrUndefined(this.limitBarSecond)) {\n detach(this.limitBarSecond);\n }\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n Slider.prototype.getPersistData = function () {\n var keyEntity = ['value'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Prepares the slider for safe removal from the DOM.\n * Detaches all event handlers, attributes, and classes to avoid memory leaks.\n * @method destroy\n * @return {void}\n */\n Slider.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n this.unwireEvents();\n window.removeEventListener('resize', this.onresize);\n removeClass([this.sliderContainer], [classNames.sliderDisabled]);\n this.firstHandle.removeAttribute('aria-orientation');\n if (this.type === 'Range') {\n this.secondHandle.removeAttribute('aria-orientation');\n }\n this.sliderContainer.parentNode.insertBefore(this.element, this.sliderContainer);\n detach(this.sliderContainer);\n if (this.tooltip.isVisible) {\n this.firstTooltipObj.destroy();\n if (this.type === 'Range' && !isNullOrUndefined(this.secondTooltipObj)) {\n this.secondTooltipObj.destroy();\n }\n }\n this.element.innerHTML = '';\n };\n /**\n * Calls internally if any of the property value is changed.\n * @private\n */\n Slider.prototype.onPropertyChanged = function (newProp, oldProp) {\n var _this = this;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'cssClass':\n this.setCSSClass(oldProp.cssClass);\n break;\n case 'value':\n if (!isNullOrUndefined(oldProp.value) && !isNullOrUndefined(newProp.value)) {\n if (oldProp.value.toString() !== newProp.value.toString()) {\n this.setValue();\n this.refreshTooltip();\n if (this.type === 'Range') {\n if (oldProp.value[0] === newProp.value[0]) {\n this.activeHandle = 2;\n }\n else {\n this.activeHandle = 1;\n }\n }\n }\n }\n break;\n case 'min':\n case 'step':\n case 'max':\n this.setMinMaxValue();\n break;\n case 'tooltip':\n if (!isNullOrUndefined(newProp.tooltip) && !isNullOrUndefined(oldProp.tooltip)) {\n this.setTooltip();\n }\n break;\n case 'type':\n this.changeSliderType(oldProp.type);\n this.setZindex();\n break;\n case 'enableRtl':\n if (oldProp.enableRtl !== newProp.enableRtl && this.orientation !== 'Vertical') {\n this.rtl = oldProp.enableRtl;\n this.changeRtl();\n }\n break;\n case 'limits':\n this.limitsPropertyChange();\n break;\n case 'orientation':\n this.changeOrientation();\n break;\n case 'ticks':\n if (!isNullOrUndefined(this.sliderContainer.querySelector('.' + classNames.scale))) {\n detach(this.ul);\n Array.prototype.forEach.call(this.sliderContainer.classList, function (className) {\n if (className.match(/e-scale-/)) {\n _this.sliderContainer.classList.remove(className);\n }\n });\n }\n if (this.ticks.placement !== 'None') {\n this.renderScale();\n this.setZindex();\n }\n break;\n case 'locale':\n if (this.showButtons) {\n this.buttonTitle();\n }\n break;\n case 'showButtons':\n if (newProp.showButtons) {\n this.setButtons();\n this.onResize();\n if (this.enabled && !this.readonly) {\n this.wireButtonEvt(false);\n }\n }\n else {\n if (this.firstBtn && this.secondBtn) {\n this.sliderContainer.removeChild(this.firstBtn);\n this.sliderContainer.removeChild(this.secondBtn);\n this.firstBtn = undefined;\n this.secondBtn = undefined;\n }\n }\n break;\n case 'enabled':\n this.setEnabled();\n break;\n case 'readonly':\n this.setReadOnly();\n break;\n case 'customValue':\n this.setValue();\n this.onResize();\n break;\n }\n }\n };\n Slider.prototype.setReadOnly = function () {\n if (this.readonly) {\n this.unwireEvents();\n this.sliderContainer.classList.add(classNames.readonly);\n }\n else {\n this.wireEvents();\n this.sliderContainer.classList.remove(classNames.readonly);\n }\n };\n Slider.prototype.setMinMaxValue = function () {\n var _this = this;\n this.setValue();\n this.refreshTooltip();\n if (!isNullOrUndefined(this.sliderContainer.querySelector('.' + classNames.scale))) {\n if (this.ul) {\n detach(this.ul);\n Array.prototype.forEach.call(this.sliderContainer.classList, function (className) {\n if (className.match(/e-scale-/)) {\n _this.sliderContainer.classList.remove(className);\n }\n });\n }\n }\n if (this.ticks.placement !== 'None') {\n this.renderScale();\n this.setZindex();\n }\n };\n Slider.prototype.setZindex = function () {\n this.zIndex = 6;\n if (!isNullOrUndefined(this.ticks) && this.ticks.placement !== 'None') {\n this.ul.style.zIndex = (this.zIndex + -7) + '';\n this.element.style.zIndex = (this.zIndex + 2) + '';\n }\n if (!this.isMaterial && !isNullOrUndefined(this.ticks) && this.ticks.placement === 'Both') {\n this.element.style.zIndex = (this.zIndex + 2) + '';\n }\n this.firstHandle.style.zIndex = (this.zIndex + 3) + '';\n if (this.type === 'Range') {\n this.secondHandle.style.zIndex = (this.zIndex + 4) + '';\n }\n };\n Slider.prototype.setTooltip = function () {\n this.changeSliderType(this.type);\n };\n /**\n * Gets the component name\n * @private\n */\n Slider.prototype.getModuleName = function () {\n return 'slider';\n };\n __decorate([\n Property(null)\n ], Slider.prototype, \"value\", void 0);\n __decorate([\n Property(null)\n ], Slider.prototype, \"customValues\", void 0);\n __decorate([\n Property(1)\n ], Slider.prototype, \"step\", void 0);\n __decorate([\n Property(0)\n ], Slider.prototype, \"min\", void 0);\n __decorate([\n Property(100)\n ], Slider.prototype, \"max\", void 0);\n __decorate([\n Property(false)\n ], Slider.prototype, \"readonly\", void 0);\n __decorate([\n Property('Default')\n ], Slider.prototype, \"type\", void 0);\n __decorate([\n Complex({}, TicksData)\n ], Slider.prototype, \"ticks\", void 0);\n __decorate([\n Complex({}, LimitData)\n ], Slider.prototype, \"limits\", void 0);\n __decorate([\n Property(true)\n ], Slider.prototype, \"enabled\", void 0);\n __decorate([\n Property(false)\n ], Slider.prototype, \"enableRtl\", void 0);\n __decorate([\n Complex({}, TooltipData)\n ], Slider.prototype, \"tooltip\", void 0);\n __decorate([\n Property(false)\n ], Slider.prototype, \"showButtons\", void 0);\n __decorate([\n Property(true)\n ], Slider.prototype, \"enableAnimation\", void 0);\n __decorate([\n Property('Horizontal')\n ], Slider.prototype, \"orientation\", void 0);\n __decorate([\n Property('')\n ], Slider.prototype, \"cssClass\", void 0);\n __decorate([\n Event()\n ], Slider.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Slider.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], Slider.prototype, \"changed\", void 0);\n __decorate([\n Event()\n ], Slider.prototype, \"renderingTicks\", void 0);\n __decorate([\n Event()\n ], Slider.prototype, \"renderedTicks\", void 0);\n __decorate([\n Event()\n ], Slider.prototype, \"tooltipChange\", void 0);\n Slider = __decorate([\n NotifyPropertyChanges\n ], Slider);\n return Slider;\n}(Component));\nexport { Slider };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, Event, EventHandler, L10n, compile, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, detach, append, Animation } from '@syncfusion/ej2-base';\nimport { addClass, removeClass, KeyboardEvents, setValue, getValue, ChildProperty } from '@syncfusion/ej2-base';\nimport { Collection, Complex, Browser, Ajax } from '@syncfusion/ej2-base';\nimport { createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';\nvar ROOT = 'e-uploader';\nvar CONTROL_WRAPPER = 'e-upload';\nvar INPUT_WRAPPER = 'e-file-select';\nvar DROP_AREA = 'e-file-drop';\nvar DROP_WRAPPER = 'e-file-select-wrap';\nvar LIST_PARENT = 'e-upload-files';\nvar FILE = 'e-upload-file-list';\nvar STATUS = 'e-file-status';\nvar ACTION_BUTTONS = 'e-upload-actions';\nvar UPLOAD_BUTTONS = 'e-file-upload-btn e-css e-btn e-flat e-primary';\nvar CLEAR_BUTTONS = 'e-file-clear-btn e-css e-btn e-flat';\nvar FILE_NAME = 'e-file-name';\nvar FILE_TYPE = 'e-file-type';\nvar FILE_SIZE = 'e-file-size';\nvar CLEAR_ICON = 'e-file-remove-btn';\nvar REMOVE_ICON = 'e-file-delete-btn';\nvar ABORT_ICON = 'e-file-abort-btn';\nvar RETRY_ICON = 'e-file-reload-btn';\nvar DRAG_HOVER = 'e-upload-drag-hover';\nvar PROGRESS_WRAPPER = 'e-upload-progress-wrap';\nvar PROGRESSBAR = 'e-upload-progress-bar';\nvar PROGRESSBAR_TEXT = 'e-progress-bar-text';\nvar UPLOAD_INPROGRESS = 'e-upload-progress';\nvar UPLOAD_SUCCESS = 'e-upload-success';\nvar UPLOAD_FAILED = 'e-upload-fails';\nvar TEXT_CONTAINER = 'e-file-container';\nvar VALIDATION_FAILS = 'e-validation-fails';\nvar RTL = 'e-rtl';\nvar DISABLED = 'e-disabled';\nvar RTL_CONTAINER = 'e-rtl-container';\nvar ICON_FOCUSED = 'e-clear-icon-focus';\nvar PROGRESS_INNER_WRAPPER = 'e-progress-inner-wrap';\nvar PAUSE_UPLOAD = 'e-file-pause-btn';\nvar RESUME_UPLOAD = 'e-file-play-btn';\nvar FilesProp = /** @class */ (function (_super) {\n __extends(FilesProp, _super);\n function FilesProp() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], FilesProp.prototype, \"name\", void 0);\n __decorate([\n Property(null)\n ], FilesProp.prototype, \"size\", void 0);\n __decorate([\n Property('')\n ], FilesProp.prototype, \"type\", void 0);\n return FilesProp;\n}(ChildProperty));\nexport { FilesProp };\nvar ButtonsProps = /** @class */ (function (_super) {\n __extends(ButtonsProps, _super);\n function ButtonsProps() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Browse...')\n ], ButtonsProps.prototype, \"browse\", void 0);\n __decorate([\n Property('Upload')\n ], ButtonsProps.prototype, \"upload\", void 0);\n __decorate([\n Property('Clear')\n ], ButtonsProps.prototype, \"clear\", void 0);\n return ButtonsProps;\n}(ChildProperty));\nexport { ButtonsProps };\nvar AsyncSettings = /** @class */ (function (_super) {\n __extends(AsyncSettings, _super);\n function AsyncSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], AsyncSettings.prototype, \"saveUrl\", void 0);\n __decorate([\n Property('')\n ], AsyncSettings.prototype, \"removeUrl\", void 0);\n __decorate([\n Property(0)\n ], AsyncSettings.prototype, \"chunkSize\", void 0);\n __decorate([\n Property(3)\n ], AsyncSettings.prototype, \"retryCount\", void 0);\n __decorate([\n Property(500)\n ], AsyncSettings.prototype, \"retryAfterDelay\", void 0);\n return AsyncSettings;\n}(ChildProperty));\nexport { AsyncSettings };\n/**\n * The uploader component allows to upload images, documents, and other files from local to server.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar Uploader = /** @class */ (function (_super) {\n __extends(Uploader, _super);\n /**\n * Triggers when change the Uploader value.\n */\n function Uploader(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.initialAttr = { accept: null, multiple: false, disabled: false };\n _this.fileList = [];\n _this.filesData = [];\n _this.uploadedFilesData = [];\n _this.isForm = false;\n _this.allTypes = false;\n _this.pausedData = [];\n _this.uploadMetaData = [];\n return _this;\n }\n /**\n * Calls internally if any of the property value is changed.\n * @private\n */\n Uploader.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'allowedExtensions':\n this.setExtensions(this.allowedExtensions);\n this.clearAll();\n break;\n case 'enabled':\n this.setControlStatus();\n break;\n case 'multiple':\n this.setMultipleSelection();\n break;\n case 'enableRtl':\n this.setRTL();\n this.reRenderFileList();\n break;\n case 'buttons':\n this.buttons.browse = isNullOrUndefined(this.buttons.browse) ? '' : this.buttons.browse;\n this.buttons.clear = isNullOrUndefined(this.buttons.clear) ? '' : this.buttons.clear;\n this.buttons.upload = isNullOrUndefined(this.buttons.upload) ? '' : this.buttons.upload;\n this.renderButtonTemplates();\n break;\n case 'dropArea':\n this.unBindDropEvents();\n this.setDropArea();\n break;\n case 'files':\n this.renderPreLoadFiles();\n break;\n case 'minFileSize':\n case 'maxFileSize':\n case 'template':\n case 'autoUpload':\n this.clearAll();\n break;\n case 'locale':\n this.l10n.setLocale(this.locale);\n this.setLocalizedTexts();\n this.preLocaleObj = getValue('currentLocale', this.l10n);\n break;\n }\n }\n };\n Uploader.prototype.setLocalizedTexts = function () {\n if (isNullOrUndefined(this.template)) {\n if (typeof (this.buttons.browse) === 'string') {\n this.browseButton.innerText = (this.buttons.browse === 'Browse...') ?\n this.localizedTexts('Browse') : this.buttons.browse;\n this.browseButton.setAttribute('title', this.browseButton.innerText);\n this.uploadWrapper.querySelector('.' + DROP_AREA).innerHTML = this.localizedTexts('dropFilesHint');\n }\n this.updateFileList();\n }\n };\n Uploader.prototype.getKeyValue = function (val) {\n var keyValue;\n for (var _i = 0, _a = Object.keys(this.preLocaleObj); _i < _a.length; _i++) {\n var key = _a[_i];\n if (this.preLocaleObj[key] === val) {\n keyValue = key;\n }\n }\n return keyValue;\n };\n Uploader.prototype.updateFileList = function () {\n var element;\n if (this.fileList.length > 0 && !isNullOrUndefined(this.uploadWrapper.querySelector('.' + LIST_PARENT))) {\n for (var i = 0; i < this.fileList.length; i++) {\n element = this.fileList[i].querySelector('.e-file-status');\n element.innerHTML = this.localizedTexts(this.getKeyValue(this.filesData[i].status));\n this.filesData[i].status = this.localizedTexts(this.getKeyValue(this.filesData[i].status));\n /* istanbul ignore next */\n if (this.fileList[i].classList.contains(UPLOAD_SUCCESS)) {\n this.fileList[i].querySelector('.e-icons').setAttribute('title', this.localizedTexts('remove'));\n }\n else {\n this.fileList[i].querySelector('.e-icons').setAttribute('title', this.localizedTexts('delete'));\n }\n if (!this.autoUpload) {\n this.uploadButton.innerText = (this.buttons.upload === 'Upload') ?\n this.localizedTexts('Upload') : this.buttons.upload;\n this.clearButton.innerText = (this.buttons.clear === 'Clear') ?\n this.localizedTexts('Clear') : this.buttons.clear;\n }\n }\n }\n };\n Uploader.prototype.reRenderFileList = function () {\n if (this.listParent) {\n detach(this.listParent);\n this.listParent = null;\n this.fileList = [];\n this.createFileList(this.filesData);\n if (this.actionButtons) {\n this.removeActionButtons();\n this.renderActionButtons();\n this.checkActionButtonStatus();\n }\n }\n };\n Uploader.prototype.preRender = function () {\n this.cloneElement = this.element.cloneNode(true);\n this.localeText = { Browse: 'Browse...', Clear: 'Clear', Upload: 'Upload',\n dropFilesHint: 'Or drop files here', invalidMaxFileSize: 'File size is too large',\n invalidMinFileSize: 'File size is too small', invalidFileType: 'File type is not allowed',\n uploadFailedMessage: 'File failed to upload', uploadSuccessMessage: 'File uploaded successfully',\n removedSuccessMessage: 'File removed successfully', removedFailedMessage: 'Unable to remove file', inProgress: 'Uploading',\n readyToUploadMessage: 'Ready to upload', abort: 'Abort', remove: 'Remove', cancel: 'Cancel', delete: 'Delete file',\n pauseUpload: 'File upload paused', pause: 'Pause', resume: 'Resume', retry: 'Retry',\n fileUploadCancel: 'File upload canceled'\n };\n this.l10n = new L10n('uploader', this.localeText, this.locale);\n this.preLocaleObj = getValue('currentLocale', this.l10n);\n this.checkHTMLAttributes();\n if (this.asyncSettings.saveUrl === '' && this.asyncSettings.removeUrl === '' && !this.autoUpload) {\n var parentEle = this.element.parentElement;\n for (; parentEle && parentEle !== document.documentElement; parentEle = parentEle.parentElement) {\n if (parentEle.tagName === 'FORM') {\n this.isForm = true;\n this.formElement = parentEle;\n parentEle.setAttribute('enctype', 'multipart/form-data');\n parentEle.setAttribute('encoding', 'multipart/form-data');\n }\n }\n }\n // tslint:disable-next-line\n var ejInstance = getValue('ej2_instances', this.element);\n /* istanbul ignore next */\n if (this.element.tagName === 'EJS-UPLOADER') {\n var inputElement = this.createElement('input', { attrs: { type: 'file' } });\n var index = 0;\n for (index; index < this.element.attributes.length; index++) {\n inputElement.setAttribute(this.element.attributes[index].nodeName, this.element.attributes[index].nodeValue);\n inputElement.innerHTML = this.element.innerHTML;\n }\n if (!inputElement.hasAttribute('name')) {\n inputElement.setAttribute('name', 'UploadFiles');\n }\n this.element.appendChild(inputElement);\n this.element = inputElement;\n setValue('ej2_instances', ejInstance, this.element);\n }\n /* istanbul ignore next */\n if (ejInstance[0].isPureReactComponent) {\n if (!isNullOrUndefined(ejInstance[0].props.name)) {\n this.element.setAttribute('name', ejInstance[0].props.name);\n }\n else if (!isNullOrUndefined(ejInstance[0].props.id) && isNullOrUndefined(ejInstance[0].props.name)) {\n this.element.setAttribute('name', ejInstance[0].props.id);\n }\n else {\n this.element.setAttribute('name', 'UploadFiles');\n }\n }\n if (isNullOrUndefined(this.element.getAttribute('name'))) {\n this.element.setAttribute('name', this.element.getAttribute('id'));\n }\n if (!this.element.hasAttribute('type')) {\n this.element.setAttribute('type', 'file');\n }\n this.keyConfigs = {\n previous: 'shift+tab',\n enter: 'enter',\n next: 'tab'\n };\n };\n Uploader.prototype.getPersistData = function () {\n return this.addOnPersist([]);\n };\n /**\n * Return the module name of the component.\n */\n Uploader.prototype.getModuleName = function () {\n return 'uploader';\n };\n /**\n * To Initialize the control rendering\n * @private\n */\n Uploader.prototype.render = function () {\n this.renderBrowseButton();\n this.initializeUpload();\n this.wireEvents();\n this.setMultipleSelection();\n this.setExtensions(this.allowedExtensions);\n this.setRTL();\n this.renderPreLoadFiles();\n this.setControlStatus();\n };\n Uploader.prototype.renderBrowseButton = function () {\n this.browseButton = this.createElement('button', { className: 'e-css e-btn', attrs: { 'type': 'button' } });\n if (typeof (this.buttons.browse) === 'string') {\n this.browseButton.innerText = (this.buttons.browse === 'Browse...') ?\n this.localizedTexts('Browse') : this.buttons.browse;\n this.browseButton.setAttribute('title', this.browseButton.innerText);\n }\n else {\n this.browseButton.appendChild(this.buttons.browse);\n }\n this.element.setAttribute('aria-label', 'Uploader');\n };\n Uploader.prototype.renderActionButtons = function () {\n this.element.setAttribute('tabindex', '-1');\n this.actionButtons = this.createElement('div', { className: ACTION_BUTTONS });\n this.uploadButton = this.createElement('button', { className: UPLOAD_BUTTONS, attrs: { 'type': 'button', 'tabindex': '-1' } });\n this.clearButton = this.createElement('button', { className: CLEAR_BUTTONS, attrs: { 'type': 'button', 'tabindex': '-1' } });\n this.actionButtons.appendChild(this.clearButton);\n this.actionButtons.appendChild(this.uploadButton);\n this.renderButtonTemplates();\n this.uploadWrapper.appendChild(this.actionButtons);\n this.browseButton.blur();\n this.uploadButton.focus();\n this.wireActionButtonEvents();\n };\n Uploader.prototype.wireActionButtonEvents = function () {\n EventHandler.add(this.uploadButton, 'click', this.uploadButtonClick, this);\n EventHandler.add(this.clearButton, 'click', this.clearButtonClick, this);\n };\n Uploader.prototype.unwireActionButtonEvents = function () {\n EventHandler.remove(this.uploadButton, 'click', this.uploadButtonClick);\n EventHandler.remove(this.clearButton, 'click', this.clearButtonClick);\n };\n Uploader.prototype.removeActionButtons = function () {\n if (this.actionButtons) {\n this.unwireActionButtonEvents();\n detach(this.actionButtons);\n this.actionButtons = null;\n }\n };\n Uploader.prototype.renderButtonTemplates = function () {\n if (typeof (this.buttons.browse) === 'string') {\n this.browseButton.innerText = (this.buttons.browse === 'Browse...') ?\n this.localizedTexts('Browse') : this.buttons.browse;\n this.browseButton.setAttribute('title', this.browseButton.innerText);\n }\n else {\n this.browseButton.innerHTML = '';\n this.browseButton.appendChild(this.buttons.browse);\n }\n if (this.uploadButton) {\n var uploadText = void 0;\n uploadText = isNullOrUndefined(this.buttons.upload) ? 'Upload' : this.buttons.upload;\n this.buttons.upload = uploadText;\n if (typeof (this.buttons.upload) === 'string') {\n this.uploadButton.innerText = (this.buttons.upload === 'Upload') ?\n this.localizedTexts('Upload') : this.buttons.upload;\n this.uploadButton.setAttribute('title', this.uploadButton.innerText);\n }\n else {\n this.uploadButton.innerHTML = '';\n this.uploadButton.appendChild(this.buttons.upload);\n }\n }\n if (this.clearButton) {\n var clearText = void 0;\n clearText = isNullOrUndefined(this.buttons.clear) ? 'Clear' : this.buttons.clear;\n this.buttons.clear = clearText;\n if (typeof (this.buttons.clear) === 'string') {\n this.clearButton.innerText = (this.buttons.clear === 'Clear') ?\n this.localizedTexts('Clear') : this.buttons.clear;\n this.clearButton.setAttribute('title', this.clearButton.innerText);\n }\n else {\n this.clearButton.innerHTML = '';\n this.clearButton.appendChild(this.buttons.clear);\n }\n }\n };\n Uploader.prototype.initializeUpload = function () {\n this.element.setAttribute('tabindex', '-1');\n var inputWrapper = this.createElement('span', { className: INPUT_WRAPPER });\n this.element.parentElement.insertBefore(inputWrapper, this.element);\n this.dropAreaWrapper = this.createElement('div', { className: DROP_WRAPPER });\n this.element.parentElement.insertBefore(this.dropAreaWrapper, this.element);\n inputWrapper.appendChild(this.element);\n this.dropAreaWrapper.appendChild(this.browseButton);\n this.dropAreaWrapper.appendChild(inputWrapper);\n var fileDropArea = this.createElement('span', { className: DROP_AREA });\n fileDropArea.innerHTML = this.localizedTexts('dropFilesHint');\n this.dropAreaWrapper.appendChild(fileDropArea);\n this.uploadWrapper = this.createElement('div', { className: CONTROL_WRAPPER, attrs: { 'aria-activedescendant': 'li-focused' } });\n this.dropAreaWrapper.parentElement.insertBefore(this.uploadWrapper, this.dropAreaWrapper);\n this.uploadWrapper.appendChild(this.dropAreaWrapper);\n this.setDropArea();\n };\n Uploader.prototype.renderPreLoadFiles = function () {\n if (isNullOrUndefined(this.files[0].size) || !isNullOrUndefined(this.template)) {\n return;\n }\n var files = [].slice.call(this.files);\n var filesData = [];\n if (!this.multiple) {\n this.clearData();\n files = [files[0]];\n }\n for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {\n var data = files_1[_i];\n var fileData = {\n name: data.name + '.' + data.type.split('.')[data.type.split('.').length - 1],\n rawFile: '',\n size: data.size,\n status: this.localizedTexts('uploadSuccessMessage'),\n type: data.type,\n validationMessages: { minSize: '', maxSize: '' },\n statusCode: '2'\n };\n filesData.push(fileData);\n this.filesData.push(fileData);\n }\n this.createFileList(filesData);\n if (!this.autoUpload && this.listParent && !this.actionButtons && !this.isForm && this.showFileList) {\n this.renderActionButtons();\n }\n this.checkActionButtonStatus();\n };\n Uploader.prototype.checkActionButtonStatus = function () {\n if (this.actionButtons) {\n var length_1 = this.uploadWrapper.querySelectorAll('.' + VALIDATION_FAILS).length +\n this.uploadWrapper.querySelectorAll('.e-upload-fails:not(.e-upload-progress)').length +\n this.uploadWrapper.querySelectorAll('span.' + UPLOAD_SUCCESS).length +\n this.uploadWrapper.querySelectorAll('span.' + UPLOAD_INPROGRESS).length;\n if (length_1 > 0 && length_1 === this.uploadWrapper.querySelectorAll('li').length) {\n this.uploadButton.setAttribute('disabled', 'disabled');\n }\n else {\n this.uploadButton.removeAttribute('disabled');\n }\n }\n };\n Uploader.prototype.setDropArea = function () {\n var dropTextArea = this.dropAreaWrapper.querySelector('.e-file-drop');\n if (this.dropArea) {\n this.dropZoneElement = (typeof (this.dropArea) !== 'string') ? this.dropArea :\n document.querySelector(this.dropArea);\n var element = this.element;\n var enableDropText = false;\n while (element.parentNode) {\n element = element.parentNode;\n if (element === this.dropZoneElement) {\n enableDropText = true;\n dropTextArea.textContent = this.localizedTexts('dropFilesHint');\n }\n }\n if (!enableDropText) {\n dropTextArea.textContent = '';\n }\n }\n else {\n this.dropZoneElement = this.uploadWrapper;\n dropTextArea.textContent = this.localizedTexts('dropFilesHint');\n }\n this.bindDropEvents();\n };\n Uploader.prototype.setMultipleSelection = function () {\n if (this.multiple && !this.element.hasAttribute('multiple')) {\n var newAttr = document.createAttribute('multiple');\n this.element.setAttributeNode(newAttr);\n }\n else if (!this.multiple) {\n this.element.removeAttribute('multiple');\n }\n };\n Uploader.prototype.checkAutoUpload = function (fileData) {\n if (this.autoUpload) {\n this.upload(fileData);\n this.removeActionButtons();\n }\n else if (!this.actionButtons) {\n this.renderActionButtons();\n }\n this.checkActionButtonStatus();\n };\n Uploader.prototype.wireEvents = function () {\n EventHandler.add(this.browseButton, 'click', this.browseButtonClick, this);\n EventHandler.add(this.element, 'change', this.onSelectFiles, this);\n EventHandler.add(document, 'click', this.removeFocus, this);\n this.keyboardModule = new KeyboardEvents(this.uploadWrapper, {\n keyAction: this.keyActionHandler.bind(this),\n keyConfigs: this.keyConfigs,\n eventName: 'keydown',\n });\n if (this.isForm) {\n EventHandler.add(this.formElement, 'reset', this.resetForm, this);\n }\n };\n Uploader.prototype.unWireEvents = function () {\n EventHandler.remove(this.browseButton, 'click', this.browseButtonClick);\n EventHandler.remove(this.element, 'change', this.onSelectFiles);\n EventHandler.remove(document, 'click', this.removeFocus);\n this.keyboardModule.destroy();\n };\n Uploader.prototype.resetForm = function () {\n this.clearAll();\n };\n Uploader.prototype.keyActionHandler = function (e) {\n var targetElement = e.target;\n switch (e.action) {\n case 'next':\n if (e.target === this.browseButton && isNullOrUndefined(this.listParent)) {\n this.browseButton.blur();\n }\n else if (e.target === this.uploadButton) {\n this.uploadButton.blur();\n }\n else {\n this.setTabFocus(e);\n e.preventDefault();\n e.stopPropagation();\n if (e.target === this.clearButton && this.uploadButton.hasAttribute('disabled')) {\n this.clearButton.blur();\n }\n }\n break;\n case 'previous':\n if (e.target === this.browseButton) {\n this.browseButton.blur();\n }\n else {\n this.setReverseFocus(e);\n e.preventDefault();\n e.stopPropagation();\n }\n break;\n case 'enter':\n if (e.target === this.clearButton) {\n this.clearButtonClick();\n }\n else if (e.target === this.uploadButton) {\n this.uploadButtonClick();\n }\n else if (e.target === this.browseButton) {\n this.browseButtonClick();\n }\n else if (targetElement.classList.contains(PAUSE_UPLOAD)) {\n var metaData = this.getCurrentMetaData(null, e);\n metaData.file.statusCode = '4';\n metaData.file.status = this.localizedTexts('pauseUpload');\n this.abortUpload(metaData, false);\n }\n else if (targetElement.classList.contains(RESUME_UPLOAD)) {\n this.resumeUpload(this.getCurrentMetaData(null, e), e);\n }\n else if (targetElement.classList.contains(RETRY_ICON)) {\n var metaData = this.getCurrentMetaData(null, e);\n metaData.file.statusCode = '1';\n metaData.file.status = this.localizedTexts('readyToUploadMessage');\n this.chunkUpload(metaData.file);\n }\n else {\n this.removeFiles(e);\n if (!targetElement.classList.contains(ABORT_ICON)) {\n this.browseButton.focus();\n }\n }\n e.preventDefault();\n e.stopPropagation();\n break;\n }\n };\n Uploader.prototype.getCurrentMetaData = function (fileInfo, e) {\n var fileData;\n var targetMetaData;\n if (isNullOrUndefined(fileInfo)) {\n var target = this.uploadWrapper.querySelector('.' + ICON_FOCUSED).parentElement;\n fileData = this.filesData[this.fileList.indexOf(target)];\n }\n else {\n fileData = fileInfo;\n }\n for (var i = 0; i < this.uploadMetaData.length; i++) {\n if (this.uploadMetaData[i].file.name === fileData.name) {\n targetMetaData = this.uploadMetaData[i];\n }\n }\n return targetMetaData;\n };\n Uploader.prototype.setReverseFocus = function (e) {\n var target = e.target;\n if (target === this.uploadButton) {\n this.uploadButton.blur();\n this.clearButton.focus();\n }\n else if (target === this.clearButton && this.listParent && this.listParent.querySelector('.e-icons')) {\n this.clearButton.blur();\n var items = [].slice.call(this.listParent.querySelectorAll('span.e-icons'));\n items[items.length - 1].classList.add(ICON_FOCUSED);\n items[items.length - 1].focus();\n }\n else {\n var iconElements = [].slice.call(this.listParent.querySelectorAll('span.e-icons'));\n var index = iconElements.indexOf(target);\n if (index > 0) {\n this.removeFocus();\n iconElements[index - 1].classList.add(ICON_FOCUSED);\n iconElements[index - 1].focus();\n }\n else {\n this.removeFocus();\n this.browseButton.focus();\n }\n }\n };\n Uploader.prototype.setTabFocus = function (e) {\n var target = e.target;\n if (target === this.clearButton) {\n this.removeFocus();\n if (this.uploadButton.hasAttribute('disabled')) {\n return;\n }\n this.uploadButton.focus();\n }\n else if (target.classList.contains('e-icons')) {\n var iconElements = [].slice.call(this.listParent.querySelectorAll('span.e-icons'));\n var index = iconElements.indexOf(target);\n if (index < (iconElements.length - 1)) {\n this.removeFocus();\n iconElements[index + 1].classList.add(ICON_FOCUSED);\n iconElements[index + 1].focus();\n }\n else {\n this.removeFocus();\n this.clearButton.focus();\n }\n }\n else {\n this.browseButton.blur();\n var iconElement = this.listParent.querySelectorAll('span.e-icons')[0];\n iconElement.focus();\n iconElement.classList.add(ICON_FOCUSED);\n }\n };\n Uploader.prototype.removeFocus = function () {\n if (this.uploadWrapper && this.listParent && this.listParent.querySelector('.' + ICON_FOCUSED)) {\n document.activeElement.blur();\n this.listParent.querySelector('.' + ICON_FOCUSED).classList.remove(ICON_FOCUSED);\n }\n };\n Uploader.prototype.browseButtonClick = function () {\n this.element.click();\n };\n Uploader.prototype.uploadButtonClick = function () {\n this.upload(this.filesData);\n };\n Uploader.prototype.clearButtonClick = function () {\n this.clearAll();\n };\n Uploader.prototype.bindDropEvents = function () {\n if (this.dropZoneElement) {\n EventHandler.add(this.dropZoneElement, 'drop', this.dropElement, this);\n EventHandler.add(this.dropZoneElement, 'dragover', this.dragHover, this);\n EventHandler.add(this.dropZoneElement, 'dragleave', this.onDragLeave, this);\n }\n };\n Uploader.prototype.unBindDropEvents = function () {\n if (this.dropZoneElement) {\n EventHandler.remove(this.dropZoneElement, 'drop', this.dropElement);\n EventHandler.remove(this.dropZoneElement, 'dragover', this.dragHover);\n EventHandler.remove(this.dropZoneElement, 'dragleave', this.onDragLeave);\n }\n };\n Uploader.prototype.onDragLeave = function (e) {\n this.dropZoneElement.classList.remove(DRAG_HOVER);\n };\n Uploader.prototype.dragHover = function (e) {\n if (!this.enabled) {\n return;\n }\n this.dropZoneElement.classList.add(DRAG_HOVER);\n e.preventDefault();\n e.stopPropagation();\n };\n Uploader.prototype.dropElement = function (e) {\n this.dropZoneElement.classList.remove(DRAG_HOVER);\n this.onSelectFiles(e);\n e.preventDefault();\n e.stopPropagation();\n };\n Uploader.prototype.removeFiles = function (args) {\n if (!this.enabled) {\n return;\n }\n var selectedElement = args.target.parentElement;\n var index = this.fileList.indexOf(selectedElement);\n var liElement = this.fileList[index];\n var fileData = this.filesData[index];\n if (args.target.classList.contains(ABORT_ICON)) {\n if (args.target.classList.contains(DISABLED)) {\n return;\n }\n fileData.statusCode = '5';\n if (!isNullOrUndefined(liElement)) {\n var spinnerTarget = liElement.querySelector('.' + ABORT_ICON);\n createSpinner({ target: spinnerTarget, width: '20px' });\n showSpinner(spinnerTarget);\n }\n }\n else {\n this.remove(fileData, false, false, args);\n }\n this.element.value = '';\n this.checkActionButtonStatus();\n };\n Uploader.prototype.removeFilesData = function (file, customTemplate) {\n var index;\n if (customTemplate) {\n if (!this.showFileList) {\n index = this.filesData.indexOf(file);\n this.filesData.splice(index, 1);\n }\n return;\n }\n var selectedElement = this.getLiElement(file);\n if (isNullOrUndefined(selectedElement)) {\n return;\n }\n detach(selectedElement);\n index = this.fileList.indexOf(selectedElement);\n this.fileList.splice(index, 1);\n this.filesData.splice(index, 1);\n if (this.fileList.length === 0 && !isNullOrUndefined(this.listParent)) {\n detach(this.listParent);\n this.listParent = null;\n this.removeActionButtons();\n }\n };\n Uploader.prototype.removeUploadedFile = function (file, eventArgs, removeDirectly, custom) {\n var _this = this;\n var selectedFiles = file;\n var name = this.element.getAttribute('name');\n var ajax = new Ajax(this.asyncSettings.removeUrl, 'POST', true, null);\n var formData = new FormData();\n ajax.beforeSend = function (e) {\n eventArgs.currentRequest = ajax.httpRequest;\n if (!removeDirectly) {\n _this.trigger('removing', eventArgs);\n }\n if (eventArgs.cancel) {\n e.cancel = true;\n }\n if (eventArgs.postRawFile && !isNullOrUndefined(selectedFiles.rawFile) && selectedFiles.rawFile !== '') {\n formData.append(name, selectedFiles.rawFile);\n }\n else {\n formData.append(name, selectedFiles.name);\n }\n _this.updateFormData(formData, eventArgs.customFormData);\n };\n var liElement = this.getLiElement(file);\n ajax.onLoad = function (e) { _this.removeCompleted(e, selectedFiles, custom); return {}; };\n /* istanbul ignore next */\n ajax.onError = function (e) { _this.removeFailed(e, selectedFiles, custom); return {}; };\n ajax.send(formData);\n if (!isNullOrUndefined(liElement) && !isNullOrUndefined(liElement.querySelector('.' + REMOVE_ICON))) {\n var spinnerTarget = liElement.querySelector('.' + REMOVE_ICON);\n createSpinner({ target: spinnerTarget, width: '20px' });\n showSpinner(spinnerTarget);\n }\n };\n /* istanbul ignore next */\n Uploader.prototype.updateFormData = function (formData, customData) {\n if (customData.length > 0 && customData[0]) {\n var _loop_1 = function (i) {\n var data = customData[i];\n // tslint:disable-next-line\n var value = Object.keys(data).map(function (e) {\n return data[e];\n });\n formData.append(Object.keys(data)[0], value);\n };\n for (var i = 0; i < customData.length; i++) {\n _loop_1(i);\n }\n }\n };\n Uploader.prototype.removeCompleted = function (e, files, customTemplate) {\n var args = {\n e: e, operation: 'remove', file: this.updateStatus(files, this.localizedTexts('removedSuccessMessage'), '2')\n };\n this.trigger('success', args);\n this.removeFilesData(files, customTemplate);\n var index = this.uploadedFilesData.indexOf(files);\n this.uploadedFilesData.splice(index, 1);\n this.trigger('change', { files: this.uploadedFilesData });\n };\n Uploader.prototype.removeFailed = function (e, files, customTemplate) {\n var args = {\n e: e, operation: 'remove', file: this.updateStatus(files, this.localizedTexts('removedFailedMessage'), '0')\n };\n if (!customTemplate) {\n var index = this.filesData.indexOf(files);\n var rootElement = this.fileList[index];\n if (rootElement) {\n var statusElement = rootElement.querySelector('.' + STATUS);\n rootElement.classList.remove(UPLOAD_SUCCESS);\n statusElement.classList.remove(UPLOAD_SUCCESS);\n rootElement.classList.add(UPLOAD_FAILED);\n statusElement.classList.add(UPLOAD_FAILED);\n }\n this.checkActionButtonStatus();\n }\n this.trigger('failure', args);\n var liElement = this.getLiElement(files);\n if (!isNullOrUndefined(liElement) && !isNullOrUndefined(liElement.querySelector('.' + REMOVE_ICON))) {\n var spinnerTarget = liElement.querySelector('.' + REMOVE_ICON);\n hideSpinner(spinnerTarget);\n detach(liElement.querySelector('.e-spinner-pane'));\n }\n };\n Uploader.prototype.onSelectFiles = function (args) {\n if (!this.enabled) {\n return;\n }\n var fileData = [];\n var targetFiles;\n if (args.type === 'drop') {\n var files = args.dataTransfer.files;\n targetFiles = this.multiple ? this.sortFileList(files) : [files[0]];\n }\n else {\n targetFiles = [].slice.call(args.target.files);\n }\n if (!this.multiple) {\n this.clearData(true);\n targetFiles = [targetFiles[0]];\n }\n for (var i = 0; i < targetFiles.length; i++) {\n var file = targetFiles[i];\n var eventArgs_1 = {\n name: file.name,\n rawFile: file,\n size: file.size,\n status: this.localizedTexts('readyToUploadMessage'),\n type: this.getFileType(file.name),\n validationMessages: this.validatedFileSize(file.size),\n statusCode: '1'\n };\n eventArgs_1.status = eventArgs_1.validationMessages.minSize !== '' ? this.localizedTexts('invalidMinFileSize') :\n eventArgs_1.validationMessages.maxSize !== '' ? this.localizedTexts('invalidMaxFileSize') : eventArgs_1.status;\n if (eventArgs_1.validationMessages.minSize !== '' || eventArgs_1.validationMessages.maxSize !== '') {\n eventArgs_1.statusCode = '0';\n }\n fileData.push(eventArgs_1);\n }\n var eventArgs = {\n event: args,\n cancel: false,\n filesData: fileData,\n isModified: false,\n modifiedFilesData: [],\n progressInterval: ''\n };\n if (this.allowedExtensions.indexOf('*') > -1) {\n this.allTypes = true;\n }\n if (!this.allTypes) {\n fileData = this.checkExtension(fileData);\n }\n this.trigger('selected', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n if (this.showFileList) {\n if (eventArgs.isModified && eventArgs.modifiedFilesData.length > 0) {\n var dataFiles = this.allTypes ? eventArgs.modifiedFilesData :\n this.checkExtension(eventArgs.modifiedFilesData);\n this.updateSortedFileList(dataFiles);\n this.filesData = dataFiles;\n if (!this.isForm) {\n this.checkAutoUpload(dataFiles);\n }\n }\n else {\n this.createFileList(fileData);\n this.filesData = this.filesData.concat(fileData);\n if (!this.isForm) {\n this.checkAutoUpload(fileData);\n }\n }\n if (!isNullOrUndefined(eventArgs.progressInterval) && eventArgs.progressInterval !== '') {\n this.progressInterval = eventArgs.progressInterval;\n }\n }\n else {\n this.filesData = this.filesData.concat(fileData);\n if (this.autoUpload) {\n this.upload(this.filesData, true);\n }\n }\n };\n Uploader.prototype.clearData = function (singleUpload) {\n if (!isNullOrUndefined(this.listParent)) {\n detach(this.listParent);\n this.listParent = null;\n }\n if (Browser.info.name !== 'msie' && !singleUpload) {\n this.element.value = '';\n }\n this.fileList = [];\n this.filesData = [];\n this.removeActionButtons();\n };\n Uploader.prototype.updateSortedFileList = function (filesData) {\n var previousListClone = this.createElement('div', { id: 'clonewrapper' });\n var added = -1;\n var removedList;\n if (this.listParent) {\n for (var i = 0; i < this.listParent.querySelectorAll('li').length; i++) {\n var liElement = this.listParent.querySelectorAll('li')[i];\n previousListClone.appendChild(liElement.cloneNode(true));\n }\n removedList = this.listParent.querySelectorAll('li');\n for (var _i = 0, removedList_1 = removedList; _i < removedList_1.length; _i++) {\n var item = removedList_1[_i];\n detach(item);\n }\n this.removeActionButtons();\n var oldList = [].slice.call(previousListClone.childNodes);\n detach(this.listParent);\n this.listParent = null;\n this.fileList = [];\n this.createParentUL();\n for (var index = 0; index < filesData.length; index++) {\n for (var j = 0; j < this.filesData.length; j++) {\n if (this.filesData[j].name === filesData[index].name) {\n this.listParent.appendChild(oldList[j]);\n EventHandler.add(oldList[j].querySelector('.e-icons'), 'click', this.removeFiles, this);\n this.fileList.push(oldList[j]);\n added = index;\n }\n }\n if (added !== index) {\n this.createFileList([filesData[index]]);\n }\n }\n }\n else {\n this.createFileList(filesData);\n }\n };\n Uploader.prototype.checkExtension = function (files) {\n var dropFiles = files;\n if (this.allowedExtensions !== '') {\n var allowedExtensions = [];\n var extensions = this.allowedExtensions.split(',');\n for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {\n var extension = extensions_1[_i];\n allowedExtensions.push(extension.trim().toLocaleLowerCase());\n }\n for (var i = 0; i < files.length; i++) {\n if (allowedExtensions.indexOf(('.' + files[i].type).toLocaleLowerCase()) === -1) {\n files[i].status = this.localizedTexts('invalidFileType');\n files[i].statusCode = '0';\n }\n }\n }\n return dropFiles;\n };\n Uploader.prototype.validatedFileSize = function (fileSize) {\n var minSizeError = '';\n var maxSizeError = '';\n if (fileSize < this.minFileSize) {\n minSizeError = this.localizedTexts('invalidMinFileSize');\n }\n else if (fileSize > this.maxFileSize) {\n maxSizeError = this.localizedTexts('invalidMaxFileSize');\n }\n else {\n minSizeError = '';\n maxSizeError = '';\n }\n var errorMessage = { minSize: minSizeError, maxSize: maxSizeError };\n return errorMessage;\n };\n Uploader.prototype.createCustomfileList = function (fileData) {\n this.createParentUL();\n for (var _i = 0, fileData_1 = fileData; _i < fileData_1.length; _i++) {\n var listItem = fileData_1[_i];\n var liElement = this.createElement('li', { className: FILE, attrs: { 'data-file-name': listItem.name } });\n this.uploadTemplateFn = this.templateComplier(this.template);\n this.listParent.appendChild(liElement);\n var fromElements = [].slice.call(this.uploadTemplateFn(listItem));\n append(fromElements, liElement);\n this.fileList.push(liElement);\n }\n };\n Uploader.prototype.createParentUL = function () {\n if (isNullOrUndefined(this.listParent)) {\n this.listParent = this.createElement('ul', { className: LIST_PARENT });\n this.uploadWrapper.appendChild(this.listParent);\n }\n };\n Uploader.prototype.createFileList = function (fileData) {\n this.createParentUL();\n if (this.template !== '' && !isNullOrUndefined(this.template)) {\n this.createCustomfileList(fileData);\n }\n else {\n for (var _i = 0, fileData_2 = fileData; _i < fileData_2.length; _i++) {\n var listItem = fileData_2[_i];\n var liElement = this.createElement('li', { className: FILE, attrs: { 'data-file-name': listItem.name } });\n var textContainer = this.createElement('span', { className: TEXT_CONTAINER });\n var textElement = this.createElement('span', { className: FILE_NAME, attrs: { 'title': listItem.name } });\n textElement.innerHTML = this.getFileNameOnly(listItem.name);\n var fileExtension = this.createElement('span', { className: FILE_TYPE });\n fileExtension.innerHTML = '.' + this.getFileType(listItem.name);\n if (!this.enableRtl) {\n textContainer.appendChild(textElement);\n textContainer.appendChild(fileExtension);\n }\n else {\n var rtlContainer = this.createElement('span', { className: RTL_CONTAINER });\n rtlContainer.appendChild(fileExtension);\n rtlContainer.appendChild(textElement);\n textContainer.appendChild(rtlContainer);\n }\n var fileSize = this.createElement('span', { className: FILE_SIZE });\n fileSize.innerHTML = this.bytesToSize(listItem.size);\n textContainer.appendChild(fileSize);\n var statusElement = this.createElement('span', { className: STATUS });\n textContainer.appendChild(statusElement);\n statusElement.innerHTML = listItem.status;\n liElement.appendChild(textContainer);\n var iconElement = this.createElement('span', { className: ' e-icons', attrs: { 'tabindex': '-1' } });\n /* istanbul ignore next */\n if (Browser.info.name === 'msie') {\n iconElement.classList.add('e-msie');\n }\n iconElement.setAttribute('title', this.localizedTexts('remove'));\n liElement.appendChild(iconElement);\n EventHandler.add(iconElement, 'click', this.removeFiles, this);\n if (listItem.statusCode === '2') {\n statusElement.classList.add(UPLOAD_SUCCESS);\n iconElement.classList.add(REMOVE_ICON);\n iconElement.setAttribute('title', this.localizedTexts('delete'));\n }\n else if (listItem.statusCode !== '1') {\n statusElement.classList.remove(UPLOAD_SUCCESS);\n statusElement.classList.add(VALIDATION_FAILS);\n }\n if (this.autoUpload && listItem.statusCode === '1' && this.asyncSettings.saveUrl !== '') {\n statusElement.innerHTML = '';\n }\n if (!iconElement.classList.contains(REMOVE_ICON)) {\n iconElement.classList.add(CLEAR_ICON);\n }\n this.listParent.appendChild(liElement);\n this.fileList.push(liElement);\n this.truncateName(textElement);\n }\n }\n };\n Uploader.prototype.truncateName = function (name) {\n var nameElement = name;\n var text;\n if (nameElement.offsetWidth < nameElement.scrollWidth) {\n text = nameElement.textContent;\n nameElement.dataset.tail = text.slice(text.length - 10);\n }\n };\n Uploader.prototype.getFileType = function (name) {\n var extension;\n var index = name.lastIndexOf('.');\n if (index >= 0) {\n extension = name.substring(index + 1);\n }\n return extension ? extension : '';\n };\n Uploader.prototype.getFileNameOnly = function (name) {\n var type = this.getFileType(name);\n var names = name.split('.' + type);\n return type = names[0];\n };\n Uploader.prototype.setInitialAttributes = function () {\n if (this.initialAttr.accept) {\n this.element.setAttribute('accept', this.initialAttr.accept);\n }\n if (this.initialAttr.disabled) {\n this.element.setAttribute('disabled', 'disabled');\n }\n if (this.initialAttr.multiple) {\n var newAttr = document.createAttribute('multiple');\n this.element.setAttributeNode(newAttr);\n }\n };\n Uploader.prototype.filterfileList = function (files) {\n var filterFiles = [];\n var li;\n for (var i = 0; i < files.length; i++) {\n li = this.getLiElement(files[i]);\n if (!li.classList.contains(UPLOAD_SUCCESS)) {\n filterFiles.push(files[i]);\n }\n }\n return filterFiles;\n };\n Uploader.prototype.updateStatus = function (files, status, statusCode) {\n if (!(status === '' || isNullOrUndefined(status)) && !(statusCode === '' || isNullOrUndefined(statusCode))) {\n files.status = status;\n files.statusCode = statusCode;\n }\n var li = this.getLiElement(files);\n if (!isNullOrUndefined(li)) {\n if (!isNullOrUndefined(li.querySelector('.' + STATUS)) && !((status === '' || isNullOrUndefined(status)))) {\n li.querySelector('.' + STATUS).textContent = status;\n }\n }\n return files;\n };\n Uploader.prototype.getLiElement = function (files) {\n var index = this.filesData.indexOf(files);\n return this.fileList[index];\n };\n Uploader.prototype.createProgressBar = function (liElement) {\n var progressbarWrapper = this.createElement('span', { className: PROGRESS_WRAPPER });\n var progressBar = this.createElement('progressbar', { className: PROGRESSBAR, attrs: { value: '0', max: '100' } });\n var progressbarInnerWrapper = this.createElement('span', { className: PROGRESS_INNER_WRAPPER });\n progressBar.setAttribute('style', 'width: 0%');\n var progressbarText = this.createElement('span', { className: PROGRESSBAR_TEXT });\n progressbarText.textContent = '0%';\n progressbarInnerWrapper.appendChild(progressBar);\n progressbarWrapper.appendChild(progressbarInnerWrapper);\n progressbarWrapper.appendChild(progressbarText);\n liElement.querySelector('.' + TEXT_CONTAINER).appendChild(progressbarWrapper);\n };\n /* istanbul ignore next */\n Uploader.prototype.updateProgressbar = function (e, li) {\n if (!isNaN(Math.round((e.loaded / e.total) * 100)) && !isNullOrUndefined(li.querySelector('.' + PROGRESSBAR))) {\n if (!isNullOrUndefined(this.progressInterval) && this.progressInterval !== '') {\n var value = (Math.round((e.loaded / e.total) * 100)) % parseInt(this.progressInterval, 10);\n if (value === 0 || value === 100) {\n this.changeProgressValue(li, Math.round((e.loaded / e.total) * 100).toString() + '%');\n }\n }\n else {\n this.changeProgressValue(li, Math.round((e.loaded / e.total) * 100).toString() + '%');\n }\n }\n };\n Uploader.prototype.changeProgressValue = function (li, progressValue) {\n li.querySelector('.' + PROGRESSBAR).setAttribute('style', 'width:' + progressValue);\n li.querySelector('.' + PROGRESSBAR_TEXT).textContent = progressValue;\n };\n Uploader.prototype.uploadInProgress = function (e, files, customUI, request) {\n var _this = this;\n var li = this.getLiElement(files);\n if (isNullOrUndefined(li) && (!customUI || isNullOrUndefined(customUI))) {\n return;\n }\n if (!isNullOrUndefined(li)) {\n /* istanbul ignore next */\n if (files.statusCode === '5') {\n var eventArgs = {\n event: e,\n fileData: files,\n cancel: false\n };\n this.trigger('canceling', eventArgs);\n if (eventArgs.cancel) {\n files.statusCode = '3';\n var spinnerTarget = li.querySelector('.' + ABORT_ICON);\n if (!isNullOrUndefined(li) && !isNullOrUndefined(spinnerTarget)) {\n hideSpinner(spinnerTarget);\n detach(li.querySelector('.e-spinner-pane'));\n }\n return;\n }\n request.emitError = false;\n request.httpRequest.abort();\n var formData = new FormData();\n if (files.statusCode === '5') {\n var name_1 = this.element.getAttribute('name');\n formData.append(name_1, files.name);\n formData.append('cancel-uploading', files.name);\n var ajax = new Ajax(this.asyncSettings.removeUrl, 'POST', true, null);\n ajax.onLoad = function (e) { _this.removecanceledFile(e, files); return {}; };\n ajax.send(formData);\n }\n }\n if (!(li.querySelectorAll('.' + PROGRESS_WRAPPER).length > 0) && li.querySelector('.' + STATUS)) {\n li.querySelector('.' + STATUS).classList.add(UPLOAD_INPROGRESS);\n this.createProgressBar(li);\n this.updateProgressBarClasses(li, UPLOAD_INPROGRESS);\n li.querySelector('.' + STATUS).classList.remove(UPLOAD_FAILED);\n }\n this.updateProgressbar(e, li);\n var iconEle = li.querySelector('.' + CLEAR_ICON);\n if (!isNullOrUndefined(iconEle)) {\n iconEle.classList.add(ABORT_ICON, UPLOAD_INPROGRESS);\n iconEle.setAttribute('title', this.localizedTexts('abort'));\n iconEle.classList.remove(CLEAR_ICON);\n }\n }\n var args = { e: e, operation: 'upload', file: this.updateStatus(files, this.localizedTexts('inProgress'), '3') };\n this.trigger('progress', args);\n };\n Uploader.prototype.removecanceledFile = function (e, file) {\n var liElement = this.getLiElement(file);\n if (liElement.querySelector('.' + RETRY_ICON) || isNullOrUndefined(liElement.querySelector('.' + ABORT_ICON))) {\n return;\n }\n this.updateStatus(file, this.localizedTexts('fileUploadCancel'), '5');\n this.renderFailureState(e, file, liElement);\n var spinnerTarget = liElement.querySelector('.' + CLEAR_ICON);\n if (!isNullOrUndefined(liElement)) {\n hideSpinner(spinnerTarget);\n detach(liElement.querySelector('.e-spinner-pane'));\n }\n var args = { event: e, operation: 'cancel', file: file };\n this.trigger('success', args);\n };\n Uploader.prototype.renderFailureState = function (e, file, liElement) {\n var _this = this;\n this.updateProgressBarClasses(liElement, UPLOAD_FAILED);\n this.removeProgressbar(liElement, 'failure');\n if (!isNullOrUndefined(liElement.querySelector('.e-file-status'))) {\n liElement.querySelector('.e-file-status').classList.add(UPLOAD_FAILED);\n }\n var deleteIcon = liElement.querySelector('.' + ABORT_ICON);\n if (isNullOrUndefined(deleteIcon)) {\n return;\n }\n deleteIcon.classList.remove(ABORT_ICON, UPLOAD_INPROGRESS);\n deleteIcon.classList.add(CLEAR_ICON);\n deleteIcon.setAttribute('title', this.localizedTexts('remove'));\n this.pauseButton = this.createElement('span', { className: 'e-icons e-file-reload-btn', attrs: { 'tabindex': '-1' } });\n liElement.insertBefore(this.pauseButton, deleteIcon);\n this.pauseButton.setAttribute('title', this.localizedTexts('retry'));\n var retryElement = liElement.querySelector('.' + RETRY_ICON);\n /* istanbul ignore next */\n retryElement.addEventListener('click', function (e) { _this.reloadcanceledFile(e, file, liElement); }, false);\n };\n Uploader.prototype.reloadcanceledFile = function (e, file, liElement) {\n file.statusCode = '1';\n file.status = this.localizedTexts('readyToUploadMessage');\n liElement.querySelector('.' + STATUS).classList.remove(UPLOAD_FAILED);\n if (!isNullOrUndefined(liElement.querySelector('.' + RETRY_ICON))) {\n detach(liElement.querySelector('.' + RETRY_ICON));\n }\n this.pauseButton = null;\n this.upload([file]);\n };\n /* istanbul ignore next */\n Uploader.prototype.uploadComplete = function (e, file, customUI) {\n var status = e.target;\n if (status.readyState === 4 && status.status >= 200 && status.status <= 299) {\n var li = this.getLiElement(file);\n if (isNullOrUndefined(li) && (!customUI || isNullOrUndefined(customUI))) {\n return;\n }\n if (!isNullOrUndefined(li)) {\n this.updateProgressBarClasses(li, UPLOAD_SUCCESS);\n this.removeProgressbar(li, 'success');\n var iconEle = li.querySelector('.' + ABORT_ICON);\n if (!isNullOrUndefined(iconEle)) {\n iconEle.classList.add(REMOVE_ICON);\n iconEle.setAttribute('title', this.localizedTexts('delete'));\n iconEle.classList.remove(ABORT_ICON);\n iconEle.classList.remove(UPLOAD_INPROGRESS);\n }\n }\n this.raiseSuccessEvent(e, file);\n }\n else {\n this.uploadFailed(e, file);\n }\n };\n Uploader.prototype.raiseSuccessEvent = function (e, file) {\n var args = { e: e, operation: 'upload', file: this.updateStatus(file, this.localizedTexts('uploadSuccessMessage'), '2') };\n this.trigger('success', args);\n this.uploadedFilesData.push(file);\n this.trigger('change', { file: this.uploadedFilesData });\n this.checkActionButtonStatus();\n };\n Uploader.prototype.uploadFailed = function (e, file) {\n var li = this.getLiElement(file);\n var args = { e: e, operation: 'upload', file: this.updateStatus(file, this.localizedTexts('uploadFailedMessage'), '0') };\n if (!isNullOrUndefined(li)) {\n this.renderFailureState(e, file, li);\n }\n this.trigger('failure', args);\n this.checkActionButtonStatus();\n };\n Uploader.prototype.updateProgressBarClasses = function (li, className) {\n var progressBar = li.querySelector('.' + PROGRESSBAR);\n if (!isNullOrUndefined(progressBar)) {\n progressBar.classList.add(className);\n }\n };\n Uploader.prototype.removeProgressbar = function (li, callType) {\n var _this = this;\n if (!isNullOrUndefined(li.querySelector('.' + PROGRESS_WRAPPER))) {\n this.progressAnimation = new Animation({ duration: 1250 });\n this.progressAnimation.animate(li.querySelector('.' + PROGRESS_WRAPPER), { name: 'FadeOut' });\n this.progressAnimation.animate(li.querySelector('.' + PROGRESSBAR_TEXT), { name: 'FadeOut' });\n setTimeout(function () { _this.animateProgressBar(li, callType); }, 750);\n }\n };\n /* istanbul ignore next */\n Uploader.prototype.animateProgressBar = function (li, callType) {\n if (callType === 'success') {\n li.classList.add(UPLOAD_SUCCESS);\n if (!isNullOrUndefined(li.querySelector('.' + STATUS))) {\n li.querySelector('.' + STATUS).classList.remove(UPLOAD_INPROGRESS);\n this.progressAnimation.animate(li.querySelector('.' + STATUS), { name: 'FadeIn' });\n li.querySelector('.' + STATUS).classList.add(UPLOAD_SUCCESS);\n }\n }\n else {\n if (!isNullOrUndefined(li.querySelector('.' + STATUS))) {\n li.querySelector('.' + STATUS).classList.remove(UPLOAD_INPROGRESS);\n this.progressAnimation.animate(li.querySelector('.' + STATUS), { name: 'FadeIn' });\n li.querySelector('.' + STATUS).classList.add(UPLOAD_FAILED);\n }\n }\n if (li.querySelector('.' + PROGRESS_WRAPPER)) {\n detach(li.querySelector('.' + PROGRESS_WRAPPER));\n }\n };\n Uploader.prototype.setExtensions = function (extensions) {\n this.element.setAttribute('accept', extensions);\n };\n Uploader.prototype.templateComplier = function (uploadTemplate) {\n if (uploadTemplate) {\n var exception = void 0;\n try {\n if (document.querySelectorAll(uploadTemplate).length) {\n return compile(document.querySelector(uploadTemplate).innerHTML.trim());\n }\n }\n catch (exception) {\n return compile(uploadTemplate);\n }\n }\n return undefined;\n };\n Uploader.prototype.setRTL = function () {\n this.enableRtl ? addClass([this.uploadWrapper], RTL) : removeClass([this.uploadWrapper], RTL);\n };\n Uploader.prototype.localizedTexts = function (localeText) {\n this.l10n.setLocale(this.locale);\n return this.l10n.getConstant(localeText);\n };\n Uploader.prototype.setControlStatus = function () {\n if (!this.enabled) {\n this.uploadWrapper.classList.add(DISABLED);\n this.element.setAttribute('disabled', 'disabled');\n this.browseButton.setAttribute('disabled', 'disabled');\n if (!isNullOrUndefined(this.clearButton)) {\n this.clearButton.setAttribute('disabled', 'disabled');\n }\n if (!isNullOrUndefined(this.uploadButton)) {\n this.uploadButton.setAttribute('disabled', 'disabled');\n }\n }\n else {\n if (this.uploadWrapper.classList.contains(DISABLED)) {\n this.uploadWrapper.classList.remove(DISABLED);\n }\n if (!isNullOrUndefined(this.browseButton) && this.element.hasAttribute('disabled')) {\n this.element.removeAttribute('disabled');\n this.browseButton.removeAttribute('disabled');\n }\n if (!isNullOrUndefined(this.clearButton) && this.clearButton.hasAttribute('disabled')) {\n this.clearButton.removeAttribute('disabled');\n }\n if (!isNullOrUndefined(this.uploadButton) && this.uploadButton.hasAttribute('disabled')) {\n this.uploadButton.hasAttribute('disabled');\n }\n }\n };\n Uploader.prototype.checkHTMLAttributes = function () {\n if (this.element.hasAttribute('accept')) {\n this.allowedExtensions = this.element.getAttribute('accept');\n this.initialAttr.accept = this.allowedExtensions;\n }\n if (this.element.hasAttribute('multiple')) {\n this.multiple = true;\n this.initialAttr.multiple = true;\n }\n if (this.element.hasAttribute('disabled')) {\n this.enabled = false;\n this.initialAttr.disabled = true;\n }\n };\n Uploader.prototype.chunkUpload = function (file, custom) {\n var start = 0;\n var end = Math.min(this.asyncSettings.chunkSize, file.size);\n var index = 0;\n var blob = file.rawFile.slice(start, end);\n var metaData = { chunkIndex: index, blob: blob, file: file, start: start, end: end, retryCount: 0, request: null };\n this.sendRequest(file, metaData, custom);\n };\n Uploader.prototype.sendRequest = function (file, metaData, custom) {\n var _this = this;\n var formData = new FormData();\n var blob = file.rawFile.slice(metaData.start, metaData.end);\n formData.append('chunkFile', blob, file.name);\n formData.append('chunk-index', metaData.chunkIndex.toString());\n var totalChunk = Math.max(Math.ceil(file.size / this.asyncSettings.chunkSize), 1);\n formData.append('total-chunk', totalChunk.toString());\n var ajax = new Ajax({ url: this.asyncSettings.saveUrl, type: 'POST', async: true, contentType: null });\n ajax.onLoad = function (e) { _this.chunkUploadComplete(e, metaData, custom); return {}; };\n ajax.onUploadProgress = function (e) {\n _this.chunkUploadInProgress(e, metaData, custom);\n return {};\n };\n var eventArgs = {\n fileData: file,\n customFormData: [],\n cancel: false,\n chunkSize: this.asyncSettings.chunkSize === 0 ? null : this.asyncSettings.chunkSize\n };\n ajax.beforeSend = function (e) {\n if (metaData.chunkIndex !== 0) {\n return;\n }\n eventArgs.currentRequest = ajax.httpRequest;\n _this.trigger('uploading', eventArgs);\n if (eventArgs.cancel) {\n _this.eventCancelByArgs(e, eventArgs, file);\n }\n else {\n _this.updateFormData(formData, eventArgs.customFormData);\n }\n };\n /* istanbul ignore next */\n ajax.onError = function (e) { _this.chunkUploadFailed(e, metaData, custom); return {}; };\n ajax.send(formData);\n metaData.request = ajax;\n };\n Uploader.prototype.eventCancelByArgs = function (e, eventArgs, file) {\n var _this = this;\n e.cancel = true;\n if (eventArgs.fileData.statusCode === '5') {\n return;\n }\n var liElement = this.getLiElement(eventArgs.fileData);\n liElement.querySelector('.' + STATUS).innerHTML = this.localizedTexts('fileUploadCancel');\n liElement.querySelector('.' + STATUS).classList.add(UPLOAD_FAILED);\n eventArgs.fileData.statusCode = '5';\n eventArgs.fileData.status = this.localizedTexts('fileUploadCancel');\n this.pauseButton = this.createElement('span', { className: 'e-icons e-file-reload-btn', attrs: { 'tabindex': '-1' } });\n liElement.insertBefore(this.pauseButton, liElement.querySelector('.' + CLEAR_ICON));\n this.pauseButton.setAttribute('title', this.localizedTexts('retry'));\n /* istanbul ignore next */\n this.pauseButton.addEventListener('click', function (e) { _this.reloadcanceledFile(e, file, liElement); }, false);\n this.checkActionButtonStatus();\n };\n Uploader.prototype.checkChunkUpload = function () {\n return (this.asyncSettings.chunkSize <= 0 || isNullOrUndefined(this.asyncSettings.chunkSize)) ? false : true;\n };\n Uploader.prototype.chunkUploadComplete = function (e, metaData, custom) {\n var _this = this;\n var response = e.target;\n var liElement;\n if (response.readyState === 4 && response.status >= 200 && response.status < 300) {\n var totalChunk = Math.max(Math.ceil(metaData.file.size / this.asyncSettings.chunkSize), 1);\n var eventArgs = {\n event: e,\n file: metaData.file,\n chunkIndex: metaData.chunkIndex,\n totalChunk: totalChunk,\n chunkSize: this.asyncSettings.chunkSize\n };\n this.trigger('chunkSuccess', eventArgs);\n if (isNullOrUndefined(custom) || !custom) {\n liElement = this.getLiElement(metaData.file);\n }\n this.updateMetaData(metaData);\n if (metaData.end === metaData.file.size) {\n metaData.file.statusCode = '3';\n }\n if (metaData.file.statusCode === '5') {\n var eventArgs_2 = { event: e, fileData: metaData.file, cancel: false };\n this.trigger('canceling', eventArgs_2);\n if (eventArgs_2.cancel) {\n metaData.file.statusCode = '3';\n var spinnerTarget = liElement.querySelector('.' + ABORT_ICON);\n if (!isNullOrUndefined(liElement) && !isNullOrUndefined(spinnerTarget)) {\n hideSpinner(spinnerTarget);\n detach(liElement.querySelector('.e-spinner-pane'));\n }\n this.sendNextRequest(metaData);\n return;\n }\n metaData.request.emitError = false;\n response.abort();\n var formData = new FormData();\n var name_2 = this.element.getAttribute('name');\n formData.append(name_2, metaData.file.name);\n formData.append('cancel-uploading', metaData.file.name);\n var ajax = new Ajax(this.asyncSettings.removeUrl, 'POST', true, null);\n ajax.onLoad = function (e) { _this.removeChunkFile(e, metaData, custom); return {}; };\n ajax.send(formData);\n }\n else {\n if ((totalChunk - 1) === metaData.chunkIndex && totalChunk > metaData.chunkIndex) {\n var index = this.pausedData.indexOf(metaData);\n if (index >= 0) {\n this.pausedData.splice(index, 1);\n }\n if (isNullOrUndefined(this.template) && (isNullOrUndefined(custom) || !custom) && liElement) {\n if (liElement) {\n detach(liElement.querySelector('.' + PAUSE_UPLOAD));\n }\n this.removeChunkProgressBar(metaData);\n }\n this.raiseSuccessEvent(e, metaData.file);\n return;\n }\n this.sendNextRequest(metaData);\n }\n }\n else {\n this.chunkUploadFailed(e, metaData);\n }\n };\n Uploader.prototype.sendNextRequest = function (metaData) {\n metaData.start = metaData.end;\n metaData.end += this.asyncSettings.chunkSize;\n metaData.end = Math.min(metaData.end, metaData.file.size);\n metaData.chunkIndex += 1;\n this.sendRequest(metaData.file, metaData);\n };\n Uploader.prototype.removeChunkFile = function (e, metaData, custom) {\n if (isNullOrUndefined(this.template) && (isNullOrUndefined(custom) && !custom)) {\n var liElement = this.getLiElement(metaData.file);\n var deleteIcon = liElement.querySelector('.' + ABORT_ICON);\n var spinnerTarget = deleteIcon;\n this.updateStatus(metaData.file, this.localizedTexts('fileUploadCancel'), '5');\n this.updateProgressBarClasses(liElement, UPLOAD_FAILED);\n this.removeProgressbar(liElement, 'failure');\n deleteIcon.classList.remove(ABORT_ICON);\n deleteIcon.classList.add(CLEAR_ICON);\n deleteIcon.setAttribute('title', this.localizedTexts('remove'));\n var pauseIcon = liElement.querySelector('.' + PAUSE_UPLOAD);\n pauseIcon.classList.add(RETRY_ICON);\n pauseIcon.classList.remove(PAUSE_UPLOAD);\n pauseIcon.setAttribute('title', this.localizedTexts('retry'));\n if (!isNullOrUndefined(liElement) && !isNullOrUndefined(deleteIcon)) {\n hideSpinner(spinnerTarget);\n detach(liElement.querySelector('.e-spinner-pane'));\n }\n }\n };\n Uploader.prototype.pauseUpload = function (metaData, e, custom) {\n metaData.file.statusCode = '4';\n metaData.file.status = this.localizedTexts('pause');\n this.updateMetaData(metaData);\n var eventArgs = {\n event: e ? e : null,\n file: metaData.file,\n chunkIndex: metaData.chunkIndex,\n chunkCount: Math.round(metaData.file.size / this.asyncSettings.chunkSize),\n chunkSize: this.asyncSettings.chunkSize\n };\n this.abortUpload(metaData, custom, eventArgs);\n };\n Uploader.prototype.abortUpload = function (metaData, custom, eventArgs) {\n metaData.request.emitError = false;\n metaData.request.httpRequest.abort();\n var liElement = this.getLiElement(metaData.file);\n if (isNullOrUndefined(this.template) && (isNullOrUndefined(custom) || !custom)) {\n var targetElement = liElement.querySelector('.' + PAUSE_UPLOAD);\n targetElement.classList.remove(PAUSE_UPLOAD);\n targetElement.classList.add(RESUME_UPLOAD);\n targetElement.setAttribute('title', this.localizedTexts('resume'));\n }\n for (var i = 0; i < this.pausedData.length; i++) {\n if (this.pausedData[i].file.name === metaData.file.name) {\n this.pausedData.splice(i, 1);\n }\n }\n this.pausedData.push(metaData);\n this.trigger('pausing', eventArgs);\n };\n Uploader.prototype.resumeUpload = function (metaData, e, custom) {\n var liElement = this.getLiElement(metaData.file);\n var targetElement;\n if (!isNullOrUndefined(liElement)) {\n targetElement = liElement.querySelector('.' + RESUME_UPLOAD);\n }\n if (!isNullOrUndefined(targetElement) && (isNullOrUndefined(custom) || !custom)) {\n targetElement.classList.remove(RESUME_UPLOAD);\n targetElement.classList.add(PAUSE_UPLOAD);\n targetElement.setAttribute('title', this.localizedTexts('pause'));\n }\n metaData.file.status = this.localizedTexts('inProgress');\n metaData.file.statusCode = '3';\n this.updateMetaData(metaData);\n var eventArgs = {\n event: e ? e : null,\n file: metaData.file,\n chunkIndex: metaData.chunkIndex,\n chunkCount: Math.round(metaData.file.size / this.asyncSettings.chunkSize),\n chunkSize: this.asyncSettings.chunkSize\n };\n this.trigger('resuming', eventArgs);\n for (var i = 0; i < this.pausedData.length; i++) {\n if (this.pausedData[i].end === this.pausedData[i].file.size) {\n this.chunkUploadComplete(e, metaData, custom);\n }\n else {\n if (this.pausedData[i].file.name === metaData.file.name) {\n this.pausedData[i].start = this.pausedData[i].end;\n this.pausedData[i].end = this.pausedData[i].end + this.asyncSettings.chunkSize;\n this.pausedData[i].end = Math.min(this.pausedData[i].end, this.pausedData[i].file.size);\n this.pausedData[i].chunkIndex = this.pausedData[i].chunkIndex + 1;\n this.sendRequest(this.pausedData[i].file, this.pausedData[i], custom);\n }\n }\n }\n };\n Uploader.prototype.updateMetaData = function (metaData) {\n if (this.uploadMetaData.indexOf(metaData) === -1) {\n this.uploadMetaData.push(metaData);\n }\n else {\n this.uploadMetaData.splice(this.uploadMetaData.indexOf(metaData), 1);\n this.uploadMetaData.push(metaData);\n }\n };\n Uploader.prototype.removeChunkProgressBar = function (metaData) {\n var liElement = this.getLiElement(metaData.file);\n if (!isNullOrUndefined(liElement)) {\n this.updateProgressBarClasses(liElement, UPLOAD_SUCCESS);\n this.removeProgressbar(liElement, 'success');\n var cancelButton = liElement.querySelector('.' + ABORT_ICON);\n if (!isNullOrUndefined(cancelButton)) {\n cancelButton.classList.add(REMOVE_ICON);\n cancelButton.setAttribute('title', this.localizedTexts('delete'));\n cancelButton.classList.remove(ABORT_ICON, UPLOAD_INPROGRESS);\n }\n }\n };\n Uploader.prototype.chunkUploadFailed = function (e, metaData, custom) {\n var _this = this;\n var chunkCount = Math.max(Math.ceil(metaData.file.size / this.asyncSettings.chunkSize), 1);\n var liElement;\n if (isNullOrUndefined(this.template) && (isNullOrUndefined(custom) || !custom)) {\n liElement = this.getLiElement(metaData.file);\n }\n var eventArgs = {\n event: e,\n file: metaData.file,\n chunkIndex: metaData.chunkIndex,\n totalChunk: chunkCount,\n chunkSize: this.asyncSettings.chunkSize\n };\n this.trigger('chunkFailure', eventArgs);\n if (metaData.retryCount < this.asyncSettings.retryCount) {\n setTimeout(function () { _this.retryRequest(liElement, metaData, custom); }, this.asyncSettings.retryAfterDelay);\n }\n else {\n if (!isNullOrUndefined(liElement)) {\n var pauseButton = liElement.querySelector('.' + PAUSE_UPLOAD) ?\n liElement.querySelector('.' + PAUSE_UPLOAD) : liElement.querySelector('.' + RESUME_UPLOAD);\n if (!isNullOrUndefined(pauseButton)) {\n pauseButton.classList.add(RETRY_ICON);\n pauseButton.classList.remove(PAUSE_UPLOAD, RESUME_UPLOAD);\n }\n this.updateProgressBarClasses(liElement, UPLOAD_FAILED);\n this.removeProgressbar(liElement, 'failure');\n liElement.querySelector('.e-icons').classList.remove(UPLOAD_INPROGRESS);\n var iconElement = liElement.querySelector('.' + ABORT_ICON);\n iconElement.classList.remove(ABORT_ICON);\n if (!isNullOrUndefined(liElement.querySelector('.' + PAUSE_UPLOAD))) {\n detach(liElement.querySelector('.' + PAUSE_UPLOAD));\n }\n if (metaData.start > 0) {\n iconElement.classList.add(REMOVE_ICON);\n iconElement.setAttribute('title', this.localizedTexts('delete'));\n }\n else {\n iconElement.classList.add(CLEAR_ICON);\n iconElement.setAttribute('title', this.localizedTexts('remove'));\n }\n }\n metaData.retryCount = 0;\n var file = metaData.file;\n var args = { e: e, operation: 'upload', file: this.updateStatus(file, this.localizedTexts('uploadFailedMessage'), '0') };\n this.trigger('failure', args);\n }\n };\n Uploader.prototype.retryRequest = function (liElement, metaData, custom) {\n if (isNullOrUndefined(this.template) && (isNullOrUndefined(custom) || !custom) && liElement) {\n this.updateProgressBarClasses(liElement, UPLOAD_FAILED);\n }\n metaData.retryCount += 1;\n this.sendRequest(metaData.file, metaData);\n };\n Uploader.prototype.checkPausePlayAction = function (e) {\n var targetElement = e.target;\n var selectedElement = e.target.parentElement;\n var index = this.fileList.indexOf(selectedElement);\n var fileData = this.filesData[index];\n var metaData = this.getCurrentMetaData(fileData);\n if (targetElement.classList.contains(PAUSE_UPLOAD)) {\n this.pauseUpload(metaData, e);\n targetElement.nextElementSibling.classList.add(DISABLED);\n }\n else if (targetElement.classList.contains(RESUME_UPLOAD)) {\n this.resumeUpload(metaData, e);\n targetElement.nextElementSibling.classList.remove(DISABLED);\n }\n else if (targetElement.classList.contains(RETRY_ICON)) {\n if (metaData.file.status === this.localizedTexts('fileUploadCancel')) {\n this.retryUpload(metaData, false);\n }\n else {\n this.retryUpload(metaData, true);\n }\n }\n };\n Uploader.prototype.retryUpload = function (metaData, fromcanceledStage) {\n if (fromcanceledStage) {\n metaData.end = metaData.end + this.asyncSettings.chunkSize;\n metaData.start = metaData.start + this.asyncSettings.chunkSize;\n this.sendRequest(metaData.file, metaData);\n }\n else {\n metaData.file.statusCode = '1';\n metaData.file.status = this.localizedTexts('readyToUploadMessage');\n this.chunkUpload(metaData.file);\n }\n };\n Uploader.prototype.chunkUploadInProgress = function (e, metaData, custom) {\n var _this = this;\n if (metaData.file.statusCode === '4') {\n return;\n }\n if (metaData.file.statusCode !== '4' && metaData.file.statusCode !== '5') {\n metaData.file.statusCode = '3';\n metaData.file.status = this.localizedTexts('inProgress');\n }\n this.updateMetaData(metaData);\n var liElement = this.getLiElement(metaData.file);\n if (isNullOrUndefined(liElement)) {\n return;\n }\n var target;\n var retryElement = liElement.querySelector('.' + RETRY_ICON);\n if (!isNullOrUndefined(retryElement)) {\n retryElement.classList.add(PAUSE_UPLOAD);\n retryElement.setAttribute('title', this.localizedTexts('pause'));\n retryElement.classList.remove(RETRY_ICON);\n }\n if (!isNullOrUndefined(liElement)) {\n if (!(liElement.querySelectorAll('.' + PROGRESS_WRAPPER).length > 0)) {\n var statusElement = liElement.querySelector('.' + STATUS);\n if (isNullOrUndefined(this.template)) {\n statusElement.classList.add(UPLOAD_INPROGRESS);\n statusElement.classList.remove(UPLOAD_FAILED);\n this.createProgressBar(liElement);\n this.updateProgressBarClasses(liElement, UPLOAD_INPROGRESS);\n }\n var clearIcon = liElement.querySelector('.' + CLEAR_ICON) ? liElement.querySelector('.' + CLEAR_ICON) :\n liElement.querySelector('.' + REMOVE_ICON);\n if (!isNullOrUndefined(clearIcon)) {\n clearIcon.classList.add(ABORT_ICON);\n clearIcon.setAttribute('title', this.localizedTexts('abort'));\n clearIcon.classList.remove(CLEAR_ICON);\n }\n }\n if (!isNaN(Math.round((e.loaded / e.total) * 100)) && isNullOrUndefined(this.template) && metaData.file.statusCode !== '4') {\n var loadedSize = (metaData.chunkIndex * this.asyncSettings.chunkSize);\n var value = Math.min((((loadedSize + e.loaded) / metaData.file.size) * 100), 100);\n this.changeProgressValue(liElement, Math.round(value).toString() + '%');\n }\n if (metaData.chunkIndex === 0) {\n this.checkActionButtonStatus();\n }\n }\n if (isNullOrUndefined(liElement.querySelector('.' + PAUSE_UPLOAD)) && isNullOrUndefined(this.template)) {\n this.pauseButton = this.createElement('span', { className: 'e-icons e-file-pause-btn', attrs: { 'tabindex': '-1' } });\n if (Browser.info.name === 'msie') {\n this.pauseButton.classList.add('e-msie');\n }\n liElement.insertBefore(this.pauseButton, liElement.querySelector('.' + ABORT_ICON));\n this.pauseButton.setAttribute('title', this.localizedTexts('pause'));\n this.pauseButton.addEventListener('click', function (e) { _this.checkPausePlayAction(e); }, false);\n }\n };\n /**\n * It is used to convert bytes value into kilobytes or megabytes depending on the size based\n * on [binary prefix](https://en.wikipedia.org/wiki/Binary_prefix).\n * @param { number } bytes - specifies the file size in bytes.\n * @returns string\n */\n Uploader.prototype.bytesToSize = function (bytes) {\n var i = -1;\n var size;\n if (!bytes) {\n return '0.0 KB';\n }\n do {\n bytes = bytes / 1024;\n i++;\n } while (bytes > 99);\n if (i >= 2) {\n bytes = bytes * 1024;\n i = 1;\n }\n return Math.max(bytes, 0).toFixed(1) + ' ' + ['KB', 'MB'][i];\n };\n /**\n * Allows you to sort the file data alphabetically based on its file name clearly.\n * @param { FileList } filesData - specifies the files data for upload.\n * @returns File[]\n */\n Uploader.prototype.sortFileList = function (filesData) {\n var files = filesData;\n var fileNames = [];\n for (var i = 0; i < files.length; i++) {\n fileNames.push(files[i].name);\n }\n var sortedFileNames = fileNames.sort();\n var sortedFilesData = [];\n var index = 0;\n for (var _i = 0, sortedFileNames_1 = sortedFileNames; _i < sortedFileNames_1.length; _i++) {\n var name_3 = sortedFileNames_1[_i];\n for (var i = 0; i < files.length; i++) {\n if (name_3 === files[i].name) {\n sortedFilesData.push(files[i]);\n }\n }\n }\n return sortedFilesData;\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers. Also it removes the attributes and classes.\n * @method destroy\n * @return {void}.\n */\n Uploader.prototype.destroy = function () {\n this.element.value = null;\n this.clearAll();\n this.unWireEvents();\n this.unBindDropEvents();\n if (this.multiple) {\n this.element.removeAttribute('multiple');\n }\n if (!this.enabled) {\n this.element.removeAttribute('disabled');\n }\n this.element.removeAttribute('accept');\n this.setInitialAttributes();\n this.uploadWrapper.parentElement.appendChild(this.cloneElement);\n this.cloneElement.classList.remove('e-control', ROOT);\n detach(this.uploadWrapper);\n this.uploadWrapper = null;\n _super.prototype.destroy.call(this);\n };\n /**\n * Allows you to call the upload process manually by calling save URL action.\n * To process the selected files (added in upload queue), pass an empty argument otherwise\n * upload the specific file based on its argument.\n * @param { FileInfo | FileInfo[] } files - specifies the files data for upload.\n * @returns void\n */\n Uploader.prototype.upload = function (files, custom) {\n var uploadFiles = this.validateFileType(files);\n this.uploadFiles(uploadFiles, custom);\n };\n Uploader.prototype.validateFileType = function (files) {\n var uploadFiles = [];\n if (files instanceof Array) {\n uploadFiles = files;\n }\n else {\n uploadFiles.push(files);\n }\n return uploadFiles;\n };\n Uploader.prototype.uploadFiles = function (files, custom) {\n var _this = this;\n var selectedFiles = [];\n if (this.asyncSettings.saveUrl === '' || isNullOrUndefined(this.asyncSettings.saveUrl)) {\n return;\n }\n if (!custom || isNullOrUndefined(custom)) {\n if (!this.multiple) {\n var file = [];\n file.push(files[0]);\n selectedFiles = this.filterfileList(file);\n }\n else {\n selectedFiles = this.filterfileList(files);\n }\n }\n else {\n selectedFiles = files;\n }\n var chunkEnabled = this.checkChunkUpload();\n var _loop_2 = function (i) {\n var ajax = new Ajax(this_1.asyncSettings.saveUrl, 'POST', true, null);\n var eventArgs = {\n fileData: selectedFiles[i],\n customFormData: [],\n cancel: false\n };\n var formData = new FormData();\n ajax.beforeSend = function (e) {\n eventArgs.currentRequest = ajax.httpRequest;\n _this.trigger('uploading', eventArgs);\n if (eventArgs.cancel) {\n _this.eventCancelByArgs(e, eventArgs, selectedFiles[i]);\n }\n _this.updateFormData(formData, eventArgs.customFormData);\n };\n if (selectedFiles[i].statusCode === '1') {\n var name_4 = this_1.element.getAttribute('name');\n formData.append(name_4, selectedFiles[i].rawFile, selectedFiles[i].name);\n if (chunkEnabled && selectedFiles[i].size > this_1.asyncSettings.chunkSize) {\n this_1.chunkUpload(selectedFiles[i], custom);\n }\n else {\n ajax.onLoad = function (e) { _this.uploadComplete(e, selectedFiles[i], custom); return {}; };\n ajax.onUploadProgress = function (e) {\n _this.uploadInProgress(e, selectedFiles[i], custom, ajax);\n return {};\n };\n /* istanbul ignore next */\n ajax.onError = function (e) { _this.uploadFailed(e, selectedFiles[i]); return {}; };\n ajax.send(formData);\n }\n }\n };\n var this_1 = this;\n for (var i = 0; i < selectedFiles.length; i++) {\n _loop_2(i);\n }\n };\n /**\n * Remove the uploaded file from server manually by calling the remove URL action.\n * If you pass an empty argument to this method, the complete file list can be cleared,\n * otherwise remove the specific file based on its argument (“file_data”).\n * @param { FileInfo | FileInfo[] } fileData - specifies the files data to remove from file list/server.\n * @param { boolean } customTemplate - Set true if the component rendering with customize template.\n * @param { boolean } removeDirectly - Set true if files remove without removing event.\n * @returns void\n */\n Uploader.prototype.remove = function (fileData, customTemplate, removeDirectly, args) {\n var eventArgs = {\n event: args,\n cancel: false,\n filesData: [],\n customFormData: [],\n postRawFile: true\n };\n if (this.isForm) {\n eventArgs.filesData = this.getFilesData();\n this.trigger('removing', eventArgs);\n if (!eventArgs.cancel) {\n this.clearAll();\n }\n return;\n }\n var removeFiles = [];\n fileData = !isNullOrUndefined(fileData) ? fileData : this.filesData;\n if (fileData instanceof Array) {\n removeFiles = fileData;\n }\n else {\n removeFiles.push(fileData);\n }\n eventArgs.filesData = removeFiles;\n var removeUrl = this.asyncSettings.removeUrl;\n var validUrl = (removeUrl === '' || isNullOrUndefined(removeUrl)) ? false : true;\n for (var _i = 0, removeFiles_1 = removeFiles; _i < removeFiles_1.length; _i++) {\n var files = removeFiles_1[_i];\n if ((files.statusCode === '2' || files.statusCode === '4') && validUrl) {\n this.removeUploadedFile(files, eventArgs, removeDirectly, customTemplate);\n }\n else {\n if (!removeDirectly) {\n this.trigger('removing', eventArgs);\n }\n if (eventArgs.cancel) {\n return;\n }\n this.removeFilesData(files, customTemplate);\n }\n }\n };\n /**\n * Clear all the file entries from list that can be uploaded files or added in upload queue.\n * @returns void\n */\n Uploader.prototype.clearAll = function () {\n if (isNullOrUndefined(this.listParent)) {\n if (Browser.info.name !== 'msie') {\n this.element.value = '';\n }\n this.filesData = [];\n return;\n }\n var eventArgs = {\n cancel: false,\n filesData: this.filesData\n };\n this.trigger('clearing', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.clearData();\n };\n /**\n * Get the data of files which are shown in file list.\n * @returns FileInfo[]\n */\n Uploader.prototype.getFilesData = function () {\n return this.filesData;\n };\n /**\n * Pauses the in-progress chunked upload based on the file data.\n * @param { FileInfo | FileInfo[] } fileData - specifies the files data to pause from uploading.\n * @param { boolean } custom - Set true if used custom UI.\n * @returns void\n */\n Uploader.prototype.pause = function (fileData, custom) {\n var fileDataFiles = this.validateFileType(fileData);\n this.pauseUploading(fileDataFiles, custom);\n };\n Uploader.prototype.pauseUploading = function (fileData, custom) {\n var files = this.getFiles(fileData);\n for (var i = 0; i < files.length; i++) {\n if (files[i].statusCode === '3') {\n this.pauseUpload(this.getCurrentMetaData(files[i], null), null, custom);\n }\n }\n };\n Uploader.prototype.getFiles = function (fileData) {\n var files = [];\n if (!isNullOrUndefined(fileData) && !(fileData instanceof Array)) {\n files.push(fileData);\n }\n else {\n files = fileData;\n }\n return files;\n };\n /**\n * Resumes the chunked upload that is previously paused based on the file data.\n * @param { FileInfo | FileInfo[] } fileData - specifies the files data to resume the paused file.\n * @param { boolean } custom - Set true if used custom UI.\n * @returns void\n */\n Uploader.prototype.resume = function (fileData, custom) {\n var fileDataFiles = this.validateFileType(fileData);\n this.resumeFiles(fileDataFiles, custom);\n };\n Uploader.prototype.resumeFiles = function (fileData, custom) {\n var files = this.getFiles(fileData);\n for (var i = 0; i < files.length; i++) {\n if (files[i].statusCode === '4') {\n this.resumeUpload(this.getCurrentMetaData(files[i], null), null, custom);\n }\n }\n };\n /**\n * Retries the canceled or failed file upload based on the file data.\n * @param { FileInfo | FileInfo[] } fileData - specifies the files data to retry the canceled or failed file.\n * @param { boolean } fromcanceledStage - Set true to retry from canceled stage and set false to retry from initial stage.\n * @returns void\n */\n Uploader.prototype.retry = function (fileData, fromcanceledStage) {\n var fileDataFiles = this.validateFileType(fileData);\n this.retryFailedFiles(fileDataFiles, fromcanceledStage);\n };\n Uploader.prototype.retryFailedFiles = function (fileData, fromcanceledStage) {\n var files = this.getFiles(fileData);\n for (var i = 0; i < files.length; i++) {\n if (files[i].statusCode === '5' || files[i].statusCode === '0') {\n if (this.asyncSettings.chunkSize > 0) {\n this.retryUpload(this.getCurrentMetaData(files[i], null), fromcanceledStage);\n }\n else {\n var liElement = this.fileList[this.filesData.indexOf(files[i])];\n this.reloadcanceledFile(null, files[i], liElement);\n }\n }\n }\n };\n /**\n * Stops the in-progress chunked upload based on the file data.\n * When the file upload is canceled, the partially uploaded file is removed from server.\n * @param { FileInfo | FileInfo[] } fileData - specifies the files data to cancel the progressing file.\n * @returns void\n */\n Uploader.prototype.cancel = function (fileData) {\n var fileDataFiles = this.validateFileType(fileData);\n this.cancelUpload(fileDataFiles);\n };\n Uploader.prototype.cancelUpload = function (fileData) {\n var files = this.getFiles(fileData);\n for (var i = 0; i < files.length; i++) {\n if (files[i].statusCode === '3') {\n var metaData = this.getCurrentMetaData(files[i], null);\n metaData.file.statusCode = '5';\n metaData.file.status = this.localizedTexts('fileUploadCancel');\n this.updateMetaData(metaData);\n var liElement = this.getLiElement(files[i]);\n if (!isNullOrUndefined(liElement) && isNullOrUndefined(this.template)) {\n var spinnerTarget = liElement.querySelector('.' + ABORT_ICON);\n createSpinner({ target: spinnerTarget, width: '20px' });\n showSpinner(spinnerTarget);\n }\n }\n }\n };\n __decorate([\n Complex({ saveUrl: '', removeUrl: '' }, AsyncSettings)\n ], Uploader.prototype, \"asyncSettings\", void 0);\n __decorate([\n Property(false)\n ], Uploader.prototype, \"enableRtl\", void 0);\n __decorate([\n Property(true)\n ], Uploader.prototype, \"enabled\", void 0);\n __decorate([\n Property(null)\n ], Uploader.prototype, \"template\", void 0);\n __decorate([\n Property(true)\n ], Uploader.prototype, \"multiple\", void 0);\n __decorate([\n Property(true)\n ], Uploader.prototype, \"autoUpload\", void 0);\n __decorate([\n Complex({}, ButtonsProps)\n ], Uploader.prototype, \"buttons\", void 0);\n __decorate([\n Property('')\n ], Uploader.prototype, \"allowedExtensions\", void 0);\n __decorate([\n Property(0)\n ], Uploader.prototype, \"minFileSize\", void 0);\n __decorate([\n Property(30000000)\n ], Uploader.prototype, \"maxFileSize\", void 0);\n __decorate([\n Property(null)\n ], Uploader.prototype, \"dropArea\", void 0);\n __decorate([\n Collection([{}], FilesProp)\n ], Uploader.prototype, \"files\", void 0);\n __decorate([\n Property(true)\n ], Uploader.prototype, \"showFileList\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"selected\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"uploading\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"success\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"failure\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"removing\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"clearing\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"progress\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"chunkSuccess\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"chunkFailure\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"canceling\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"pausing\", void 0);\n __decorate([\n Event()\n ], Uploader.prototype, \"resuming\", void 0);\n Uploader = __decorate([\n NotifyPropertyChanges\n ], Uploader);\n return Uploader;\n}(Component));\nexport { Uploader };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Collection, Event, NotifyPropertyChanges, detach, Property, EventHandler } from '@syncfusion/ej2-base';\nimport { addClass, getUniqueID, rippleEffect } from '@syncfusion/ej2-base';\nimport { attributes, Component, closest, select } from '@syncfusion/ej2-base';\nimport { classList, removeClass } from '@syncfusion/ej2-base';\nimport { Button } from '@syncfusion/ej2-buttons';\nimport { Popup } from '@syncfusion/ej2-popups';\nimport { getModel, Item } from './../common/common';\nvar classNames = {\n DISABLED: 'e-disabled',\n FOCUS: 'e-focused',\n ICON: 'e-menu-icon',\n ITEM: 'e-item',\n POPUP: 'e-dropdown-popup',\n RTL: 'e-rtl',\n SEPARATOR: 'e-separator',\n VERTICAL: 'e-vertical'\n};\n/**\n * DropDownButton component is used to toggle contextual overlays for displaying list of action items.\n * It can contain both text and images.\n * ``````html\n *
DropDownButton \n * ```\n * ```typescript\n * \n * ```\n */\nvar DropDownButton = /** @class */ (function (_super) {\n __extends(DropDownButton, _super);\n /**\n * Constructor for creating the widget\n * @param {DropDownButtonModel} options?\n * @param {string|HTMLButtonElement} element?\n */\n function DropDownButton(options, element) {\n return _super.call(this, options, element) || this;\n }\n DropDownButton.prototype.preRender = function () {\n /** */\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @returns string\n */\n DropDownButton.prototype.getPersistData = function () {\n return this.addOnPersist([]);\n };\n /**\n * To open/close DropDownButton popup based on current state of the DropDownButton.\n * @returns void\n */\n DropDownButton.prototype.toggle = function () {\n this.canOpen() ? this.openPopUp() : this.closePopup();\n };\n /**\n * Initialize the Component rendering\n * @returns void\n * @private\n */\n DropDownButton.prototype.render = function () {\n this.initialize();\n if (!this.disabled) {\n this.wireEvents();\n }\n };\n DropDownButton.prototype.createPopup = function () {\n var div = this.createElement('div', {\n className: classNames.POPUP,\n id: this.element.id + '-popup'\n });\n document.body.appendChild(div);\n this.dropDown = new Popup(div, {\n relateTo: this.element,\n collision: { X: 'fit', Y: 'flip' },\n position: { X: 'left', Y: 'bottom' },\n targetType: 'relative',\n content: this.target ? this.getTargetElement() : '',\n enableRtl: this.enableRtl\n });\n if (this.dropDown.element.style.position === 'fixed') {\n this.dropDown.refreshPosition(this.element);\n }\n this.dropDown.hide();\n attributes(this.element, (_a = {},\n _a['role'] = 'menu',\n _a['aria-haspopup'] = this.items.length || this.target ? 'true' : 'false',\n _a['aria-expanded'] = 'false',\n _a['aria-owns'] = this.getPopUpElement().id,\n _a['type'] = 'button',\n _a));\n if (this.cssClass) {\n addClass([div], this.cssClass.split(' '));\n }\n var _a;\n };\n DropDownButton.prototype.getTargetElement = function () {\n return typeof (this.target) === 'string' ? select(this.target) : this.target;\n };\n DropDownButton.prototype.createItems = function (items) {\n var showIcon = this.hasIcon(items, 'iconCss');\n var span;\n var item;\n var li;\n var eventArgs;\n var ul = this.createElement('ul', {\n attrs: { 'tabindex': '0' }\n });\n for (var i = 0; i < items.length; i++) {\n item = items[i];\n li = this.createElement('li', {\n innerHTML: item.url ? '' : item.text,\n className: item.separator ? classNames.ITEM + ' ' + classNames.SEPARATOR : classNames.ITEM,\n attrs: { 'role': 'menuItem', 'tabindex': '-1' },\n id: item.id ? item.id : getUniqueID('e-' + this.getModuleName() + '-item')\n });\n if (item.iconCss) {\n span = this.createElement('span', { className: classNames.ICON + ' ' + item.iconCss });\n li.insertBefore(span, li.childNodes[0]);\n }\n else {\n if (showIcon && !item.separator) {\n li.classList.add('e-blank-icon');\n }\n }\n if (item.url) {\n li.appendChild(this.createAnchor(item));\n }\n eventArgs = { item: item, element: li };\n this.trigger('beforeItemRender', eventArgs);\n ul.appendChild(li);\n }\n return ul;\n };\n DropDownButton.prototype.hasIcon = function (items, field) {\n for (var i = 0, len = items.length; i < len; i++) {\n if (items[i][field]) {\n return true;\n }\n }\n return false;\n };\n DropDownButton.prototype.createAnchor = function (item) {\n return this.createElement('a', { className: 'e-menu-text e-menu-url', innerHTML: item.text, attrs: { 'href': item.url } });\n };\n DropDownButton.prototype.initialize = function () {\n this.button = new Button({\n iconCss: this.iconCss, cssClass: this.cssClass, content: this.content,\n disabled: this.disabled, enableRtl: this.enableRtl, enablePersistence: this.enablePersistence\n });\n this.button.appendTo(this.element);\n if (!this.element.id) {\n this.element.id = getUniqueID('e-' + this.getModuleName());\n }\n this.setIconPositionTop();\n this.appendArrowSpan();\n this.createPopup();\n this.setActiveElem([this.element]);\n };\n DropDownButton.prototype.setIconPositionTop = function () {\n var iconSpan = this.element.querySelector('.e-icon-left');\n if (iconSpan && this.iconPosition === 'Top') {\n addClass([this.element], 'e-top-icon-btn');\n removeClass([iconSpan], 'e-icon-left');\n addClass([iconSpan], 'e-icon-top');\n }\n };\n DropDownButton.prototype.appendArrowSpan = function () {\n this.element.appendChild(this.createElement('span', {\n className: 'e-btn-icon e-icons ' + 'e-icon-' + (this.cssClass.indexOf(classNames.VERTICAL) > -1\n ? 'bottom' : 'right') + ' e-caret'\n }));\n };\n DropDownButton.prototype.setActiveElem = function (elem) {\n this.activeElem = elem;\n };\n /**\n * Get component name.\n * @returns string\n * @private\n */\n DropDownButton.prototype.getModuleName = function () {\n return 'dropdown-btn';\n };\n DropDownButton.prototype.canOpen = function () {\n return this.getPopUpElement().classList.contains('e-popup-close');\n };\n /**\n * Destroys the widget.\n * @returns void\n */\n DropDownButton.prototype.destroy = function () {\n var _this = this;\n if (this.element.querySelector('span.e-caret')) {\n detach(this.element.querySelector('span.e-caret'));\n }\n _super.prototype.destroy.call(this);\n this.button.destroy();\n ['role', 'aria-haspopup', 'aria-expanded', 'aria-owns', 'type'].forEach(function (key) {\n _this.element.removeAttribute(key);\n });\n removeClass([this.element], ['e-btn']);\n removeClass(this.activeElem, ['e-active']);\n this.dropDown.destroy();\n var popupEle = document.getElementById(this.getPopUpElement().id);\n if (popupEle) {\n removeClass([popupEle], ['e-popup-open', 'e-popup-close']);\n detach(popupEle);\n }\n if (!this.disabled) {\n this.unWireEvents();\n }\n };\n DropDownButton.prototype.getPopUpElement = function () {\n return this.dropDown.element;\n };\n DropDownButton.prototype.getULElement = function () {\n return this.getPopUpElement().children[0];\n };\n DropDownButton.prototype.wireEvents = function () {\n var popupElement = this.getPopUpElement();\n this.delegateMousedownHandler = this.mousedownHandler.bind(this);\n EventHandler.add(document, 'mousedown touchstart', this.delegateMousedownHandler, this);\n EventHandler.add(this.element, 'click', this.clickHandler, this);\n EventHandler.add(popupElement, 'click', this.clickHandler, this);\n EventHandler.add(this.element, 'keydown', this.keyBoardHandler, this);\n EventHandler.add(popupElement, 'keydown', this.keyBoardHandler, this);\n this.rippleFn = rippleEffect(popupElement, { selector: '.' + classNames.ITEM });\n };\n DropDownButton.prototype.keyBoardHandler = function (e) {\n if (e.target === this.element && (e.keyCode === 9 || (!e.altKey && e.keyCode === 40) || e.keyCode === 38)) {\n return;\n }\n switch (e.keyCode) {\n case 38:\n case 40:\n if (e.altKey && (e.keyCode === 38 || e.keyCode === 40)) {\n this.keyEventHandler(e);\n }\n else {\n this.upDownKeyHandler(e);\n }\n break;\n case 9:\n case 13:\n case 27:\n case 32:\n this.keyEventHandler(e);\n break;\n }\n };\n DropDownButton.prototype.upDownKeyHandler = function (e) {\n if (this.target && (e.keyCode === 38 || e.keyCode === 40)) {\n return;\n }\n e.preventDefault();\n var ul = this.getULElement();\n var defaultIdx = e.keyCode === 40 ? 0 : ul.childElementCount - 1;\n var liIdx = defaultIdx;\n var li = null;\n this.removeCustomSelection();\n for (var i = 0, len = ul.children.length; i < len; i++) {\n if (ul.children[i].classList.contains(classNames.FOCUS)) {\n li = ul.children[i];\n liIdx = i;\n li.classList.remove(classNames.FOCUS);\n e.keyCode === 40 ? liIdx++ : liIdx--;\n if (liIdx === (e.keyCode === 40 ? ul.childElementCount : -1)) {\n liIdx = defaultIdx;\n }\n }\n }\n li = ul.children[liIdx];\n liIdx = this.isValidLI(li, liIdx, e.keyCode);\n if (liIdx !== -1) {\n addClass([ul.children[liIdx]], classNames.FOCUS);\n ul.children[liIdx].focus();\n }\n };\n DropDownButton.prototype.removeCustomSelection = function () {\n var selectedLi = this.getULElement().querySelector('.e-selected');\n if (selectedLi) {\n selectedLi.classList.remove('e-selected');\n }\n };\n DropDownButton.prototype.isValidLI = function (li, index, keyCode, count) {\n if (count === void 0) { count = 0; }\n if (li.classList.contains(classNames.SEPARATOR) || li.classList.contains(classNames.DISABLED)) {\n if (index === (keyCode === 40 ? this.items.length - 1 : 0)) {\n index = keyCode === 40 ? 0 : this.items.length - 1;\n }\n else {\n keyCode === 40 ? index++ : index--;\n }\n }\n li = this.getULElement().children[index];\n if (li.classList.contains(classNames.SEPARATOR) || li.classList.contains(classNames.DISABLED)) {\n count++;\n if (count === this.items.length) {\n return index = -1;\n }\n index = this.isValidLI(li, index, keyCode, count);\n }\n return index;\n };\n DropDownButton.prototype.keyEventHandler = function (e) {\n if (this.target && (e.keyCode === 13 || e.keyCode === 9)) {\n return;\n }\n if (e.keyCode !== 9) {\n e.preventDefault();\n }\n if (e.keyCode === 27 || e.keyCode === 38 || e.keyCode === 9) {\n if (!this.canOpen()) {\n this.closePopup(e, this.element);\n }\n }\n else {\n this.clickHandler(e);\n }\n };\n DropDownButton.prototype.getLI = function (elem) {\n return elem.tagName === 'LI' ? elem : closest(elem, 'li');\n };\n DropDownButton.prototype.mousedownHandler = function (e) {\n var trgt = e.target;\n if (!this.canOpen() && !(closest(trgt, '#' + this.getPopUpElement().id) || closest(trgt, '#' + this.element.id))) {\n this.closePopup(e);\n }\n };\n DropDownButton.prototype.clickHandler = function (e) {\n var trgt = e.target;\n var canOpen = this.canOpen();\n if (closest(trgt, '#' + this.element.id)) {\n if (canOpen) {\n this.openPopUp(e);\n }\n else {\n this.closePopup(e, this.activeElem[0]);\n }\n }\n else {\n if (closest(trgt, '#' + this.getPopUpElement().id)) {\n var eventArgs = void 0;\n var liIdx = void 0;\n var item = void 0;\n var li = this.getLI(trgt);\n if (li) {\n liIdx = Array.prototype.indexOf.call(this.getULElement().children, li);\n item = this.items[liIdx];\n if (item) {\n eventArgs = { element: li, item: item };\n this.trigger('select', eventArgs);\n }\n this.closePopup(e, this.activeElem[0]);\n }\n }\n }\n };\n DropDownButton.prototype.openPopUp = function (e) {\n if (e === void 0) { e = null; }\n if (!this.target) {\n this.getPopUpElement().appendChild(this.createItems(this.items));\n }\n var ul = this.getULElement();\n var beforeOpenArgs = { element: ul, items: this.items, event: e, cancel: false };\n this.trigger('beforeOpen', beforeOpenArgs);\n if (!beforeOpenArgs.cancel) {\n this.dropDown.show(null, this.element);\n addClass([this.element], 'e-active');\n this.element.setAttribute('aria-expanded', 'true');\n ul.focus();\n var openArgs = { element: ul, items: this.items };\n this.trigger('open', openArgs);\n }\n };\n DropDownButton.prototype.closePopup = function (e, focusEle) {\n if (e === void 0) { e = null; }\n var ul = this.getULElement();\n var beforeCloseArgs = { element: ul, items: this.items, event: e, cancel: false };\n this.trigger('beforeClose', beforeCloseArgs);\n if (!beforeCloseArgs.cancel) {\n this.removeCustomSelection();\n this.dropDown.hide();\n removeClass(this.activeElem, 'e-active');\n this.element.setAttribute('aria-expanded', 'false');\n if (focusEle) {\n focusEle.focus();\n }\n var closeArgs = { element: ul, items: this.items };\n this.trigger('close', closeArgs);\n if (!this.target && ul) {\n detach(ul);\n }\n }\n };\n DropDownButton.prototype.unWireEvents = function () {\n EventHandler.remove(document, 'mousedown touchstart', this.delegateMousedownHandler);\n EventHandler.remove(this.element, 'click', this.clickHandler);\n EventHandler.remove(this.getPopUpElement(), 'click', this.clickHandler);\n EventHandler.remove(this.element, 'keydown', this.keyBoardHandler);\n EventHandler.remove(this.getPopUpElement(), 'keydown', this.keyBoardHandler);\n this.rippleFn();\n };\n /**\n * Called internally if any of the property value changed.\n * @param {DropDownButtonModel} newProp\n * @param {DropDownButtonModel} oldProp\n * @returns void\n * @private\n */\n DropDownButton.prototype.onPropertyChanged = function (newProp, oldProp) {\n var btnModel = ['content', 'cssClass', 'iconCss', 'disabled', 'enableRtl'];\n if (newProp.iconPosition === 'Left') {\n btnModel.push('iconPosition');\n }\n this.button.setProperties(getModel(newProp, btnModel));\n var popupElement = this.getPopUpElement();\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'content':\n if (!this.element.querySelector('span.e-caret')) {\n this.appendArrowSpan();\n }\n break;\n case 'disabled':\n if (newProp.disabled) {\n this.unWireEvents();\n if (!this.canOpen()) {\n this.closePopup();\n }\n }\n else {\n this.wireEvents();\n }\n break;\n case 'cssClass':\n if (newProp.cssClass.indexOf(classNames.VERTICAL) > -1) {\n var arrowSpan = this.element.querySelector('span.e-caret');\n classList(arrowSpan, ['e-icon-bottom'], ['e-icon-right']);\n }\n if (oldProp.cssClass) {\n removeClass([popupElement], oldProp.cssClass.split(' '));\n }\n if (newProp.cssClass) {\n addClass([popupElement], newProp.cssClass.split(' '));\n }\n break;\n case 'iconPosition':\n this.setIconPositionTop();\n break;\n case 'enableRtl':\n popupElement.classList.toggle(classNames.RTL);\n break;\n case 'target':\n this.target = newProp.target;\n detach(this.getULElement());\n popupElement.appendChild(this.getTargetElement());\n this.dropDown.content = this.getTargetElement();\n break;\n case 'items':\n this.dropDown.refresh();\n if (popupElement.classList.contains('e-popup-open')) {\n classList(popupElement, ['e-popup-close'], ['e-popup-open']);\n }\n break;\n }\n }\n };\n __decorate([\n Property('')\n ], DropDownButton.prototype, \"content\", void 0);\n __decorate([\n Property('')\n ], DropDownButton.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], DropDownButton.prototype, \"disabled\", void 0);\n __decorate([\n Property('')\n ], DropDownButton.prototype, \"iconCss\", void 0);\n __decorate([\n Property('Left')\n ], DropDownButton.prototype, \"iconPosition\", void 0);\n __decorate([\n Collection([], Item)\n ], DropDownButton.prototype, \"items\", void 0);\n __decorate([\n Property('')\n ], DropDownButton.prototype, \"target\", void 0);\n __decorate([\n Event()\n ], DropDownButton.prototype, \"beforeItemRender\", void 0);\n __decorate([\n Event()\n ], DropDownButton.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], DropDownButton.prototype, \"beforeClose\", void 0);\n __decorate([\n Event()\n ], DropDownButton.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], DropDownButton.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], DropDownButton.prototype, \"select\", void 0);\n DropDownButton = __decorate([\n NotifyPropertyChanges\n ], DropDownButton);\n return DropDownButton;\n}(Component));\nexport { DropDownButton };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n///
\nimport { Event, remove, addClass, removeClass, detach, getValue, setValue } from '@syncfusion/ej2-base';\nimport { EventHandler, Collection, NotifyPropertyChanges, Property } from '@syncfusion/ej2-base';\nimport { attributes, getUniqueID, getInstance, KeyboardEvents } from '@syncfusion/ej2-base';\nimport { Button } from '@syncfusion/ej2-buttons';\nimport { getModel, Item } from './../common/common';\nimport { DropDownButton } from '../drop-down-button/drop-down-button';\nvar RTL = 'e-rtl';\nvar TAGNAME = 'EJS-SPLITBUTTON';\n/**\n * SplitButton component has primary and secondary button. Primary button is used to select\n * default action and secondary button is used to toggle contextual overlays for displaying list of\n * action items. It can contain both text and images.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar SplitButton = /** @class */ (function (_super) {\n __extends(SplitButton, _super);\n /**\n * Constructor for creating the widget\n * @param {SplitButtonModel} options?\n * @param {string|HTMLButtonElement} element?\n */\n function SplitButton(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * Initialize Angular support.\n * @private\n */\n SplitButton.prototype.preRender = function () {\n var ele = this.element;\n if (ele.tagName === TAGNAME) {\n var ejInstance = getValue('ej2_instances', ele);\n var btn = this.createElement('button', { attrs: { 'type': 'button' } });\n var wrapper = this.createElement(TAGNAME, { className: 'e-' + this.getModuleName() + '-wrapper' });\n for (var idx = 0, len = ele.attributes.length; idx < len; idx++) {\n btn.setAttribute(ele.attributes[idx].nodeName, ele.attributes[idx].nodeValue);\n }\n ele.parentNode.insertBefore(wrapper, ele);\n detach(ele);\n ele = btn;\n wrapper.appendChild(ele);\n setValue('ej2_instances', ejInstance, ele);\n this.wrapper = wrapper;\n this.element = ele;\n }\n if (!this.element.id) {\n this.element.id = getUniqueID('e-' + this.getModuleName());\n }\n };\n SplitButton.prototype.render = function () {\n this.initWrapper();\n this.createPrimaryButton();\n this.createSecondaryButton();\n this.setActiveElem([this.element, this.secondaryBtnObj.element]);\n this.setAria();\n this.wireEvents();\n };\n SplitButton.prototype.initWrapper = function () {\n if (!this.wrapper) {\n this.wrapper = this.createElement('div', { className: 'e-' + this.getModuleName() + '-wrapper' });\n this.element.parentNode.insertBefore(this.wrapper, this.element);\n }\n this.element.classList.remove('e-' + this.getModuleName());\n if (this.enableRtl) {\n this.wrapper.classList.add(RTL);\n }\n if (this.cssClass) {\n addClass([this.wrapper], this.cssClass.split(' '));\n }\n };\n SplitButton.prototype.createPrimaryButton = function () {\n var btnModel = {\n cssClass: this.cssClass,\n enableRtl: this.enableRtl,\n iconCss: this.iconCss,\n content: this.content,\n disabled: this.disabled\n };\n this.primaryBtnObj = new Button(btnModel, this.element);\n this.element.classList.add('e-' + this.getModuleName());\n this.element.type = 'button';\n this.wrapper.appendChild(this.element);\n this.setIconPositionTop();\n };\n SplitButton.prototype.createSecondaryButton = function () {\n var _this = this;\n var btnElem = this.createElement('button', {\n className: 'e-icon-btn',\n attrs: { 'tabindex': '-1' },\n id: this.element.id + '_dropdownbtn'\n });\n this.wrapper.appendChild(btnElem);\n var dropDownBtnModel = {\n cssClass: this.cssClass,\n disabled: this.disabled,\n enableRtl: this.enableRtl,\n items: this.items,\n target: this.target,\n beforeItemRender: function (args) {\n _this.trigger('beforeItemRender', args);\n },\n beforeOpen: function (args) {\n _this.trigger('beforeOpen', args);\n },\n beforeClose: function (args) {\n _this.trigger('beforeClose', args);\n },\n open: function (args) {\n _this.trigger('open', args);\n },\n close: function (args) {\n _this.trigger('close', args);\n },\n select: function (args) {\n _this.trigger('select', args);\n }\n };\n this.secondaryBtnObj = new DropDownButton(dropDownBtnModel, btnElem);\n this.secondaryBtnObj.dropDown.relateTo = this.wrapper;\n this.dropDown = this.secondaryBtnObj.dropDown;\n this.secondaryBtnObj.activeElem = [this.element, this.secondaryBtnObj.element];\n EventHandler.remove(this.getPopUpElement(), 'keydown', this.secondaryBtnObj.keyBoardHandler);\n this.secondaryBtnObj.element.querySelector('.e-btn-icon').classList.remove('e-icon-right');\n };\n SplitButton.prototype.setAria = function () {\n attributes(this.element, {\n 'role': 'listbox', 'aria-expanded': 'false', 'aria-haspopup': 'true',\n 'aria-label': this.element.textContent + ' splitbutton', 'aria-owns': this.secondaryBtnObj.dropDown.element.id\n });\n };\n /**\n * Get component name.\n * @returns string\n * @private\n */\n SplitButton.prototype.getModuleName = function () {\n return 'split-btn';\n };\n /**\n * To open/close SplitButton popup based on current state of the SplitButton.\n * @returns void\n */\n SplitButton.prototype.toggle = function () {\n this.secondaryBtnObj.toggle();\n };\n SplitButton.prototype.destroy = function () {\n var _this = this;\n this.primaryBtnObj.destroy();\n this.secondaryBtnObj.destroy();\n var element = document.getElementById(this.element.id);\n if (element && element.parentElement === this.wrapper) {\n if (this.wrapper.tagName === TAGNAME) {\n this.wrapper.innerHTML = '';\n removeClass([this.wrapper], ['e-rtl', 'e-' + this.getModuleName() + '-wrapper']);\n removeClass([this.wrapper], this.cssClass.split(' '));\n }\n else {\n removeClass([this.element], ['e-' + this.getModuleName(), RTL]);\n ['role', 'aria-label', 'aria-haspopup', 'aria-expanded', 'aria-owns', 'type'].forEach(function (key) {\n _this.element.removeAttribute(key);\n });\n this.wrapper.parentNode.insertBefore(this.element, this.wrapper);\n remove(this.wrapper);\n }\n this.unWireEvents();\n }\n };\n SplitButton.prototype.wireEvents = function () {\n EventHandler.add(this.element, 'click', this.primaryBtnClickHandler, this);\n EventHandler.add(this.getPopUpElement(), 'keydown', this.keyBoardHandler, this);\n new KeyboardEvents(this.element, {\n keyAction: this.btnKeyBoardHandler.bind(this),\n keyConfigs: {\n altdownarrow: 'alt+downarrow'\n }\n });\n };\n SplitButton.prototype.unWireEvents = function () {\n EventHandler.remove(this.element, 'click', this.primaryBtnClickHandler);\n getInstance(this.element, KeyboardEvents).destroy();\n };\n SplitButton.prototype.primaryBtnClickHandler = function () {\n this.trigger('click', { element: this.element });\n };\n SplitButton.prototype.btnKeyBoardHandler = function (e) {\n switch (e.action) {\n case 'altdownarrow':\n this.clickHandler(e);\n break;\n }\n };\n /**\n * Called internally if any of the property value changed.\n * @param {SplitButtonModel} newProp\n * @param {SplitButtonModel} oldProp\n * @returns void\n */\n SplitButton.prototype.onPropertyChanged = function (newProp, oldProp) {\n var model = ['content', 'iconCss', 'cssClass', 'disabled', 'enableRtl'];\n if (newProp.iconPosition === 'Left') {\n model.push('iconPosition');\n }\n this.primaryBtnObj.setProperties(getModel(newProp, model));\n model = ['items', 'beforeOpen', 'beforeItemRender', 'select', 'open',\n 'close', 'cssClass', 'disabled', 'enableRtl'];\n this.secondaryBtnObj.setProperties(getModel(newProp, model));\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'cssClass':\n if (oldProp.cssClass) {\n removeClass([this.wrapper], oldProp.cssClass.split(' '));\n }\n addClass([this.wrapper], newProp.cssClass.split(' '));\n break;\n case 'iconPosition':\n this.setIconPositionTop();\n break;\n case 'enableRtl':\n if (newProp.enableRtl) {\n addClass([this.wrapper], RTL);\n }\n else {\n removeClass([this.wrapper], RTL);\n }\n break;\n }\n }\n };\n __decorate([\n Property('')\n ], SplitButton.prototype, \"content\", void 0);\n __decorate([\n Property('')\n ], SplitButton.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], SplitButton.prototype, \"disabled\", void 0);\n __decorate([\n Property('')\n ], SplitButton.prototype, \"iconCss\", void 0);\n __decorate([\n Property('Left')\n ], SplitButton.prototype, \"iconPosition\", void 0);\n __decorate([\n Collection([], Item)\n ], SplitButton.prototype, \"items\", void 0);\n __decorate([\n Property('')\n ], SplitButton.prototype, \"target\", void 0);\n __decorate([\n Event()\n ], SplitButton.prototype, \"beforeItemRender\", void 0);\n __decorate([\n Event()\n ], SplitButton.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], SplitButton.prototype, \"beforeClose\", void 0);\n __decorate([\n Event()\n ], SplitButton.prototype, \"click\", void 0);\n __decorate([\n Event()\n ], SplitButton.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], SplitButton.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], SplitButton.prototype, \"select\", void 0);\n SplitButton = __decorate([\n NotifyPropertyChanges\n ], SplitButton);\n return SplitButton;\n}(DropDownButton));\nexport { SplitButton };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Event, NotifyPropertyChanges, Property } from '@syncfusion/ej2-base';\nimport { Browser, closest, detach, EventHandler, getInstance, select, selectAll, formatUnit } from '@syncfusion/ej2-base';\nimport { addClass, attributes, classList, isNullOrUndefined, L10n } from '@syncfusion/ej2-base';\nimport { remove, removeClass, rippleEffect } from '@syncfusion/ej2-base';\nimport { SplitButton, getModel } from '@syncfusion/ej2-splitbuttons';\nimport { Tooltip, getZindexPartial, Popup } from '@syncfusion/ej2-popups';\nimport { Input } from './../input/index';\nimport { NumericTextBox } from './../numerictextbox/index';\nimport { Slider } from './../slider/slider';\nvar APPLY = 'e-apply';\nvar CANCEL = 'e-cancel';\nvar CURRENT = 'e-current';\nvar CONTAINER = 'e-container';\nvar CTRLBTN = 'e-ctrl-btn';\nvar CTRLSWITCH = 'e-switch-ctrl-btn';\nvar DISABLED = 'e-disabled';\nvar FORMATSWITCH = 'e-value-switch-btn';\nvar HANDLER = 'e-handler';\nvar HEX = 'e-hex';\nvar HSVAREA = 'e-hsv-color';\nvar HSVCONTAINER = 'e-hsv-container';\nvar INPUTWRAPPER = 'e-selected-value';\nvar MODESWITCH = 'e-mode-switch-btn';\nvar NOCOLOR = 'e-nocolor-item';\nvar PALETTES = 'e-palette';\nvar PALETTECONTENT = 'e-color-palette';\nvar PICKERCONTENT = 'e-color-picker';\nvar PREVIEW = 'e-preview-container';\nvar PREVIOUS = 'e-previous';\nvar RTL = 'e-rtl';\nvar SELECT = 'e-selected';\nvar SPLITPREVIEW = 'e-split-preview';\nvar TILE = 'e-tile';\nvar TOHSV = 'e-to-hsv';\nvar presets = {\n default: ['#000000', '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#ffeb3b',\n '#ffffff', '#ffebee', '#fce4ec', '#f3e5f5', '#ede7f6', '#e3f2fd', '#e1f5fe', '#e0f7fa', '#e0f2f1', '#fffde7',\n '#f2f2f2', '#ffcdd2', '#f8bbd0', '#e1bee7', '#d1c4e9', '#bbdefb', '#b3e5fc', '#b2ebf2', '#b2dfdb', '#fff9c4',\n '#e6e6e6', '#ef9a9a', '#f48fb1', '#ce93d8', '#b39ddb', '#90caf9', '#81d4fa', '#80deea', '#80cbc4', '#fff59d',\n '#cccccc', '#e57373', '#f06292', '#ba68c8', '#9575cd', '#64b5f6', '#4fc3f7', '#4dd0e1', '#4db6ac', '#fff176',\n '#b3b3b3', '#ef5350', '#ec407a', '#ab47bc', '#7e57c2', '#42a5f5', '#29b6f6', '#26c6da', '#26a69a', '#ffee58',\n '#999999', '#e53935', '#d81b60', '#8e24aa', '#5e35b1', '#1e88e5', '#039be5', '#00acc1', '#00897b', '#fdd835',\n '#808080', '#d32f2f', '#c2185b', '#7b1fa2', '#512da8', '#1976d2', '#0288d1', '#0097a7', '#00796b', '#fbc02d',\n '#666666', '#c62828', '#ad1457', '#6a1b9a', '#4527a0', '#1565c0', '#0277bd', '#00838f', '#00695c', '#f9a825',\n '#4d4d4d', '#b71c1c', '#880e4f', '#4a148c', '#311b92', '#0d47a1', '#01579b', '#006064', '#004d40', '#f57f17']\n};\n/**\n * ColorPicker component is a user interface to select and adjust color values. It provides supports for various\n * color specification like Red Green Blue, Hue Saturation Value and Hex codes.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar ColorPicker = /** @class */ (function (_super) {\n __extends(ColorPicker, _super);\n function ColorPicker(options, element) {\n return _super.call(this, options, element) || this;\n }\n ColorPicker.prototype.preRender = function () {\n var localeText = { Apply: 'Apply', Cancel: 'Cancel', ModeSwitcher: 'Switch Mode' };\n this.l10n = new L10n('colorpicker', localeText, this.locale);\n };\n /**\n * To Initialize the component rendering\n * @private\n */\n ColorPicker.prototype.render = function () {\n this.initWrapper();\n if (this.inline) {\n this.createWidget();\n }\n else {\n this.createSplitBtn();\n }\n };\n ColorPicker.prototype.initWrapper = function () {\n var wrapper = this.createElement('div', { className: 'e-' + this.getModuleName() + '-wrapper' });\n this.element.parentNode.insertBefore(wrapper, this.element);\n wrapper.appendChild(this.element);\n attributes(this.element, { 'tabindex': '-1', 'spellcheck': 'false' });\n this.container = this.createElement('div', { className: CONTAINER });\n this.getWrapper().appendChild(this.container);\n var value = this.value ? this.value : '#008000';\n this.element.value = value.slice(0, 7);\n if (this.mode === 'Picker') {\n value = this.roundValue(value);\n }\n this.setProperties({ 'value': value }, true);\n if (this.enableRtl) {\n wrapper.classList.add(RTL);\n }\n if (this.cssClass) {\n addClass([wrapper], this.cssClass.split(' '));\n }\n this.tileRipple = rippleEffect(this.container, { selector: '.' + TILE });\n this.ctrlBtnRipple = rippleEffect(this.container, { selector: '.e-btn' });\n };\n ColorPicker.prototype.getWrapper = function () {\n return this.element.parentElement;\n };\n ColorPicker.prototype.createWidget = function () {\n if (this.mode === 'Palette') {\n this.createPalette();\n if (!this.inline) {\n this.firstPaletteFocus();\n }\n }\n else {\n this.createPicker();\n if (!this.inline) {\n this.getDragHandler().focus();\n }\n }\n var wrapper = this.getWrapper();\n if ((this.isPicker() && !wrapper.classList.contains('e-hide-value')) || wrapper.classList.contains('e-show-value')) {\n this.createInput();\n }\n this.createCtrlBtn();\n if (!this.disabled) {\n this.wireEvents();\n }\n if (this.inline && this.disabled) {\n this.toggleDisabled(true);\n }\n if (Browser.isDevice) {\n this.refreshPopupPos();\n }\n };\n ColorPicker.prototype.createSplitBtn = function () {\n var _this = this;\n var splitButton = this.createElement('button', { className: 'e-split-colorpicker' });\n this.getWrapper().appendChild(splitButton);\n this.splitBtn = new SplitButton({\n iconCss: 'e-selected-color',\n target: this.container,\n disabled: this.disabled,\n enableRtl: this.enableRtl,\n beforeOpen: this.beforeOpenFn.bind(this),\n open: this.onOpen.bind(this),\n beforeClose: this.popupClose.bind(this),\n click: function (args) {\n _this.trigger('change', {\n currentValue: { hex: _this.value.slice(0, 7), rgba: _this.convertToRgbString(_this.hexToRgb(_this.value)) },\n previousValue: { hex: null, rgba: null }\n });\n }\n }, splitButton);\n var preview = this.createElement('span', { className: SPLITPREVIEW });\n select('.e-selected-color', splitButton).appendChild(preview);\n preview.style.backgroundColor = this.convertToRgbString(this.hexToRgb(this.value));\n var popupEle = this.getPopupEle();\n addClass([popupEle], 'e-colorpicker-popup');\n if (this.cssClass) {\n addClass([popupEle], this.cssClass.split(' '));\n }\n if (Browser.isDevice) {\n var popupInst = this.getPopupInst();\n popupInst.relateTo = document.body;\n popupInst.position = { X: 'center', Y: 'center' };\n popupInst.targetType = 'container';\n popupInst.collision = { X: 'fit', Y: 'fit' };\n popupInst.offsetY = 4;\n }\n };\n ColorPicker.prototype.onOpen = function (args) {\n this.trigger('open', { element: this.container });\n };\n ColorPicker.prototype.getPopupInst = function () {\n return getInstance(this.getPopupEle(), Popup);\n };\n ColorPicker.prototype.beforeOpenFn = function (args) {\n var beforeOpenArgs = { element: this.container, event: args.event, cancel: false };\n this.trigger('beforeOpen', beforeOpenArgs);\n args.cancel = beforeOpenArgs.cancel;\n if (!beforeOpenArgs.cancel) {\n var popupEle = this.getPopupEle();\n popupEle.style.display = 'block';\n this.createWidget();\n popupEle.style.display = '';\n if (Browser.isDevice) {\n this.modal = this.createElement('div');\n this.modal.className = 'e-' + this.getModuleName() + ' e-modal';\n this.modal.style.display = 'none';\n document.body.insertBefore(this.modal, popupEle);\n document.body.className += ' e-colorpicker-overflow';\n this.modal.style.display = 'block';\n }\n }\n };\n ColorPicker.prototype.popupClose = function (args) {\n var beforeCloseArgs = { element: this.container, event: args.event, cancel: false };\n this.trigger('beforeClose', beforeCloseArgs);\n args.cancel = beforeCloseArgs.cancel;\n if (!beforeCloseArgs.cancel) {\n if (args.event && Browser.isDevice && args.event.target === this.modal) {\n args.cancel = true;\n }\n else {\n this.unWireEvents();\n this.destroyOtherComp();\n this.container.style.width = '';\n select('.' + SPLITPREVIEW, this.splitBtn.element).style.backgroundColor\n = this.convertToRgbString(this.hexToRgb(this.value));\n this.container.innerHTML = '';\n removeClass([this.container], [PICKERCONTENT, PALETTECONTENT]);\n if (Browser.isDevice && this.modal) {\n removeClass([document.body], 'e-colorpicker-overflow');\n this.modal.style.display = 'none';\n this.modal.outerHTML = '';\n this.modal = null;\n }\n }\n }\n };\n ColorPicker.prototype.createPalette = function () {\n classList(this.container, [PALETTECONTENT], [PICKERCONTENT]);\n if (this.presetColors) {\n var paletteGroup = this.createElement('div', { className: 'e-custom-palette' });\n this.appendElement(paletteGroup);\n var keys = Object.keys(this.presetColors);\n if (keys.length === 1) {\n this.appendPalette(this.presetColors[keys[0]], keys[0], paletteGroup);\n }\n else {\n for (var i = 0, len = keys.length; i < len; i++) {\n this.appendPalette(this.presetColors[keys[i]], keys[i], paletteGroup);\n }\n }\n if (selectAll('.e-row', paletteGroup).length > 10) {\n addClass([paletteGroup], 'e-palette-group');\n }\n }\n else {\n this.appendPalette(presets.default, 'default');\n }\n if (this.mode === 'Palette' && !this.modeSwitcher && this.noColor) {\n this.setNoColor();\n }\n var width = parseInt(getComputedStyle(this.container).borderBottomWidth, 10);\n this.container.style.width = formatUnit(this.container.children[0].offsetWidth + width + width);\n this.rgb = this.hexToRgb(this.roundValue(this.value));\n this.hsv = this.rgbToHsv.apply(this, this.rgb);\n };\n ColorPicker.prototype.firstPaletteFocus = function () {\n if (!select('.' + SELECT, this.container.children[0])) {\n selectAll('.' + PALETTES, this.container)[0].focus();\n }\n };\n ColorPicker.prototype.appendPalette = function (colors, key, refEle) {\n var palette = this.createElement('div', { className: PALETTES, attrs: { 'tabindex': '0' } });\n if (refEle) {\n refEle.appendChild(palette);\n }\n else {\n this.appendElement(palette);\n }\n var row;\n var tile;\n for (var i = 0, len = colors.length; i < len; i++) {\n if (i === 0 || i % this.columns === 0) {\n row = this.createElement('div', {\n className: 'e-row', attrs: { 'role': 'row' }\n });\n palette.appendChild(row);\n }\n tile = this.createElement('span', {\n className: TILE, attrs: { 'role': 'gridcell', 'aria-label': colors[i], 'aria-selected': 'false' }\n });\n this.trigger('beforeTileRender', { element: tile, presetName: key, value: colors[i] });\n row.appendChild(tile);\n if (this.value.slice(0, colors[i].length).toLowerCase() === colors[i].toLowerCase()) {\n this.addTileSelection(tile);\n palette.focus();\n }\n tile.style.backgroundColor = colors[i];\n }\n };\n ColorPicker.prototype.setNoColor = function () {\n var noColorEle = selectAll('.e-row')[0].children[0];\n noColorEle.classList.add(NOCOLOR);\n if (!this.value) {\n noColorEle.classList.add(SELECT);\n closest(noColorEle, '.' + PALETTES).focus();\n }\n ['aria-selected', 'aria-label'].forEach(function (attr) { noColorEle.removeAttribute(attr); });\n noColorEle.style.backgroundColor = '';\n };\n ColorPicker.prototype.appendElement = function (ele, insertPos) {\n if (insertPos === void 0) { insertPos = 0; }\n var refEle = this.container.children[insertPos];\n refEle ? this.container.insertBefore(ele, refEle) : this.container.appendChild(ele);\n };\n ColorPicker.prototype.addTileSelection = function (ele) {\n ele.classList.add(SELECT);\n ele.setAttribute('aria-selected', 'true');\n };\n ColorPicker.prototype.createPicker = function () {\n classList(this.container, [PICKERCONTENT], [PALETTECONTENT]);\n var hsvContainer = this.createElement('div', { className: HSVCONTAINER });\n this.appendElement(hsvContainer);\n hsvContainer.appendChild(this.createElement('div', { className: HSVAREA }));\n var dragHandler = this.createElement('span', { className: HANDLER, attrs: { 'tabindex': '0' } });\n hsvContainer.appendChild(dragHandler);\n this.rgb = this.hexToRgb(this.value);\n this.hsv = this.rgbToHsv.apply(this, this.rgb);\n this.setHsvContainerBg();\n this.setHandlerPosition();\n this.createSlider();\n this.createDragTooltip();\n };\n ColorPicker.prototype.setHsvContainerBg = function (h) {\n if (h === void 0) { h = this.hsv[0]; }\n this.getHsvContainer().style.backgroundColor = this.convertToRgbString(this.hsvToRgb(h, 100, 100, 1));\n };\n ColorPicker.prototype.getHsvContainer = function () {\n return select('.' + HSVCONTAINER, this.container);\n };\n ColorPicker.prototype.setHandlerPosition = function () {\n var dragHandler = this.getDragHandler();\n var hsvArea = select('.' + HSVAREA, this.container);\n if (this.enableRtl) {\n dragHandler.style.left = formatUnit(hsvArea.offsetWidth * Math.abs(100 - this.hsv[1]) / 100);\n }\n else {\n dragHandler.style.left = formatUnit(hsvArea.offsetWidth * this.hsv[1] / 100);\n }\n dragHandler.style.top = formatUnit(hsvArea.offsetHeight * (100 - this.hsv[2]) / 100);\n };\n ColorPicker.prototype.createSlider = function () {\n var sliderPreviewWrapper = this.createElement('div', { className: 'e-slider-preview' });\n this.appendElement(sliderPreviewWrapper, 1);\n this.createPreview(sliderPreviewWrapper);\n var sliderWrapper = this.createElement('div', { className: 'e-colorpicker-slider' });\n sliderPreviewWrapper.insertBefore(sliderWrapper, sliderPreviewWrapper.children[0]);\n var slider = this.createElement('div', { className: 'e-hue-slider' });\n sliderWrapper.appendChild(slider);\n this.hueSlider = new Slider({\n value: this.hsv[0],\n min: 0,\n max: 359,\n enableRtl: this.enableRtl,\n enabled: !this.disabled,\n change: this.hueChange.bind(this)\n }, slider);\n slider = this.createElement('div', { className: 'e-opacity-slider' });\n sliderWrapper.appendChild(slider);\n this.opacitySlider = new Slider({\n value: this.rgb[3] * 100,\n min: 0,\n max: 100,\n enableRtl: this.enableRtl,\n enabled: !this.disabled,\n change: this.opacityChange.bind(this)\n }, slider);\n var opacityBgTrack = this.createElement('div', { className: 'e-opacity-empty-track' });\n slider.appendChild(opacityBgTrack);\n this.updateOpacitySliderBg();\n };\n ColorPicker.prototype.updateOpacitySliderBg = function () {\n var direction = this.enableRtl ? 'to left' : 'to right';\n select('.e-slider-track', this.opacitySlider.element).style.background =\n 'linear-gradient(' + direction + ', rgba(' + this.rgb.slice(0, 3) + ', 0) 0%, ' +\n this.convertToRgbString(this.rgb.slice(0, 3)) + ' 100%)';\n };\n ColorPicker.prototype.hueChange = function (args) {\n this.hsv[0] = args.value;\n this.setHsvContainerBg();\n this.convertToOtherFormat();\n };\n ColorPicker.prototype.opacityChange = function (args) {\n var value = args.value;\n var pValue = this.rgbToHex(this.rgb);\n this.hsv[3] = value / 100;\n this.rgb[3] = value / 100;\n var cValue = this.rgbToHex(this.rgb);\n if (!this.getWrapper().classList.contains('e-hide-value')) {\n getInstance(select('.e-opacity-value', this.container), NumericTextBox).value = value;\n }\n var rgb = this.convertToRgbString(this.rgb);\n this.updatePreview(rgb);\n this.triggerEvent(cValue, pValue, rgb);\n };\n ColorPicker.prototype.createPreview = function (parentEle) {\n var previewContainer = this.createElement('div', { className: PREVIEW });\n parentEle.appendChild(previewContainer);\n var preview = this.createElement('span', { className: 'e-preview ' + CURRENT });\n previewContainer.appendChild(preview);\n var colorValue = this.convertToRgbString(this.rgb);\n preview.style.backgroundColor = colorValue;\n preview = this.createElement('span', { className: 'e-preview ' + PREVIOUS });\n previewContainer.appendChild(preview);\n preview.style.backgroundColor = colorValue;\n };\n ColorPicker.prototype.isPicker = function () {\n return !this.container.classList.contains(PALETTECONTENT);\n };\n ColorPicker.prototype.getPopupEle = function () {\n return this.container.parentElement;\n };\n ColorPicker.prototype.getNumericTextBoxModel = function (value, label, max) {\n var _this = this;\n return {\n value: value,\n placeholder: label,\n min: 0,\n max: max,\n format: '###.##',\n showSpinButton: false,\n floatLabelType: 'Always',\n enableRtl: this.enableRtl,\n enabled: !this.disabled,\n readonly: this.isPicker() ? false : true,\n change: function (args) {\n if (args.event) {\n _this.inputHandler(args.event);\n }\n }\n };\n };\n ColorPicker.prototype.createInput = function (child) {\n if (child === void 0) { child = 2; }\n var inputWrap = this.createElement('div', { className: INPUTWRAPPER });\n this.appendElement(inputWrap, child);\n var container = this.createElement('div', { className: 'e-input-container' });\n inputWrap.appendChild(container);\n inputWrap.appendChild(this.createElement('button', { className: 'e-icons e-btn e-flat e-icon-btn ' + FORMATSWITCH + ' ' + TOHSV }));\n var hexInput = this.createElement('input', {\n className: HEX,\n attrs: { 'maxlength': '7', 'spellcheck': 'false' }\n });\n if (!this.isPicker()) {\n Input.setReadonly(true, hexInput);\n }\n container.appendChild(hexInput);\n Input.createInput({\n element: hexInput,\n floatLabelType: 'Always',\n properties: {\n placeholder: 'HEX',\n enableRtl: this.enableRtl,\n enabled: !this.disabled\n }\n }, this.createElement);\n Input.setValue(this.value.slice(0, 7), hexInput);\n var numericInput;\n var label = 'RGB';\n var clsName = ['rh', 'gs', 'bv'];\n for (var i = 0; i < 3; i++) {\n numericInput = new NumericTextBox(this.getNumericTextBoxModel(this.rgb[i], label[i], 255), container.appendChild(this.createElement('input', { className: 'e-' + clsName[i] + '-value' })));\n }\n numericInput = new NumericTextBox(this.getNumericTextBoxModel(this.rgb[3] * 100, 'A', 100), container.appendChild(this.createElement('input', { className: 'e-opacity-value' })));\n };\n ColorPicker.prototype.createCtrlBtn = function () {\n if (this.modeSwitcher || this.showButtons) {\n this.l10n.setLocale(this.locale);\n var btnWrapper = this.createElement('div', { className: CTRLSWITCH });\n this.container.appendChild(btnWrapper);\n if (this.showButtons) {\n var controlBtnWrapper = this.createElement('div', { className: CTRLBTN });\n btnWrapper.appendChild(controlBtnWrapper);\n var apply = this.l10n.getConstant('Apply');\n controlBtnWrapper.appendChild(this.createElement('button', {\n innerHTML: apply,\n className: 'e-btn e-flat e-primary e-small ' + APPLY,\n attrs: { 'title': apply }\n }));\n var cancel = this.l10n.getConstant('Cancel');\n controlBtnWrapper.appendChild(this.createElement('button', {\n innerHTML: cancel,\n className: 'e-btn e-flat e-small ' + CANCEL,\n attrs: { 'title': cancel }\n }));\n }\n if (this.modeSwitcher) {\n this.appendModeSwitchBtn();\n }\n }\n };\n ColorPicker.prototype.appendModeSwitchBtn = function () {\n var modeSwitcher = this.createElement('button', {\n className: 'e-icons e-btn e-flat e-icon-btn ' + MODESWITCH, attrs: { title: this.l10n.getConstant('ModeSwitcher') }\n });\n select('.' + CTRLSWITCH, this.container).insertBefore(modeSwitcher, select('.' + CTRLBTN, this.container));\n };\n ColorPicker.prototype.createDragTooltip = function () {\n var _this = this;\n var tooltip = new Tooltip({\n opensOn: 'Custom',\n showTipPointer: false,\n cssClass: 'e-color-picker-tooltip',\n beforeOpen: function (args) {\n _this.tooltipEle = args.element;\n },\n animation: { open: { effect: 'None' }, close: { effect: 'None' } }\n });\n tooltip.appendTo(this.container);\n tooltip.open(this.container);\n this.tooltipEle.style.zIndex = getZindexPartial(this.tooltipEle).toString();\n select('.e-tip-content', this.tooltipEle).appendChild(this.createElement('div', { className: 'e-tip-transparent' }));\n };\n ColorPicker.prototype.getTooltipInst = function () {\n return getInstance(this.container, Tooltip);\n };\n ColorPicker.prototype.setTooltipOffset = function (value) {\n this.getTooltipInst().offsetY = value;\n };\n ColorPicker.prototype.toggleDisabled = function (enable) {\n enable ? this.getWrapper().classList.add(DISABLED) : this.getWrapper().classList.remove(DISABLED);\n if (this.showButtons) {\n ([].slice.call(selectAll('.e-btn', this.container))).forEach(function (ele) {\n enable ? attributes(ele, { 'disabled': '' }) : ele.removeAttribute('disabled');\n });\n }\n };\n ColorPicker.prototype.convertToRgbString = function (rgb) {\n return rgb.length ? rgb.length === 4 ? 'rgba(' + rgb.join() + ')' : 'rgb(' + rgb.join() + ')' : '';\n };\n ColorPicker.prototype.convertToHsvString = function (hsv) {\n return hsv.length === 4 ? 'hsva(' + hsv.join() + ')' : 'hsv(' + hsv.join() + ')';\n };\n ColorPicker.prototype.updateHsv = function () {\n this.hsv[1] = this.hsv[1] > 100 ? 100 : this.hsv[1];\n this.hsv[2] = this.hsv[2] > 100 ? 100 : this.hsv[2];\n this.setHandlerPosition();\n };\n ColorPicker.prototype.convertToOtherFormat = function (isKey) {\n if (isKey === void 0) { isKey = false; }\n var pValue = this.rgbToHex(this.rgb);\n this.rgb = this.hsvToRgb.apply(this, this.hsv);\n var cValue = this.rgbToHex(this.rgb);\n var rgba = this.convertToRgbString(this.rgb);\n this.updatePreview(rgba);\n this.updateInput(cValue);\n this.triggerEvent(cValue, pValue, rgba, isKey);\n };\n ColorPicker.prototype.updateInput = function (value) {\n if (!this.getWrapper().classList.contains('e-hide-value')) {\n Input.setValue(value.substr(0, 7), select('.' + HEX, this.container));\n if (select('.' + FORMATSWITCH, this.container).classList.contains(TOHSV)) {\n this.updateValue(this.rgb, false);\n }\n else {\n this.updateValue(this.hsv, false);\n }\n }\n };\n ColorPicker.prototype.updatePreview = function (value) {\n this.updateOpacitySliderBg();\n select('.e-tip-transparent', this.tooltipEle).style.backgroundColor = value;\n select('.' + PREVIEW + ' .' + CURRENT, this.container).style.backgroundColor = value;\n select('.' + PREVIEW + ' .' + PREVIOUS, this.container).style.backgroundColor\n = this.convertToRgbString(this.hexToRgb(this.value));\n };\n ColorPicker.prototype.getDragHandler = function () {\n return select('.' + HANDLER, this.container);\n };\n ColorPicker.prototype.removeTileSelection = function () {\n var selectedEle = [].slice.call(selectAll('.' + SELECT, this.container.children[0]));\n selectedEle.forEach(function (ele) {\n ele.classList.remove(SELECT);\n ele.setAttribute('aria-selected', 'false');\n });\n };\n ColorPicker.prototype.convertRgbToNumberArray = function (value) {\n return (value.slice(value.indexOf('(') + 1, value.indexOf(')'))).split(',').map(function (n, i) {\n return (i !== 3) ? parseInt(n, 10) : parseFloat(n);\n });\n };\n /**\n * To get color value in specified type.\n * @param value - Specify the color value.\n * @param type - Specify the converted color value type.\n * @method getValue\n * @return {string}\n */\n ColorPicker.prototype.getValue = function (value, type) {\n if (!value) {\n value = this.value;\n }\n type = !type ? 'hex' : type.toLowerCase();\n if (value[0] === 'r') {\n var cValue = this.convertRgbToNumberArray(value);\n if (type === 'hex' || type === 'hexa') {\n var hex = this.rgbToHex(cValue);\n return type === 'hex' ? hex.slice(0, 7) : hex;\n }\n else {\n if (type === 'hsv') {\n return this.convertToHsvString(this.rgbToHsv.apply(this, cValue.slice(0, 3)));\n }\n else {\n if (type === 'hsva') {\n return this.convertToHsvString(this.rgbToHsv.apply(this, cValue));\n }\n else {\n return 'null';\n }\n }\n }\n }\n else {\n if (value[0] === 'h') {\n var cValue = this.hsvToRgb.apply(this, this.convertRgbToNumberArray(value));\n if (type === 'rgba') {\n return this.convertToRgbString(cValue);\n }\n else {\n if (type === 'hex' || type === 'hexa') {\n var hex = this.rgbToHex(cValue);\n return type === 'hex' ? hex.slice(0, 7) : hex;\n }\n else {\n if (type === 'rgb') {\n return this.convertToRgbString(cValue.slice(0, 3));\n }\n else {\n return 'null';\n }\n }\n }\n }\n else {\n value = this.roundValue(value);\n var rgb = this.hexToRgb(value);\n if (type === 'rgb' || type === 'hsv') {\n rgb = rgb.slice(0, 3);\n }\n if (type === 'rgba' || type === 'rgb') {\n return this.convertToRgbString(rgb);\n }\n else {\n if (type === 'hsva' || type === 'hsv') {\n return this.convertToHsvString(this.rgbToHsv.apply(this, rgb));\n }\n else {\n if (type === 'hex') {\n return value.slice(0, 7);\n }\n else {\n if (type === 'a') {\n return rgb[3].toString();\n }\n else {\n return 'null';\n }\n }\n }\n }\n }\n }\n };\n /**\n * To show/hide ColorPicker popup based on current state of the SplitButton.\n * @method toggle\n * @return {void}\n */\n ColorPicker.prototype.toggle = function () {\n this.splitBtn.toggle();\n };\n /**\n * Get component name.\n * @returns string\n * @private\n */\n ColorPicker.prototype.getModuleName = function () {\n return 'colorpicker';\n };\n /**\n * Gets the properties to be maintained in the persisted state.\n * @return {string}\n */\n ColorPicker.prototype.getPersistData = function () {\n return this.addOnPersist(['value']);\n };\n ColorPicker.prototype.wireEvents = function () {\n if (this.isPicker()) {\n var dragHandler = this.getDragHandler();\n EventHandler.add(dragHandler, 'keydown', this.pickerKeyDown, this);\n EventHandler.add(this.getHsvContainer(), 'mousedown touchstart', this.handlerDown, this);\n if (this.modeSwitcher || this.showButtons) {\n this.addCtrlSwitchEvent();\n }\n if (!this.getWrapper().classList.contains('e-hide-value')) {\n this.addvalueEventHandler();\n }\n EventHandler.add(select('.' + PREVIOUS, this.container), 'click', this.previewHandler, this);\n }\n else {\n EventHandler.add(this.container, 'click', this.paletteClickHandler, this);\n EventHandler.add(this.container, 'keydown', this.paletteKeyDown, this);\n }\n };\n ColorPicker.prototype.addCtrlSwitchEvent = function () {\n EventHandler.add(select('.' + CTRLSWITCH, this.container), 'click', this.btnClickHandler, this);\n };\n ColorPicker.prototype.addInputEvent = function () {\n EventHandler.add(select('.' + HEX, this.container), 'input', this.inputHandler, this);\n };\n ColorPicker.prototype.addvalueEventHandler = function () {\n this.addInputEvent();\n EventHandler.add(select('.' + FORMATSWITCH, this.container), 'click', this.formatSwitchHandler, this);\n };\n ColorPicker.prototype.pickerKeyDown = function (e) {\n switch (e.keyCode) {\n case 39:\n this.handlerDragPosition(1, this.enableRtl ? -1 : 1, e);\n break;\n case 37:\n this.handlerDragPosition(1, this.enableRtl ? 1 : -1, e);\n break;\n case 38:\n this.handlerDragPosition(2, 1, e);\n break;\n case 40:\n this.handlerDragPosition(2, -1, e);\n break;\n case 13:\n e.preventDefault();\n var cValue = this.rgbToHex(this.rgb);\n this.enterKeyHandler(cValue);\n }\n };\n ColorPicker.prototype.enterKeyHandler = function (value) {\n this.triggerChangeEvent(value);\n if (!this.inline) {\n this.toggle();\n this.splitBtn.element.focus();\n }\n };\n ColorPicker.prototype.triggerChangeEvent = function (value) {\n var hex = value.slice(0, 7);\n this.trigger('change', {\n currentValue: { hex: hex, rgba: this.convertToRgbString(this.rgb) },\n previousValue: { hex: this.value.slice(0, 7), rgba: this.convertToRgbString(this.hexToRgb(this.value)) }\n });\n this.setProperties({ 'value': value }, true);\n this.element.value = hex ? hex : '#000000';\n };\n ColorPicker.prototype.handlerDragPosition = function (prob, value, e) {\n e.preventDefault();\n this.hsv[prob] += value * (e.ctrlKey ? 1 : 3);\n if (this.hsv[prob] < 0) {\n this.hsv[prob] = 0;\n }\n this.updateHsv();\n this.convertToOtherFormat(true);\n };\n ColorPicker.prototype.handlerDown = function (e) {\n e.preventDefault();\n var x;\n var y;\n if (e.type === 'mousedown') {\n this.clientX = Math.abs(e.pageX - pageXOffset);\n this.clientY = Math.abs(e.pageY - pageYOffset);\n this.setTooltipOffset(8);\n }\n else {\n this.clientX = Math.abs(e.changedTouches[0].pageX - pageXOffset);\n this.clientY = Math.abs(e.changedTouches[0].pageY - pageYOffset);\n this.setTooltipOffset(-8);\n }\n this.setHsv(this.clientX, this.clientY);\n this.getDragHandler().style.transition = 'left .4s cubic-bezier(.25, .8, .25, 1), top .4s cubic-bezier(.25, .8, .25, 1)';\n this.updateHsv();\n this.convertToOtherFormat();\n this.getDragHandler().focus();\n EventHandler.add(document, 'mousemove touchmove', this.handlerMove, this);\n EventHandler.add(document, 'mouseup touchend', this.handlerEnd, this);\n };\n ColorPicker.prototype.handlerMove = function (e) {\n if (e.type !== 'touchmove') {\n e.preventDefault();\n }\n var x;\n var y;\n if (e.type === 'mousemove') {\n x = Math.abs(e.pageX - pageXOffset);\n y = Math.abs(e.pageY - pageYOffset);\n }\n else {\n x = Math.abs(e.changedTouches[0].pageX - pageXOffset);\n y = Math.abs(e.changedTouches[0].pageY - pageYOffset);\n }\n this.setHsv(x, y);\n var dragHandler = this.getDragHandler();\n var left = parseInt(dragHandler.style.left, 10);\n var top = parseInt(dragHandler.style.top, 10);\n this.updateHsv();\n this.convertToOtherFormat();\n this.getTooltipInst().refresh(dragHandler);\n if (!this.tooltipEle.style.transform) {\n if (Math.abs(this.clientX - x) > 8 || Math.abs(this.clientY - y) > 8) {\n select('.' + HSVAREA, this.container).style.cursor = 'pointer';\n dragHandler.style.transition = 'none';\n if (!this.inline) {\n this.tooltipEle.style.zIndex = (parseInt(this.getPopupEle().style.zIndex, 10) + 1).toString();\n }\n this.tooltipEle.style.transform = 'rotate(45deg)';\n dragHandler.classList.add('e-hide-handler');\n }\n }\n };\n ColorPicker.prototype.setHsv = function (clientX, clientY) {\n var ele = select('.' + HSVAREA, this.container);\n var position = ele.getBoundingClientRect();\n if (this.enableRtl) {\n clientX = clientX > position.right ? 0 : Math.abs(clientX - position.right);\n }\n else {\n clientX = clientX > position.left ? Math.abs(clientX - position.left) : 0;\n }\n clientY = clientY > position.top ? Math.abs(clientY - position.top) : 0;\n this.hsv[2] = Math.round(Number(100 * (ele.offsetHeight -\n Math.max(0, Math.min(ele.offsetHeight, (clientY - ele.offsetTop)))) / ele.offsetHeight) * 10) / 10;\n this.hsv[1] =\n Math.round(Number(100 * (Math.max(0, Math.min(ele.offsetWidth, (clientX - ele.offsetLeft)))) / ele.offsetWidth) * 10) / 10;\n };\n ColorPicker.prototype.handlerEnd = function (e) {\n if (e.type !== 'touchend') {\n e.preventDefault();\n }\n EventHandler.remove(document, 'mousemove touchmove', this.handlerMove);\n EventHandler.remove(document, 'mouseup touchend', this.handlerEnd);\n var dragHandler = this.getDragHandler();\n select('.' + HSVAREA, this.container).style.cursor = '';\n if (this.tooltipEle.style.transform) {\n this.tooltipEle.style.transform = '';\n dragHandler.classList.remove('e-hide-handler');\n }\n if (!this.inline && !this.showButtons) {\n this.toggle();\n }\n };\n ColorPicker.prototype.btnClickHandler = function (e) {\n var target = e.target;\n if (closest(target, '.' + MODESWITCH)) {\n e.stopPropagation();\n this.switchToPalette();\n }\n else {\n if (target.classList.contains(APPLY) || target.classList.contains(CANCEL)) {\n this.ctrlBtnClick(target);\n }\n }\n };\n ColorPicker.prototype.switchToPalette = function () {\n this.trigger('beforeModeSwitch', { element: this.container, mode: 'Palette' });\n this.unWireEvents();\n this.destroyOtherComp();\n detach(select('.e-slider-preview', this.container));\n if (!this.getWrapper().classList.contains('e-hide-value')) {\n detach(select('.' + INPUTWRAPPER, this.container));\n }\n detach(this.getHsvContainer());\n this.createPalette();\n this.firstPaletteFocus();\n if (this.getWrapper().classList.contains('e-show-value')) {\n this.createInput(1);\n }\n this.refreshPopupPos();\n this.wireEvents();\n };\n ColorPicker.prototype.refreshPopupPos = function () {\n if (!this.inline) {\n var popupEle = this.getPopupEle();\n popupEle.style.left = '0px';\n popupEle.style.top = '0px';\n this.getPopupInst().refreshPosition(this.splitBtn.element.parentElement);\n }\n };\n ColorPicker.prototype.formatSwitchHandler = function (e) {\n var target = e.target;\n if (target.classList.contains(TOHSV)) {\n this.updateValue(this.hsv, true, 3, [360, 100, 100]);\n target.classList.remove(TOHSV);\n }\n else {\n this.updateValue(this.rgb, true, 2);\n target.classList.add(TOHSV);\n }\n };\n ColorPicker.prototype.updateValue = function (value, format, idx, max) {\n var clsName = ['e-rh-value', 'e-gs-value', 'e-bv-value'];\n var inst;\n for (var i = 0, len = clsName.length; i < len; i++) {\n inst = getInstance(select('.' + clsName[i], this.container), NumericTextBox);\n inst.value = Math.round(value[i]);\n if (format) {\n inst.placeholder = clsName[i].substr(idx, 1).toUpperCase();\n inst.max = max ? max[i] : 255;\n }\n inst.dataBind();\n }\n };\n ColorPicker.prototype.previewHandler = function (e) {\n var target = e.target;\n var pValue = this.rgbToHex(this.rgb);\n this.rgb = this.convertRgbToNumberArray(target.style.backgroundColor);\n if (!this.rgb[3]) {\n this.rgb[3] = 1;\n }\n var cValue = this.rgbToHex(this.rgb);\n var hsv = this.rgbToHsv.apply(this, this.rgb);\n if (hsv[0] !== this.hsv[0]) {\n this.hueSlider.setProperties({ 'value': hsv[0] }, true);\n this.hueSlider.refresh();\n }\n this.setHsvContainerBg(hsv[0]);\n if (hsv[3] !== this.hsv[3]) {\n this.opacitySlider.setProperties({ 'value': hsv[3] * 100 }, true);\n this.opacitySlider.refresh();\n }\n this.updateOpacitySliderBg();\n this.hsv = hsv;\n this.setHandlerPosition();\n this.updateInput(cValue);\n select('.' + PREVIEW + ' .' + CURRENT, this.container).style.backgroundColor = this.convertToRgbString(this.rgb);\n this.triggerEvent(cValue, pValue, this.convertToRgbString(this.rgb));\n };\n ColorPicker.prototype.paletteClickHandler = function (e) {\n e.preventDefault();\n var target = e.target;\n if (target.classList.contains(TILE)) {\n this.removeTileSelection();\n this.addTileSelection(target);\n if (target.classList.contains(NOCOLOR)) {\n this.noColorTile();\n }\n else {\n var cValue = target.getAttribute('aria-label');\n var pValue = this.rgbToHex(this.rgb);\n this.rgb = this.hexToRgb(this.roundValue(cValue));\n this.hsv = this.rgbToHsv.apply(this, this.rgb);\n if (this.getWrapper().classList.contains('e-show-value')) {\n this.updateInput(cValue);\n }\n this.triggerEvent(cValue, pValue, this.convertToRgbString(this.rgb));\n }\n if (!this.inline && !this.showButtons) {\n this.toggle();\n }\n }\n else {\n if (closest(target, '.' + MODESWITCH)) {\n this.switchToPicker();\n }\n else {\n if (target.classList.contains(APPLY) || target.classList.contains(CANCEL)) {\n this.ctrlBtnClick(target);\n }\n else {\n if (this.getWrapper().classList.contains('e-show-value') && closest(target, '.' + FORMATSWITCH)) {\n this.formatSwitchHandler(e);\n }\n }\n }\n }\n };\n ColorPicker.prototype.noColorTile = function (isKey) {\n if (isKey === void 0) { isKey = false; }\n var pValue = this.rgbToHex(this.rgb);\n this.rgb = [];\n this.hsv = [];\n this.triggerEvent('', pValue, '', isKey);\n };\n ColorPicker.prototype.switchToPicker = function () {\n var wrapper = this.getWrapper();\n this.trigger('beforeModeSwitch', { element: this.container, mode: 'Picker' });\n this.unWireEvents();\n ([].slice.call(selectAll('.' + PALETTES, this.container))).forEach(function (ele) {\n detach(ele);\n });\n if (wrapper.classList.contains('e-show-value')) {\n detach(select('.' + INPUTWRAPPER, this.container));\n }\n this.container.style.width = '';\n var grpEle = select('.e-custom-palette', this.container);\n if (this.presetColors) {\n remove(grpEle);\n }\n this.createPicker();\n this.getDragHandler().focus();\n if (!wrapper.classList.contains('e-hide-value')) {\n this.createInput();\n }\n this.refreshPopupPos();\n this.wireEvents();\n };\n ColorPicker.prototype.ctrlBtnClick = function (ele) {\n if (ele.classList.contains(APPLY)) {\n var cValue = this.rgbToHex(this.rgb);\n this.triggerChangeEvent(cValue);\n }\n if (!this.inline) {\n this.toggle();\n this.splitBtn.element.focus();\n }\n };\n ColorPicker.prototype.paletteKeyDown = function (e) {\n var target = e.target;\n if (!target.classList.contains(PALETTES)) {\n return;\n }\n var selectedEle;\n var idx;\n var tiles = [].slice.call(selectAll('.' + TILE, target));\n var prevSelectedEle = (tiles.filter(function (tile) { return tile.classList.contains('e-selected'); })).pop();\n switch (!e.altKey && e.keyCode) {\n case 39:\n e.preventDefault();\n selectedEle = prevSelectedEle ? tiles[this.tilePosition(tiles, prevSelectedEle, this.enableRtl ? -1 : 1)]\n : tiles[this.enableRtl ? tiles.length - 1 : 0];\n this.keySelectionChanges(selectedEle);\n break;\n case 37:\n e.preventDefault();\n selectedEle = prevSelectedEle ? tiles[this.tilePosition(tiles, prevSelectedEle, this.enableRtl ? 1 : -1)]\n : tiles[this.enableRtl ? 0 : tiles.length - 1];\n this.keySelectionChanges(selectedEle);\n break;\n case 38:\n e.preventDefault();\n idx = prevSelectedEle ? this.tilePosition(tiles, prevSelectedEle, -this.columns) : 0;\n selectedEle = tiles[idx] ? tiles[idx] : tiles[idx - this.columns];\n this.keySelectionChanges(selectedEle);\n break;\n case 40:\n e.preventDefault();\n idx = prevSelectedEle ? this.tilePosition(tiles, prevSelectedEle, this.columns) : tiles.length - 1;\n if (tiles[idx]) {\n selectedEle = tiles[idx];\n }\n else {\n idx %= tiles.length;\n idx += tiles[tiles.length - 1].parentElement.childElementCount;\n selectedEle = tiles[idx];\n }\n this.keySelectionChanges(selectedEle);\n break;\n case 13:\n e.preventDefault();\n if (prevSelectedEle) {\n var cValue = prevSelectedEle.getAttribute('aria-label');\n this.enterKeyHandler(cValue ? cValue : '');\n }\n }\n };\n ColorPicker.prototype.keySelectionChanges = function (newEle) {\n this.removeTileSelection();\n this.addTileSelection(newEle);\n if (newEle.classList.contains(NOCOLOR)) {\n this.noColorTile(true);\n }\n else {\n var cValue = newEle.getAttribute('aria-label');\n var pValue = this.rgbToHex(this.rgb);\n this.rgb = this.hexToRgb(cValue);\n this.hsv = this.rgbToHsv.apply(this, this.rgb);\n if (this.getWrapper().classList.contains('e-show-value')) {\n this.updateInput(cValue);\n }\n this.triggerEvent(cValue, pValue, this.convertToRgbString(this.rgb), true);\n }\n };\n ColorPicker.prototype.tilePosition = function (items, element, cIdx) {\n items = Array.prototype.slice.call(items);\n var n = items.length;\n var emptyCount = this.columns - items[n - 1].parentElement.childElementCount;\n var idx = items.indexOf(element);\n idx += cIdx;\n idx < 0 ? idx += n + emptyCount : idx %= n + emptyCount;\n return idx;\n };\n ColorPicker.prototype.inputHandler = function (e) {\n var target = e.target;\n if (!target.value.length) {\n return;\n }\n var hsv;\n var pValue;\n var label = select('.e-float-text', target.parentElement).textContent;\n switch (label) {\n case 'HEX':\n var value = '';\n if ((target.value[0] === '#' && target.value.length !== 5) || (target.value[0] !== '#' && target.value.length !== 4)) {\n value = this.roundValue(target.value);\n }\n if (value.length === 9) {\n pValue = this.rgbToHex(this.rgb);\n this.rgb = this.hexToRgb(value + value.substr(-2));\n this.inputValueChange(this.rgbToHsv.apply(this, this.rgb), pValue, target.value);\n }\n else {\n return;\n }\n break;\n case 'R':\n if (this.rgb[0] !== Number(target.value)) {\n pValue = this.rgbToHex(this.rgb);\n this.rgb[0] = Number(target.value);\n hsv = this.rgbToHsv.apply(this, this.rgb);\n this.inputValueChange(hsv, pValue);\n }\n break;\n case 'G':\n if (this.rgb[1] !== Number(target.value)) {\n pValue = this.rgbToHex(this.rgb);\n this.rgb[1] = Number(target.value);\n hsv = this.rgbToHsv.apply(this, this.rgb);\n this.inputValueChange(hsv, pValue);\n }\n break;\n case 'B':\n if (this.rgb[2] !== Number(target.value)) {\n pValue = this.rgbToHex(this.rgb);\n this.rgb[2] = Number(target.value);\n hsv = this.rgbToHsv.apply(this, this.rgb);\n this.inputValueChange(hsv, pValue);\n }\n break;\n case 'H':\n this.hueSlider.value = Number(target.value);\n break;\n case 'S':\n if (this.hsv[1] !== Number(target.value)) {\n this.hsv[1] = Number(target.value);\n this.updateHsv();\n this.convertToOtherFormat();\n }\n break;\n case 'V':\n if (this.hsv[2] !== Number(target.value)) {\n this.hsv[2] = Number(target.value);\n this.updateHsv();\n this.convertToOtherFormat();\n }\n break;\n case 'A':\n this.opacitySlider.value = Number(target.value);\n break;\n }\n };\n ColorPicker.prototype.inputValueChange = function (hsv, pValue, value) {\n if (hsv[0] !== this.hsv[0]) {\n this.hueSlider.setProperties({ 'value': hsv[0] }, true);\n this.hueSlider.refresh();\n this.setHsvContainerBg(hsv[0]);\n }\n this.hsv = hsv;\n var cValue = this.rgbToHex(this.rgb);\n this.setHandlerPosition();\n this.updateInput(value ? value : cValue);\n var rgba = this.convertToRgbString(this.rgb);\n this.updatePreview(rgba);\n this.triggerEvent(cValue, pValue, rgba);\n };\n ColorPicker.prototype.triggerEvent = function (cValue, pValue, rgba, isKey) {\n if (isKey === void 0) { isKey = false; }\n var hex = cValue.slice(0, 7);\n var eventArgs = {\n currentValue: { hex: hex, rgba: rgba },\n previousValue: { hex: pValue.slice(0, 7), rgba: this.convertToRgbString(this.hexToRgb(pValue)) }\n };\n if (!this.showButtons && !isKey) {\n eventArgs.previousValue = { hex: this.value.slice(0, 7), rgba: this.convertToRgbString(this.hexToRgb(this.value)) };\n this.trigger('change', eventArgs);\n this.setProperties({ 'value': cValue }, true);\n this.element.value = hex ? hex : '#000000';\n }\n else {\n this.trigger('select', eventArgs);\n }\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers.\n * Also it maintains the initial input element from the DOM.\n * @method destroy\n * @return {void}\n */\n ColorPicker.prototype.destroy = function () {\n var _this = this;\n var wrapper = this.getWrapper();\n _super.prototype.destroy.call(this);\n ['tabindex', 'spellcheck'].forEach(function (attr) { _this.element.removeAttribute(attr); });\n if (this.inline) {\n this.unWireEvents();\n this.destroyOtherComp();\n }\n else {\n if (this.isPopupOpen()) {\n this.unWireEvents();\n this.destroyOtherComp();\n }\n this.splitBtn.destroy();\n this.splitBtn = null;\n }\n this.tileRipple();\n this.tileRipple = null;\n this.ctrlBtnRipple();\n this.ctrlBtnRipple = null;\n detach(this.element.nextElementSibling);\n wrapper.parentElement.insertBefore(this.element, wrapper);\n detach(wrapper);\n this.container = null;\n };\n ColorPicker.prototype.destroyOtherComp = function () {\n if (this.isPicker()) {\n this.hueSlider.destroy();\n this.opacitySlider.destroy();\n this.hueSlider = null;\n this.opacitySlider = null;\n var tooltipInst = this.getTooltipInst();\n tooltipInst.close();\n tooltipInst.destroy();\n this.tooltipEle = null;\n }\n };\n ColorPicker.prototype.isPopupOpen = function () {\n return this.getPopupEle().classList.contains('e-popup-open');\n };\n ColorPicker.prototype.unWireEvents = function () {\n if (this.isPicker()) {\n var dragHandler = this.getDragHandler();\n EventHandler.remove(dragHandler, 'keydown', this.pickerKeyDown);\n EventHandler.remove(this.getHsvContainer(), 'mousedown touchstart', this.handlerDown);\n if (this.modeSwitcher || this.showButtons) {\n EventHandler.remove(select('.' + CTRLSWITCH, this.container), 'click', this.btnClickHandler);\n }\n if (!this.getWrapper().classList.contains('e-hide-value')) {\n EventHandler.remove(select('.' + FORMATSWITCH, this.container), 'click', this.formatSwitchHandler);\n EventHandler.remove(select('.' + HEX, this.container), 'input', this.inputHandler);\n }\n EventHandler.remove(select('.' + PREVIOUS, this.container), 'click', this.previewHandler);\n }\n else {\n EventHandler.remove(this.container, 'click', this.paletteClickHandler);\n EventHandler.remove(this.container, 'keydown', this.paletteKeyDown);\n }\n };\n ColorPicker.prototype.roundValue = function (value) {\n if (!value) {\n return '';\n }\n if (value[0] !== '#') {\n value = '#' + value;\n }\n var len = value.length;\n if (len === 4) {\n value += 'f';\n len = 5;\n }\n if (len === 5) {\n var tempValue = '';\n for (var i = 1, len_1 = value.length; i < len_1; i++) {\n tempValue += (value.charAt(i) + value.charAt(i));\n }\n value = '#' + tempValue;\n len = 9;\n }\n if (len === 7) {\n value += 'ff';\n }\n return value;\n };\n ColorPicker.prototype.hexToRgb = function (hex) {\n if (!hex) {\n return [];\n }\n hex = hex.trim();\n if (hex.length !== 9) {\n hex = this.roundValue(hex);\n }\n var opacity = Number((parseInt(hex.slice(-2), 16) / 255).toFixed(2));\n hex = hex.slice(1, 7);\n var bigInt = parseInt(hex, 16);\n var h = [];\n h.push((bigInt >> 16) & 255);\n h.push((bigInt >> 8) & 255);\n h.push(bigInt & 255);\n h.push(opacity);\n return h;\n };\n ColorPicker.prototype.rgbToHsv = function (r, g, b, opacity) {\n if (this.rgb && !this.rgb.length) {\n return [];\n }\n r /= 255;\n g /= 255;\n b /= 255;\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var h;\n var s;\n var v = max;\n var d = max - min;\n s = max === 0 ? 0 : d / max;\n if (max === min) {\n h = 0;\n }\n else {\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n var hsv = [Math.round(h * 360), Math.round(s * 1000) / 10, Math.round(v * 1000) / 10];\n if (!isNullOrUndefined(opacity)) {\n hsv.push(opacity);\n }\n return hsv;\n };\n ColorPicker.prototype.hsvToRgb = function (h, s, v, opacity) {\n var r;\n var g;\n var b;\n var i;\n var f;\n var p;\n var q;\n var t;\n s /= 100;\n v /= 100;\n if (s === 0) {\n r = g = b = v;\n return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), opacity];\n }\n h /= 60;\n i = Math.floor(h);\n f = h - i;\n p = v * (1 - s);\n q = v * (1 - s * f);\n t = v * (1 - s * (1 - f));\n switch (i) {\n case 0:\n r = v;\n g = t;\n b = p;\n break;\n case 1:\n r = q;\n g = v;\n b = p;\n break;\n case 2:\n r = p;\n g = v;\n b = t;\n break;\n case 3:\n r = p;\n g = q;\n b = v;\n break;\n case 4:\n r = t;\n g = p;\n b = v;\n break;\n default:\n r = v;\n g = p;\n b = q;\n }\n var rgb = [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];\n if (!isNullOrUndefined(opacity)) {\n rgb.push(opacity);\n }\n return rgb;\n };\n ColorPicker.prototype.rgbToHex = function (rgb) {\n return rgb.length ? ('#' + this.hex(rgb[0]) + this.hex(rgb[1]) + this.hex(rgb[2]) +\n (!isNullOrUndefined(rgb[3]) ? (rgb[3] !== 0 ? (Math.round(rgb[3] * 255) + 0x10000).toString(16).substr(-2) : '00') : '')) : '';\n };\n ColorPicker.prototype.hex = function (x) {\n return ('0' + x.toString(16)).slice(-2);\n };\n ColorPicker.prototype.changeModeSwitcherProp = function (prop) {\n var ctrlSwitchWrapper = select('.' + CTRLSWITCH, this.container);\n if (prop) {\n if (ctrlSwitchWrapper) {\n this.appendModeSwitchBtn();\n }\n else {\n this.createCtrlBtn();\n if (this.isPicker() && !this.disabled) {\n this.addCtrlSwitchEvent();\n }\n }\n }\n else {\n if (ctrlSwitchWrapper) {\n if (this.showButtons) {\n detach(select('.' + MODESWITCH, ctrlSwitchWrapper));\n }\n else {\n remove(ctrlSwitchWrapper);\n }\n }\n }\n };\n ColorPicker.prototype.changeShowBtnProps = function (prop) {\n var ctrlBtnWrapper = select('.' + CTRLSWITCH, this.container);\n if (prop) {\n if (ctrlBtnWrapper) {\n remove(ctrlBtnWrapper);\n }\n this.createCtrlBtn();\n if (this.isPicker() && !this.disabled) {\n this.addCtrlSwitchEvent();\n }\n }\n else {\n if (this.modeSwitcher) {\n detach(select('.' + CTRLBTN, ctrlBtnWrapper));\n }\n else {\n remove(ctrlBtnWrapper);\n }\n }\n };\n ColorPicker.prototype.changeValueProp = function (newProp) {\n if (this.isPicker()) {\n this.rgb = this.hexToRgb(newProp);\n this.hsv = this.rgbToHsv.apply(this, this.rgb);\n this.setHandlerPosition();\n detach(closest(this.hueSlider.element, '.e-slider-preview'));\n this.createSlider();\n this.setHsvContainerBg();\n this.updateOpacitySliderBg();\n this.updateInput(newProp);\n }\n else {\n this.removeTileSelection();\n this.addTileSelection(select('span[aria-label=\"' + newProp + '\"]', this.container));\n }\n this.element.value = newProp.slice(0, 7);\n };\n ColorPicker.prototype.setInputEleProps = function (prop) {\n remove(select('.' + INPUTWRAPPER, this.container));\n this.createInput();\n };\n ColorPicker.prototype.changeDisabledProp = function (newProp) {\n if (this.isPicker()) {\n this.hueSlider.enabled = !newProp;\n this.opacitySlider.enabled = !newProp;\n this.setInputEleProps(newProp);\n }\n if (newProp) {\n this.toggleDisabled(true);\n this.unWireEvents();\n }\n else {\n this.toggleDisabled(false);\n this.wireEvents();\n }\n };\n ColorPicker.prototype.changeCssClassProps = function (newProp, oldProp) {\n var wrapper = this.getWrapper();\n var popupWrapper = this.getPopupEle();\n if (oldProp) {\n removeClass([wrapper, popupWrapper], oldProp.split(' '));\n }\n if (newProp) {\n addClass([wrapper, popupWrapper], newProp.split(' '));\n }\n };\n ColorPicker.prototype.changeRtlProps = function (newProp) {\n if (newProp) {\n addClass([this.getWrapper()], 'e-rtl');\n }\n else {\n removeClass([this.getWrapper()], 'e-rtl');\n }\n };\n ColorPicker.prototype.changePaletteProps = function () {\n detach(this.container.children[0]);\n this.container.style.width = '';\n this.createPalette();\n };\n /**\n * Called internally if any of the property value changed.\n * @param {ColorPickerModel} newProp\n * @param {ColorPickerModel} oldProp\n * @returns void\n * @private\n */\n ColorPicker.prototype.onPropertyChanged = function (newProp, oldProp) {\n var _this = this;\n var wrapper = this.getWrapper();\n if (!this.inline && isNullOrUndefined(newProp.inline)) {\n var otherCompModel = ['disabled', 'enableRtl'];\n this.splitBtn.setProperties(getModel(newProp, otherCompModel));\n if (!this.isPopupOpen()) {\n if (newProp.value) {\n select('.' + SPLITPREVIEW, this.splitBtn.element).style.backgroundColor = newProp.value;\n }\n this.changeCssClassProps(newProp.cssClass, oldProp.cssClass);\n this.changeRtlProps(newProp.enableRtl);\n return;\n }\n }\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'inline':\n if (newProp.inline) {\n this.getWrapper().appendChild(this.container);\n this.splitBtn.destroy();\n detach(this.element.nextElementSibling);\n if (!this.container.children.length) {\n this.createWidget();\n }\n }\n else {\n this.destroyOtherComp();\n this.unWireEvents();\n this.container.innerHTML = '';\n this.createSplitBtn();\n }\n break;\n case 'cssClass':\n if (this.isPicker()) {\n if (wrapper.classList.contains('e-hide-value')) {\n this.createInput();\n this.addvalueEventHandler();\n }\n newProp.cssClass.split(' ').forEach(function (cls) {\n if (cls === 'e-hide-value') {\n remove(select('.' + INPUTWRAPPER, _this.container));\n }\n });\n }\n else {\n if (wrapper.classList.contains('e-show-value')) {\n remove(select('.' + INPUTWRAPPER, this.container));\n }\n newProp.cssClass.split(' ').forEach(function (cls) {\n if (cls === 'e-show-value') {\n _this.createInput(1);\n _this.addInputEvent();\n }\n });\n }\n this.changeCssClassProps(newProp.cssClass, oldProp.cssClass);\n break;\n case 'enableRtl':\n if (this.isPicker()) {\n this.hueSlider.enableRtl = newProp.enableRtl;\n this.opacitySlider.enableRtl = newProp.enableRtl;\n this.setInputEleProps(newProp.enableRtl);\n }\n this.changeRtlProps(newProp.enableRtl);\n break;\n case 'disabled':\n this.changeDisabledProp(newProp.disabled);\n break;\n case 'value':\n this.changeValueProp(newProp.value);\n break;\n case 'showButtons':\n this.changeShowBtnProps(newProp.showButtons);\n break;\n case 'mode':\n if (newProp.mode === 'Picker') {\n this.switchToPicker();\n }\n else {\n this.switchToPalette();\n }\n break;\n case 'modeSwitcher':\n this.changeModeSwitcherProp(newProp.modeSwitcher);\n break;\n case 'columns':\n case 'presetColors':\n if (!this.isPicker()) {\n this.changePaletteProps();\n }\n break;\n case 'noColor':\n if (newProp.noColor) {\n if (this.mode === 'Palette' && !this.modeSwitcher) {\n this.setNoColor();\n }\n }\n else {\n this.changePaletteProps();\n }\n break;\n }\n }\n };\n __decorate([\n Property('#008000')\n ], ColorPicker.prototype, \"value\", void 0);\n __decorate([\n Property('')\n ], ColorPicker.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], ColorPicker.prototype, \"disabled\", void 0);\n __decorate([\n Property(false)\n ], ColorPicker.prototype, \"enableRtl\", void 0);\n __decorate([\n Property('Picker')\n ], ColorPicker.prototype, \"mode\", void 0);\n __decorate([\n Property(true)\n ], ColorPicker.prototype, \"modeSwitcher\", void 0);\n __decorate([\n Property(null)\n ], ColorPicker.prototype, \"presetColors\", void 0);\n __decorate([\n Property(true)\n ], ColorPicker.prototype, \"showButtons\", void 0);\n __decorate([\n Property(10)\n ], ColorPicker.prototype, \"columns\", void 0);\n __decorate([\n Property(false)\n ], ColorPicker.prototype, \"inline\", void 0);\n __decorate([\n Property(false)\n ], ColorPicker.prototype, \"noColor\", void 0);\n __decorate([\n Property(false)\n ], ColorPicker.prototype, \"enablePersistence\", void 0);\n __decorate([\n Event()\n ], ColorPicker.prototype, \"select\", void 0);\n __decorate([\n Event()\n ], ColorPicker.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], ColorPicker.prototype, \"beforeTileRender\", void 0);\n __decorate([\n Event()\n ], ColorPicker.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], ColorPicker.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], ColorPicker.prototype, \"beforeClose\", void 0);\n __decorate([\n Event()\n ], ColorPicker.prototype, \"beforeModeSwitch\", void 0);\n ColorPicker = __decorate([\n NotifyPropertyChanges\n ], ColorPicker);\n return ColorPicker;\n}(Component));\nexport { ColorPicker };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n///
\nimport { EventHandler, Property, Internationalization, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { KeyboardEvents, Animation, Event, L10n, Browser, formatUnit } from '@syncfusion/ej2-base';\nimport { detach, addClass, removeClass, closest, attributes } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, setValue, getUniqueID } from '@syncfusion/ej2-base';\nimport { Popup } from '@syncfusion/ej2-popups';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { Calendar } from '../calendar/calendar';\n//class constant defination\nvar DATEWRAPPER = 'e-date-wrapper';\nvar ROOT = 'e-datepicker';\nvar POPUPWRAPPER = 'e-popup-wrapper';\nvar INPUTWRAPPER = 'e-input-group-icon';\nvar POPUP = 'e-popup';\nvar INPUTCONTAINER = 'e-input-group';\nvar INPUTFOCUS = 'e-input-focus';\nvar INPUTROOT = 'e-input';\nvar ERROR = 'e-error';\nvar RTL = 'e-rtl';\nvar LINK = 'e-day';\nvar ACTIVE = 'e-active';\nvar OVERFLOW = 'e-date-overflow';\nvar DATEICON = 'e-date-icon';\nvar ICONS = 'e-icons';\nvar OPENDURATION = 300;\nvar CLOSEDURATION = 200;\nvar OFFSETVALUE = 4;\n/**\n * Represents the DatePicker component that allows user to select\n * or enter a date value.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar DatePicker = /** @class */ (function (_super) {\n __extends(DatePicker, _super);\n /**\n * Constructor for creating the widget.\n */\n function DatePicker(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.previousElementValue = '';\n _this.isDateIconClicked = false;\n _this.keyConfigs = {\n altUpArrow: 'alt+uparrow',\n altDownArrow: 'alt+downarrow',\n escape: 'escape',\n enter: 'enter',\n controlUp: 'ctrl+38',\n controlDown: 'ctrl+40',\n moveDown: 'downarrow',\n moveUp: 'uparrow',\n moveLeft: 'leftarrow',\n moveRight: 'rightarrow',\n select: 'enter',\n home: 'home',\n end: 'end',\n pageUp: 'pageup',\n pageDown: 'pagedown',\n shiftPageUp: 'shift+pageup',\n shiftPageDown: 'shift+pagedown',\n controlHome: 'ctrl+home',\n controlEnd: 'ctrl+end',\n tab: 'tab'\n };\n _this.calendarKeyConfigs = {\n escape: 'escape',\n enter: 'enter',\n tab: 'tab'\n };\n return _this;\n }\n /**\n * To Initialize the control rendering.\n * @return void\n * @private\n */\n DatePicker.prototype.render = function () {\n this.initialize();\n this.bindEvents();\n };\n DatePicker.prototype.setAllowEdit = function () {\n if (this.allowEdit) {\n if (!this.readonly) {\n this.inputElement.removeAttribute('readonly');\n }\n }\n else {\n attributes(this.inputElement, { 'readonly': '' });\n }\n };\n DatePicker.prototype.initialize = function () {\n this.createInput();\n this.setAllowEdit();\n this.updateInput();\n this.previousElementValue = this.inputElement.value;\n this.previousDate = new Date(+this.value);\n };\n DatePicker.prototype.createInput = function () {\n var ariaAttrs = {\n 'aria-live': 'assertive', 'aria-atomic': 'true',\n 'aria-haspopup': 'true', 'aria-activedescendant': 'null',\n 'aria-owns': this.element.id + '_options', 'aria-expanded': 'false', 'role': 'combobox', 'autocomplete': 'off',\n 'autocorrect': 'off', 'autocapitalize': 'off', 'spellcheck': 'false'\n };\n if (this.getModuleName() === 'datepicker') {\n var l10nLocale = { placeholder: null };\n this.globalize = new Internationalization(this.locale);\n this.l10n = new L10n('datepicker', l10nLocale, this.locale);\n this.setProperties({ placeholder: this.placeholder || this.l10n.getConstant('placeholder') }, true);\n }\n this.inputWrapper = Input.createInput({\n element: this.inputElement,\n floatLabelType: this.floatLabelType,\n properties: {\n readonly: this.readonly,\n placeholder: this.placeholder,\n cssClass: this.cssClass,\n enabled: this.enabled,\n enableRtl: this.enableRtl,\n showClearButton: this.showClearButton,\n },\n buttons: [INPUTWRAPPER + ' ' + DATEICON + ' ' + ICONS]\n }, this.createElement);\n this.setWidth(this.width);\n if (this.inputElement.name !== '') {\n this.inputElement.setAttribute('name', '' + this.inputElement.getAttribute('name'));\n }\n else {\n this.inputElement.setAttribute('name', '' + this.element.id);\n }\n attributes(this.inputElement, ariaAttrs);\n if (!this.enabled) {\n this.inputElement.setAttribute('aria-disabled', 'true');\n }\n else {\n this.inputElement.setAttribute('aria-disabled', 'false');\n }\n Input.addAttributes({ 'aria-label': 'select' }, this.inputWrapper.buttons[0]);\n addClass([this.inputWrapper.container], DATEWRAPPER);\n };\n DatePicker.prototype.updateInput = function () {\n if (this.value && !this.isCalendar()) {\n this.disabledDates();\n }\n if (+new Date('' + this.value)) {\n if (typeof this.value === 'string') {\n this.value = this.checkDateValue(new Date('' + this.value));\n var dateOptions = void 0;\n if (this.getModuleName() === 'datetimepicker') {\n dateOptions = {\n format: !isNullOrUndefined(this.format) ? this.format : this.dateTimeFormat,\n type: 'dateTime', skeleton: 'yMd'\n };\n }\n else {\n dateOptions = { format: this.format, type: 'dateTime', skeleton: 'yMd' };\n }\n var dateString = this.globalize.formatDate(this.value, dateOptions);\n this.setProperties({ value: this.globalize.parseDate(dateString, dateOptions) }, true);\n }\n }\n else {\n this.setProperties({ value: null }, true);\n }\n if (this.strictMode) {\n //calls the Calendar processDate protected method to update the date value according to the strictMode true behaviour.\n _super.prototype.validateDate.call(this);\n this.minMaxUpdates();\n _super.prototype.minMaxUpdate.call(this);\n }\n if (!isNullOrUndefined(this.value)) {\n var dateValue = this.value;\n var dateString = void 0;\n var tempFormat = !isNullOrUndefined(this.format) ? this.format : this.dateTimeFormat;\n if (this.getModuleName() === 'datetimepicker') {\n dateString = this.globalize.formatDate(this.value, { format: tempFormat, type: 'dateTime', skeleton: 'yMd' });\n }\n else {\n dateString = this.globalize.formatDate(this.value, { format: this.format, type: 'dateTime', skeleton: 'yMd' });\n }\n if ((+dateValue <= +this.max) && (+dateValue >= +this.min)) {\n Input.setValue(dateString, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n else {\n var value = (+dateValue >= +this.max || !+this.value) || (!+this.value || +dateValue <= +this.min);\n if (!this.strictMode && value) {\n Input.setValue(dateString, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n }\n }\n if (isNullOrUndefined(this.value) && this.strictMode) {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n }\n this.changedArgs = { value: this.value };\n this.errorClass();\n };\n ;\n DatePicker.prototype.minMaxUpdates = function () {\n if (!isNullOrUndefined(this.value) && this.value < this.min && this.min <= this.max && this.strictMode) {\n this.setProperties({ value: this.min }, true);\n this.changedArgs = { value: this.value };\n }\n else {\n if (!isNullOrUndefined(this.value) && this.value > this.max && this.min <= this.max && this.strictMode) {\n this.setProperties({ value: this.max }, true);\n this.changedArgs = { value: this.value };\n }\n }\n };\n DatePicker.prototype.bindEvents = function () {\n if (this.enabled) {\n EventHandler.add(this.inputWrapper.buttons[0], 'mousedown touchstart', this.dateIconHandler, this);\n EventHandler.add(this.inputElement, 'focus', this.inputFocusHandler, this);\n EventHandler.add(this.inputElement, 'blur', this.inputBlurHandler, this);\n // To prevent the twice triggering.\n EventHandler.add(this.inputElement, 'change', this.inputChangeHandler, this);\n if (this.showClearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler, this);\n }\n if (this.formElement) {\n EventHandler.add(this.formElement, 'reset', this.resetFormHandler, this);\n }\n }\n else {\n EventHandler.remove(this.inputWrapper.buttons[0], 'mousedown touchstart', this.dateIconHandler);\n EventHandler.remove(this.inputElement, 'focus', this.inputFocusHandler);\n EventHandler.remove(this.inputElement, 'blur', this.inputBlurHandler);\n EventHandler.remove(this.inputElement, 'change', this.inputChangeHandler);\n if (this.showClearButton) {\n EventHandler.remove(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler);\n }\n if (this.formElement) {\n EventHandler.remove(this.formElement, 'reset', this.resetFormHandler);\n }\n }\n this.keyboardModules = new KeyboardEvents(this.inputElement, {\n eventName: 'keydown',\n keyAction: this.inputKeyActionHandle.bind(this),\n keyConfigs: this.keyConfigs\n });\n };\n DatePicker.prototype.resetFormHandler = function () {\n if (this.inputElement.getAttribute('value')) {\n this.value = this.checkDateValue(new Date('' + this.element.getAttribute('value')));\n }\n else {\n this.value = null;\n if (this.inputElement) {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n attributes(this.inputElement, { 'aria-invalid': 'false' });\n removeClass([this.inputWrapper.container], ERROR);\n }\n }\n };\n DatePicker.prototype.inputChangeHandler = function (e) {\n e.stopPropagation();\n };\n DatePicker.prototype.bindClearEvent = function () {\n if (this.showClearButton && this.inputWrapper.clearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler, this);\n }\n };\n DatePicker.prototype.resetHandler = function (e) {\n e.preventDefault();\n this.clear(e);\n };\n DatePicker.prototype.clear = function (event) {\n this.setProperties({ value: null }, true);\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n this.updateInput();\n this.changeEvent(event);\n };\n DatePicker.prototype.dateIconHandler = function (e) {\n e.preventDefault();\n if (!this.readonly) {\n if (this.isCalendar()) {\n this.hide(e);\n }\n else {\n this.isDateIconClicked = true;\n this.show(null, e);\n if (this.getModuleName() === 'datetimepicker') {\n this.inputElement.focus();\n }\n this.inputElement.focus();\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n addClass(this.inputWrapper.buttons, ACTIVE);\n }\n }\n };\n DatePicker.prototype.CalendarKeyActionHandle = function (e) {\n switch (e.action) {\n case 'escape':\n if (this.isCalendar()) {\n this.hide(e);\n }\n else {\n this.inputWrapper.container.children[this.index].blur();\n }\n break;\n case 'enter':\n if (!this.isCalendar()) {\n this.show(null, e);\n }\n else {\n if (+this.value !== +this.currentDate && !this.isCalendar()) {\n this.inputWrapper.container.children[this.index].focus();\n }\n }\n if (this.getModuleName() === 'datetimepicker') {\n this.inputElement.focus();\n }\n break;\n case 'tab':\n this.hide(e);\n }\n };\n DatePicker.prototype.inputFocusHandler = function () {\n var focusArguments = {\n model: this\n };\n this.isDateIconClicked = false;\n this.trigger('focus', focusArguments);\n };\n DatePicker.prototype.inputBlurHandler = function (e) {\n this.strictModeUpdate();\n this.updateInput();\n this.changeTrigger(e);\n this.errorClass();\n if (this.isCalendar() && document.activeElement === this.inputElement) {\n this.hide(e);\n }\n if (this.getModuleName() === 'datepicker') {\n var blurArguments = {\n model: this\n };\n this.trigger('blur', blurArguments);\n }\n if (this.isCalendar()) {\n this.calendarKeyboardModules = new KeyboardEvents(this.calendarElement.children[1].firstElementChild, {\n eventName: 'keydown',\n keyAction: this.CalendarKeyActionHandle.bind(this),\n keyConfigs: this.calendarKeyConfigs\n });\n }\n };\n DatePicker.prototype.documentHandler = function (e) {\n if (e.type !== 'touchstart') {\n e.preventDefault();\n }\n var target = e.target;\n if (!(closest(target, '.e-datepicker.e-popup-wrapper'))\n && !(closest(target, '.' + INPUTCONTAINER) === this.inputWrapper.container)\n && (!target.classList.contains('e-day'))) {\n this.hide(e);\n }\n };\n DatePicker.prototype.inputKeyActionHandle = function (e) {\n switch (e.action) {\n case 'altUpArrow':\n this.hide(e);\n this.inputElement.focus();\n break;\n case 'altDownArrow':\n this.strictModeUpdate();\n this.updateInput();\n this.changeTrigger(e);\n if (this.getModuleName() === 'datepicker') {\n this.show(null, e);\n }\n break;\n case 'escape':\n this.hide(e);\n break;\n case 'enter':\n this.strictModeUpdate();\n this.updateInput();\n this.changeTrigger(e);\n this.errorClass();\n if (!this.isCalendar() && document.activeElement === this.inputElement) {\n this.hide(e);\n }\n break;\n case 'tab':\n this.strictModeUpdate();\n this.updateInput();\n this.changeTrigger(e);\n this.errorClass();\n this.hide(e);\n break;\n default:\n this.previousDate = (!isNullOrUndefined(this.value) && new Date('' + this.value) || null);\n if (this.isCalendar()) {\n _super.prototype.keyActionHandle.call(this, e);\n }\n }\n };\n DatePicker.prototype.strictModeUpdate = function () {\n var format;\n if (this.getModuleName() === 'datetimepicker') {\n format = !isNullOrUndefined(this.format) ? this.format : this.dateTimeFormat;\n }\n else {\n format = isNullOrUndefined(this.format) ? this.format : this.format.replace('dd', 'd');\n }\n if (!isNullOrUndefined(format)) {\n var len = format.split('M').length - 1;\n if (len < 3) {\n format = format.replace('MM', 'M');\n }\n }\n var dateOptions;\n if (this.getModuleName() === 'datetimepicker') {\n dateOptions = {\n format: !isNullOrUndefined(this.format) ? this.format : this.dateTimeFormat,\n type: 'dateTime', skeleton: 'yMd'\n };\n }\n else {\n dateOptions = { format: format, type: 'dateTime', skeleton: 'yMd' };\n }\n var date = this.globalize.parseDate(this.inputElement.value, dateOptions);\n if (this.strictMode && date) {\n Input.setValue(this.globalize.formatDate(date, dateOptions), this.inputElement, this.floatLabelType, this.showClearButton);\n if (this.inputElement.value !== this.previousElementValue) {\n this.setProperties({ value: date }, true);\n }\n }\n else if (!this.strictMode) {\n if (this.inputElement.value !== this.previousElementValue) {\n this.setProperties({ value: date }, true);\n }\n }\n if (this.strictMode && !date && this.inputElement.value === '') {\n this.setProperties({ value: null }, true);\n }\n if (isNaN(+this.value)) {\n this.setProperties({ value: null }, true);\n }\n if (isNullOrUndefined(this.value)) {\n this.currentDate = new Date(new Date().setHours(0, 0, 0, 0));\n }\n };\n DatePicker.prototype.createCalendar = function () {\n var _this = this;\n this.popupWrapper = this.createElement('div', { className: '' + ROOT + ' ' + POPUPWRAPPER });\n if (!isNullOrUndefined(this.cssClass)) {\n this.popupWrapper.classList.add(this.cssClass);\n }\n if (Browser.isDevice) {\n this.modelHeader();\n this.modal = this.createElement('div');\n this.modal.className = '' + ROOT + ' e-date-modal';\n document.body.className += ' ' + OVERFLOW;\n this.modal.style.display = 'block';\n document.body.appendChild(this.modal);\n }\n //this.calendarElement represent the Calendar object from the Calendar class.\n this.calendarElement.querySelector('table tbody').className = '';\n this.popupObj = new Popup(this.popupWrapper, {\n content: this.calendarElement,\n relateTo: Browser.isDevice ? document.body : this.inputWrapper.container,\n position: Browser.isDevice ? { X: 'center', Y: 'center' } : { X: 'left', Y: 'bottom' },\n offsetY: OFFSETVALUE,\n targetType: 'container',\n enableRtl: this.enableRtl,\n zIndex: this.zIndex,\n collision: Browser.isDevice ? { X: 'fit', Y: 'fit' } : { X: 'flip', Y: 'flip' },\n open: function () {\n if (_this.getModuleName() !== 'datetimepicker') {\n if (document.activeElement !== _this.inputElement) {\n _this.calendarElement.children[1].firstElementChild.focus();\n _this.calendarKeyboardModules = new KeyboardEvents(_this.calendarElement.children[1].firstElementChild, {\n eventName: 'keydown',\n keyAction: _this.CalendarKeyActionHandle.bind(_this),\n keyConfigs: _this.calendarKeyConfigs\n });\n _this.calendarKeyboardModules = new KeyboardEvents(_this.inputWrapper.container.children[_this.index], {\n eventName: 'keydown',\n keyAction: _this.CalendarKeyActionHandle.bind(_this),\n keyConfigs: _this.calendarKeyConfigs\n });\n }\n }\n }, close: function () {\n if (_this.isDateIconClicked) {\n _this.inputWrapper.container.children[_this.index].focus();\n }\n if (_this.value) {\n _this.disabledDates();\n }\n if (_this.popupObj) {\n _this.popupObj.destroy();\n }\n detach(_this.popupWrapper);\n _this.popupObj = _this.popupWrapper = null;\n _this.setAriaAttributes();\n }\n });\n this.popupObj.element.classList.add(this.cssClass);\n this.setAriaAttributes();\n };\n DatePicker.prototype.modelHeader = function () {\n var modelHeader = this.createElement('div', { className: 'e-model-header' });\n var yearHeading = this.createElement('h1', { className: 'e-model-year' });\n var h2 = this.createElement('div');\n var daySpan = this.createElement('span', { className: 'e-model-day' });\n var monthSpan = this.createElement('span', { className: 'e-model-month' });\n yearHeading.textContent = '' + this.globalize.formatDate(this.value || new Date(), { format: 'y', skeleton: 'dateTime' });\n daySpan.textContent = '' + this.globalize.formatDate(this.value || new Date(), { format: 'E', skeleton: 'dateTime' }) + ', ';\n monthSpan.textContent = '' + this.globalize.formatDate(this.value || new Date(), { format: 'MMM d', skeleton: 'dateTime' });\n modelHeader.appendChild(yearHeading);\n h2.appendChild(daySpan);\n h2.appendChild(monthSpan);\n modelHeader.appendChild(h2);\n this.calendarElement.insertBefore(modelHeader, this.calendarElement.firstElementChild);\n };\n DatePicker.prototype.changeTrigger = function (event) {\n if (this.inputElement.value !== this.previousElementValue) {\n if (((this.previousDate && this.previousDate.valueOf()) !== (this.value && this.value.valueOf()))) {\n this.changedArgs.value = this.value;\n this.changedArgs.event = this.changedArgs.event = event || null;\n this.changedArgs.element = this.element;\n this.changedArgs.isInteracted = !isNullOrUndefined(event);\n this.trigger('change', this.changedArgs);\n this.previousElementValue = this.inputElement.value;\n this.previousDate = new Date('' + this.value);\n }\n }\n };\n DatePicker.prototype.navigatedEvent = function () {\n this.trigger('navigated', this.navigatedArgs);\n };\n DatePicker.prototype.changeEvent = function (event) {\n if (((this.previousDate && this.previousDate.valueOf()) !== (this.value && this.value.valueOf()))) {\n this.selectCalendar(event);\n this.changedArgs.event = event ? event : null;\n this.changedArgs.element = this.element;\n this.changedArgs.isInteracted = !isNullOrUndefined(event);\n this.trigger('change', this.changedArgs);\n this.previousDate = this.value && new Date(+this.value);\n this.hide(event);\n this.previousElementValue = this.inputElement.value;\n this.errorClass();\n }\n };\n DatePicker.prototype.selectCalendar = function (e) {\n var date;\n var tempFormat;\n if (this.getModuleName() === 'datetimepicker') {\n tempFormat = !isNullOrUndefined(this.format) ? this.format : this.dateTimeFormat;\n }\n else {\n tempFormat = this.format;\n }\n if (this.value) {\n if (this.getModuleName() === 'datetimepicker') {\n date = this.globalize.formatDate(this.changedArgs.value, { format: tempFormat, type: 'dateTime', skeleton: 'yMd' });\n }\n else {\n date = this.globalize.formatDate(this.changedArgs.value, { format: this.format, type: 'dateTime', skeleton: 'yMd' });\n }\n }\n if (!isNullOrUndefined(date)) {\n Input.setValue(date, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n };\n DatePicker.prototype.isCalendar = function () {\n if (this.popupWrapper && this.popupWrapper.classList.contains('' + POPUPWRAPPER)) {\n return true;\n }\n return false;\n };\n DatePicker.prototype.setWidth = function (width) {\n if (typeof width === 'number') {\n this.inputWrapper.container.style.width = formatUnit(this.width);\n }\n else if (typeof width === 'string') {\n this.inputWrapper.container.style.width = (width.match(/px|%|em/)) ? (this.width) : (formatUnit(this.width));\n }\n else {\n this.inputWrapper.container.style.width = '100%';\n }\n };\n /**\n * Shows the Calendar.\n * @returns void\n */\n DatePicker.prototype.show = function (type, e) {\n if ((this.enabled && this.readonly) || !this.enabled || this.popupObj) {\n return;\n }\n else {\n var prevent_1 = true;\n var outOfRange = void 0;\n if (!isNullOrUndefined(this.value) && !(+this.value >= +this.min && +this.value <= +this.max)) {\n outOfRange = new Date('' + this.value);\n this.setProperties({ 'value': null }, true);\n }\n else {\n outOfRange = this.value || null;\n }\n if (!this.isCalendar()) {\n _super.prototype.render.call(this);\n this.setProperties({ 'value': outOfRange || null }, true);\n this.previousDate = outOfRange;\n this.createCalendar();\n }\n this.preventArgs = {\n preventDefault: function () {\n prevent_1 = false;\n },\n popup: this.popupObj,\n event: e || null,\n cancel: false,\n appendTo: document.body\n };\n this.trigger('open', this.preventArgs);\n if (prevent_1 && !this.preventArgs.cancel) {\n addClass(this.inputWrapper.buttons, ACTIVE);\n this.preventArgs.appendTo.appendChild(this.popupWrapper);\n this.popupObj.refreshPosition(this.inputElement);\n var openAnimation = {\n name: 'FadeIn',\n duration: Browser.isDevice ? 0 : OPENDURATION,\n };\n if (this.zIndex === 1000) {\n this.popupObj.show(new Animation(openAnimation), this.element);\n }\n else {\n this.popupObj.show(new Animation(openAnimation), null);\n }\n this.setAriaAttributes();\n }\n else {\n this.popupObj.destroy();\n this.popupWrapper = this.popupObj = null;\n }\n EventHandler.add(document, 'mousedown touchstart', this.documentHandler, this);\n }\n };\n /**\n * Hide the Calendar.\n * @returns void\n */\n DatePicker.prototype.hide = function (event) {\n if (!isNullOrUndefined(this.popupWrapper)) {\n var prevent_2 = true;\n this.preventArgs = {\n preventDefault: function () {\n prevent_2 = false;\n },\n popup: this.popupObj,\n event: event || null,\n cancel: false\n };\n removeClass(this.inputWrapper.buttons, ACTIVE);\n removeClass([document.body], OVERFLOW);\n if (this.isCalendar()) {\n this.trigger('close', this.preventArgs);\n }\n if (this.isCalendar() && (prevent_2 && !this.preventArgs.cancel)) {\n var closeAnimation = {\n name: 'FadeOut',\n duration: CLOSEDURATION,\n };\n this.popupObj.hide();\n this.keyboardModule.destroy();\n removeClass(this.inputWrapper.buttons, ACTIVE);\n }\n this.setAriaAttributes();\n this.previousElementValue = this.inputElement.value;\n if (Browser.isDevice && this.modal) {\n this.modal.style.display = 'none';\n this.modal.outerHTML = '';\n this.modal = null;\n }\n EventHandler.remove(document, 'mousedown touchstart', this.documentHandler);\n }\n if (Browser.isDevice) {\n this.element.removeAttribute('readonly');\n }\n };\n /**\n * Sets the focus to widget for interaction.\n * @returns void\n */\n DatePicker.prototype.focusIn = function (triggerEvent) {\n if (document.activeElement !== this.inputElement && this.enabled) {\n this.inputElement.focus();\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n var focusArguments = {\n model: this\n };\n this.trigger('focus', focusArguments);\n }\n };\n /**\n * Remove the focus from widget, if the widget is in focus state.\n * @returns void\n */\n DatePicker.prototype.focusOut = function () {\n if (document.activeElement === this.inputElement) {\n this.inputElement.blur();\n removeClass([this.inputWrapper.container], [INPUTFOCUS]);\n var blurArguments = {\n model: this\n };\n this.trigger('blur', blurArguments);\n }\n };\n /**\n * Gets the current view of the DatePicker.\n * @returns string\n */\n DatePicker.prototype.currentView = function () {\n var currentView;\n if (this.calendarElement) {\n // calls the Calendar currentView public method\n currentView = _super.prototype.currentView.call(this);\n }\n return currentView;\n };\n /**\n * This method used to navigate to the month/year/decade view of the DatePicker.\n * @param {string} view - Specifies the view of the calendar.\n * @param {Date} date - Specifies the focused date in a view.\n * @returns void\n */\n DatePicker.prototype.navigateTo = function (view, date) {\n if (this.calendarElement) {\n // calls the Calendar navigateTo public method\n _super.prototype.navigateTo.call(this, view, date);\n }\n };\n /**\n * To destroy the widget.\n * @returns void\n */\n DatePicker.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n this.keyboardModules.destroy();\n if (this.popupObj && this.popupObj.element.classList.contains(POPUP)) {\n _super.prototype.destroy.call(this);\n }\n var ariaAttrs = {\n 'aria-live': 'assertive', 'aria-atomic': 'true', 'aria-disabled': 'true',\n 'aria-haspopup': 'true', 'aria-activedescendant': 'null',\n 'aria-owns': this.element.id + '_options', 'aria-expanded': 'false', 'role': 'combobox', 'autocomplete': 'off',\n 'autocorrect': 'off', 'autocapitalize': 'off', 'spellcheck': 'false'\n };\n if (this.inputElement) {\n Input.removeAttributes(ariaAttrs, this.inputElement);\n EventHandler.remove(this.inputElement, 'blur', this.inputBlurHandler);\n EventHandler.remove(this.inputElement, 'focus', this.inputFocusHandler);\n this.ensureInputAttribute();\n }\n if (this.isCalendar()) {\n if (this.popupWrapper) {\n detach(this.popupWrapper);\n }\n this.popupObj = this.popupWrapper = null;\n this.keyboardModule.destroy();\n }\n if (this.ngTag === null) {\n if (this.inputElement) {\n this.inputWrapper.container.insertAdjacentElement('afterend', this.inputElement);\n removeClass([this.inputElement], [INPUTROOT]);\n }\n removeClass([this.element], [ROOT]);\n detach(this.inputWrapper.container);\n }\n if (this.formElement) {\n EventHandler.remove(this.formElement, 'reset', this.resetFormHandler);\n }\n };\n DatePicker.prototype.ensureInputAttribute = function () {\n for (var i = 0; i < this.inputElement.attributes.length; i++) {\n var prop = this.inputElement.attributes[i].name;\n if (isNullOrUndefined(this.inputEleCopy.getAttribute(prop))) {\n if (prop.toLowerCase() === 'value' || isNullOrUndefined(this.inputEleCopy.getAttribute('value'))) {\n this.inputElement.value = '';\n }\n this.inputElement.removeAttribute(prop);\n }\n }\n };\n /**\n * Initialize the event handler\n * @private\n */\n DatePicker.prototype.preRender = function () {\n this.inputEleCopy = this.element.cloneNode(true);\n this.inputElement = this.element;\n this.formElement = closest(this.inputElement, 'form');\n this.index = this.showClearButton ? 2 : 1;\n this.ngTag = null;\n if (this.element.tagName === 'EJS-DATEPICKER' || this.element.tagName === 'EJS-DATETIMEPICKER') {\n this.ngTag = this.element.tagName;\n this.inputElement = this.createElement('input');\n this.element.appendChild(this.inputElement);\n }\n if (this.element.getAttribute('id')) {\n if (this.ngTag !== null) {\n this.inputElement.id = this.element.getAttribute('id') + '_input';\n }\n }\n else {\n if (this.getModuleName() === 'datetimepicker') {\n this.element.id = getUniqueID('ej2-datetimepicker');\n if (this.ngTag !== null) {\n attributes(this.inputElement, { 'id': this.element.id + '_input' });\n }\n }\n else {\n this.element.id = getUniqueID('ej2-datepicker');\n if (this.ngTag !== null) {\n attributes(this.inputElement, { 'id': this.element.id + '_input' });\n }\n }\n }\n if (this.ngTag !== null) {\n this.validationAttribute(this.element, this.inputElement);\n }\n this.checkHtmlAttributes();\n _super.prototype.preRender.call(this);\n };\n ;\n DatePicker.prototype.validationAttribute = function (target, inputElement) {\n var nameAttribute = target.getAttribute('name') ? target.getAttribute('name') : target.getAttribute('id');\n inputElement.setAttribute('name', nameAttribute);\n target.removeAttribute('name');\n var attribute = ['required', 'aria-required', 'form'];\n for (var i = 0; i < attribute.length; i++) {\n if (isNullOrUndefined(target.getAttribute(attribute[i]))) {\n continue;\n }\n var attr = target.getAttribute(attribute[i]);\n inputElement.setAttribute(attribute[i], attr);\n target.removeAttribute(attribute[i]);\n }\n };\n DatePicker.prototype.checkHtmlAttributes = function () {\n this.globalize = new Internationalization(this.locale);\n var attributes = ['value', 'min', 'max', 'disabled', 'readonly', 'style', 'name', 'placeholder', 'type'];\n var options;\n if (this.getModuleName() === 'datetimepicker') {\n options = {\n format: !isNullOrUndefined(this.format) ? this.format : this.dateTimeFormat,\n type: 'dateTime', skeleton: 'yMd'\n };\n }\n else {\n options = { format: this.format, type: 'dateTime', skeleton: 'yMd' };\n }\n for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {\n var prop = attributes_1[_i];\n if (!isNullOrUndefined(this.inputElement.getAttribute(prop))) {\n switch (prop) {\n case 'disabled':\n var enabled = this.inputElement.getAttribute(prop) === 'disabled' ||\n this.inputElement.getAttribute(prop) === '';\n this.setProperties({ enabled: !enabled }, true);\n break;\n case 'readonly':\n var readonly = this.inputElement.getAttribute(prop) === 'readonly' ||\n this.inputElement.getAttribute(prop) === '';\n this.setProperties({ readonly: readonly }, true);\n break;\n case 'placeholder':\n if (this.placeholder === null) {\n var placeholder = this.inputElement.getAttribute(prop);\n this.setProperties({ placeholder: this.inputElement.getAttribute(prop) }, true);\n }\n break;\n case 'style':\n this.inputElement.setAttribute('style', '' + this.inputElement.getAttribute(prop));\n break;\n case 'name':\n this.inputElement.setAttribute('name', '' + this.inputElement.getAttribute(prop));\n break;\n case 'value':\n if (!this.value) {\n var value = this.inputElement.getAttribute(prop);\n this.setProperties(setValue(prop, this.globalize.parseDate(value, options), {}), true);\n }\n break;\n case 'min':\n if (+this.min === +new Date(1900, 0, 1)) {\n this.setProperties(setValue(prop, this.globalize.parseDate(this.inputElement.getAttribute(prop)), {}), true);\n }\n break;\n case 'max':\n if (+this.max === +new Date(2099, 11, 31)) {\n this.setProperties(setValue(prop, this.globalize.parseDate(this.inputElement.getAttribute(prop)), {}), true);\n }\n break;\n case 'type':\n if (this.inputElement.getAttribute(prop) !== 'text') {\n this.inputElement.setAttribute('type', 'text');\n }\n break;\n }\n }\n }\n };\n /**\n * To get component name.\n * @private\n */\n DatePicker.prototype.getModuleName = function () {\n return 'datepicker';\n };\n DatePicker.prototype.disabledDates = function () {\n var valueCopy = new Date('' + this.value);\n var previousValCopy = this.previousDate;\n //calls the Calendar render method to check the disabled dates through renderDayCell event and update the input value accordingly.\n this.minMaxUpdates();\n _super.prototype.render.call(this);\n this.previousDate = previousValCopy;\n var date = valueCopy && +(valueCopy);\n var dateIdString = '*[id^=\"/id\"]'.replace('/id', '' + date);\n if (!this.strictMode) {\n if (typeof this.value === 'string' || ((typeof this.value === 'object') && (+this.value) !== (+valueCopy))) {\n this.setProperties({ value: valueCopy }, true);\n }\n }\n if (!isNullOrUndefined(this.calendarElement.querySelectorAll(dateIdString)[0])) {\n if (this.calendarElement.querySelectorAll(dateIdString)[0].classList.contains('e-disabled')) {\n if (!this.strictMode) {\n this.currentDate = new Date(new Date().setHours(0, 0, 0, 0));\n }\n }\n }\n var inputVal;\n if (this.getModuleName() === 'datetimepicker') {\n inputVal = this.globalize.formatDate(valueCopy, {\n format: !isNullOrUndefined(this.format) ? this.format : this.dateTimeFormat,\n type: 'dateTime', skeleton: 'yMd'\n });\n }\n else {\n inputVal = this.globalize.formatDate(valueCopy, { format: this.format, type: 'dateTime', skeleton: 'yMd' });\n }\n Input.setValue(inputVal, this.inputElement, this.floatLabelType, this.showClearButton);\n };\n DatePicker.prototype.setAriaAttributes = function () {\n if (this.isCalendar()) {\n Input.addAttributes({ 'aria-expanded': 'true' }, this.inputElement);\n attributes(this.inputElement, {\n 'aria-activedescendant': '' + this.setActiveDescendant()\n });\n }\n else {\n Input.addAttributes({ 'aria-expanded': 'false' }, this.inputElement);\n attributes(this.inputElement, {\n 'aria-activedescendant': 'null'\n });\n }\n };\n DatePicker.prototype.errorClass = function () {\n var dateIdString = '*[id^=\"/id\"]'.replace('/id', '' + (+this.value));\n var isDisabledDate = this.calendarElement &&\n this.calendarElement.querySelectorAll(dateIdString)[0] &&\n this.calendarElement.querySelectorAll(dateIdString)[0].classList.contains('e-disabled');\n if ((!isNullOrUndefined(this.value) && !(+this.value >= +this.min && +this.value <= +this.max))\n || (!this.strictMode && this.inputElement.value !== '' && isNullOrUndefined(this.value) || isDisabledDate)) {\n addClass([this.inputWrapper.container], ERROR);\n }\n else {\n removeClass([this.inputWrapper.container], ERROR);\n }\n };\n /**\n * Called internally if any of the property value changed.\n * returns void\n * @private\n */\n DatePicker.prototype.onPropertyChanged = function (newProp, oldProp) {\n var options = { format: this.format, type: 'dateTime', skeleton: 'yMd' };\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'value':\n if (typeof newProp.value === 'string') {\n newProp.value = this.checkDateValue(new Date('' + newProp.value));\n this.setProperties({ value: newProp.value }, true);\n }\n this.previousElementValue = this.inputElement.value;\n if (isNullOrUndefined(this.value)) {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n this.currentDate = new Date(new Date().setHours(0, 0, 0, 0));\n }\n this.updateInput();\n this.changeTrigger(null);\n break;\n case 'format':\n this.updateInput();\n break;\n case 'allowEdit':\n this.setAllowEdit();\n break;\n case 'placeholder':\n Input.setPlaceholder(this.placeholder, this.inputElement);\n break;\n case 'readonly':\n Input.setReadonly(this.readonly, this.inputElement);\n break;\n case 'enabled':\n Input.setEnabled(this.enabled, this.inputElement);\n if (!this.enabled) {\n this.inputElement.setAttribute('aria-disabled', 'true');\n }\n else {\n this.inputElement.setAttribute('aria-disabled', 'false');\n }\n this.bindEvents();\n break;\n case 'locale':\n this.globalize = new Internationalization(this.locale);\n this.l10n.setLocale(this.locale);\n this.setProperties({ placeholder: this.l10n.getConstant('placeholder') }, true);\n Input.setPlaceholder(this.placeholder, this.inputElement);\n this.updateInput();\n break;\n case 'enableRtl':\n Input.setEnableRtl(this.enableRtl, [this.inputWrapper.container]);\n break;\n case 'zIndex':\n this.setProperties({ zIndex: newProp.zIndex }, true);\n break;\n case 'cssClass':\n Input.setCssClass(newProp.cssClass, [this.inputWrapper.container]);\n if (this.popupWrapper) {\n addClass([this.popupWrapper], [newProp.cssClass]);\n }\n break;\n case 'showClearButton':\n Input.setClearButton(this.showClearButton, this.inputElement, this.inputWrapper);\n this.bindClearEvent();\n break;\n case 'strictMode':\n this.updateInput();\n break;\n case 'width':\n this.setWidth(newProp.width);\n break;\n case 'floatLabelType':\n this.floatLabelType = newProp.floatLabelType;\n Input.removeFloating(this.inputWrapper);\n Input.addFloating(this.inputElement, this.floatLabelType, this.placeholder);\n break;\n default:\n if (this.calendarElement) {\n _super.prototype.onPropertyChanged.call(this, newProp, oldProp);\n }\n break;\n }\n this.hide(null);\n }\n };\n __decorate([\n Property(null)\n ], DatePicker.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], DatePicker.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], DatePicker.prototype, \"strictMode\", void 0);\n __decorate([\n Property(null)\n ], DatePicker.prototype, \"format\", void 0);\n __decorate([\n Property(true)\n ], DatePicker.prototype, \"enabled\", void 0);\n __decorate([\n Property(true)\n ], DatePicker.prototype, \"showClearButton\", void 0);\n __decorate([\n Property(true)\n ], DatePicker.prototype, \"allowEdit\", void 0);\n __decorate([\n Property(false)\n ], DatePicker.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(1000)\n ], DatePicker.prototype, \"zIndex\", void 0);\n __decorate([\n Property(false)\n ], DatePicker.prototype, \"readonly\", void 0);\n __decorate([\n Property(null)\n ], DatePicker.prototype, \"placeholder\", void 0);\n __decorate([\n Property('Never')\n ], DatePicker.prototype, \"floatLabelType\", void 0);\n __decorate([\n Event()\n ], DatePicker.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], DatePicker.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], DatePicker.prototype, \"blur\", void 0);\n __decorate([\n Event()\n ], DatePicker.prototype, \"focus\", void 0);\n __decorate([\n Event()\n ], DatePicker.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], DatePicker.prototype, \"destroyed\", void 0);\n DatePicker = __decorate([\n NotifyPropertyChanges\n ], DatePicker);\n return DatePicker;\n}(Calendar));\nexport { DatePicker };\n","import { DataUtil } from './util';\n/**\n * Query class is used to build query which is used by the DataManager to communicate with datasource.\n */\nvar Query = /** @class */ (function () {\n /**\n * Constructor for Query class.\n * @param {string|string[]} from?\n * @hidden\n */\n function Query(from) {\n /** @hidden */\n this.subQuery = null;\n /** @hidden */\n this.isChild = false;\n this.queries = [];\n this.key = '';\n this.fKey = '';\n if (typeof from === 'string') {\n this.fromTable = from;\n }\n else if (from && from instanceof Array) {\n this.lookups = from;\n }\n this.expands = [];\n this.sortedColumns = [];\n this.groupedColumns = [];\n this.subQuery = null;\n this.isChild = false;\n this.params = [];\n return this;\n }\n /**\n * Sets the primary key.\n * @param {string} field - Defines the column field.\n */\n Query.prototype.setKey = function (field) {\n this.key = field;\n return this;\n };\n /**\n * Sets default DataManager to execute query.\n * @param {DataManager} dataManager - Defines the DataManager.\n */\n Query.prototype.using = function (dataManager) {\n this.dataManager = dataManager;\n return this;\n };\n /**\n * Executes query with the given DataManager.\n * @param {DataManager} dataManager - Defines the DataManager.\n * @param {Function} done - Defines the success callback.\n * @param {Function} fail - Defines the failure callback.\n * @param {Function} always - Defines the callback which will be invoked on either success or failure.\n *\n *
\n * let dataManager: DataManager = new DataManager([{ ID: '10' }, { ID: '2' }, { ID: '1' }, { ID: '20' }]);\n * let query: Query = new Query();\n * query.sortBy('ID', (x: string, y: string): number => { return parseInt(x, 10) - parseInt(y, 10) });\n * let promise: Promise< Object > = query.execute(dataManager);\n * promise.then((e: { result: Object }) => { });\n * \n */\n Query.prototype.execute = function (dataManager, done, fail, always) {\n dataManager = dataManager || this.dataManager;\n if (dataManager) {\n return dataManager.executeQuery(this, done, fail, always);\n }\n return DataUtil.throwError('Query - execute() : dataManager needs to be is set using \"using\" function or should be passed as argument');\n };\n /**\n * Executes query with the local datasource.\n * @param {DataManager} dataManager - Defines the DataManager.\n */\n Query.prototype.executeLocal = function (dataManager) {\n dataManager = dataManager || this.dataManager;\n if (dataManager) {\n return dataManager.executeLocal(this);\n }\n return DataUtil.throwError('Query - executeLocal() : dataManager needs to be is set using \"using\" function or should be passed as argument');\n };\n /**\n * Creates deep copy of the Query object.\n */\n Query.prototype.clone = function () {\n var cloned = new Query();\n cloned.queries = this.queries.slice(0);\n cloned.key = this.key;\n cloned.isChild = this.isChild;\n cloned.dataManager = this.dataManager;\n cloned.fromTable = this.fromTable;\n cloned.params = this.params.slice(0);\n cloned.expands = this.expands.slice(0);\n cloned.sortedColumns = this.sortedColumns.slice(0);\n cloned.groupedColumns = this.groupedColumns.slice(0);\n cloned.subQuerySelector = this.subQuerySelector;\n cloned.subQuery = this.subQuery;\n cloned.fKey = this.fKey;\n cloned.isCountRequired = this.isCountRequired;\n return cloned;\n };\n /**\n * Specifies the name of table to retrieve data in query execution.\n * @param {string} tableName - Defines the table name.\n */\n Query.prototype.from = function (tableName) {\n this.fromTable = tableName;\n return this;\n };\n /**\n * Adds additional parameter which will be sent along with the request which will be generated while DataManager execute.\n * @param {string} key - Defines the key of additional parameter.\n * @param {Function|string} value - Defines the value for the key.\n */\n Query.prototype.addParams = function (key, value) {\n if (typeof value === 'function') {\n this.params.push({ key: key, fn: value });\n }\n else {\n this.params.push({ key: key, value: value });\n }\n return this;\n };\n /**\n * Expands the related table.\n * @param {string|Object[]} tables\n */\n Query.prototype.expand = function (tables) {\n if (typeof tables === 'string') {\n this.expands = [].slice.call([tables], 0);\n }\n else {\n this.expands = tables.slice(0);\n }\n return this;\n };\n /**\n * Filter data with given filter criteria.\n * @param {string|Predicate} fieldName - Defines the column field or Predicate.\n * @param {string} operator - Defines the operator how to filter data.\n * @param {string|number|boolean} value - Defines the values to match with data.\n * @param {boolean} ignoreCase - If ignore case set to false, then filter data with exact match or else\n * filter data with case insensitive.\n */\n Query.prototype.where = function (fieldName, operator, value, ignoreCase, ignoreAccent) {\n operator = operator ? (operator).toLowerCase() : null;\n var predicate = null;\n if (typeof fieldName === 'string') {\n predicate = new Predicate(fieldName, operator, value, ignoreCase, ignoreAccent);\n }\n else if (fieldName instanceof Predicate) {\n predicate = fieldName;\n }\n this.queries.push({\n fn: 'onWhere',\n e: predicate\n });\n return this;\n };\n /**\n * Search data with given search criteria.\n * @param {string|number|boolean} searchKey - Defines the search key.\n * @param {string|string[]} fieldNames - Defines the collection of column fields.\n * @param {string} operator - Defines the operator how to search data.\n * @param {boolean} ignoreCase - If ignore case set to false, then filter data with exact match or else\n * filter data with case insensitive.\n */\n Query.prototype.search = function (searchKey, fieldNames, operator, ignoreCase, ignoreAccent) {\n if (typeof fieldNames === 'string') {\n fieldNames = [fieldNames];\n }\n operator = operator || 'contains';\n var comparer = DataUtil.fnOperators[operator];\n this.queries.push({\n fn: 'onSearch',\n e: {\n fieldNames: fieldNames,\n operator: operator,\n searchKey: searchKey,\n ignoreCase: ignoreCase,\n ignoreAccent: ignoreAccent,\n comparer: comparer\n }\n });\n return this;\n };\n /**\n * Sort the data with given sort criteria.\n * By default, sort direction is ascending.\n * @param {string|string[]} fieldName - Defines the single or collection of column fields.\n * @param {string|Function} comparer - Defines the sort direction or custom sort comparer function.\n */\n Query.prototype.sortBy = function (fieldName, comparer, isFromGroup) {\n var order = 'ascending';\n var sorts;\n var temp;\n if (typeof fieldName === 'string' && DataUtil.endsWith(fieldName.toLowerCase(), ' desc')) {\n fieldName = fieldName.replace(/ desc$/i, '');\n comparer = 'descending';\n }\n if (!comparer || typeof comparer === 'string') {\n order = comparer ? comparer.toLowerCase() : 'ascending';\n comparer = DataUtil.fnSort(comparer);\n }\n if (isFromGroup) {\n sorts = Query.filterQueries(this.queries, 'onSortBy');\n for (var i = 0; i < sorts.length; i++) {\n temp = sorts[i].e.fieldName;\n if (typeof temp === 'string') {\n if (temp === fieldName) {\n return this;\n }\n }\n else if (temp instanceof Array) {\n for (var j = 0; j < temp.length; j++) {\n if (temp[j] === fieldName || fieldName.toLowerCase() === temp[j] + ' desc') {\n return this;\n }\n }\n }\n }\n }\n this.queries.push({\n fn: 'onSortBy',\n e: {\n fieldName: fieldName,\n comparer: comparer,\n direction: order\n }\n });\n return this;\n };\n /**\n * Sorts data in descending order.\n * @param {string} fieldName - Defines the column field.\n */\n Query.prototype.sortByDesc = function (fieldName) {\n return this.sortBy(fieldName, 'descending');\n };\n /**\n * Groups data with the given field name.\n * @param {string} fieldName - Defines the column field.\n */\n Query.prototype.group = function (fieldName, fn, format) {\n this.sortBy(fieldName, null, true);\n this.queries.push({\n fn: 'onGroup',\n e: {\n fieldName: fieldName,\n comparer: fn ? fn : null,\n format: format ? format : null\n }\n });\n return this;\n };\n /**\n * Gets data based on the given page index and size.\n * @param {number} pageIndex - Defines the current page index.\n * @param {number} pageSize - Defines the no of records per page.\n */\n Query.prototype.page = function (pageIndex, pageSize) {\n this.queries.push({\n fn: 'onPage',\n e: {\n pageIndex: pageIndex,\n pageSize: pageSize\n }\n });\n return this;\n };\n /**\n * Gets data based on the given start and end index.\n * @param {number} start - Defines the start index of the datasource.\n * @param {number} end - Defines the end index of the datasource.\n */\n Query.prototype.range = function (start, end) {\n this.queries.push({\n fn: 'onRange',\n e: {\n start: start,\n end: end\n }\n });\n return this;\n };\n /**\n * Gets data from the top of the data source based on given number of records count.\n * @param {number} nos - Defines the no of records to retrieve from datasource.\n */\n Query.prototype.take = function (nos) {\n this.queries.push({\n fn: 'onTake',\n e: {\n nos: nos\n }\n });\n return this;\n };\n /**\n * Skips data with given number of records count from the top of the data source.\n * @param {number} nos - Defines the no of records skip in the datasource.\n */\n Query.prototype.skip = function (nos) {\n this.queries.push({\n fn: 'onSkip',\n e: { nos: nos }\n });\n return this;\n };\n /**\n * Selects specified columns from the data source.\n * @param {string|string[]} fieldNames - Defines the collection of column fields.\n */\n Query.prototype.select = function (fieldNames) {\n if (typeof fieldNames === 'string') {\n fieldNames = [].slice.call([fieldNames], 0);\n }\n this.queries.push({\n fn: 'onSelect',\n e: { fieldNames: fieldNames }\n });\n return this;\n };\n /**\n * Gets the records in hierarchical relationship from two tables. It requires the foreign key to relate two tables.\n * @param {Query} query - Defines the query to relate two tables.\n * @param {Function} selectorFn - Defines the custom function to select records.\n */\n Query.prototype.hierarchy = function (query, selectorFn) {\n this.subQuerySelector = selectorFn;\n this.subQuery = query;\n return this;\n };\n /**\n * Sets the foreign key which is used to get data from the related table.\n * @param {string} key - Defines the foreign key.\n */\n Query.prototype.foreignKey = function (key) {\n this.fKey = key;\n return this;\n };\n /**\n * It is used to get total number of records in the DataManager execution result.\n */\n Query.prototype.requiresCount = function () {\n this.isCountRequired = true;\n return this;\n };\n //type - sum, avg, min, max\n /**\n * Aggregate the data with given type and field name.\n * @param {string} type - Defines the aggregate type.\n * @param {string} field - Defines the column field to aggregate.\n */\n Query.prototype.aggregate = function (type, field) {\n this.queries.push({\n fn: 'onAggregates',\n e: { field: field, type: type }\n });\n return this;\n };\n /**\n * Pass array of filterColumn query for performing filter operation.\n * @param {QueryOptions[]} queries\n * @param {string} name\n * @hidden\n */\n Query.filterQueries = function (queries, name) {\n return queries.filter(function (q) {\n return q.fn === name;\n });\n };\n /**\n * To get the list of queries which is already filtered in current data source.\n * @param {Object[]} queries\n * @param {string[]} singles\n * @hidden\n */\n Query.filterQueryLists = function (queries, singles) {\n var filtered = queries.filter(function (q) {\n return singles.indexOf(q.fn) !== -1;\n });\n var res = {};\n for (var i = 0; i < filtered.length; i++) {\n if (!res[filtered[i].fn]) {\n res[filtered[i].fn] = filtered[i].e;\n }\n }\n return res;\n };\n return Query;\n}());\nexport { Query };\n/**\n * Predicate class is used to generate complex filter criteria.\n * This will be used by DataManager to perform multiple filtering operation.\n */\nvar Predicate = /** @class */ (function () {\n /**\n * Constructor for Predicate class.\n * @param {string|Predicate} field\n * @param {string} operator\n * @param {string|number|boolean|Predicate|Predicate[]} value\n * @param {boolean=false} ignoreCase\n * @hidden\n */\n function Predicate(field, operator, value, ignoreCase, ignoreAccent) {\n if (ignoreCase === void 0) { ignoreCase = false; }\n /** @hidden */\n this.ignoreAccent = false;\n /** @hidden */\n this.isComplex = false;\n if (typeof field === 'string') {\n this.field = field;\n this.operator = operator.toLowerCase();\n this.value = value;\n this.ignoreCase = ignoreCase;\n this.ignoreAccent = ignoreAccent;\n this.isComplex = false;\n this.comparer = DataUtil.fnOperators.processOperator(this.operator);\n }\n else if (field instanceof Predicate && value instanceof Predicate || value instanceof Array) {\n this.isComplex = true;\n this.condition = operator.toLowerCase();\n this.predicates = [field];\n if (value instanceof Array) {\n [].push.apply(this.predicates, value);\n }\n else {\n this.predicates.push(value);\n }\n }\n return this;\n }\n /**\n * Adds n-number of new predicates on existing predicate with “and” condition.\n * @param {Object[]} args - Defines the collection of predicates.\n */\n Predicate.and = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return Predicate.combinePredicates([].slice.call(args, 0), 'and');\n };\n /**\n * Adds new predicate on existing predicate with “and” condition.\n * @param {string} field - Defines the column field.\n * @param {string} operator - Defines the operator how to filter data.\n * @param {string} value - Defines the values to match with data.\n * @param {boolean} ignoreCase? - If ignore case set to false, then filter data with exact match or else\n * filter data with case insensitive.\n */\n Predicate.prototype.and = function (field, operator, value, ignoreCase, ignoreAccent) {\n return Predicate.combine(this, field, operator, value, 'and', ignoreCase, ignoreAccent);\n };\n /**\n * Adds n-number of new predicates on existing predicate with “or” condition.\n * @param {Object[]} args - Defines the collection of predicates.\n */\n Predicate.or = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return Predicate.combinePredicates([].slice.call(args, 0), 'or');\n };\n /**\n * Adds new predicate on existing predicate with “or” condition.\n * @param {string} field - Defines the column field.\n * @param {string} operator - Defines the operator how to filter data.\n * @param {string} value - Defines the values to match with data.\n * @param {boolean} ignoreCase? - If ignore case set to false, then filter data with exact match or else\n * filter data with case insensitive.\n */\n Predicate.prototype.or = function (field, operator, value, ignoreCase, ignoreAccent) {\n return Predicate.combine(this, field, operator, value, 'or', ignoreCase, ignoreAccent);\n };\n /**\n * Converts plain JavaScript object to Predicate object.\n * @param {Predicate[]|Predicate} json - Defines single or collection of Predicate.\n */\n Predicate.fromJson = function (json) {\n if (json instanceof Array) {\n var res = [];\n for (var i = 0, len = json.length; i < len; i++) {\n res.push(this.fromJSONData(json[i]));\n }\n return res;\n }\n var pred = json;\n return this.fromJSONData(pred);\n };\n /**\n * Validate the record based on the predicates.\n * @param {Object} record - Defines the datasource record.\n */\n Predicate.prototype.validate = function (record) {\n var predicate = this.predicates ? this.predicates : [];\n var isAnd;\n var ret;\n if (!this.isComplex && this.comparer) {\n return this.comparer.call(this, DataUtil.getObject(this.field, record), this.value, this.ignoreCase, this.ignoreAccent);\n }\n isAnd = this.condition === 'and';\n for (var i = 0; i < predicate.length; i++) {\n ret = predicate[i].validate(record);\n if (isAnd) {\n if (!ret) {\n return false;\n }\n }\n else {\n if (ret) {\n return true;\n }\n }\n }\n return isAnd;\n };\n /**\n * Converts predicates to plain JavaScript.\n * This method is uses Json stringify when serializing Predicate object.\n */\n Predicate.prototype.toJson = function () {\n var predicates;\n var p;\n if (this.isComplex) {\n predicates = [];\n p = this.predicates;\n for (var i = 0; i < p.length; i++) {\n predicates.push(p[i].toJson());\n }\n }\n return {\n isComplex: this.isComplex,\n field: this.field,\n operator: this.operator,\n value: this.value,\n ignoreCase: this.ignoreCase,\n ignoreAccent: this.ignoreAccent,\n condition: this.condition,\n predicates: predicates\n };\n };\n Predicate.combinePredicates = function (predicates, operator) {\n if (predicates.length === 1) {\n if (!(predicates[0] instanceof Array)) {\n return predicates[0];\n }\n predicates = predicates[0];\n }\n return new Predicate(predicates[0], operator, predicates.slice(1));\n };\n Predicate.combine = function (pred, field, operator, value, condition, ignoreCase, ignoreAccent) {\n if (field instanceof Predicate) {\n return Predicate[condition](pred, field);\n }\n if (typeof field === 'string') {\n return Predicate[condition](pred, new Predicate(field, operator, value, ignoreCase, ignoreAccent));\n }\n return DataUtil.throwError('Predicate - ' + condition + ' : invalid arguments');\n };\n Predicate.fromJSONData = function (json) {\n var preds = json.predicates || [];\n var len = preds.length;\n var predicates = [];\n var result;\n for (var i = 0; i < len; i++) {\n predicates.push(this.fromJSONData(preds[i]));\n }\n if (!json.isComplex) {\n result = new Predicate(json.field, json.operator, json.value, json.ignoreCase, json.ignoreAccent);\n }\n else {\n result = new Predicate(predicates[0], json.condition, predicates.slice(1));\n }\n return result;\n };\n return Predicate;\n}());\nexport { Predicate };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { DataManager } from './manager';\nimport { Query } from './query';\nvar consts = { GroupGuid: '{271bbba0-1ee7}' };\n/**\n * Data manager common utility methods.\n * @hidden\n */\nvar DataUtil = /** @class */ (function () {\n function DataUtil() {\n }\n /**\n * Returns the value by invoking the provided parameter function.\n * If the paramater is not of type function then it will be returned as it is.\n * @param {Function|string|string[]|number} value\n * @param {Object} inst?\n * @hidden\n */\n DataUtil.getValue = function (value, inst) {\n if (typeof value === 'function') {\n return value.call(inst || {});\n }\n return value;\n };\n /**\n * Returns true if the input string ends with given string.\n * @param {string} input\n * @param {string} substr\n */\n DataUtil.endsWith = function (input, substr) {\n return input.slice(-substr.length) === substr;\n };\n /**\n * Returns true if the input string starts with given string.\n * @param {string} str\n * @param {string} startstr\n */\n DataUtil.startsWith = function (input, start) {\n return input.slice(0, start.length) === start;\n };\n /**\n * To return the sorting function based on the string.\n * @param {string} order\n * @hidden\n */\n DataUtil.fnSort = function (order) {\n order = order ? DataUtil.toLowerCase(order) : 'ascending';\n if (order === 'ascending') {\n return this.fnAscending;\n }\n return this.fnDescending;\n };\n /**\n * Comparer function which is used to sort the data in ascending order.\n * @param {string|number} x\n * @param {string|number} y\n * @returns number\n */\n DataUtil.fnAscending = function (x, y) {\n if (y === null || y === undefined) {\n return -1;\n }\n if (typeof x === 'string') {\n return x.localeCompare(y);\n }\n if (x === null || x === undefined) {\n return 1;\n }\n return x - y;\n };\n /**\n * Comparer function which is used to sort the data in descending order.\n * @param {string|number} x\n * @param {string|number} y\n * @returns number\n */\n DataUtil.fnDescending = function (x, y) {\n if (y === null || y === undefined) {\n return 1;\n }\n if (typeof x === 'string') {\n return x.localeCompare(y) * -1;\n }\n if (x === null || x === undefined) {\n return -1;\n }\n return y - x;\n };\n DataUtil.extractFields = function (obj, fields) {\n var newObj = {};\n for (var i = 0; i < fields.length; i++) {\n newObj = this.setValue(fields[i], this.getObject(fields[i], obj), newObj);\n }\n return newObj;\n };\n /**\n * Select objects by given fields from jsonArray.\n * @param {Object[]} jsonArray\n * @param {string[]} fields\n */\n DataUtil.select = function (jsonArray, fields) {\n var newData = [];\n for (var i = 0; i < jsonArray.length; i++) {\n newData.push(this.extractFields(jsonArray[i], fields));\n }\n return newData;\n };\n /**\n * Group the input data based on the field name.\n * It also performs aggregation of the grouped records based on the aggregates paramater.\n * @param {Object[]} jsonArray\n * @param {string} field?\n * @param {Object[]} agg?\n * @param {number} level?\n * @param {Object[]} groupDs?\n */\n DataUtil.group = function (jsonArray, field, aggregates, level, groupDs, format) {\n level = level || 1;\n var jsonData = jsonArray;\n var guid = 'GroupGuid';\n if (jsonData.GroupGuid === consts[guid]) {\n var _loop_1 = function (j) {\n if (!isNullOrUndefined(groupDs)) {\n var indx = -1;\n var temp = groupDs.filter(function (e) { return e.key === jsonData[j].key; });\n indx = groupDs.indexOf(temp[0]);\n jsonData[j].items = this_1.group(jsonData[j].items, field, aggregates, jsonData.level + 1, groupDs[indx].items, format);\n jsonData[j].count = groupDs[indx].count;\n }\n else {\n jsonData[j].items = this_1.group(jsonData[j].items, field, aggregates, jsonData.level + 1, null, format);\n jsonData[j].count = jsonData[j].items.length;\n }\n };\n var this_1 = this;\n for (var j = 0; j < jsonData.length; j++) {\n _loop_1(j);\n }\n jsonData.childLevels += 1;\n return jsonData;\n }\n var grouped = {};\n var groupedArray = [];\n groupedArray.GroupGuid = consts[guid];\n groupedArray.level = level;\n groupedArray.childLevels = 0;\n groupedArray.records = jsonData;\n var _loop_2 = function (i) {\n var val = this_2.getVal(jsonData, i, field);\n if (!isNullOrUndefined(format)) {\n val = format(val, field);\n }\n if (!grouped[val]) {\n grouped[val] = {\n key: val,\n count: 0,\n items: [],\n aggregates: {},\n field: field\n };\n groupedArray.push(grouped[val]);\n if (!isNullOrUndefined(groupDs)) {\n var tempObj = groupDs.filter(function (e) { return e.key === grouped[val].key; });\n grouped[val].count = tempObj[0].count;\n }\n }\n grouped[val].count = !isNullOrUndefined(groupDs) ? grouped[val].count : grouped[val].count += 1;\n grouped[val].items.push(jsonData[i]);\n };\n var this_2 = this;\n for (var i = 0; i < jsonData.length; i++) {\n _loop_2(i);\n }\n if (aggregates && aggregates.length) {\n var _loop_3 = function (i) {\n var res = {};\n var fn = void 0;\n var aggs = aggregates;\n for (var j = 0; j < aggregates.length; j++) {\n fn = DataUtil.aggregates[aggregates[j].type];\n if (!isNullOrUndefined(groupDs)) {\n var temp = groupDs.filter(function (e) { return e.key === groupedArray[i].key; });\n if (fn) {\n res[aggs[j].field + ' - ' + aggs[j].type] = fn(temp[0].items, aggs[j].field);\n }\n }\n else {\n if (fn) {\n res[aggs[j].field + ' - ' + aggs[j].type] = fn(groupedArray[i].items, aggs[j].field);\n }\n }\n }\n groupedArray[i].aggregates = res;\n };\n for (var i = 0; i < groupedArray.length; i++) {\n _loop_3(i);\n }\n }\n return jsonData.length && groupedArray || jsonData;\n };\n /**\n * It is used to categorize the multiple items based on a specific field in jsonArray.\n * The hierarchical queries are commonly required when you use foreign key binding.\n * @param {string} fKey\n * @param {string} from\n * @param {Object[]} source\n * @param {Group} lookup?\n * @param {string} pKey?\n * @hidden\n */\n DataUtil.buildHierarchy = function (fKey, from, source, lookup, pKey) {\n var i;\n var grp = {};\n var temp;\n if (lookup.result) {\n lookup = lookup.result;\n }\n if (lookup.GroupGuid) {\n this.throwError('DataManager: Do not have support Grouping in hierarchy');\n }\n for (i = 0; i < lookup.length; i++) {\n var fKeyData = this.getObject(fKey, lookup[i]);\n temp = grp[fKeyData] || (grp[fKeyData] = []);\n temp.push(lookup[i]);\n }\n for (i = 0; i < source.length; i++) {\n var fKeyData = this.getObject(pKey || fKey, source[i]);\n source[i][from] = grp[fKeyData];\n }\n };\n /**\n * The method used to get the field names which started with specified characters.\n * @param {Object} obj\n * @param {string[]} fields?\n * @param {string} prefix?\n * @hidden\n */\n DataUtil.getFieldList = function (obj, fields, prefix) {\n if (prefix === undefined) {\n prefix = '';\n }\n if (fields === undefined || fields === null) {\n return this.getFieldList(obj, [], prefix);\n }\n var copyObj = obj;\n var keys = Object.keys(obj);\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var prop = keys_1[_i];\n if (typeof copyObj[prop] === 'object' && !(copyObj[prop] instanceof Array)) {\n this.getFieldList(copyObj[prop], fields, prefix + prop + '.');\n }\n else {\n fields.push(prefix + prop);\n }\n }\n return fields;\n };\n /**\n * Gets the value of the property in the given object.\n * The complex object can be accessed by providing the field names concatenated with dot(.).\n * @param {string} nameSpace - The name of the property to be accessed.\n * @param {Object} from - Defines the source object.\n */\n DataUtil.getObject = function (nameSpace, from) {\n if (!nameSpace) {\n return from;\n }\n if (!from) {\n return undefined;\n }\n if (nameSpace.indexOf('.') === -1) {\n return from[nameSpace];\n }\n var value = from;\n var splits = nameSpace.split('.');\n for (var i = 0; i < splits.length; i++) {\n if (value == null) {\n break;\n }\n value = value[splits[i]];\n }\n return value;\n };\n /**\n * To set value for the nameSpace in desired object.\n * @param {string} nameSpace - String value to the get the inner object.\n * @param {Object} value - Value that you need to set.\n * @param {Object} obj - Object to get the inner object value.\n * @return { [key: string]: Object; } | Object\n * @hidden\n */\n DataUtil.setValue = function (nameSpace, value, obj) {\n var keys = nameSpace.toString().split('.');\n var start = obj || {};\n var fromObj = start;\n var i;\n var length = keys.length;\n var key;\n for (i = 0; i < length; i++) {\n key = keys[i];\n if (i + 1 === length) {\n fromObj[key] = value === undefined ? undefined : value;\n }\n else if (isNullOrUndefined(fromObj[key])) {\n fromObj[key] = {};\n }\n fromObj = fromObj[key];\n }\n return start;\n };\n /**\n * Sort the given data based on the field and comparer.\n * @param {Object[]} ds - Defines the input data.\n * @param {string} field - Defines the field to be sorted.\n * @param {Function} comparer - Defines the comparer function used to sort the records.\n */\n DataUtil.sort = function (ds, field, comparer) {\n if (ds.length <= 1) {\n return ds;\n }\n var middle = parseInt((ds.length / 2).toString(), 10);\n var left = ds.slice(0, middle);\n var right = ds.slice(middle);\n left = this.sort(left, field, comparer);\n right = this.sort(right, field, comparer);\n return this.merge(left, right, field, comparer);\n };\n DataUtil.ignoreDiacritics = function (value) {\n if (typeof value !== 'string') {\n return value;\n }\n var result = value.split('');\n var newValue = result.map(function (temp) { return temp in DataUtil.diacritics ? DataUtil.diacritics[temp] : temp; });\n return newValue.join('');\n };\n DataUtil.merge = function (left, right, fieldName, comparer) {\n var result = [];\n var current;\n while (left.length > 0 || right.length > 0) {\n if (left.length > 0 && right.length > 0) {\n if (comparer) {\n current = comparer(this.getVal(left, 0, fieldName), this.getVal(right, 0, fieldName)) <= 0 ? left : right;\n }\n else {\n current = left[0][fieldName] < left[0][fieldName] ? left : right;\n }\n }\n else {\n current = left.length > 0 ? left : right;\n }\n result.push(current.shift());\n }\n return result;\n };\n DataUtil.getVal = function (array, index, field) {\n return field ? this.getObject(field, array[index]) : array[index];\n };\n DataUtil.toLowerCase = function (val) {\n return val ? typeof val === 'string' ? val.toLowerCase() : val.toString() : (val === 0 || val === false) ? val.toString() : '';\n };\n /**\n * To perform the filter operation with specified adaptor and returns the result.\n * @param {Object} adaptor\n * @param {string} fnName\n * @param {Object} param1?\n * @param {Object} param2?\n * @hidden\n */\n DataUtil.callAdaptorFunction = function (adaptor, fnName, param1, param2) {\n if (fnName in adaptor) {\n var res = adaptor[fnName](param1, param2);\n if (!isNullOrUndefined(res)) {\n param1 = res;\n }\n }\n return param1;\n };\n /**\n * Checks wheather the given input is a plain object or not.\n * @param {Object|Object[]} obj\n */\n DataUtil.isPlainObject = function (obj) {\n return (!!obj) && (obj.constructor === Object);\n };\n /**\n * Returns true when the browser cross origin request.\n */\n DataUtil.isCors = function () {\n var xhr = null;\n var request = 'XMLHttpRequest';\n try {\n xhr = new window[request]();\n }\n catch (e) {\n // No exception handling\n }\n return !!xhr && ('withCredentials' in xhr);\n };\n /**\n * Generate random GUID value which will be prefixed with the given value.\n * @param {string} prefix\n */\n DataUtil.getGuid = function (prefix) {\n var hexs = '0123456789abcdef';\n var rand;\n return (prefix || '') + '00000000-0000-4000-0000-000000000000'.replace(/0/g, function (val, i) {\n if ('crypto' in window && 'getRandomValues' in crypto) {\n var arr = new Uint8Array(1);\n window.crypto.getRandomValues(arr);\n rand = arr[0] % 16 | 0;\n }\n else {\n rand = Math.random() * 16 | 0;\n }\n return hexs[i === 19 ? rand & 0x3 | 0x8 : rand];\n });\n };\n /**\n * Checks wheather the given value is null or not.\n * @param {string|Object} val\n * @returns boolean\n */\n DataUtil.isNull = function (val) {\n return val === undefined || val === null;\n };\n /**\n * To get the required items from collection of objects.\n * @param {Object[]} array\n * @param {string} field\n * @param {Function} comparer\n * @returns Object\n * @hidden\n */\n DataUtil.getItemFromComparer = function (array, field, comparer) {\n var keyVal;\n var current;\n var key;\n var i = 0;\n var castRequired = typeof DataUtil.getVal(array, 0, field) === 'string';\n if (array.length) {\n while (isNullOrUndefined(keyVal) && i < array.length) {\n keyVal = DataUtil.getVal(array, i, field);\n key = array[i++];\n }\n }\n for (; i < array.length; i++) {\n current = DataUtil.getVal(array, i, field);\n if (isNullOrUndefined(current)) {\n continue;\n }\n if (castRequired) {\n keyVal = +keyVal;\n current = +current;\n }\n if (comparer(keyVal, current) > 0) {\n keyVal = current;\n key = array[i];\n }\n }\n return key;\n };\n /**\n * To get distinct values of Array or Array of Objects.\n * @param {Object[]} json\n * @param {string} field\n * @param {boolean} requiresCompleteRecord\n * @returns Object[]\n * * distinct array of objects is return when requiresCompleteRecord set as true.\n * @hidden\n */\n DataUtil.distinct = function (json, fieldName, requiresCompleteRecord) {\n requiresCompleteRecord = isNullOrUndefined(requiresCompleteRecord) ? false : requiresCompleteRecord;\n var result = [];\n var val;\n var tmp = {};\n json.forEach(function (data, index) {\n val = DataUtil.getVal(json, index, fieldName);\n if (!(val in tmp)) {\n result.push(!requiresCompleteRecord ? val : json[index]);\n tmp[val] = 1;\n }\n });\n return result;\n };\n /**\n * Specifies the value which will be used to adjust the date value to server timezone.\n * @default null\n */\n DataUtil.serverTimezoneOffset = null;\n /**\n * Throw error with the given string as message.\n * @param {string} er\n */\n DataUtil.throwError = function (error) {\n try {\n throw new Error(error);\n }\n catch (e) {\n throw e.message + '\\n' + e.stack;\n }\n };\n DataUtil.aggregates = {\n /**\n * Calculate sum of the given field in the data.\n * @param {Object[]} ds\n * @param {string} field\n */\n sum: function (ds, field) {\n var result = 0;\n var val;\n var castRequired = typeof DataUtil.getVal(ds, 0, field) !== 'number';\n for (var i = 0; i < ds.length; i++) {\n val = DataUtil.getVal(ds, i, field);\n if (!isNaN(val) && val !== null) {\n if (castRequired) {\n val = +val;\n }\n result += val;\n }\n }\n return result;\n },\n /**\n * Calculate average value of the given field in the data.\n * @param {Object[]} ds\n * @param {string} field\n */\n average: function (ds, field) {\n return DataUtil.aggregates.sum(ds, field) / ds.length;\n },\n /**\n * Returns the min value of the data based on the field.\n * @param {Object[]} ds\n * @param {string|Function} field\n */\n min: function (ds, field) {\n var comparer;\n if (typeof field === 'function') {\n comparer = field;\n field = null;\n }\n return DataUtil.getObject(field, DataUtil.getItemFromComparer(ds, field, comparer || DataUtil.fnAscending));\n },\n /**\n * Returns the max value of the data based on the field.\n * @param {Object[]} ds\n * @param {string} field\n * @returns number\n */\n max: function (ds, field) {\n var comparer;\n if (typeof field === 'function') {\n comparer = field;\n field = null;\n }\n return DataUtil.getObject(field, DataUtil.getItemFromComparer(ds, field, comparer || DataUtil.fnDescending));\n },\n /**\n * Returns the total number of true value present in the data based on the given boolean field name.\n * @param {Object[]} ds\n * @param {string} field\n */\n truecount: function (ds, field) {\n return new DataManager(ds).executeLocal(new Query().where(field, 'equal', true, true)).length;\n },\n /**\n * Returns the total number of false value present in the data based on the given boolean field name.\n * @param {Object[]} ds\n * @param {string} field\n */\n falsecount: function (ds, field) {\n return new DataManager(ds).executeLocal(new Query().where(field, 'equal', false, true)).length;\n },\n /**\n * Returns the length of the given data.\n * @param {Object[]} ds\n * @param {string} field?\n * @returns number\n */\n count: function (ds, field) {\n return ds.length;\n }\n };\n /**\n * Specifies the Object with filter operators.\n */\n DataUtil.operatorSymbols = {\n '<': 'lessthan',\n '>': 'greaterthan',\n '<=': 'lessthanorequal',\n '>=': 'greaterthanorequal',\n '==': 'equal',\n '!=': 'notequal',\n '*=': 'contains',\n '$=': 'endswith',\n '^=': 'startswith'\n };\n /**\n * Specifies the Object with filter operators which will be used for OData filter query generation.\n * * It will be used for date/number type filter query.\n */\n DataUtil.odBiOperator = {\n '<': ' lt ',\n '>': ' gt ',\n '<=': ' le ',\n '>=': ' ge ',\n '==': ' eq ',\n '!=': ' ne ',\n 'lessthan': ' lt ',\n 'lessthanorequal': ' le ',\n 'greaterthan': ' gt ',\n 'greaterthanorequal': ' ge ',\n 'equal': ' eq ',\n 'notequal': ' ne '\n };\n /**\n * Specifies the Object with filter operators which will be used for OData filter query generation.\n * It will be used for string type filter query.\n */\n DataUtil.odUniOperator = {\n '$=': 'endswith',\n '^=': 'startswith',\n '*=': 'substringof',\n 'endswith': 'endswith',\n 'startswith': 'startswith',\n 'contains': 'substringof'\n };\n /**\n * Specifies the Object with filter operators which will be used for ODataV4 filter query generation.\n * It will be used for string type filter query.\n */\n DataUtil.odv4UniOperator = {\n '$=': 'endswith',\n '^=': 'startswith',\n '*=': 'contains',\n 'endswith': 'endswith',\n 'startswith': 'startswith',\n 'contains': 'contains'\n };\n DataUtil.diacritics = {\n '\\u24B6': 'A',\n '\\uFF21': 'A',\n '\\u00C0': 'A',\n '\\u00C1': 'A',\n '\\u00C2': 'A',\n '\\u1EA6': 'A',\n '\\u1EA4': 'A',\n '\\u1EAA': 'A',\n '\\u1EA8': 'A',\n '\\u00C3': 'A',\n '\\u0100': 'A',\n '\\u0102': 'A',\n '\\u1EB0': 'A',\n '\\u1EAE': 'A',\n '\\u1EB4': 'A',\n '\\u1EB2': 'A',\n '\\u0226': 'A',\n '\\u01E0': 'A',\n '\\u00C4': 'A',\n '\\u01DE': 'A',\n '\\u1EA2': 'A',\n '\\u00C5': 'A',\n '\\u01FA': 'A',\n '\\u01CD': 'A',\n '\\u0200': 'A',\n '\\u0202': 'A',\n '\\u1EA0': 'A',\n '\\u1EAC': 'A',\n '\\u1EB6': 'A',\n '\\u1E00': 'A',\n '\\u0104': 'A',\n '\\u023A': 'A',\n '\\u2C6F': 'A',\n '\\uA732': 'AA',\n '\\u00C6': 'AE',\n '\\u01FC': 'AE',\n '\\u01E2': 'AE',\n '\\uA734': 'AO',\n '\\uA736': 'AU',\n '\\uA738': 'AV',\n '\\uA73A': 'AV',\n '\\uA73C': 'AY',\n '\\u24B7': 'B',\n '\\uFF22': 'B',\n '\\u1E02': 'B',\n '\\u1E04': 'B',\n '\\u1E06': 'B',\n '\\u0243': 'B',\n '\\u0182': 'B',\n '\\u0181': 'B',\n '\\u24B8': 'C',\n '\\uFF23': 'C',\n '\\u0106': 'C',\n '\\u0108': 'C',\n '\\u010A': 'C',\n '\\u010C': 'C',\n '\\u00C7': 'C',\n '\\u1E08': 'C',\n '\\u0187': 'C',\n '\\u023B': 'C',\n '\\uA73E': 'C',\n '\\u24B9': 'D',\n '\\uFF24': 'D',\n '\\u1E0A': 'D',\n '\\u010E': 'D',\n '\\u1E0C': 'D',\n '\\u1E10': 'D',\n '\\u1E12': 'D',\n '\\u1E0E': 'D',\n '\\u0110': 'D',\n '\\u018B': 'D',\n '\\u018A': 'D',\n '\\u0189': 'D',\n '\\uA779': 'D',\n '\\u01F1': 'DZ',\n '\\u01C4': 'DZ',\n '\\u01F2': 'Dz',\n '\\u01C5': 'Dz',\n '\\u24BA': 'E',\n '\\uFF25': 'E',\n '\\u00C8': 'E',\n '\\u00C9': 'E',\n '\\u00CA': 'E',\n '\\u1EC0': 'E',\n '\\u1EBE': 'E',\n '\\u1EC4': 'E',\n '\\u1EC2': 'E',\n '\\u1EBC': 'E',\n '\\u0112': 'E',\n '\\u1E14': 'E',\n '\\u1E16': 'E',\n '\\u0114': 'E',\n '\\u0116': 'E',\n '\\u00CB': 'E',\n '\\u1EBA': 'E',\n '\\u011A': 'E',\n '\\u0204': 'E',\n '\\u0206': 'E',\n '\\u1EB8': 'E',\n '\\u1EC6': 'E',\n '\\u0228': 'E',\n '\\u1E1C': 'E',\n '\\u0118': 'E',\n '\\u1E18': 'E',\n '\\u1E1A': 'E',\n '\\u0190': 'E',\n '\\u018E': 'E',\n '\\u24BB': 'F',\n '\\uFF26': 'F',\n '\\u1E1E': 'F',\n '\\u0191': 'F',\n '\\uA77B': 'F',\n '\\u24BC': 'G',\n '\\uFF27': 'G',\n '\\u01F4': 'G',\n '\\u011C': 'G',\n '\\u1E20': 'G',\n '\\u011E': 'G',\n '\\u0120': 'G',\n '\\u01E6': 'G',\n '\\u0122': 'G',\n '\\u01E4': 'G',\n '\\u0193': 'G',\n '\\uA7A0': 'G',\n '\\uA77D': 'G',\n '\\uA77E': 'G',\n '\\u24BD': 'H',\n '\\uFF28': 'H',\n '\\u0124': 'H',\n '\\u1E22': 'H',\n '\\u1E26': 'H',\n '\\u021E': 'H',\n '\\u1E24': 'H',\n '\\u1E28': 'H',\n '\\u1E2A': 'H',\n '\\u0126': 'H',\n '\\u2C67': 'H',\n '\\u2C75': 'H',\n '\\uA78D': 'H',\n '\\u24BE': 'I',\n '\\uFF29': 'I',\n '\\u00CC': 'I',\n '\\u00CD': 'I',\n '\\u00CE': 'I',\n '\\u0128': 'I',\n '\\u012A': 'I',\n '\\u012C': 'I',\n '\\u0130': 'I',\n '\\u00CF': 'I',\n '\\u1E2E': 'I',\n '\\u1EC8': 'I',\n '\\u01CF': 'I',\n '\\u0208': 'I',\n '\\u020A': 'I',\n '\\u1ECA': 'I',\n '\\u012E': 'I',\n '\\u1E2C': 'I',\n '\\u0197': 'I',\n '\\u24BF': 'J',\n '\\uFF2A': 'J',\n '\\u0134': 'J',\n '\\u0248': 'J',\n '\\u24C0': 'K',\n '\\uFF2B': 'K',\n '\\u1E30': 'K',\n '\\u01E8': 'K',\n '\\u1E32': 'K',\n '\\u0136': 'K',\n '\\u1E34': 'K',\n '\\u0198': 'K',\n '\\u2C69': 'K',\n '\\uA740': 'K',\n '\\uA742': 'K',\n '\\uA744': 'K',\n '\\uA7A2': 'K',\n '\\u24C1': 'L',\n '\\uFF2C': 'L',\n '\\u013F': 'L',\n '\\u0139': 'L',\n '\\u013D': 'L',\n '\\u1E36': 'L',\n '\\u1E38': 'L',\n '\\u013B': 'L',\n '\\u1E3C': 'L',\n '\\u1E3A': 'L',\n '\\u0141': 'L',\n '\\u023D': 'L',\n '\\u2C62': 'L',\n '\\u2C60': 'L',\n '\\uA748': 'L',\n '\\uA746': 'L',\n '\\uA780': 'L',\n '\\u01C7': 'LJ',\n '\\u01C8': 'Lj',\n '\\u24C2': 'M',\n '\\uFF2D': 'M',\n '\\u1E3E': 'M',\n '\\u1E40': 'M',\n '\\u1E42': 'M',\n '\\u2C6E': 'M',\n '\\u019C': 'M',\n '\\u24C3': 'N',\n '\\uFF2E': 'N',\n '\\u01F8': 'N',\n '\\u0143': 'N',\n '\\u00D1': 'N',\n '\\u1E44': 'N',\n '\\u0147': 'N',\n '\\u1E46': 'N',\n '\\u0145': 'N',\n '\\u1E4A': 'N',\n '\\u1E48': 'N',\n '\\u0220': 'N',\n '\\u019D': 'N',\n '\\uA790': 'N',\n '\\uA7A4': 'N',\n '\\u01CA': 'NJ',\n '\\u01CB': 'Nj',\n '\\u24C4': 'O',\n '\\uFF2F': 'O',\n '\\u00D2': 'O',\n '\\u00D3': 'O',\n '\\u00D4': 'O',\n '\\u1ED2': 'O',\n '\\u1ED0': 'O',\n '\\u1ED6': 'O',\n '\\u1ED4': 'O',\n '\\u00D5': 'O',\n '\\u1E4C': 'O',\n '\\u022C': 'O',\n '\\u1E4E': 'O',\n '\\u014C': 'O',\n '\\u1E50': 'O',\n '\\u1E52': 'O',\n '\\u014E': 'O',\n '\\u022E': 'O',\n '\\u0230': 'O',\n '\\u00D6': 'O',\n '\\u022A': 'O',\n '\\u1ECE': 'O',\n '\\u0150': 'O',\n '\\u01D1': 'O',\n '\\u020C': 'O',\n '\\u020E': 'O',\n '\\u01A0': 'O',\n '\\u1EDC': 'O',\n '\\u1EDA': 'O',\n '\\u1EE0': 'O',\n '\\u1EDE': 'O',\n '\\u1EE2': 'O',\n '\\u1ECC': 'O',\n '\\u1ED8': 'O',\n '\\u01EA': 'O',\n '\\u01EC': 'O',\n '\\u00D8': 'O',\n '\\u01FE': 'O',\n '\\u0186': 'O',\n '\\u019F': 'O',\n '\\uA74A': 'O',\n '\\uA74C': 'O',\n '\\u01A2': 'OI',\n '\\uA74E': 'OO',\n '\\u0222': 'OU',\n '\\u24C5': 'P',\n '\\uFF30': 'P',\n '\\u1E54': 'P',\n '\\u1E56': 'P',\n '\\u01A4': 'P',\n '\\u2C63': 'P',\n '\\uA750': 'P',\n '\\uA752': 'P',\n '\\uA754': 'P',\n '\\u24C6': 'Q',\n '\\uFF31': 'Q',\n '\\uA756': 'Q',\n '\\uA758': 'Q',\n '\\u024A': 'Q',\n '\\u24C7': 'R',\n '\\uFF32': 'R',\n '\\u0154': 'R',\n '\\u1E58': 'R',\n '\\u0158': 'R',\n '\\u0210': 'R',\n '\\u0212': 'R',\n '\\u1E5A': 'R',\n '\\u1E5C': 'R',\n '\\u0156': 'R',\n '\\u1E5E': 'R',\n '\\u024C': 'R',\n '\\u2C64': 'R',\n '\\uA75A': 'R',\n '\\uA7A6': 'R',\n '\\uA782': 'R',\n '\\u24C8': 'S',\n '\\uFF33': 'S',\n '\\u1E9E': 'S',\n '\\u015A': 'S',\n '\\u1E64': 'S',\n '\\u015C': 'S',\n '\\u1E60': 'S',\n '\\u0160': 'S',\n '\\u1E66': 'S',\n '\\u1E62': 'S',\n '\\u1E68': 'S',\n '\\u0218': 'S',\n '\\u015E': 'S',\n '\\u2C7E': 'S',\n '\\uA7A8': 'S',\n '\\uA784': 'S',\n '\\u24C9': 'T',\n '\\uFF34': 'T',\n '\\u1E6A': 'T',\n '\\u0164': 'T',\n '\\u1E6C': 'T',\n '\\u021A': 'T',\n '\\u0162': 'T',\n '\\u1E70': 'T',\n '\\u1E6E': 'T',\n '\\u0166': 'T',\n '\\u01AC': 'T',\n '\\u01AE': 'T',\n '\\u023E': 'T',\n '\\uA786': 'T',\n '\\uA728': 'TZ',\n '\\u24CA': 'U',\n '\\uFF35': 'U',\n '\\u00D9': 'U',\n '\\u00DA': 'U',\n '\\u00DB': 'U',\n '\\u0168': 'U',\n '\\u1E78': 'U',\n '\\u016A': 'U',\n '\\u1E7A': 'U',\n '\\u016C': 'U',\n '\\u00DC': 'U',\n '\\u01DB': 'U',\n '\\u01D7': 'U',\n '\\u01D5': 'U',\n '\\u01D9': 'U',\n '\\u1EE6': 'U',\n '\\u016E': 'U',\n '\\u0170': 'U',\n '\\u01D3': 'U',\n '\\u0214': 'U',\n '\\u0216': 'U',\n '\\u01AF': 'U',\n '\\u1EEA': 'U',\n '\\u1EE8': 'U',\n '\\u1EEE': 'U',\n '\\u1EEC': 'U',\n '\\u1EF0': 'U',\n '\\u1EE4': 'U',\n '\\u1E72': 'U',\n '\\u0172': 'U',\n '\\u1E76': 'U',\n '\\u1E74': 'U',\n '\\u0244': 'U',\n '\\u24CB': 'V',\n '\\uFF36': 'V',\n '\\u1E7C': 'V',\n '\\u1E7E': 'V',\n '\\u01B2': 'V',\n '\\uA75E': 'V',\n '\\u0245': 'V',\n '\\uA760': 'VY',\n '\\u24CC': 'W',\n '\\uFF37': 'W',\n '\\u1E80': 'W',\n '\\u1E82': 'W',\n '\\u0174': 'W',\n '\\u1E86': 'W',\n '\\u1E84': 'W',\n '\\u1E88': 'W',\n '\\u2C72': 'W',\n '\\u24CD': 'X',\n '\\uFF38': 'X',\n '\\u1E8A': 'X',\n '\\u1E8C': 'X',\n '\\u24CE': 'Y',\n '\\uFF39': 'Y',\n '\\u1EF2': 'Y',\n '\\u00DD': 'Y',\n '\\u0176': 'Y',\n '\\u1EF8': 'Y',\n '\\u0232': 'Y',\n '\\u1E8E': 'Y',\n '\\u0178': 'Y',\n '\\u1EF6': 'Y',\n '\\u1EF4': 'Y',\n '\\u01B3': 'Y',\n '\\u024E': 'Y',\n '\\u1EFE': 'Y',\n '\\u24CF': 'Z',\n '\\uFF3A': 'Z',\n '\\u0179': 'Z',\n '\\u1E90': 'Z',\n '\\u017B': 'Z',\n '\\u017D': 'Z',\n '\\u1E92': 'Z',\n '\\u1E94': 'Z',\n '\\u01B5': 'Z',\n '\\u0224': 'Z',\n '\\u2C7F': 'Z',\n '\\u2C6B': 'Z',\n '\\uA762': 'Z',\n '\\u24D0': 'a',\n '\\uFF41': 'a',\n '\\u1E9A': 'a',\n '\\u00E0': 'a',\n '\\u00E1': 'a',\n '\\u00E2': 'a',\n '\\u1EA7': 'a',\n '\\u1EA5': 'a',\n '\\u1EAB': 'a',\n '\\u1EA9': 'a',\n '\\u00E3': 'a',\n '\\u0101': 'a',\n '\\u0103': 'a',\n '\\u1EB1': 'a',\n '\\u1EAF': 'a',\n '\\u1EB5': 'a',\n '\\u1EB3': 'a',\n '\\u0227': 'a',\n '\\u01E1': 'a',\n '\\u00E4': 'a',\n '\\u01DF': 'a',\n '\\u1EA3': 'a',\n '\\u00E5': 'a',\n '\\u01FB': 'a',\n '\\u01CE': 'a',\n '\\u0201': 'a',\n '\\u0203': 'a',\n '\\u1EA1': 'a',\n '\\u1EAD': 'a',\n '\\u1EB7': 'a',\n '\\u1E01': 'a',\n '\\u0105': 'a',\n '\\u2C65': 'a',\n '\\u0250': 'a',\n '\\uA733': 'aa',\n '\\u00E6': 'ae',\n '\\u01FD': 'ae',\n '\\u01E3': 'ae',\n '\\uA735': 'ao',\n '\\uA737': 'au',\n '\\uA739': 'av',\n '\\uA73B': 'av',\n '\\uA73D': 'ay',\n '\\u24D1': 'b',\n '\\uFF42': 'b',\n '\\u1E03': 'b',\n '\\u1E05': 'b',\n '\\u1E07': 'b',\n '\\u0180': 'b',\n '\\u0183': 'b',\n '\\u0253': 'b',\n '\\u24D2': 'c',\n '\\uFF43': 'c',\n '\\u0107': 'c',\n '\\u0109': 'c',\n '\\u010B': 'c',\n '\\u010D': 'c',\n '\\u00E7': 'c',\n '\\u1E09': 'c',\n '\\u0188': 'c',\n '\\u023C': 'c',\n '\\uA73F': 'c',\n '\\u2184': 'c',\n '\\u24D3': 'd',\n '\\uFF44': 'd',\n '\\u1E0B': 'd',\n '\\u010F': 'd',\n '\\u1E0D': 'd',\n '\\u1E11': 'd',\n '\\u1E13': 'd',\n '\\u1E0F': 'd',\n '\\u0111': 'd',\n '\\u018C': 'd',\n '\\u0256': 'd',\n '\\u0257': 'd',\n '\\uA77A': 'd',\n '\\u01F3': 'dz',\n '\\u01C6': 'dz',\n '\\u24D4': 'e',\n '\\uFF45': 'e',\n '\\u00E8': 'e',\n '\\u00E9': 'e',\n '\\u00EA': 'e',\n '\\u1EC1': 'e',\n '\\u1EBF': 'e',\n '\\u1EC5': 'e',\n '\\u1EC3': 'e',\n '\\u1EBD': 'e',\n '\\u0113': 'e',\n '\\u1E15': 'e',\n '\\u1E17': 'e',\n '\\u0115': 'e',\n '\\u0117': 'e',\n '\\u00EB': 'e',\n '\\u1EBB': 'e',\n '\\u011B': 'e',\n '\\u0205': 'e',\n '\\u0207': 'e',\n '\\u1EB9': 'e',\n '\\u1EC7': 'e',\n '\\u0229': 'e',\n '\\u1E1D': 'e',\n '\\u0119': 'e',\n '\\u1E19': 'e',\n '\\u1E1B': 'e',\n '\\u0247': 'e',\n '\\u025B': 'e',\n '\\u01DD': 'e',\n '\\u24D5': 'f',\n '\\uFF46': 'f',\n '\\u1E1F': 'f',\n '\\u0192': 'f',\n '\\uA77C': 'f',\n '\\u24D6': 'g',\n '\\uFF47': 'g',\n '\\u01F5': 'g',\n '\\u011D': 'g',\n '\\u1E21': 'g',\n '\\u011F': 'g',\n '\\u0121': 'g',\n '\\u01E7': 'g',\n '\\u0123': 'g',\n '\\u01E5': 'g',\n '\\u0260': 'g',\n '\\uA7A1': 'g',\n '\\u1D79': 'g',\n '\\uA77F': 'g',\n '\\u24D7': 'h',\n '\\uFF48': 'h',\n '\\u0125': 'h',\n '\\u1E23': 'h',\n '\\u1E27': 'h',\n '\\u021F': 'h',\n '\\u1E25': 'h',\n '\\u1E29': 'h',\n '\\u1E2B': 'h',\n '\\u1E96': 'h',\n '\\u0127': 'h',\n '\\u2C68': 'h',\n '\\u2C76': 'h',\n '\\u0265': 'h',\n '\\u0195': 'hv',\n '\\u24D8': 'i',\n '\\uFF49': 'i',\n '\\u00EC': 'i',\n '\\u00ED': 'i',\n '\\u00EE': 'i',\n '\\u0129': 'i',\n '\\u012B': 'i',\n '\\u012D': 'i',\n '\\u00EF': 'i',\n '\\u1E2F': 'i',\n '\\u1EC9': 'i',\n '\\u01D0': 'i',\n '\\u0209': 'i',\n '\\u020B': 'i',\n '\\u1ECB': 'i',\n '\\u012F': 'i',\n '\\u1E2D': 'i',\n '\\u0268': 'i',\n '\\u0131': 'i',\n '\\u24D9': 'j',\n '\\uFF4A': 'j',\n '\\u0135': 'j',\n '\\u01F0': 'j',\n '\\u0249': 'j',\n '\\u24DA': 'k',\n '\\uFF4B': 'k',\n '\\u1E31': 'k',\n '\\u01E9': 'k',\n '\\u1E33': 'k',\n '\\u0137': 'k',\n '\\u1E35': 'k',\n '\\u0199': 'k',\n '\\u2C6A': 'k',\n '\\uA741': 'k',\n '\\uA743': 'k',\n '\\uA745': 'k',\n '\\uA7A3': 'k',\n '\\u24DB': 'l',\n '\\uFF4C': 'l',\n '\\u0140': 'l',\n '\\u013A': 'l',\n '\\u013E': 'l',\n '\\u1E37': 'l',\n '\\u1E39': 'l',\n '\\u013C': 'l',\n '\\u1E3D': 'l',\n '\\u1E3B': 'l',\n '\\u017F': 'l',\n '\\u0142': 'l',\n '\\u019A': 'l',\n '\\u026B': 'l',\n '\\u2C61': 'l',\n '\\uA749': 'l',\n '\\uA781': 'l',\n '\\uA747': 'l',\n '\\u01C9': 'lj',\n '\\u24DC': 'm',\n '\\uFF4D': 'm',\n '\\u1E3F': 'm',\n '\\u1E41': 'm',\n '\\u1E43': 'm',\n '\\u0271': 'm',\n '\\u026F': 'm',\n '\\u24DD': 'n',\n '\\uFF4E': 'n',\n '\\u01F9': 'n',\n '\\u0144': 'n',\n '\\u00F1': 'n',\n '\\u1E45': 'n',\n '\\u0148': 'n',\n '\\u1E47': 'n',\n '\\u0146': 'n',\n '\\u1E4B': 'n',\n '\\u1E49': 'n',\n '\\u019E': 'n',\n '\\u0272': 'n',\n '\\u0149': 'n',\n '\\uA791': 'n',\n '\\uA7A5': 'n',\n '\\u01CC': 'nj',\n '\\u24DE': 'o',\n '\\uFF4F': 'o',\n '\\u00F2': 'o',\n '\\u00F3': 'o',\n '\\u00F4': 'o',\n '\\u1ED3': 'o',\n '\\u1ED1': 'o',\n '\\u1ED7': 'o',\n '\\u1ED5': 'o',\n '\\u00F5': 'o',\n '\\u1E4D': 'o',\n '\\u022D': 'o',\n '\\u1E4F': 'o',\n '\\u014D': 'o',\n '\\u1E51': 'o',\n '\\u1E53': 'o',\n '\\u014F': 'o',\n '\\u022F': 'o',\n '\\u0231': 'o',\n '\\u00F6': 'o',\n '\\u022B': 'o',\n '\\u1ECF': 'o',\n '\\u0151': 'o',\n '\\u01D2': 'o',\n '\\u020D': 'o',\n '\\u020F': 'o',\n '\\u01A1': 'o',\n '\\u1EDD': 'o',\n '\\u1EDB': 'o',\n '\\u1EE1': 'o',\n '\\u1EDF': 'o',\n '\\u1EE3': 'o',\n '\\u1ECD': 'o',\n '\\u1ED9': 'o',\n '\\u01EB': 'o',\n '\\u01ED': 'o',\n '\\u00F8': 'o',\n '\\u01FF': 'o',\n '\\u0254': 'o',\n '\\uA74B': 'o',\n '\\uA74D': 'o',\n '\\u0275': 'o',\n '\\u01A3': 'oi',\n '\\u0223': 'ou',\n '\\uA74F': 'oo',\n '\\u24DF': 'p',\n '\\uFF50': 'p',\n '\\u1E55': 'p',\n '\\u1E57': 'p',\n '\\u01A5': 'p',\n '\\u1D7D': 'p',\n '\\uA751': 'p',\n '\\uA753': 'p',\n '\\uA755': 'p',\n '\\u24E0': 'q',\n '\\uFF51': 'q',\n '\\u024B': 'q',\n '\\uA757': 'q',\n '\\uA759': 'q',\n '\\u24E1': 'r',\n '\\uFF52': 'r',\n '\\u0155': 'r',\n '\\u1E59': 'r',\n '\\u0159': 'r',\n '\\u0211': 'r',\n '\\u0213': 'r',\n '\\u1E5B': 'r',\n '\\u1E5D': 'r',\n '\\u0157': 'r',\n '\\u1E5F': 'r',\n '\\u024D': 'r',\n '\\u027D': 'r',\n '\\uA75B': 'r',\n '\\uA7A7': 'r',\n '\\uA783': 'r',\n '\\u24E2': 's',\n '\\uFF53': 's',\n '\\u00DF': 's',\n '\\u015B': 's',\n '\\u1E65': 's',\n '\\u015D': 's',\n '\\u1E61': 's',\n '\\u0161': 's',\n '\\u1E67': 's',\n '\\u1E63': 's',\n '\\u1E69': 's',\n '\\u0219': 's',\n '\\u015F': 's',\n '\\u023F': 's',\n '\\uA7A9': 's',\n '\\uA785': 's',\n '\\u1E9B': 's',\n '\\u24E3': 't',\n '\\uFF54': 't',\n '\\u1E6B': 't',\n '\\u1E97': 't',\n '\\u0165': 't',\n '\\u1E6D': 't',\n '\\u021B': 't',\n '\\u0163': 't',\n '\\u1E71': 't',\n '\\u1E6F': 't',\n '\\u0167': 't',\n '\\u01AD': 't',\n '\\u0288': 't',\n '\\u2C66': 't',\n '\\uA787': 't',\n '\\uA729': 'tz',\n '\\u24E4': 'u',\n '\\uFF55': 'u',\n '\\u00F9': 'u',\n '\\u00FA': 'u',\n '\\u00FB': 'u',\n '\\u0169': 'u',\n '\\u1E79': 'u',\n '\\u016B': 'u',\n '\\u1E7B': 'u',\n '\\u016D': 'u',\n '\\u00FC': 'u',\n '\\u01DC': 'u',\n '\\u01D8': 'u',\n '\\u01D6': 'u',\n '\\u01DA': 'u',\n '\\u1EE7': 'u',\n '\\u016F': 'u',\n '\\u0171': 'u',\n '\\u01D4': 'u',\n '\\u0215': 'u',\n '\\u0217': 'u',\n '\\u01B0': 'u',\n '\\u1EEB': 'u',\n '\\u1EE9': 'u',\n '\\u1EEF': 'u',\n '\\u1EED': 'u',\n '\\u1EF1': 'u',\n '\\u1EE5': 'u',\n '\\u1E73': 'u',\n '\\u0173': 'u',\n '\\u1E77': 'u',\n '\\u1E75': 'u',\n '\\u0289': 'u',\n '\\u24E5': 'v',\n '\\uFF56': 'v',\n '\\u1E7D': 'v',\n '\\u1E7F': 'v',\n '\\u028B': 'v',\n '\\uA75F': 'v',\n '\\u028C': 'v',\n '\\uA761': 'vy',\n '\\u24E6': 'w',\n '\\uFF57': 'w',\n '\\u1E81': 'w',\n '\\u1E83': 'w',\n '\\u0175': 'w',\n '\\u1E87': 'w',\n '\\u1E85': 'w',\n '\\u1E98': 'w',\n '\\u1E89': 'w',\n '\\u2C73': 'w',\n '\\u24E7': 'x',\n '\\uFF58': 'x',\n '\\u1E8B': 'x',\n '\\u1E8D': 'x',\n '\\u24E8': 'y',\n '\\uFF59': 'y',\n '\\u1EF3': 'y',\n '\\u00FD': 'y',\n '\\u0177': 'y',\n '\\u1EF9': 'y',\n '\\u0233': 'y',\n '\\u1E8F': 'y',\n '\\u00FF': 'y',\n '\\u1EF7': 'y',\n '\\u1E99': 'y',\n '\\u1EF5': 'y',\n '\\u01B4': 'y',\n '\\u024F': 'y',\n '\\u1EFF': 'y',\n '\\u24E9': 'z',\n '\\uFF5A': 'z',\n '\\u017A': 'z',\n '\\u1E91': 'z',\n '\\u017C': 'z',\n '\\u017E': 'z',\n '\\u1E93': 'z',\n '\\u1E95': 'z',\n '\\u01B6': 'z',\n '\\u0225': 'z',\n '\\u0240': 'z',\n '\\u2C6C': 'z',\n '\\uA763': 'z',\n '\\u0386': '\\u0391',\n '\\u0388': '\\u0395',\n '\\u0389': '\\u0397',\n '\\u038A': '\\u0399',\n '\\u03AA': '\\u0399',\n '\\u038C': '\\u039F',\n '\\u038E': '\\u03A5',\n '\\u03AB': '\\u03A5',\n '\\u038F': '\\u03A9',\n '\\u03AC': '\\u03B1',\n '\\u03AD': '\\u03B5',\n '\\u03AE': '\\u03B7',\n '\\u03AF': '\\u03B9',\n '\\u03CA': '\\u03B9',\n '\\u0390': '\\u03B9',\n '\\u03CC': '\\u03BF',\n '\\u03CD': '\\u03C5',\n '\\u03CB': '\\u03C5',\n '\\u03B0': '\\u03C5',\n '\\u03C9': '\\u03C9',\n '\\u03C2': '\\u03C3'\n };\n DataUtil.fnOperators = {\n /**\n * Returns true when the actual input is equal to the given input.\n * @param {string|number|boolean} actual\n * @param {string|number|boolean} expected\n * @param {boolean} ignoreCase?\n * @param {boolean} ignoreAccent?\n */\n equal: function (actual, expected, ignoreCase, ignoreAccent) {\n if (ignoreAccent) {\n actual = DataUtil.ignoreDiacritics(actual);\n expected = DataUtil.ignoreDiacritics(expected);\n }\n if (ignoreCase) {\n return DataUtil.toLowerCase(actual) === DataUtil.toLowerCase(expected);\n }\n return actual === expected;\n },\n /**\n * Returns true when the actual input is not equal to the given input.\n * @param {string|number|boolean} actual\n * @param {string|number|boolean} expected\n * @param {boolean} ignoreCase?\n */\n notequal: function (actual, expected, ignoreCase, ignoreAccent) {\n if (ignoreAccent) {\n actual = DataUtil.ignoreDiacritics(actual);\n expected = DataUtil.ignoreDiacritics(expected);\n }\n return !DataUtil.fnOperators.equal(actual, expected, ignoreCase);\n },\n /**\n * Returns true when the actual input is less than to the given input.\n * @param {string|number|boolean} actual\n * @param {string|number|boolean} expected\n * @param {boolean} ignoreCase?\n */\n lessthan: function (actual, expected, ignoreCase) {\n if (ignoreCase) {\n return DataUtil.toLowerCase(actual) < DataUtil.toLowerCase(expected);\n }\n return actual < expected;\n },\n /**\n * Returns true when the actual input is greater than to the given input.\n * @param {string|number|boolean} actual\n * @param {string|number|boolean} expected\n * @param {boolean} ignoreCase?\n */\n greaterthan: function (actual, expected, ignoreCase) {\n if (ignoreCase) {\n return DataUtil.toLowerCase(actual) > DataUtil.toLowerCase(expected);\n }\n return actual > expected;\n },\n /**\n * Returns true when the actual input is less than or equal to the given input.\n * @param {string|number|boolean} actual\n * @param {string|number|boolean} expected\n * @param {boolean} ignoreCase?\n */\n lessthanorequal: function (actual, expected, ignoreCase) {\n if (ignoreCase) {\n return DataUtil.toLowerCase(actual) <= DataUtil.toLowerCase(expected);\n }\n return actual <= expected;\n },\n /**\n * Returns true when the actual input is greater than or equal to the given input.\n * @param {string|number|boolean} actual\n * @param {string|number|boolean} expected\n * @param {boolean} ignoreCase?\n */\n greaterthanorequal: function (actual, expected, ignoreCase) {\n if (ignoreCase) {\n return DataUtil.toLowerCase(actual) >= DataUtil.toLowerCase(expected);\n }\n return actual >= expected;\n },\n /**\n * Returns true when the actual input contains the given string.\n * @param {string|number} actual\n * @param {string|number} expected\n * @param {boolean} ignoreCase?\n */\n contains: function (actual, expected, ignoreCase, ignoreAccent) {\n if (ignoreAccent) {\n actual = DataUtil.ignoreDiacritics(actual);\n expected = DataUtil.ignoreDiacritics(expected);\n }\n if (ignoreCase) {\n return !isNullOrUndefined(actual) && !isNullOrUndefined(expected) &&\n DataUtil.toLowerCase(actual).indexOf(DataUtil.toLowerCase(expected)) !== -1;\n }\n return !isNullOrUndefined(actual) && !isNullOrUndefined(expected) &&\n actual.toString().indexOf(expected) !== -1;\n },\n /**\n * Returns true when the given input value is not null.\n * @param {string|number} actual\n * @returns boolean\n */\n notnull: function (actual) {\n return actual !== null;\n },\n /**\n * Returns true when the given input value is null.\n * @param {string|number} actual\n * @returns boolean\n */\n isnull: function (actual) {\n return actual === null;\n },\n /**\n * Returns true when the actual input starts with the given string\n * @param {string} actual\n * @param {string} expected\n * @param {boolean} ignoreCase?\n */\n startswith: function (actual, expected, ignoreCase, ignoreAccent) {\n if (ignoreAccent) {\n actual = DataUtil.ignoreDiacritics(actual);\n expected = DataUtil.ignoreDiacritics(expected);\n }\n if (ignoreCase) {\n return actual && expected && DataUtil.startsWith(DataUtil.toLowerCase(actual), DataUtil.toLowerCase(expected));\n }\n return actual && expected && DataUtil.startsWith(actual, expected);\n },\n /**\n * Returns true when the actual input ends with the given string.\n * @param {string} actual\n * @param {string} expected\n * @param {boolean} ignoreCase?\n */\n endswith: function (actual, expected, ignoreCase, ignoreAccent) {\n if (ignoreAccent) {\n actual = DataUtil.ignoreDiacritics(actual);\n expected = DataUtil.ignoreDiacritics(expected);\n }\n if (ignoreCase) {\n return actual && expected && DataUtil.endsWith(DataUtil.toLowerCase(actual), DataUtil.toLowerCase(expected));\n }\n return actual && expected && DataUtil.endsWith(actual, expected);\n },\n /**\n * It will return the filter operator based on the filter symbol.\n * @param {string} operator\n * @hidden\n */\n processSymbols: function (operator) {\n var fnName = DataUtil.operatorSymbols[operator];\n if (fnName) {\n var fn = DataUtil.fnOperators[fnName];\n return fn;\n }\n return DataUtil.throwError('Query - Process Operator : Invalid operator');\n },\n /**\n * It will return the valid filter operator based on the specified operators.\n * @param {string} operator\n * @hidden\n */\n processOperator: function (operator) {\n var fn = DataUtil.fnOperators[operator];\n if (fn) {\n return fn;\n }\n return DataUtil.fnOperators.processSymbols(operator);\n }\n };\n /**\n * To perform the parse operation on JSON data, like convert to string from JSON or convert to JSON from string.\n */\n DataUtil.parse = {\n /**\n * Parse the given string to the plain JavaScript object.\n * @param {string|Object|Object[]} jsonText\n */\n parseJson: function (jsonText) {\n if (typeof jsonText === 'string') {\n jsonText = JSON.parse(jsonText, DataUtil.parse.jsonReviver);\n }\n else if (jsonText instanceof Array) {\n DataUtil.parse.iterateAndReviveArray(jsonText);\n }\n else if (typeof jsonText === 'object') {\n DataUtil.parse.iterateAndReviveJson(jsonText);\n }\n return jsonText;\n },\n /**\n * It will perform on array of values.\n * @param {string[]|Object[]} array\n * @hidden\n */\n iterateAndReviveArray: function (array) {\n for (var i = 0; i < array.length; i++) {\n if (typeof array[i] === 'object') {\n DataUtil.parse.iterateAndReviveJson(array[i]);\n }\n else if (typeof array[i] === 'string' && !/^[\\s]*\\[|^[\\s]*\\{|\\\"/g.test(array[i])) {\n array[i] = DataUtil.parse.jsonReviver('', array[i]);\n }\n else {\n array[i] = DataUtil.parse.parseJson(array[i]);\n }\n }\n },\n /**\n * It will perform on JSON values\n * @param {JSON} json\n * @hidden\n */\n iterateAndReviveJson: function (json) {\n var value;\n var keys = Object.keys(json);\n for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {\n var prop = keys_2[_i];\n if (DataUtil.startsWith(prop, '__')) {\n continue;\n }\n value = json[prop];\n if (typeof value === 'object') {\n if (value instanceof Array) {\n DataUtil.parse.iterateAndReviveArray(value);\n }\n else if (value) {\n DataUtil.parse.iterateAndReviveJson(value);\n }\n }\n else {\n json[prop] = DataUtil.parse.jsonReviver(json[prop], value);\n }\n }\n },\n /**\n * It will perform on JSON values\n * @param {string} field\n * @param {string|Date} value\n * @hidden\n */\n jsonReviver: function (field, value) {\n var dupValue = value;\n if (typeof value === 'string') {\n var ms = /^\\/Date\\(([+-]?[0-9]+)([+-][0-9]{4})?\\)\\/$/.exec(value);\n if (ms) {\n return DataUtil.dateParse.toTimeZone(new Date(parseInt(ms[1], 10)), DataUtil.serverTimezoneOffset, true);\n }\n else if (/^(\\d{4}\\-\\d\\d\\-\\d\\d([tT][\\d:\\.]*){1})([zZ]|([+\\-])(\\d\\d):?(\\d\\d))?$/.test(value)) {\n var arr = dupValue.split(/[^0-9]/);\n value = DataUtil.dateParse\n .toTimeZone(new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, parseInt(arr[2], 10), parseInt(arr[3], 10), parseInt(arr[4], 10), parseInt(arr[5], 10)), DataUtil.serverTimezoneOffset, true);\n }\n }\n return value;\n },\n /**\n * Check wheather the given value is JSON or not.\n * @param {Object[]} jsonData\n */\n isJson: function (jsonData) {\n if (typeof jsonData[0] === 'string') {\n return jsonData;\n }\n return DataUtil.parse.parseJson(jsonData);\n },\n /**\n * Checks wheather the given value is GUID or not.\n * @param {string} value\n */\n isGuid: function (value) {\n var regex = /[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}/i;\n var match = regex.exec(value);\n return match != null;\n },\n /**\n * The method used to replace the value based on the type.\n * @param {Object} value\n * @param {boolean} stringify\n * @hidden\n */\n replacer: function (value, stringify) {\n if (DataUtil.isPlainObject(value)) {\n return DataUtil.parse.jsonReplacer(value, stringify);\n }\n if (value instanceof Array) {\n return DataUtil.parse.arrayReplacer(value);\n }\n if (value instanceof Date) {\n return DataUtil.parse.jsonReplacer({ val: value }, stringify).val;\n }\n return value;\n },\n /**\n * It will replace the JSON value.\n * @param {string} key\n * @param {Object} val\n * @hidden\n */\n jsonReplacer: function (val, stringify) {\n var value;\n var keys = Object.keys(val);\n for (var _i = 0, keys_3 = keys; _i < keys_3.length; _i++) {\n var prop = keys_3[_i];\n value = val[prop];\n if (!(value instanceof Date)) {\n continue;\n }\n var d = value;\n val[prop] = DataUtil.dateParse.toTimeZone(DataUtil.dateParse.addSelfOffset(d), DataUtil.serverTimezoneOffset).toJSON();\n }\n return val;\n },\n /**\n * It will replace the Array of value.\n * @param {string} key\n * @param {Object[]} val\n * @hidden\n */\n arrayReplacer: function (val) {\n for (var i = 0; i < val.length; i++) {\n if (DataUtil.isPlainObject(val[i])) {\n val[i] = DataUtil.parse.jsonReplacer(val[i]);\n }\n else if (val[i] instanceof Date) {\n val[i] = DataUtil.parse.jsonReplacer({ date: val[i] }).date;\n }\n }\n return val;\n }\n };\n /**\n * @hidden\n */\n DataUtil.dateParse = {\n addSelfOffset: function (input) {\n return new Date(+input - (input.getTimezoneOffset() * 60000));\n },\n toUTC: function (input) {\n return new Date(+input + (input.getTimezoneOffset() * 60000));\n },\n toTimeZone: function (input, offset, utc) {\n if (offset === null) {\n return input;\n }\n var unix = utc ? DataUtil.dateParse.toUTC(input) : input;\n return new Date(+unix - (offset * 3600000));\n },\n toLocalTime: function (input) {\n var datefn = input;\n var timeZone = -datefn.getTimezoneOffset();\n var differenceString = timeZone >= 0 ? '+' : '-';\n var localtimefn = function (num) {\n var norm = Math.floor(Math.abs(num));\n return (norm < 10 ? '0' : '') + norm;\n };\n var val = datefn.getFullYear() + '-' + localtimefn(datefn.getMonth() + 1) + '-' + localtimefn(datefn.getDate()) +\n 'T' + localtimefn(datefn.getHours()) +\n ':' + localtimefn(datefn.getMinutes()) +\n ':' + localtimefn(datefn.getSeconds()) +\n differenceString + localtimefn(timeZone / 60) +\n ':' + localtimefn(timeZone % 60);\n return val;\n }\n };\n return DataUtil;\n}());\nexport { DataUtil };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { merge, extend, isNullOrUndefined, setValue, getValue } from '@syncfusion/ej2-base';\nimport { DataUtil } from './util';\nimport { Query, Predicate } from './query';\n/**\n * Adaptors are specific data source type aware interfaces that are used by DataManager to communicate with DataSource.\n * This is the base adaptor class that other adaptors can extend.\n * @hidden\n */\nvar Adaptor = /** @class */ (function () {\n function Adaptor(ds) {\n // common options for all the adaptors \n this.options = {\n from: 'table',\n requestType: 'json',\n sortBy: 'sorted',\n select: 'select',\n skip: 'skip',\n group: 'group',\n take: 'take',\n search: 'search',\n count: 'requiresCounts',\n where: 'where',\n aggregates: 'aggregates'\n };\n /**\n * Specifies the type of adaptor.\n * @default Adaptor\n */\n this.type = Adaptor;\n this.dataSource = ds;\n this.pvt = {};\n }\n /**\n * Returns the data from the query processing.\n * @param {Object} data\n * @param {DataOptions} ds?\n * @param {Query} query?\n * @param {XMLHttpRequest} xhr?\n * @returns Object\n */\n Adaptor.prototype.processResponse = function (data, ds, query, xhr) {\n return data;\n };\n return Adaptor;\n}());\nexport { Adaptor };\n/**\n * JsonAdaptor is used to process JSON data. It contains methods to process the given JSON data based on the queries.\n * @hidden\n */\nvar JsonAdaptor = /** @class */ (function (_super) {\n __extends(JsonAdaptor, _super);\n function JsonAdaptor() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Process the JSON data based on the provided queries.\n * @param {DataManager} dataManager\n * @param {Query} query\n * @returns Object\n */\n JsonAdaptor.prototype.processQuery = function (dataManager, query) {\n var result = dataManager.dataSource.json.slice(0);\n var count = result.length;\n var countFlg = true;\n var ret;\n var key;\n var agg = {};\n for (var i = 0; i < query.queries.length; i++) {\n key = query.queries[i];\n ret = this[key.fn].call(this, result, key.e, query);\n if (key.fn === 'onAggregates') {\n agg[key.e.field + ' - ' + key.e.type] = ret;\n }\n else {\n result = ret !== undefined ? ret : result;\n }\n if (key.fn === 'onPage' || key.fn === 'onSkip' || key.fn === 'onTake' || key.fn === 'onRange') {\n countFlg = false;\n }\n if (countFlg) {\n count = result.length;\n }\n }\n if (query.isCountRequired) {\n result = {\n result: result,\n count: count,\n aggregates: agg\n };\n }\n return result;\n };\n /**\n * Performs batch update in the JSON array which add, remove and update records.\n * @param {DataManager} dm\n * @param {CrudOptions} changes\n * @param {RemoteArgs} e\n */\n JsonAdaptor.prototype.batchRequest = function (dm, changes, e) {\n var i;\n for (i = 0; i < changes.addedRecords.length; i++) {\n this.insert(dm, changes.addedRecords[i]);\n }\n for (i = 0; i < changes.changedRecords.length; i++) {\n this.update(dm, e.key, changes.changedRecords[i]);\n }\n for (i = 0; i < changes.deletedRecords.length; i++) {\n this.remove(dm, e.key, changes.deletedRecords[i]);\n }\n return changes;\n };\n /**\n * Performs filter operation with the given data and where query.\n * @param {Object[]} ds\n * @param {{validate:Function}} e\n */\n JsonAdaptor.prototype.onWhere = function (ds, e) {\n if (!ds || !ds.length) {\n return ds;\n }\n return ds.filter(function (obj) {\n if (e) {\n return e.validate(obj);\n }\n });\n };\n /**\n * Returns aggregate function based on the aggregate type.\n * @param {Object[]} ds\n * @param {{field:string} e\n * @param {string}} type\n */\n JsonAdaptor.prototype.onAggregates = function (ds, e) {\n var fn = DataUtil.aggregates[e.type];\n if (!ds || !fn || ds.length === 0) {\n return null;\n }\n return fn(ds, e.field);\n };\n /**\n * Performs search operation based on the given query.\n * @param {Object[]} ds\n * @param {QueryOptions} e\n */\n JsonAdaptor.prototype.onSearch = function (ds, e) {\n if (!ds || !ds.length) {\n return ds;\n }\n if (e.fieldNames.length === 0) {\n DataUtil.getFieldList(ds[0], e.fieldNames);\n }\n return ds.filter(function (obj) {\n for (var j = 0; j < e.fieldNames.length; j++) {\n if (e.comparer.call(obj, DataUtil.getObject(e.fieldNames[j], obj), e.searchKey, e.ignoreCase, e.ignoreAccent)) {\n return true;\n }\n }\n return false;\n });\n };\n /**\n * Sort the data with given direction and field.\n * @param {Object[]} ds\n * @param {{comparer:(a:Object} e\n * @param {Object} b\n */\n JsonAdaptor.prototype.onSortBy = function (ds, e, query) {\n if (!ds || !ds.length) {\n return ds;\n }\n var fnCompare;\n var field = DataUtil.getValue(e.fieldName, query);\n if (!field) {\n return ds.sort(e.comparer);\n }\n if (field instanceof Array) {\n field = field.slice(0);\n for (var i = field.length - 1; i >= 0; i--) {\n if (!field[i]) {\n continue;\n }\n fnCompare = e.comparer;\n if (DataUtil.endsWith(field[i], ' desc')) {\n fnCompare = DataUtil.fnSort('descending');\n field[i] = field[i].replace(' desc', '');\n }\n ds = DataUtil.sort(ds, field[i], fnCompare);\n }\n return ds;\n }\n return DataUtil.sort(ds, field, e.comparer);\n };\n /**\n * Group the data based on the given query.\n * @param {Object[]} ds\n * @param {QueryOptions} e\n * @param {Query} query\n */\n JsonAdaptor.prototype.onGroup = function (ds, e, query) {\n if (!ds || !ds.length) {\n return ds;\n }\n var aggQuery = Query.filterQueries(query.queries, 'onAggregates');\n var agg = [];\n if (aggQuery.length) {\n var tmp = void 0;\n for (var i = 0; i < aggQuery.length; i++) {\n tmp = aggQuery[i].e;\n agg.push({ type: tmp.type, field: DataUtil.getValue(tmp.field, query) });\n }\n }\n return DataUtil.group(ds, DataUtil.getValue(e.fieldName, query), agg, null, null, e.comparer);\n };\n /**\n * Retrieves records based on the given page index and size.\n * @param {Object[]} ds\n * @param {{pageSize:number} e\n * @param {number}} pageIndex\n * @param {Query} query\n */\n JsonAdaptor.prototype.onPage = function (ds, e, query) {\n var size = DataUtil.getValue(e.pageSize, query);\n var start = (DataUtil.getValue(e.pageIndex, query) - 1) * size;\n var end = start + size;\n if (!ds || !ds.length) {\n return ds;\n }\n return ds.slice(start, end);\n };\n /**\n * Retrieves records based on the given start and end index from query.\n * @param {Object[]} ds\n * @param {{start:number} e\n * @param {number}} end\n */\n JsonAdaptor.prototype.onRange = function (ds, e) {\n if (!ds || !ds.length) {\n return ds;\n }\n return ds.slice(DataUtil.getValue(e.start), DataUtil.getValue(e.end));\n };\n /**\n * Picks the given count of records from the top of the datasource.\n * @param {Object[]} ds\n * @param {{nos:number}} e\n */\n JsonAdaptor.prototype.onTake = function (ds, e) {\n if (!ds || !ds.length) {\n return ds;\n }\n return ds.slice(0, DataUtil.getValue(e.nos));\n };\n /**\n * Skips the given count of records from the data source.\n * @param {Object[]} ds\n * @param {{nos:number}} e\n */\n JsonAdaptor.prototype.onSkip = function (ds, e) {\n if (!ds || !ds.length) {\n return ds;\n }\n return ds.slice(DataUtil.getValue(e.nos));\n };\n /**\n * Selects specified columns from the data source.\n * @param {Object[]} ds\n * @param {{fieldNames:string}} e\n */\n JsonAdaptor.prototype.onSelect = function (ds, e) {\n if (!ds || !ds.length) {\n return ds;\n }\n return DataUtil.select(ds, DataUtil.getValue(e.fieldNames));\n };\n /**\n * Inserts new record in the table.\n * @param {DataManager} dm\n * @param {Object} data\n * @param {number} position\n */\n JsonAdaptor.prototype.insert = function (dm, data, tableName, query, position) {\n if (isNullOrUndefined(position)) {\n return dm.dataSource.json.push(data);\n }\n else {\n return dm.dataSource.json.splice(position, 0, data);\n }\n };\n /**\n * Remove the data from the dataSource based on the key field value.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {Object} value\n * @param {string} tableName?\n * @returns null\n */\n JsonAdaptor.prototype.remove = function (dm, keyField, value, tableName) {\n var ds = dm.dataSource.json;\n var i;\n if (typeof value === 'object') {\n value = value[keyField];\n }\n for (i = 0; i < ds.length; i++) {\n if (ds[i][keyField] === value) {\n break;\n }\n }\n return i !== ds.length ? ds.splice(i, 1) : null;\n };\n /**\n * Updates existing record and saves the changes to the table.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {Object} value\n * @param {string} tableName?\n * @returns null\n */\n JsonAdaptor.prototype.update = function (dm, keyField, value, tableName) {\n var ds = dm.dataSource.json;\n var i;\n var key = value[keyField];\n for (i = 0; i < ds.length; i++) {\n if (ds[i][keyField] === key) {\n break;\n }\n }\n return i < ds.length ? merge(ds[i], value) : null;\n };\n return JsonAdaptor;\n}(Adaptor));\nexport { JsonAdaptor };\n/**\n * URL Adaptor of DataManager can be used when you are required to use remote service to retrieve data.\n * It interacts with server-side for all DataManager Queries and CRUD operations.\n * @hidden\n */\nvar UrlAdaptor = /** @class */ (function (_super) {\n __extends(UrlAdaptor, _super);\n function UrlAdaptor() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Process the query to generate request body.\n * @param {DataManager} dm\n * @param {Query} query\n * @param {Object[]} hierarchyFilters?\n * @returns p\n */\n UrlAdaptor.prototype.processQuery = function (dm, query, hierarchyFilters) {\n var queries = this.getQueryRequest(query);\n var singles = Query.filterQueryLists(query.queries, ['onSelect', 'onPage', 'onSkip', 'onTake', 'onRange']);\n var params = query.params;\n var url = dm.dataSource.url;\n var temp;\n var skip;\n var take = null;\n var options = this.options;\n var request = { sorts: [], groups: [], filters: [], searches: [], aggregates: [] };\n // calc Paging & Range\n if ('onPage' in singles) {\n temp = singles.onPage;\n skip = DataUtil.getValue(temp.pageIndex, query);\n take = DataUtil.getValue(temp.pageSize, query);\n skip = (skip - 1) * take;\n }\n else if ('onRange' in singles) {\n temp = singles.onRange;\n skip = temp.start;\n take = temp.end - temp.start;\n }\n // Sorting\n for (var i = 0; i < queries.sorts.length; i++) {\n temp = DataUtil.getValue(queries.sorts[i].e.fieldName, query);\n request.sorts.push(DataUtil.callAdaptorFunction(this, 'onEachSort', { name: temp, direction: queries.sorts[i].e.direction }, query));\n }\n // hierarchy\n if (hierarchyFilters) {\n temp = this.getFiltersFrom(hierarchyFilters, query);\n if (temp) {\n request.filters.push(DataUtil.callAdaptorFunction(this, 'onEachWhere', temp.toJson(), query));\n }\n }\n // Filters\n for (var i = 0; i < queries.filters.length; i++) {\n request.filters.push(DataUtil.callAdaptorFunction(this, 'onEachWhere', queries.filters[i].e.toJson(), query));\n var keys_1 = typeof request.filters[i] === 'object' ? Object.keys(request.filters[i]) : [];\n for (var _i = 0, keys_2 = keys_1; _i < keys_2.length; _i++) {\n var prop = keys_2[_i];\n if (DataUtil.isNull((request)[prop])) {\n delete request[prop];\n }\n }\n }\n // Searches\n for (var i = 0; i < queries.searches.length; i++) {\n temp = queries.searches[i].e;\n request.searches.push(DataUtil.callAdaptorFunction(this, 'onEachSearch', {\n fields: temp.fieldNames,\n operator: temp.operator,\n key: temp.searchKey,\n ignoreCase: temp.ignoreCase\n }, query));\n }\n // Grouping\n for (var i = 0; i < queries.groups.length; i++) {\n request.groups.push(DataUtil.getValue(queries.groups[i].e.fieldName, query));\n }\n // aggregates\n for (var i = 0; i < queries.aggregates.length; i++) {\n temp = queries.aggregates[i].e;\n request.aggregates.push({ type: temp.type, field: DataUtil.getValue(temp.field, query) });\n }\n var req = {};\n this.getRequestQuery(options, query, singles, request, req);\n // Params\n DataUtil.callAdaptorFunction(this, 'addParams', { dm: dm, query: query, params: params, reqParams: req });\n // cleanup\n var keys = Object.keys(req);\n for (var _a = 0, keys_3 = keys; _a < keys_3.length; _a++) {\n var prop = keys_3[_a];\n if (DataUtil.isNull(req[prop]) || req[prop] === '' || req[prop].length === 0) {\n delete req[prop];\n }\n }\n if (!(options.skip in req && options.take in req) && take !== null) {\n req[options.skip] = DataUtil.callAdaptorFunction(this, 'onSkip', skip, query);\n req[options.take] = DataUtil.callAdaptorFunction(this, 'onTake', take, query);\n }\n var p = this.pvt;\n this.pvt = {};\n if (this.options.requestType === 'json') {\n return {\n data: JSON.stringify(req),\n url: url,\n pvtData: p,\n type: 'POST',\n contentType: 'application/json; charset=utf-8'\n };\n }\n temp = this.convertToQueryString(req, query, dm);\n temp = (dm.dataSource.url.indexOf('?') !== -1 ? '&' : '/') + temp;\n return {\n type: 'GET', url: temp.length ? url.replace(/\\/*$/, temp) : url, pvtData: p\n };\n };\n UrlAdaptor.prototype.getRequestQuery = function (options, query, singles, request, request1) {\n var param = 'param';\n var req = request1;\n req[options.from] = query.fromTable;\n if (options.expand) {\n req[options.expand] = 'onExpand' in this && 'onSelect' in singles ?\n DataUtil.callAdaptorFunction(this, 'onExpand', { selects: DataUtil.getValue(singles.onSelect.fieldNames, query), expands: query.expands }, query) : query.expands;\n }\n req[options.select] = 'onSelect' in singles ?\n DataUtil.callAdaptorFunction(this, 'onSelect', DataUtil.getValue(singles.onSelect.fieldNames, query), query) : '';\n req[options.count] = query.isCountRequired ? DataUtil.callAdaptorFunction(this, 'onCount', query.isCountRequired, query) : '';\n req[options.search] = request.searches.length ? DataUtil.callAdaptorFunction(this, 'onSearch', request.searches, query) : '';\n req[options.skip] = 'onSkip' in singles ?\n DataUtil.callAdaptorFunction(this, 'onSkip', DataUtil.getValue(singles.onSkip.nos, query), query) : '';\n req[options.take] = 'onTake' in singles ?\n DataUtil.callAdaptorFunction(this, 'onTake', DataUtil.getValue(singles.onTake.nos, query), query) : '';\n req[options.where] = request.filters.length || request.searches.length ?\n DataUtil.callAdaptorFunction(this, 'onWhere', request.filters, query) : '';\n req[options.sortBy] = request.sorts.length ? DataUtil.callAdaptorFunction(this, 'onSortBy', request.sorts, query) : '';\n req[options.group] = request.groups.length ? DataUtil.callAdaptorFunction(this, 'onGroup', request.groups, query) : '';\n req[options.aggregates] = request.aggregates.length ?\n DataUtil.callAdaptorFunction(this, 'onAggregates', request.aggregates, query) : '';\n req[param] = [];\n };\n /**\n * Convert the object from processQuery to string which can be added query string.\n * @param {Object} req\n * @param {Query} query\n * @param {DataManager} dm\n */\n UrlAdaptor.prototype.convertToQueryString = function (request, query, dm) {\n return '';\n // this needs to be overridden\n };\n /**\n * Return the data from the data manager processing.\n * @param {DataResult} data\n * @param {DataOptions} ds?\n * @param {Query} query?\n * @param {XMLHttpRequest} xhr?\n * @param {Object} request?\n * @param {CrudOptions} changes?\n */\n UrlAdaptor.prototype.processResponse = function (data, ds, query, xhr, request, changes) {\n var requests = request;\n var pvt = requests.pvtData || {};\n var groupDs = data.groupDs;\n if (xhr && xhr.getResponseHeader('Content-Type') &&\n xhr.getResponseHeader('Content-Type').indexOf('xml') !== -1) {\n return (query.isCountRequired ? { result: [], count: 0 } : []);\n }\n var d = JSON.parse(requests.data);\n if (d && d.action === 'batch' && data.addedRecords) {\n changes.addedRecords = data.addedRecords;\n return changes;\n }\n if (data.d) {\n data = data.d;\n }\n var args = {};\n if ('count' in data) {\n args.count = data.count;\n }\n args.result = data.result ? data.result : data;\n this.getAggregateResult(pvt, data, args, groupDs, query);\n return DataUtil.isNull(args.count) ? args.result : { result: args.result, count: args.count, aggregates: args.aggregates };\n };\n /**\n * Add the group query to the adaptor`s option.\n * @param {Object[]} e\n * @returns void\n */\n UrlAdaptor.prototype.onGroup = function (e) {\n this.pvt.groups = e;\n return e;\n };\n /**\n * Add the aggregate query to the adaptor`s option.\n * @param {Aggregates[]} e\n * @returns void\n */\n UrlAdaptor.prototype.onAggregates = function (e) {\n this.pvt.aggregates = e;\n };\n /**\n * Prepare the request body based on the newly added, removed and updated records.\n * The result is used by the batch request.\n * @param {DataManager} dm\n * @param {CrudOptions} changes\n * @param {Object} e\n */\n UrlAdaptor.prototype.batchRequest = function (dm, changes, e, query, original) {\n var url;\n var key;\n return {\n type: 'POST',\n url: dm.dataSource.batchUrl || dm.dataSource.crudUrl || dm.dataSource.removeUrl || dm.dataSource.url,\n contentType: 'application/json; charset=utf-8',\n dataType: 'json',\n data: JSON.stringify({\n changed: changes.changedRecords,\n added: changes.addedRecords,\n deleted: changes.deletedRecords,\n action: 'batch',\n table: e[url],\n key: e[key]\n })\n };\n };\n /**\n * Method will trigger before send the request to server side.\n * Used to set the custom header or modify the request options.\n * @param {DataManager} dm\n * @param {XMLHttpRequest} request\n * @returns void\n */\n UrlAdaptor.prototype.beforeSend = function (dm, request) {\n // need to extend this method\n };\n /**\n * Prepare and returns request body which is used to insert a new record in the table.\n * @param {DataManager} dm\n * @param {Object} data\n * @param {string} tableName\n */\n UrlAdaptor.prototype.insert = function (dm, data, tableName) {\n return {\n url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url,\n data: JSON.stringify({\n value: data,\n table: tableName,\n action: 'insert'\n })\n };\n };\n /**\n * Prepare and return request body which is used to remove record from the table.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {number|string} value\n * @param {string} tableName\n */\n UrlAdaptor.prototype.remove = function (dm, keyField, value, tableName) {\n return {\n type: 'POST',\n url: dm.dataSource.removeUrl || dm.dataSource.crudUrl || dm.dataSource.url,\n data: JSON.stringify({\n key: value,\n keyColumn: keyField,\n table: tableName,\n action: 'remove'\n })\n };\n };\n /**\n * Prepare and return request body which is used to update record.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {Object} value\n * @param {string} tableName\n */\n UrlAdaptor.prototype.update = function (dm, keyField, value, tableName) {\n return {\n type: 'POST',\n url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url,\n data: JSON.stringify({\n value: value,\n action: 'update',\n keyColumn: keyField,\n key: value[keyField],\n table: tableName\n })\n };\n };\n /**\n * To generate the predicate based on the filtered query.\n * @param {Object[]|string[]|number[]} data\n * @param {Query} query\n * @hidden\n */\n UrlAdaptor.prototype.getFiltersFrom = function (data, query) {\n var key = query.fKey;\n var value;\n var prop = key;\n var pKey = query.key;\n var predicats = [];\n if (typeof data[0] !== 'object') {\n prop = null;\n }\n for (var i = 0; i < data.length; i++) {\n if (typeof data[0] === 'object') {\n value = DataUtil.getObject(pKey || prop, data[i]);\n }\n else {\n value = data[i];\n }\n predicats.push(new Predicate(key, 'equal', value));\n }\n return Predicate.or(predicats);\n };\n UrlAdaptor.prototype.getAggregateResult = function (pvt, data, args, groupDs, query) {\n var pData = data;\n if (data && data.result) {\n pData = data.result;\n }\n if (pvt && pvt.aggregates && pvt.aggregates.length) {\n var agg = pvt.aggregates;\n var fn = void 0;\n var aggregateData = pData;\n var res = {};\n if (data.aggregate) {\n aggregateData = data.aggregate;\n }\n for (var i = 0; i < agg.length; i++) {\n fn = DataUtil.aggregates[agg[i].type];\n if (fn) {\n res[agg[i].field + ' - ' + agg[i].type] = fn(aggregateData, agg[i].field);\n }\n }\n args.aggregates = res;\n }\n if (pvt && pvt.groups && pvt.groups.length) {\n var groups = pvt.groups;\n for (var i = 0; i < groups.length; i++) {\n var level = null;\n if (!isNullOrUndefined(groupDs)) {\n groupDs = DataUtil.group(groupDs, groups[i]);\n }\n var groupQuery = Query.filterQueries(query.queries, 'onGroup')[i].e;\n pData = DataUtil.group(pData, groups[i], pvt.aggregates, level, groupDs, groupQuery.comparer);\n }\n args.result = pData;\n }\n return args;\n };\n UrlAdaptor.prototype.getQueryRequest = function (query) {\n var req = { sorts: [], groups: [], filters: [], searches: [], aggregates: [] };\n req.sorts = Query.filterQueries(query.queries, 'onSortBy');\n req.groups = Query.filterQueries(query.queries, 'onGroup');\n req.filters = Query.filterQueries(query.queries, 'onWhere');\n req.searches = Query.filterQueries(query.queries, 'onSearch');\n req.aggregates = Query.filterQueries(query.queries, 'onAggregates');\n return req;\n };\n UrlAdaptor.prototype.addParams = function (options) {\n var req = options.reqParams;\n if (options.params.length) {\n req.params = {};\n }\n for (var _i = 0, _a = options.params; _i < _a.length; _i++) {\n var tmp = _a[_i];\n if (req[tmp.key]) {\n throw new Error('Query() - addParams: Custom Param is conflicting other request arguments');\n }\n req[tmp.key] = tmp.value;\n if (tmp.fn) {\n req[tmp.key] = tmp.fn.call(options.query, tmp.key, options.query, options.dm);\n }\n req.params[tmp.key] = req[tmp.key];\n }\n };\n return UrlAdaptor;\n}(Adaptor));\nexport { UrlAdaptor };\n/**\n * OData Adaptor that is extended from URL Adaptor, is used for consuming data through OData Service.\n * @hidden\n */\nvar ODataAdaptor = /** @class */ (function (_super) {\n __extends(ODataAdaptor, _super);\n function ODataAdaptor(props) {\n var _this = _super.call(this) || this;\n // options replaced the default adaptor options\n _this.options = extend({}, _this.options, {\n requestType: 'get',\n accept: 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5',\n multipartAccept: 'multipart/mixed',\n sortBy: '$orderby',\n select: '$select',\n skip: '$skip',\n take: '$top',\n count: '$inlinecount',\n where: '$filter',\n expand: '$expand',\n batch: '$batch',\n changeSet: '--changeset_',\n batchPre: 'batch_',\n contentId: 'Content-Id: ',\n batchContent: 'Content-Type: multipart/mixed; boundary=',\n changeSetContent: 'Content-Type: application/http\\nContent-Transfer-Encoding: binary ',\n batchChangeSetContentType: 'Content-Type: application/json; charset=utf-8 ',\n updateType: 'PUT'\n });\n _this.getModuleName = getValue('getModulename', _this);\n extend(_this.options, props || {});\n return _this;\n }\n /**\n * Generate request string based on the filter criteria from query.\n * @param {Predicate} pred\n * @param {boolean} requiresCast?\n */\n ODataAdaptor.prototype.onPredicate = function (predicate, query, requiresCast) {\n var returnValue = '';\n var operator;\n var guid;\n var val = predicate.value;\n var type = typeof val;\n var field = predicate.field ? ODataAdaptor.getField(predicate.field) : null;\n if (val instanceof Date) {\n val = 'datetime\\'' + DataUtil.parse.replacer(val) + '\\'';\n }\n if (type === 'string') {\n val = '\\'' + val + '\\'';\n if (requiresCast) {\n field = 'cast(' + field + ', \\'Edm.String\\')';\n }\n if (DataUtil.parse.isGuid(val)) {\n guid = 'guid';\n }\n if (predicate.ignoreCase) {\n if (!guid) {\n field = 'tolower(' + field + ')';\n }\n val = val.toLowerCase();\n }\n }\n operator = DataUtil.odBiOperator[predicate.operator];\n if (operator) {\n returnValue += field;\n returnValue += operator;\n if (guid) {\n returnValue += guid;\n }\n return returnValue + val;\n }\n if (!isNullOrUndefined(this.getModuleName)) {\n if (this.getModuleName() === 'ODataV4Adaptor') {\n operator = DataUtil.odv4UniOperator[predicate.operator];\n }\n }\n else {\n operator = DataUtil.odUniOperator[predicate.operator];\n }\n if (operator === 'substringof') {\n var temp = val;\n val = field;\n field = temp;\n }\n returnValue += operator + '(';\n returnValue += field + ',';\n if (guid) {\n returnValue += guid;\n }\n returnValue += val + ')';\n return returnValue;\n };\n ODataAdaptor.prototype.addParams = function (options) {\n _super.prototype.addParams.call(this, options);\n delete options.reqParams.params;\n };\n /**\n * Generate request string based on the multiple filter criteria from query.\n * @param {Predicate} pred\n * @param {boolean} requiresCast?\n */\n ODataAdaptor.prototype.onComplexPredicate = function (predicate, query, requiresCast) {\n var res = [];\n for (var i = 0; i < predicate.predicates.length; i++) {\n res.push('(' + this.onEachWhere(predicate.predicates[i], query, requiresCast) + ')');\n }\n return res.join(' ' + predicate.condition + ' ');\n };\n /**\n * Generate query string based on the multiple filter criteria from query.\n * @param {Predicate} filter\n * @param {boolean} requiresCast?\n */\n ODataAdaptor.prototype.onEachWhere = function (filter, query, requiresCast) {\n return filter.isComplex ? this.onComplexPredicate(filter, query, requiresCast) : this.onPredicate(filter, query, requiresCast);\n };\n /**\n * Generate query string based on the multiple filter criteria from query.\n * @param {string[]} filters\n */\n ODataAdaptor.prototype.onWhere = function (filters) {\n if (this.pvt.search) {\n filters.push(this.onEachWhere(this.pvt.search, null, true));\n }\n return filters.join(' and ');\n };\n /**\n * Generate query string based on the multiple search criteria from query.\n * @param {{fields:string[]} e\n * @param {string} operator\n * @param {string} key\n * @param {boolean}} ignoreCase\n */\n ODataAdaptor.prototype.onEachSearch = function (e) {\n if (e.fields && e.fields.length === 0) {\n DataUtil.throwError('Query() - Search : oData search requires list of field names to search');\n }\n var filter = this.pvt.search || [];\n for (var i = 0; i < e.fields.length; i++) {\n filter.push(new Predicate(e.fields[i], e.operator, e.key, e.ignoreCase));\n }\n this.pvt.search = filter;\n };\n /**\n * Generate query string based on the search criteria from query.\n * @param {Object} e\n */\n ODataAdaptor.prototype.onSearch = function (e) {\n this.pvt.search = Predicate.or(this.pvt.search);\n return '';\n };\n /**\n * Generate query string based on multiple sort criteria from query.\n * @param {QueryOptions} e\n */\n ODataAdaptor.prototype.onEachSort = function (e) {\n var res = [];\n if (e.name instanceof Array) {\n for (var i = 0; i < e.name.length; i++) {\n res.push(ODataAdaptor.getField(e.name[i]) + (e.direction === 'descending' ? ' desc' : ''));\n }\n }\n else {\n res.push(ODataAdaptor.getField(e.name) + (e.direction === 'descending' ? ' desc' : ''));\n }\n return res.join(',');\n };\n /**\n * Returns sort query string.\n * @param {string[]} e\n */\n ODataAdaptor.prototype.onSortBy = function (e) {\n return e.reverse().join(',');\n };\n /**\n * Adds the group query to the adaptor option.\n * @param {Object[]} e\n * @returns string\n */\n ODataAdaptor.prototype.onGroup = function (e) {\n this.pvt.groups = e;\n return [];\n };\n /**\n * Returns the select query string.\n * @param {string[]} e\n */\n ODataAdaptor.prototype.onSelect = function (e) {\n for (var i = 0; i < e.length; i++) {\n e[i] = ODataAdaptor.getField(e[i]);\n }\n return e.join(',');\n };\n /**\n * Add the aggregate query to the adaptor option.\n * @param {Object[]} e\n * @returns string\n */\n ODataAdaptor.prototype.onAggregates = function (e) {\n this.pvt.aggregates = e;\n return '';\n };\n /**\n * Returns the query string which requests total count from the data source.\n * @param {boolean} e\n * @returns string\n */\n ODataAdaptor.prototype.onCount = function (e) {\n return e === true ? 'allpages' : '';\n };\n /**\n * Method will trigger before send the request to server side.\n * Used to set the custom header or modify the request options.\n * @param {DataManager} dm\n * @param {XMLHttpRequest} request\n * @param {Ajax} settings?\n */\n ODataAdaptor.prototype.beforeSend = function (dm, request, settings) {\n if (DataUtil.endsWith(settings.url, this.options.batch) && settings.type.toLowerCase() === 'post') {\n request.setRequestHeader('Accept', this.options.multipartAccept);\n request.setRequestHeader('DataServiceVersion', '2.0');\n request.overrideMimeType('text/plain; charset=x-user-defined');\n }\n else {\n request.setRequestHeader('Accept', this.options.accept);\n }\n request.setRequestHeader('DataServiceVersion', '2.0');\n request.setRequestHeader('MaxDataServiceVersion', '2.0');\n };\n /**\n * Returns the data from the query processing.\n * @param {DataResult} data\n * @param {DataOptions} ds?\n * @param {Query} query?\n * @param {XMLHttpRequest} xhr?\n * @param {Ajax} request?\n * @param {CrudOptions} changes?\n * @returns aggregateResult\n */\n ODataAdaptor.prototype.processResponse = function (data, ds, query, xhr, request, changes) {\n var pvtData = 'pvtData';\n if (!isNullOrUndefined(data.d)) {\n var dataCopy = ((query && query.isCountRequired) ? data.d.results : data.d);\n var metaData = '__metadata';\n if (!isNullOrUndefined(dataCopy)) {\n for (var i = 0; i < dataCopy.length; i++) {\n if (!isNullOrUndefined(dataCopy[i][metaData])) {\n delete dataCopy[i][metaData];\n }\n }\n }\n }\n var pvt = request && request[pvtData];\n var emptyAndBatch = this.processBatchResponse(data, query, xhr, request, changes);\n if (emptyAndBatch) {\n return emptyAndBatch;\n }\n var versionCheck = xhr && request.getResponseHeader('DataServiceVersion');\n var count = null;\n var version = (versionCheck && parseInt(versionCheck, 10)) || 2;\n if (query && query.isCountRequired) {\n var oDataCount = '__count';\n if (data[oDataCount] || data['odata.count']) {\n count = data[oDataCount] || data['odata.count'];\n }\n if (data.d) {\n data = data.d;\n }\n if (data[oDataCount] || data['odata.count']) {\n count = data[oDataCount] || data['odata.count'];\n }\n }\n if (version === 3 && data.value) {\n data = data.value;\n }\n if (data.d) {\n data = data.d;\n }\n if (version < 3 && data.results) {\n data = data.results;\n }\n var args = {};\n args.count = count;\n args.result = data;\n this.getAggregateResult(pvt, data, args, null, query);\n return DataUtil.isNull(count) ? args.result : { result: args.result, count: args.count, aggregates: args.aggregates };\n };\n /**\n * Converts the request object to query string.\n * @param {Object} req\n * @param {Query} query\n * @param {DataManager} dm\n * @returns tableName\n */\n ODataAdaptor.prototype.convertToQueryString = function (request, query, dm) {\n var res = [];\n var table = 'table';\n var tableName = request[table] || '';\n var format = '$format';\n delete request[table];\n if (dm.dataSource.requiresFormat) {\n request[format] = 'json';\n }\n var keys = Object.keys(request);\n for (var _i = 0, keys_4 = keys; _i < keys_4.length; _i++) {\n var prop = keys_4[_i];\n res.push(prop + '=' + request[prop]);\n }\n res = res.join('&');\n if (dm.dataSource.url && dm.dataSource.url.indexOf('?') !== -1 && !tableName) {\n return res;\n }\n return res.length ? tableName + '?' + res : tableName || '';\n };\n ODataAdaptor.prototype.localTimeReplacer = function (key, convertObj) {\n for (var _i = 0, _a = !isNullOrUndefined(convertObj) ? Object.keys(convertObj) : []; _i < _a.length; _i++) {\n var prop = _a[_i];\n if ((convertObj[prop] instanceof Date)) {\n convertObj[prop] = DataUtil.dateParse.toLocalTime(convertObj[prop]);\n }\n }\n return convertObj;\n };\n /**\n * Prepare and returns request body which is used to insert a new record in the table.\n * @param {DataManager} dm\n * @param {Object} data\n * @param {string} tableName?\n */\n ODataAdaptor.prototype.insert = function (dm, data, tableName) {\n return {\n url: dm.dataSource.url.replace(/\\/*$/, tableName ? '/' + tableName : ''),\n data: JSON.stringify(data, this.options.localTime ? this.localTimeReplacer : null)\n };\n };\n /**\n * Prepare and return request body which is used to remove record from the table.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {number} value\n * @param {string} tableName?\n */\n ODataAdaptor.prototype.remove = function (dm, keyField, value, tableName) {\n return {\n type: 'DELETE',\n url: dm.dataSource.url.replace(/\\/*$/, tableName ? '/' + tableName : '') + '(' + value + ')'\n };\n };\n /**\n * Updates existing record and saves the changes to the table.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {Object} value\n * @param {string} tableName?\n * @returns this\n */\n ODataAdaptor.prototype.update = function (dm, keyField, value, tableName, query, original) {\n if (this.options.updateType === 'PATCH' && !isNullOrUndefined(original)) {\n value = this.compareAndRemove(value, original, keyField);\n }\n return {\n type: this.options.updateType,\n url: dm.dataSource.url.replace(/\\/*$/, tableName ? '/' + tableName : '') + '(' + value[keyField] + ')',\n data: JSON.stringify(value, this.options.localTime ? this.localTimeReplacer : null),\n accept: this.options.accept\n };\n };\n /**\n * Prepare the request body based on the newly added, removed and updated records.\n * The result is used by the batch request.\n * @param {DataManager} dm\n * @param {CrudOptions} changes\n * @param {RemoteArgs} e\n * @returns {Object}\n */\n ODataAdaptor.prototype.batchRequest = function (dm, changes, e, query, original) {\n var initialGuid = e.guid = DataUtil.getGuid(this.options.batchPre);\n var url = dm.dataSource.url.replace(/\\/*$/, '/' + this.options.batch);\n var args = {\n url: e.url,\n key: e.key,\n cid: 1,\n cSet: DataUtil.getGuid(this.options.changeSet)\n };\n var req = '--' + initialGuid + '\\n';\n req += 'Content-Type: multipart/mixed; boundary=' + args.cSet.replace('--', '') + '\\n';\n this.pvt.changeSet = 0;\n req += this.generateInsertRequest(changes.addedRecords, args);\n req += this.generateUpdateRequest(changes.changedRecords, args, original ? original.changedRecords : []);\n req += this.generateDeleteRequest(changes.deletedRecords, args);\n req += args.cSet + '--\\n';\n req += '--' + initialGuid + '--';\n return {\n type: 'POST',\n url: url,\n dataType: 'json',\n contentType: 'multipart/mixed; charset=UTF-8;boundary=' + initialGuid,\n data: req\n };\n };\n /**\n * Generate the string content from the removed records.\n * The result will be send during batch update.\n * @param {Object[]} arr\n * @param {RemoteArgs} e\n * @returns this\n */\n ODataAdaptor.prototype.generateDeleteRequest = function (arr, e) {\n if (!arr) {\n return '';\n }\n var req = '';\n var stat = {\n 'method': 'DELETE ',\n 'url': function (data, i, key) { return '(' + data[i][key] + ')'; },\n 'data': function (data, i) { return ''; }\n };\n req = this.generateBodyContent(arr, e, stat);\n return req + '\\n';\n };\n /**\n * Generate the string content from the inserted records.\n * The result will be send during batch update.\n * @param {Object[]} arr\n * @param {RemoteArgs} e\n */\n ODataAdaptor.prototype.generateInsertRequest = function (arr, e) {\n if (!arr) {\n return '';\n }\n var req = '';\n var stat = {\n 'method': 'POST ',\n 'url': function (data, i, key) { return ''; },\n 'data': function (data, i) { return JSON.stringify(data[i]) + '\\n\\n'; }\n };\n req = this.generateBodyContent(arr, e, stat);\n return req;\n };\n /**\n * Generate the string content from the updated records.\n * The result will be send during batch update.\n * @param {Object[]} arr\n * @param {RemoteArgs} e\n */\n ODataAdaptor.prototype.generateUpdateRequest = function (arr, e, org) {\n var _this = this;\n if (!arr) {\n return '';\n }\n var req = '';\n arr.forEach(function (change) { return change = _this.compareAndRemove(change, org.filter(function (o) { return DataUtil.getObject(e.key, o) === DataUtil.getObject(e.key, change); })[0], e.key); });\n var stat = {\n 'method': this.options.updateType + ' ',\n 'url': function (data, i, key) { return '(' + data[i][key] + ')'; },\n 'data': function (data, i) { return JSON.stringify(data[i]) + '\\n\\n'; }\n };\n req = this.generateBodyContent(arr, e, stat);\n return req;\n };\n ODataAdaptor.getField = function (prop) {\n return prop.replace(/\\./g, '/');\n };\n ODataAdaptor.prototype.generateBodyContent = function (arr, e, stat) {\n var req = '';\n for (var i = 0; i < arr.length; i++) {\n req += '\\n' + e.cSet + '\\n';\n req += this.options.changeSetContent + '\\n\\n';\n req += stat.method;\n req += e.url + stat.url(arr, i, e.key) + ' HTTP/1.1\\n';\n req += 'Accept: ' + this.options.accept + '\\n';\n req += 'Content-Id: ' + this.pvt.changeSet++ + '\\n';\n req += this.options.batchChangeSetContentType + '\\n';\n if (!isNullOrUndefined(arr[i]['@odata.etag'])) {\n req += 'If-Match: ' + arr[i]['@odata.etag'] + '\\n\\n';\n delete arr[i]['@odata.etag'];\n }\n else {\n req += '\\n';\n }\n req += stat.data(arr, i);\n }\n return req;\n };\n ODataAdaptor.prototype.processBatchResponse = function (data, query, xhr, request, changes) {\n if (xhr && xhr.getResponseHeader('Content-Type') && xhr.getResponseHeader('Content-Type').indexOf('xml') !== -1) {\n return (query.isCountRequired ? { result: [], count: 0 } : []);\n }\n if (request && this.options.batch && DataUtil.endsWith(request.url, this.options.batch) && request.type.toLowerCase() === 'post') {\n var guid = xhr.getResponseHeader('Content-Type');\n var cIdx = void 0;\n var jsonObj = void 0;\n var d = data + '';\n guid = guid.substring(guid.indexOf('=batchresponse') + 1);\n d = d.split(guid);\n if (d.length < 2) {\n return {};\n }\n d = d[1];\n var exVal = /(?:\\bContent-Type.+boundary=)(changesetresponse.+)/i.exec(d);\n if (exVal) {\n d.replace(exVal[0], '');\n }\n var changeGuid = exVal ? exVal[1] : '';\n d = d.split(changeGuid);\n for (var i = d.length; i > -1; i--) {\n if (!/\\bContent-ID:/i.test(d[i]) || !/\\bHTTP.+201/.test(d[i])) {\n continue;\n }\n cIdx = parseInt(/\\bContent-ID: (\\d+)/i.exec(d[i])[1], 10);\n if (changes.addedRecords[cIdx]) {\n jsonObj = DataUtil.parse.parseJson(/^\\{.+\\}/m.exec(d[i])[0]);\n extend({}, changes.addedRecords[cIdx], this.processResponse(jsonObj));\n }\n }\n return changes;\n }\n return null;\n };\n ODataAdaptor.prototype.compareAndRemove = function (data, original, key) {\n var _this = this;\n if (isNullOrUndefined(original)) {\n return data;\n }\n Object.keys(data).forEach(function (prop) {\n if (prop !== key && prop !== '@odata.etag') {\n if (DataUtil.isPlainObject(data[prop])) {\n _this.compareAndRemove(data[prop], original[prop]);\n if (Object.keys(data[prop]).length === 0) {\n delete data[prop];\n }\n }\n else if (data[prop] === original[prop]) {\n delete data[prop];\n }\n else if (data[prop] && original[prop] && data[prop].valueOf() === original[prop].valueOf()) {\n delete data[prop];\n }\n }\n });\n return data;\n };\n return ODataAdaptor;\n}(UrlAdaptor));\nexport { ODataAdaptor };\n/**\n * The OData v4 is an improved version of OData protocols.\n * The DataManager uses the ODataV4Adaptor to consume OData v4 services.\n * @hidden\n */\nvar ODataV4Adaptor = /** @class */ (function (_super) {\n __extends(ODataV4Adaptor, _super);\n function ODataV4Adaptor(props) {\n var _this = _super.call(this, props) || this;\n // options replaced the default adaptor options\n _this.options = extend({}, _this.options, {\n requestType: 'get',\n accept: 'application/json, text/javascript, */*; q=0.01',\n multipartAccept: 'multipart/mixed',\n sortBy: '$orderby',\n select: '$select',\n skip: '$skip',\n take: '$top',\n count: '$count',\n search: '$search',\n where: '$filter',\n expand: '$expand',\n batch: '$batch',\n changeSet: '--changeset_',\n batchPre: 'batch_',\n contentId: 'Content-Id: ',\n batchContent: 'Content-Type: multipart/mixed; boundary=',\n changeSetContent: 'Content-Type: application/http\\nContent-Transfer-Encoding: binary ',\n batchChangeSetContentType: 'Content-Type: application/json; charset=utf-8 ',\n updateType: 'PATCH',\n localTime: false\n });\n getValue('getModulename', _this.getModulename());\n extend(_this.options, props || {});\n return _this;\n }\n /**\n * @hidden\n */\n ODataV4Adaptor.prototype.getModulename = function () {\n return 'ODataV4Adaptor';\n };\n ;\n /**\n * Returns the query string which requests total count from the data source.\n * @param {boolean} e\n * @returns string\n */\n ODataV4Adaptor.prototype.onCount = function (e) {\n return e === true ? 'true' : '';\n };\n /**\n * Generate request string based on the filter criteria from query.\n * @param {Predicate} pred\n * @param {boolean} requiresCast?\n */\n ODataV4Adaptor.prototype.onPredicate = function (predicate, query, requiresCast) {\n var returnValue = '';\n var val = predicate.value;\n var isDate = val instanceof Date;\n returnValue = _super.prototype.onPredicate.call(this, predicate, query, requiresCast);\n if (isDate) {\n returnValue = returnValue.replace(/datetime'(.*)'$/, '$1');\n }\n return returnValue;\n };\n /**\n * Generate query string based on the multiple search criteria from query.\n * @param {{fields:string[]} e\n * @param {string} operator\n * @param {string} key\n * @param {boolean}} ignoreCase\n */\n ODataV4Adaptor.prototype.onEachSearch = function (e) {\n var search = this.pvt.searches || [];\n search.push(e.key);\n this.pvt.searches = search;\n };\n /**\n * Generate query string based on the search criteria from query.\n * @param {Object} e\n */\n ODataV4Adaptor.prototype.onSearch = function (e) {\n return this.pvt.searches.join(' OR ');\n };\n /**\n * Returns the expand query string.\n * @param {string} e\n */\n ODataV4Adaptor.prototype.onExpand = function (e) {\n var _this = this;\n var selected = {};\n var expanded = {};\n var expands = e.expands.slice();\n var exArr = [];\n var selects = e.selects.filter(function (item) { return item.indexOf('.') > -1; });\n selects.forEach(function (select) {\n var splits = select.split('.');\n if (!(splits[0] in selected)) {\n selected[splits[0]] = [];\n }\n selected[splits[0]].push(splits[1]);\n });\n //Auto expand from select query\n Object.keys(selected).forEach(function (expand) {\n if ((expands.indexOf(expand) === -1)) {\n expands.push(expand);\n }\n });\n expands.forEach(function (expand) {\n expanded[expand] = expand in selected ? expand + \"(\" + _this.options.select + \"=\" + selected[expand].join(',') + \")\" : expand;\n });\n Object.keys(expanded).forEach(function (ex) { return exArr.push(expanded[ex]); });\n return exArr.join(',');\n };\n /**\n * Returns the select query string.\n * @param {string[]} e\n */\n ODataV4Adaptor.prototype.onSelect = function (e) {\n return _super.prototype.onSelect.call(this, e.filter(function (item) { return item.indexOf('.') === -1; }));\n };\n /**\n * Method will trigger before send the request to server side.\n * Used to set the custom header or modify the request options.\n * @param {DataManager} dm\n * @param {XMLHttpRequest} request\n * @param {Ajax} settings\n * @returns void\n */\n ODataV4Adaptor.prototype.beforeSend = function (dm, request, settings) {\n if (settings.type === 'POST' || settings.type === 'PUT' || settings.type === 'PATCH') {\n request.setRequestHeader('Prefer', 'return=representation');\n }\n request.setRequestHeader('Accept', this.options.accept);\n };\n /**\n * Returns the data from the query processing.\n * @param {DataResult} data\n * @param {DataOptions} ds?\n * @param {Query} query?\n * @param {XMLHttpRequest} xhr?\n * @param {Ajax} request?\n * @param {CrudOptions} changes?\n * @returns aggregateResult\n */\n ODataV4Adaptor.prototype.processResponse = function (data, ds, query, xhr, request, changes) {\n var pvtData = 'pvtData';\n var pvt = request && request[pvtData];\n var emptyAndBatch = _super.prototype.processBatchResponse.call(this, data, query, xhr, request, changes);\n if (emptyAndBatch) {\n return emptyAndBatch;\n }\n var count = null;\n var dataCount = '@odata.count';\n if (query && query.isCountRequired) {\n if (dataCount in data) {\n count = data[dataCount];\n }\n }\n data = !isNullOrUndefined(data.value) ? data.value : data;\n var args = {};\n args.count = count;\n args.result = data;\n this.getAggregateResult(pvt, data, args, null, query);\n return DataUtil.isNull(count) ? args.result : { result: args.result, count: count, aggregates: args.aggregates };\n };\n return ODataV4Adaptor;\n}(ODataAdaptor));\nexport { ODataV4Adaptor };\n/**\n * The Web API is a programmatic interface to define the request and response messages system that is mostly exposed in JSON or XML.\n * The DataManager uses the WebApiAdaptor to consume Web API.\n * Since this adaptor is targeted to interact with Web API created using OData endpoint, it is extended from ODataAdaptor\n * @hidden\n */\nvar WebApiAdaptor = /** @class */ (function (_super) {\n __extends(WebApiAdaptor, _super);\n function WebApiAdaptor() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Prepare and returns request body which is used to insert a new record in the table.\n * @param {DataManager} dm\n * @param {Object} data\n * @param {string} tableName?\n */\n WebApiAdaptor.prototype.insert = function (dm, data, tableName) {\n return {\n type: 'POST',\n url: dm.dataSource.url,\n data: JSON.stringify(data)\n };\n };\n /**\n * Prepare and return request body which is used to remove record from the table.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {number} value\n * @param {string} tableName?\n */\n WebApiAdaptor.prototype.remove = function (dm, keyField, value, tableName) {\n return {\n type: 'DELETE',\n url: dm.dataSource.url + '/' + value,\n data: JSON.stringify(value)\n };\n };\n /**\n * Prepare and return request body which is used to update record.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {Object} value\n * @param {string} tableName?\n */\n WebApiAdaptor.prototype.update = function (dm, keyField, value, tableName) {\n return {\n type: 'PUT',\n url: dm.dataSource.url,\n data: JSON.stringify(value)\n };\n };\n /**\n * Method will trigger before send the request to server side.\n * Used to set the custom header or modify the request options.\n * @param {DataManager} dm\n * @param {XMLHttpRequest} request\n * @param {Ajax} settings\n * @returns void\n */\n WebApiAdaptor.prototype.beforeSend = function (dm, request, settings) {\n request.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');\n };\n /**\n * Returns the data from the query processing.\n * @param {DataResult} data\n * @param {DataOptions} ds?\n * @param {Query} query?\n * @param {XMLHttpRequest} xhr?\n * @param {Ajax} request?\n * @param {CrudOptions} changes?\n * @returns aggregateResult\n */\n WebApiAdaptor.prototype.processResponse = function (data, ds, query, xhr, request, changes) {\n var pvtData = 'pvtData';\n var pvt = request && request[pvtData];\n var count = null;\n var args = {};\n if (request && request.type.toLowerCase() !== 'post') {\n var versionCheck = xhr && request.getResponseHeader('DataServiceVersion');\n var version = (versionCheck && parseInt(versionCheck, 10)) || 2;\n if (query && query.isCountRequired) {\n if (!DataUtil.isNull(data.Count)) {\n count = data.Count;\n }\n }\n if (version < 3 && data.Items) {\n data = data.Items;\n }\n args.count = count;\n args.result = data;\n this.getAggregateResult(pvt, data, args, null, query);\n }\n args.result = args.result || data;\n return DataUtil.isNull(count) ? args.result : { result: args.result, count: args.count, aggregates: args.aggregates };\n };\n return WebApiAdaptor;\n}(ODataAdaptor));\nexport { WebApiAdaptor };\n/**\n * WebMethodAdaptor can be used by DataManager to interact with web method.\n * @hidden\n */\nvar WebMethodAdaptor = /** @class */ (function (_super) {\n __extends(WebMethodAdaptor, _super);\n function WebMethodAdaptor() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Prepare the request body based on the query.\n * The query information can be accessed at the WebMethod using variable named `value`.\n * @param {DataManager} dm\n * @param {Query} query\n * @param {Object[]} hierarchyFilters?\n * @returns application\n */\n WebMethodAdaptor.prototype.processQuery = function (dm, query, hierarchyFilters) {\n var obj = new UrlAdaptor().processQuery(dm, query, hierarchyFilters);\n var getData = 'data';\n var data = DataUtil.parse.parseJson(obj[getData]);\n var result = {};\n var value = 'value';\n if (data.param) {\n for (var i = 0; i < data.param.length; i++) {\n var param = data.param[i];\n var key = Object.keys(param)[0];\n result[key] = param[key];\n }\n }\n result[value] = data;\n var pvtData = 'pvtData';\n var url = 'url';\n return {\n data: JSON.stringify(result),\n url: obj[url],\n pvtData: obj[pvtData],\n type: 'POST',\n contentType: 'application/json; charset=utf-8'\n };\n };\n return WebMethodAdaptor;\n}(UrlAdaptor));\nexport { WebMethodAdaptor };\n/**\n * RemoteSaveAdaptor, extended from JsonAdaptor and it is used for binding local data and performs all DataManager queries in client-side.\n * It interacts with server-side only for CRUD operations.\n * @hidden\n */\nvar RemoteSaveAdaptor = /** @class */ (function (_super) {\n __extends(RemoteSaveAdaptor, _super);\n /**\n * @hidden\n */\n function RemoteSaveAdaptor() {\n var _this = _super.call(this) || this;\n setValue('beforeSend', UrlAdaptor.prototype.beforeSend, _this);\n return _this;\n }\n RemoteSaveAdaptor.prototype.insert = function (dm, data, tableName) {\n this.updateType = 'add';\n return {\n url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url,\n data: JSON.stringify({\n value: data,\n table: tableName,\n action: 'insert'\n })\n };\n };\n RemoteSaveAdaptor.prototype.remove = function (dm, keyField, value, tableName) {\n _super.prototype.remove.call(this, dm, keyField, value);\n return {\n type: 'POST',\n url: dm.dataSource.removeUrl || dm.dataSource.crudUrl || dm.dataSource.url,\n data: JSON.stringify({\n key: value,\n keyColumn: keyField,\n table: tableName,\n action: 'remove'\n })\n };\n };\n RemoteSaveAdaptor.prototype.update = function (dm, keyField, value, tableName) {\n this.updateType = 'update';\n this.updateKey = keyField;\n return {\n type: 'POST',\n url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url,\n data: JSON.stringify({\n value: value,\n action: 'update',\n keyColumn: keyField,\n key: value[keyField],\n table: tableName\n })\n };\n };\n RemoteSaveAdaptor.prototype.processResponse = function (data, ds, query, xhr, request, changes, e) {\n var i;\n if (this.updateType === 'add') {\n _super.prototype.insert.call(this, ds, data, null, null, 0);\n }\n if (this.updateType === 'update') {\n _super.prototype.update.call(this, ds, this.updateKey, data);\n }\n if (data.added) {\n for (i = 0; i < data.added.length; i++) {\n _super.prototype.insert.call(this, ds, data.added[i]);\n }\n }\n if (data.changed) {\n for (i = 0; i < data.changed.length; i++) {\n _super.prototype.update.call(this, ds, e.key, data.changed[i]);\n }\n }\n if (data.deleted) {\n for (i = 0; i < data.deleted.length; i++) {\n _super.prototype.remove.call(this, ds, e.key, data.deleted[i]);\n }\n }\n return data;\n };\n /**\n * Prepare the request body based on the newly added, removed and updated records.\n * Also perform the changes in the locally cached data to sync with the remote data.\n * The result is used by the batch request.\n * @param {DataManager} dm\n * @param {CrudOptions} changes\n * @param {RemoteArgs} e\n */\n RemoteSaveAdaptor.prototype.batchRequest = function (dm, changes, e) {\n return {\n type: 'POST',\n url: dm.dataSource.batchUrl || dm.dataSource.crudUrl || dm.dataSource.url,\n contentType: 'application/json; charset=utf-8',\n dataType: 'json',\n data: JSON.stringify({\n changed: changes.changedRecords,\n added: changes.addedRecords,\n deleted: changes.deletedRecords,\n action: 'batch',\n table: e.url,\n key: e.key\n })\n };\n };\n return RemoteSaveAdaptor;\n}(JsonAdaptor));\nexport { RemoteSaveAdaptor };\n/**\n * Cache Adaptor is used to cache the data of the visited pages. It prevents new requests for the previously visited pages.\n * You can configure cache page size and duration of caching by using cachingPageSize and timeTillExpiration properties of the DataManager\n * @hidden\n */\nvar CacheAdaptor = /** @class */ (function (_super) {\n __extends(CacheAdaptor, _super);\n /**\n * Constructor for CacheAdaptor class.\n * @param {CacheAdaptor} adaptor?\n * @param {number} timeStamp?\n * @param {number} pageSize?\n * @hidden\n */\n function CacheAdaptor(adaptor, timeStamp, pageSize) {\n var _this = _super.call(this) || this;\n _this.isCrudAction = false;\n _this.isInsertAction = false;\n if (!isNullOrUndefined(adaptor)) {\n _this.cacheAdaptor = adaptor;\n }\n _this.pageSize = pageSize;\n _this.guidId = DataUtil.getGuid('cacheAdaptor');\n var obj = { keys: [], results: [] };\n window.localStorage.setItem(_this.guidId, JSON.stringify(obj));\n var guid = _this.guidId;\n if (!isNullOrUndefined(timeStamp)) {\n setInterval(function () {\n var data;\n data = DataUtil.parse.parseJson(window.localStorage.getItem(guid));\n var forDel = [];\n for (var i = 0; i < data.results.length; i++) {\n var currentTime = +new Date();\n var requestTime = +new Date(data.results[i].timeStamp);\n data.results[i].timeStamp = currentTime - requestTime;\n if (currentTime - requestTime > timeStamp) {\n forDel.push(i);\n }\n }\n for (var i = 0; i < forDel.length; i++) {\n data.results.splice(forDel[i], 1);\n data.keys.splice(forDel[i], 1);\n }\n window.localStorage.removeItem(guid);\n window.localStorage.setItem(guid, JSON.stringify(data));\n }, timeStamp);\n }\n return _this;\n }\n /**\n * It will generate the key based on the URL when we send a request to server.\n * @param {string} url\n * @param {Query} query?\n * @hidden\n */\n CacheAdaptor.prototype.generateKey = function (url, query) {\n var queries = this.getQueryRequest(query);\n var singles = Query.filterQueryLists(query.queries, ['onSelect', 'onPage', 'onSkip', 'onTake', 'onRange']);\n var key = url;\n var page = 'onPage';\n if (page in singles) {\n key += singles[page].pageIndex;\n }\n queries.sorts.forEach(function (obj) {\n key += obj.e.direction + obj.e.fieldName;\n });\n queries.groups.forEach(function (obj) {\n key += obj.e.fieldName;\n });\n queries.searches.forEach(function (obj) {\n key += obj.e.searchKey;\n });\n for (var filter = 0; filter < queries.filters.length; filter++) {\n var currentFilter = queries.filters[filter];\n if (currentFilter.e.isComplex) {\n var newQuery = query.clone();\n newQuery.queries = [];\n for (var i = 0; i < currentFilter.e.predicates.length; i++) {\n newQuery.queries.push({ fn: 'onWhere', e: currentFilter.e.predicates[i], filter: query.queries.filter });\n }\n key += currentFilter.e.condition + this.generateKey(url, newQuery);\n }\n else {\n key += currentFilter.e.field + currentFilter.e.operator + currentFilter.e.value;\n }\n }\n return key;\n };\n /**\n * Process the query to generate request body.\n * If the data is already cached, it will return the cached data.\n * @param {DataManager} dm\n * @param {Query} query?\n * @param {Object[]} hierarchyFilters?\n */\n CacheAdaptor.prototype.processQuery = function (dm, query, hierarchyFilters) {\n var key = this.generateKey(dm.dataSource.url, query);\n var cachedItems;\n cachedItems = DataUtil.parse.parseJson(window.localStorage.getItem(this.guidId));\n var data = cachedItems ? cachedItems.results[cachedItems.keys.indexOf(key)] : null;\n if (data != null && !this.isCrudAction && !this.isInsertAction) {\n return data;\n }\n this.isCrudAction = null;\n this.isInsertAction = null;\n return this.cacheAdaptor.processQuery.apply(this.cacheAdaptor, [].slice.call(arguments, 0));\n };\n /**\n * Returns the data from the query processing.\n * It will also cache the data for later usage.\n * @param {DataResult} data\n * @param {DataManager} ds?\n * @param {Query} query?\n * @param {XMLHttpRequest} xhr?\n * @param {Ajax} request?\n * @param {CrudOptions} changes?\n */\n CacheAdaptor.prototype.processResponse = function (data, ds, query, xhr, request, changes) {\n if (this.isInsertAction || (request && this.cacheAdaptor.options.batch &&\n DataUtil.endsWith(request.url, this.cacheAdaptor.options.batch) && request.type.toLowerCase() === 'post')) {\n return this.cacheAdaptor.processResponse(data, ds, query, xhr, request, changes);\n }\n data = this.cacheAdaptor.processResponse.apply(this.cacheAdaptor, [].slice.call(arguments, 0));\n var key = query ? this.generateKey(ds.dataSource.url, query) : ds.dataSource.url;\n var obj = {};\n obj = DataUtil.parse.parseJson(window.localStorage.getItem(this.guidId));\n var index = obj.keys.indexOf(key);\n if (index !== -1) {\n obj.results.splice(index, 1);\n obj.keys.splice(index, 1);\n }\n obj.results[obj.keys.push(key) - 1] = { keys: key, result: data.result, timeStamp: new Date(), count: data.count };\n while (obj.results.length > this.pageSize) {\n obj.results.splice(0, 1);\n obj.keys.splice(0, 1);\n }\n window.localStorage.setItem(this.guidId, JSON.stringify(obj));\n return data;\n };\n /**\n * Method will trigger before send the request to server side. Used to set the custom header or modify the request options.\n * @param {DataManager} dm\n * @param {XMLHttpRequest} request\n * @param {Ajax} settings?\n */\n CacheAdaptor.prototype.beforeSend = function (dm, request, settings) {\n if (DataUtil.endsWith(settings.url, this.cacheAdaptor.options.batch) && settings.type.toLowerCase() === 'post') {\n request.setRequestHeader('Accept', this.cacheAdaptor.options.multipartAccept);\n }\n if (!dm.dataSource.crossDomain) {\n request.setRequestHeader('Accept', this.cacheAdaptor.options.accept);\n }\n };\n /**\n * Updates existing record and saves the changes to the table.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {Object} value\n * @param {string} tableName\n */\n CacheAdaptor.prototype.update = function (dm, keyField, value, tableName) {\n this.isCrudAction = true;\n return this.cacheAdaptor.update(dm, keyField, value, tableName);\n };\n /**\n * Prepare and returns request body which is used to insert a new record in the table.\n * @param {DataManager} dm\n * @param {Object} data\n * @param {string} tableName?\n */\n CacheAdaptor.prototype.insert = function (dm, data, tableName) {\n this.isInsertAction = true;\n return this.cacheAdaptor.insert(dm, data, tableName);\n };\n /**\n * Prepare and return request body which is used to remove record from the table.\n * @param {DataManager} dm\n * @param {string} keyField\n * @param {Object} value\n * @param {string} tableName?\n */\n CacheAdaptor.prototype.remove = function (dm, keyField, value, tableName) {\n this.isCrudAction = true;\n return this.cacheAdaptor.remove(dm, keyField, value, tableName);\n };\n /**\n * Prepare the request body based on the newly added, removed and updated records.\n * The result is used by the batch request.\n * @param {DataManager} dm\n * @param {CrudOptions} changes\n * @param {RemoteArgs} e\n */\n CacheAdaptor.prototype.batchRequest = function (dm, changes, e) {\n return this.cacheAdaptor.batchRequest(dm, changes, e);\n };\n return CacheAdaptor;\n}(UrlAdaptor));\nexport { CacheAdaptor };\n","import { Ajax } from '@syncfusion/ej2-base';\nimport { extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { DataUtil } from './util';\nimport { Query } from './query';\nimport { ODataAdaptor, JsonAdaptor, CacheAdaptor, RemoteSaveAdaptor } from './adaptors';\n/**\n * DataManager is used to manage and manipulate relational data.\n */\nvar DataManager = /** @class */ (function () {\n /**\n * Constructor for DataManager class\n * @param {DataOptions|JSON[]} dataSource?\n * @param {Query} query?\n * @param {AdaptorOptions|string} adaptor?\n * @hidden\n */\n function DataManager(dataSource, query, adaptor) {\n var _this = this;\n /** @hidden */\n this.dateParse = true;\n this.requests = [];\n if (!dataSource && !this.dataSource) {\n dataSource = [];\n }\n adaptor = adaptor || dataSource.adaptor;\n var data;\n if (dataSource instanceof Array) {\n data = {\n json: dataSource,\n offline: true\n };\n }\n else if (typeof dataSource === 'object') {\n if (!dataSource.json) {\n dataSource.json = [];\n }\n data = {\n url: dataSource.url,\n insertUrl: dataSource.insertUrl,\n removeUrl: dataSource.removeUrl,\n updateUrl: dataSource.updateUrl,\n crudUrl: dataSource.crudUrl,\n batchUrl: dataSource.batchUrl,\n json: dataSource.json,\n headers: dataSource.headers,\n accept: dataSource.accept,\n data: dataSource.data,\n timeTillExpiration: dataSource.timeTillExpiration,\n cachingPageSize: dataSource.cachingPageSize,\n enableCaching: dataSource.enableCaching,\n requestType: dataSource.requestType,\n key: dataSource.key,\n crossDomain: dataSource.crossDomain,\n jsonp: dataSource.jsonp,\n dataType: dataSource.dataType,\n offline: dataSource.offline !== undefined ? dataSource.offline\n : dataSource.adaptor instanceof RemoteSaveAdaptor ? false : dataSource.url ? false : true,\n requiresFormat: dataSource.requiresFormat\n };\n }\n else {\n DataUtil.throwError('DataManager: Invalid arguments');\n }\n if (data.requiresFormat === undefined && !DataUtil.isCors()) {\n data.requiresFormat = isNullOrUndefined(data.crossDomain) ? true : data.crossDomain;\n }\n if (data.dataType === undefined) {\n data.dataType = 'json';\n }\n this.dataSource = data;\n this.defaultQuery = query;\n if (data.url && data.offline && !data.json.length) {\n this.isDataAvailable = false;\n this.adaptor = adaptor || new ODataAdaptor();\n this.dataSource.offline = false;\n this.ready = this.executeQuery(query || new Query());\n this.ready.then(function (e) {\n _this.dataSource.offline = true;\n _this.isDataAvailable = true;\n data.json = e.result;\n _this.adaptor = new JsonAdaptor();\n });\n }\n else {\n this.adaptor = data.offline ? new JsonAdaptor() : new ODataAdaptor();\n }\n if (!data.jsonp && this.adaptor instanceof ODataAdaptor) {\n data.jsonp = 'callback';\n }\n this.adaptor = adaptor || this.adaptor;\n if (data.enableCaching) {\n this.adaptor = new CacheAdaptor(this.adaptor, data.timeTillExpiration, data.cachingPageSize);\n }\n return this;\n }\n /**\n * Overrides DataManager's default query with given query.\n * @param {Query} query - Defines the new default query.\n */\n DataManager.prototype.setDefaultQuery = function (query) {\n this.defaultQuery = query;\n return this;\n };\n /**\n * Executes the given query with local data source.\n * @param {Query} query - Defines the query to retrieve data.\n */\n DataManager.prototype.executeLocal = function (query) {\n if (!this.defaultQuery && !(query instanceof Query)) {\n DataUtil.throwError('DataManager - executeLocal() : A query is required to execute');\n }\n if (!this.dataSource.json) {\n DataUtil.throwError('DataManager - executeLocal() : Json data is required to execute');\n }\n query = query || this.defaultQuery;\n var result = this.adaptor.processQuery(this, query);\n if (query.subQuery) {\n var from = query.subQuery.fromTable;\n var lookup = query.subQuery.lookups;\n var res = query.isCountRequired ? result.result :\n result;\n if (lookup && lookup instanceof Array) {\n DataUtil.buildHierarchy(query.subQuery.fKey, from, res, lookup, query.subQuery.key);\n }\n for (var j = 0; j < res.length; j++) {\n if (res[j][from] instanceof Array) {\n res[j] = extend({}, {}, res[j]);\n res[j][from] = this.adaptor.processResponse(query.subQuery.using(new DataManager(res[j][from].slice(0))).executeLocal(), this, query);\n }\n }\n }\n return this.adaptor.processResponse(result, this, query);\n };\n /**\n * Executes the given query with either local or remote data source.\n * It will be executed as asynchronously and returns Promise object which will be resolved or rejected after action completed.\n * @param {Query|Function} query - Defines the query to retrieve data.\n * @param {Function} done - Defines the callback function and triggers when the Promise is resolved.\n * @param {Function} fail - Defines the callback function and triggers when the Promise is rejected.\n * @param {Function} always - Defines the callback function and triggers when the Promise is resolved or rejected.\n */\n DataManager.prototype.executeQuery = function (query, done, fail, always) {\n var _this = this;\n if (typeof query === 'function') {\n always = fail;\n fail = done;\n done = query;\n query = null;\n }\n if (!query) {\n query = this.defaultQuery;\n }\n if (!(query instanceof Query)) {\n DataUtil.throwError('DataManager - executeQuery() : A query is required to execute');\n }\n var deffered = new Deferred();\n var args = { query: query };\n if (!this.dataSource.offline && (this.dataSource.url !== undefined && this.dataSource.url !== '')) {\n var result = this.adaptor.processQuery(this, query);\n this.makeRequest(result, deffered, args, query);\n }\n else {\n DataManager.nextTick(function () {\n var res = _this.executeLocal(query);\n args = DataManager.getDeferedArgs(query, res, args);\n deffered.resolve(args);\n });\n }\n if (done || fail) {\n deffered.promise.then(done, fail);\n }\n if (always) {\n deffered.promise.then(always, always);\n }\n return deffered.promise;\n };\n DataManager.getDeferedArgs = function (query, result, args) {\n if (query.isCountRequired) {\n args.result = result.result;\n args.count = result.count;\n args.aggregates = result.aggregates;\n }\n else {\n args.result = result;\n }\n return args;\n };\n DataManager.nextTick = function (fn) {\n (window.setImmediate || window.setTimeout)(fn, 0);\n };\n DataManager.prototype.extendRequest = function (url, fnSuccess, fnFail) {\n return extend({}, {\n type: 'GET',\n dataType: this.dataSource.dataType,\n crossDomain: this.dataSource.crossDomain,\n jsonp: this.dataSource.jsonp,\n cache: true,\n processData: false,\n onSuccess: fnSuccess,\n onFailure: fnFail\n }, url);\n };\n DataManager.prototype.makeRequest = function (url, deffered, args, query) {\n var _this = this;\n var isSelector = !!query.subQuerySelector;\n var fnFail = function (e) {\n args.error = e;\n deffered.reject(args);\n };\n var process = function (data, count, xhr, request, actual, aggregates, virtualSelectRecords) {\n args.xhr = xhr;\n args.count = count ? parseInt(count.toString(), 10) : 0;\n args.result = data;\n args.request = request;\n args.aggregates = aggregates;\n args.actual = actual;\n args.virtualSelectRecords = virtualSelectRecords;\n deffered.resolve(args);\n };\n var fnQueryChild = function (data, selector) {\n var subDeffer = new Deferred();\n var childArgs = { parent: args };\n query.subQuery.isChild = true;\n var subUrl = _this.adaptor.processQuery(_this, query.subQuery, data ? _this.adaptor.processResponse(data) : selector);\n var childReq = _this.makeRequest(subUrl, subDeffer, childArgs, query.subQuery);\n if (!isSelector) {\n subDeffer.then(function (subData) {\n if (data) {\n DataUtil.buildHierarchy(query.subQuery.fKey, query.subQuery.fromTable, data, subData, query.subQuery.key);\n process(data, subData.count, subData.xhr);\n }\n }, fnFail);\n }\n return childReq;\n };\n var fnSuccess = function (data, request) {\n if (request.httpRequest.getResponseHeader('Content-Type').indexOf('xml') === -1 && _this.dateParse) {\n data = DataUtil.parse.parseJson(data);\n }\n var result = _this.adaptor.processResponse(data, _this, query, request.httpRequest, request);\n var count = 0;\n var aggregates = null;\n var virtualSelectRecords = 'virtualSelectRecords';\n var virtualRecords = data[virtualSelectRecords];\n if (query.isCountRequired) {\n count = result.count;\n aggregates = result.aggregates;\n result = result.result;\n }\n if (!query.subQuery) {\n process(result, count, request.httpRequest, request.type, data, aggregates, virtualRecords);\n return;\n }\n if (!isSelector) {\n fnQueryChild(result, request);\n }\n };\n var req = this.extendRequest(url, fnSuccess, fnFail);\n var ajax = new Ajax(req);\n ajax.beforeSend = function () {\n _this.beforeSend(ajax.httpRequest, ajax);\n };\n req = ajax.send();\n req.catch(function (e) { return true; }); // to handle failure remote requests. \n this.requests.push(ajax);\n if (isSelector) {\n var promise = void 0;\n var res = query.subQuerySelector.call(this, { query: query.subQuery, parent: query });\n if (res && res.length) {\n promise = Promise.all([req, fnQueryChild(null, res)]);\n promise.then(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var result = args[0];\n var pResult = _this.adaptor.processResponse(result[0], _this, query, _this.requests[0].httpRequest, _this.requests[0]);\n var count = 0;\n if (query.isCountRequired) {\n count = pResult.count;\n pResult = pResult.result;\n }\n var cResult = _this.adaptor.processResponse(result[1], _this, query.subQuery, _this.requests[1].httpRequest, _this.requests[1]);\n count = 0;\n if (query.subQuery.isCountRequired) {\n count = cResult.count;\n cResult = cResult.result;\n }\n DataUtil.buildHierarchy(query.subQuery.fKey, query.subQuery.fromTable, pResult, cResult, query.subQuery.key);\n isSelector = false;\n process(pResult, count, _this.requests[0].httpRequest);\n });\n }\n else {\n isSelector = false;\n }\n }\n return req;\n };\n DataManager.prototype.beforeSend = function (request, settings) {\n this.adaptor.beforeSend(this, request, settings);\n var headers = this.dataSource.headers;\n var props;\n for (var i = 0; headers && i < headers.length; i++) {\n props = [];\n var keys = Object.keys(headers[i]);\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var prop = keys_1[_i];\n props.push(prop);\n request.setRequestHeader(prop, headers[i][prop]);\n }\n }\n };\n /**\n * Save bulk changes to the given table name.\n * User can add a new record, edit an existing record, and delete a record at the same time.\n * If the datasource from remote, then updated in a single post.\n * @param {Object} changes - Defines the CrudOptions.\n * @param {string} key - Defines the column field.\n * @param {string|Query} tableName - Defines the table name.\n * @param {Query} query - Sets default query for the DataManager.\n */\n DataManager.prototype.saveChanges = function (changes, key, tableName, query, original) {\n var _this = this;\n if (tableName instanceof Query) {\n query = tableName;\n tableName = null;\n }\n var args = {\n url: tableName,\n key: key || this.dataSource.key\n };\n var req = this.adaptor.batchRequest(this, changes, args, query, original);\n if (this.dataSource.offline) {\n return req;\n }\n var deff = new Deferred();\n var ajax = new Ajax(req);\n ajax.beforeSend = function () {\n _this.beforeSend(ajax.httpRequest, ajax);\n };\n ajax.onSuccess = function (data, request) {\n deff.resolve(_this.adaptor.processResponse(DataUtil.parse.parseJson(data), _this, null, request.httpRequest, request, changes, args));\n };\n ajax.onFailure = function (e) {\n deff.reject([{ error: e }]);\n };\n ajax.send().catch(function (e) { return true; }); // to handle the failure requests. \n return deff.promise;\n };\n /**\n * Inserts new record in the given table.\n * @param {Object} data - Defines the data to insert.\n * @param {string|Query} tableName - Defines the table name.\n * @param {Query} query - Sets default query for the DataManager.\n */\n DataManager.prototype.insert = function (data, tableName, query, position) {\n if (tableName instanceof Query) {\n query = tableName;\n tableName = null;\n }\n var req = this.adaptor.insert(this, data, tableName, query, position);\n if (this.dataSource.offline) {\n return req;\n }\n return this.doAjaxRequest(req);\n };\n /**\n * Removes data from the table with the given key.\n * @param {string} keyField - Defines the column field.\n * @param {Object} value - Defines the value to find the data in the specified column.\n * @param {string|Query} tableName - Defines the table name\n * @param {Query} query - Sets default query for the DataManager.\n */\n DataManager.prototype.remove = function (keyField, value, tableName, query) {\n if (typeof value === 'object') {\n value = value[keyField];\n }\n if (tableName instanceof Query) {\n query = tableName;\n tableName = null;\n }\n var res = this.adaptor.remove(this, keyField, value, tableName, query);\n if (this.dataSource.offline) {\n return res;\n }\n return this.doAjaxRequest(res);\n };\n /**\n * Updates existing record in the given table.\n * @param {string} keyField - Defines the column field.\n * @param {Object} value - Defines the value to find the data in the specified column.\n * @param {string|Query} tableName - Defines the table name\n * @param {Query} query - Sets default query for the DataManager.\n */\n DataManager.prototype.update = function (keyField, value, tableName, query, original) {\n if (tableName instanceof Query) {\n query = tableName;\n tableName = null;\n }\n var res = this.adaptor.update(this, keyField, value, tableName, query, original);\n if (this.dataSource.offline) {\n return res;\n }\n return this.doAjaxRequest(res);\n };\n DataManager.prototype.doAjaxRequest = function (res) {\n var _this = this;\n var defer = new Deferred();\n res = extend({}, {\n type: 'POST',\n contentType: 'application/json; charset=utf-8',\n processData: false\n }, res);\n var ajax = new Ajax(res);\n ajax.beforeSend = function () {\n _this.beforeSend(ajax.httpRequest, ajax);\n };\n ajax.onSuccess = function (record, request) {\n try {\n DataUtil.parse.parseJson(record);\n }\n catch (e) {\n record = [];\n }\n record = _this.adaptor.processResponse(DataUtil.parse.parseJson(record), _this, null, request.httpRequest, request);\n defer.resolve(record);\n };\n ajax.onFailure = function (e) {\n defer.reject([{ error: e }]);\n };\n ajax.send().catch(function (e) { return true; }); // to handle the failure requests.\n return defer.promise;\n };\n return DataManager;\n}());\nexport { DataManager };\n/**\n * Deferred is used to handle asynchronous operation.\n */\nvar Deferred = /** @class */ (function () {\n function Deferred() {\n var _this = this;\n /**\n * Promise is an object that represents a value that may not be available yet, but will be resolved at some point in the future.\n */\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n /**\n * Defines the callback function triggers when the Deferred object is resolved.\n */\n this.then = this.promise.then.bind(this.promise);\n /**\n * Defines the callback function triggers when the Deferred object is rejected.\n */\n this.catch = this.promise.catch.bind(this.promise);\n }\n return Deferred;\n}());\nexport { Deferred };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { merge, formatUnit, isNullOrUndefined, append, detach } from '@syncfusion/ej2-base';\nimport { attributes, addClass, removeClass, prepend, closest, remove } from '@syncfusion/ej2-base';\nimport { Component, EventHandler, Property, Complex, Event } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, ChildProperty } from '@syncfusion/ej2-base';\nimport { compile } from '@syncfusion/ej2-base';\nimport { Animation, rippleEffect, Touch } from '@syncfusion/ej2-base';\nimport { DataManager, Query } from '@syncfusion/ej2-data';\nimport { createCheckBox } from '@syncfusion/ej2-buttons';\nimport { ListBase, getFieldValues } from '../common/list-base';\n// Effect Configuration Effect[] = [fromViewBackward,fromViewForward,toViewBackward,toviewForward];\nvar effectsConfig = {\n 'None': [],\n 'SlideLeft': ['SlideRightOut', 'SlideLeftOut', 'SlideLeftIn', 'SlideRightIn'],\n 'SlideDown': ['SlideTopOut', 'SlideBottomOut', 'SlideBottomIn', 'SlideTopIn'],\n 'Zoom': ['FadeOut', 'FadeZoomOut', 'FadeZoomIn', 'FadeIn'],\n 'Fade': ['FadeOut', 'FadeOut', 'FadeIn', 'FadeIn']\n};\nvar effectsRTLConfig = {\n 'None': [],\n 'SlideLeft': ['SlideLeftOut', 'SlideRightOut', 'SlideRightIn', 'SlideLeftIn'],\n 'SlideDown': ['SlideBottomOut', 'SlideTopOut', 'SlideTopIn', 'SlideBottomIn'],\n 'Zoom': ['FadeZoomOut', 'FadeOut', 'FadeIn', 'FadeZoomIn'],\n 'Fade': ['FadeOut', 'FadeOut', 'FadeIn', 'FadeIn']\n};\n// don't use space in classnames.\nexport var classNames = {\n root: 'e-listview',\n hover: 'e-hover',\n selected: 'e-active',\n focused: 'e-focused',\n parentItem: 'e-list-parent',\n listItem: 'e-list-item',\n listIcon: 'e-list-icon',\n textContent: 'e-text-content',\n listItemText: 'e-list-text',\n groupListItem: 'e-list-group-item',\n hasChild: 'e-has-child',\n view: 'e-view',\n header: 'e-list-header',\n headerText: 'e-headertext',\n headerTemplateText: 'e-headertemplate-text',\n text: 'e-text',\n disable: 'e-disabled',\n content: 'e-content',\n icon: 'e-icons',\n backIcon: 'e-icon-back',\n checkboxWrapper: 'e-checkbox-wrapper',\n checkbox: 'e-checkbox',\n checked: 'e-check',\n checklist: 'e-checklist',\n checkboxIcon: 'e-frame',\n checkboxRight: 'e-checkbox-right',\n checkboxLeft: 'e-checkbox-left',\n listviewCheckbox: 'e-listview-checkbox',\n itemCheckList: 'e-checklist'\n};\nvar FieldSettings = /** @class */ (function (_super) {\n __extends(FieldSettings, _super);\n function FieldSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('id')\n ], FieldSettings.prototype, \"id\", void 0);\n __decorate([\n Property('text')\n ], FieldSettings.prototype, \"text\", void 0);\n __decorate([\n Property('isChecked')\n ], FieldSettings.prototype, \"isChecked\", void 0);\n __decorate([\n Property('isVisible')\n ], FieldSettings.prototype, \"isVisible\", void 0);\n __decorate([\n Property('enabled')\n ], FieldSettings.prototype, \"enabled\", void 0);\n __decorate([\n Property('iconCss')\n ], FieldSettings.prototype, \"iconCss\", void 0);\n __decorate([\n Property('child')\n ], FieldSettings.prototype, \"child\", void 0);\n __decorate([\n Property('tooltip')\n ], FieldSettings.prototype, \"tooltip\", void 0);\n __decorate([\n Property('groupBy')\n ], FieldSettings.prototype, \"groupBy\", void 0);\n __decorate([\n Property('text')\n ], FieldSettings.prototype, \"sortBy\", void 0);\n __decorate([\n Property('htmlAttributes')\n ], FieldSettings.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property('tableName')\n ], FieldSettings.prototype, \"tableName\", void 0);\n return FieldSettings;\n}(ChildProperty));\nexport { FieldSettings };\n/**\n * Represents the EJ2 ListView control.\n * ```html\n *
\n *
\n * Favourite \n * Documents \n * Downloads \n * \n *
\n * ```\n * ```typescript\n * var lvObj = new ListView({});\n * lvObj.appendTo(\"#listview\");\n * ```\n */\nvar ListView = /** @class */ (function (_super) {\n __extends(ListView, _super);\n /**\n * Constructor for creating the widget\n */\n function ListView(options, element) {\n return _super.call(this, options, element) || this;\n }\n ListView.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'htmlAttributes':\n this.setHTMLAttribute();\n break;\n case 'cssClass':\n this.setCSSClass(oldProp.cssClass);\n break;\n case 'enable':\n this.setEnable();\n break;\n case 'width':\n case 'height':\n this.setSize();\n break;\n case 'enableRtl':\n this.setEnableRTL();\n break;\n case 'fields':\n this.listBaseOption.fields = this.fields.properties;\n if (this.enableVirtualization) {\n this.virtualizationModule.reRenderUiVirtualization();\n }\n else {\n this.reRender();\n }\n break;\n case 'headerTitle':\n if (!this.curDSLevel.length) {\n this.header(this.headerTitle, false);\n }\n break;\n case 'showHeader':\n this.header(this.headerTitle, false);\n break;\n case 'enableVirtualization':\n detach(this.contentContainer);\n this.refresh();\n break;\n case 'showCheckBox':\n case 'checkBoxPosition':\n if (this.enableVirtualization) {\n this.virtualizationModule.reRenderUiVirtualization();\n }\n else {\n this.setCheckbox();\n }\n break;\n case 'dataSource':\n if (this.enableVirtualization) {\n this.virtualizationModule.reRenderUiVirtualization();\n }\n else {\n this.reRender();\n }\n break;\n case 'sortOrder':\n case 'showIcon':\n if (this.enableVirtualization) {\n this.virtualizationModule.reRenderUiVirtualization();\n }\n else {\n this.listBaseOption.showIcon = this.showIcon;\n this.curViewDS = this.getSubDS();\n this.resetCurrentList();\n }\n break;\n default:\n break;\n }\n }\n };\n // Model Changes\n ListView.prototype.setHTMLAttribute = function () {\n if (Object.keys(this.htmlAttributes).length) {\n attributes(this.element, this.htmlAttributes);\n }\n };\n ListView.prototype.setCSSClass = function (oldCSSClass) {\n if (this.cssClass) {\n addClass([this.element], this.cssClass.split(' '));\n }\n if (oldCSSClass) {\n removeClass([this.element], oldCSSClass.split(' '));\n }\n };\n ListView.prototype.setSize = function () {\n this.element.style.height = formatUnit(this.height);\n this.element.style.width = formatUnit(this.width);\n this.isWindow = this.element.getBoundingClientRect().height ? false : true;\n };\n ListView.prototype.setEnable = function () {\n this.enableElement(this.element, this.enable);\n };\n ListView.prototype.setEnableRTL = function () {\n if (this.enableRtl) {\n this.element.classList.add('e-rtl');\n }\n else {\n this.element.classList.remove('e-rtl');\n }\n };\n ListView.prototype.enableElement = function (element, isEnabled) {\n if (isEnabled) {\n element.classList.remove(classNames.disable);\n }\n else {\n element.classList.add(classNames.disable);\n }\n };\n //Suport Component Functions\n ListView.prototype.header = function (text, showBack) {\n if (this.headerEle === undefined && this.showHeader) {\n this.headerEle = this.createElement('div', { className: classNames.header });\n var innerHeaderEle = this.createElement('span', { className: classNames.headerText, innerHTML: this.headerTitle });\n var textEle = this.createElement('div', { className: classNames.text, innerHTML: innerHeaderEle.outerHTML });\n var hedBackButton = this.createElement('div', {\n className: classNames.icon + ' ' + classNames.backIcon + ' e-but-back',\n attrs: { style: 'display:none;' }\n });\n this.headerEle.appendChild(hedBackButton);\n this.headerEle.appendChild(textEle);\n if (this.headerTemplate) {\n var compiledString = compile(this.headerTemplate);\n var headerTemplateEle = this.createElement('div', { className: classNames.headerTemplateText });\n append(compiledString({}), headerTemplateEle);\n append([headerTemplateEle], this.headerEle);\n }\n if (this.headerTemplate && this.headerTitle) {\n textEle.classList.add('header');\n }\n this.element.classList.add('e-has-header');\n prepend([this.headerEle], this.element);\n }\n else if (this.headerEle) {\n if (this.showHeader) {\n this.headerEle.style.display = '';\n var textEle = this.headerEle.querySelector('.' + classNames.headerText);\n var hedBackButton = this.headerEle.querySelector('.' + classNames.backIcon);\n textEle.innerHTML = text;\n if (this.headerTemplate && showBack) {\n textEle.parentElement.classList.remove('header');\n this.headerEle.querySelector('.' + classNames.headerTemplateText).classList.add('nested-header');\n }\n if (this.headerTemplate && !showBack) {\n textEle.parentElement.classList.add('header');\n this.headerEle.querySelector('.' + classNames.headerTemplateText).classList.remove('nested-header');\n this.headerEle.querySelector('.' + classNames.headerTemplateText).classList.add('header');\n }\n if (showBack === true) {\n hedBackButton.style.display = '';\n }\n else {\n hedBackButton.style.display = 'none';\n }\n }\n else {\n this.headerEle.style.display = 'none';\n }\n }\n };\n // Animation Related Functions\n ListView.prototype.switchView = function (fromView, toView, reverse) {\n var _this = this;\n if (fromView && toView) {\n var fPos_1 = fromView.style.position;\n var overflow_1 = (this.element.style.overflow !== 'hidden') ? this.element.style.overflow : '';\n fromView.style.position = 'absolute';\n fromView.classList.add('e-view');\n var anim = void 0;\n var duration = this.animation.duration;\n if (this.animation.effect) {\n anim = (this.enableRtl ? effectsRTLConfig[this.animation.effect] : effectsConfig[this.animation.effect]);\n }\n else {\n var slideLeft = 'SlideLeft';\n anim = effectsConfig[slideLeft];\n reverse = this.enableRtl;\n duration = 0;\n }\n this.element.style.overflow = 'hidden';\n this.aniObj.animate(fromView, {\n name: (reverse === true ? anim[0] : anim[1]),\n duration: duration,\n timingFunction: this.animation.easing,\n end: function (model) {\n fromView.style.display = 'none';\n _this.element.style.overflow = overflow_1;\n fromView.style.position = fPos_1;\n fromView.classList.remove('e-view');\n }\n });\n toView.style.display = '';\n this.aniObj.animate(toView, {\n name: (reverse === true ? anim[2] : anim[3]),\n duration: duration,\n timingFunction: this.animation.easing,\n end: function () {\n _this.trigger('actionComplete');\n }\n });\n this.curUL = toView;\n }\n };\n ListView.prototype.preRender = function () {\n this.listBaseOption = {\n template: this.template,\n headerTemplate: this.headerTemplate,\n groupTemplate: this.groupTemplate, expandCollapse: true, listClass: '',\n ariaAttributes: {\n itemRole: 'listitem', listRole: 'list', itemText: '',\n groupItemRole: 'group', wrapperRole: 'presentation'\n },\n fields: this.fields.properties, sortOrder: this.sortOrder, showIcon: this.showIcon,\n itemCreated: this.renderCheckbox.bind(this)\n };\n this.initialization();\n };\n ListView.prototype.initialization = function () {\n this.curDSLevel = [];\n this.animateOptions = {};\n this.curViewDS = [];\n this.currentLiElements = [];\n this.isNestedList = false;\n this.selectedData = [];\n this.selectedId = [];\n this.aniObj = new Animation(this.animateOptions);\n };\n ListView.prototype.renderCheckbox = function (args) {\n if (args.item.classList.contains(classNames.hasChild)) {\n this.isNestedList = true;\n }\n if (this.showCheckBox && this.isValidLI(args.item)) {\n var checkboxElement = void 0;\n var fieldData = void 0;\n checkboxElement = createCheckBox(this.createElement, false, {\n checked: false, enableRtl: this.enableRtl,\n cssClass: classNames.listviewCheckbox\n });\n checkboxElement.setAttribute('role', 'checkbox');\n var frameElement_1 = checkboxElement.querySelector('.' + classNames.checkboxIcon);\n args.item.classList.add(classNames.itemCheckList);\n args.item.firstElementChild.classList.add(classNames.checkbox);\n if (typeof this.dataSource[0] !== 'string' && typeof this.dataSource[0] !== 'number') {\n fieldData = getFieldValues(args.curData, this.listBaseOption.fields);\n if (fieldData[this.listBaseOption.fields.isChecked]) {\n this.checkInternally(args, checkboxElement);\n }\n }\n else if (((typeof this.dataSource[0] === 'string' ||\n typeof this.dataSource[0] === 'number') && this.selectedData.indexOf(args.text) !== -1)) {\n this.checkInternally(args, checkboxElement);\n }\n checkboxElement.setAttribute('aria-checked', frameElement_1.classList.contains(classNames.checked) ? 'true' : 'false');\n if (this.checkBoxPosition === 'Left') {\n checkboxElement.classList.add(classNames.checkboxLeft);\n args.item.firstElementChild.classList.add(classNames.checkboxLeft);\n args.item.firstElementChild.insertBefore(checkboxElement, args.item.firstElementChild.childNodes[0]);\n }\n else {\n checkboxElement.classList.add(classNames.checkboxRight);\n args.item.firstElementChild.classList.add(classNames.checkboxRight);\n args.item.firstElementChild.appendChild(checkboxElement);\n }\n this.currentLiElements.push(args.item);\n }\n };\n ListView.prototype.checkInternally = function (args, checkboxElement) {\n args.item.classList.add(classNames.selected);\n args.item.setAttribute('aria-selected', 'true');\n checkboxElement.querySelector('.' + classNames.checkboxIcon).classList.add(classNames.checked);\n checkboxElement.setAttribute('aria-checked', 'true');\n };\n /**\n * It is used to check the checkbox of an item.\n * @param {Fields | HTMLElement} item - It accepts Fields or HTML list element as an argument.\n */\n ListView.prototype.checkItem = function (item) {\n this.toggleCheckBase(item, true);\n };\n ListView.prototype.toggleCheckBase = function (item, checked) {\n if (this.showCheckBox) {\n var liElement = item;\n if (item instanceof Object && item.constructor !== HTMLLIElement) {\n liElement = this.getLiFromObjOrElement(item);\n }\n if (!isNullOrUndefined(liElement)) {\n var checkboxIcon = liElement.querySelector('.' + classNames.checkboxIcon);\n checked ? liElement.classList.add(classNames.selected) : liElement.classList.remove(classNames.selected);\n liElement.setAttribute('aria-selected', checked ? 'true' : 'false');\n checked ? checkboxIcon.classList.add(classNames.checked) : checkboxIcon.classList.remove(classNames.checked);\n checkboxIcon.parentElement.setAttribute('aria-checked', checked ? 'true' : 'false');\n }\n this.setSelectedItemData(liElement);\n }\n };\n /**\n * It is used to uncheck the checkbox of an item.\n * @param {Fields | HTMLElement} item - It accepts Fields or HTML list element as an argument.\n */\n ListView.prototype.uncheckItem = function (item) {\n this.toggleCheckBase(item, false);\n };\n /**\n * It is used to check all the items in ListView.\n */\n ListView.prototype.checkAllItems = function () {\n this.toggleAllCheckBase(true);\n };\n /**\n * It is used to un-check all the items in ListView.\n */\n ListView.prototype.uncheckAllItems = function () {\n this.toggleAllCheckBase(false);\n };\n ListView.prototype.toggleAllCheckBase = function (checked) {\n if (this.showCheckBox) {\n for (var i = 0; i < this.liCollection.length; i++) {\n var checkIcon = this.liCollection[i].querySelector('.' + classNames.checkboxIcon);\n if (checkIcon) {\n if (checked) {\n if (!checkIcon.classList.contains(classNames.checked)) {\n this.checkItem(this.liCollection[i]);\n }\n }\n else {\n if (checkIcon.classList.contains(classNames.checked)) {\n this.uncheckItem(this.liCollection[i]);\n }\n }\n }\n }\n if (this.enableVirtualization) {\n this.virtualizationModule.checkedItem(checked);\n }\n }\n };\n ListView.prototype.setCheckbox = function () {\n var _this = this;\n if (this.showCheckBox) {\n var liCollection = Array.prototype.slice.call(this.element.querySelectorAll('.' + classNames.listItem));\n var args_1 = {\n item: undefined, curData: undefined, dataSource: undefined, fields: undefined,\n options: undefined, text: ''\n };\n liCollection.forEach(function (element) {\n args_1.item = element;\n args_1.curData = _this.getItemData(element);\n if (element.querySelector('.' + classNames.checkboxWrapper)) {\n _this.removeElement(element.querySelector('.' + classNames.checkboxWrapper));\n }\n _this.renderCheckbox(args_1);\n if (args_1.item.classList.contains(classNames.selected)) {\n _this.checkInternally(args_1, args_1.item.querySelector('.' + classNames.checkboxWrapper));\n }\n });\n }\n else {\n var liCollection = Array.prototype.slice.call(this.element.querySelectorAll('.' + classNames.itemCheckList));\n liCollection.forEach(function (element) {\n element.classList.remove(classNames.selected);\n element.firstElementChild.classList.remove(classNames.checkbox);\n _this.removeElement(element.querySelector('.' + classNames.checkboxWrapper));\n });\n if (this.selectedItems) {\n this.selectedItems.item.classList.add(classNames.selected);\n }\n }\n };\n ListView.prototype.clickHandler = function (e) {\n var target = e.target;\n var classList = target.classList;\n if (classList.contains(classNames.backIcon) || classList.contains(classNames.headerText)) {\n if (this.showCheckBox && this.curDSLevel[this.curDSLevel.length - 1]) {\n this.uncheckAllItems();\n }\n this.back();\n }\n else {\n var li = closest(target.parentNode, '.' + classNames.listItem);\n if (li === null) {\n li = target;\n }\n this.removeFocus();\n if (this.enable && this.showCheckBox && this.isValidLI(li)) {\n if (e.target.classList.contains(classNames.checkboxIcon)) {\n li.classList.add(classNames.focused);\n if (isNullOrUndefined(li.querySelector('.' + classNames.checked))) {\n var args = {\n curData: undefined, dataSource: undefined, fields: undefined, options: undefined,\n text: undefined, item: li\n };\n this.checkInternally(args, args.item.querySelector('.' + classNames.checkboxWrapper));\n }\n else {\n this.uncheckItem(li);\n li.classList.add(classNames.focused);\n }\n if (e) {\n var eventArgs = this.selectEventData(li, e);\n var checkIcon = li.querySelector('.' + classNames.checkboxIcon);\n merge(eventArgs, { isChecked: checkIcon.classList.contains(classNames.checked) });\n this.trigger('select', eventArgs);\n }\n }\n else if (li.classList.contains(classNames.hasChild)) {\n this.removeHover();\n this.removeSelect();\n this.removeSelect(li);\n this.setSelectLI(li, e);\n li.classList.remove(classNames.selected);\n }\n else {\n this.setCheckboxLI(li, e);\n }\n }\n else {\n this.setSelectLI(li, e);\n }\n }\n };\n ListView.prototype.removeElement = function (element) {\n return element && element.parentNode && element.parentNode.removeChild(element);\n };\n ListView.prototype.hoverHandler = function (e) {\n var curLi = closest(e.target.parentNode, '.' + classNames.listItem);\n this.setHoverLI(curLi);\n };\n ListView.prototype.leaveHandler = function (e) {\n this.removeHover();\n };\n ;\n ListView.prototype.homeKeyHandler = function (e, end) {\n if (Object.keys(this.dataSource).length && this.curUL) {\n var li = this.curUL.querySelectorAll('.' + classNames.listItem);\n var focusedElement = this.curUL.querySelector('.' + classNames.focused) ||\n this.curUL.querySelector('.' + classNames.selected);\n if (focusedElement) {\n focusedElement.classList.remove(classNames.focused);\n if (!this.showCheckBox) {\n focusedElement.classList.remove(classNames.selected);\n }\n }\n var index = !end ? 0 : li.length - 1;\n if (li[index].classList.contains(classNames.hasChild) || this.showCheckBox) {\n li[index].classList.add(classNames.focused);\n }\n else {\n this.setSelectLI(li[index], e);\n }\n }\n };\n ListView.prototype.onArrowKeyDown = function (e, prev) {\n var siblingLI;\n var li;\n var hasChild = !isNullOrUndefined(this.curUL.querySelector('.' + classNames.hasChild)) ? true : false;\n if (hasChild || this.showCheckBox) {\n li = this.curUL.querySelector('.' + classNames.focused) || this.curUL.querySelector('.' + classNames.selected);\n siblingLI = ListBase.getSiblingLI(this.curUL.querySelectorAll('.' + classNames.listItem), li, prev);\n if (!isNullOrUndefined(siblingLI)) {\n if (li) {\n li.classList.remove(classNames.focused);\n if (!this.showCheckBox) {\n li.classList.remove(classNames.selected);\n }\n }\n if (siblingLI.classList.contains(classNames.hasChild) || this.showCheckBox) {\n siblingLI.classList.add(classNames.focused);\n }\n else {\n this.setSelectLI(siblingLI, e);\n }\n }\n }\n else {\n li = this.curUL.querySelector('.' + classNames.selected);\n siblingLI = ListBase.getSiblingLI(this.curUL.querySelectorAll('.' + classNames.listItem), li, prev);\n this.setSelectLI(siblingLI, e);\n }\n return siblingLI;\n };\n ListView.prototype.arrowKeyHandler = function (e, prev) {\n var _this = this;\n if (Object.keys(this.dataSource).length && this.curUL) {\n var siblingLI = this.onArrowKeyDown(e, prev);\n var elementTop = this.element.getBoundingClientRect().top;\n var elementHeight = this.element.getBoundingClientRect().height;\n var firstItemBounds = this.curUL.querySelector('.' + classNames.listItem).getBoundingClientRect();\n var heightDiff = void 0;\n var groupItemBounds = void 0;\n if (this.fields.groupBy) {\n groupItemBounds = this.curUL.querySelector('.' + classNames.groupListItem).getBoundingClientRect();\n }\n if (siblingLI) {\n var siblingTop = siblingLI.getBoundingClientRect().top;\n var siblingHeight = siblingLI.getBoundingClientRect().height;\n if (!prev) {\n var height = this.isWindow ? window.innerHeight : elementHeight;\n heightDiff = this.isWindow ? (siblingTop + siblingHeight) :\n ((siblingTop - elementTop) + siblingHeight);\n if (heightDiff > height) {\n this.isWindow ? window.scrollTo(0, pageYOffset + (heightDiff - height)) :\n this.element.scrollTo(0, this.element.scrollTop + (heightDiff - height));\n }\n }\n else {\n heightDiff = this.isWindow ? siblingTop : (siblingTop - elementTop);\n if (heightDiff < 0) {\n this.isWindow ? window.scrollTo(0, pageYOffset + heightDiff) :\n this.element.scrollTo(0, this.element.scrollTop + heightDiff);\n }\n }\n }\n else if (this.enableVirtualization && prev && this.virtualizationModule.uiFirstIndex) {\n this.onUIScrolled = function () {\n _this.onArrowKeyDown(e, prev);\n _this.onUIScrolled = undefined;\n };\n heightDiff = this.virtualizationModule.listItemHeight;\n this.isWindow ? window.scrollTo(0, pageYOffset - heightDiff) :\n this.element.scrollTo(0, this.element.scrollTop - heightDiff);\n }\n else if (prev) {\n if (this.showHeader && this.headerEle) {\n var topHeight = groupItemBounds ? groupItemBounds.top : firstItemBounds.top;\n var headerBounds = this.headerEle.getBoundingClientRect();\n heightDiff = headerBounds.top < 0 ? (headerBounds.height - topHeight) : 0;\n this.isWindow ? window.scrollTo(0, pageYOffset - heightDiff)\n : this.element.scrollTo(0, 0);\n }\n else if (this.fields.groupBy) {\n heightDiff = this.isWindow ? (groupItemBounds.top < 0 ? groupItemBounds.top : 0) :\n (elementTop - firstItemBounds.top) + groupItemBounds.height;\n this.isWindow ? window.scrollTo(0, pageYOffset + heightDiff) :\n this.element.scrollTo(0, this.element.scrollTop - heightDiff);\n }\n }\n }\n };\n ListView.prototype.enterKeyHandler = function (e) {\n if (Object.keys(this.dataSource).length && this.curUL) {\n var hasChild = !isNullOrUndefined(this.curUL.querySelector('.' + classNames.hasChild)) ? true : false;\n var li = this.curUL.querySelector('.' + classNames.focused);\n if (hasChild && li) {\n li.classList.remove(classNames.focused);\n if (this.showCheckBox) {\n this.removeSelect();\n this.removeSelect(li);\n this.removeHover();\n }\n this.setSelectLI(li, e);\n }\n }\n };\n ListView.prototype.spaceKeyHandler = function (e) {\n if (this.enable && this.showCheckBox && Object.keys(this.dataSource).length && this.curUL) {\n var li = this.curUL.querySelector('.' + classNames.focused);\n if (!isNullOrUndefined(li) && isNullOrUndefined(li.querySelector('.' + classNames.checked))) {\n var args = {\n curData: undefined, dataSource: undefined, fields: undefined, options: undefined,\n text: undefined, item: li\n };\n this.checkInternally(args, args.item.querySelector('.' + classNames.checkboxWrapper));\n }\n else {\n this.uncheckItem(li);\n }\n }\n };\n ListView.prototype.keyActionHandler = function (e) {\n e.preventDefault();\n switch (e.keyCode) {\n case 36:\n this.homeKeyHandler(e);\n break;\n case 35:\n this.homeKeyHandler(e, true);\n break;\n case 40:\n this.arrowKeyHandler(e);\n break;\n case 38:\n this.arrowKeyHandler(e, true);\n break;\n case 13:\n this.enterKeyHandler(e);\n break;\n case 8:\n if (this.showCheckBox && this.curDSLevel[this.curDSLevel.length - 1]) {\n this.uncheckAllItems();\n }\n this.back();\n break;\n case 9:\n this.tabFocus(e);\n break;\n case 32:\n this.spaceKeyHandler(e);\n break;\n }\n };\n ListView.prototype.swipeActionHandler = function (e) {\n if (e.swipeDirection === 'Right') {\n if (this.showCheckBox && this.curDSLevel[this.curDSLevel.length - 1]) {\n this.uncheckAllItems();\n }\n this.back();\n }\n };\n ListView.prototype.focusout = function () {\n if (Object.keys(this.dataSource).length && this.curUL) {\n var focusedElement = this.curUL.querySelector('.' + classNames.focused);\n var activeElement = this.curUL.querySelector('[aria-selected = true]');\n if (focusedElement && !this.showCheckBox) {\n focusedElement.classList.remove(classNames.focused);\n if (activeElement) {\n activeElement.classList.add(classNames.selected);\n }\n }\n }\n };\n ListView.prototype.wireEvents = function () {\n EventHandler.add(this.element, 'keydown', this.keyActionHandler, this);\n EventHandler.add(this.element, 'click', this.clickHandler, this);\n if (!this.enableVirtualization) {\n EventHandler.add(this.element, 'mouseover', this.hoverHandler, this);\n EventHandler.add(this.element, 'mouseout', this.leaveHandler, this);\n }\n EventHandler.add(this.element, 'focusout', this.focusout, this);\n this.touchModule = new Touch(this.element, { swipe: this.swipeActionHandler.bind(this) });\n };\n ListView.prototype.unWireEvents = function () {\n EventHandler.remove(this.element, 'click', this.clickHandler);\n if (!this.enableVirtualization) {\n EventHandler.remove(this.element, 'mouseover', this.hoverHandler);\n EventHandler.remove(this.element, 'mouseout', this.leaveHandler);\n }\n EventHandler.remove(this.element, 'mouseover', this.hoverHandler);\n EventHandler.remove(this.element, 'mouseout', this.leaveHandler);\n this.touchModule.destroy();\n };\n ListView.prototype.tabFocus = function (e) {\n if (Object.keys(this.dataSource).length && this.curUL) {\n var selectedList = this.curUL.querySelector('.' + classNames.selected);\n if ((!selectedList && this.curUL) || this.showCheckBox) {\n var li = this.curUL.querySelector('.' + classNames.listItem);\n if (li.classList.contains(classNames.hasChild) || this.showCheckBox) {\n var focusedElement = this.curUL.querySelector('.' + classNames.focused);\n if (isNullOrUndefined(focusedElement)) {\n li.classList.add(classNames.focused);\n }\n }\n else {\n this.setSelectLI(li, e);\n }\n }\n }\n };\n ListView.prototype.removeFocus = function () {\n var focusedLI = this.element.querySelectorAll('.' + classNames.focused);\n for (var _i = 0, focusedLI_1 = focusedLI; _i < focusedLI_1.length; _i++) {\n var ele = focusedLI_1[_i];\n ele.classList.remove(classNames.focused);\n }\n };\n ListView.prototype.removeHover = function () {\n var hoverLI = this.element.querySelector('.' + classNames.hover);\n if (hoverLI) {\n hoverLI.classList.remove(classNames.hover);\n }\n };\n ListView.prototype.removeSelect = function (li) {\n if (isNullOrUndefined(li)) {\n var selectedLI = this.element.querySelectorAll('.' + classNames.selected);\n for (var _i = 0, selectedLI_1 = selectedLI; _i < selectedLI_1.length; _i++) {\n var ele = selectedLI_1[_i];\n if (this.showCheckBox && ele.querySelector('.' + classNames.checked)) {\n continue;\n }\n else {\n ele.setAttribute('aria-selected', 'false');\n ele.classList.remove(classNames.selected);\n }\n }\n }\n else {\n li.classList.remove(classNames.selected);\n li.setAttribute('aria-selected', 'false');\n }\n };\n ListView.prototype.isValidLI = function (li) {\n return (li && li.classList.contains(classNames.listItem)\n && !li.classList.contains(classNames.groupListItem)\n && !li.classList.contains(classNames.disable));\n };\n ListView.prototype.setCheckboxLI = function (li, e) {\n if (this.isValidLI(li) && this.enable && this.showCheckBox) {\n if (this.curUL.querySelector('.' + classNames.focused)) {\n this.curUL.querySelector('.' + classNames.focused).classList.remove(classNames.focused);\n }\n li.classList.add(classNames.focused);\n var checkboxElement = li.querySelector('.' + classNames.checkboxWrapper);\n var checkIcon = checkboxElement.querySelector('.' + classNames.checkboxIcon + '.' + classNames.icon);\n this.removeHover();\n if (!checkIcon.classList.contains(classNames.checked)) {\n checkIcon.classList.add(classNames.checked);\n li.classList.add(classNames.selected);\n li.setAttribute('aria-selected', 'true');\n }\n else {\n checkIcon.classList.remove(classNames.checked);\n li.classList.remove(classNames.selected);\n li.setAttribute('aria-selected', 'false');\n }\n checkboxElement.setAttribute('aria-checked', checkIcon.classList.contains(classNames.checked) ?\n 'true' : 'false');\n if (e) {\n var eventArgs = this.selectEventData(li, e);\n merge(eventArgs, { isChecked: checkIcon.classList.contains(classNames.checked) });\n if (this.enableVirtualization) {\n this.virtualizationModule.setCheckboxLI(li, e);\n }\n this.trigger('select', eventArgs);\n }\n this.setSelectedItemData(li);\n this.renderSubList(li);\n }\n };\n ListView.prototype.selectEventData = function (li, e) {\n var data = this.getItemData(li);\n var fieldData = getFieldValues(data, this.listBaseOption.fields);\n var selectedItem;\n if (!isNullOrUndefined(data)\n && typeof this.dataSource[0] === 'string' || typeof this.dataSource[0] === 'number') {\n selectedItem = { item: li, text: li && li.innerText.trim(), data: this.dataSource };\n }\n else {\n selectedItem = { item: li, text: fieldData && fieldData[this.listBaseOption.fields.text], data: data };\n }\n var eventArgs = {};\n merge(eventArgs, selectedItem);\n if (e) {\n merge(eventArgs, { isInteracted: true, event: e, index: Array.prototype.indexOf.call(this.curUL.children, li) });\n }\n return eventArgs;\n };\n ListView.prototype.setSelectedItemData = function (li) {\n var data = this.getItemData(li);\n var fieldData = getFieldValues(data, this.listBaseOption.fields);\n if (!isNullOrUndefined(data) && ((typeof this.dataSource[0] === 'string') ||\n (typeof this.dataSource[0] === 'number'))) {\n this.selectedItems = {\n item: li,\n text: li && li.innerText.trim(),\n data: this.dataSource\n };\n }\n else {\n this.selectedItems = {\n item: li,\n text: fieldData && fieldData[this.listBaseOption.fields.text],\n data: data\n };\n }\n };\n ListView.prototype.setSelectLI = function (li, e) {\n if (this.isValidLI(li) && !li.classList.contains(classNames.selected) && this.enable) {\n if (!this.showCheckBox) {\n this.removeSelect();\n }\n li.classList.add(classNames.selected);\n li.setAttribute('aria-selected', 'true');\n this.removeHover();\n this.setSelectedItemData(li);\n if (this.enableVirtualization) {\n this.virtualizationModule.setSelectLI(li, e);\n }\n var eventArgs = this.selectEventData(li, e);\n this.trigger('select', eventArgs);\n this.selectedLI = li;\n this.renderSubList(li);\n }\n };\n ListView.prototype.setHoverLI = function (li) {\n if (this.isValidLI(li) && !li.classList.contains(classNames.hover) && this.enable) {\n var lastLi = this.element.querySelectorAll('.' + classNames.hover);\n if (lastLi && lastLi.length) {\n removeClass(lastLi, classNames.hover);\n }\n if (!li.classList.contains(classNames.selected) || this.showCheckBox) {\n li.classList.add(classNames.hover);\n }\n }\n };\n ListView.prototype.hoverSiblingLI = function (prev) {\n var lastLi = this.curUL.querySelector('.' + classNames.hover);\n var siblingLI;\n if (!lastLi) {\n lastLi = this.curUL.querySelector('.' + classNames.selected);\n }\n if (lastLi) {\n siblingLI = ListBase.getSiblingLI(this.curUL.querySelectorAll('.' + classNames.listItem), lastLi, prev);\n }\n else {\n if (prev) {\n var curLIs = this.curUL.querySelectorAll('.' + classNames.listItem);\n siblingLI = curLIs[curLIs.length - 1];\n }\n else {\n siblingLI = this.curUL.querySelector('.' + classNames.listItem);\n }\n }\n this.setHoverLI(siblingLI);\n };\n //Data Source Related Functions\n ListView.prototype.getSubDS = function () {\n var levelKeys = this.curDSLevel;\n if (levelKeys.length) {\n var ds = this.localData;\n for (var _i = 0, levelKeys_1 = levelKeys; _i < levelKeys_1.length; _i++) {\n var key = levelKeys_1[_i];\n var field = {};\n field[this.fields.id] = key;\n this.curDSJSON = this.findItemFromDS(ds, field);\n var fieldData = getFieldValues(this.curDSJSON, this.listBaseOption.fields);\n ds = this.curDSJSON ? fieldData[this.fields.child] : ds;\n }\n return ds;\n }\n return this.localData;\n };\n ListView.prototype.getItemData = function (li) {\n var fields = this.getElementUID(li);\n var curDS;\n if (isNullOrUndefined(this.curUL.querySelector('.' + classNames.hasChild)) && this.fields.groupBy) {\n curDS = this.curViewDS;\n }\n else {\n curDS = this.dataSource;\n }\n return this.findItemFromDS(curDS, fields);\n };\n ListView.prototype.findItemFromDS = function (dataSource, fields, parent) {\n var _this = this;\n var resultJSON;\n if (dataSource && dataSource.length && fields) {\n dataSource.some(function (data) {\n var fieldData = getFieldValues(data, _this.listBaseOption.fields);\n //(!(fid) || id === fid) && (!(ftext) || text === ftext) && (!!fid || !!ftext)\n if ((fields[_this.fields.id] || fields[_this.fields.text]) &&\n (!fields[_this.fields.id] || (!isNullOrUndefined(fieldData[_this.fields.id]) &&\n fieldData[_this.fields.id].toString()) === fields[_this.fields.id].toString()) &&\n (!fields[_this.fields.text] || fieldData[_this.fields.text] === fields[_this.fields.text])) {\n resultJSON = (parent ? dataSource : data);\n }\n else if (typeof data !== 'object' && dataSource.indexOf(data) !== -1) {\n resultJSON = (parent ? dataSource : data);\n }\n else if (!isNullOrUndefined(fields[_this.fields.id]) && isNullOrUndefined(fieldData[_this.fields.id])) {\n var li = _this.element.querySelector('[data-uid=\"'\n + fields[_this.fields.id] + '\"]');\n if (li && li.innerText.trim() === fieldData[_this.fields.text]) {\n resultJSON = data;\n }\n }\n else if (fieldData.hasOwnProperty(_this.fields.child) && fieldData[_this.fields.child].length) {\n resultJSON = _this.findItemFromDS(fieldData[_this.fields.child], fields, parent);\n }\n return !!resultJSON;\n });\n }\n else {\n resultJSON = dataSource;\n }\n return resultJSON;\n };\n ListView.prototype.getQuery = function () {\n var columns = [];\n var query = (this.query ? this.query : new Query());\n if (!this.query) {\n for (var _i = 0, _a = Object.keys(this.fields.properties); _i < _a.length; _i++) {\n var column = _a[_i];\n if (column !== 'tableName' && !!(this.fields[column]) &&\n this.fields[column] !==\n ListBase.defaultMappedFields[column]\n && columns.indexOf(this.fields[column]) === -1) {\n columns.push(this.fields[column]);\n }\n }\n query.select(columns);\n if (this.fields.properties.hasOwnProperty('tableName')) {\n query.from(this.fields.tableName);\n }\n }\n return query;\n };\n ListView.prototype.setViewDataSource = function (dataSource) {\n if (dataSource === void 0) { dataSource = this.localData; }\n if (dataSource && this.fields.groupBy) {\n this.curViewDS = ListBase.groupDataSource(dataSource, this.listBaseOption.fields, this.sortOrder);\n }\n else if (dataSource && this.sortOrder !== 'None') {\n this.curViewDS = ListBase.getDataSource(dataSource, ListBase.addSorting(this.sortOrder, this.fields.sortBy));\n }\n else {\n this.curViewDS = dataSource;\n }\n };\n ListView.prototype.isInAnimation = function () {\n return this.curUL.classList.contains('.e-animate');\n };\n ListView.prototype.setLocalData = function () {\n var _this = this;\n this.trigger('actionBegin');\n if (this.dataSource instanceof DataManager) {\n this.dataSource.executeQuery(this.getQuery()).then(function (e) {\n if (_this.isDestroyed) {\n return;\n }\n _this.localData = e.result;\n _this.renderList();\n _this.trigger('actionComplete', e);\n }).catch(function (e) {\n if (_this.isDestroyed) {\n return;\n }\n _this.trigger('actionFailure', e);\n });\n }\n else if (!this.dataSource || !this.dataSource.length) {\n var ul = this.element.querySelector('ul');\n if (ul) {\n remove(ul);\n this.setProperties({ dataSource: ListBase.createJsonFromElement(ul) }, true);\n this.localData = this.dataSource;\n this.renderList();\n this.trigger('actionComplete', { data: this.localData });\n }\n }\n else {\n this.localData = this.dataSource;\n this.renderList();\n this.trigger('actionComplete', { data: this.localData });\n }\n };\n ListView.prototype.reRender = function () {\n this.element.innerHTML = '';\n this.headerEle = this.ulElement = this.liCollection = undefined;\n this.setLocalData();\n this.header();\n };\n ListView.prototype.resetCurrentList = function () {\n this.setViewDataSource(this.curViewDS);\n this.contentContainer.innerHTML = '';\n this.createList();\n this.renderIntoDom(this.curUL);\n };\n ListView.prototype.createList = function () {\n this.currentLiElements = [];\n this.isNestedList = false;\n this.ulElement = this.curUL = ListBase.createList(this.createElement, this.curViewDS, this.listBaseOption);\n this.liCollection = this.curUL.querySelectorAll('.' + classNames.listItem);\n };\n ListView.prototype.renderSubList = function (li) {\n var uID = li.getAttribute('data-uid');\n if (li.classList.contains(classNames.hasChild) && uID) {\n var ul = closest(li.parentNode, '.' + classNames.parentItem);\n var ele = this.element.querySelector('[pid=\\'' + uID + '\\']');\n this.curDSLevel.push(uID);\n this.setViewDataSource(this.getSubDS());\n if (!ele) {\n var data = this.curViewDS;\n ele = ListBase.createListFromJson(this.createElement, data, this.listBaseOption, this.curDSLevel.length);\n ele.setAttribute('pID', uID);\n ele.style.display = 'none';\n this.renderIntoDom(ele);\n }\n this.switchView(ul, ele);\n this.liCollection = this.curUL.querySelectorAll('.' + classNames.listItem);\n if (this.selectedItems) {\n var fieldData = getFieldValues(this.selectedItems.data, this.listBaseOption.fields);\n this.header((fieldData[this.listBaseOption.fields.text]), true);\n }\n this.selectedLI = undefined;\n }\n };\n ListView.prototype.renderIntoDom = function (ele) {\n this.contentContainer.appendChild(ele);\n };\n ListView.prototype.renderList = function (data) {\n this.setViewDataSource(data);\n if (this.enableVirtualization && Object.keys(this.dataSource).length) {\n if (this.template || this.groupTemplate) {\n this.listBaseOption.template = null;\n this.listBaseOption.groupTemplate = null;\n this.listBaseOption.itemCreated = this.virtualizationModule.createUIItem.bind(this.virtualizationModule);\n }\n this.virtualizationModule.uiVirtualization();\n }\n else {\n this.createList();\n this.contentContainer = this.createElement('div', { className: classNames.content });\n this.element.appendChild(this.contentContainer);\n this.renderIntoDom(this.ulElement);\n }\n };\n ListView.prototype.getElementUID = function (obj) {\n var fields = {};\n if (obj instanceof Element) {\n fields[this.fields.id] = obj.getAttribute('data-uid');\n }\n else {\n fields = obj;\n }\n return fields;\n };\n /**\n * It is used to Initialize the control rendering.\n */\n ListView.prototype.render = function () {\n this.element.classList.add(classNames.root);\n attributes(this.element, { role: 'list', tabindex: '0' });\n this.setCSSClass();\n this.setEnableRTL();\n this.setEnable();\n this.setSize();\n this.wireEvents();\n this.header();\n this.setLocalData();\n this.setHTMLAttribute();\n this.rippleFn = rippleEffect(this.element, {\n selector: '.' + classNames.listItem\n });\n };\n /**\n * It is used to destroy the ListView component.\n */\n ListView.prototype.destroy = function () {\n this.unWireEvents();\n var classAr = [classNames.root, this.cssClass, classNames.disable, 'e-rtl',\n 'e-has-header', 'e-control'];\n removeClass([this.element], classAr);\n this.rippleFn();\n this.element.removeAttribute('role');\n this.element.removeAttribute('tabindex');\n this.element.innerHTML = '';\n this.curUL = this.ulElement = this.liCollection = this.headerEle = undefined;\n _super.prototype.destroy.call(this);\n };\n /**\n * It helps to switch back from navigated sub list.\n */\n ListView.prototype.back = function () {\n var pID = this.curDSLevel[this.curDSLevel.length - 1];\n if (pID === undefined || this.isInAnimation()) {\n return;\n }\n this.curDSLevel.pop();\n this.setViewDataSource(this.getSubDS());\n var toUL = this.element.querySelector('[data-uid=\\'' + pID + '\\']');\n var fromUL = this.curUL;\n if (!toUL) {\n this.createList();\n this.renderIntoDom(this.ulElement);\n toUL = this.curUL;\n }\n else {\n toUL = toUL.parentElement;\n }\n var fieldData = getFieldValues(this.curDSJSON, this.listBaseOption.fields);\n var text = fieldData[this.fields.text];\n this.switchView(fromUL, toUL, true);\n this.removeFocus();\n var li = this.element.querySelector('[data-uid=\\'' + pID + '\\']');\n li.classList.add(classNames.focused);\n if (this.showCheckBox && li.querySelector('.' + classNames.checkboxIcon).classList.contains(classNames.checked)) {\n li.setAttribute('aria-selected', 'true');\n }\n else {\n li.classList.remove(classNames.selected);\n li.setAttribute('aria-selected', 'false');\n }\n this.liCollection = this.curUL.querySelectorAll('.' + classNames.listItem);\n this.header((this.curDSLevel.length ? text : this.headerTitle), (this.curDSLevel.length ? true : false));\n };\n /**\n * It is used to select the list item from the ListView.\n * @param {Fields|HTMLElement} obj - We can pass element Object or Fields as Object with ID and Text fields.\n */\n ListView.prototype.selectItem = function (obj) {\n if (!isNullOrUndefined(obj)) {\n if (this.enableVirtualization) {\n this.virtualizationModule.selectItem(obj);\n }\n else if (this.showCheckBox) {\n this.setCheckboxLI(this.getLiFromObjOrElement(obj));\n }\n else {\n this.setSelectLI(this.getLiFromObjOrElement(obj));\n }\n }\n };\n ListView.prototype.getLiFromObjOrElement = function (obj) {\n var li;\n if (!isNullOrUndefined(obj)) {\n if (typeof this.dataSource[0] === 'string' || typeof this.dataSource[0] === 'number') {\n if (obj instanceof Element) {\n var uid = obj.getAttribute('data-uid').toString();\n for (var i = 0; i < this.liCollection.length; i++) {\n if (this.liCollection[i].getAttribute('data-uid').toString() === uid) {\n li = this.liCollection[i];\n break;\n }\n }\n }\n else {\n Array.prototype.some.call(this.curUL.querySelectorAll('.' + classNames.listItem), function (item) {\n if (item.innerText.trim() === obj.toString()) {\n li = item;\n return true;\n }\n else {\n return false;\n }\n });\n }\n }\n else {\n var resultJSON = this.getItemData(obj);\n var fieldData = getFieldValues(resultJSON, this.listBaseOption.fields);\n if (resultJSON) {\n li = this.element.querySelector('[data-uid=\"'\n + fieldData[this.fields.id] + '\"]');\n if (isNullOrUndefined(li)) {\n var curLi = this.element.querySelectorAll('.' + classNames.listItem);\n for (var i = 0; i < curLi.length; i++) {\n if (curLi[i].innerText.trim() === resultJSON.text) {\n li = curLi[i];\n }\n }\n }\n }\n }\n }\n return li;\n };\n /**\n * It is used to select multiple list item from the ListView.\n * @param {Fields[] | HTMLElement[]} obj - We can pass array of elements or array of field Object with ID and Text fields.\n */\n ListView.prototype.selectMultipleItems = function (obj) {\n if (!isNullOrUndefined(obj)) {\n for (var i = 0; i < obj.length; i++) {\n if (!isNullOrUndefined(obj[i])) {\n this.selectItem(obj[i]);\n }\n }\n }\n };\n ListView.prototype.getParentId = function () {\n var parentId = [];\n if (this.isNestedList) {\n for (var i = this.curDSLevel.length - 1; i >= 0; i--) {\n parentId.push(this.curDSLevel[i]);\n }\n }\n return parentId;\n };\n /**\n * It is used to get the currently [here](http://ej2.syncfusion.com/documentation/list-view/api-selectedItem.html?lang=typescript)\n * item details from the list items.\n */\n ListView.prototype.getSelectedItems = function () {\n this.selectedId = [];\n if (this.enableVirtualization) {\n return this.virtualizationModule.getSelectedItems();\n }\n else if (this.showCheckBox) {\n var liCollection = this.curUL.getElementsByClassName(classNames.selected);\n var liTextCollection = [];\n var liDataCollection = [];\n this.selectedId = [];\n var dataParent = [];\n for (var i = 0; i < liCollection.length; i++) {\n if (typeof this.dataSource[0] === 'string' || typeof this.dataSource[0] === 'number') {\n liTextCollection.push(liCollection[i].innerText.trim());\n }\n else {\n var tempData = this.getItemData(liCollection[i]);\n var fieldData = getFieldValues(tempData, this.listBaseOption.fields);\n if (this.isNestedList) {\n dataParent.push({ data: tempData, parentId: this.getParentId() });\n }\n else {\n liDataCollection.push(tempData);\n }\n if (fieldData) {\n liTextCollection.push(fieldData[this.listBaseOption.fields.text]);\n this.selectedId.push(fieldData[this.listBaseOption.fields.id]);\n }\n else {\n liTextCollection.push(undefined);\n this.selectedId.push(undefined);\n }\n }\n }\n if (typeof this.dataSource[0] === 'string' || typeof this.dataSource[0] === 'number') {\n return { item: liCollection, data: this.dataSource, text: liTextCollection };\n }\n if (this.isNestedList) {\n return { item: liCollection, data: dataParent, text: liTextCollection };\n }\n else {\n return { item: liCollection, data: liDataCollection, text: liTextCollection };\n }\n }\n else {\n var liElement = this.element.getElementsByClassName(classNames.selected)[0];\n var fieldData = getFieldValues(this.getItemData(liElement), this.listBaseOption.fields);\n if (typeof this.dataSource[0] === 'string' || typeof this.dataSource[0] === 'number') {\n return (!isNullOrUndefined(liElement)) ? {\n item: liElement, data: this.dataSource,\n text: liElement.innerText.trim()\n } : undefined;\n }\n else {\n if (isNullOrUndefined(fieldData) || isNullOrUndefined(liElement)) {\n return undefined;\n }\n else {\n this.selectedId.push(fieldData[this.listBaseOption.fields.id]);\n return {\n text: fieldData[this.listBaseOption.fields.text], item: liElement,\n data: this.getItemData(liElement)\n };\n }\n }\n }\n };\n /**\n * It is used to find out an item details from the current list.\n * @param {Fields|HTMLElement} obj - We can pass element Object or Fields as Object with ID and Text fields.\n */\n ListView.prototype.findItem = function (obj) {\n return this.getItemData(obj);\n };\n /**\n * A function that used to enable the disabled list items based on passed element.\n * @param {Fields|HTMLElement} obj - We can pass element Object or Fields as Object with ID and Text fields.\n */\n ListView.prototype.enableItem = function (obj) {\n this.setItemState(obj, true);\n if (this.enableVirtualization) {\n this.virtualizationModule.enableItem(obj);\n }\n };\n /**\n * It is used to disable the list items based on passed element.\n * @param {Fields|HTMLElement} obj - We can pass element Object or Fields as Object with ID and Text fields.\n */\n ListView.prototype.disableItem = function (obj) {\n this.setItemState(obj, false);\n if (this.enableVirtualization) {\n this.virtualizationModule.disableItem(obj);\n }\n };\n //A function that used to set state of the list item like enable, disable.\n ListView.prototype.setItemState = function (obj, isEnable) {\n var resultJSON = this.getItemData(obj);\n var fieldData = getFieldValues(resultJSON, this.listBaseOption.fields);\n if (resultJSON) {\n var li = this.element.querySelector('[data-uid=\"' + fieldData[this.fields.id] + '\"]');\n if (isEnable) {\n if (li) {\n li.classList.remove(classNames.disable);\n }\n delete resultJSON[this.fields.enabled];\n }\n else if (!isEnable) {\n if (li) {\n li.classList.add(classNames.disable);\n }\n resultJSON[this.fields.enabled] = false;\n }\n }\n };\n /**\n * It is used to show an list item from the ListView.\n * @param {Fields|HTMLElement} obj - We can pass element Object or Fields as Object with ID and Text fields.\n */\n ListView.prototype.showItem = function (obj) {\n this.showHideItem(obj, false, '');\n if (this.enableVirtualization) {\n this.virtualizationModule.showItem(obj);\n }\n };\n /**\n * It is used to hide an item from the ListView.\n * @param {Fields|HTMLElement} obj - We can pass element Object or Fields as Object with ID and Text fields.\n */\n ListView.prototype.hideItem = function (obj) {\n this.showHideItem(obj, true, 'none');\n if (this.enableVirtualization) {\n this.virtualizationModule.hideItem(obj);\n }\n };\n ListView.prototype.showHideItem = function (obj, isHide, display) {\n var resultJSON = this.getItemData(obj);\n var fieldData = getFieldValues(resultJSON, this.listBaseOption.fields);\n if (resultJSON) {\n var li = this.element.querySelector('[data-uid=\"' + fieldData[this.fields.id] + '\"]');\n if (li) {\n li.style.display = display;\n }\n if (isHide) {\n resultJSON[this.fields.isVisible] = false;\n }\n else {\n delete resultJSON[this.fields.isVisible];\n }\n }\n };\n /**\n * It adds new item to current ListView.\n * To add a new item in the list view, we need to pass ‘data’ as array or object and ‘fields’ as object.\n * For example fields: { text: 'Name', tooltip: 'Name', id:'id'}\n * @param {{[key:string]:Object}[]} data - Array JSON Data that need to add.\n * @param {Fields} fields - Fields as an Object with ID and Text fields.\n */\n ListView.prototype.addItem = function (data, fields) {\n var _this = this;\n if (fields === void 0) { fields = undefined; }\n if (data instanceof Array) {\n if (this.enableVirtualization) {\n this.virtualizationModule.addItem(data, fields);\n }\n else {\n var ds = this.findItemFromDS(this.dataSource, fields);\n var fieldData = getFieldValues(ds, this.listBaseOption.fields);\n var child = fieldData[this.fields.child];\n if (!child) {\n child = [];\n }\n child = child.concat(data);\n if (ds instanceof Array) {\n data.forEach(function (dataSource) {\n _this.dataSource.push(dataSource);\n _this.setViewDataSource(_this.dataSource);\n if (_this.ulElement) {\n var index = _this.curViewDS.indexOf(dataSource);\n _this.addListItem(dataSource, index);\n var curViewDS = _this.curViewDS[index - 1];\n if (curViewDS && curViewDS.isHeader && curViewDS.items.length === 1) {\n _this.addListItem(curViewDS, (index - 1));\n }\n }\n else {\n _this.reRender();\n }\n });\n this.liCollection = this.curUL.querySelectorAll('.' + classNames.listItem);\n }\n else {\n ds[this.fields.child] = child;\n this.reRender();\n }\n }\n }\n };\n ListView.prototype.addListItem = function (dataSource, index) {\n var target = this.getLiFromObjOrElement(this.curViewDS[index + 1]) ||\n this.getLiFromObjOrElement(this.curViewDS[index + 2]) || null;\n var li = ListBase.createListItemFromJson(this.createElement, [dataSource], this.listBaseOption);\n this.ulElement.insertBefore(li[0], target);\n };\n /**\n * A function that removes the item from data source based on passed element like fields: { text: 'Name', tooltip: 'Name', id:'id'}\n * @param {Fields|HTMLElement} obj - We can pass element Object or Fields as Object with ID and Text fields.\n */\n ListView.prototype.removeItem = function (obj) {\n if (this.enableVirtualization) {\n this.virtualizationModule.removeItem(obj);\n }\n else {\n this.removeItemFromList(obj);\n }\n };\n ListView.prototype.removeItemFromList = function (obj) {\n var fields = obj instanceof Element ? this.getElementUID(obj) : obj;\n var dataSource;\n dataSource = this.findItemFromDS(this.dataSource, fields, true);\n if (dataSource) {\n var data = void 0;\n data = this.findItemFromDS(dataSource, fields);\n var index = this.curViewDS.indexOf(data);\n if (this.fields.groupBy && this.curViewDS[index - 1] &&\n this.curViewDS[index - 1].isHeader &&\n (this.curViewDS[index - 1])\n .items.length === 1) {\n detach(this.getLiFromObjOrElement(this.curViewDS[index - 1]));\n }\n if (this.getLiFromObjOrElement(obj)) {\n detach(this.getLiFromObjOrElement(obj));\n }\n var dsIndex = dataSource.indexOf(data);\n dataSource.splice(dsIndex, 1);\n this.setViewDataSource(this.dataSource);\n this.liCollection = Array.prototype.slice.call(this.element.querySelectorAll('.' + classNames.listItem));\n }\n };\n /**\n * A function that removes multiple item from list view based on given input.\n * @param {Fields[] | HTMLElement[]} obj - We can pass array of elements or array of field Object with ID and Text fields.\n */\n ListView.prototype.removeMultipleItems = function (obj) {\n if (obj.length) {\n for (var i = 0; i < obj.length; i++) {\n if (this.enableVirtualization) {\n this.removeItem(obj[i]);\n }\n else {\n this.removeItemFromList(obj[i]);\n }\n }\n }\n };\n // Module Required function\n ListView.prototype.getModuleName = function () {\n return 'listview';\n };\n ListView.prototype.requiredModules = function () {\n var modules = [];\n if (this.enableVirtualization) {\n modules.push({ args: [this], member: 'virtualization' });\n }\n return modules;\n };\n /**\n * Get the properties to be maintained in the persisted state.\n */\n ListView.prototype.getPersistData = function () {\n return this.addOnPersist(['cssClass', 'enableRtl', 'htmlAttributes',\n 'enable', 'fields', 'animation', 'headerTitle',\n 'sortOrder', 'showIcon', 'height', 'width', 'showCheckBox', 'checkBoxPosition']);\n };\n __decorate([\n Property()\n ], ListView.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], ListView.prototype, \"enableVirtualization\", void 0);\n __decorate([\n Property({})\n ], ListView.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property(true)\n ], ListView.prototype, \"enable\", void 0);\n __decorate([\n Property([])\n ], ListView.prototype, \"dataSource\", void 0);\n __decorate([\n Property()\n ], ListView.prototype, \"query\", void 0);\n __decorate([\n Complex(ListBase.defaultMappedFields, FieldSettings)\n ], ListView.prototype, \"fields\", void 0);\n __decorate([\n Property({ effect: 'SlideLeft', duration: 400, easing: 'ease' })\n ], ListView.prototype, \"animation\", void 0);\n __decorate([\n Property('None')\n ], ListView.prototype, \"sortOrder\", void 0);\n __decorate([\n Property(false)\n ], ListView.prototype, \"showIcon\", void 0);\n __decorate([\n Property(false)\n ], ListView.prototype, \"showCheckBox\", void 0);\n __decorate([\n Property('Left')\n ], ListView.prototype, \"checkBoxPosition\", void 0);\n __decorate([\n Property('')\n ], ListView.prototype, \"headerTitle\", void 0);\n __decorate([\n Property(false)\n ], ListView.prototype, \"showHeader\", void 0);\n __decorate([\n Property('')\n ], ListView.prototype, \"height\", void 0);\n __decorate([\n Property('')\n ], ListView.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], ListView.prototype, \"template\", void 0);\n __decorate([\n Property(null)\n ], ListView.prototype, \"headerTemplate\", void 0);\n __decorate([\n Property(null)\n ], ListView.prototype, \"groupTemplate\", void 0);\n __decorate([\n Event()\n ], ListView.prototype, \"select\", void 0);\n __decorate([\n Event()\n ], ListView.prototype, \"actionBegin\", void 0);\n __decorate([\n Event()\n ], ListView.prototype, \"actionComplete\", void 0);\n __decorate([\n Event()\n ], ListView.prototype, \"actionFailure\", void 0);\n ListView = __decorate([\n NotifyPropertyChanges\n ], ListView);\n return ListView;\n}(Component));\nexport { ListView };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { EventHandler, Property, Internationalization, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { KeyboardEvents, Animation, Browser } from '@syncfusion/ej2-base';\nimport { cldrData, L10n, Component, getDefaultDateObject, rippleEffect, Event } from '@syncfusion/ej2-base';\nimport { remove, addClass, removeClass, closest, append, attributes, setStyleAttribute } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, formatUnit, getValue, getUniqueID } from '@syncfusion/ej2-base';\nimport { Popup } from '@syncfusion/ej2-popups';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { ListBase, cssClass as ListBaseClasses } from '@syncfusion/ej2-lists';\nvar WRAPPERCLASS = 'e-time-wrapper';\nvar POPUP = 'e-popup';\nvar ERROR = 'e-error';\nvar POPUPDIMENSION = '240px';\nvar DAY = new Date().getDate();\nvar MONTH = new Date().getMonth();\nvar YEAR = new Date().getFullYear();\nvar ROOT = 'e-timepicker';\nvar RTL = 'e-rtl';\nvar CONTENT = 'e-content';\nvar SELECTED = 'e-active';\nvar HOVER = 'e-hover';\nvar NAVIGATION = 'e-navigation';\nvar DISABLED = 'e-disabled';\nvar ICONANIMATION = 'e-icon-anim';\nvar FOCUS = 'e-input-focus';\nvar DEVICE = 'e-device';\nvar LISTCLASS = ListBaseClasses.li;\nvar HALFPOSITION = 2;\nvar ANIMATIONDURATION = 50;\nexport var TimePickerBase;\n(function (TimePickerBase) {\n // tslint:disable-next-line\n function createListItems(createEl, min, max, globalize, timeFormat, step) {\n var start;\n var end;\n var interval = step * 60000;\n var listItems = [];\n var timeCollections = [];\n start = +(min.setMilliseconds(0));\n end = +(max.setMilliseconds(0));\n while (end >= start) {\n timeCollections.push(start);\n listItems.push(globalize.formatDate(new Date(start), { format: timeFormat, type: 'time' }));\n start += interval;\n }\n var listTag = ListBase.createList(createEl, listItems, null, true);\n return { collection: timeCollections, list: listTag };\n }\n TimePickerBase.createListItems = createListItems;\n})(TimePickerBase || (TimePickerBase = {}));\n/**\n * TimePicker is an intuitive interface component which provides an options to select a time value\n * from popup list or to set a desired time value.\n * ```\n *
\n * \n * ```\n */\nvar TimePicker = /** @class */ (function (_super) {\n __extends(TimePicker, _super);\n /**\n * Constructor for creating the widget\n */\n function TimePicker(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.liCollections = [];\n _this.timeCollections = [];\n _this.disableItemCollection = [];\n return _this;\n }\n /**\n * Initialize the event handler\n * @private\n */\n TimePicker.prototype.preRender = function () {\n this.keyConfigure = {\n enter: 'enter',\n escape: 'escape',\n end: 'end',\n tab: 'tab',\n home: 'home',\n down: 'downarrow',\n up: 'uparrow',\n left: 'leftarrow',\n right: 'rightarrow',\n open: 'alt+downarrow',\n close: 'alt+uparrow'\n };\n this.cloneElement = this.element.cloneNode(true);\n this.inputElement = this.element;\n this.angularTag = null;\n if (this.element.tagName === 'EJS-TIMEPICKER') {\n this.angularTag = this.element.tagName;\n this.inputElement = this.createElement('input');\n this.element.appendChild(this.inputElement);\n }\n };\n // element creation\n TimePicker.prototype.render = function () {\n this.initialize();\n this.createInputElement();\n this.setTimeAllowEdit();\n this.setEnable();\n this.validateInterval();\n this.bindEvents();\n this.validateDisable();\n this.setValue(this.getFormattedValue(this.value));\n };\n TimePicker.prototype.setTimeAllowEdit = function () {\n if (this.allowEdit) {\n if (!this.readonly) {\n this.inputElement.removeAttribute('readonly');\n }\n }\n else {\n attributes(this.inputElement, { 'readonly': '' });\n }\n };\n TimePicker.prototype.validateDisable = function () {\n this.setMinMax(this.initMin, this.initMax);\n this.popupCreation();\n this.popupObj.hide();\n if ((!isNaN(+this.value) && this.value !== null)) {\n if (!this.valueIsDisable(this.value)) {\n //disable value given in value property so reset the date based on current date\n if (this.strictMode) {\n this.resetState();\n }\n this.initValue = null;\n this.initMax = this.getDateObject(this.initMax);\n this.initMin = this.getDateObject(this.initMin);\n this.timeCollections = this.liCollections = [];\n this.setMinMax(this.initMin, this.initMax);\n }\n }\n };\n TimePicker.prototype.validationAttribute = function (target, input) {\n var name = target.getAttribute('name') ? target.getAttribute('name') : target.getAttribute('id');\n input.setAttribute('name', name);\n target.removeAttribute('name');\n var attributes = ['required', 'aria-required', 'form'];\n for (var i = 0; i < attributes.length; i++) {\n if (isNullOrUndefined(target.getAttribute(attributes[i]))) {\n continue;\n }\n var attr = target.getAttribute(attributes[i]);\n input.setAttribute(attributes[i], attr);\n target.removeAttribute(attributes[i]);\n }\n };\n TimePicker.prototype.initialize = function () {\n this.globalize = new Internationalization(this.locale);\n this.defaultCulture = new Internationalization('en');\n // persist the value property.\n this.setProperties({ value: this.checkDateValue(new Date('' + this.value)) }, true);\n this.setProperties({ min: this.checkDateValue(new Date('' + this.min)) }, true);\n this.setProperties({ max: this.checkDateValue(new Date('' + this.max)) }, true);\n if (this.angularTag !== null) {\n this.validationAttribute(this.element, this.inputElement);\n }\n this.checkAttributes(); //check the input element attributes\n var localeText = { placeholder: this.placeholder };\n this.l10n = new L10n('timepicker', localeText, this.locale);\n this.setProperties({ placeholder: this.placeholder || this.l10n.getConstant('placeholder') }, true);\n this.initValue = this.checkDateValue(this.value);\n this.initMin = this.checkDateValue(this.min);\n this.initMax = this.checkDateValue(this.max);\n this.isNavigate = this.isPreventBlur = this.isTextSelected = false;\n this.activeIndex = this.valueWithMinutes = this.prevDate = null;\n if (!isNullOrUndefined(this.element.getAttribute('id'))) {\n if (this.angularTag !== null) {\n this.inputElement.id = this.element.getAttribute('id') + '_input';\n }\n }\n else {\n //for angular case\n this.element.id = getUniqueID('ej2_timepicker');\n if (this.angularTag !== null) {\n attributes(this.inputElement, { 'id': this.element.id + '_input' });\n }\n }\n if (isNullOrUndefined(this.inputElement.getAttribute('name'))) {\n attributes(this.inputElement, { 'name': this.element.id });\n }\n };\n TimePicker.prototype.checkDateValue = function (value) {\n return (!isNullOrUndefined(value) && value instanceof Date && !isNaN(+value)) ? value : null;\n };\n TimePicker.prototype.createInputElement = function () {\n this.inputWrapper = Input.createInput({\n element: this.inputElement,\n floatLabelType: this.floatLabelType,\n properties: {\n readonly: this.readonly,\n placeholder: this.placeholder,\n cssClass: this.cssClass,\n enabled: this.enabled,\n enableRtl: this.enableRtl,\n showClearButton: this.showClearButton,\n },\n buttons: [' e-input-group-icon e-time-icon e-icons']\n }, this.createElement);\n this.inputWrapper.container.style.width = this.setWidth(this.width);\n attributes(this.inputElement, {\n 'aria-haspopup': 'true', 'aria-autocomplete': 'list', 'tabindex': '0', 'aria-activedescendant': 'null',\n 'aria-owns': this.element.id + '_options', 'aria-expanded': 'false', 'role': 'combobox', 'autocomplete': 'off',\n 'autocorrect': 'off', 'autocapitalize': 'off', 'spellcheck': 'false', 'aria-disabled': 'false', 'aria-invalid': 'false'\n });\n if (!this.isNullOrEmpty(this.inputStyle)) {\n Input.addAttributes({ 'style': this.inputStyle }, this.inputElement);\n }\n addClass([this.inputWrapper.container], WRAPPERCLASS);\n };\n // destroy function\n TimePicker.prototype.destroy = function () {\n this.hide();\n this.unBindEvents();\n var ariaAttribute = {\n 'aria-haspopup': 'true', 'aria-autocomplete': 'list', 'tabindex': '0', 'aria-activedescendant': 'null',\n 'aria-owns': this.element.id + '_options', 'aria-expanded': 'false', 'role': 'combobox', 'autocomplete': 'off',\n 'autocorrect': 'off', 'autocapitalize': 'off', 'spellcheck': 'false', 'aria-disabled': 'true', 'aria-invalid': 'false'\n };\n if (this.inputElement) {\n Input.removeAttributes(ariaAttribute, this.inputElement);\n if (this.angularTag === null) {\n this.inputWrapper.container.parentElement.appendChild(this.inputElement);\n }\n this.ensureInputAttribute();\n this.enableElement([this.inputElement]);\n this.inputElement.classList.remove('e-input');\n if (isNullOrUndefined(this.cloneElement.getAttribute('disabled'))) {\n Input.setEnabled(true, this.inputElement, this.floatLabelType);\n }\n }\n if (this.inputWrapper.container) {\n remove(this.inputWrapper.container);\n }\n this.inputWrapper = this.popupWrapper = this.cloneElement = undefined;\n this.liCollections = this.timeCollections = this.disableItemCollection = [];\n if (!isNullOrUndefined(this.rippleFn)) {\n this.rippleFn();\n }\n _super.prototype.destroy.call(this);\n var form = closest(this.element, 'form');\n if (form) {\n EventHandler.remove(form, 'reset', this.formResetHandler.bind(this));\n }\n };\n TimePicker.prototype.ensureInputAttribute = function () {\n for (var i = 0; i < this.inputElement.attributes.length; i++) {\n var prop = this.inputElement.attributes[i].name;\n if (isNullOrUndefined(this.cloneElement.getAttribute(prop))) {\n if (prop.toLowerCase() === 'value' || isNullOrUndefined(this.cloneElement.getAttribute('value'))) {\n this.inputElement.value = '';\n }\n this.inputElement.removeAttribute(prop);\n }\n }\n };\n //popup creation\n TimePicker.prototype.popupCreation = function () {\n this.popupWrapper = this.createElement('div', {\n className: ROOT + ' ' + POPUP,\n attrs: { 'id': this.element.id + '_popup', 'style': 'visibility:hidden' }\n });\n if (!isNullOrUndefined(this.cssClass)) {\n this.popupWrapper.classList.add(this.cssClass);\n }\n if (!isNullOrUndefined(this.step) && this.step > 0) {\n this.generateList();\n append([this.listWrapper], this.popupWrapper);\n }\n document.body.appendChild(this.popupWrapper);\n this.addSelection();\n this.renderPopup();\n this.setScrollPosition();\n };\n TimePicker.prototype.getPopupHeight = function () {\n var height = parseInt(POPUPDIMENSION, 10);\n var popupHeight = this.popupWrapper.getBoundingClientRect().height;\n return popupHeight > height ? height : popupHeight;\n };\n TimePicker.prototype.generateList = function () {\n this.createListItems();\n this.wireListEvents();\n var rippleModel = { duration: 300, selector: '.' + LISTCLASS };\n this.rippleFn = rippleEffect(this.listWrapper, rippleModel);\n this.liCollections = this.listWrapper.querySelectorAll('.' + LISTCLASS);\n };\n TimePicker.prototype.popupCalculation = function () {\n var left = 0;\n if (Browser.isDevice) {\n var firstItem = this.isEmptyList() ? this.listTag : this.liCollections[0];\n left = -(parseInt(getComputedStyle(firstItem).textIndent, 10) -\n (this.enableRtl ? parseInt(getComputedStyle(this.inputElement).paddingRight, 10) :\n parseInt(getComputedStyle(this.inputElement).paddingLeft, 10)));\n }\n return left;\n };\n TimePicker.prototype.isEmptyList = function () {\n return !isNullOrUndefined(this.liCollections) && this.liCollections.length === 0 ||\n isNullOrUndefined(this.liCollections);\n };\n TimePicker.prototype.renderPopup = function () {\n var _this = this;\n this.containerStyle = this.inputWrapper.container.getBoundingClientRect();\n var offset = Browser.isDevice ? this.setPopupPosition() : 2;\n this.popupObj = new Popup(this.popupWrapper, {\n width: this.setPopupWidth(this.width),\n zIndex: this.zIndex,\n targetType: 'relative',\n collision: { X: 'flip', Y: 'flip' },\n relateTo: this.inputWrapper.container,\n position: { X: 'left', Y: 'bottom' },\n enableRtl: this.enableRtl,\n offsetY: offset,\n offsetX: this.popupCalculation(),\n open: function () {\n _this.popupWrapper.style.visibility = 'visible';\n addClass([_this.inputWrapper.buttons[0]], SELECTED);\n }, close: function () {\n removeClass([_this.inputWrapper.buttons[0]], SELECTED);\n _this.unWireListEvents();\n _this.inputElement.setAttribute('aria-activedescendant', 'null');\n remove(_this.popupObj.element);\n _this.popupObj.destroy();\n _this.popupWrapper.innerHTML = '';\n _this.listWrapper = _this.popupWrapper = _this.listTag = undefined;\n }\n });\n if (!Browser.isDevice) {\n this.popupObj.collision = { X: 'none', Y: 'flip' };\n }\n this.popupObj.element.style.maxHeight = POPUPDIMENSION;\n };\n //util function\n TimePicker.prototype.getFormattedValue = function (value) {\n if (isNullOrUndefined(this.checkDateValue(value))) {\n return null;\n }\n else {\n return this.globalize.formatDate(value, { skeleton: 'medium', type: 'time' });\n }\n };\n TimePicker.prototype.getDateObject = function (text) {\n if (!this.isNullOrEmpty(text)) {\n var dateValue = this.createDateObj(text);\n var value = !this.isNullOrEmpty(this.initValue);\n if (this.checkDateValue(dateValue)) {\n var date = value ? this.initValue.getDate() : DAY;\n var month = value ? this.initValue.getMonth() : MONTH;\n var year = value ? this.initValue.getFullYear() : YEAR;\n return new Date(year, month, date, dateValue.getHours(), dateValue.getMinutes(), dateValue.getSeconds());\n }\n }\n return null;\n };\n TimePicker.prototype.removeErrorClass = function () {\n removeClass([this.inputWrapper.container], ERROR);\n attributes(this.inputElement, { 'aria-invalid': 'false' });\n };\n TimePicker.prototype.checkErrorState = function (val) {\n var value = this.getDateObject(val);\n if (this.validateState(value)) {\n this.removeErrorClass();\n }\n else {\n addClass([this.inputWrapper.container], ERROR);\n attributes(this.inputElement, { 'aria-invalid': 'true' });\n }\n };\n TimePicker.prototype.validateInterval = function () {\n if (!isNullOrUndefined(this.step) && this.step > 0) {\n this.enableElement([this.inputWrapper.buttons[0]]);\n }\n else {\n this.disableTimeIcon();\n }\n };\n TimePicker.prototype.disableTimeIcon = function () {\n this.disableElement([this.inputWrapper.buttons[0]]);\n this.hide();\n };\n TimePicker.prototype.disableElement = function (element) {\n addClass(element, DISABLED);\n };\n TimePicker.prototype.enableElement = function (element) {\n removeClass(element, DISABLED);\n };\n TimePicker.prototype.selectInputText = function () {\n this.inputElement.setSelectionRange(0, (this.inputElement).value.length);\n };\n TimePicker.prototype.getMeridianText = function () {\n var meridian;\n if (this.locale === 'en' || this.locale === 'en-US') {\n meridian = getValue('dayPeriods.format.wide', getDefaultDateObject());\n }\n else {\n meridian = getValue('main.' + '' + this.locale + '.dates.calendars.gregorian.dayPeriods.format.abbreviated', cldrData);\n }\n return meridian;\n };\n TimePicker.prototype.getCursorSelection = function () {\n var input = (this.inputElement);\n var start = 0;\n var end = 0;\n if (!isNaN(input.selectionStart)) {\n start = input.selectionStart;\n end = input.selectionEnd;\n }\n return { start: Math.abs(start), end: Math.abs(end) };\n };\n TimePicker.prototype.getActiveElement = function () {\n if (!isNullOrUndefined(this.popupWrapper)) {\n return this.popupWrapper.querySelectorAll('.' + SELECTED);\n }\n else {\n return null;\n }\n };\n TimePicker.prototype.isNullOrEmpty = function (value) {\n if (isNullOrUndefined(value) || (typeof value === 'string' && value.trim() === '')) {\n return true;\n }\n else {\n return false;\n }\n };\n TimePicker.prototype.setWidth = function (width) {\n if (typeof width === 'number') {\n width = formatUnit(width);\n }\n else if (typeof width === 'string') {\n width = (width.match(/px|%|em/)) ? width : formatUnit(width);\n }\n else {\n width = '100%';\n }\n return width;\n };\n TimePicker.prototype.setPopupWidth = function (width) {\n width = this.setWidth(width);\n if (width.indexOf('%') > -1) {\n var inputWidth = this.containerStyle.width * parseFloat(width) / 100;\n width = inputWidth.toString() + 'px';\n }\n if (Browser.isDevice) {\n var firstItem = this.isEmptyList() ? this.listTag : this.liCollections[0];\n width = (parseInt(width, 10) + (parseInt(getComputedStyle(firstItem).textIndent, 10) -\n parseInt(getComputedStyle(this.inputElement).textIndent, 10) +\n parseInt(getComputedStyle(this.inputElement.parentElement).borderLeftWidth, 10)) * 2) + 'px';\n }\n return width;\n };\n TimePicker.prototype.setScrollPosition = function () {\n var listHeight = this.getPopupHeight();\n var element;\n element = this.selectedElement;\n if (!isNullOrUndefined(element)) {\n this.findScrollTop(element);\n }\n else if (this.popupWrapper && this.checkDateValue(this.scrollTo)) {\n this.setScrollTo();\n }\n };\n TimePicker.prototype.findScrollTop = function (element) {\n var listHeight = this.getPopupHeight();\n var nextEle = element.nextElementSibling;\n var height = nextEle ? nextEle.offsetTop : element.offsetTop;\n var liHeight = element.getBoundingClientRect().height;\n if ((height + element.offsetTop) > listHeight) {\n this.popupWrapper.scrollTop = nextEle ? (height - (listHeight / HALFPOSITION + liHeight / HALFPOSITION)) : height;\n }\n else {\n this.popupWrapper.scrollTop = 0;\n }\n };\n TimePicker.prototype.setScrollTo = function () {\n var element;\n if (!isNullOrUndefined(this.popupWrapper)) {\n var items = this.popupWrapper.querySelectorAll('.' + LISTCLASS);\n if (items.length) {\n var initialTime = this.timeCollections[0];\n var scrollTime = this.getDateObject(this.checkDateValue(this.scrollTo)).getTime();\n element = items[Math.round((scrollTime - initialTime) / (this.step * 60000))];\n }\n }\n else {\n this.popupWrapper.scrollTop = 0;\n }\n if (!isNullOrUndefined(element)) {\n this.findScrollTop(element);\n }\n else {\n this.popupWrapper.scrollTop = 0;\n }\n };\n TimePicker.prototype.getText = function () {\n return (isNullOrUndefined(this.checkDateValue(this.value))) ? '' : this.getValue(this.value);\n };\n TimePicker.prototype.getValue = function (value) {\n return (isNullOrUndefined(this.checkDateValue(value))) ? null : this.globalize.formatDate(value, {\n format: this.cldrTimeFormat(), type: 'time'\n });\n };\n TimePicker.prototype.cldrDateFormat = function () {\n var cldrDate;\n if (this.locale === 'en' || this.locale === 'en-US') {\n cldrDate = (getValue('dateFormats.short', getDefaultDateObject()));\n }\n else {\n cldrDate = (this.getCultureDateObject(cldrData, '' + this.locale));\n }\n return cldrDate;\n };\n TimePicker.prototype.cldrTimeFormat = function () {\n var cldrTime;\n if (this.isNullOrEmpty(this.format)) {\n if (this.locale === 'en' || this.locale === 'en-US') {\n cldrTime = (getValue('timeFormats.short', getDefaultDateObject()));\n }\n else {\n cldrTime = (this.getCultureTimeObject(cldrData, '' + this.locale));\n }\n }\n else {\n cldrTime = this.format;\n }\n return cldrTime;\n };\n TimePicker.prototype.dateToNumeric = function () {\n var cldrTime;\n if (this.locale === 'en' || this.locale === 'en-US') {\n cldrTime = (getValue('timeFormats.medium', getDefaultDateObject()));\n }\n else {\n cldrTime = (getValue('main.' + '' + this.locale + '.dates.calendars.gregorian.timeFormats.medium', cldrData));\n }\n return cldrTime;\n };\n TimePicker.prototype.getExactDateTime = function (value) {\n if (isNullOrUndefined(this.checkDateValue(value))) {\n return null;\n }\n else {\n return this.globalize.formatDate(value, { format: this.dateToNumeric(), type: 'time' });\n }\n };\n TimePicker.prototype.setValue = function (value) {\n var time = this.checkValue(value);\n if (!this.strictMode && !this.validateState(time)) {\n this.initValue = this.valueWithMinutes = null;\n this.validateMinMax(this.value, this.min, this.max);\n }\n else {\n if (this.isNullOrEmpty(time)) {\n this.initValue = null;\n this.validateMinMax(this.value, this.min, this.max);\n }\n else {\n this.initValue = this.compareFormatChange(time);\n }\n }\n this.updateInput(true, this.initValue);\n };\n TimePicker.prototype.compareFormatChange = function (value) {\n if (isNullOrUndefined(value)) {\n return null;\n }\n return (value !== this.getText()) ? this.getDateObject(value) : this.getDateObject(this.value);\n };\n TimePicker.prototype.updatePlaceHolder = function () {\n Input.setPlaceholder(this.l10n.getConstant('placeholder'), this.inputElement);\n };\n //event related functions\n TimePicker.prototype.popupHandler = function (e) {\n e.preventDefault();\n if (this.isPopupOpen()) {\n this.closePopup(0, e);\n }\n else {\n this.show(e);\n }\n };\n TimePicker.prototype.mouseDownHandler = function () {\n if (!this.readonly) {\n var curPos = this.getCursorSelection();\n this.inputElement.setSelectionRange(0, 0);\n EventHandler.add(this.inputElement, 'mouseup', this.mouseUpHandler, this);\n }\n };\n TimePicker.prototype.mouseUpHandler = function (event) {\n if (!this.readonly) {\n event.preventDefault();\n EventHandler.remove(this.inputElement, 'mouseup', this.mouseUpHandler);\n var curPos = this.getCursorSelection();\n if (!(curPos.start === 0 && curPos.end === this.inputElement.value.length)) {\n if (this.inputElement.value.length > 0) {\n this.cursorDetails = this.focusSelection();\n }\n this.inputElement.setSelectionRange(this.cursorDetails.start, this.cursorDetails.end);\n }\n }\n };\n TimePicker.prototype.focusSelection = function () {\n var regex = new RegExp('^[a-zA-Z0-9]+$');\n var split = this.inputElement.value.split('');\n split.push(' ');\n var curPos = this.getCursorSelection();\n var start = 0;\n var end = 0;\n var isSeparator = false;\n if (!this.isTextSelected) {\n for (var i = 0; i < split.length; i++) {\n if (!regex.test(split[i])) {\n end = i;\n isSeparator = true;\n }\n if (isSeparator) {\n if (curPos.start >= start && curPos.end <= end) {\n end = end;\n this.isTextSelected = true;\n break;\n }\n else {\n start = i + 1;\n isSeparator = false;\n }\n }\n }\n }\n else {\n start = curPos.start;\n end = curPos.end;\n this.isTextSelected = false;\n }\n return { start: start, end: end };\n };\n TimePicker.prototype.inputHandler = function (event) {\n if (!this.readonly && this.enabled) {\n if (event.action !== 'right' && event.action !== 'left' && event.action !== 'tab') {\n event.preventDefault();\n }\n switch (event.action) {\n case 'home':\n case 'end':\n case 'up':\n case 'down':\n this.keyHandler(event);\n break;\n case 'enter':\n if (this.isNavigate) {\n this.selectedElement = this.liCollections[this.activeIndex];\n this.valueWithMinutes = new Date(this.timeCollections[this.activeIndex]);\n this.updateValue(this.valueWithMinutes, event);\n }\n else {\n this.updateValue(this.inputElement.value, event);\n }\n this.hide();\n addClass([this.inputWrapper.container], FOCUS);\n this.isNavigate = false;\n break;\n case 'open':\n this.show(event);\n break;\n case 'escape':\n Input.setValue(this.objToString(this.value), this.inputElement, this.floatLabelType, this.showClearButton);\n this.previousState(this.value);\n this.hide();\n break;\n case 'close':\n this.hide();\n break;\n default:\n this.isNavigate = false;\n break;\n }\n }\n };\n TimePicker.prototype.onMouseClick = function (event) {\n var target = event.target;\n var li = this.selectedElement = closest(target, '.' + LISTCLASS);\n this.setSelection(li, event);\n if (li && li.classList.contains(LISTCLASS)) {\n this.hide();\n if (!Browser.isDevice) {\n addClass([this.inputWrapper.container], FOCUS);\n }\n }\n };\n TimePicker.prototype.closePopup = function (delay, e) {\n if (this.isPopupOpen() && this.popupWrapper) {\n var args = {\n popup: this.popupObj,\n event: e || null,\n cancel: false,\n name: 'open'\n };\n this.trigger('close', args);\n if (!args.cancel) {\n var animModel = {\n name: 'FadeOut',\n duration: ANIMATIONDURATION,\n delay: delay ? delay : 0\n };\n this.popupObj.hide(new Animation(animModel));\n removeClass([this.inputWrapper.container], [ICONANIMATION]);\n attributes(this.inputElement, { 'aria-expanded': 'false' });\n EventHandler.remove(document, 'mousedown touchstart', this.documentClickHandler);\n }\n }\n };\n TimePicker.prototype.checkValueChange = function (event, isNavigation) {\n if (!this.strictMode && !this.validateState(this.valueWithMinutes)) {\n this.initValue = this.valueWithMinutes = null;\n this.setProperties({ value: this.compareFormatChange(this.inputElement.value) }, true);\n this.prevValue = this.inputElement.value;\n if (+this.prevDate !== +this.value) {\n this.changeEvent(event);\n }\n }\n else {\n if (!isNavigation) {\n if ((this.prevValue !== this.inputElement.value) || isNullOrUndefined(this.checkDateValue(this.value))) {\n this.valueProcess(event, this.compareFormatChange(this.inputElement.value));\n }\n }\n else {\n var value = this.getDateObject(new Date(this.timeCollections[this.activeIndex]));\n if (+this.prevDate !== +value) {\n this.valueProcess(event, value);\n }\n }\n }\n };\n TimePicker.prototype.onMouseOver = function (event) {\n var currentLi = closest(event.target, '.' + LISTCLASS);\n this.setHover(currentLi, HOVER);\n };\n TimePicker.prototype.setHover = function (li, className) {\n if (this.enabled && this.isValidLI(li) && !li.classList.contains(className)) {\n this.removeHover(className);\n addClass([li], className);\n if (className === NAVIGATION) {\n li.setAttribute('aria-selected', 'true');\n }\n }\n };\n TimePicker.prototype.setSelection = function (li, event) {\n if (this.isValidLI(li) && !li.classList.contains(SELECTED)) {\n this.checkValue(li.getAttribute('data-value'));\n this.selectedElement = li;\n this.activeIndex = Array.prototype.slice.call(this.liCollections).indexOf(li);\n this.valueWithMinutes = new Date(this.timeCollections[this.activeIndex]);\n addClass([this.selectedElement], SELECTED);\n this.selectedElement.setAttribute('aria-selected', 'true');\n this.checkValueChange(event, true);\n }\n };\n TimePicker.prototype.onMouseLeave = function () {\n this.removeHover(HOVER);\n };\n TimePicker.prototype.scrollHandler = function () {\n if (this.getModuleName() === 'timepicker' && Browser.isDevice) {\n return;\n }\n else {\n this.hide();\n }\n };\n TimePicker.prototype.setMinMax = function (minVal, maxVal) {\n if (isNullOrUndefined(this.checkDateValue(minVal))) {\n this.initMin = this.getDateObject('12:00:00 AM');\n }\n if (isNullOrUndefined(this.checkDateValue(maxVal))) {\n this.initMax = this.getDateObject('11:59:59 PM');\n }\n };\n //protected function\n TimePicker.prototype.validateMinMax = function (dateVal, minVal, maxVal) {\n var value = dateVal instanceof Date ? dateVal : this.getDateObject(dateVal);\n if (!isNullOrUndefined(this.checkDateValue(value))) {\n dateVal = this.strictOperation(this.initMin, this.initMax, dateVal, value);\n }\n else if (+(this.createDateObj(this.getFormattedValue(this.initMin))) >\n +(this.createDateObj(this.getFormattedValue(this.initMax)))) {\n this.disableTimeIcon();\n }\n if (this.strictMode) {\n dateVal = this.valueIsDisable(dateVal) ? dateVal : null;\n }\n this.checkErrorState(dateVal);\n return dateVal;\n };\n TimePicker.prototype.valueIsDisable = function (value) {\n if (this.disableItemCollection.length > 0) {\n if (this.disableItemCollection.length === this.timeCollections.length) {\n return false;\n }\n var time = value instanceof Date ? this.objToString(value) : value;\n for (var index = 0; index < this.disableItemCollection.length; index++) {\n if (time === this.disableItemCollection[index]) {\n return false;\n }\n }\n }\n return true;\n };\n TimePicker.prototype.validateState = function (val) {\n if (!this.strictMode) {\n if (this.valueIsDisable(val)) {\n var value = typeof val === 'string' ? this.setCurrentDate(this.getDateObject(val)) :\n this.setCurrentDate(this.getDateObject(val));\n var maxValue = this.setCurrentDate(this.getDateObject(this.initMax));\n var minValue = this.setCurrentDate(this.getDateObject(this.initMin));\n if (!isNullOrUndefined(this.checkDateValue(value))) {\n if ((+(value) > +(maxValue)) || (+(value) < +(minValue))) {\n return false;\n }\n }\n else {\n if ((+(maxValue) < +(minValue)) || this.inputElement.value !== '') {\n return false;\n }\n }\n }\n else {\n return false;\n }\n }\n return true;\n };\n TimePicker.prototype.strictOperation = function (minimum, maximum, dateVal, val) {\n var maxValue = this.createDateObj(this.getFormattedValue(maximum));\n var minValue = this.createDateObj(this.getFormattedValue(minimum));\n var value = this.createDateObj(this.getFormattedValue(val));\n if (this.strictMode) {\n if (+minValue > +maxValue) {\n this.disableTimeIcon();\n this.initValue = this.getDateObject(maxValue);\n Input.setValue(this.getValue(this.initValue), this.inputElement, this.floatLabelType, this.showClearButton);\n return this.inputElement.value;\n }\n else if (+minValue >= +value) {\n return this.getDateObject(minValue);\n }\n else if (+value >= +maxValue || +minValue === +maxValue) {\n return this.getDateObject(maxValue);\n }\n }\n else {\n if (+minValue > +maxValue) {\n this.disableTimeIcon();\n if (!isNaN(+this.createDateObj(dateVal))) {\n return dateVal;\n }\n }\n }\n return dateVal;\n };\n TimePicker.prototype.bindEvents = function () {\n EventHandler.add(this.inputWrapper.buttons[0], 'mousedown touchstart', this.popupHandler, this);\n EventHandler.add(this.inputElement, 'blur', this.inputBlurHandler, this);\n EventHandler.add(this.inputElement, 'focus', this.inputFocusHandler, this);\n EventHandler.add(this.inputElement, 'change', this.inputChangeHandler, this);\n if (this.showClearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.clearHandler, this);\n }\n var form = closest(this.element, 'form');\n if (form) {\n EventHandler.add(form, 'reset', this.formResetHandler.bind(this));\n }\n if (!Browser.isDevice) {\n this.inputEvent = new KeyboardEvents(this.inputWrapper.container, {\n keyAction: this.inputHandler.bind(this), keyConfigs: this.keyConfigure, eventName: 'keydown'\n });\n if (this.showClearButton) {\n EventHandler.add(this.inputElement, 'mousedown touchstart', this.mouseDownHandler, this);\n }\n }\n };\n TimePicker.prototype.formResetHandler = function () {\n if (!this.inputElement.getAttribute('value')) {\n this.value = null;\n if (this.inputElement) {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n this.removeErrorClass();\n }\n }\n else {\n this.value = this.checkDateValue(new Date('' + this.element.getAttribute('value')));\n }\n };\n TimePicker.prototype.inputChangeHandler = function (e) {\n e.stopPropagation();\n };\n TimePicker.prototype.unBindEvents = function () {\n EventHandler.remove(this.inputWrapper.buttons[0], 'mousedown touchstart', this.popupHandler);\n EventHandler.remove(this.inputElement, 'blur', this.inputBlurHandler);\n EventHandler.remove(this.inputElement, 'focus', this.inputFocusHandler);\n EventHandler.remove(this.inputElement, 'change', this.inputChangeHandler);\n if (this.inputEvent) {\n this.inputEvent.destroy();\n }\n EventHandler.remove(this.inputElement, 'mousedown touchstart', this.mouseDownHandler);\n EventHandler.remove(this.inputWrapper.clearButton, 'mousedown touchstart', this.clearHandler);\n var form = closest(this.element, 'form');\n if (form) {\n EventHandler.remove(form, 'reset', this.formResetHandler.bind(this));\n }\n };\n TimePicker.prototype.bindClearEvent = function () {\n if (this.showClearButton && this.inputWrapper.clearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.clearHandler, this);\n }\n };\n TimePicker.prototype.clearHandler = function (e) {\n e.preventDefault();\n this.clear(e);\n if (this.popupWrapper) {\n this.popupWrapper.scrollTop = 0;\n }\n };\n TimePicker.prototype.clear = function (event) {\n this.setProperties({ value: null }, true);\n this.initValue = null;\n this.resetState();\n this.changeEvent(event);\n };\n TimePicker.prototype.setZIndex = function () {\n if (this.popupObj) {\n this.popupObj.zIndex = this.zIndex;\n this.popupObj.dataBind();\n }\n };\n TimePicker.prototype.checkAttributes = function () {\n var attributes = ['step', 'disabled', 'readonly', 'style', 'name', 'value', 'min', 'max', 'placeholder'];\n var value;\n for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {\n var prop = attributes_1[_i];\n if (!isNullOrUndefined(this.inputElement.getAttribute(prop))) {\n switch (prop) {\n case 'disabled':\n var enabled = isNullOrUndefined(this.inputElement.getAttribute(prop));\n this.setProperties({ enabled: enabled }, true);\n break;\n case 'readonly':\n var readonly = !isNullOrUndefined(this.inputElement.getAttribute(prop));\n this.setProperties({ readonly: readonly }, true);\n break;\n case 'style':\n this.inputStyle = this.inputElement.getAttribute(prop);\n break;\n case 'name':\n this.inputElement.setAttribute('name', this.inputElement.getAttribute(prop));\n break;\n case 'step':\n this.step = parseInt(this.inputElement.getAttribute(prop), 10);\n break;\n case 'placeholder':\n this.placeholder = this.inputElement.getAttribute(prop);\n break;\n case 'min':\n value = new Date(this.inputElement.getAttribute(prop));\n if (!isNullOrUndefined(this.checkDateValue(value))) {\n this.setProperties({ min: value }, true);\n }\n break;\n case 'max':\n value = new Date(this.inputElement.getAttribute(prop));\n if (!isNullOrUndefined(this.checkDateValue(value))) {\n this.setProperties({ max: value }, true);\n }\n break;\n case 'value':\n value = new Date(this.inputElement.getAttribute(prop));\n if (!isNullOrUndefined(this.checkDateValue(value))) {\n this.initValue = value;\n this.updateInput(false, this.initValue);\n }\n break;\n }\n }\n }\n };\n TimePicker.prototype.setCurrentDate = function (value) {\n if (isNullOrUndefined(this.checkDateValue(value))) {\n return null;\n }\n return new Date(YEAR, MONTH, DAY, value.getHours(), value.getMinutes(), value.getSeconds());\n };\n TimePicker.prototype.getTextFormat = function () {\n var time = 0;\n if (this.cldrTimeFormat().split(' ')[0] === 'a' || this.cldrTimeFormat().indexOf('a') === 0) {\n time = 1;\n }\n else if (this.cldrTimeFormat().indexOf('a') < 0) {\n var strArray = this.cldrTimeFormat().split(' ');\n for (var i = 0; i < strArray.length; i++) {\n if (strArray[i].toLowerCase().indexOf('h') >= 0) {\n time = i;\n break;\n }\n }\n }\n return time;\n };\n TimePicker.prototype.updateValue = function (value, event) {\n var val;\n if (this.isNullOrEmpty(value)) {\n this.resetState();\n }\n else {\n val = this.checkValue(value);\n if (this.strictMode) {\n // this case set previous value to the text box when set invalid date\n var inputVal = (val === null && value.trim().length > 0) ?\n this.previousState(this.prevDate) : this.inputElement.value;\n Input.setValue(inputVal, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n }\n this.checkValueChange(event, typeof value === 'string' ? false : true);\n };\n TimePicker.prototype.previousState = function (date) {\n var value = this.getDateObject(date);\n for (var i = 0; i < this.timeCollections.length; i++) {\n if (+value === this.timeCollections[i]) {\n this.activeIndex = i;\n this.selectedElement = this.liCollections[i];\n this.valueWithMinutes = new Date(this.timeCollections[i]);\n break;\n }\n }\n return this.prevValue;\n };\n TimePicker.prototype.resetState = function () {\n this.removeSelection();\n Input.setValue('', this.inputElement, this.floatLabelType, false);\n this.valueWithMinutes = this.activeIndex = null;\n if (!this.strictMode) {\n this.checkErrorState(null);\n }\n };\n TimePicker.prototype.objToString = function (val) {\n if (isNullOrUndefined(this.checkDateValue(val))) {\n return null;\n }\n else {\n return this.globalize.formatDate(val, { format: this.cldrTimeFormat(), type: 'time' });\n }\n };\n TimePicker.prototype.checkValue = function (value) {\n if (!this.isNullOrEmpty(value)) {\n var date = value instanceof Date ? value : this.getDateObject(value);\n return this.validateValue(date, value);\n }\n this.resetState();\n return this.valueWithMinutes = null;\n };\n TimePicker.prototype.validateValue = function (date, value) {\n var time;\n var val = this.validateMinMax(value, this.min, this.max);\n var newval = this.createDateObj(val);\n if (this.getFormattedValue(newval) !== this.getFormattedValue(this.value)) {\n this.valueWithMinutes = isNullOrUndefined(newval) ? null : newval;\n time = this.objToString(this.valueWithMinutes);\n }\n else {\n if (this.strictMode) {\n //for strict mode case, when value not present within a range. Reset the nearest range value.\n date = newval;\n }\n this.valueWithMinutes = this.checkDateValue(date);\n time = this.objToString(this.valueWithMinutes);\n }\n if (!this.strictMode && isNullOrUndefined(time)) {\n var value_1 = val.trim().length > 0 ? val : '';\n Input.setValue(value_1, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n else {\n Input.setValue(time, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n return time;\n };\n TimePicker.prototype.findNextElement = function (event) {\n var textVal = (this.inputElement).value;\n var value = isNullOrUndefined(this.valueWithMinutes) ? this.createDateObj(textVal) :\n this.getDateObject(this.valueWithMinutes);\n var timeVal = null;\n var count = this.liCollections.length;\n if (!isNullOrUndefined(this.checkDateValue(value)) || !isNullOrUndefined(this.activeIndex)) {\n if (event.action === 'home') {\n var index = this.validLiElement(0);\n timeVal = +(this.createDateObj(new Date(this.timeCollections[index])));\n this.activeIndex = index;\n }\n else if (event.action === 'end') {\n var index = this.validLiElement(this.timeCollections.length - 1, true);\n timeVal = +(this.createDateObj(new Date(this.timeCollections[index])));\n this.activeIndex = index;\n }\n else {\n if (event.action === 'down') {\n for (var i = 0; i < count; i++) {\n if (+value < this.timeCollections[i]) {\n var index = this.validLiElement(i);\n timeVal = +(this.createDateObj(new Date(this.timeCollections[index])));\n this.activeIndex = index;\n break;\n }\n else if (i === count - 1) {\n var index = this.validLiElement(0);\n timeVal = +(this.createDateObj(new Date(this.timeCollections[index])));\n this.activeIndex = index;\n break;\n }\n }\n }\n else {\n for (var i = count - 1; i >= 0; i--) {\n if (+value > this.timeCollections[i]) {\n var index = this.validLiElement(i, true);\n timeVal = +(this.createDateObj(new Date(this.timeCollections[index])));\n this.activeIndex = index;\n break;\n }\n else if (i === 0) {\n var index = this.validLiElement(count - 1);\n timeVal = +(this.createDateObj(new Date(this.timeCollections[index])));\n this.activeIndex = index;\n break;\n }\n }\n }\n }\n this.selectedElement = this.liCollections[this.activeIndex];\n this.elementValue(isNullOrUndefined(timeVal) ? null : new Date(timeVal));\n }\n else {\n var index = this.validLiElement(0, event.action === 'down' ? false : true);\n this.activeIndex = index;\n this.selectedElement = this.liCollections[index];\n this.elementValue(new Date(this.timeCollections[index]));\n }\n };\n TimePicker.prototype.elementValue = function (value) {\n if (!isNullOrUndefined(this.checkDateValue(value))) {\n this.checkValue(value);\n }\n };\n TimePicker.prototype.validLiElement = function (index, backward) {\n var elementIndex = null;\n var items = isNullOrUndefined(this.popupWrapper) ? this.liCollections :\n this.popupWrapper.querySelectorAll('.' + LISTCLASS);\n var isCheck = true;\n if (items.length) {\n if (backward) {\n for (var i = index; i >= 0; i--) {\n if (!items[i].classList.contains(DISABLED)) {\n elementIndex = i;\n break;\n }\n else if (i === 0) {\n if (isCheck) {\n index = i = items.length;\n isCheck = false;\n }\n }\n }\n }\n else {\n for (var i = index; i <= items.length - 1; i++) {\n if (!items[i].classList.contains(DISABLED)) {\n elementIndex = i;\n break;\n }\n else if (i === items.length - 1) {\n if (isCheck) {\n index = i = -1;\n isCheck = false;\n }\n }\n }\n }\n }\n return elementIndex;\n };\n TimePicker.prototype.keyHandler = function (event) {\n if (isNullOrUndefined(this.step) || this.step <= 0 || this.inputWrapper.buttons[0].classList.contains(DISABLED)) {\n return;\n }\n var count = this.timeCollections.length;\n if (isNullOrUndefined(this.getActiveElement()) || this.getActiveElement().length === 0) {\n if (this.liCollections.length > 0) {\n if (isNullOrUndefined(this.value) && isNullOrUndefined(this.activeIndex)) {\n var index = this.validLiElement(0, event.action === 'down' ? false : true);\n this.activeIndex = index;\n this.selectedElement = this.liCollections[index];\n this.elementValue(new Date(this.timeCollections[index]));\n }\n else {\n this.findNextElement(event);\n }\n }\n else {\n this.findNextElement(event);\n }\n }\n else {\n var nextItem = void 0;\n if ((event.keyCode >= 37) && (event.keyCode <= 40)) {\n var index = (event.keyCode === 40 || event.keyCode === 39) ? ++this.activeIndex : --this.activeIndex;\n this.activeIndex = index = this.activeIndex === (count) ? 0 : this.activeIndex;\n this.activeIndex = index = this.activeIndex < 0 ? (count - 1) : this.activeIndex;\n this.activeIndex = index = this.validLiElement(this.activeIndex, (event.keyCode === 40 || event.keyCode === 39) ?\n false : true);\n nextItem = isNullOrUndefined(this.timeCollections[index]) ? this.timeCollections[0] : this.timeCollections[index];\n }\n else if (event.action === 'home') {\n var index = this.validLiElement(0);\n this.activeIndex = index;\n nextItem = this.timeCollections[index];\n }\n else if (event.action === 'end') {\n var index = this.validLiElement(count - 1, true);\n this.activeIndex = index;\n nextItem = this.timeCollections[index];\n }\n this.selectedElement = this.liCollections[this.activeIndex];\n this.elementValue(new Date(nextItem));\n }\n this.isNavigate = true;\n this.setHover(this.selectedElement, NAVIGATION);\n this.setActiveDescendant();\n this.selectInputText();\n if (this.isPopupOpen() && this.selectedElement !== null && (!event || event.type !== 'click')) {\n this.setScrollPosition();\n }\n };\n TimePicker.prototype.setPopupPosition = function () {\n var offsetValue;\n var padding = 1;\n var popupHeight = this.getPopupHeight();\n var element = this.getActiveElement();\n var liHeight = this.liCollections[0].getBoundingClientRect().height;\n var listHeight = popupHeight / HALFPOSITION;\n var height = element.length === 0 ? this.liCollections[0].offsetTop : element[0].offsetTop;\n var lastItemOffsetValue = this.liCollections[this.liCollections.length - 1].offsetTop;\n var ulPadding = (parseInt(getComputedStyle(this.listTag).paddingTop, 10));\n if (lastItemOffsetValue - listHeight < height) {\n var count = popupHeight / liHeight;\n offsetValue = (count - (this.liCollections.length - this.activeIndex)) * liHeight - ulPadding - HALFPOSITION;\n }\n else if ((height + liHeight) > listHeight) {\n offsetValue = listHeight - liHeight / HALFPOSITION;\n }\n else {\n offsetValue = height;\n }\n offsetValue = offsetValue + HALFPOSITION + ((liHeight - this.containerStyle.height) / HALFPOSITION);\n return -offsetValue;\n };\n TimePicker.prototype.getCultureTimeObject = function (ld, c) {\n return getValue('main.' + c + '.dates.calendars.gregorian.timeFormats.short', ld);\n };\n TimePicker.prototype.getCultureDateObject = function (ld, c) {\n return getValue('main.' + c + '.dates.calendars.gregorian.dateFormats.short', ld);\n };\n TimePicker.prototype.wireListEvents = function () {\n EventHandler.add(this.listWrapper, 'click', this.onMouseClick, this);\n if (!Browser.isDevice) {\n EventHandler.add(this.listWrapper, 'mouseover', this.onMouseOver, this);\n EventHandler.add(this.listWrapper, 'mouseout', this.onMouseLeave, this);\n }\n };\n TimePicker.prototype.unWireListEvents = function () {\n if (this.listWrapper) {\n EventHandler.remove(this.listWrapper, 'click', this.onMouseClick);\n if (!Browser.isDevice) {\n EventHandler.remove(this.listWrapper, 'mouseover', this.onMouseOver);\n EventHandler.remove(this.listWrapper, 'mouseout', this.onMouseLeave);\n }\n }\n };\n TimePicker.prototype.valueProcess = function (event, value) {\n var result = (isNullOrUndefined(this.checkDateValue(value))) ? null : value;\n if (+this.prevDate !== +result) {\n this.initValue = result;\n this.changeEvent(event);\n }\n };\n TimePicker.prototype.changeEvent = function (e) {\n this.addSelection();\n this.updateInput(true, this.initValue);\n var eventArgs = {\n event: (e || null),\n value: this.value,\n text: (this.inputElement).value,\n isInteracted: !isNullOrUndefined(e),\n element: this.element\n };\n eventArgs.value = this.valueWithMinutes || this.getDateObject(this.inputElement.value);\n this.prevDate = this.valueWithMinutes || this.getDateObject(this.inputElement.value);\n this.trigger('change', eventArgs);\n };\n TimePicker.prototype.updateInput = function (isUpdate, date) {\n if (isUpdate) {\n this.prevValue = this.getValue(date);\n }\n this.prevDate = this.valueWithMinutes = date;\n this.setProperties({ value: date }, true);\n };\n TimePicker.prototype.setActiveDescendant = function () {\n if (!isNullOrUndefined(this.selectedElement)) {\n attributes(this.inputElement, { 'aria-activedescendant': this.selectedElement.getAttribute('id') });\n }\n else {\n attributes(this.inputElement, { 'aria-activedescendant': 'null' });\n }\n };\n TimePicker.prototype.removeSelection = function () {\n this.removeHover(HOVER);\n if (!isNullOrUndefined(this.popupWrapper)) {\n var items = this.popupWrapper.querySelectorAll('.' + SELECTED);\n if (items.length) {\n removeClass(items, SELECTED);\n items[0].removeAttribute('aria-selected');\n }\n }\n };\n TimePicker.prototype.removeHover = function (className) {\n var hoveredItem = this.getHoverItem(className);\n if (hoveredItem && hoveredItem.length) {\n removeClass(hoveredItem, className);\n if (className === NAVIGATION) {\n hoveredItem[0].removeAttribute('aria-selected');\n }\n }\n };\n TimePicker.prototype.getHoverItem = function (className) {\n var hoveredItem;\n if (!isNullOrUndefined(this.popupWrapper)) {\n hoveredItem = this.popupWrapper.querySelectorAll('.' + className);\n }\n return hoveredItem;\n };\n TimePicker.prototype.setActiveClass = function () {\n if (!isNullOrUndefined(this.popupWrapper)) {\n var items = this.popupWrapper.querySelectorAll('.' + LISTCLASS);\n if (items.length) {\n for (var i = 0; i < items.length; i++) {\n if (this.timeCollections[i] === +this.getDateObject(this.valueWithMinutes)) {\n items[i].setAttribute('aria-selected', 'true');\n this.selectedElement = items[i];\n this.activeIndex = i;\n break;\n }\n }\n }\n }\n };\n TimePicker.prototype.addSelection = function () {\n this.selectedElement = null;\n this.removeSelection();\n this.setActiveClass();\n if (!isNullOrUndefined(this.selectedElement)) {\n addClass([this.selectedElement], SELECTED);\n this.selectedElement.setAttribute('aria-selected', 'true');\n }\n };\n TimePicker.prototype.isValidLI = function (li) {\n return (li && li.classList.contains(LISTCLASS) && !li.classList.contains(DISABLED));\n };\n TimePicker.prototype.createDateObj = function (val) {\n var today = this.globalize.formatDate(new Date(), { skeleton: 'short', type: 'date' });\n var value = null;\n if (typeof val === 'string') {\n if (val.toUpperCase().indexOf('AM') > -1 || val.toUpperCase().indexOf('PM') > -1) {\n today = this.defaultCulture.formatDate(new Date(), { skeleton: 'short', type: 'date' });\n value = isNaN(+new Date(today + ' ' + val)) ? null : new Date(new Date(today + ' ' + val).setMilliseconds(0));\n if (isNullOrUndefined(value)) {\n value = this.TimeParse(today, val);\n }\n }\n else {\n value = this.TimeParse(today, val);\n }\n }\n else if (val instanceof Date) {\n value = val;\n }\n return value;\n };\n TimePicker.prototype.TimeParse = function (today, val) {\n var value;\n value = this.globalize.parseDate(today + ' ' + val, {\n format: this.cldrDateFormat() + ' ' + this.cldrTimeFormat(), type: 'datetime'\n });\n value = isNullOrUndefined(value) ? this.globalize.parseDate(today + ' ' + val, {\n format: this.cldrDateFormat() + ' ' + this.dateToNumeric(), type: 'datetime'\n }) : value;\n value = isNullOrUndefined(value) ? value : new Date(value.setMilliseconds(0));\n return value;\n };\n TimePicker.prototype.createListItems = function () {\n var _this = this;\n this.listWrapper = this.createElement('div', { className: CONTENT, attrs: { 'tabindex': '0' } });\n var start;\n var end;\n var interval = this.step * 60000;\n var listItems = [];\n this.timeCollections = [];\n this.disableItemCollection = [];\n start = +(this.getDateObject(this.initMin).setMilliseconds(0));\n end = +(this.getDateObject(this.initMax).setMilliseconds(0));\n while (end >= start) {\n this.timeCollections.push(start);\n listItems.push(this.globalize.formatDate(new Date(start), { format: this.cldrTimeFormat(), type: 'time' }));\n start += interval;\n }\n var listBaseOptions = {\n itemCreated: function (args) {\n var eventArgs = {\n element: args.item,\n text: args.text, value: _this.getDateObject(args.text), isDisabled: false\n };\n _this.trigger('itemRender', eventArgs);\n if (eventArgs.isDisabled) {\n eventArgs.element.classList.add(DISABLED);\n }\n if (eventArgs.element.classList.contains(DISABLED)) {\n _this.disableItemCollection.push(eventArgs.element.getAttribute('data-value'));\n }\n }\n };\n this.listTag = ListBase.createList(this.createElement, listItems, listBaseOptions, true);\n attributes(this.listTag, { 'role': 'listbox', 'aria-hidden': 'false', 'id': this.element.id + '_options' });\n append([this.listTag], this.listWrapper);\n };\n TimePicker.prototype.documentClickHandler = function (event) {\n if (!Browser.isDevice) {\n event.preventDefault();\n }\n var target = event.target;\n if (!(closest(target, '#' + this.popupObj.element.id)) && target !== this.inputElement\n && target !== (this.inputWrapper && this.inputWrapper.buttons[0]) &&\n target !== (this.inputWrapper && this.inputWrapper.clearButton) &&\n target !== (this.inputWrapper && this.inputWrapper.container)) {\n if (this.isPopupOpen()) {\n this.hide();\n }\n }\n else if (target !== this.inputElement) {\n if (!Browser.isDevice) {\n this.isPreventBlur = (Browser.isIE || Browser.info.name === 'edge') && (document.activeElement === this.inputElement);\n event.preventDefault();\n }\n }\n };\n TimePicker.prototype.setEnableRtl = function () {\n Input.setEnableRtl(this.enableRtl, [this.inputWrapper.container]);\n if (this.popupObj) {\n this.popupObj.enableRtl = this.enableRtl;\n this.popupObj.dataBind();\n }\n };\n TimePicker.prototype.setEnable = function () {\n Input.setEnabled(this.enabled, this.inputElement, this.floatLabelType);\n if (this.enabled) {\n removeClass([this.inputWrapper.container], DISABLED);\n attributes(this.inputElement, { 'aria-disabled': 'false' });\n }\n else {\n this.hide();\n addClass([this.inputWrapper.container], DISABLED);\n attributes(this.inputElement, { 'aria-disabled': 'true' });\n }\n };\n TimePicker.prototype.getProperty = function (date, val) {\n if (val === 'min') {\n this.initMin = this.checkDateValue(new Date('' + date.min));\n this.setProperties({ min: this.initMin }, true);\n }\n else {\n this.initMax = this.checkDateValue(new Date('' + date.max));\n this.setProperties({ max: this.initMax }, true);\n }\n if (this.inputElement.value === '') {\n this.validateMinMax(this.value, this.min, this.max);\n }\n else {\n this.checkValue(this.inputElement.value);\n }\n this.checkValueChange(null, false);\n };\n TimePicker.prototype.inputBlurHandler = function (e) {\n // IE popup closing issue when click over the scrollbar\n if (this.isPreventBlur && this.isPopupOpen()) {\n this.inputElement.focus();\n return;\n }\n this.closePopup(0, e);\n removeClass([this.inputWrapper.container], [FOCUS]);\n var blurArguments = {\n model: this\n };\n this.trigger('blur', blurArguments);\n if (this.getText() !== this.inputElement.value) {\n this.updateValue((this.inputElement).value, e);\n }\n else if (this.inputElement.value.trim().length === 0) {\n this.resetState();\n }\n this.cursorDetails = null;\n this.isNavigate = false;\n };\n /**\n * Focuses out the TimePicker textbox element.\n * @returns void\n */\n TimePicker.prototype.focusOut = function () {\n if (document.activeElement === this.inputElement) {\n this.inputElement.blur();\n var blurArguments = {\n model: this\n };\n this.trigger('blur', blurArguments);\n }\n };\n TimePicker.prototype.isPopupOpen = function () {\n if (this.popupWrapper && this.popupWrapper.classList.contains('' + ROOT)) {\n return true;\n }\n return false;\n };\n TimePicker.prototype.inputFocusHandler = function () {\n var focusArguments = {\n model: this\n };\n if (!this.readonly && !Browser.isDevice) {\n this.selectInputText();\n }\n this.trigger('focus', focusArguments);\n };\n /**\n * Focused the TimePicker textbox element.\n * @returns void\n */\n TimePicker.prototype.focusIn = function () {\n if (document.activeElement !== this.inputElement && this.enabled) {\n this.inputElement.focus();\n var focusArguments = {\n model: this\n };\n this.trigger('focus', focusArguments);\n }\n };\n /**\n * Hides the TimePicker popup.\n * @returns void\n */\n TimePicker.prototype.hide = function () {\n this.closePopup(100, null);\n };\n /**\n * Opens the popup to show the list items.\n * @returns void\n */\n TimePicker.prototype.show = function (event) {\n if ((this.enabled && this.readonly) || !this.enabled || this.popupWrapper) {\n return;\n }\n else {\n var args = {\n popup: this.popupObj || null,\n cancel: false,\n event: event || null,\n name: 'open'\n };\n this.trigger('open', args);\n if (!args.cancel && !this.isPopupOpen() && !this.inputWrapper.buttons[0].classList.contains(DISABLED)) {\n if (!Browser.isDevice) {\n this.inputElement.focus();\n }\n this.popupCreation();\n if (!args.cancel) {\n var openAnimation = {\n name: 'FadeIn',\n duration: ANIMATIONDURATION,\n };\n this.popupObj.refreshPosition(this.inputElement);\n if (this.zIndex === 1000) {\n this.popupObj.show(new Animation(openAnimation), this.element);\n }\n else {\n this.popupObj.show(new Animation(openAnimation), null);\n }\n this.setActiveDescendant();\n attributes(this.inputElement, { 'aria-expanded': 'true' });\n if (!Browser.isDevice) {\n addClass([this.inputWrapper.container], FOCUS);\n }\n }\n EventHandler.add(document, 'mousedown touchstart', this.documentClickHandler, this);\n }\n }\n };\n /**\n * Gets the properties to be maintained upon browser refresh.\n * @returns string\n */\n TimePicker.prototype.getPersistData = function () {\n var keyEntity = ['value'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * To get component name\n * @private\n */\n TimePicker.prototype.getModuleName = function () {\n return 'timepicker';\n };\n /**\n * Called internally if any of the property value changed.\n * returns void\n * @private\n */\n TimePicker.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'placeholder':\n Input.setPlaceholder(newProp.placeholder, this.inputElement);\n this.inputElement.setAttribute('aria-placeholder', newProp.placeholder);\n break;\n case 'readonly':\n Input.setReadonly(this.readonly, this.inputElement, this.floatLabelType);\n if (this.readonly) {\n this.hide();\n }\n break;\n case 'cssClass':\n addClass([this.inputWrapper.container], [newProp.cssClass]);\n if (this.popupWrapper) {\n addClass([this.popupWrapper], [newProp.cssClass]);\n }\n this.setProperties({ cssClass: newProp.cssClass }, true);\n break;\n case 'enabled':\n this.setProperties({ enabled: newProp.enabled }, true);\n this.setEnable();\n break;\n case 'allowEdit':\n this.setTimeAllowEdit();\n break;\n case 'enableRtl':\n this.setProperties({ enableRtl: newProp.enableRtl }, true);\n this.setEnableRtl();\n break;\n case 'zIndex':\n this.setProperties({ zIndex: newProp.zIndex }, true);\n this.setZIndex();\n break;\n case 'min':\n case 'max':\n this.getProperty(newProp, prop);\n break;\n case 'showClearButton':\n Input.setClearButton(this.showClearButton, this.inputElement, this.inputWrapper);\n this.bindClearEvent();\n break;\n case 'locale':\n this.setProperties({ locale: newProp.locale }, true);\n this.globalize = new Internationalization(this.locale);\n this.l10n.setLocale(this.locale);\n this.updatePlaceHolder();\n this.setValue(this.value);\n break;\n case 'width':\n setStyleAttribute(this.inputWrapper.container, { 'width': this.setWidth(newProp.width) });\n this.containerStyle = this.inputWrapper.container.getBoundingClientRect();\n break;\n case 'format':\n this.setProperties({ format: newProp.format }, true);\n this.setValue(this.value);\n break;\n case 'value':\n if (typeof newProp.value === 'string') {\n this.setProperties({ value: this.checkDateValue(new Date(newProp.value)) }, true);\n newProp.value = this.value;\n }\n else {\n newProp.value = this.checkDateValue(new Date('' + newProp.value));\n }\n this.initValue = newProp.value;\n newProp.value = this.compareFormatChange(this.checkValue(newProp.value));\n this.checkValueChange(null, false);\n break;\n case 'floatLabelType':\n this.floatLabelType = newProp.floatLabelType;\n Input.removeFloating(this.inputWrapper);\n Input.addFloating(this.inputElement, this.floatLabelType, this.placeholder);\n break;\n case 'strictMode':\n if (newProp.strictMode) {\n this.checkErrorState(null);\n }\n this.setProperties({ strictMode: newProp.strictMode }, true);\n this.checkValue((this.inputElement).value);\n this.checkValueChange(null, false);\n break;\n case 'scrollTo':\n if (this.checkDateValue(new Date('' + newProp.scrollTo))) {\n if (this.popupWrapper) {\n this.setScrollTo();\n }\n this.setProperties({ scrollTo: newProp.scrollTo }, true);\n }\n else {\n this.setProperties({ scrollTo: null }, true);\n }\n break;\n }\n }\n };\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], TimePicker.prototype, \"strictMode\", void 0);\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"format\", void 0);\n __decorate([\n Property(true)\n ], TimePicker.prototype, \"enabled\", void 0);\n __decorate([\n Property(false)\n ], TimePicker.prototype, \"readonly\", void 0);\n __decorate([\n Property('Never')\n ], TimePicker.prototype, \"floatLabelType\", void 0);\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"placeholder\", void 0);\n __decorate([\n Property(1000)\n ], TimePicker.prototype, \"zIndex\", void 0);\n __decorate([\n Property(false)\n ], TimePicker.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(true)\n ], TimePicker.prototype, \"showClearButton\", void 0);\n __decorate([\n Property(30)\n ], TimePicker.prototype, \"step\", void 0);\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"scrollTo\", void 0);\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"value\", void 0);\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"min\", void 0);\n __decorate([\n Property(null)\n ], TimePicker.prototype, \"max\", void 0);\n __decorate([\n Property(true)\n ], TimePicker.prototype, \"allowEdit\", void 0);\n __decorate([\n Property(false)\n ], TimePicker.prototype, \"enableRtl\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"destroyed\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"itemRender\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"blur\", void 0);\n __decorate([\n Event()\n ], TimePicker.prototype, \"focus\", void 0);\n TimePicker = __decorate([\n NotifyPropertyChanges\n ], TimePicker);\n return TimePicker;\n}(Component));\nexport { TimePicker };\n","import { classNames } from './list-view';\nimport { EventHandler, append, isNullOrUndefined, detach } from '@syncfusion/ej2-base';\nimport { ListBase } from '../common/list-base';\nvar Virtualization = /** @class */ (function () {\n function Virtualization(instance) {\n this.listViewInstance = instance;\n }\n Virtualization.prototype.uiVirtualization = function () {\n var curViewDS = this.listViewInstance.curViewDS;\n var firstDs = curViewDS.slice(0, 1);\n this.listViewInstance.ulElement = this.listViewInstance.curUL = ListBase.createList(this.listViewInstance.createElement, firstDs, this.listViewInstance.listBaseOption);\n this.listViewInstance.contentContainer = this.listViewInstance.createElement('div', { className: classNames.content });\n this.listViewInstance.element.appendChild(this.listViewInstance.contentContainer);\n this.listViewInstance.contentContainer.appendChild(this.listViewInstance.ulElement);\n this.listItemHeight = this.listViewInstance.ulElement.firstElementChild.getBoundingClientRect().height;\n this.expectedDomItemCount = this.ValidateItemCount(10000);\n this.domItemCount = this.ValidateItemCount(Object.keys(this.listViewInstance.curViewDS).length);\n this.uiFirstIndex = 0;\n this.uiLastIndex = this.domItemCount - 1;\n this.wireScrollEvent(false);\n var otherDs = curViewDS.slice(1, this.domItemCount);\n var listItems = ListBase.createListItemFromJson(this.listViewInstance.createElement, otherDs, this.listViewInstance.listBaseOption);\n append(listItems, this.listViewInstance.ulElement);\n this.listViewInstance.liCollection = this.listViewInstance.curUL.querySelectorAll('li');\n this.topElement = this.listViewInstance.createElement('div');\n this.listViewInstance.ulElement.insertBefore(this.topElement, this.listViewInstance.ulElement.firstElementChild);\n this.bottomElement = this.listViewInstance.createElement('div');\n this.listViewInstance.ulElement.insertBefore(this.bottomElement, null);\n this.totalHeight = (Object.keys(curViewDS).length * this.listItemHeight) - (this.domItemCount * this.listItemHeight);\n this.topElement.style.height = 0 + 'px';\n this.bottomElement.style.height = this.totalHeight + 'px';\n this.topElementHeight = 0;\n this.bottomElementHeight = this.totalHeight;\n this.listDiff = 0;\n this.uiIndicesInitialization();\n };\n Virtualization.prototype.wireScrollEvent = function (destroy) {\n if (!destroy) {\n if (this.listViewInstance.isWindow) {\n this.onVirtualScroll = this.onVirtualUiScroll.bind(this);\n window.addEventListener('scroll', this.onVirtualScroll);\n }\n else {\n EventHandler.add(this.listViewInstance.element, 'scroll', this.onVirtualUiScroll, this);\n }\n }\n else {\n this.listViewInstance.isWindow ? window.removeEventListener('scroll', this.onVirtualScroll) :\n EventHandler.remove(this.listViewInstance.element, 'scroll', this.onVirtualUiScroll);\n }\n };\n Virtualization.prototype.ValidateItemCount = function (dataSourceLength) {\n var itemCount = this.listViewInstance.isWindow ? Math.round((window.innerHeight / this.listItemHeight) * 3) :\n Math.round((this.listViewInstance.height / this.listItemHeight) * 1.5);\n if (itemCount > dataSourceLength) {\n itemCount = dataSourceLength;\n }\n return itemCount;\n };\n Virtualization.prototype.uiIndicesInitialization = function () {\n var _this = this;\n this.uiIndices = { 'activeIndices': [], 'disabledItemIndices': [], 'hiddenItemIndices': [] };\n this.listViewInstance.curViewDS.forEach(function (ds, index) {\n if (_this.listViewInstance.showCheckBox && ds[_this.listViewInstance.fields.isChecked]) {\n _this.uiIndices.activeIndices.push(index);\n }\n if (!isNullOrUndefined(ds[_this.listViewInstance.fields.enabled]) && !ds[_this.listViewInstance.fields.enabled]) {\n _this.uiIndices.disabledItemIndices.push(index);\n }\n });\n };\n Virtualization.prototype.getscrollerHeight = function () {\n return this.listViewInstance.isWindow ? (((pageYOffset - this.startingHeight) <= 0) ? 0 :\n (pageYOffset - this.startingHeight)) : ((this.listViewInstance.element.scrollTop - this.startingHeight) <= 0) ? 0 :\n (this.listViewInstance.element.scrollTop - this.startingHeight);\n };\n Virtualization.prototype.onVirtualUiScroll = function () {\n if (isNullOrUndefined(this.startingHeight)) {\n if (this.listViewInstance.isWindow) {\n this.startingHeight = document.documentElement.getBoundingClientRect().height -\n this.listViewInstance.ulElement.getBoundingClientRect().height;\n }\n else {\n this.startingHeight = this.listViewInstance.headerEle ? this.listViewInstance.headerEle.getBoundingClientRect().height : 0;\n }\n this.scrollPosition = 0;\n }\n var scroll = this.getscrollerHeight();\n this.topElementHeight = this.listItemHeight * Math.floor(scroll / this.listItemHeight);\n this.bottomElementHeight = this.totalHeight - this.topElementHeight;\n _a = scroll <= this.totalHeight ?\n [this.topElementHeight, this.bottomElementHeight] : [this.totalHeight, 0], this.topElementHeight = _a[0], this.bottomElementHeight = _a[1];\n if (this.topElementHeight !== parseFloat(this.topElement.style.height)) {\n this.topElement.style.height = this.topElementHeight + 'px';\n this.bottomElement.style.height = this.bottomElementHeight + 'px';\n if (scroll > this.scrollPosition) {\n var listDiff = ((this.topElementHeight / this.listItemHeight) - this.listDiff);\n if (listDiff > (this.expectedDomItemCount + 5)) {\n this.onLongScroll(listDiff, true);\n }\n else {\n this.onNormalScroll(listDiff, true);\n }\n }\n else {\n var listDiff = (this.listDiff - (this.topElementHeight / this.listItemHeight));\n if (listDiff > (this.expectedDomItemCount + 5)) {\n this.onLongScroll(listDiff, false);\n }\n else {\n this.onNormalScroll(listDiff, false);\n }\n }\n this.listDiff = this.topElementHeight / this.listItemHeight;\n if (typeof this.listViewInstance.onUIScrolled === 'function') {\n this.listViewInstance.onUIScrolled();\n }\n }\n this.scrollPosition = scroll;\n var _a;\n };\n Virtualization.prototype.onLongScroll = function (listDiff, isScrollingDown) {\n var _this = this;\n var index = isScrollingDown ? (this.uiFirstIndex + listDiff) : (this.uiFirstIndex - listDiff);\n Array.prototype.forEach.call(this.listViewInstance.ulElement.querySelectorAll('li'), function (element) {\n _this.updateUI(element, index);\n index++;\n });\n this.uiLastIndex = isScrollingDown ? (this.uiLastIndex + listDiff) : (this.uiLastIndex - listDiff);\n this.uiFirstIndex = isScrollingDown ? (this.uiFirstIndex + listDiff) : (this.uiFirstIndex - listDiff);\n };\n Virtualization.prototype.onNormalScroll = function (listDiff, isScrollingDown) {\n if (isScrollingDown) {\n for (var i = 0; i < listDiff; i++) {\n var index = ++this.uiLastIndex;\n this.updateUI(this.topElement.nextElementSibling, index, this.bottomElement);\n this.uiFirstIndex++;\n }\n }\n else {\n for (var i = 0; i < listDiff; i++) {\n var index = --this.uiFirstIndex;\n var target = this.topElement.nextSibling;\n this.updateUI(this.bottomElement.previousElementSibling, index, target);\n this.uiLastIndex--;\n }\n }\n };\n Virtualization.prototype.updateUiContent = function (element, index) {\n var curViewDs = this.listViewInstance.curViewDS;\n if (typeof this.listViewInstance.dataSource[0] === 'string' ||\n typeof this.listViewInstance.dataSource[0] === 'number') {\n element.dataset.uid = ListBase.generateId();\n element.getElementsByClassName(classNames.listItemText)[0].innerHTML =\n this.listViewInstance.curViewDS[index].toString();\n }\n else {\n element.dataset.uid = curViewDs[index][this.listViewInstance.fields.id] ?\n curViewDs[index][this.listViewInstance.fields.id].toString() : ListBase.generateId();\n element.getElementsByClassName(classNames.listItemText)[0].innerHTML =\n curViewDs[index][this.listViewInstance.fields.text].toString();\n }\n if (this.listViewInstance.showIcon) {\n if (element.querySelector('.' + classNames.listIcon)) {\n detach(element.querySelector('.' + classNames.listIcon));\n }\n if (this.listViewInstance.curViewDS[index][this.listViewInstance.fields.iconCss]) {\n var textContent = element.querySelector('.' + classNames.textContent);\n var target = this.listViewInstance.createElement('div', {\n className: classNames.listIcon + ' ' +\n this.listViewInstance.curViewDS[index][this.listViewInstance.fields.iconCss]\n });\n textContent.insertBefore(target, element.querySelector('.' + classNames.listItemText));\n }\n }\n if (this.listViewInstance.showCheckBox && this.listViewInstance.fields.groupBy) {\n if (!this.checkListWrapper) {\n this.checkListWrapper = this.listViewInstance.curUL.querySelector('.' + classNames.checkboxWrapper).cloneNode(true);\n }\n var textContent = element.querySelector('.' + classNames.textContent);\n if (this.listViewInstance.curViewDS[index].isHeader) {\n if (element.querySelector('.' + classNames.checkboxWrapper)) {\n element.classList.remove(classNames.checklist);\n textContent.classList.remove(classNames.checkbox);\n detach(element.querySelector('.' + classNames.checkboxWrapper));\n }\n }\n else {\n if (!element.querySelector('.' + classNames.checkboxWrapper)) {\n element.classList.add(classNames.checklist);\n textContent.classList.add(classNames.checkbox);\n textContent.insertBefore(this.checkListWrapper.cloneNode(true), element.querySelector('.' + classNames.listItemText));\n }\n }\n }\n };\n Virtualization.prototype.changeElementAttributes = function (element, index) {\n element.classList.remove(classNames.disable);\n if (this.uiIndices.disabledItemIndices.length && this.uiIndices.disabledItemIndices.indexOf(index) !== -1) {\n element.classList.add(classNames.disable);\n }\n element.style.display = '';\n if (this.uiIndices.hiddenItemIndices.length && this.uiIndices.hiddenItemIndices.indexOf(index) !== -1) {\n element.style.display = 'none';\n }\n if (this.listViewInstance.showCheckBox) {\n var checklistElement = element.querySelector('.' + classNames.checkboxWrapper);\n element.classList.remove(classNames.selected);\n element.classList.remove(classNames.focused);\n if (checklistElement) {\n checklistElement.removeAttribute('aria-checked');\n checklistElement.firstElementChild.classList.remove(classNames.checked);\n }\n if (this.uiIndices.activeIndices.length && this.uiIndices.activeIndices.indexOf(index) !== -1 &&\n !this.listViewInstance.curUL.querySelector(classNames.selected)) {\n element.classList.add(classNames.selected);\n checklistElement.firstElementChild.classList.add(classNames.checked);\n checklistElement.setAttribute('aria-checked', 'true');\n if (this.activeIndex === index) {\n element.classList.add(classNames.focused);\n }\n }\n }\n else {\n element.classList.remove(classNames.selected);\n element.removeAttribute('aria-selected');\n if (!isNullOrUndefined(this.activeIndex) && this.activeIndex === index &&\n !this.listViewInstance.curUL.querySelector(classNames.selected)) {\n element.classList.add(classNames.selected);\n element.setAttribute('aria-selected', 'true');\n }\n }\n if (this.listViewInstance.fields.groupBy) {\n if (this.listViewInstance.curViewDS[index].isHeader) {\n if (element.classList.contains(classNames.listItem)) {\n element.classList.remove(classNames.listItem);\n element.setAttribute('role', 'group');\n element.classList.add(classNames.groupListItem);\n }\n }\n else {\n if (element.classList.contains(classNames.groupListItem)) {\n element.classList.remove(classNames.groupListItem);\n element.setAttribute('role', 'listitem');\n element.classList.add(classNames.listItem);\n }\n }\n }\n };\n Virtualization.prototype.findDSAndIndexFromId = function (ds, fields) {\n var _this = this;\n var resultJSON = {};\n ds.some(function (data, index) {\n if ((fields[_this.listViewInstance.fields.id] &&\n fields[_this.listViewInstance.fields.id].toString()\n === (data[_this.listViewInstance.fields.id] && data[_this.listViewInstance.fields.id].toString())) || fields === data) {\n resultJSON.index = index;\n resultJSON.data = data;\n return true;\n }\n else {\n return false;\n }\n });\n return resultJSON;\n };\n Virtualization.prototype.getSelectedItems = function () {\n var _this = this;\n if (!isNullOrUndefined(this.activeIndex) || (this.listViewInstance.showCheckBox && this.uiIndices.activeIndices.length)) {\n var dataCollection_1 = [];\n var textCollection_1 = [];\n if (typeof this.listViewInstance.dataSource[0] === 'string' ||\n typeof this.listViewInstance.dataSource[0] === 'number') {\n var curViewDS_1 = this.listViewInstance.curViewDS;\n if (this.listViewInstance.showCheckBox) {\n this.uiIndices.activeIndices.forEach(function (index) {\n dataCollection_1.push(curViewDS_1[index]);\n });\n return {\n text: dataCollection_1,\n data: dataCollection_1,\n index: this.uiIndices.activeIndices.map(function (index) {\n return _this.listViewInstance.dataSource.indexOf(curViewDS_1[index]);\n })\n };\n }\n else {\n return {\n text: curViewDS_1[this.activeIndex],\n data: curViewDS_1[this.activeIndex],\n index: this.listViewInstance.dataSource.indexOf(curViewDS_1[this.activeIndex])\n };\n }\n }\n else {\n var curViewDS_2 = this.listViewInstance.curViewDS;\n var text_1 = this.listViewInstance.fields.text;\n if (this.listViewInstance.showCheckBox) {\n this.uiIndices.activeIndices.forEach(function (index) {\n textCollection_1.push(curViewDS_2[index][text_1]);\n dataCollection_1.push(curViewDS_2[index]);\n });\n return {\n text: textCollection_1,\n data: dataCollection_1,\n index: this.uiIndices.activeIndices.map(function (index) {\n return (_this.listViewInstance.dataSource).indexOf(curViewDS_2[index]);\n })\n };\n }\n else {\n return {\n text: curViewDS_2[this.activeIndex][this.listViewInstance.fields.text],\n data: curViewDS_2[this.activeIndex],\n index: this.listViewInstance.dataSource.indexOf(curViewDS_2[this.activeIndex])\n };\n }\n }\n }\n else {\n return undefined;\n }\n };\n Virtualization.prototype.selectItem = function (obj) {\n var resutJSON = this.findDSAndIndexFromId(this.listViewInstance.curViewDS, obj);\n if (Object.keys(resutJSON).length) {\n this.activeIndex = resutJSON.index;\n if (this.listViewInstance.showCheckBox && this.uiIndices.activeIndices.indexOf(resutJSON.index) === -1) {\n this.uiIndices.activeIndices.push(resutJSON.index);\n }\n this.listViewInstance.removeSelect();\n if (this.listViewInstance.showCheckBox && this.listViewInstance.curUL.querySelector('.' + classNames.focused)) {\n this.listViewInstance.curUL.querySelector('.' + classNames.focused).classList.remove(classNames.focused);\n }\n if (this.listViewInstance.getLiFromObjOrElement(obj)) {\n if (this.listViewInstance.showCheckBox) {\n this.listViewInstance.setCheckboxLI(this.listViewInstance.getLiFromObjOrElement(obj));\n }\n else {\n this.listViewInstance.setSelectLI(this.listViewInstance.getLiFromObjOrElement(obj));\n }\n }\n else {\n var eventArgs = void 0;\n if (typeof this.listViewInstance.dataSource[0] === 'string' ||\n typeof this.listViewInstance.dataSource[0] === 'number') {\n eventArgs = {\n text: this.listViewInstance.curViewDS[this.activeIndex],\n data: this.listViewInstance.curViewDS[this.activeIndex],\n index: this.activeIndex\n };\n }\n else {\n var curViewDS = this.listViewInstance.curViewDS;\n eventArgs = {\n text: curViewDS[this.activeIndex][this.listViewInstance.fields.text],\n data: curViewDS[this.activeIndex],\n index: this.uiIndices.activeIndices\n };\n }\n this.listViewInstance.trigger('select', eventArgs);\n }\n }\n };\n Virtualization.prototype.enableItem = function (obj) {\n var resutJSON = this.findDSAndIndexFromId(this.listViewInstance.curViewDS, obj);\n if (Object.keys(resutJSON).length) {\n this.uiIndices.disabledItemIndices.splice(this.uiIndices.disabledItemIndices.indexOf(resutJSON.index), 1);\n }\n };\n Virtualization.prototype.disableItem = function (obj) {\n var resutJSON = this.findDSAndIndexFromId(this.listViewInstance.curViewDS, obj);\n if (Object.keys(resutJSON).length && this.uiIndices.disabledItemIndices.indexOf(resutJSON.index) === -1) {\n this.uiIndices.disabledItemIndices.push(resutJSON.index);\n }\n };\n Virtualization.prototype.showItem = function (obj) {\n var resutJSON = this.findDSAndIndexFromId(this.listViewInstance.curViewDS, obj);\n if (Object.keys(resutJSON).length) {\n this.uiIndices.hiddenItemIndices.splice(this.uiIndices.hiddenItemIndices.indexOf(resutJSON.index), 1);\n }\n };\n Virtualization.prototype.hideItem = function (obj) {\n var resutJSON = this.findDSAndIndexFromId(this.listViewInstance.curViewDS, obj);\n if (Object.keys(resutJSON).length && this.uiIndices.hiddenItemIndices.indexOf(resutJSON.index) === -1) {\n this.uiIndices.hiddenItemIndices.push(resutJSON.index);\n }\n };\n Virtualization.prototype.removeItem = function (obj) {\n var dataSource;\n var resutJSON = this.findDSAndIndexFromId(this.listViewInstance.curViewDS, obj);\n if (Object.keys(resutJSON).length) {\n dataSource = resutJSON.data;\n if (this.listViewInstance.curViewDS[resutJSON.index - 1] &&\n this.listViewInstance.curViewDS[resutJSON.index - 1].isHeader &&\n (this.listViewInstance.curViewDS[resutJSON.index - 1])\n .items.length === 1) {\n this.removeUiItem(resutJSON.index - 1);\n this.removeUiItem(resutJSON.index - 1);\n }\n else {\n this.removeUiItem(resutJSON.index);\n }\n }\n var index = this.listViewInstance.dataSource.indexOf(dataSource);\n if (index !== -1) {\n this.listViewInstance.dataSource.splice(index, 1);\n this.listViewInstance.setViewDataSource(this.listViewInstance.dataSource);\n }\n };\n Virtualization.prototype.setCheckboxLI = function (li, e) {\n var index = Array.prototype.indexOf.call(this.listViewInstance.curUL.querySelectorAll('li'), li) + this.uiFirstIndex;\n this.activeIndex = Array.prototype.indexOf.call(this.listViewInstance.curUL.querySelectorAll('li'), li) + this.uiFirstIndex;\n if (li.classList.contains(classNames.selected)) {\n if (this.uiIndices.activeIndices.indexOf(index) === -1) {\n this.uiIndices.activeIndices.push(index);\n }\n }\n else {\n this.uiIndices.activeIndices.splice(this.uiIndices.activeIndices.indexOf(index), 1);\n }\n };\n Virtualization.prototype.setSelectLI = function (li, e) {\n this.activeIndex = Array.prototype.indexOf.call(this.listViewInstance.curUL.querySelectorAll('li'), li) + this.uiFirstIndex;\n };\n Virtualization.prototype.checkedItem = function (checked) {\n var _this = this;\n if (checked) {\n this.uiIndices.activeIndices = [];\n this.activeIndex = undefined;\n this.listViewInstance.curViewDS.forEach(function (ds, index) {\n if (!ds.isHeader) {\n _this.uiIndices.activeIndices.push(index);\n }\n });\n }\n else {\n this.activeIndex = undefined;\n this.uiIndices.activeIndices = [];\n }\n };\n Virtualization.prototype.addUiItem = function (index) {\n var curViewDs = this.listViewInstance.curViewDS;\n this.changeUiIndices(index, true);\n if (this.activeIndex && this.activeIndex >= index) {\n this.activeIndex++;\n }\n if (this.listViewInstance.showCheckBox &&\n curViewDs[index][this.listViewInstance.fields.isChecked]) {\n this.uiIndices.activeIndices.push(index);\n }\n if (!parseFloat(this.bottomElement.style.height) && !parseFloat(this.topElement.style.height)) {\n this.bottomElement.style.height = parseFloat(this.bottomElement.style.height) + this.listItemHeight + 'px';\n }\n if (parseFloat(this.bottomElement.style.height)) {\n var liItem = this.listViewInstance.curUL.lastElementChild.previousSibling;\n var target = this.listViewInstance.getLiFromObjOrElement(curViewDs[index + 1]) ||\n this.listViewInstance.getLiFromObjOrElement(curViewDs[index + 2]);\n if (target) {\n this.bottomElement.style.height = parseFloat(this.bottomElement.style.height) + this.listItemHeight + 'px';\n this.updateUI(liItem, index, target);\n }\n }\n else {\n var liItem = this.listViewInstance.curUL.firstElementChild.nextSibling;\n var target = void 0;\n if ((Object.keys(this.listViewInstance.curViewDS).length - 1) === index) {\n target = this.listViewInstance.curUL.lastElementChild;\n }\n else {\n target = this.listViewInstance.getLiFromObjOrElement(curViewDs[index + 1]) ||\n this.listViewInstance.getLiFromObjOrElement(curViewDs[index + 2]);\n }\n this.topElement.style.height = parseFloat(this.topElement.style.height) + this.listItemHeight + 'px';\n this.uiFirstIndex++;\n this.uiLastIndex++;\n if (target) {\n this.updateUI(liItem, index, target);\n this.listViewInstance.isWindow ? window.scrollTo(0, (pageYOffset + this.listItemHeight)) :\n this.listViewInstance.element.scrollTop += this.listItemHeight;\n }\n }\n this.totalHeight += this.listItemHeight;\n this.listDiff = parseFloat(this.topElement.style.height) / this.listItemHeight;\n };\n Virtualization.prototype.removeUiItem = function (index) {\n this.totalHeight -= this.listItemHeight;\n var curViewDS = this.listViewInstance.curViewDS[index];\n var liItem = this.listViewInstance.getLiFromObjOrElement(curViewDS);\n this.listViewInstance.curViewDS.splice(index, 1);\n if (this.activeIndex && this.activeIndex >= index) {\n this.activeIndex--;\n }\n if (liItem) {\n if (this.domItemCount > Object.keys(this.listViewInstance.curViewDS).length) {\n detach(liItem);\n this.domItemCount--;\n this.uiLastIndex--;\n this.totalHeight = 0;\n }\n else {\n if (liItem.classList.contains(classNames.disable)) {\n liItem.classList.remove(classNames.disable);\n this.uiIndices.disabledItemIndices.splice(this.uiIndices.disabledItemIndices.indexOf(index), 1);\n }\n if (liItem.style.display === 'none') {\n liItem.style.display = '';\n this.uiIndices.hiddenItemIndices.splice(this.uiIndices.hiddenItemIndices.indexOf(index), 1);\n }\n if (this.listViewInstance.showCheckBox && liItem.classList.contains(classNames.selected)) {\n this.listViewInstance.removeSelect();\n this.uiIndices.activeIndices.splice(this.uiIndices.activeIndices.indexOf(index), 1);\n var checklistElement = liItem.querySelector('.' + classNames.checkboxWrapper);\n checklistElement.removeAttribute('aria-checked');\n checklistElement.firstElementChild.classList.remove(classNames.checked);\n if (liItem.classList.contains(classNames.focused)) {\n liItem.classList.remove(classNames.focused);\n this.activeIndex = undefined;\n }\n }\n else if (liItem.classList.contains(classNames.selected)) {\n this.listViewInstance.removeSelect();\n this.activeIndex = undefined;\n }\n if (!parseFloat(this.bottomElement.style.height) && !parseFloat(this.topElement.style.height)) {\n this.updateUI(liItem, this.uiLastIndex, this.bottomElement);\n }\n else if (parseFloat(this.bottomElement.style.height)) {\n this.bottomElement.style.height = parseFloat(this.bottomElement.style.height) - this.listItemHeight + 'px';\n this.updateUI(liItem, this.uiLastIndex, this.bottomElement);\n }\n else {\n this.topElement.style.height = parseFloat(this.topElement.style.height) - this.listItemHeight + 'px';\n this.updateUI(liItem, (this.uiFirstIndex - 1), this.topElement.nextSibling);\n this.uiLastIndex--;\n this.uiFirstIndex--;\n }\n }\n }\n this.changeUiIndices(index, false);\n this.listDiff = parseFloat(this.topElement.style.height) / this.listItemHeight;\n };\n Virtualization.prototype.changeUiIndices = function (index, increment) {\n var _this = this;\n Object.keys(this.uiIndices).forEach(function (key) {\n _this.uiIndices[key] = _this.uiIndices[key].map(function (i) {\n if (i >= index) {\n return increment ? ++i : --i;\n }\n else {\n return i;\n }\n });\n });\n };\n Virtualization.prototype.addItem = function (data, fields) {\n var _this = this;\n data.forEach(function (dataSource) {\n _this.listViewInstance.dataSource.push(dataSource);\n _this.listViewInstance.setViewDataSource(_this.listViewInstance.dataSource);\n if (!_this.domItemCount) {\n _this.uiVirtualization();\n }\n else if (_this.domItemCount < _this.expectedDomItemCount) {\n _this.wireScrollEvent(true);\n detach(_this.listViewInstance.contentContainer);\n _this.uiVirtualization();\n }\n else {\n var index = _this.listViewInstance.curViewDS.indexOf(dataSource);\n _this.addUiItem(index);\n var curViewDS = _this.listViewInstance.curViewDS[index - 1];\n if (curViewDS && curViewDS.isHeader && curViewDS.items.length === 1) {\n _this.addUiItem(index - 1);\n }\n }\n });\n };\n Virtualization.prototype.createUIItem = function (args) {\n var template = this.listViewInstance.createElement('div');\n var commonTemplate = '
' +\n ' ${' + this.listViewInstance.fields.text + '}
';\n template.innerHTML = this.listViewInstance.template || commonTemplate;\n var templateElements = template.getElementsByTagName('*');\n var groupTemplate = this.listViewInstance.createElement('div');\n if (this.listViewInstance.fields.groupBy) {\n groupTemplate.innerHTML = this.listViewInstance.groupTemplate || commonTemplate;\n }\n var groupTemplateElements = groupTemplate.getElementsByTagName('*');\n if (args.curData.isHeader) {\n this.headerData = args.curData;\n }\n this.templateData = args.curData.isHeader ? args.curData.items[0] :\n args.curData;\n args.item.innerHTML = '';\n args.item.context = { data: args.curData, nodes: { flatTemplateNodes: [], groupTemplateNodes: [] } };\n for (var i = 0; i < templateElements.length; i++) {\n this.compileTemplate(templateElements[i], args.item, false);\n }\n for (var i = 0; i < groupTemplateElements.length; i++) {\n this.compileTemplate(groupTemplateElements[i], args.item, true);\n }\n args.item.context.template = args.curData.isHeader ? template.firstElementChild :\n groupTemplate.firstElementChild;\n args.item.context.type = args.curData.isHeader ? 'flatList' : 'groupList';\n var element = args.curData.isHeader ? groupTemplate : template;\n args.item.insertBefore(element.firstElementChild, null);\n };\n Virtualization.prototype.compileTemplate = function (element, item, isHeader) {\n this.textProperty(element, item, isHeader);\n this.classProperty(element, item, isHeader);\n this.attributeProperty(element, item, isHeader);\n };\n Virtualization.prototype.onChange = function (newData, listElement) {\n listElement.context.data = newData;\n var groupTemplateNodes = listElement.context.nodes.groupTemplateNodes;\n var flatTemplateNodes = listElement.context.nodes.flatTemplateNodes;\n if (!isNullOrUndefined(newData.isHeader) && newData.isHeader && listElement.context.type === 'groupList') {\n var element = listElement.firstElementChild;\n detach(listElement.firstElementChild);\n listElement.insertBefore(listElement.context.template, null);\n listElement.context.template = element;\n listElement.context.type = 'flatList';\n groupTemplateNodes.forEach(function (node) { return node.onChange(newData); });\n }\n else if (!newData.isHeader && listElement.context.type === 'flatList') {\n var element = listElement.firstElementChild;\n detach(listElement.firstElementChild);\n listElement.insertBefore(listElement.context.template, null);\n listElement.context.template = element;\n listElement.context.type = 'groupList';\n flatTemplateNodes.forEach(function (node) { return node.onChange(newData); });\n }\n else if (!newData.isHeader) {\n flatTemplateNodes.forEach(function (node) { return node.onChange(newData); });\n }\n else {\n groupTemplateNodes.forEach(function (node) { return node.onChange(newData); });\n }\n };\n Virtualization.prototype.updateContextData = function (listElement, node, isHeader) {\n if (isHeader) {\n listElement.context.nodes.groupTemplateNodes.push(node);\n }\n else {\n listElement.context.nodes.flatTemplateNodes.push(node);\n }\n };\n Virtualization.prototype.classProperty = function (element, listElement, isHeader) {\n var _this = this;\n var regex = new RegExp('\\\\${([^}]*)}', 'g');\n var resultantOutput = [];\n var regexMatch;\n while (regexMatch !== null) {\n var match = regex.exec(element.className);\n resultantOutput.push(match);\n regexMatch = match;\n if (regexMatch === null) {\n resultantOutput.pop();\n }\n }\n if (resultantOutput && resultantOutput.length) {\n resultantOutput.forEach(function (classNameMatch) {\n var classFunction;\n if (classNameMatch[1].indexOf('?') !== -1 && classNameMatch[1].indexOf(':') !== -1) {\n // tslint:disable-next-line:no-function-constructor-with-string-args\n classFunction = new Function('data', 'return ' + classNameMatch[1].replace(/\\$/g, 'data.'));\n }\n else {\n // tslint:disable-next-line:no-function-constructor-with-string-args\n classFunction = new Function('data', 'return ' + 'data.' + classNameMatch[1]);\n }\n var subNode = {};\n if (isHeader) {\n subNode.bindedvalue = classFunction(_this.headerData);\n }\n else {\n subNode.bindedvalue = classFunction(_this.templateData);\n }\n subNode.onChange = function (value) {\n element.classList.remove(subNode.bindedvalue);\n element.classList.add(classFunction(value));\n subNode.bindedvalue = classFunction(value);\n };\n classNameMatch[0].split(' ').forEach(function (className) {\n element.classList.remove(className);\n });\n element.classList.add(subNode.bindedvalue);\n _this.updateContextData(listElement, subNode, isHeader);\n });\n }\n };\n Virtualization.prototype.attributeProperty = function (element, listElement, isHeader) {\n var _this = this;\n var attributeNames = [];\n for (var i = 0; i < element.attributes.length; i++) {\n attributeNames.push(element.attributes[i].nodeName);\n }\n if (attributeNames.indexOf('class') !== -1) {\n attributeNames.splice(attributeNames.indexOf('class'), 1);\n }\n attributeNames.forEach(function (attributeName) {\n var attrNameMatch = new RegExp('\\\\${([^}]*)}', 'g').exec(attributeName) || [];\n var attrValueMatch = new RegExp('\\\\${([^}]*)}', 'g').exec(element.getAttribute(attributeName))\n || [];\n var attributeNameFunction;\n var attributeValueFunction;\n if (attrNameMatch.length || attrValueMatch.length) {\n if (attrNameMatch[1]) {\n // tslint:disable-next-line:no-function-constructor-with-string-args\n attributeNameFunction = new Function('data', 'return ' + 'data.' + attrNameMatch[1]);\n }\n if (attrValueMatch[1]) {\n if (attrValueMatch[1].indexOf('?') !== -1 && attrValueMatch[1].indexOf(':') !== -1) {\n // tslint:disable-next-line:no-function-constructor-with-string-args\n attributeValueFunction = new Function('data', 'return ' + attrValueMatch[1].replace(/\\$/g, 'data.'));\n }\n else {\n // tslint:disable-next-line:no-function-constructor-with-string-args\n attributeValueFunction = new Function('data', 'return ' + 'data.' + attrValueMatch[1]);\n }\n }\n var subNode_1 = {};\n if (isHeader) {\n subNode_1.bindedvalue = [attrNameMatch[1] === undefined ? undefined : attributeNameFunction(_this.headerData),\n attrValueMatch[1] === undefined ? undefined : attributeValueFunction(_this.headerData)];\n }\n else {\n subNode_1.bindedvalue = [attrNameMatch[1] === undefined ? undefined : attributeNameFunction(_this.templateData),\n attrValueMatch[1] === undefined ? undefined : attributeValueFunction(_this.templateData)];\n }\n subNode_1.attrName = subNode_1.bindedvalue[0] === undefined ?\n attributeName : subNode_1.bindedvalue[0];\n subNode_1.onChange = function (value) {\n var bindedvalue = subNode_1.bindedvalue[1] === undefined ?\n element.getAttribute(subNode_1.attrName) : attributeValueFunction(value);\n element.removeAttribute(subNode_1.attrName);\n subNode_1.attrName = subNode_1.bindedvalue[0] === undefined ? subNode_1.attrName : attributeNameFunction(value);\n element.setAttribute(subNode_1.attrName, bindedvalue);\n subNode_1.bindedvalue = [subNode_1.bindedvalue[0] === undefined ? undefined : attributeNameFunction(value),\n subNode_1.bindedvalue[1] === undefined ? undefined : attributeValueFunction(value)];\n };\n var attributeValue = subNode_1.bindedvalue[1] === undefined ? element.getAttribute(attributeName) :\n subNode_1.bindedvalue[1];\n element.removeAttribute(attributeName);\n element.setAttribute(subNode_1.attrName, attributeValue);\n _this.updateContextData(listElement, subNode_1, isHeader);\n }\n });\n };\n Virtualization.prototype.textProperty = function (element, listElement, isHeader) {\n var _this = this;\n var regex = new RegExp('\\\\${([^}]*)}', 'g');\n var resultantOutput = [];\n var regexMatch;\n while (regexMatch !== null) {\n var match = regex.exec(element.innerText);\n resultantOutput.push(match);\n regexMatch = match;\n if (regexMatch === null) {\n resultantOutput.pop();\n }\n }\n var isChildHasTextContent = Array.prototype.some.call(element.children, function (element) {\n if (new RegExp('\\\\${([^}]*)}', 'g').exec(element.innerText)) {\n return true;\n }\n else {\n return false;\n }\n });\n if (resultantOutput && resultantOutput.length && !isChildHasTextContent) {\n resultantOutput.forEach(function (textPropertyMatch) {\n var subNode = {};\n var textFunction;\n if (textPropertyMatch[1].indexOf('?') !== -1 && textPropertyMatch[1].indexOf(':') !== -1) {\n // tslint:disable-next-line:no-function-constructor-with-string-args\n textFunction = new Function('data', 'return ' + textPropertyMatch[1].replace(/\\$/g, 'data.'));\n }\n else {\n // tslint:disable-next-line:no-function-constructor-with-string-args\n textFunction = new Function('data', 'return ' + 'data.' + textPropertyMatch[1]);\n }\n if (isHeader) {\n subNode.bindedvalue = textFunction(_this.headerData);\n }\n else {\n subNode.bindedvalue = textFunction(_this.templateData);\n }\n subNode.onChange = function (value) {\n element.innerText = element.innerText.replace(subNode.bindedvalue, textFunction(value));\n subNode.bindedvalue = textFunction(value);\n };\n element.innerText = element.innerText.replace(textPropertyMatch[0], subNode.bindedvalue);\n _this.updateContextData(listElement, subNode, isHeader);\n });\n }\n };\n Virtualization.prototype.reRenderUiVirtualization = function () {\n this.wireScrollEvent(true);\n if (this.listViewInstance.contentContainer) {\n detach(this.listViewInstance.contentContainer);\n }\n this.listViewInstance.preRender();\n this.listViewInstance.localData = this.listViewInstance.dataSource;\n this.listViewInstance.renderList();\n };\n Virtualization.prototype.updateUI = function (element, index, targetElement) {\n if (this.listViewInstance.template || this.listViewInstance.groupTemplate) {\n var curViewDS = this.listViewInstance.curViewDS[index];\n element.dataset.uid = curViewDS[this.listViewInstance.fields.id] ?\n curViewDS[this.listViewInstance.fields.id].toString() : ListBase.generateId();\n this.onChange(curViewDS, element);\n }\n else {\n this.updateUiContent(element, index);\n }\n this.changeElementAttributes(element, index);\n if (targetElement) {\n this.listViewInstance.ulElement.insertBefore(element, targetElement);\n }\n };\n Virtualization.prototype.getModuleName = function () {\n return 'virtualization';\n };\n Virtualization.prototype.destroy = function () {\n this.wireScrollEvent(true);\n };\n return Virtualization;\n}());\nexport { Virtualization };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n///
\nimport { Property, EventHandler, Internationalization, NotifyPropertyChanges, detach, getUniqueID } from '@syncfusion/ej2-base';\nimport { KeyboardEvents, Event, Browser, L10n, ChildProperty } from '@syncfusion/ej2-base';\nimport { addClass, createElement, remove, closest, select, prepend, removeClass, attributes, Collection } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, isUndefined, formatUnit, setValue, rippleEffect, merge, extend } from '@syncfusion/ej2-base';\nimport { CalendarBase } from '../calendar/calendar';\nimport { Popup } from '@syncfusion/ej2-popups';\nimport { Button } from '@syncfusion/ej2-buttons';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { ListBase, cssClass as ListBaseClasses } from '@syncfusion/ej2-lists';\nvar DATERANGEWRAPPER = 'e-date-range-wrapper';\nvar INPUTCONTAINER = 'e-input-group';\nvar DATERANGEICON = 'e-input-group-icon e-range-icon e-icons';\nvar POPUP = 'e-popup';\nvar LEFTCALENDER = 'e-left-calendar';\nvar RIGHTCALENDER = 'e-right-calendar';\nvar LEFTCONTAINER = 'e-left-container';\nvar RIGHTCONTAINER = 'e-right-container';\nvar ROOT = 'e-daterangepicker';\nvar ERROR = 'e-error';\nvar ACTIVE = 'e-active';\nvar STARTENDCONTAINER = 'e-start-end';\nvar STARTDATE = 'e-start-date';\nvar ENDDATE = 'e-end-date';\nvar STARTBUTTON = 'e-start-btn';\nvar INPUTFOCUS = 'e-input-focus';\nvar ENDBUTTON = 'e-end-btn';\nvar RANGEHOVER = 'e-range-hover';\nvar OTHERMONTH = 'e-other-month';\nvar STARTLABEL = 'e-start-label';\nvar ENDLABEL = 'e-end-label';\nvar DISABLED = 'e-disabled';\nvar SELECTED = 'e-selected';\nvar CALENDAR = 'e-calendar';\nvar NEXTICON = 'e-next';\nvar PREVICON = 'e-prev';\nvar HEADER = 'e-header';\nvar TITLE = 'e-title';\nvar ICONCONTAINER = 'e-icon-container';\nvar RANGECONTAINER = 'e-date-range-container';\nvar RANGEHEADER = 'e-range-header';\nvar PRESETS = 'e-presets';\nvar FOOTER = 'e-footer';\nvar RANGEBORDER = 'e-range-border';\nvar TODAY = 'e-today';\nvar FOCUSDATE = 'e-focused-date';\nvar CONTENT = 'e-content';\nvar DAYSPAN = 'e-day-span';\nvar WEEKNUMBER = 'e-week-number';\nvar DATEDISABLED = 'e-date-disabled';\nvar ICONDISABLED = 'e-icon-disabled';\nvar CALENDARCONTAINER = 'e-calendar-container';\nvar SEPARATOR = 'e-separator';\nvar APPLY = 'e-apply';\nvar CANCEL = 'e-cancel';\nvar DEVICE = 'e-device';\nvar OVERLAY = 'e-overlay';\nvar CHANGEICON = 'e-change-icon e-icons';\nvar LISTCLASS = ListBaseClasses.li;\nvar RTL = 'e-rtl';\nvar HOVER = 'e-hover';\nvar OVERFLOW = 'e-range-overflow';\nvar OFFSETVALUE = 4;\nvar PRIMARY = 'e-primary';\nvar FLAT = 'e-flat';\nvar CSS = 'e-css';\nvar Presets = /** @class */ (function (_super) {\n __extends(Presets, _super);\n function Presets() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], Presets.prototype, \"label\", void 0);\n __decorate([\n Property()\n ], Presets.prototype, \"start\", void 0);\n __decorate([\n Property()\n ], Presets.prototype, \"end\", void 0);\n return Presets;\n}(ChildProperty));\nexport { Presets };\n/**\n * Represents the DateRangePicker component that allows user to select the date range from the calendar\n * or entering the range through the input element.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar DateRangePicker = /** @class */ (function (_super) {\n __extends(DateRangePicker, _super);\n /**\n * Constructor for creating the widget\n */\n function DateRangePicker(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.isCustomRange = false;\n _this.isCustomWindow = false;\n _this.presetsItem = [];\n _this.liCollections = [];\n _this.previousEleValue = '';\n _this.isKeyPopup = false;\n _this.dateDisabled = false;\n _this.isRangeIconClicked = false;\n _this.isMaxDaysClicked = false;\n _this.disabledDays = [];\n _this.preventBlur = false;\n _this.preventFocus = false;\n return _this;\n }\n /**\n * To Initialize the control rendering.\n * @return void\n * @private\n */\n DateRangePicker.prototype.render = function () {\n this.initialize();\n this.setProperties({ startDate: this.startValue }, true);\n this.setProperties({ endDate: this.endValue }, true);\n this.setModelValue();\n };\n /**\n * Initialize the event handler\n * @returns void\n * @private\n */\n DateRangePicker.prototype.preRender = function () {\n this.presetKeyConfig = {\n moveUp: 'uparrow',\n moveDown: 'downarrow',\n enter: 'enter',\n tab: 'tab',\n spacebar: 'space'\n };\n this.keyInputConfigs = {\n altDownArrow: 'alt+downarrow',\n escape: 'escape',\n enter: 'enter',\n tab: 'tab',\n };\n this.defaultConstant = {\n placeholder: '',\n startLabel: 'Start Date',\n endLabel: 'End Date',\n customRange: 'Custom Range',\n applyText: 'Apply',\n cancelText: 'Cancel',\n selectedDays: 'Selected Days',\n days: 'days'\n };\n /**\n * Mobile View\n */\n this.isMobile = window.matchMedia('(max-width:550px)').matches;\n this.inputElement = this.element;\n this.angularTag = null;\n if (this.element.tagName === 'EJS-DATERANGEPICKER') {\n this.angularTag = this.element.tagName;\n this.inputElement = this.createElement('input');\n this.element.appendChild(this.inputElement);\n }\n this.cloneElement = this.element.cloneNode(true);\n if (this.element.getAttribute('id')) {\n if (this.angularTag !== null) {\n this.inputElement.id = this.element.getAttribute('id') + '_input';\n }\n }\n else {\n this.element.id = getUniqueID('ej2-datetimepicker');\n if (this.angularTag !== null) {\n attributes(this.inputElement, { 'id': this.element.id + '_input' });\n }\n }\n this.initProperty();\n _super.prototype.preRender.call(this);\n this.navNextFunction = this.navNextMonth.bind(this);\n this.navPrevFunction = this.navPrevMonth.bind(this);\n this.deviceNavNextFunction = this.deviceNavNext.bind(this);\n this.deviceNavPrevFunction = this.deviceNavPrevious.bind(this);\n this.initStartDate = this.checkDateValue(this.startValue);\n this.initEndDate = this.checkDateValue(this.endValue);\n };\n ;\n DateRangePicker.prototype.updateValue = function () {\n var dateOptions = { format: this.format, type: 'date', skeleton: 'yMd' };\n if (this.value && this.value.length > 0) {\n if (this.value[0] instanceof Date && !isNaN(+this.value[0])) {\n this.setProperties({ startDate: this.value[0] }, true);\n this.startValue = this.value[0];\n }\n else if (typeof this.value[0] === 'string') {\n this.setProperties({ startDate: new Date('' + this.value[0]) }, true);\n this.startValue = new Date('' + this.value[0]);\n }\n else {\n this.startValue = null;\n this.setValue();\n }\n if (this.value[1] instanceof Date && !isNaN(+this.value[1])) {\n this.setProperties({ endDate: this.value[1] }, true);\n this.endValue = this.value[1];\n }\n else if (typeof this.value[1] === 'string') {\n this.setProperties({ endDate: new Date('' + this.value[1]) }, true);\n this.endValue = new Date('' + this.value[1]);\n this.setValue();\n }\n else {\n this.setProperties({ endDate: null }, true);\n this.endValue = null;\n this.setValue();\n }\n }\n else if (this.value && this.value.start) {\n if (this.value.start instanceof Date && !isNaN(+this.value.start)) {\n this.setProperties({ startDate: this.value.start }, true);\n this.startValue = this.value.start;\n }\n else if (typeof this.value.start === 'string') {\n this.setProperties({ startDate: new Date('' + this.value.start) }, true);\n this.startValue = new Date('' + this.value.start);\n }\n else {\n this.startValue = null;\n this.setValue();\n }\n if (this.value.end instanceof Date && !isNaN(+this.value.end)) {\n this.setProperties({ endDate: this.value.end }, true);\n this.endValue = this.value.end;\n }\n else if (typeof this.value.end === 'string') {\n this.setProperties({ endDate: new Date('' + this.value.end) }, true);\n this.endValue = new Date('' + this.value.end);\n this.setValue();\n }\n else {\n this.setProperties({ endDate: null }, true);\n this.endValue = null;\n this.setValue();\n }\n }\n else if (isNullOrUndefined(this.value)) {\n this.endValue = this.checkDateValue(new Date('' + this.endDate));\n this.startValue = this.checkDateValue(new Date('' + this.startDate));\n this.setValue();\n }\n };\n DateRangePicker.prototype.initProperty = function () {\n this.globalize = new Internationalization(this.locale);\n if (isNullOrUndefined(this.firstDayOfWeek) || this.firstDayOfWeek > 6 || this.firstDayOfWeek < 0) {\n this.setProperties({ firstDayOfWeek: this.globalize.getFirstDayOfWeek() }, true);\n }\n this.updateValue();\n };\n DateRangePicker.prototype.initialize = function () {\n if (this.angularTag !== null) {\n this.validationAttribute(this.element, this.inputElement);\n }\n this.checkHtmlAttributes();\n merge(this.keyConfigs, { shiftTab: 'shift+tab' });\n this.setProperties({ startDate: this.checkDateValue(new Date('' + this.startValue)) }, true); // persist the value propeerty.\n this.setProperties({ endValue: this.checkDateValue(new Date('' + this.endValue)) }, true);\n this.setValue();\n this.setProperties({ min: this.checkDateValue(new Date('' + this.min)) }, true);\n this.setProperties({ max: this.checkDateValue(new Date('' + this.max)) }, true);\n this.l10n = new L10n('daterangepicker', this.defaultConstant, this.locale);\n this.l10n.setLocale(this.locale);\n this.setProperties({ placeholder: this.placeholder || this.l10n.getConstant('placeholder') }, true);\n this.processPresets();\n this.createInput();\n this.setRangeAllowEdit();\n this.bindEvents();\n };\n DateRangePicker.prototype.setRangeAllowEdit = function () {\n if (this.allowEdit) {\n if (!this.readonly) {\n this.inputElement.removeAttribute('readonly');\n }\n }\n else {\n attributes(this.inputElement, { 'readonly': '' });\n }\n };\n DateRangePicker.prototype.validationAttribute = function (element, input) {\n var name = element.getAttribute('name') ? element.getAttribute('name') : element.getAttribute('id');\n input.setAttribute('name', name);\n element.removeAttribute('name');\n var attributes = ['required', 'aria-required', 'form'];\n for (var i = 0; i < attributes.length; i++) {\n if (isNullOrUndefined(element.getAttribute(attributes[i]))) {\n continue;\n }\n var attr = element.getAttribute(attributes[i]);\n input.setAttribute(attributes[i], attr);\n element.removeAttribute(attributes[i]);\n }\n };\n DateRangePicker.prototype.processPresets = function () {\n var i = 0;\n if (!isUndefined(this.presets[0].start && this.presets[0].end && this.presets[0].label)) {\n for (var _i = 0, _a = this.presets; _i < _a.length; _i++) {\n var range = _a[_i];\n var id = range.label.replace(/\\s+/g, '') + '_' + (++i);\n if (typeof range.end === 'string') {\n this.presetsItem.push({\n id: id, text: range.label, end: new Date('' + range.end), start: new Date('' + range.start)\n });\n }\n else {\n this.presetsItem.push({ id: id, text: range.label, start: range.start, end: range.end });\n }\n }\n var startDate = isNullOrUndefined(this.startValue) ? null : new Date(+this.startValue);\n var endDate = isNullOrUndefined(this.endValue) ? null : new Date(+this.endValue);\n this.presetsItem.push({ id: 'custom_range', text: this.l10n.getConstant('customRange'), start: startDate, end: endDate });\n if (!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) {\n this.isCustomRange = true;\n this.activeIndex = this.presetsItem.length - 1;\n }\n }\n };\n DateRangePicker.prototype.bindEvents = function () {\n var form = closest(this.element, 'form');\n if (this.enabled) {\n EventHandler.add(this.inputWrapper.buttons[0], 'mousedown', this.rangeIconHandler, this);\n EventHandler.add(this.inputElement, 'focus', this.inputFocusHandler, this);\n EventHandler.add(this.inputElement, 'blur', this.inputBlurHandler, this);\n EventHandler.add(this.inputElement, 'change', this.inputChangeHandler, this);\n if (this.showClearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler, this);\n }\n if (!this.isMobile) {\n this.inputKeyboardModule = new KeyboardEvents(this.inputElement, {\n eventName: 'keydown', keyAction: this.inputHandler.bind(this), keyConfigs: this.keyInputConfigs\n });\n }\n if (form) {\n EventHandler.add(form, 'reset', this.formResetHandler.bind(this));\n }\n }\n else {\n EventHandler.remove(this.inputWrapper.buttons[0], 'mousedown', this.rangeIconHandler);\n EventHandler.remove(this.inputElement, 'blur', this.inputBlurHandler);\n EventHandler.remove(this.inputElement, 'focus', this.inputFocusHandler);\n EventHandler.remove(this.inputElement, 'change', this.inputChangeHandler);\n if (this.showClearButton) {\n EventHandler.remove(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler);\n }\n if (!this.isMobile) {\n if (!isNullOrUndefined(this.inputKeyboardModule)) {\n this.inputKeyboardModule.destroy();\n }\n }\n if (form) {\n EventHandler.remove(form, 'reset', this.formResetHandler.bind(this));\n }\n }\n };\n DateRangePicker.prototype.inputChangeHandler = function (e) {\n e.stopPropagation();\n };\n DateRangePicker.prototype.bindClearEvent = function () {\n if (this.showClearButton && this.inputWrapper.clearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler, this);\n }\n };\n DateRangePicker.prototype.resetHandler = function (e) {\n this.valueType = this.value;\n e.preventDefault();\n this.clear();\n this.changeTrigger(e);\n this.clearRange();\n this.hide(e);\n };\n DateRangePicker.prototype.formResetHandler = function () {\n this.value = null;\n if (this.inputElement) {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n attributes(this.inputElement, { 'aria-invalid': 'false' });\n removeClass([this.inputWrapper.container], ERROR);\n }\n };\n DateRangePicker.prototype.clear = function () {\n if (this.startValue !== null) {\n this.startValue = null;\n }\n if (this.endValue !== null) {\n this.endValue = null;\n }\n if (this.value && this.value.start) {\n this.setProperties({ value: { start: null, end: null } }, true);\n }\n if (this.value !== null && this.value.length > 0) {\n this.setProperties({ value: null }, true);\n }\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n if (!(isNullOrUndefined(this.applyButton))) {\n this.applyButton.disabled = this.applyButton.element.disabled = true;\n }\n this.removeSelection();\n };\n DateRangePicker.prototype.rangeIconHandler = function (e) {\n e.preventDefault();\n this.targetElement = null;\n if (this.isPopupOpen()) {\n this.applyFunction(e);\n }\n else {\n this.isRangeIconClicked = true;\n if (!this.isMobile) {\n this.inputWrapper.container.children[0].focus();\n }\n this.show(null, e);\n if (!this.isMobile) {\n if (!isNullOrUndefined(this.leftCalendar)) {\n this.isRangeIconClicked = false;\n this.calendarFocus();\n this.isRangeIconClicked = true;\n }\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n }\n }\n };\n DateRangePicker.prototype.checkHtmlAttributes = function () {\n this.globalize = new Internationalization(this.locale);\n var attributes;\n attributes = ['startDate', 'endDate', 'minDays', 'maxDays', 'min', 'max', 'disabled',\n 'readonly', 'style', 'name', 'placeholder', 'type'];\n var format = { format: this.format, type: 'date', skeleton: 'yMd' };\n for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {\n var prop = attributes_1[_i];\n if (!isNullOrUndefined(this.inputElement.getAttribute(prop))) {\n switch (prop) {\n case 'disabled':\n var disabled = this.inputElement.getAttribute(prop) === 'disabled' ||\n this.inputElement.getAttribute(prop) === '';\n this.setProperties({ enabled: !disabled }, true);\n break;\n case 'readonly':\n var readonly = this.inputElement.getAttribute(prop) === 'readonly' ||\n this.inputElement.getAttribute(prop) === '';\n this.setProperties({ readonly: readonly }, true);\n break;\n case 'placeholder':\n if (isNullOrUndefined(this.placeholder) || this.placeholder.trim() === '') {\n this.setProperties({ placeholder: this.inputElement.getAttribute(prop) }, true);\n }\n break;\n case 'style':\n this.inputElement.setAttribute('style', '' + this.inputElement.getAttribute(prop));\n break;\n case 'min':\n if (isNullOrUndefined(this.min) || +this.min === +new Date(1900, 0, 1)) {\n var dateValue = this.globalize.parseDate(this.inputElement.getAttribute(prop), format);\n this.setProperties(setValue(prop, dateValue, {}), true);\n }\n break;\n case 'name':\n this.inputElement.setAttribute('name', '' + this.inputElement.getAttribute(prop));\n break;\n case 'max':\n if (isNullOrUndefined(this.max) || +this.max === +new Date(2099, 11, 31)) {\n var dateValue = this.globalize.parseDate(this.inputElement.getAttribute(prop), format);\n this.setProperties(setValue(prop, dateValue, {}), true);\n }\n break;\n case 'startDate':\n if (isNullOrUndefined(this.startDate)) {\n var dateValue = this.globalize.parseDate(this.inputElement.getAttribute(prop), format);\n this.startValue = dateValue;\n this.setValue();\n }\n break;\n case 'endDate':\n if (isNullOrUndefined(this.endDate)) {\n var dateValue = this.globalize.parseDate(this.inputElement.getAttribute(prop), format);\n this.endValue = dateValue;\n this.setValue();\n }\n break;\n case 'minDays':\n if (isNullOrUndefined(this.minDays)) {\n this.setProperties(setValue(prop, parseInt(this.inputElement.getAttribute(prop), 10), {}), true);\n }\n break;\n case 'maxDays':\n if (isNullOrUndefined(this.maxDays)) {\n this.setProperties(setValue(prop, parseInt(this.inputElement.getAttribute(prop), 10), {}), true);\n }\n break;\n case 'type':\n if (this.inputElement.getAttribute(prop) !== 'text') {\n this.inputElement.setAttribute('type', 'text');\n }\n break;\n }\n }\n }\n };\n DateRangePicker.prototype.createPopup = function () {\n for (var i = 0; i < this.presetsItem.length; i++) {\n if ((i !== (this.presetsItem.length - 1)) && this.presetsItem[i].id === 'custom_range') {\n this.presetsItem.splice(i, 1);\n }\n }\n this.activeIndex = this.presetsItem.length - 1;\n this.isCustomRange = true;\n for (var i = 0; i <= this.presetsItem.length - 2; i++) {\n var startDate = this.presetsItem[i].start;\n var endDate = this.presetsItem[i].end;\n if (this.startValue && this.endValue) {\n if ((+startDate.setMilliseconds(0) === +this.startValue.setMilliseconds(0)) &&\n (+endDate.setMilliseconds(0) === +this.endValue.setMilliseconds(0))) {\n this.activeIndex = i;\n this.isCustomRange = false;\n }\n }\n }\n this.popupWrapper = createElement('div', { id: this.element.id + '_popup', className: ROOT + ' ' + POPUP });\n var isPreset = (!this.isCustomRange || this.isMobile);\n if (!isUndefined(this.presets[0].start && this.presets[0].end && this.presets[0].label) && isPreset) {\n this.isCustomWindow = false;\n this.createPresets();\n this.listRippleEffect();\n this.renderPopup();\n }\n else {\n this.isCustomWindow = true;\n this.renderControl();\n }\n };\n DateRangePicker.prototype.renderControl = function () {\n this.createControl();\n this.bindCalendarEvents();\n this.updateRange((this.isMobile ? [this.calendarElement] : [this.leftCalendar, this.rightCalendar]));\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n this.disabledDateRender();\n }\n this.updateHeader();\n };\n DateRangePicker.prototype.clearCalendarEvents = function () {\n EventHandler.clearEvents(this.leftCalPrevIcon);\n EventHandler.clearEvents(this.leftCalNextIcon);\n EventHandler.clearEvents(this.rightCalPrevIcon);\n EventHandler.clearEvents(this.rightCalNextIcon);\n };\n DateRangePicker.prototype.updateNavIcons = function () {\n if (this.currentView() === 'Year' || this.currentView() === 'Decade') {\n return;\n }\n this.previousIcon = this.rightCalPrevIcon;\n this.nextIcon = this.leftCalNextIcon;\n this.nextIconHandler(this.compareMonths(new Date('' + this.leftCalCurrentDate), this.rightCalCurrentDate) < 1);\n this.previousIconHandler(this.compareMonths(new Date('' + this.leftCalCurrentDate), this.rightCalCurrentDate) < 1);\n };\n DateRangePicker.prototype.calendarIconEvent = function () {\n this.clearCalendarEvents();\n if (this.leftCalPrevIcon && !this.leftCalPrevIcon.classList.contains(DISABLED)) {\n EventHandler.add(this.leftCalPrevIcon, 'mousedown touchstart', this.navPrevFunction);\n }\n if (this.leftCalNextIcon && !this.leftCalNextIcon.classList.contains(DISABLED)) {\n EventHandler.add(this.leftCalNextIcon, 'mousedown touchstart', this.navNextFunction);\n }\n if (this.rightCalPrevIcon && !this.rightCalPrevIcon.classList.contains(DISABLED)) {\n EventHandler.add(this.rightCalPrevIcon, 'mousedown touchstart', this.navPrevFunction);\n }\n if (this.rightCalNextIcon && !this.rightCalNextIcon.classList.contains(DISABLED)) {\n EventHandler.add(this.rightCalNextIcon, 'mousedown touchstart', this.navNextFunction);\n }\n };\n DateRangePicker.prototype.bindCalendarEvents = function () {\n if (!this.isMobile) {\n this.updateNavIcons();\n this.calendarIconEvent();\n this.calendarIconRipple();\n this.headerTitleElement = this.popupObj.element.querySelector('.' + RIGHTCALENDER + ' .' + HEADER + ' .' + TITLE);\n this.headerTitleElement = this.popupObj.element.querySelector('.' + LEFTCALENDER + ' .' + HEADER + ' .' + TITLE);\n this.leftKeyboardModule = new KeyboardEvents(this.leftCalendar, {\n eventName: 'keydown',\n keyAction: this.keyInputHandler.bind(this),\n keyConfigs: this.keyConfigs\n });\n this.rightKeyboardModule = new KeyboardEvents(this.rightCalendar, {\n eventName: 'keydown',\n keyAction: this.keyInputHandler.bind(this),\n keyConfigs: this.keyConfigs\n });\n }\n else {\n this.deviceCalendarEvent();\n EventHandler.add(this.startButton.element, 'click touchstart', this.deviceHeaderClick, this);\n EventHandler.add(this.endButton.element, 'click touchstart', this.deviceHeaderClick, this);\n }\n this.bindCalendarCellEvents();\n this.removeFocusedDate();\n };\n DateRangePicker.prototype.calendarIconRipple = function () {\n rippleEffect(this.leftCalPrevIcon, { selector: '.e-prev', duration: 400, isCenterRipple: true });\n rippleEffect(this.leftCalNextIcon, { selector: '.e-next', duration: 400, isCenterRipple: true });\n rippleEffect(this.rightCalPrevIcon, { selector: '.e-prev', duration: 400, isCenterRipple: true });\n rippleEffect(this.rightCalNextIcon, { selector: '.e-next', duration: 400, isCenterRipple: true });\n };\n DateRangePicker.prototype.deviceCalendarEvent = function () {\n EventHandler.clearEvents(this.nextIcon);\n EventHandler.clearEvents(this.previousIcon);\n rippleEffect(this.nextIcon, { selector: '.e-prev', duration: 400, isCenterRipple: true });\n rippleEffect(this.previousIcon, { selector: '.e-next', duration: 400, isCenterRipple: true });\n if (this.nextIcon && !this.nextIcon.classList.contains(DISABLED)) {\n EventHandler.add(this.nextIcon, 'mousedown', this.deviceNavNextFunction);\n }\n if (this.previousIcon && !this.previousIcon.classList.contains(DISABLED)) {\n EventHandler.add(this.previousIcon, 'mousedown', this.deviceNavPrevFunction);\n }\n };\n DateRangePicker.prototype.deviceNavNext = function (e) {\n var calendar = closest(e.target, '.' + CALENDAR);\n this.updateDeviceCalendar(calendar);\n this.navigateNext(e);\n this.deviceNavigation();\n };\n DateRangePicker.prototype.deviceNavPrevious = function (e) {\n var calendar = closest(e.target, '.' + CALENDAR);\n this.updateDeviceCalendar(calendar);\n this.navigatePrevious(e);\n this.deviceNavigation();\n };\n DateRangePicker.prototype.updateDeviceCalendar = function (calendar) {\n if (calendar) {\n this.previousIcon = calendar.querySelector('.' + PREVICON);\n this.nextIcon = calendar.querySelector('.' + NEXTICON);\n this.calendarElement = calendar;\n this.deviceCalendar = calendar;\n this.contentElement = calendar.querySelector('.' + CONTENT);\n this.tableBodyElement = select('.' + CONTENT + ' tbody', calendar);\n this.table = calendar.querySelector('.' + CONTENT).getElementsByTagName('table')[0];\n this.headerTitleElement = calendar.querySelector('.' + HEADER + ' .' + TITLE);\n this.headerElement = calendar.querySelector('.' + HEADER);\n }\n };\n DateRangePicker.prototype.deviceHeaderClick = function (event) {\n var element = event.currentTarget;\n if (element.classList.contains(STARTBUTTON) && !isNullOrUndefined(this.startValue)) {\n this.endButton.element.classList.remove(ACTIVE);\n this.startButton.element.classList.add(ACTIVE);\n var calendar = this.popupObj.element.querySelector('.' + CALENDAR);\n this.updateDeviceCalendar(calendar);\n if (isNullOrUndefined(this.calendarElement.querySelector('.' + STARTDATE + ':not(.e-other-month)'))) {\n this.currentDate = new Date(+this.startValue);\n remove(this.tableBodyElement);\n this.renderMonths();\n this.deviceNavigation();\n }\n this.removeClassDisabled();\n }\n else if (!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) {\n this.startButton.element.classList.remove(ACTIVE);\n this.endButton.element.classList.add(ACTIVE);\n var calendar = this.popupObj.element.querySelector('.' + CALENDAR);\n this.updateDeviceCalendar(calendar);\n if (isNullOrUndefined(this.calendarElement.querySelector('.' + ENDDATE + ':not(.e-other-month)'))) {\n this.currentDate = new Date(+this.endValue);\n remove(this.tableBodyElement);\n this.renderMonths();\n this.deviceNavigation();\n }\n this.updateMinMaxDays(this.popupObj.element.querySelector('.' + CALENDAR));\n this.selectableDates();\n }\n };\n DateRangePicker.prototype.inputFocusHandler = function () {\n this.preventBlur = false;\n var focusArguments = {\n model: this\n };\n if (!this.preventFocus) {\n this.preventFocus = true;\n this.trigger('focus', focusArguments);\n }\n };\n DateRangePicker.prototype.inputBlurHandler = function (e) {\n if (!this.preventBlur) {\n var value = this.inputElement.value;\n if (!isNullOrUndefined(this.presetsItem)) {\n if (this.presetsItem.length > 0 && this.previousEleValue !== this.inputElement.value) {\n this.activeIndex = this.presetsItem.length - 1;\n this.isCustomRange = true;\n }\n }\n if (!isNullOrUndefined(value) && value.trim() !== '') {\n var range = value.split(' ' + this.separator + ' ');\n if (range.length > 1) {\n var dateOptions = { format: this.format, type: 'date', skeleton: 'yMd' };\n var startDate = this.globalize.parseDate(range[0].trim(), dateOptions);\n var endDate = this.globalize.parseDate(range[1].trim(), dateOptions);\n if (!isNullOrUndefined(startDate) && !isNaN(+startDate) && !isNullOrUndefined(endDate) && !isNaN(+endDate)) {\n this.startValue = startDate;\n this.endValue = endDate;\n this.setValue();\n this.refreshControl();\n this.changeTrigger(e);\n if (!this.preventBlur && document.activeElement !== this.inputElement) {\n this.preventFocus = false;\n var blurArguments = {\n model: this\n };\n this.trigger('blur', blurArguments);\n }\n return;\n }\n else {\n if (!this.strictMode) {\n this.startValue = null;\n this.endValue = null;\n this.setValue();\n }\n }\n }\n else {\n if (!this.strictMode) {\n this.startValue = null;\n this.endValue = null;\n this.setValue();\n }\n }\n }\n if (!this.strictMode) {\n this.clearRange();\n this.startValue = null;\n this.endValue = null;\n this.setValue();\n }\n else {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n this.updateInput();\n }\n this.errorClass();\n this.changeTrigger(e);\n if (!this.preventBlur && document.activeElement !== this.inputElement) {\n this.preventFocus = false;\n var blurArguments = {\n model: this\n };\n this.trigger('blur', blurArguments);\n }\n }\n };\n DateRangePicker.prototype.clearRange = function () {\n this.previousStartValue = this.previousEndValue = null;\n this.currentDate = null;\n };\n DateRangePicker.prototype.errorClass = function () {\n var inputStr = this.inputElement.value.trim();\n if (((isNullOrUndefined(this.endValue) && isNullOrUndefined(this.startValue) && inputStr !== '') ||\n ((!isNullOrUndefined(this.startValue) && +this.startValue < +this.min)\n || ((!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) && +this.startValue > +this.endValue)\n || (!isNullOrUndefined(this.endValue) && +this.endValue > +this.max))\n || ((this.startValue && this.isDateDisabled(this.startValue))\n || (this.endValue && this.isDateDisabled(this.endValue)))) && inputStr !== '') {\n addClass([this.inputWrapper.container], ERROR);\n attributes(this.inputElement, { 'aria-invalid': 'true' });\n }\n else {\n if (this.inputWrapper) {\n removeClass([this.inputWrapper.container], ERROR);\n attributes(this.inputElement, { 'aria-invalid': 'false' });\n }\n }\n };\n DateRangePicker.prototype.keyCalendarUpdate = function (isLeftCalendar, ele) {\n this.removeFocusedDate();\n if (isLeftCalendar) {\n this.leftCalCurrentDate = new Date(+this.currentDate);\n ele = this.leftCalendar;\n }\n else {\n this.rightCalCurrentDate = new Date(+this.currentDate);\n ele = this.rightCalendar;\n }\n this.updateCalendarElement(ele);\n this.table.focus();\n return ele;\n };\n DateRangePicker.prototype.navInCalendar = function (e, isLeftCalendar, leftLimit, rightLimit, ele) {\n var date;\n var min = this.min;\n var max;\n if (!isNullOrUndefined(this.maxDays) && this.isMaxDaysClicked && !isNullOrUndefined(this.startValue)) {\n max = new Date(new Date(+this.startValue).setDate(this.startValue.getDate() + (this.maxDays - 1)));\n }\n else {\n max = this.max;\n }\n switch (e.action) {\n case 'moveRight':\n date = new Date(+this.currentDate);\n this.addDay(date, 1, e, max, min);\n if (isLeftCalendar && +date === +rightLimit) {\n ele = this.keyCalendarUpdate(false, ele);\n }\n this.KeyboardNavigate(1, 0, e, max, min);\n this.keyNavigation(ele, e);\n break;\n case 'moveLeft':\n date = new Date(+this.currentDate);\n this.addDay(date, -1, e, max, min);\n if (!isLeftCalendar && +date === +leftLimit) {\n ele = this.keyCalendarUpdate(true, ele);\n }\n this.KeyboardNavigate(-1, 0, e, max, min);\n this.keyNavigation(ele, e);\n break;\n case 'moveUp':\n date = new Date(+this.currentDate);\n this.addDay(date, -7, e, max, min);\n if (!isLeftCalendar && +date <= +leftLimit) {\n ele = this.keyCalendarUpdate(true, ele);\n }\n this.KeyboardNavigate(-7, 0, e, max, min);\n this.keyNavigation(ele, e);\n break;\n case 'moveDown':\n date = new Date(+this.currentDate);\n this.addDay(date, 7, e, max, min);\n if (isLeftCalendar && +date >= +rightLimit) {\n ele = this.keyCalendarUpdate(false, ele);\n }\n this.KeyboardNavigate(7, 0, e, max, min);\n this.keyNavigation(ele, e);\n break;\n case 'home':\n this.currentDate = this.firstDay(this.currentDate);\n remove(this.tableBodyElement);\n this.renderMonths();\n this.keyNavigation(ele, e);\n break;\n case 'end':\n this.currentDate = this.lastDay(this.currentDate);\n remove(this.tableBodyElement);\n this.renderMonths();\n this.keyNavigation(ele, e);\n break;\n }\n };\n // tslint:disable-next-line:max-func-body-length\n DateRangePicker.prototype.keyInputHandler = function (e) {\n var date;\n var rightDateLimit = new Date(this.rightCalCurrentDate.getFullYear(), this.rightCalCurrentDate.getMonth(), 1);\n var leftDateLimit = new Date(this.leftCalCurrentDate.getFullYear(), this.leftCalCurrentDate.getMonth() + 1, 0);\n var ele = closest(e.target, '.' + RIGHTCALENDER);\n ele = isNullOrUndefined(ele) ? this.leftCalendar : ele;\n var isLeftCalendar = ele.classList.contains(LEFTCALENDER);\n this.updateCalendarElement(ele);\n var focusedDate = ele.querySelector('tr td.' + FOCUSDATE);\n var startDate = ele.querySelector('tr td.' + STARTDATE);\n var endDate = ele.querySelector('tr td.' + ENDDATE);\n if (!isNullOrUndefined(focusedDate)) {\n this.currentDate = this.currentDate;\n }\n else if (!isNullOrUndefined(endDate) && !this.dateDisabled) {\n this.currentDate = new Date(+this.endValue);\n }\n else if (!isNullOrUndefined(startDate) && !this.dateDisabled) {\n this.currentDate = new Date(+this.startValue);\n }\n else if (!this.dateDisabled) {\n this.currentDate.setDate(1);\n }\n this.effect = '';\n switch (e.action) {\n case 'altUpArrow':\n if (this.isPopupOpen()) {\n this.hide(e);\n this.preventFocus = true;\n if (!this.isMobile) {\n this.inputElement.focus();\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n }\n }\n break;\n case 'select':\n var element = !isNullOrUndefined(focusedDate) ? focusedDate : startDate;\n if (!isNullOrUndefined(element) && !element.classList.contains(DISABLED)) {\n this.selectRange(e, (element));\n }\n e.preventDefault();\n break;\n case 'controlHome':\n var yearDate = new Date(this.currentDate.getFullYear(), 0, 1);\n if (!isLeftCalendar && +yearDate < +leftDateLimit) {\n ele = this.keyCalendarUpdate(true, ele);\n }\n this.navigateTo('Month', new Date(this.currentDate.getFullYear(), 0, 1));\n this.keyNavigation(ele, e);\n break;\n case 'controlEnd':\n yearDate = new Date(this.currentDate.getFullYear(), 11, 31);\n if (isLeftCalendar && +yearDate > +rightDateLimit) {\n ele = this.keyCalendarUpdate(false, ele);\n }\n this.navigateTo('Month', new Date(this.currentDate.getFullYear(), 11, 31));\n this.keyNavigation(ele, e);\n break;\n case 'pageUp':\n date = new Date(+this.currentDate);\n this.addMonths(date, -1);\n if (!isLeftCalendar && +date <= +leftDateLimit) {\n ele = this.keyCalendarUpdate(true, ele);\n }\n this.addMonths(this.currentDate, -1);\n this.navigateTo('Month', this.currentDate);\n this.keyNavigation(ele, e);\n break;\n case 'pageDown':\n date = new Date(+this.currentDate);\n this.addMonths(date, 1);\n if (isLeftCalendar && +date >= +rightDateLimit) {\n ele = this.keyCalendarUpdate(false, ele);\n }\n this.addMonths(this.currentDate, 1);\n this.navigateTo('Month', this.currentDate);\n this.keyNavigation(ele, e);\n break;\n case 'shiftPageUp':\n date = new Date(+this.currentDate);\n this.addYears(date, -1);\n if (!isLeftCalendar && +date <= +leftDateLimit) {\n ele = this.keyCalendarUpdate(true, ele);\n }\n this.addYears(this.currentDate, -1);\n this.navigateTo('Month', this.currentDate);\n this.keyNavigation(ele, e);\n break;\n case 'shiftPageDown':\n date = new Date(+this.currentDate);\n this.addYears(date, 1);\n if (isLeftCalendar && +date >= +rightDateLimit) {\n ele = this.keyCalendarUpdate(false, ele);\n }\n this.addYears(this.currentDate, 1);\n this.navigateTo('Month', this.currentDate);\n this.keyNavigation(ele, e);\n break;\n case 'shiftTab':\n if (!isNullOrUndefined(this.presetElement)) {\n this.presetElement.setAttribute('tabindex', '0');\n this.presetElement.focus();\n this.removeFocusedDate();\n }\n e.preventDefault();\n break;\n case 'spacebar':\n if (this.applyButton && !this.applyButton.disabled) {\n this.applyFunction(e);\n }\n break;\n default:\n this.navInCalendar(e, isLeftCalendar, leftDateLimit, rightDateLimit, ele);\n this.checkMinMaxDays();\n }\n this.presetHeight();\n };\n DateRangePicker.prototype.keyNavigation = function (calendar, e) {\n this.bindCalendarCellEvents(calendar);\n if (calendar.classList.contains(LEFTCALENDER)) {\n this.leftCalCurrentDate = new Date(+this.currentDate);\n }\n else {\n this.rightCalCurrentDate = new Date(+this.currentDate);\n }\n this.updateNavIcons();\n this.calendarIconEvent();\n this.updateRange([calendar]);\n this.dateDisabled = this.isDateDisabled(this.currentDate);\n e.preventDefault();\n };\n DateRangePicker.prototype.inputHandler = function (e) {\n switch (e.action) {\n case 'altDownArrow':\n if (!this.isPopupOpen()) {\n this.show(null, e);\n this.isRangeIconClicked = false;\n if (!this.isMobile) {\n if (!isNullOrUndefined(this.leftCalendar)) {\n this.calendarFocus();\n }\n }\n this.isKeyPopup = true;\n }\n break;\n case 'escape':\n if (this.isPopupOpen()) {\n this.hide(e);\n }\n break;\n case 'enter':\n if (document.activeElement === this.inputElement) {\n this.inputBlurHandler(e);\n this.hide(e);\n }\n break;\n case 'tab':\n if (document.activeElement === this.inputElement && this.isPopupOpen()) {\n this.hide(e);\n e.preventDefault();\n }\n break;\n }\n };\n DateRangePicker.prototype.bindCalendarCellEvents = function (calendar) {\n var tdCells;\n if (calendar) {\n tdCells = calendar.querySelectorAll('.' + CALENDAR + ' td');\n }\n else {\n tdCells = this.popupObj.element.querySelectorAll('.' + CALENDAR + ' td');\n }\n for (var _i = 0, tdCells_1 = tdCells; _i < tdCells_1.length; _i++) {\n var cell = tdCells_1[_i];\n EventHandler.clearEvents(cell);\n var disabledCell = void 0;\n disabledCell = cell.classList.contains(DISABLED) || cell.classList.contains(DATEDISABLED);\n if (!disabledCell && !cell.classList.contains(WEEKNUMBER)) {\n if (!this.isMobile) {\n EventHandler.add(cell, 'mouseover touchstart', this.hoverSelection, this);\n }\n EventHandler.add(cell, 'mousedown touchstart', this.selectRange, this);\n }\n }\n };\n DateRangePicker.prototype.removeFocusedDate = function () {\n var isDate = !isNullOrUndefined(this.startValue) || !isNullOrUndefined(this.endValue);\n var focusedDate;\n focusedDate = this.popupObj.element.querySelectorAll('.' + CALENDAR + ' .' + FOCUSDATE);\n if ((this.leftCalendar && this.leftCalendar.querySelector('.e-content').classList.contains('e-month')\n && this.rightCalendar && this.rightCalendar.querySelector('.e-content').classList.contains('e-month')) ||\n this.calendarElement && this.calendarElement.querySelector('.e-content').classList.contains('e-month')) {\n for (var _i = 0, focusedDate_1 = focusedDate; _i < focusedDate_1.length; _i++) {\n var ele = focusedDate_1[_i];\n if (!ele.classList.contains(TODAY) || (ele.classList.contains(TODAY) && (isDate))) {\n ele.classList.remove(FOCUSDATE);\n if (!ele.classList.contains(STARTDATE) && !ele.classList.contains(ENDDATE)) {\n ele.removeAttribute('aria-label');\n }\n }\n }\n }\n };\n DateRangePicker.prototype.hoverSelection = function (event, element) {\n var currentElement = element || event.currentTarget;\n var currentDate = this.getIdValue(null, currentElement);\n if (!isNullOrUndefined(this.startValue) && +this.startValue >= +this.min && +this.startValue <= +this.max) {\n if ((!this.isDateDisabled(this.endValue) && !this.isDateDisabled(this.startValue)\n && isNullOrUndefined(this.endValue) && isNullOrUndefined(this.startValue))\n || (!isNullOrUndefined(this.startValue) && isNullOrUndefined(this.endValue))) {\n var tdCells = void 0;\n tdCells = this.popupObj.element.querySelectorAll('.' + CALENDAR + ' td');\n for (var _i = 0, tdCells_2 = tdCells; _i < tdCells_2.length; _i++) {\n var ele = tdCells_2[_i];\n var isDisabledCell = (!ele.classList.contains(DISABLED) || ele.classList.contains(DATEDISABLED));\n if (!ele.classList.contains(WEEKNUMBER) && isDisabledCell) {\n var eleDate = this.getIdValue(null, ele);\n var startDateValue = new Date(+this.startValue);\n var eleDateValue = new Date(+eleDate);\n if (eleDateValue.setHours(0, 0, 0, 0) >= startDateValue.setHours(0, 0, 0, 0) && +eleDate <= +currentDate) {\n addClass([ele], RANGEHOVER);\n }\n else {\n removeClass([ele], [RANGEHOVER]);\n }\n }\n }\n }\n }\n };\n DateRangePicker.prototype.updateRange = function (elementCollection) {\n if (!isNullOrUndefined(this.startValue)) {\n for (var _i = 0, elementCollection_1 = elementCollection; _i < elementCollection_1.length; _i++) {\n var calendar = elementCollection_1[_i];\n var tdCells = calendar.querySelectorAll('.' + CALENDAR + ' td');\n for (var _a = 0, tdCells_3 = tdCells; _a < tdCells_3.length; _a++) {\n var ele = tdCells_3[_a];\n if (!ele.classList.contains(WEEKNUMBER) && !ele.classList.contains(DISABLED)) {\n var eleDate = this.getIdValue(null, ele);\n var eleDateValue = this.getIdValue(null, ele);\n if (!isNullOrUndefined(this.endValue)) {\n if (this.currentView() === 'Month' &&\n +eleDateValue.setHours(0, 0, 0, 0) >= +new Date(+this.startValue).setHours(0, 0, 0, 0)\n && +eleDateValue.setHours(0, 0, 0, 0) <= +new Date(+this.endValue).setHours(0, 0, 0, 0) &&\n +new Date(+this.startValue).setHours(0, 0, 0, 0) !== +new Date(+this.endValue).setHours(0, 0, 0, 0) &&\n +new Date(+this.startValue).setHours(0, 0, 0, 0) >= +this.min\n && +new Date(+this.endValue).setHours(0, 0, 0, 0) <= +this.max\n && !(this.isDateDisabled(this.startValue) || this.isDateDisabled(this.endValue))) {\n addClass([ele], RANGEHOVER);\n }\n }\n else {\n removeClass([ele], [RANGEHOVER]);\n }\n if (!ele.classList.contains(OTHERMONTH)) {\n var startDateValue = new Date(+this.startValue);\n var eleDateValue_1 = new Date(+eleDate);\n if (this.currentView() === 'Month' &&\n +eleDateValue_1.setHours(0, 0, 0, 0) === +startDateValue.setHours(0, 0, 0, 0)\n && +eleDateValue_1.setHours(0, 0, 0, 0) >= +startDateValue.setHours(0, 0, 0, 0) &&\n +this.startValue >= +this.min\n && !this.inputWrapper.container.classList.contains('e-error')\n && !(this.isDateDisabled(this.startValue) || this.isDateDisabled(this.endValue))) {\n addClass([ele], [STARTDATE, SELECTED]);\n this.addSelectedAttributes(ele, this.startValue, true);\n }\n var endDateValue = new Date(+this.endValue);\n if (this.currentView() === 'Month' &&\n !isNullOrUndefined(this.endValue) &&\n +eleDateValue_1.setHours(0, 0, 0, 0) === +endDateValue.setHours(0, 0, 0, 0)\n && +eleDateValue_1.setHours(0, 0, 0, 0) <= +endDateValue.setHours(0, 0, 0, 0) &&\n +this.startValue >= +this.min\n && !this.inputWrapper.container.classList.contains('e-error')\n && !(this.isDateDisabled(this.startValue) || this.isDateDisabled(this.endValue))) {\n addClass([ele], [ENDDATE, SELECTED]);\n this.addSelectedAttributes(ele, this.startValue, false);\n }\n if (+eleDate === +this.startValue && !isNullOrUndefined(this.endValue) && +eleDate === +this.endValue) {\n this.addSelectedAttributes(ele, this.endValue, false, true);\n }\n }\n }\n }\n }\n }\n };\n DateRangePicker.prototype.checkMinMaxDays = function () {\n if ((!isNullOrUndefined(this.minDays) && this.minDays > 0) || (!isNullOrUndefined(this.maxDays) && this.maxDays > 0)) {\n if (!this.isMobile) {\n this.updateMinMaxDays(this.popupObj.element.querySelector('.' + LEFTCALENDER));\n this.updateMinMaxDays(this.popupObj.element.querySelector('.' + RIGHTCALENDER));\n }\n else {\n this.updateMinMaxDays(this.popupObj.element.querySelector('.' + CALENDAR));\n }\n }\n };\n DateRangePicker.prototype.rangeArgs = function (e) {\n var inputValue;\n var range;\n var startDate = !isNullOrUndefined(this.startValue) ?\n this.globalize.formatDate(this.startValue, { format: this.format, type: 'date', skeleton: 'yMd' }) : null;\n var endDate = !isNullOrUndefined(this.endValue) ?\n this.globalize.formatDate(this.endValue, { format: this.format, type: 'date', skeleton: 'yMd' }) : null;\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n inputValue = startDate + ' ' + this.separator + ' ' + endDate;\n range = (Math.round(Math.abs((this.startValue.getTime() - this.endValue.getTime()) / (1000 * 60 * 60 * 24))) + 1);\n }\n else {\n inputValue = '';\n range = 0;\n }\n var args = {\n value: this.value,\n startDate: this.startValue,\n endDate: this.endValue,\n daySpan: range,\n event: e || null,\n element: this.element,\n isInteracted: !isNullOrUndefined(e),\n text: inputValue\n };\n return args;\n };\n DateRangePicker.prototype.otherMonthSelect = function (ele, isStartDate, sameDate) {\n var value = +this.getIdValue(null, ele);\n var dateIdString = '*[id^=\"/id\"]:not(.e-other-month)'.replace('/id', '' + value);\n var tdCell = this.popupObj && this.popupObj.element.querySelector(dateIdString);\n if (!isNullOrUndefined(tdCell)) {\n if (isStartDate) {\n addClass([tdCell], [STARTDATE, SELECTED]);\n this.addSelectedAttributes(tdCell, this.startValue, true);\n }\n else {\n addClass([tdCell], [ENDDATE, SELECTED]);\n this.addSelectedAttributes(tdCell, this.endValue, true);\n }\n if (sameDate) {\n this.addSelectedAttributes(ele, this.endValue, false, true);\n }\n }\n };\n // tslint:disable-next-line:max-func-body-length\n DateRangePicker.prototype.selectRange = function (event, element) {\n event.preventDefault();\n var date;\n date = (event instanceof MouseEvent || event instanceof TouchEvent) ? this.getIdValue(event, null) : this.getIdValue(null, element);\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n if (!this.isMobile || this.isMobile && !this.endButton.element.classList.contains(ACTIVE)) {\n this.removeSelection();\n }\n }\n else if (this.isMobile && this.startButton.element.classList.contains(ACTIVE)) {\n this.removeSelection();\n }\n var ele = element || event.currentTarget;\n if (isNullOrUndefined(this.startValue)) {\n if (!isNullOrUndefined(this.previousStartValue)) {\n date.setHours(this.previousStartValue.getHours());\n date.setMinutes(this.previousStartValue.getMinutes());\n date.setSeconds(this.previousStartValue.getSeconds());\n }\n this.startValue = new Date('' + date);\n this.endValue = null;\n this.setValue();\n addClass([ele], STARTDATE);\n this.addSelectedAttributes(ele, this.startValue, true);\n if (ele.classList.contains(OTHERMONTH)) {\n this.otherMonthSelect(ele, true);\n }\n this.checkMinMaxDays();\n this.applyButton.disabled = true;\n this.applyButton.element.disabled = true;\n if (this.isMobile) {\n this.endButton.element.classList.add(ACTIVE);\n this.startButton.element.classList.remove(ACTIVE);\n this.endButton.element.removeAttribute('disabled');\n this.selectableDates();\n }\n this.trigger('select', this.rangeArgs(event));\n }\n else {\n if (+date === +this.startValue || +date > +this.startValue) {\n if (+date === +this.startValue && !isNullOrUndefined(this.minDays) && this.minDays > 1) {\n return;\n }\n this.endValue = null;\n this.setValue();\n if (this.isMobile || element) {\n this.hoverSelection(event, element);\n }\n if (!isNullOrUndefined(this.previousEndValue)) {\n date.setHours(this.previousEndValue.getHours());\n date.setMinutes(this.previousEndValue.getMinutes());\n date.setSeconds(this.previousEndValue.getSeconds());\n }\n this.endValue = new Date('' + date);\n this.setValue();\n var endEle = this.popupObj.element.querySelectorAll('.' + ENDDATE);\n if (this.isMobile) {\n this.startButton.element.classList.remove(ACTIVE);\n this.endButton.element.classList.add(ACTIVE);\n for (var _i = 0, endEle_1 = endEle; _i < endEle_1.length; _i++) {\n var ele_1 = endEle_1[_i];\n ele_1.removeAttribute('aria-label');\n if (!ele_1.classList.contains(STARTDATE)) {\n ele_1.setAttribute('aria-selected', 'false');\n removeClass([ele_1], [ENDDATE, SELECTED]);\n }\n else {\n this.addSelectedAttributes(ele_1, this.startValue, true);\n removeClass([ele_1], [ENDDATE]);\n }\n }\n }\n addClass([ele], ENDDATE);\n if (+this.endValue === +this.startValue) {\n this.addSelectedAttributes(ele, this.endValue, false, true);\n }\n else {\n this.addSelectedAttributes(ele, this.endValue, false);\n }\n if (ele.classList.contains(OTHERMONTH)) {\n if (+this.endValue === +this.startValue) {\n this.otherMonthSelect(ele, false, true);\n }\n else {\n this.otherMonthSelect(ele, false);\n }\n }\n endEle = this.popupObj.element.querySelectorAll('.' + ENDDATE);\n for (var _a = 0, endEle_2 = endEle; _a < endEle_2.length; _a++) {\n var ele_2 = endEle_2[_a];\n if (ele_2.classList.contains(STARTDATE)) {\n removeClass([ele_2], [RANGEHOVER]);\n }\n }\n this.applyButton.disabled = false;\n this.applyButton.element.disabled = false;\n if (!this.isMobile) {\n this.removeClassDisabled();\n }\n this.disabledDateRender();\n this.trigger('select', this.rangeArgs(event));\n }\n else if (+date < +this.startValue) {\n this.removeClassDisabled();\n this.startValue = new Date('' + date);\n this.setValue();\n this.removeSelectedAttributes();\n removeClass(this.popupObj.element.querySelectorAll('.' + STARTDATE), [STARTDATE, SELECTED]);\n addClass([ele], STARTDATE);\n this.addSelectedAttributes(ele, this.startValue, true);\n if (ele.classList.contains(OTHERMONTH)) {\n this.otherMonthSelect(ele, true);\n }\n this.checkMinMaxDays();\n }\n }\n addClass([ele], SELECTED);\n this.updateHeader();\n this.removeFocusedDate();\n };\n DateRangePicker.prototype.selectableDates = function () {\n if (!isNullOrUndefined(this.startValue)) {\n var tdCells = this.calendarElement.querySelectorAll('.' + CALENDAR + ' td');\n var isStartDate = false;\n if (this.currentView() === 'Month') {\n for (var _i = 0, tdCells_4 = tdCells; _i < tdCells_4.length; _i++) {\n var ele = tdCells_4[_i];\n if (!ele.classList.contains(STARTDATE) && !ele.classList.contains(WEEKNUMBER)) {\n if (!ele.classList.contains(DISABLED)) {\n var eleDate = this.getIdValue(null, ele);\n if (+eleDate < +this.startValue) {\n addClass([ele], [DATEDISABLED, DISABLED, OVERLAY]);\n EventHandler.clearEvents(ele);\n continue;\n }\n else {\n break;\n }\n }\n }\n if (ele.classList.contains(STARTDATE) && !ele.classList.contains(OTHERMONTH)) {\n isStartDate = true;\n break;\n }\n }\n if (isStartDate) {\n if (!this.previousIcon.classList.contains(DISABLED)) {\n addClass([this.previousIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n }\n }\n else {\n for (var _a = 0, tdCells_5 = tdCells; _a < tdCells_5.length; _a++) {\n var ele = tdCells_5[_a];\n var startMonth = this.startValue.getMonth();\n var startYear = this.startValue.getFullYear();\n var element = this.getIdValue(null, ele);\n if (!this.startButton.element.classList.contains(ACTIVE) && ((this.currentView() === 'Year' &&\n (element.getMonth() < startMonth) && (element.getFullYear() <= startYear))\n || (this.currentView() === 'Decade' && (element.getMonth() <= startMonth) &&\n (element.getFullYear() < startYear)))) {\n addClass([ele], [DISABLED]);\n }\n else {\n break;\n }\n }\n if (tdCells[0].classList.contains(DISABLED)) {\n this.previousIconHandler(true);\n }\n else if (tdCells[tdCells.length - 1].classList.contains(DISABLED)) {\n this.nextIconHandler(true);\n }\n }\n }\n };\n DateRangePicker.prototype.updateMinMaxDays = function (calendar) {\n if (!isNullOrUndefined(this.startValue) && (isNullOrUndefined(this.endValue) || this.isMobile)) {\n if ((!isNullOrUndefined(this.minDays) && this.minDays > 0) || (!isNullOrUndefined(this.maxDays) && this.maxDays > 0)) {\n var minDate = new Date(new Date(+this.startValue).setDate(this.startValue.getDate() + (this.minDays - 1)));\n var maxDate = new Date(new Date(+this.startValue).setDate(this.startValue.getDate() + (this.maxDays - 1)));\n minDate = (!isNullOrUndefined(this.minDays) && this.minDays > 0) ? minDate : null;\n maxDate = (!isNullOrUndefined(this.maxDays) && this.maxDays > 0) ? maxDate : null;\n var tdCells = calendar.querySelectorAll('.' + CALENDAR + ' td');\n var maxEle = void 0;\n for (var _i = 0, tdCells_6 = tdCells; _i < tdCells_6.length; _i++) {\n var ele = tdCells_6[_i];\n if (!ele.classList.contains(STARTDATE) && !ele.classList.contains(WEEKNUMBER)) {\n var eleDate = this.getIdValue(null, ele);\n if (!isNullOrUndefined(minDate) && +eleDate === +minDate && ele.classList.contains(DISABLED)) {\n minDate.setDate(minDate.getDate() + 1);\n }\n if (!ele.classList.contains(DISABLED)) {\n if (+eleDate <= +this.startValue) {\n continue;\n }\n if (!isNullOrUndefined(minDate) && +eleDate < +minDate) {\n addClass([ele], [DATEDISABLED, DISABLED, OVERLAY]);\n EventHandler.clearEvents(ele);\n }\n if (!isNullOrUndefined(maxDate) && +eleDate > +maxDate) {\n addClass([ele], [DATEDISABLED, DISABLED, OVERLAY]);\n this.isMaxDaysClicked = true;\n EventHandler.clearEvents(ele);\n if (isNullOrUndefined(maxEle) && !ele.classList.contains(OTHERMONTH)) {\n maxEle = ele;\n }\n }\n }\n }\n }\n if (!isNullOrUndefined(maxEle)) {\n if (this.isMobile) {\n if (!this.nextIcon.classList.contains(DISABLED)) {\n addClass([this.nextIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n }\n else {\n var calendar_1 = closest(maxEle, '.' + RIGHTCALENDER);\n calendar_1 = isNullOrUndefined(calendar_1) ? this.leftCalendar : calendar_1;\n var isLeftCalendar = calendar_1.classList.contains(LEFTCALENDER);\n if (!isLeftCalendar) {\n if (!this.rightCalNextIcon.classList.contains(DISABLED)) {\n addClass([this.rightCalNextIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n }\n else {\n if (!this.rightCalNextIcon.classList.contains(DISABLED)) {\n addClass([this.rightCalNextIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n if (!this.leftCalNextIcon.classList.contains(DISABLED)) {\n addClass([this.leftCalNextIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n if (!this.rightCalPrevIcon.classList.contains(DISABLED)) {\n addClass([this.rightCalPrevIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n }\n }\n }\n }\n }\n else {\n this.isMaxDaysClicked = false;\n }\n };\n DateRangePicker.prototype.removeClassDisabled = function () {\n var tdCells;\n tdCells = this.popupObj.element.querySelectorAll('.' + CALENDAR + ' td' + '.' + DATEDISABLED);\n for (var _i = 0, tdCells_7 = tdCells; _i < tdCells_7.length; _i++) {\n var ele = tdCells_7[_i];\n if (ele.classList.contains(DATEDISABLED)) {\n removeClass([ele], [DATEDISABLED, DISABLED, OVERLAY]);\n EventHandler.add(ele, 'click', this.selectRange, this);\n if (!this.isMobile) {\n EventHandler.add(ele, 'mouseover touchstart', this.hoverSelection, this);\n }\n }\n }\n if (this.isMobile) {\n if (this.nextIcon.classList.contains(ICONDISABLED)) {\n removeClass([this.nextIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n if (this.previousIcon.classList.contains(ICONDISABLED)) {\n removeClass([this.previousIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n }\n else {\n if (this.rightCalNextIcon.classList.contains(ICONDISABLED)) {\n removeClass([this.rightCalNextIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n if (this.rightCalPrevIcon.classList.contains(ICONDISABLED)) {\n removeClass([this.rightCalPrevIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n if (this.leftCalNextIcon.classList.contains(ICONDISABLED)) {\n removeClass([this.leftCalNextIcon], [ICONDISABLED, DISABLED, OVERLAY]);\n }\n }\n };\n DateRangePicker.prototype.updateHeader = function () {\n var format = { type: 'date', skeleton: 'yMMMd' };\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n var range = (Math.round(Math.abs((this.startValue.getTime() - this.endValue.getTime()) / (1000 * 60 * 60 * 24))) + 1);\n if (!isNullOrUndefined(this.disabledDayCnt)) {\n range = range - this.disabledDayCnt;\n this.disabledDayCnt = null;\n }\n this.popupObj.element.querySelector('.' + DAYSPAN).textContent = range.toString() + ' ' + this.l10n.getConstant('days');\n }\n else {\n this.popupObj.element.querySelector('.' + DAYSPAN).textContent = this.l10n.getConstant('selectedDays');\n }\n if (!this.isMobile) {\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n this.popupObj.element.querySelector('.' + ENDLABEL).textContent = this.globalize.formatDate(this.endValue, format);\n }\n else {\n this.popupObj.element.querySelector('.' + ENDLABEL).textContent = this.l10n.getConstant('endLabel');\n }\n if (!isNullOrUndefined(this.startValue)) {\n this.popupObj.element.querySelector('.' + STARTLABEL).textContent = this.globalize.formatDate(this.startValue, format);\n }\n else {\n this.popupObj.element.querySelector('.' + STARTLABEL).textContent = this.l10n.getConstant('startLabel');\n }\n }\n else {\n if (!isNullOrUndefined(this.startValue)) {\n this.startButton.element.textContent = this.globalize.formatDate(this.startValue, format);\n }\n else {\n this.startButton.element.textContent = this.l10n.getConstant('startLabel');\n }\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n this.endButton.element.textContent = this.globalize.formatDate(this.endValue, format);\n }\n else {\n this.endButton.element.textContent = this.l10n.getConstant('endLabel');\n }\n }\n if ((this.isDateDisabled(this.startValue) || this.isDateDisabled(this.endValue)) ||\n ((!isNullOrUndefined(this.startValue) && +this.startValue < +this.min)\n || (!isNullOrUndefined(this.endValue) && +this.endValue > +this.max)\n || ((!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue))\n && +this.startValue > +this.endValue))) {\n if (!this.isMobile) {\n this.popupObj.element.querySelector('.' + DAYSPAN).textContent = this.l10n.getConstant('selectedDays');\n this.popupObj.element.querySelector('.' + STARTLABEL).textContent = this.l10n.getConstant('startLabel');\n this.popupObj.element.querySelector('.' + ENDLABEL).textContent = this.l10n.getConstant('endLabel');\n }\n else {\n this.startButton.element.textContent = this.l10n.getConstant('startLabel');\n this.endButton.element.textContent = this.l10n.getConstant('endLabel');\n this.popupObj.element.querySelector('.' + DAYSPAN).textContent = this.l10n.getConstant('selectedDays');\n }\n }\n };\n DateRangePicker.prototype.removeSelection = function () {\n this.startValue = null;\n this.endValue = null;\n this.setValue();\n this.removeSelectedAttributes();\n if (this.popupObj) {\n if (this.popupObj.element.querySelectorAll('.' + SELECTED).length > 0) {\n removeClass(this.popupObj.element.querySelectorAll('.' + SELECTED), [STARTDATE, ENDDATE, SELECTED]);\n }\n if (this.popupObj.element.querySelectorAll('.' + FOCUSDATE).length > 0) {\n removeClass(this.popupObj.element.querySelectorAll('.' + FOCUSDATE), FOCUSDATE);\n }\n if (this.popupObj.element.querySelectorAll('.' + RANGEHOVER).length > 0) {\n removeClass(this.popupObj.element.querySelectorAll('.' + RANGEHOVER), [RANGEHOVER]);\n }\n }\n };\n DateRangePicker.prototype.addSelectedAttributes = function (ele, date, isStartDate, sameDate) {\n if (ele) {\n var title = this.globalize.formatDate(date, { type: 'date', skeleton: 'full' });\n if (!isNullOrUndefined(sameDate) && sameDate) {\n ele.setAttribute('aria-label', 'The current start and end date is ' + '' + title);\n }\n else {\n ele.setAttribute('aria-label', 'The current ' + (isStartDate ? 'start' : 'end') + ' date is ' + '' + title);\n }\n ele.setAttribute('aria-selected', 'true');\n }\n };\n DateRangePicker.prototype.removeSelectedAttributes = function () {\n if (this.popupObj) {\n var start = this.popupObj.element.querySelectorAll('.' + STARTDATE);\n for (var _i = 0, start_1 = start; _i < start_1.length; _i++) {\n var ele = start_1[_i];\n ele.setAttribute('aria-selected', 'false');\n ele.removeAttribute('aria-label');\n }\n var end = this.popupObj.element.querySelectorAll('.' + ENDDATE);\n for (var _a = 0, end_1 = end; _a < end_1.length; _a++) {\n var ele = end_1[_a];\n ele.setAttribute('aria-selected', 'false');\n ele.removeAttribute('aria-label');\n }\n }\n };\n DateRangePicker.prototype.updateCalendarElement = function (calendar) {\n if (calendar.classList.contains(LEFTCALENDER)) {\n this.calendarElement = this.leftCalendar;\n this.currentDate = this.leftCalCurrentDate;\n this.previousIcon = this.leftCalPrevIcon;\n this.nextIcon = this.leftCalNextIcon;\n }\n else {\n this.calendarElement = this.rightCalendar;\n this.currentDate = this.rightCalCurrentDate;\n this.previousIcon = this.rightCalPrevIcon;\n this.nextIcon = this.rightCalNextIcon;\n }\n this.contentElement = calendar.querySelector('.' + CONTENT);\n this.tableBodyElement = select('.' + CONTENT + ' tbody', calendar);\n this.table = calendar.querySelector('.' + CONTENT).getElementsByTagName('table')[0];\n this.headerTitleElement = calendar.querySelector('.' + HEADER + ' .' + TITLE);\n this.headerElement = calendar.querySelector('.' + HEADER);\n };\n DateRangePicker.prototype.navPrevMonth = function (e) {\n e.preventDefault();\n var ele = closest(e.target, '.' + LEFTCALENDER);\n ele = isNullOrUndefined(ele) ? closest(e.target, '.' + RIGHTCALENDER) : ele;\n this.updateCalendarElement(ele);\n this.navigatePrevious(e);\n if (!isNullOrUndefined(this.startValue) && isNullOrUndefined(this.endValue)) {\n this.updateMinMaxDays(ele);\n }\n this.updateControl(ele);\n };\n DateRangePicker.prototype.deviceNavigation = function (ele) {\n this.deviceCalendarEvent();\n this.updateRange([this.popupObj.element.querySelector('.' + CALENDAR)]);\n if ((!isNullOrUndefined(this.endValue) && this.endButton.element.classList.contains(ACTIVE))) {\n this.updateMinMaxDays(this.popupObj.element.querySelector('.' + CALENDAR));\n }\n if (this.endButton.element.classList.contains(ACTIVE)) {\n this.selectableDates();\n }\n if (this.currentView() === 'Month') {\n this.bindCalendarCellEvents();\n }\n this.removeFocusedDate();\n };\n DateRangePicker.prototype.updateControl = function (calendar) {\n if (calendar.classList.contains(RIGHTCALENDER)) {\n this.rightCalCurrentDate = new Date(+this.currentDate);\n }\n else {\n this.leftCalCurrentDate = new Date(+this.currentDate);\n }\n this.updateNavIcons();\n this.calendarIconEvent();\n if ((this.leftCalendar.querySelector('.e-content').classList.contains('e-month')\n && this.rightCalendar.querySelector('.e-content').classList.contains('e-month'))\n || this.isMobile) {\n this.bindCalendarCellEvents();\n }\n this.removeFocusedDate();\n this.updateRange([calendar]);\n };\n DateRangePicker.prototype.navNextMonth = function (event) {\n event.preventDefault();\n var ele = closest(event.target, '.' + LEFTCALENDER);\n ele = isNullOrUndefined(ele) ? closest(event.target, '.' + RIGHTCALENDER) : ele;\n this.updateCalendarElement(ele);\n this.navigateNext(event);\n if (!isNullOrUndefined(this.startValue) && isNullOrUndefined(this.endValue)) {\n this.updateMinMaxDays(ele);\n }\n this.updateControl(ele);\n };\n DateRangePicker.prototype.compareMonths = function (start, end) {\n var result;\n if (start.getFullYear() === end.getFullYear() &&\n (this.currentView() === 'Year' || this.currentView() === 'Decade')) {\n result = -1;\n }\n else if (start.getFullYear() > end.getFullYear()) {\n result = -1;\n }\n else if (start.getFullYear() < end.getFullYear()) {\n if (start.getFullYear() + 1 === end.getFullYear() && start.getMonth() === 11 && end.getMonth() === 0) {\n result = -1;\n }\n else {\n result = 1;\n }\n }\n else {\n result = start.getMonth() === end.getMonth() ? 0 : start.getMonth() + 1 === end.getMonth() ? -1 : 1;\n }\n return result;\n };\n DateRangePicker.prototype.isPopupOpen = function () {\n if (!isNullOrUndefined(this.popupObj) && this.popupObj.element.classList.contains(POPUP)) {\n return true;\n }\n return false;\n };\n DateRangePicker.prototype.createRangeHeader = function () {\n var labelContainer = this.createElement('div', { className: STARTENDCONTAINER });\n if (!this.isMobile) {\n var startLabel = this.createElement('a', { className: STARTLABEL });\n var endLabel = this.createElement('a', { className: ENDLABEL });\n var changeIcon = this.createElement('span', { className: CHANGEICON });\n attributes(startLabel, { 'aria-atomic': 'true', 'aria-live': 'assertive', 'aria-label': 'Start Date', 'role': 'button' });\n attributes(endLabel, { 'aria-atomic': 'true', 'aria-live': 'assertive', 'aria-label': 'End Date', 'role': 'button' });\n labelContainer.appendChild(startLabel);\n labelContainer.appendChild(changeIcon);\n labelContainer.appendChild(endLabel);\n startLabel.textContent = this.l10n.getConstant('startLabel');\n endLabel.textContent = this.l10n.getConstant('endLabel');\n }\n else {\n var endBtn = this.createElement('button', { className: ENDBUTTON });\n var startBtn = this.createElement('button', { className: STARTBUTTON });\n this.startButton = new Button({ content: this.l10n.getConstant('startLabel') }, startBtn);\n this.endButton = new Button({ content: this.l10n.getConstant('endLabel') }, endBtn);\n labelContainer.appendChild(startBtn);\n labelContainer.appendChild(endBtn);\n }\n return labelContainer;\n };\n DateRangePicker.prototype.disableInput = function () {\n if (this.strictMode) {\n if (!isNullOrUndefined(this.previousStartValue) && !isNullOrUndefined(this.previousEndValue)) {\n this.startValue = this.previousStartValue;\n this.endValue = this.previousEndValue;\n this.setValue();\n this.updateInput();\n }\n }\n else {\n this.updateInput();\n this.clearRange();\n this.setProperties({ startDate: null }, true);\n this.setProperties({ endDate: null }, true);\n this.startValue = null;\n this.endValue = null;\n this.setValue();\n this.errorClass();\n }\n this.setProperties({ enabled: false }, true);\n Input.setEnabled(this.enabled, this.inputElement);\n this.bindEvents();\n };\n DateRangePicker.prototype.validateMinMax = function () {\n this.min = isNullOrUndefined(this.min) || !(+this.min) ? this.min = new Date(1900, 0, 1) : this.min;\n this.max = isNullOrUndefined(this.max) || !(+this.max) ? this.max = new Date(2099, 11, 31) : this.max;\n if (!(this.min <= this.max)) {\n this.disableInput();\n return;\n }\n if (!isNullOrUndefined(this.minDays) && !isNullOrUndefined(this.maxDays)) {\n if (this.maxDays > 0 && this.minDays > 0 && (this.minDays > this.maxDays)) {\n this.maxDays = null;\n }\n }\n if (!isNullOrUndefined(this.minDays) && this.minDays < 0) {\n this.minDays = null;\n }\n if (!isNullOrUndefined(this.maxDays) && this.maxDays < 0) {\n this.maxDays = null;\n }\n };\n DateRangePicker.prototype.validateRangeStrict = function () {\n if (!isNullOrUndefined(this.startValue)) {\n if (+this.startValue < +this.min) {\n this.startValue = this.min;\n this.setValue();\n }\n else if (+this.startValue > +this.max) {\n this.startValue = this.max;\n }\n }\n if (!isNullOrUndefined(this.endValue)) {\n if (+this.endValue > +this.max) {\n this.endValue = this.max;\n this.setValue();\n }\n else if (+this.endValue < +this.min) {\n this.endValue = this.min;\n this.setValue();\n }\n }\n if ((!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) && +this.startValue > +this.endValue) {\n this.endValue = this.max;\n this.setValue();\n }\n this.validateMinMaxDays();\n };\n DateRangePicker.prototype.validateRange = function () {\n this.validateMinMaxDays();\n };\n DateRangePicker.prototype.validateMinMaxDays = function () {\n if (!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) {\n var range = (Math.round(Math.abs((this.startValue.getTime() - this.endValue.getTime()) / (1000 * 60 * 60 * 24))) + 1);\n if ((!isNullOrUndefined(this.minDays) && this.minDays > 0) && !(range >= this.minDays)) {\n if (this.strictMode) {\n var date = new Date(+this.startValue);\n date.setDate(date.getDate() + (this.minDays - 1));\n if (+date > +this.max) {\n this.endValue = this.max;\n this.setValue();\n }\n else {\n this.endValue = date;\n this.setValue();\n }\n }\n else {\n this.startValue = null;\n this.endValue = null;\n this.setValue();\n }\n }\n if ((!isNullOrUndefined(this.maxDays) && this.maxDays > 0) && !(range <= this.maxDays)) {\n if (this.strictMode) {\n this.endValue = new Date(+this.startValue);\n this.endValue.setDate(this.endValue.getDate() + (this.maxDays - 1));\n this.setValue();\n }\n else {\n this.startValue = null;\n this.endValue = null;\n this.setValue();\n }\n }\n }\n };\n DateRangePicker.prototype.renderCalendar = function () {\n this.calendarElement = this.createElement('div');\n this.calendarElement.classList.add(CALENDAR);\n if (this.enableRtl) {\n this.calendarElement.classList.add(RTL);\n }\n attributes(this.calendarElement, { 'role': 'calendar' });\n _super.prototype.createHeader.call(this);\n _super.prototype.createContent.call(this);\n };\n DateRangePicker.prototype.isSameMonth = function (start, end) {\n if (start.getMonth() === end.getMonth() && start.getFullYear() === end.getFullYear()) {\n return true;\n }\n return false;\n };\n DateRangePicker.prototype.startMonthCurrentDate = function () {\n if (this.isSameMonth(this.min, this.max) || +this.currentDate > +this.max || this.isSameMonth(this.currentDate, this.max)) {\n this.currentDate = new Date(+this.max);\n this.currentDate.setDate(1);\n this.currentDate.setMonth(this.currentDate.getMonth() - 1);\n }\n else if (this.currentDate < this.min) {\n this.currentDate = new Date('' + this.min);\n }\n };\n DateRangePicker.prototype.selectNextMonth = function () {\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue) && !this.isSameMonth(this.endValue, this.currentDate)\n && !this.isDateDisabled(this.endValue) && !this.isDateDisabled(this.startValue)) {\n this.currentDate = new Date(+this.endValue);\n }\n else {\n this.currentDate.setDate(1);\n this.currentDate.setMonth(this.currentDate.getMonth() + 1);\n return;\n }\n if ((!isNullOrUndefined(this.startValue) && +this.startValue < +this.min)\n || (!isNullOrUndefined(this.endValue) && +this.endValue > +this.max)\n || ((!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) && +this.startValue > +this.endValue)) {\n this.currentDate = new Date(new Date().setHours(0, 0, 0, 0));\n this.currentDate.setDate(1);\n this.currentDate.setMonth(this.currentDate.getMonth() + 1);\n }\n };\n DateRangePicker.prototype.selectStartMonth = function () {\n if (!isNullOrUndefined(this.startValue)) {\n if (!isNullOrUndefined(this.max) && this.isSameMonth(this.startValue, this.max)) {\n this.currentDate = new Date(+this.max);\n this.currentDate.setDate(1);\n this.currentDate.setMonth(this.currentDate.getMonth() - 1);\n }\n else if (!(this.startValue >= this.min && this.startValue <= this.max)\n || this.isDateDisabled(this.startValue)) {\n this.currentDate = new Date(new Date().setHours(0, 0, 0, 0));\n }\n else {\n this.currentDate = new Date(+this.startValue);\n }\n }\n else {\n this.currentDate = new Date(new Date().setHours(0, 0, 0, 0));\n this.startMonthCurrentDate();\n }\n if ((!isNullOrUndefined(this.endValue) && +this.endValue > +this.max)\n || (!isNullOrUndefined(this.startValue) && +this.startValue < +this.min)\n || ((!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) && +this.startValue > +this.endValue)) {\n this.currentDate = new Date(new Date().setHours(0, 0, 0, 0));\n }\n this.startMonthCurrentDate();\n };\n DateRangePicker.prototype.createCalendar = function () {\n var calendarContainer = this.createElement('div', { className: CALENDARCONTAINER });\n if (!this.isMobile) {\n this.selectStartMonth();\n this.renderCalendar();\n this.leftCalCurrentDate = new Date(+this.currentDate);\n this.calendarElement.classList.add(LEFTCALENDER);\n this.leftCalPrevIcon = this.calendarElement.querySelector('.' + LEFTCALENDER + ' .' + PREVICON);\n this.leftCalNextIcon = this.calendarElement.querySelector('.' + LEFTCALENDER + ' .' + NEXTICON);\n this.leftTitle = this.calendarElement.querySelector('.' + LEFTCALENDER + ' .' + TITLE);\n remove(this.calendarElement.querySelector('.' + LEFTCALENDER + ' .' + ICONCONTAINER));\n this.calendarElement.querySelector('.' + LEFTCALENDER + ' .' + HEADER).appendChild(this.leftCalNextIcon);\n this.calendarElement.querySelector('.' + LEFTCALENDER + ' .' + HEADER).appendChild(this.leftCalPrevIcon);\n prepend([this.leftCalPrevIcon], this.calendarElement.querySelector('.' + LEFTCALENDER + ' .' + HEADER));\n this.leftCalendar = this.calendarElement;\n var leftContainer = this.createElement('div', { className: LEFTCONTAINER });\n var rightContainer = this.createElement('div', { className: RIGHTCONTAINER });\n leftContainer.appendChild(this.leftCalendar);\n calendarContainer.appendChild(leftContainer);\n if (!this.isMobile) {\n EventHandler.add(this.leftTitle, 'click', this.leftNavTitle, this);\n }\n this.selectNextMonth();\n this.renderCalendar();\n this.rightCalCurrentDate = new Date(+this.currentDate);\n addClass([this.calendarElement], RIGHTCALENDER);\n this.rightCalendar = this.calendarElement;\n removeClass([this.leftCalendar && this.leftCalendar.querySelector('.e-content tbody')], 'e-zoomin');\n removeClass([this.rightCalendar && this.rightCalendar.querySelector('.e-content tbody')], 'e-zoomin');\n this.rightCalPrevIcon = this.calendarElement.querySelector('.' + RIGHTCALENDER + ' .' + PREVICON);\n this.rightCalNextIcon = this.calendarElement.querySelector('.' + RIGHTCALENDER + ' .' + NEXTICON);\n this.rightTitle = this.calendarElement.querySelector('.' + RIGHTCALENDER + ' .' + TITLE);\n remove(this.calendarElement.querySelector('.' + RIGHTCALENDER + ' .' + ICONCONTAINER));\n this.calendarElement.querySelector('table').setAttribute('tabindex', '-1');\n this.calendarElement.querySelector('.' + RIGHTCALENDER + ' .' + HEADER).appendChild(this.rightCalNextIcon);\n this.calendarElement.querySelector('.' + RIGHTCALENDER + ' .' + HEADER).appendChild(this.rightCalPrevIcon);\n prepend([this.rightCalPrevIcon], this.calendarElement.querySelector('.' + RIGHTCALENDER + ' .' + HEADER));\n rightContainer.appendChild(this.rightCalendar);\n calendarContainer.appendChild(rightContainer);\n if (!this.isMobile) {\n EventHandler.add(this.rightTitle, 'click', this.rightNavTitle, this);\n }\n }\n else {\n if (!isNullOrUndefined(this.startValue)) {\n this.currentDate = new Date(+this.startValue);\n }\n _super.prototype.validateDate.call(this);\n _super.prototype.minMaxUpdate.call(this);\n _super.prototype.render.call(this);\n var prevIcon = this.calendarElement.querySelector('.' + CALENDAR + ' .' + PREVICON);\n var nextIcon = this.calendarElement.querySelector('.' + CALENDAR + ' .' + NEXTICON);\n remove(this.calendarElement.querySelector('.' + CALENDAR + ' .' + ICONCONTAINER));\n this.calendarElement.querySelector('.' + CALENDAR + ' .' + HEADER).appendChild(nextIcon);\n this.calendarElement.querySelector('.' + CALENDAR + ' .' + HEADER).appendChild(prevIcon);\n prepend([prevIcon], this.calendarElement.querySelector('.' + CALENDAR + ' .' + HEADER));\n this.deviceCalendar = this.calendarElement;\n calendarContainer.appendChild(this.calendarElement);\n this.headerTitleElement = this.calendarElement.querySelector('.' + CALENDAR + ' .' + HEADER + ' .' + TITLE);\n }\n return calendarContainer;\n };\n DateRangePicker.prototype.leftNavTitle = function (e) {\n if (this.isPopupOpen()) {\n this.calendarElement = this.leftCalendar;\n this.table = this.leftCalendar.querySelector('table');\n this.headerTitleElement = this.leftCalendar.querySelector('.e-title');\n this.tableBodyElement = this.leftCalendar.querySelector('tbody');\n this.tableHeadElement = this.leftCalendar.querySelector('thead');\n this.contentElement = this.leftCalendar.querySelector('.e-content');\n this.updateCalendarElement(this.leftCalendar);\n _super.prototype.navigateTitle.call(this, e);\n this.updateNavIcons();\n }\n };\n DateRangePicker.prototype.rightNavTitle = function (e) {\n if (this.isPopupOpen()) {\n this.calendarElement = this.rightCalendar;\n this.table = this.rightCalendar.querySelector('table');\n this.headerTitleElement = this.rightCalendar.querySelector('.e-title');\n this.tableBodyElement = this.rightCalendar.querySelector('tbody');\n this.tableHeadElement = this.rightCalendar.querySelector('thead');\n this.contentElement = this.rightCalendar.querySelector('.e-content');\n this.updateCalendarElement(this.rightCalendar);\n _super.prototype.navigateTitle.call(this, e);\n this.updateNavIcons();\n }\n };\n DateRangePicker.prototype.clickEventEmitter = function (e) {\n if (!this.isMobile) {\n if (closest(e.target, '.e-calendar.e-left-calendar')) {\n this.calendarElement = this.leftCalendar;\n this.updateCalendarElement(this.leftCalendar);\n }\n else {\n this.calendarElement = this.rightCalendar;\n this.updateCalendarElement(this.rightCalendar);\n }\n }\n };\n /**\n * Gets the current view of the Calendar.\n * @returns string\n * @private\n * @hidden\n */\n DateRangePicker.prototype.currentView = function () {\n return _super.prototype.currentView.call(this);\n };\n DateRangePicker.prototype.navigatedEvent = function (e) {\n var element;\n if (this.isMobile && this.currentView() === 'Month') {\n this.bindCalendarCellEvents();\n this.deviceNavigation();\n this.removeFocusedDate();\n }\n else if (this.isMobile && (this.currentView() === 'Decade' || this.currentView() === 'Year')) {\n this.selectableDates();\n }\n else {\n if (!this.isMobile && this.currentView() === 'Month') {\n element = this.calendarElement.classList.contains('e-left-calendar') ? this.leftCalendar : this.rightCalendar;\n if (element === this.leftCalendar && e && !e.currentTarget.children[0].classList.contains('e-icons')) {\n this.leftCalCurrentDate = new Date(+this.currentDate);\n this.rightCalCurrentDate = new Date(new Date(+this.currentDate).setMonth(new Date(+this.currentDate).getMonth() + 1));\n this.currentDate = this.leftCalCurrentDate;\n this.updateCalendarElement(this.leftCalendar);\n this.updateControl(this.leftCalendar);\n this.updateCalendarElement(this.rightCalendar);\n this.navigateTo('Month', this.rightCalCurrentDate);\n this.updateControl(this.rightCalendar);\n this.updateNavIcons();\n this.calendarIconEvent();\n this.calendarIconRipple();\n }\n else if (e && !e.currentTarget.children[0].classList.contains('e-icons')) {\n this.rightCalCurrentDate = new Date(+this.currentDate);\n this.leftCalCurrentDate = new Date(this.currentDate.setMonth(this.currentDate.getMonth() - 1));\n this.currentDate = this.rightCalCurrentDate;\n this.updateCalendarElement(this.rightCalendar);\n this.updateControl(this.rightCalendar);\n this.updateCalendarElement(this.leftCalendar);\n if (this.startValue && (this.startValue.getMonth() < this.rightCalCurrentDate.getMonth() &&\n this.startValue.getFullYear() <= this.rightCalCurrentDate.getFullYear())) {\n if (isNullOrUndefined(this.endValue)) {\n this.effect = '';\n this.navigateTo('Month', new Date(+this.startValue));\n }\n else {\n this.navigateTo('Month', this.leftCalCurrentDate);\n }\n }\n else {\n this.navigateTo('Month', this.leftCalCurrentDate);\n }\n this.updateControl(this.leftCalendar);\n this.updateNavIcons();\n this.calendarIconEvent();\n this.calendarIconRipple();\n }\n }\n else if (!this.isMobile && (this.currentView() === 'Decade' || this.currentView() === 'Year')) {\n this.updateNavIcons();\n this.calendarIconEvent();\n }\n }\n };\n DateRangePicker.prototype.createControl = function () {\n var controlContainer = this.createElement('div', { className: RANGECONTAINER });\n var headerContainer = this.createElement('div', { className: RANGEHEADER });\n var labelContainer = this.createRangeHeader();\n headerContainer.appendChild(labelContainer);\n var daySpan = this.createElement('div', { className: DAYSPAN });\n attributes(daySpan, { 'aria-label': 'Selected Days' });\n daySpan.textContent = this.l10n.getConstant('selectedDays');\n headerContainer.appendChild(daySpan);\n var separator = this.createElement('div', { className: SEPARATOR });\n var calendarContainer = this.createCalendar();\n controlContainer.appendChild(headerContainer);\n controlContainer.appendChild(separator);\n controlContainer.appendChild(calendarContainer);\n var footerSection = this.createElement('div', { className: FOOTER });\n var cancelBtn = this.createElement('button', { className: CANCEL + ' ' + FLAT + ' ' + CSS });\n var applyBtn = this.createElement('button');\n addClass([applyBtn], [APPLY, FLAT, PRIMARY, CSS]);\n footerSection.appendChild(applyBtn);\n footerSection.appendChild(cancelBtn);\n var enable = !isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue);\n this.cancelButton = new Button({ content: this.l10n.getConstant('cancelText') }, cancelBtn);\n this.applyButton = new Button({ content: this.l10n.getConstant('applyText'), disabled: !enable }, applyBtn);\n EventHandler.add(applyBtn, 'click touchstart', this.applyFunction, this);\n EventHandler.add(cancelBtn, 'click touchstart', this.cancelFunction, this);\n this.popupWrapper.appendChild(controlContainer);\n if (!this.isMobile) {\n if (!isUndefined(this.presets[0].start && this.presets[0].end && this.presets[0].label)) {\n this.createPresets();\n this.listRippleEffect();\n addClass([controlContainer], RANGEBORDER);\n addClass([this.popupWrapper], 'e-preset-wrapper');\n var presets = this.popupWrapper.querySelector('.' + PRESETS);\n presets.style.height = this.popupWrapper.querySelector('.' + RANGECONTAINER).getBoundingClientRect().height + 'px';\n }\n }\n this.popupWrapper.appendChild(footerSection);\n if (this.isMobile) {\n this.deviceHeaderUpdate();\n }\n this.renderPopup();\n };\n DateRangePicker.prototype.cancelFunction = function (eve) {\n if (document.activeElement !== this.inputElement) {\n this.preventFocus = true;\n if (!this.isMobile) {\n this.inputElement.focus();\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n }\n }\n eve.preventDefault();\n if (!this.isMobile && this.isKeyPopup) {\n this.inputElement.focus();\n this.isKeyPopup = false;\n }\n this.startValue = null;\n this.endValue = null;\n this.removeSelection();\n this.hide(eve);\n };\n DateRangePicker.prototype.deviceHeaderUpdate = function () {\n if (isNullOrUndefined(this.startValue) && isNullOrUndefined(this.endValue)) {\n this.endButton.element.setAttribute('disabled', '');\n this.startButton.element.classList.add(ACTIVE);\n }\n else if (!isNullOrUndefined(this.startValue)) {\n this.startButton.element.classList.add(ACTIVE);\n }\n };\n DateRangePicker.prototype.applyFunction = function (eve) {\n if (this.closeEventArgs && this.closeEventArgs.cancel) {\n this.startValue = this.popupWrapper.querySelector('.e-start-date') &&\n this.getIdValue(null, this.popupWrapper.querySelector('.e-start-date'));\n this.endValue = this.popupWrapper.querySelector('.e-end-date') &&\n this.getIdValue(null, this.popupWrapper.querySelector('.e-end-date'));\n this.setValue();\n }\n if (document.activeElement !== this.inputElement) {\n this.preventFocus = true;\n if (!this.isMobile) {\n this.inputElement.focus();\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n }\n }\n if (eve.type !== 'touchstart' &&\n this.closeEventArgs && !this.closeEventArgs.cancel) {\n eve.preventDefault();\n }\n if (!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) {\n this.previousStartValue = new Date(+this.startValue);\n this.previousEndValue = new Date(+this.endValue);\n this.previousEleValue = this.inputElement.value;\n Input.setValue(this.rangeArgs(eve).text, this.inputElement, this.floatLabelType, this.showClearButton);\n this.changeTrigger(eve);\n this.hide(eve ? eve : null);\n this.errorClass();\n }\n else {\n this.hide(eve ? eve : null);\n }\n if (!this.isMobile) {\n this.isKeyPopup = false;\n if (this.isRangeIconClicked) {\n this.inputWrapper.container.children[1].focus();\n this.popupKeyboardModule = new KeyboardEvents(this.inputWrapper.container.children[1], {\n eventName: 'keydown',\n keyAction: this.popupKeyActionHandle.bind(this),\n keyConfigs: this.keyInputConfigs\n });\n }\n }\n };\n DateRangePicker.prototype.onMouseClick = function (event, item) {\n if (event.type === 'touchstart') {\n return;\n }\n var target = item || event.target;\n var li = closest(target, '.' + LISTCLASS);\n var isClick = li && li.classList.contains(ACTIVE);\n if (li && li.classList.contains(LISTCLASS)) {\n this.setListSelection(li, event);\n }\n if (!this.isMobile) {\n this.preventFocus = true;\n this.inputElement.focus();\n if (li && li.classList.contains(LISTCLASS) && li.getAttribute('id') === 'custom_range') {\n this.leftCalendar.children[1].firstElementChild.focus();\n }\n else {\n if (!isClick && event.type === 'keydown') {\n this.inputElement.focus();\n }\n }\n }\n };\n DateRangePicker.prototype.onMouseOver = function (event) {\n var li = closest(event.target, '.' + LISTCLASS);\n if (li && li.classList.contains(LISTCLASS) && !li.classList.contains(HOVER)) {\n addClass([li], HOVER);\n }\n };\n DateRangePicker.prototype.onMouseLeave = function (event) {\n var item = closest(event.target, '.' + HOVER);\n if (!isNullOrUndefined(item)) {\n removeClass([item], HOVER);\n }\n };\n DateRangePicker.prototype.setListSelection = function (li, event) {\n if (li && (!li.classList.contains(ACTIVE) || (this.isMobile && li.classList.contains(ACTIVE)))) {\n if (this.isMobile && li.classList.contains(ACTIVE)) {\n this.activeIndex = Array.prototype.slice.call(this.liCollections).indexOf(li);\n var values_1 = this.presetsItem[this.activeIndex];\n if (values_1.id === 'custom_range') {\n this.renderCustomPopup();\n return;\n }\n return;\n }\n this.removeListSelection();\n this.activeIndex = Array.prototype.slice.call(this.liCollections).indexOf(li);\n addClass([li], ACTIVE);\n li.setAttribute('aria-selected', 'true');\n var values = this.presetsItem[this.activeIndex];\n if (values.id === 'custom_range') {\n this.renderCustomPopup();\n }\n else {\n this.applyPresetRange(values);\n }\n }\n };\n DateRangePicker.prototype.removeListSelection = function () {\n var item = this.presetElement.querySelector('.' + ACTIVE);\n if (!isNullOrUndefined(item)) {\n removeClass([item], ACTIVE);\n item.removeAttribute('aria-selected');\n }\n };\n DateRangePicker.prototype.setValue = function () {\n this.modelValue = [this.startValue, this.endValue];\n };\n DateRangePicker.prototype.applyPresetRange = function (values) {\n this.hide(null);\n this.presetsItem[this.presetsItem.length - 1].start = null;\n this.presetsItem[this.presetsItem.length - 1].end = null;\n this.startValue = values.start;\n this.endValue = values.end;\n this.setValue();\n this.refreshControl();\n this.trigger('select', this.rangeArgs(null));\n this.changeTrigger();\n this.previousEleValue = this.inputElement.value;\n this.isCustomRange = false;\n this.leftCalendar = this.rightCalendar = null;\n if (this.isKeyPopup) {\n this.isRangeIconClicked = false;\n this.inputElement.focus();\n }\n };\n DateRangePicker.prototype.showPopup = function (element, event) {\n this.presetHeight();\n if (this.zIndex === 1000) {\n this.popupObj.show(null, this.element);\n }\n else {\n this.popupObj.show(null, null);\n }\n if (this.isMobile) {\n this.popupObj.refreshPosition();\n }\n };\n DateRangePicker.prototype.renderCustomPopup = function () {\n this.isCustomWindow = true;\n this.popupObj.hide();\n this.popupWrapper = this.createElement('div', { id: this.element.id + '_popup', className: ROOT + ' ' + POPUP });\n this.renderControl();\n this.openEventArgs.appendTo.appendChild(this.popupWrapper);\n this.showPopup();\n this.isCustomRange = true;\n if (!this.isMobile) {\n this.calendarFocus();\n }\n };\n DateRangePicker.prototype.listRippleEffect = function () {\n for (var _i = 0, _a = this.liCollections; _i < _a.length; _i++) {\n var li = _a[_i];\n rippleEffect(li);\n }\n };\n DateRangePicker.prototype.createPresets = function () {\n if (!isUndefined(this.presets[0].start && this.presets[0].end && this.presets[0].label)) {\n this.presetElement = this.createElement('div', { className: PRESETS, attrs: { 'tabindex': '0' } });\n var listTag = ListBase.createList(this.createElement, this.presetsItem, null, true);\n attributes(listTag, { 'role': 'listbox', 'aria-hidden': 'false', 'id': this.element.id + '_options' });\n this.presetElement.appendChild(listTag);\n this.popupWrapper.appendChild(this.presetElement);\n this.liCollections = this.presetElement.querySelectorAll('.' + LISTCLASS);\n this.wireListEvents();\n if (this.isMobile) {\n this.presetElement.style.width = this.inputWrapper.container.getBoundingClientRect().width + 'px';\n }\n if (!isNullOrUndefined(this.activeIndex) && this.activeIndex > -1) {\n addClass([this.liCollections[this.activeIndex]], ACTIVE);\n }\n }\n };\n DateRangePicker.prototype.wireListEvents = function () {\n EventHandler.add(this.presetElement, 'click touchstart', this.onMouseClick, this);\n if (!this.isMobile) {\n EventHandler.add(this.presetElement, 'mouseover', this.onMouseOver, this);\n EventHandler.add(this.presetElement, 'mouseout', this.onMouseLeave, this);\n }\n };\n DateRangePicker.prototype.unWireListEvents = function () {\n if (!isNullOrUndefined(this.presetElement)) {\n EventHandler.remove(this.presetElement, 'click touchstart', this.onMouseClick);\n if (!this.isMobile) {\n EventHandler.remove(this.presetElement, 'mouseover', this.onMouseOver);\n EventHandler.remove(this.presetElement, 'mouseout', this.onMouseLeave);\n }\n }\n };\n // tslint:disable-next-line:max-func-body-length\n DateRangePicker.prototype.renderPopup = function () {\n var _this = this;\n this.popupWrapper.classList.add('e-control');\n var popupWidth = this.popupWrapper.getBoundingClientRect().width;\n if (!isNullOrUndefined(this.cssClass) && this.cssClass.trim() !== '') {\n this.popupWrapper.classList.add(this.cssClass);\n }\n if (this.isMobile && this.isCustomWindow) {\n this.modal = this.createElement('div');\n document.body.appendChild(this.modal);\n }\n this.popupObj = new Popup(this.popupWrapper, {\n relateTo: this.isMobile && this.isCustomWindow ? document.body :\n (!isNullOrUndefined(this.targetElement) ? this.targetElement : this.inputWrapper.container),\n position: (this.isMobile ?\n (!isUndefined(this.presets[0].start && this.presets[0].end && this.presets[0].label) && !this.isCustomWindow ?\n { X: 'left', Y: 'bottom' } : { X: 'center', Y: 'center' }) :\n this.enableRtl ? { X: 'left', Y: 'bottom' } : { X: 'right', Y: 'bottom' }),\n offsetX: this.isMobile || this.enableRtl ? 0 : -popupWidth,\n offsetY: OFFSETVALUE,\n collision: this.isMobile ?\n (!isUndefined(this.presets[0].start && this.presets[0].end && this.presets[0].label) && !this.isCustomWindow ?\n { X: 'fit' } : { X: 'fit', Y: 'fit' }) : { X: 'fit', Y: 'flip' },\n targetType: this.isMobile && this.isCustomWindow ? 'container' : 'relative',\n enableRtl: this.enableRtl,\n zIndex: this.zIndex,\n open: function () {\n attributes(_this.inputElement, { 'aria-expanded': 'true' });\n addClass([_this.inputWrapper.buttons[0]], ACTIVE);\n if (!_this.isMobile) {\n if (_this.cancelButton) {\n _this.btnKeyboardModule = new KeyboardEvents(_this.cancelButton.element, {\n eventName: 'keydown',\n keyAction: _this.hide.bind(_this),\n keyConfigs: { tab: 'tab' }\n });\n }\n if (!isNullOrUndefined(_this.leftCalendar)) {\n if (!_this.isRangeIconClicked) {\n _this.calendarFocus();\n }\n }\n if (!isNullOrUndefined(_this.presetElement)) {\n _this.presetKeyboardModule = new KeyboardEvents(_this.presetElement, {\n eventName: 'keydown',\n keyAction: _this.presetKeyActionHandler.bind(_this),\n keyConfigs: _this.presetKeyConfig\n });\n if (isNullOrUndefined(_this.leftCalendar)) {\n _this.preventBlur = true;\n _this.presetElement.focus();\n }\n else {\n _this.presetElement.setAttribute('tabindex', '-1');\n }\n }\n _this.popupKeyBoardHandler();\n }\n if (_this.isMobile && !Browser.isDevice) {\n EventHandler.add(document, 'keydown', _this.popupCloseHandler, _this);\n }\n },\n close: function () {\n attributes(_this.inputElement, { 'aria-expanded': 'false' });\n removeClass([_this.inputWrapper.buttons[0]], ACTIVE);\n if (!_this.isMobile) {\n if (_this.isRangeIconClicked) {\n _this.inputWrapper.container.children[1].focus();\n }\n }\n if (!isUndefined(_this.presets[0].start && _this.presets[0].end && _this.presets[0].label)) {\n _this.unWireListEvents();\n }\n if (!isNullOrUndefined(_this.popupObj)) {\n detach(_this.popupObj.element);\n _this.popupObj.destroy();\n _this.popupObj = null;\n }\n if (_this.isMobile && !Browser.isDevice) {\n EventHandler.remove(document, 'keydown', _this.popupCloseHandler);\n }\n }\n });\n if (this.isMobile) {\n this.popupObj.element.classList.add(DEVICE);\n if (!this.isMobile) {\n this.popupObj.element.classList.add('e-bigger');\n }\n }\n if (this.isMobile && this.isCustomWindow) {\n addClass([this.modal], [DEVICE, ROOT, 'e-range-modal']);\n document.body.className += ' ' + OVERFLOW;\n this.modal.style.display = 'block';\n }\n EventHandler.add(document, 'mousedown touchstart', this.documentHandler, this);\n };\n DateRangePicker.prototype.popupCloseHandler = function (e) {\n switch (e.keyCode) {\n case 27:\n this.hide(e);\n break;\n }\n };\n DateRangePicker.prototype.calendarFocus = function () {\n var startDate = this.popupObj && this.popupObj.element.querySelector('.' + STARTDATE);\n if (startDate) {\n var ele = closest(startDate, '.' + RIGHTCALENDER);\n ele = isNullOrUndefined(ele) ? this.leftCalendar : ele;\n if (this.isRangeIconClicked) {\n this.inputWrapper.container.focus();\n }\n else {\n this.preventBlur = true;\n ele.children[1].firstElementChild.focus();\n }\n addClass([startDate], FOCUSDATE);\n }\n else {\n if (this.isRangeIconClicked) {\n this.inputWrapper.container.focus();\n }\n else {\n this.preventBlur = true;\n this.leftCalendar.children[1].firstElementChild.focus();\n }\n }\n };\n DateRangePicker.prototype.presetHeight = function () {\n var presets = this.popupObj && this.popupObj.element.querySelector('.' + PRESETS);\n var rangeContainer = this.popupObj && this.popupObj.element.querySelector('.' + RANGECONTAINER);\n if (!isNullOrUndefined(presets) && !isNullOrUndefined(rangeContainer)) {\n presets.style.height = rangeContainer.getBoundingClientRect().height + 'px';\n }\n };\n DateRangePicker.prototype.presetKeyActionHandler = function (e) {\n switch (e.action) {\n case 'moveDown':\n this.listMoveDown(e);\n this.setScrollPosition();\n e.preventDefault();\n break;\n case 'moveUp':\n this.listMoveUp(e);\n this.setScrollPosition();\n e.preventDefault();\n break;\n case 'enter':\n var hvrItem = this.getHoverLI();\n var actItem = this.getActiveLI();\n if (!isNullOrUndefined(this.leftCalendar) && !isNullOrUndefined(actItem)) {\n if (isNullOrUndefined(hvrItem) || (!isNullOrUndefined(actItem) && actItem === hvrItem)) {\n this.activeIndex = Array.prototype.slice.call(this.liCollections).indexOf(actItem);\n var values = this.presetsItem[this.activeIndex];\n if (values.id === 'custom_range') {\n this.calendarFocus();\n actItem.classList.remove(HOVER);\n e.preventDefault();\n return;\n }\n }\n }\n if (!isNullOrUndefined(hvrItem) || !isNullOrUndefined(actItem)) {\n this.onMouseClick(e, hvrItem || actItem);\n }\n e.preventDefault();\n break;\n case 'tab':\n if (this.leftCalendar) {\n var item = this.getHoverLI();\n if (!isNullOrUndefined(item)) {\n item.classList.remove(HOVER);\n }\n }\n else {\n this.hide(e);\n e.preventDefault();\n }\n break;\n }\n };\n DateRangePicker.prototype.listMoveDown = function (e) {\n var hvrItem = this.getHoverLI();\n var actItem = this.getActiveLI();\n if (!isNullOrUndefined(hvrItem)) {\n var li = hvrItem.nextElementSibling;\n if (!isNullOrUndefined(li) && li.classList.contains(LISTCLASS)) {\n removeClass([hvrItem], HOVER);\n addClass([li], HOVER);\n }\n }\n else if (!isNullOrUndefined(actItem)) {\n var li = actItem.nextElementSibling;\n if (!isNullOrUndefined(li) && li.classList.contains(LISTCLASS)) {\n addClass([li], HOVER);\n }\n }\n else {\n addClass([this.liCollections[0]], HOVER);\n }\n };\n DateRangePicker.prototype.listMoveUp = function (e) {\n var hvrItem = this.getHoverLI();\n var actItem = this.getActiveLI();\n if (!isNullOrUndefined(hvrItem)) {\n var li = hvrItem.previousElementSibling;\n if (!isNullOrUndefined(li) && li.classList.contains(LISTCLASS)) {\n removeClass([hvrItem], HOVER);\n addClass([li], HOVER);\n }\n }\n else if (!isNullOrUndefined(actItem)) {\n var li = actItem.previousElementSibling;\n if (!isNullOrUndefined(li) && li.classList.contains(LISTCLASS)) {\n addClass([li], HOVER);\n }\n }\n };\n DateRangePicker.prototype.getHoverLI = function () {\n var item = this.presetElement.querySelector('.' + HOVER);\n return item;\n };\n DateRangePicker.prototype.getActiveLI = function () {\n var item = this.presetElement.querySelector('.' + ACTIVE);\n return item;\n };\n DateRangePicker.prototype.popupKeyBoardHandler = function () {\n this.popupKeyboardModule = new KeyboardEvents(this.popupWrapper, {\n eventName: 'keydown',\n keyAction: this.popupKeyActionHandle.bind(this),\n keyConfigs: { escape: 'escape' }\n });\n this.popupKeyboardModule = new KeyboardEvents(this.inputWrapper.container.children[1], {\n eventName: 'keydown',\n keyAction: this.popupKeyActionHandle.bind(this),\n keyConfigs: this.keyInputConfigs\n });\n };\n DateRangePicker.prototype.setScrollPosition = function () {\n var listHeight = this.presetElement.getBoundingClientRect().height;\n var hover = this.presetElement.querySelector('.' + HOVER);\n var active = this.presetElement.querySelector('.' + ACTIVE);\n var element = !isNullOrUndefined(hover) ? hover : active;\n if (!isNullOrUndefined(element)) {\n var nextEle = element.nextElementSibling;\n var height = nextEle ? nextEle.offsetTop : element.offsetTop;\n var liHeight = element.getBoundingClientRect().height;\n if ((height + element.offsetTop) > listHeight) {\n this.presetElement.scrollTop = nextEle ? (height - (listHeight / 2 + liHeight / 2)) : height;\n }\n else {\n this.presetElement.scrollTop = 0;\n }\n }\n };\n DateRangePicker.prototype.popupKeyActionHandle = function (e) {\n switch (e.action) {\n case 'escape':\n if (this.isPopupOpen()) {\n if (this.isKeyPopup) {\n this.inputElement.focus();\n this.isKeyPopup = false;\n }\n this.hide(e);\n }\n else {\n this.inputWrapper.container.children[1].blur();\n }\n break;\n case 'enter':\n if (!this.isPopupOpen()) {\n this.show(null, e);\n }\n else {\n this.inputWrapper.container.children[1].focus();\n }\n break;\n case 'tab':\n this.hide(e);\n }\n };\n DateRangePicker.prototype.documentHandler = function (e) {\n if (isNullOrUndefined(this.popupObj)) {\n return;\n }\n var target = e.target;\n if (!this.inputWrapper.container.contains(target) ||\n (!isNullOrUndefined(this.popupObj) && !closest(target, this.popupWrapper.id))) {\n if (e.type !== 'touchstart' &&\n this.closeEventArgs && !this.closeEventArgs.cancel) {\n e.preventDefault();\n }\n }\n if ((isNullOrUndefined(this.targetElement) ||\n (!isNullOrUndefined(this.targetElement) && !(target === this.targetElement))) &&\n !(closest(target, '#' + this.popupObj.element.id))\n && !(closest(target, '.' + INPUTCONTAINER) === this.inputWrapper.container)\n && !(closest(target, '.e-daterangepicker.e-popup') && (!target.classList.contains('e-day')))) {\n this.preventBlur = false;\n if (this.isPopupOpen()) {\n this.applyFunction(e);\n if (!this.isMobile) {\n this.isRangeIconClicked = false;\n }\n }\n }\n };\n DateRangePicker.prototype.createInput = function () {\n this.inputWrapper = Input.createInput({\n floatLabelType: this.floatLabelType,\n element: this.inputElement,\n properties: {\n readonly: this.readonly,\n placeholder: this.placeholder,\n cssClass: this.cssClass,\n enabled: this.enabled,\n enableRtl: this.enableRtl,\n showClearButton: this.showClearButton,\n },\n buttons: [DATERANGEICON]\n }, this.createElement);\n attributes(this.inputElement, {\n 'aria-readonly': this.readonly ? 'true' : 'false', 'tabindex': '1', 'aria-haspopup': 'true',\n 'aria-activedescendant': 'null', 'aria-owns': this.element.id + '_popup', 'aria-expanded': 'false',\n 'role': 'daterangepicker', 'autocomplete': 'off', 'aria-disabled': !this.enabled ? 'true' : 'false',\n 'autocorrect': 'off', 'autocapitalize': 'off', 'spellcheck': 'false'\n });\n Input.addAttributes({ 'aria-label': 'select' }, this.inputWrapper.buttons[0]);\n if (!isNullOrUndefined(this.placeholder) && this.placeholder.trim() !== '') {\n Input.addAttributes({ 'aria-placeholder': this.placeholder }, this.inputElement);\n }\n this.setEleWidth(this.width);\n addClass([this.inputWrapper.container], DATERANGEWRAPPER);\n if (isNullOrUndefined(this.inputElement.getAttribute('name'))) {\n attributes(this.inputElement, { 'name': this.element.id });\n }\n if (this.inputElement.type === 'hidden') {\n this.inputWrapper.container.style.display = 'none';\n }\n this.refreshControl();\n this.previousEleValue = this.inputElement.value;\n };\n DateRangePicker.prototype.setEleWidth = function (width) {\n if (typeof width === 'string') {\n this.inputWrapper.container.style.width = (this.width);\n }\n else if (typeof width === 'number') {\n this.inputWrapper.container.style.width = formatUnit(this.width);\n }\n else {\n this.inputWrapper.container.style.width = '100%';\n }\n };\n DateRangePicker.prototype.refreshControl = function () {\n this.validateMinMax();\n if (this.strictMode) {\n this.validateRangeStrict();\n }\n var isDisabled = this.disabledDates();\n if (this.strictMode && (isDisabled)) {\n this.startValue = this.previousStartValue;\n this.setProperties({ startDate: this.startValue }, true);\n this.endValue = this.previousEndValue;\n this.setProperties({ endDate: this.endValue }, true);\n this.setValue();\n }\n this.updateInput();\n if (!this.strictMode) {\n this.validateRange();\n }\n if (!this.strictMode && (isDisabled)) {\n this.clearRange();\n }\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue) && !isDisabled) {\n this.disabledDateRender();\n }\n this.errorClass();\n this.previousStartValue = isNullOrUndefined(this.startValue) || isNaN(+this.startValue) ? null : new Date(+this.startValue);\n this.previousEndValue = isNullOrUndefined(this.endValue) || isNaN(+this.endValue) ? null : new Date(+this.endValue);\n };\n DateRangePicker.prototype.updateInput = function () {\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n var startDate = this.globalize.formatDate(this.startValue, { format: this.format, type: 'date', skeleton: 'yMd' });\n var endDate = this.globalize.formatDate(this.endValue, { format: this.format, type: 'date', skeleton: 'yMd' });\n Input.setValue(startDate + ' ' + this.separator + ' ' + endDate, this.inputElement, this.floatLabelType, this.showClearButton);\n this.previousStartValue = new Date(+this.startValue);\n this.previousEndValue = new Date(+this.endValue);\n }\n };\n DateRangePicker.prototype.isDateDisabled = function (date) {\n var value = new Date(+date);\n if (+value < +this.min || +value > +this.max) {\n return true;\n }\n this.virtualRenderCellArgs = {\n date: value,\n isDisabled: false,\n };\n var args = this.virtualRenderCellArgs;\n this.virtualRenderCellEvent(args);\n if (args.isDisabled) {\n return true;\n }\n return false;\n };\n DateRangePicker.prototype.disabledDateRender = function () {\n this.disabledDays = [];\n this.disabledDayCnt = null;\n var localDate = new Date(+this.startValue);\n var count = 0;\n while (+localDate <= +this.endValue) {\n this.virtualRenderCellArgs = {\n date: localDate,\n isDisabled: false,\n };\n var args = this.virtualRenderCellArgs;\n this.virtualRenderCellEvent(args);\n if (args.isDisabled) {\n this.disabledDays.push(new Date(+args.date));\n if (+localDate > +this.startValue && +localDate < +this.endValue) {\n count++;\n }\n }\n this.addDay(localDate, 1, null, this.max, this.min);\n }\n this.disabledDayCnt = count;\n };\n DateRangePicker.prototype.virtualRenderCellEvent = function (args) {\n extend(this.virtualRenderCellArgs, { name: 'renderDayCell' });\n this.trigger('renderDayCell', args);\n };\n DateRangePicker.prototype.disabledDates = function () {\n var isStartDisabled = false;\n var isEndDisabled = false;\n if (!isNullOrUndefined(this.endValue) && !isNullOrUndefined(this.startValue)) {\n isStartDisabled = this.isDateDisabled(this.startValue);\n isEndDisabled = this.isDateDisabled(this.endValue);\n this.currentDate = null;\n this.setValue();\n }\n return (isStartDisabled || isEndDisabled);\n };\n DateRangePicker.prototype.setModelValue = function () {\n if (!this.value && this.startDate === null && this.endDate === null) {\n this.setProperties({ value: null }, true);\n }\n else if (this.value === null || this.value.start === null) {\n if (this.value === null) {\n this.setProperties({ value: [this.startDate, this.endDate] }, true);\n }\n else if (this.value.start === null) {\n this.setProperties({ value: { start: this.startDate, end: this.endDate } }, true);\n }\n }\n else {\n if ((this.value && this.value.length > 0) ||\n this.valueType && this.valueType.length > 0) {\n this.setProperties({ value: [this.startDate, this.endDate] }, true);\n }\n else {\n if ((this.value && this.value.start)) {\n this.setProperties({ value: { start: this.startDate, end: this.endDate } }, true);\n }\n }\n }\n };\n DateRangePicker.prototype.changeTrigger = function (e) {\n if (+this.initStartDate !== +this.startValue || +this.initEndDate !== +this.endValue) {\n this.setProperties({ endDate: this.checkDateValue(this.endValue) }, true);\n this.setProperties({ startDate: this.checkDateValue(this.startValue) }, true);\n this.setModelValue();\n this.trigger('change', this.rangeArgs(e));\n }\n this.previousEleValue = this.inputElement.value;\n this.initStartDate = this.checkDateValue(this.startValue);\n this.initEndDate = this.checkDateValue(this.endValue);\n };\n /**\n * This method is used to navigate to the month/year/decade view of the Calendar.\n * @param {string} view - Specifies the view of the Calendar.\n * @param {Date} date - Specifies the focused date in a view.\n * @returns void\n * @hidden\n */\n DateRangePicker.prototype.navigateTo = function (view, value) {\n _super.prototype.navigateTo.call(this, view, value);\n };\n /**\n * Sets the focus to widget for interaction.\n * @returns void\n */\n DateRangePicker.prototype.focusIn = function () {\n if (document.activeElement !== this.inputElement && this.enabled) {\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n this.inputElement.focus();\n var focusArguments = {\n model: this\n };\n this.trigger('focus', focusArguments);\n }\n };\n /**\n * Remove the focus from widget, if the widget is in focus state.\n * @returns void\n */\n DateRangePicker.prototype.focusOut = function () {\n var isBlur = this.preventBlur;\n if (document.activeElement === this.inputElement) {\n removeClass([this.inputWrapper.container], [INPUTFOCUS]);\n this.preventBlur = false;\n this.inputElement.blur();\n this.preventBlur = isBlur;\n }\n };\n /**\n * To destroy the widget.\n * @returns void\n */\n DateRangePicker.prototype.destroy = function () {\n this.hide(null);\n var ariaAttrs = {\n 'aria-readonly': this.readonly ? 'true' : 'false', 'tabindex': '1', 'aria-haspopup': 'true',\n 'aria-activedescendant': 'null', 'aria-owns': this.element.id + '_popup', 'aria-expanded': 'false',\n 'role': 'daterangepicker', 'autocomplete': 'off', 'aria-disabled': !this.enabled ? 'true' : 'false',\n 'autocorrect': 'off', 'autocapitalize': 'off', 'aria-invalid': 'false', 'spellcheck': 'false'\n };\n if (this.inputElement) {\n removeClass([this.inputElement], [ROOT]);\n EventHandler.remove(this.inputElement, 'blur', this.inputBlurHandler);\n Input.removeAttributes(ariaAttrs, this.inputElement);\n this.ensureInputAttribute();\n this.inputElement.classList.remove('e-input');\n if (!isNullOrUndefined(this.inputWrapper)) {\n EventHandler.remove(this.inputWrapper.buttons[0], 'mousedown', this.rangeIconHandler);\n if (this.angularTag === null) {\n this.inputWrapper.container.parentElement.appendChild(this.inputElement);\n }\n detach(this.inputWrapper.container);\n }\n }\n if (!isNullOrUndefined(this.inputKeyboardModule) && !this.isMobile) {\n this.inputKeyboardModule.destroy();\n }\n if (this.popupObj) {\n if (!this.isMobile) {\n this.clearCalendarEvents();\n }\n }\n _super.prototype.destroy.call(this);\n this.inputWrapper = this.popupWrapper = this.popupObj = this.cloneElement = this.presetElement = null;\n var form = closest(this.element, 'form');\n if (form) {\n EventHandler.remove(form, 'reset', this.formResetHandler.bind(this));\n }\n };\n DateRangePicker.prototype.ensureInputAttribute = function () {\n for (var attr = 0; attr < this.inputElement.attributes.length; attr++) {\n var prop = this.inputElement.attributes[attr].name;\n if (isNullOrUndefined(this.cloneElement.getAttribute(prop))) {\n if (prop.toLowerCase() === 'value' || isNullOrUndefined(this.cloneElement.getAttribute('value'))) {\n this.inputElement.value = '';\n }\n this.inputElement.removeAttribute(prop);\n }\n }\n };\n /**\n * To get component name\n * @returns string\n * @private\n */\n DateRangePicker.prototype.getModuleName = function () {\n return 'daterangepicker';\n };\n /**\n * Return the properties that are maintained upon browser refresh.\n * @returns string\n */\n DateRangePicker.prototype.getPersistData = function () {\n var keyEntity = ['startDate', 'endDate', 'value'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Return the selected range and day span in the DateRangePicker.\n * @returns Object\n */\n DateRangePicker.prototype.getSelectedRange = function () {\n var range;\n if (!isNullOrUndefined(this.startValue) && !isNullOrUndefined(this.endValue)) {\n range = (Math.round(Math.abs((this.startValue.getTime() - this.endValue.getTime()) / (1000 * 60 * 60 * 24))) + 1);\n this.disabledDateRender();\n if (!isNullOrUndefined(this.disabledDayCnt)) {\n range = range - this.disabledDayCnt;\n this.disabledDayCnt = null;\n }\n }\n else {\n range = 0;\n }\n return { startDate: this.startValue, endDate: this.endValue, daySpan: range };\n };\n /**\n * To open the Popup container in the DateRangePicker component.\n * @returns void\n */\n DateRangePicker.prototype.show = function (element, event) {\n if (this.isMobile && this.popupObj) {\n this.popupObj.refreshPosition();\n }\n if ((this.enabled && this.readonly) || !this.enabled || this.popupObj) {\n return;\n }\n else {\n if (!this.isPopupOpen()) {\n if (element) {\n this.targetElement = element;\n }\n this.createPopup();\n this.openEventArgs = {\n popup: this.popupObj || null,\n cancel: false,\n date: this.inputElement.value,\n model: this,\n event: event ? event : null,\n appendTo: document.body\n };\n this.trigger('open', this.openEventArgs);\n if (!this.openEventArgs.cancel) {\n this.openEventArgs.appendTo.appendChild(this.popupWrapper);\n this.showPopup(element, event);\n var isPreset = (!this.isCustomRange || (this.isMobile && this.isCustomRange));\n if (!isUndefined(this.presets[0].start && this.presets[0].end && this.presets[0].label) && isPreset) {\n this.setScrollPosition();\n }\n }\n }\n }\n };\n /**\n * To close the Popup container in the DateRangePicker component.\n * @returns void\n */\n DateRangePicker.prototype.hide = function (event) {\n if (this.popupObj) {\n if (isNullOrUndefined(this.previousEndValue) && isNullOrUndefined(this.previousStartValue)) {\n this.clearRange();\n }\n else {\n if (!isNullOrUndefined(this.previousStartValue)) {\n this.startValue = new Date('' + this.previousStartValue);\n this.setValue();\n this.currentDate = new Date('' + this.startValue);\n }\n else {\n this.startValue = null;\n this.setValue();\n }\n if (!isNullOrUndefined(this.previousEndValue)) {\n this.endValue = new Date('' + this.previousEndValue);\n this.setValue();\n }\n else {\n this.endValue = null;\n this.setValue();\n }\n }\n if (this.isPopupOpen()) {\n this.closeEventArgs = {\n cancel: false,\n popup: this.popupObj,\n date: this.inputElement.value,\n model: this,\n event: event ? event : null\n };\n this.trigger('close', this.closeEventArgs);\n if (!this.closeEventArgs.cancel) {\n if (this.isMobile) {\n if (!isNullOrUndefined(this.startButton) && !isNullOrUndefined(this.endButton)) {\n EventHandler.remove(this.startButton.element, 'click touchstart', this.deviceHeaderClick);\n EventHandler.remove(this.endButton.element, 'click touchstart', this.deviceHeaderClick);\n }\n }\n if (this.popupObj) {\n this.popupObj.hide();\n if (this.preventBlur) {\n if (!this.isMobile) {\n this.inputElement.focus();\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n }\n }\n }\n if (!this.isMobile) {\n if (!isNullOrUndefined(this.leftKeyboardModule) && !isNullOrUndefined(this.rightKeyboardModule)) {\n this.leftKeyboardModule.destroy();\n this.rightKeyboardModule.destroy();\n }\n if (!isNullOrUndefined(this.presetElement)) {\n this.presetKeyboardModule.destroy();\n }\n if (!isNullOrUndefined(this.cancelButton)) {\n this.btnKeyboardModule.destroy();\n }\n }\n this.targetElement = null;\n removeClass([document.body], OVERFLOW);\n EventHandler.remove(document, 'mousedown touchstart', this.documentHandler);\n if (this.isMobile && this.modal) {\n this.modal.style.display = 'none';\n this.modal.outerHTML = '';\n this.modal = null;\n }\n this.isKeyPopup = this.dateDisabled = false;\n }\n else {\n removeClass([this.inputWrapper.buttons[0]], ACTIVE);\n }\n }\n }\n };\n DateRangePicker.prototype.setLocale = function () {\n this.globalize = new Internationalization(this.locale);\n this.l10n.setLocale(this.locale);\n this.setProperties({ placeholder: this.l10n.getConstant('placeholder') }, true);\n Input.setPlaceholder(this.placeholder, this.inputElement);\n this.updateInput();\n this.changeTrigger();\n };\n DateRangePicker.prototype.refreshChange = function () {\n this.refreshControl();\n this.changeTrigger();\n };\n DateRangePicker.prototype.setDate = function () {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n this.refreshChange();\n };\n DateRangePicker.prototype.enableInput = function () {\n if (+this.min <= +this.max) {\n this.setProperties({ enabled: true }, true);\n Input.setEnabled(this.enabled, this.inputElement);\n if (this.element.hasAttribute('disabled')) {\n this.bindEvents();\n }\n }\n };\n DateRangePicker.prototype.clearModelvalue = function (newProp, oldProp) {\n this.setProperties({ startDate: null }, true);\n this.setProperties({ endDate: null }, true);\n if (oldProp.value && oldProp.value.length > 0) {\n this.setProperties({ value: null }, true);\n }\n else if (oldProp.value && oldProp.value.start) {\n this.setProperties({ value: { start: null, end: null } }, true);\n }\n else if (oldProp.value && !oldProp.value.start) {\n this.setProperties({ value: { start: null, end: null } }, true);\n }\n this.updateValue();\n this.setDate();\n };\n /**\n * Called internally if any of the property value changed.\n * returns void\n * @private\n */\n // tslint:disable-next-line:max-func-body-length\n DateRangePicker.prototype.onPropertyChanged = function (newProp, oldProp) {\n var format = { format: this.format, type: 'date', skeleton: 'yMd' };\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n this.hide(null);\n switch (prop) {\n case 'width':\n this.setEleWidth(this.width);\n break;\n case 'separator':\n this.previousEleValue = this.inputElement.value;\n this.setProperties({ separator: newProp.separator }, true);\n this.updateInput();\n this.changeTrigger();\n break;\n case 'placeholder':\n Input.setPlaceholder(newProp.placeholder, this.inputElement);\n this.setProperties({ placeholder: newProp.placeholder }, true);\n break;\n case 'readonly':\n Input.setReadonly(this.readonly, this.inputElement);\n this.inputElement.setAttribute('aria-readonly', '' + this.readonly);\n break;\n case 'cssClass':\n if (this.popupWrapper) {\n addClass([this.popupWrapper], [newProp.cssClass]);\n }\n addClass([this.inputWrapper.container], [newProp.cssClass]);\n this.setProperties({ cssClass: newProp.cssClass }, true);\n break;\n case 'enabled':\n this.setProperties({ enabled: newProp.enabled }, true);\n Input.setEnabled(this.enabled, this.inputElement);\n this.bindEvents();\n break;\n case 'allowEdit':\n this.setRangeAllowEdit();\n break;\n case 'enableRtl':\n this.setProperties({ enableRtl: newProp.enableRtl }, true);\n Input.setEnableRtl(this.enableRtl, [this.inputWrapper.container]);\n break;\n case 'zIndex':\n this.setProperties({ zIndex: newProp.zIndex }, true);\n break;\n case 'format':\n this.setProperties({ format: newProp.format }, true);\n this.updateInput();\n this.changeTrigger();\n break;\n case 'locale':\n this.globalize = new Internationalization(this.locale);\n this.l10n.setLocale(this.locale);\n this.setProperties({ placeholder: this.l10n.getConstant('placeholder') }, true);\n Input.setPlaceholder(this.placeholder, this.inputElement);\n this.setLocale();\n break;\n case 'showClearButton':\n Input.setClearButton(this.showClearButton, this.inputElement, this.inputWrapper);\n this.bindClearEvent();\n break;\n case 'startDate':\n if (typeof newProp.startDate === 'string') {\n newProp.startDate = this.globalize.parseDate(newProp.startDate, format);\n }\n if (+this.initStartDate !== +newProp.startDate) {\n this.startValue = newProp.startDate;\n this.setValue();\n this.setDate();\n }\n break;\n case 'endDate':\n if (typeof newProp.endDate === 'string') {\n newProp.endDate = this.globalize.parseDate(newProp.endDate, format);\n }\n if (+this.initEndDate !== +newProp.endDate) {\n this.endValue = this.checkDateValue(new Date('' + newProp.endDate));\n this.setValue();\n this.setDate();\n }\n break;\n case 'value':\n if ((!isNullOrUndefined(newProp.value) && newProp.value.length > 0)\n || !isNullOrUndefined(newProp.value) && newProp.value.start) {\n this.valueType = newProp.value;\n if (newProp.value[0] === null || (newProp.value.start === null)) {\n if (newProp.value.length === 1 || (newProp.value.start)) {\n this.clearModelvalue(newProp, oldProp);\n }\n else if (newProp.value[1] === null ||\n (newProp.value.start === null)) {\n this.clearModelvalue(newProp, oldProp);\n }\n }\n else if ((+this.initStartDate !== +newProp.value[0]\n || +this.initEndDate !== +newProp.value[1]) ||\n (+this.initStartDate !== +(newProp.value.start\n || +this.initEndDate !== +newProp.value.start))) {\n if (newProp.value.length === 1) {\n this.modelValue = newProp.value;\n }\n else if (newProp.value.start) {\n this.modelValue = newProp.value;\n }\n this.updateValue();\n this.setDate();\n }\n }\n else {\n if (isNullOrUndefined(this.value)\n || newProp.value.start == null) {\n this.valueType = newProp.value;\n this.startValue = null;\n this.endValue = null;\n this.clearModelvalue(newProp, oldProp);\n }\n }\n break;\n case 'minDays':\n this.setProperties({ minDays: newProp.minDays }, true);\n this.refreshChange();\n break;\n case 'maxDays':\n this.setProperties({ maxDays: newProp.maxDays }, true);\n this.refreshChange();\n break;\n case 'min':\n this.setProperties({ min: this.checkDateValue(new Date('' + newProp.min)) }, true);\n this.previousEleValue = this.inputElement.value;\n this.enableInput();\n this.refreshChange();\n break;\n case 'max':\n this.setProperties({ max: this.checkDateValue(new Date('' + newProp.max)) }, true);\n this.enableInput();\n this.refreshChange();\n break;\n case 'strictMode':\n this.setProperties({ strictMode: newProp.strictMode }, true);\n this.refreshChange();\n break;\n case 'presets':\n this.setProperties({ presets: newProp.presets }, true);\n this.processPresets();\n break;\n case 'floatLabelType':\n this.floatLabelType = newProp.floatLabelType;\n Input.removeFloating(this.inputWrapper);\n Input.addFloating(this.inputElement, this.floatLabelType, this.placeholder);\n break;\n }\n }\n };\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"value\", void 0);\n __decorate([\n Property(false)\n ], DateRangePicker.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(false)\n ], DateRangePicker.prototype, \"enableRtl\", void 0);\n __decorate([\n Property(new Date(1900, 0, 1))\n ], DateRangePicker.prototype, \"min\", void 0);\n __decorate([\n Property(new Date(2099, 11, 31))\n ], DateRangePicker.prototype, \"max\", void 0);\n __decorate([\n Property('en-US')\n ], DateRangePicker.prototype, \"locale\", void 0);\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"firstDayOfWeek\", void 0);\n __decorate([\n Property(false)\n ], DateRangePicker.prototype, \"weekNumber\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"destroyed\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"navigated\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"renderDayCell\", void 0);\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"startDate\", void 0);\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"endDate\", void 0);\n __decorate([\n Collection([{}], Presets)\n ], DateRangePicker.prototype, \"presets\", void 0);\n __decorate([\n Property('')\n ], DateRangePicker.prototype, \"width\", void 0);\n __decorate([\n Property(1000)\n ], DateRangePicker.prototype, \"zIndex\", void 0);\n __decorate([\n Property(true)\n ], DateRangePicker.prototype, \"showClearButton\", void 0);\n __decorate([\n Property(true)\n ], DateRangePicker.prototype, \"showTodayButton\", void 0);\n __decorate([\n Property('Month')\n ], DateRangePicker.prototype, \"start\", void 0);\n __decorate([\n Property('Month')\n ], DateRangePicker.prototype, \"depth\", void 0);\n __decorate([\n Property('')\n ], DateRangePicker.prototype, \"cssClass\", void 0);\n __decorate([\n Property('-')\n ], DateRangePicker.prototype, \"separator\", void 0);\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"minDays\", void 0);\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"maxDays\", void 0);\n __decorate([\n Property(false)\n ], DateRangePicker.prototype, \"strictMode\", void 0);\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"format\", void 0);\n __decorate([\n Property(true)\n ], DateRangePicker.prototype, \"enabled\", void 0);\n __decorate([\n Property(false)\n ], DateRangePicker.prototype, \"readonly\", void 0);\n __decorate([\n Property(true)\n ], DateRangePicker.prototype, \"allowEdit\", void 0);\n __decorate([\n Property('Never')\n ], DateRangePicker.prototype, \"floatLabelType\", void 0);\n __decorate([\n Property(null)\n ], DateRangePicker.prototype, \"placeholder\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"select\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"focus\", void 0);\n __decorate([\n Event()\n ], DateRangePicker.prototype, \"blur\", void 0);\n DateRangePicker = __decorate([\n NotifyPropertyChanges\n ], DateRangePicker);\n return DateRangePicker;\n}(CalendarBase));\nexport { DateRangePicker };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n///
\nimport { EventHandler, Internationalization, Property, NotifyPropertyChanges, Browser } from '@syncfusion/ej2-base';\nimport { Animation, Event, cldrData, getDefaultDateObject, detach } from '@syncfusion/ej2-base';\nimport { createElement, remove, addClass, L10n, removeClass, closest, append, attributes } from '@syncfusion/ej2-base';\nimport { KeyboardEvents, isNullOrUndefined, formatUnit, getValue, rippleEffect } from '@syncfusion/ej2-base';\nimport { Popup } from '@syncfusion/ej2-popups';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { DatePicker } from '../datepicker/datepicker';\nimport { TimePickerBase } from '../timepicker/timepicker';\nimport { cssClass as ListBaseClasses } from '@syncfusion/ej2-lists';\n//class constant defination\nvar DATEWRAPPER = 'e-date-wrapper';\nvar DATEPICKERROOT = 'e-datepicker';\nvar DATETIMEWRAPPER = 'e-datetime-wrapper';\nvar DAY = new Date().getDate();\nvar MONTH = new Date().getMonth();\nvar YEAR = new Date().getFullYear();\nvar HOUR = new Date().getHours();\nvar MINUTE = new Date().getMinutes();\nvar SECOND = new Date().getSeconds();\nvar MILLISECOND = new Date().getMilliseconds();\nvar ROOT = 'e-datetimepicker';\nvar DATETIMEPOPUPWRAPPER = 'e-datetimepopup-wrapper';\nvar INPUTWRAPPER = 'e-input-group-icon';\nvar POPUP = 'e-popup';\nvar TIMEICON = 'e-time-icon';\nvar INPUTFOCUS = 'e-input-focus';\nvar POPUPDIMENSION = '250px';\nvar ICONANIMATION = 'e-icon-anim';\nvar DISABLED = 'e-disabled';\nvar ERROR = 'e-error';\nvar CONTENT = 'e-content';\nvar RTL = 'e-rtl';\nvar NAVIGATION = 'e-navigation';\nvar ACTIVE = 'e-active';\nvar HOVER = 'e-hover';\nvar ICONS = 'e-icons';\nvar HALFPOSITION = 2;\nvar LISTCLASS = ListBaseClasses.li;\nvar ANIMATIONDURATION = 100;\nvar OVERFLOW = 'e-time-overflow';\n/**\n * Represents the DateTimePicker component that allows user to select\n * or enter a date time value.\n * ```html\n *
\n * ```\n * ```typescript\n * \n * ```\n */\nvar DateTimePicker = /** @class */ (function (_super) {\n __extends(DateTimePicker, _super);\n /**\n * Constructor for creating the widget\n */\n function DateTimePicker(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.valueWithMinutes = null;\n _this.previousDateTime = null;\n return _this;\n }\n DateTimePicker.prototype.focusHandler = function () {\n addClass([this.inputWrapper.container], INPUTFOCUS);\n };\n /**\n * Sets the focus to widget for interaction.\n * @returns void\n */\n DateTimePicker.prototype.focusIn = function () {\n _super.prototype.focusIn.call(this);\n };\n /**\n * Remove the focus from widget, if the widget is in focus state.\n * @returns void\n */\n DateTimePicker.prototype.focusOut = function () {\n if (document.activeElement === this.inputElement) {\n this.inputElement.blur();\n removeClass([this.inputWrapper.container], [INPUTFOCUS]);\n }\n };\n DateTimePicker.prototype.blurHandler = function (e) {\n // IE popup closing issue when click over the scrollbar\n if (this.isTimePopupOpen() && this.isPreventBlur) {\n this.inputElement.focus();\n return;\n }\n removeClass([this.inputWrapper.container], INPUTFOCUS);\n var blurArguments = {\n model: this\n };\n if (this.isTimePopupOpen()) {\n this.hide(e);\n }\n this.trigger('blur', blurArguments);\n };\n /**\n * To destroy the widget.\n * @returns void\n */\n DateTimePicker.prototype.destroy = function () {\n if (this.popupObject && this.popupObject.element.classList.contains(POPUP)) {\n this.dateTimeWrapper = undefined;\n this.liCollections = this.timeCollections = [];\n if (!isNullOrUndefined(this.rippleFn)) {\n this.rippleFn();\n }\n }\n var ariaAttribute = {\n 'aria-live': 'assertive', 'aria-atomic': 'true', 'aria-invalid': 'false',\n 'aria-haspopup': 'true', 'aria-activedescendant': 'null',\n 'autocorrect': 'off', 'autocapitalize': 'off', 'spellcheck': 'false',\n 'aria-owns': this.element.id + '_options', 'aria-expanded': 'false', 'role': 'combobox', 'autocomplete': 'off'\n };\n if (this.inputElement) {\n Input.removeAttributes(ariaAttribute, this.inputElement);\n this.inputElement.removeAttribute('aria-placeholder');\n }\n if (this.isCalendar()) {\n if (this.popupWrapper) {\n detach(this.popupWrapper);\n }\n this.popupObject = this.popupWrapper = null;\n this.keyboardHandler.destroy();\n }\n this.unBindInputEvents();\n _super.prototype.destroy.call(this);\n };\n /**\n * To Initialize the control rendering.\n * @return void\n * @private\n */\n DateTimePicker.prototype.render = function () {\n this.timekeyConfigure = {\n enter: 'enter',\n escape: 'escape',\n end: 'end',\n tab: 'tab',\n home: 'home',\n down: 'downarrow',\n up: 'uparrow',\n left: 'leftarrow',\n right: 'rightarrow',\n open: 'alt+downarrow',\n close: 'alt+uparrow'\n };\n this.valueWithMinutes = null;\n this.previousDateTime = null;\n this.isPreventBlur = false;\n this.cloneElement = this.element.cloneNode(true);\n this.dateTimeFormat = this.cldrDateTimeFormat();\n this.initValue = this.value;\n this.checkAttributes();\n var localeText = { placeholder: this.placeholder };\n this.l10n = new L10n('datetimepicker', localeText, this.locale);\n this.setProperties({ placeholder: this.placeholder || this.l10n.getConstant('placeholder') }, true);\n _super.prototype.render.call(this);\n this.createInputElement();\n this.bindInputEvents();\n this.setValue();\n this.previousDateTime = this.value && new Date(+this.value);\n };\n DateTimePicker.prototype.setValue = function () {\n this.initValue = this.validateMinMaxRange(this.value);\n if (!this.strictMode && this.isDateObject(this.initValue)) {\n var value = this.validateMinMaxRange(this.initValue);\n Input.setValue(this.getFormattedValue(value), this.inputElement, this.floatLabelType, this.showClearButton);\n this.setProperties({ value: value }, true);\n }\n else {\n if (isNullOrUndefined(this.value)) {\n this.initValue = null;\n this.setProperties({ value: null }, true);\n }\n }\n this.valueWithMinutes = this.value;\n _super.prototype.updateInput.call(this);\n };\n DateTimePicker.prototype.validateMinMaxRange = function (value) {\n var result = value;\n if (this.isDateObject(value)) {\n result = this.validateValue(value);\n }\n else {\n if (+this.min > +this.max) {\n this.disablePopupButton(true);\n }\n }\n this.checkValidState(result);\n return result;\n };\n DateTimePicker.prototype.checkValidState = function (value) {\n this.isValidState = true;\n if (!this.strictMode) {\n if ((+(value) > +(this.max)) || (+(value) < +(this.min))) {\n this.isValidState = false;\n }\n }\n this.checkErrorState();\n };\n DateTimePicker.prototype.checkErrorState = function () {\n if (this.isValidState) {\n removeClass([this.inputWrapper.container], ERROR);\n }\n else {\n addClass([this.inputWrapper.container], ERROR);\n }\n attributes(this.inputElement, { 'aria-invalid': this.isValidState ? 'false' : 'true' });\n };\n DateTimePicker.prototype.validateValue = function (value) {\n var dateVal = value;\n if (this.strictMode) {\n if (+this.min > +this.max) {\n this.disablePopupButton(true);\n dateVal = this.max;\n }\n else if (+value < +this.min) {\n dateVal = this.min;\n }\n else if (+value > +this.max) {\n dateVal = this.max;\n }\n }\n else {\n if (+this.min > +this.max) {\n this.disablePopupButton(true);\n dateVal = value;\n }\n }\n return dateVal;\n };\n DateTimePicker.prototype.disablePopupButton = function (isDisable) {\n if (isDisable) {\n addClass([this.inputWrapper.buttons[0], this.timeIcon], DISABLED);\n this.hide();\n }\n else {\n removeClass([this.inputWrapper.buttons[0], this.timeIcon], DISABLED);\n }\n };\n DateTimePicker.prototype.getFormattedValue = function (value) {\n if (!isNullOrUndefined(value)) {\n var dateOptions = { format: this.cldrDateTimeFormat(), type: 'dateTime', skeleton: 'yMd' };\n return this.globalize.formatDate(value, dateOptions);\n }\n else {\n return null;\n }\n };\n DateTimePicker.prototype.isDateObject = function (value) {\n return (!isNullOrUndefined(value) && !isNaN(+value)) ? true : false;\n };\n DateTimePicker.prototype.createInputElement = function () {\n removeClass([this.inputElement], DATEPICKERROOT);\n removeClass([this.inputWrapper.container], DATEWRAPPER);\n addClass([this.inputWrapper.container], DATETIMEWRAPPER);\n addClass([this.inputElement], ROOT);\n this.renderTimeIcon();\n };\n DateTimePicker.prototype.renderTimeIcon = function () {\n this.timeIcon = Input.appendSpan(INPUTWRAPPER + ' ' + TIMEICON + ' ' + ICONS, this.inputWrapper.container);\n };\n DateTimePicker.prototype.bindInputEvents = function () {\n EventHandler.add(this.timeIcon, 'mousedown touchstart', this.timeHandler, this);\n EventHandler.add(this.inputWrapper.buttons[0], 'mousedown touchstart', this.dateHandler, this);\n EventHandler.add(this.inputElement, 'blur', this.blurHandler, this);\n EventHandler.add(this.inputElement, 'focus', this.focusHandler, this);\n this.keyboardHandler = new KeyboardEvents(this.inputElement, {\n eventName: 'keydown',\n keyAction: this.inputKeyAction.bind(this),\n keyConfigs: this.keyConfigs\n });\n };\n DateTimePicker.prototype.unBindInputEvents = function () {\n EventHandler.remove(this.timeIcon, 'mousedown touchstart', this.timeHandler);\n EventHandler.remove(this.inputWrapper.buttons[0], 'mousedown touchstart', this.dateHandler);\n if (this.inputElement) {\n EventHandler.remove(this.inputElement, 'blur', this.blurHandler);\n EventHandler.remove(this.inputElement, 'focus', this.focusHandler);\n }\n if (this.keyboardHandler) {\n this.keyboardHandler.destroy();\n }\n };\n DateTimePicker.prototype.cldrTimeFormat = function () {\n var cldrTime;\n if (this.isNullOrEmpty(this.timeFormat)) {\n if (this.locale === 'en' || this.locale === 'en-US') {\n cldrTime = (getValue('timeFormats.short', getDefaultDateObject()));\n }\n else {\n cldrTime = (this.getCultureTimeObject(cldrData, '' + this.locale));\n }\n }\n else {\n cldrTime = this.timeFormat;\n }\n return cldrTime;\n };\n DateTimePicker.prototype.cldrDateTimeFormat = function () {\n var cldrTime;\n var culture = new Internationalization(this.locale);\n var dateFormat = culture.getDatePattern({ skeleton: 'yMd' });\n if (this.isNullOrEmpty(this.format)) {\n cldrTime = dateFormat + ' ' + this.getCldrFormat('time');\n }\n else {\n cldrTime = this.format;\n }\n return cldrTime;\n };\n DateTimePicker.prototype.getCldrFormat = function (type) {\n var cldrDateTime;\n if (this.locale === 'en' || this.locale === 'en-US') {\n cldrDateTime = (getValue('timeFormats.short', getDefaultDateObject()));\n }\n else {\n cldrDateTime = (this.getCultureTimeObject(cldrData, '' + this.locale));\n }\n return cldrDateTime;\n };\n DateTimePicker.prototype.isNullOrEmpty = function (value) {\n if (isNullOrUndefined(value) || (typeof value === 'string' && value.trim() === '')) {\n return true;\n }\n else {\n return false;\n }\n };\n DateTimePicker.prototype.getCultureTimeObject = function (ld, c) {\n return getValue('main.' + '' + this.locale + '.dates.calendars.gregorian.timeFormats.short', ld);\n };\n DateTimePicker.prototype.timeHandler = function (e) {\n if (e.currentTarget === this.timeIcon) {\n e.preventDefault();\n }\n if (this.enabled && !this.readonly) {\n if (this.isDatePopupOpen()) {\n _super.prototype.hide.call(this, e);\n }\n if (this.isTimePopupOpen()) {\n this.closePopup(e);\n }\n else {\n if (!Browser.isDevice) {\n this.inputElement.focus();\n }\n this.popupCreation('time', e);\n addClass([this.inputWrapper.container], [INPUTFOCUS]);\n }\n }\n };\n DateTimePicker.prototype.dateHandler = function (e) {\n if (e.currentTarget === this.inputWrapper.buttons[0]) {\n e.preventDefault();\n }\n if (this.enabled && !this.readonly) {\n if (this.isTimePopupOpen()) {\n this.closePopup(e);\n }\n if (!isNullOrUndefined(this.popupWrapper)) {\n this.popupCreation('date', e);\n }\n }\n };\n DateTimePicker.prototype.show = function (type, e) {\n if ((this.enabled && this.readonly) || !this.enabled) {\n return;\n }\n else {\n if (type === 'time' && !this.dateTimeWrapper) {\n if (this.isDatePopupOpen()) {\n this.hide(e);\n }\n this.popupCreation('time', e);\n }\n else if (!this.popupObj) {\n if (this.isTimePopupOpen()) {\n this.hide(e);\n }\n _super.prototype.show.call(this);\n this.popupCreation('date', e);\n }\n }\n };\n DateTimePicker.prototype.toggle = function (e) {\n if (this.isDatePopupOpen()) {\n _super.prototype.hide.call(this, e);\n this.show('time', null);\n }\n else if (this.isTimePopupOpen()) {\n this.hide(e);\n _super.prototype.show.call(this, null, e);\n this.popupCreation('date', null);\n }\n else {\n this.show(null, e);\n }\n };\n DateTimePicker.prototype.listCreation = function () {\n var value = isNullOrUndefined(this.value) ? this.inputElement.value !== '' ?\n this.globalize.parseDate(this.inputElement.value, { format: this.cldrDateTimeFormat(), type: 'datetime' }) :\n new Date() : this.value;\n this.valueWithMinutes = value;\n this.listWrapper = createElement('div', { className: CONTENT, attrs: { 'tabindex': '0' } });\n var min = this.startTime(value);\n var max = this.endTime(value);\n var listDetails = TimePickerBase.createListItems(this.createElement, min, max, this.globalize, this.cldrTimeFormat(), this.step);\n this.timeCollections = listDetails.collection;\n this.listTag = listDetails.list;\n attributes(this.listTag, { 'role': 'listbox', 'aria-hidden': 'false', 'id': this.element.id + '_options' });\n append([listDetails.list], this.listWrapper);\n this.wireTimeListEvents();\n var rippleModel = { duration: 300, selector: '.' + LISTCLASS };\n this.rippleFn = rippleEffect(this.listWrapper, rippleModel);\n this.liCollections = this.listWrapper.querySelectorAll('.' + LISTCLASS);\n };\n DateTimePicker.prototype.popupCreation = function (type, e) {\n if (type === 'date') {\n if (!this.readonly && this.popupWrapper) {\n addClass([this.popupWrapper], DATETIMEPOPUPWRAPPER);\n attributes(this.popupWrapper, { 'id': this.element.id + '_datepopup' });\n }\n }\n else {\n if (!this.readonly) {\n this.dateTimeWrapper = createElement('div', {\n className: ROOT + ' ' + POPUP,\n attrs: { 'id': this.element.id + '_timepopup', 'style': 'visibility:hidden ; display:block' }\n });\n if (!isNullOrUndefined(this.cssClass)) {\n this.dateTimeWrapper.classList.add(this.cssClass);\n }\n if (!isNullOrUndefined(this.step) && this.step > 0) {\n this.listCreation();\n append([this.listWrapper], this.dateTimeWrapper);\n }\n document.body.appendChild(this.dateTimeWrapper);\n this.addTimeSelection();\n this.renderPopup();\n this.setTimeScrollPosition();\n this.openPopup(e);\n this.popupObject.refreshPosition(this.inputElement);\n }\n }\n };\n DateTimePicker.prototype.openPopup = function (e) {\n this.preventArgs = {\n cancel: false,\n popup: this.popupObject,\n event: e || null\n };\n this.trigger('open', this.preventArgs);\n if (!this.preventArgs.cancel && !this.readonly) {\n var openAnimation = {\n name: 'FadeIn',\n duration: ANIMATIONDURATION,\n };\n if (this.zIndex === 1000) {\n this.popupObject.show(new Animation(openAnimation), this.element);\n }\n else {\n this.popupObject.show(new Animation(openAnimation), null);\n }\n addClass([this.inputWrapper.container], [ICONANIMATION]);\n attributes(this.inputElement, { 'aria-expanded': 'true' });\n EventHandler.add(document, 'mousedown touchstart', this.documentClickHandler, this);\n }\n };\n DateTimePicker.prototype.documentClickHandler = function (event) {\n if (!Browser.isDevice) {\n event.preventDefault();\n }\n var target = event.target;\n if (!(closest(target, '#' + (this.popupObject && this.popupObject.element.id))) && target !== this.inputElement\n && target !== this.timeIcon && target !== this.inputWrapper.container) {\n if (this.isTimePopupOpen()) {\n this.hide(event);\n }\n }\n else if (target !== this.inputElement) {\n if (!Browser.isDevice) {\n this.isPreventBlur = (Browser.isIE || Browser.info.name === 'edge') && (document.activeElement === this.inputElement);\n event.preventDefault();\n }\n }\n };\n DateTimePicker.prototype.isTimePopupOpen = function () {\n return (this.dateTimeWrapper && this.dateTimeWrapper.classList.contains('' + ROOT)) ? true : false;\n };\n DateTimePicker.prototype.isDatePopupOpen = function () {\n return (this.popupWrapper && this.popupWrapper.classList.contains('' + DATETIMEPOPUPWRAPPER)) ? true : false;\n };\n DateTimePicker.prototype.renderPopup = function () {\n var _this = this;\n this.containerStyle = this.inputWrapper.container.getBoundingClientRect();\n if (Browser.isDevice) {\n this.timeModal = createElement('div');\n this.timeModal.className = '' + ROOT + ' e-time-modal';\n document.body.className += ' ' + OVERFLOW;\n this.timeModal.style.display = 'block';\n document.body.appendChild(this.timeModal);\n }\n var offset = 4;\n this.popupObject = new Popup(this.dateTimeWrapper, {\n width: this.setPopupWidth(),\n zIndex: this.zIndex,\n targetType: 'container',\n collision: Browser.isDevice ? { X: 'fit', Y: 'fit' } : { X: 'flip', Y: 'flip' },\n relateTo: Browser.isDevice ? document.body : this.inputWrapper.container,\n position: Browser.isDevice ? { X: 'center', Y: 'center' } : { X: 'left', Y: 'bottom' },\n enableRtl: this.enableRtl,\n offsetY: offset,\n open: function () {\n _this.dateTimeWrapper.style.visibility = 'visible';\n addClass([_this.timeIcon], ACTIVE);\n if (!Browser.isDevice) {\n _this.inputEvent = new KeyboardEvents(_this.inputWrapper.container, {\n keyAction: _this.TimeKeyActionHandle.bind(_this), keyConfigs: _this.timekeyConfigure, eventName: 'keydown'\n });\n }\n }, close: function () {\n removeClass([_this.timeIcon], ACTIVE);\n _this.unWireTimeListEvents();\n _this.inputElement.setAttribute('aria-activedescendant', 'null');\n remove(_this.popupObject.element);\n _this.popupObject.destroy();\n _this.dateTimeWrapper.innerHTML = '';\n _this.listWrapper = _this.dateTimeWrapper = undefined;\n if (_this.inputEvent) {\n _this.inputEvent.destroy();\n }\n }\n });\n this.popupObject.element.style.maxHeight = POPUPDIMENSION;\n };\n DateTimePicker.prototype.setDimension = function (width) {\n if (typeof width === 'number') {\n width = formatUnit(width);\n }\n else if (typeof width === 'string') {\n width = width;\n }\n else {\n width = '100%';\n }\n return width;\n };\n DateTimePicker.prototype.setPopupWidth = function () {\n var width = this.setDimension(this.width);\n if (width.indexOf('%') > -1) {\n var inputWidth = this.containerStyle.width * parseFloat(width) / 100;\n width = inputWidth.toString() + 'px';\n }\n return width;\n };\n DateTimePicker.prototype.wireTimeListEvents = function () {\n EventHandler.add(this.listWrapper, 'click', this.onMouseClick, this);\n if (!Browser.isDevice) {\n EventHandler.add(this.listWrapper, 'mouseover', this.onMouseOver, this);\n EventHandler.add(this.listWrapper, 'mouseout', this.onMouseLeave, this);\n }\n };\n DateTimePicker.prototype.unWireTimeListEvents = function () {\n if (this.listWrapper) {\n EventHandler.remove(this.listWrapper, 'click', this.onMouseClick);\n EventHandler.remove(document, 'mousedown touchstart', this.documentClickHandler);\n if (!Browser.isDevice) {\n EventHandler.add(this.listWrapper, 'mouseover', this.onMouseOver, this);\n EventHandler.add(this.listWrapper, 'mouseout', this.onMouseLeave, this);\n }\n }\n };\n DateTimePicker.prototype.onMouseOver = function (event) {\n var currentLi = closest(event.target, '.' + LISTCLASS);\n this.setTimeHover(currentLi, HOVER);\n };\n DateTimePicker.prototype.onMouseLeave = function () {\n this.removeTimeHover(HOVER);\n };\n DateTimePicker.prototype.setTimeHover = function (li, className) {\n if (this.enabled && this.isValidLI(li) && !li.classList.contains(className)) {\n this.removeTimeHover(className);\n addClass([li], className);\n }\n };\n DateTimePicker.prototype.getPopupHeight = function () {\n var height = parseInt(POPUPDIMENSION, 10);\n var popupHeight = this.dateTimeWrapper.getBoundingClientRect().height;\n return popupHeight > height ? height : popupHeight;\n };\n DateTimePicker.prototype.changeEvent = function (e) {\n if (+this.previousDateTime !== +this.value) {\n _super.prototype.changeEvent.call(this, e);\n if (!Browser.isDevice) {\n this.inputElement.focus();\n }\n this.valueWithMinutes = this.value;\n this.setInputValue('date');\n this.previousDateTime = this.value && new Date(+this.value);\n }\n };\n DateTimePicker.prototype.updateValue = function (e) {\n this.setInputValue('time');\n if (+this.previousDateTime !== +this.value) {\n this.changedArgs = {\n value: this.value, event: e || null,\n isInteracted: !isNullOrUndefined(e),\n element: this.element\n };\n this.addTimeSelection();\n this.trigger('change', this.changedArgs);\n this.previousDateTime = this.value;\n }\n };\n DateTimePicker.prototype.setTimeScrollPosition = function () {\n var popupHeight = this.getPopupHeight();\n var popupElement;\n popupElement = this.selectedElement;\n if (!isNullOrUndefined(popupElement)) {\n var nextEle = popupElement.nextElementSibling;\n var height = nextEle ? nextEle.offsetTop : popupElement.offsetTop;\n var liHeight = popupElement.getBoundingClientRect().height;\n if ((height + popupElement.offsetTop) > popupHeight) {\n this.dateTimeWrapper.scrollTop = nextEle ? (height - (popupHeight / HALFPOSITION + liHeight / HALFPOSITION)) : height;\n }\n else {\n this.dateTimeWrapper.scrollTop = 0;\n }\n }\n };\n DateTimePicker.prototype.setInputValue = function (type) {\n if (type === 'date') {\n this.inputElement.value = this.previousElementValue = this.getFormattedValue(this.getFullDateTime());\n this.setProperties({ value: this.getFullDateTime() }, true);\n }\n else {\n var tempVal = this.getFormattedValue(new Date(this.timeCollections[this.activeIndex]));\n Input.setValue(tempVal, this.inputElement, this.floatLabelType, this.showClearButton);\n this.previousElementValue = this.inputElement.value;\n this.setProperties({ value: new Date(this.timeCollections[this.activeIndex]) }, true);\n }\n };\n DateTimePicker.prototype.getFullDateTime = function () {\n var value = null;\n if (this.isDateObject(this.valueWithMinutes)) {\n value = this.combineDateTime(this.valueWithMinutes);\n }\n else {\n value = this.previousDate;\n }\n return this.validateMinMaxRange(value);\n };\n DateTimePicker.prototype.combineDateTime = function (value) {\n if (this.isDateObject(value)) {\n var day = this.previousDate.getDate();\n var month = this.previousDate.getMonth();\n var year = this.previousDate.getFullYear();\n var hour = value.getHours();\n var minutes = value.getMinutes();\n var seconds = value.getSeconds();\n return new Date(year, month, day, hour, minutes, seconds);\n }\n else {\n return this.previousDate;\n }\n };\n DateTimePicker.prototype.onMouseClick = function (event) {\n var target = event.target;\n var li = this.selectedElement = closest(target, '.' + LISTCLASS);\n if (li && li.classList.contains(LISTCLASS)) {\n this.timeValue = li.getAttribute('data-value');\n this.hide(event);\n }\n this.setSelection(li, event);\n };\n DateTimePicker.prototype.setSelection = function (li, event) {\n if (this.isValidLI(li) && !li.classList.contains(ACTIVE)) {\n var value = li.getAttribute('data-value');\n this.selectedElement = li;\n var index = Array.prototype.slice.call(this.liCollections).indexOf(li);\n this.activeIndex = index;\n this.valueWithMinutes = new Date(this.timeCollections[this.activeIndex]);\n addClass([this.selectedElement], ACTIVE);\n this.selectedElement.setAttribute('aria-selected', 'true');\n this.updateValue(event);\n }\n };\n DateTimePicker.prototype.setTimeActiveClass = function () {\n var collections = isNullOrUndefined(this.dateTimeWrapper) ? this.listWrapper : this.dateTimeWrapper;\n if (!isNullOrUndefined(collections)) {\n var items = collections.querySelectorAll('.' + LISTCLASS);\n if (items.length) {\n for (var i = 0; i < items.length; i++) {\n if (this.timeCollections[i] === +(this.valueWithMinutes)) {\n items[i].setAttribute('aria-selected', 'true');\n this.selectedElement = items[i];\n this.activeIndex = i;\n this.setTimeActiveDescendant();\n break;\n }\n }\n }\n }\n };\n DateTimePicker.prototype.setTimeActiveDescendant = function () {\n if (!isNullOrUndefined(this.selectedElement)) {\n attributes(this.inputElement, { 'aria-activedescendant': this.selectedElement.getAttribute('id') });\n }\n else {\n attributes(this.inputElement, { 'aria-activedescendant': 'null' });\n }\n };\n DateTimePicker.prototype.addTimeSelection = function () {\n this.selectedElement = null;\n this.removeTimeSelection();\n this.setTimeActiveClass();\n if (!isNullOrUndefined(this.selectedElement)) {\n addClass([this.selectedElement], ACTIVE);\n this.selectedElement.setAttribute('aria-selected', 'true');\n }\n };\n DateTimePicker.prototype.removeTimeSelection = function () {\n this.removeTimeHover(HOVER);\n if (!isNullOrUndefined(this.dateTimeWrapper)) {\n var items = this.dateTimeWrapper.querySelectorAll('.' + ACTIVE);\n if (items.length) {\n removeClass(items, ACTIVE);\n items[0].removeAttribute('aria-selected');\n }\n }\n };\n DateTimePicker.prototype.removeTimeHover = function (className) {\n var hoveredItem = this.getTimeHoverItem(className);\n if (hoveredItem && hoveredItem.length) {\n removeClass(hoveredItem, className);\n }\n };\n DateTimePicker.prototype.getTimeHoverItem = function (className) {\n var collections = isNullOrUndefined(this.dateTimeWrapper) ? this.listWrapper : this.dateTimeWrapper;\n var hoveredItem;\n if (!isNullOrUndefined(collections)) {\n hoveredItem = collections.querySelectorAll('.' + className);\n }\n return hoveredItem;\n };\n DateTimePicker.prototype.isValidLI = function (li) {\n return (li && li.classList.contains(LISTCLASS) && !li.classList.contains(DISABLED));\n };\n DateTimePicker.prototype.calculateStartEnd = function (value, range, method) {\n var day = value.getDate();\n var month = value.getMonth();\n var year = value.getFullYear();\n var hours = value.getHours();\n var minutes = value.getMinutes();\n var seconds = value.getSeconds();\n var milliseconds = value.getMilliseconds();\n if (range) {\n if (method === 'starttime') {\n return new Date(year, month, day, 0, 0, 0);\n }\n else {\n return new Date(year, month, day, 23, 59, 59);\n }\n }\n else {\n return new Date(year, month, day, hours, minutes, seconds, milliseconds);\n }\n };\n DateTimePicker.prototype.startTime = function (date) {\n var tempStartValue;\n var start;\n var tempMin = this.min;\n var value;\n value = date === null ? new Date() : date;\n if ((+value.getDate() === +tempMin.getDate() && +value.getMonth() === +tempMin.getMonth() &&\n +value.getFullYear() === +tempMin.getFullYear()) || ((+new Date(value.getFullYear(), value.getMonth(), value.getDate())) <=\n +new Date(tempMin.getFullYear(), tempMin.getMonth(), tempMin.getDate()))) {\n start = false;\n tempStartValue = this.min;\n }\n else if (+value < +this.max && +value > +this.min) {\n start = true;\n tempStartValue = value;\n }\n else if (+value >= +this.max) {\n start = true;\n tempStartValue = this.max;\n }\n return this.calculateStartEnd(tempStartValue, start, 'starttime');\n };\n DateTimePicker.prototype.endTime = function (date) {\n var tempEndValue;\n var end;\n var tempMax = this.max;\n var value;\n value = date === null ? new Date() : date;\n if ((+value.getDate() === +tempMax.getDate() && +value.getMonth() === +tempMax.getMonth() &&\n +value.getFullYear() === +tempMax.getFullYear()) || (+new Date(value.getUTCFullYear(), value.getMonth(), value.getDate()) >=\n +new Date(tempMax.getFullYear(), tempMax.getMonth(), tempMax.getDate()))) {\n end = false;\n tempEndValue = this.max;\n }\n else if (+value < +this.max && +value > +this.min) {\n end = true;\n tempEndValue = value;\n }\n else if (+value <= +this.min) {\n end = true;\n tempEndValue = this.min;\n }\n return this.calculateStartEnd(tempEndValue, end, 'endtime');\n };\n DateTimePicker.prototype.hide = function (e) {\n if (this.popupObj || this.dateTimeWrapper) {\n this.preventArgs = {\n cancel: false,\n popup: this.popupObj || this.popupObject,\n event: e || null\n };\n if (isNullOrUndefined(this.popupObj)) {\n this.trigger('close', this.preventArgs);\n }\n if (!this.preventArgs.cancel) {\n if (this.isDatePopupOpen()) {\n _super.prototype.hide.call(this, e);\n }\n else if (this.isTimePopupOpen()) {\n this.closePopup(e);\n removeClass([document.body], OVERFLOW);\n if (Browser.isDevice && this.timeModal) {\n this.timeModal.style.display = 'none';\n this.timeModal.outerHTML = '';\n this.timeModal = null;\n }\n this.setTimeActiveDescendant();\n }\n }\n }\n };\n DateTimePicker.prototype.closePopup = function (e) {\n if (this.isTimePopupOpen() && this.popupObject) {\n var animModel = {\n name: 'FadeOut',\n duration: ANIMATIONDURATION,\n delay: 0\n };\n this.popupObject.hide(new Animation(animModel));\n this.inputWrapper.container.classList.remove(ICONANIMATION);\n attributes(this.inputElement, { 'aria-expanded': 'false' });\n EventHandler.remove(document, 'mousedown touchstart', this.documentClickHandler);\n }\n if (Browser.isDevice) {\n removeClass([this.inputWrapper.container], INPUTFOCUS);\n }\n };\n DateTimePicker.prototype.preRender = function () {\n _super.prototype.preRender.call(this);\n };\n ;\n DateTimePicker.prototype.getProperty = function (date, val) {\n if (val === 'min') {\n this.setProperties({ min: this.validateValue(date.min) }, true);\n }\n else {\n this.setProperties({ max: this.validateValue(date.max) }, true);\n }\n };\n DateTimePicker.prototype.checkAttributes = function () {\n var attributes = ['style', 'name', 'step', 'disabled', 'readonly', 'value', 'min', 'max', 'placeholder', 'type'];\n var value;\n for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {\n var prop = attributes_1[_i];\n if (!isNullOrUndefined(this.inputElement.getAttribute(prop))) {\n switch (prop) {\n case 'name':\n this.inputElement.setAttribute('name', this.inputElement.getAttribute(prop));\n break;\n case 'step':\n this.step = parseInt(this.inputElement.getAttribute(prop), 10);\n break;\n case 'readonly':\n var readonly = !isNullOrUndefined(this.inputElement.getAttribute(prop));\n this.setProperties({ readonly: readonly }, true);\n break;\n case 'placeholder':\n this.placeholder = this.inputElement.getAttribute(prop);\n break;\n case 'min':\n value = new Date(this.inputElement.getAttribute(prop));\n if (!this.isNullOrEmpty(value) && !isNaN(+value)) {\n this.setProperties({ min: value }, true);\n }\n break;\n case 'disabled':\n var enabled = isNullOrUndefined(this.inputElement.getAttribute(prop));\n this.setProperties({ enabled: enabled }, true);\n break;\n case 'max':\n value = new Date(this.inputElement.getAttribute(prop));\n if (!this.isNullOrEmpty(value) && !isNaN(+value)) {\n this.setProperties({ max: value }, true);\n }\n break;\n }\n }\n }\n };\n DateTimePicker.prototype.getTimeActiveElement = function () {\n if (!isNullOrUndefined(this.dateTimeWrapper)) {\n return this.dateTimeWrapper.querySelectorAll('.' + ACTIVE);\n }\n else {\n return null;\n }\n };\n DateTimePicker.prototype.createDateObj = function (val) {\n return val instanceof Date ? val : null;\n };\n DateTimePicker.prototype.getDateObject = function (text) {\n if (!this.isNullOrEmpty(text)) {\n var dateValue = this.createDateObj(text);\n var value = this.valueWithMinutes;\n var status_1 = !isNullOrUndefined(value);\n if (this.checkDateValue(dateValue)) {\n var date = status_1 ? value.getDate() : DAY;\n var month = status_1 ? value.getMonth() : MONTH;\n var year = status_1 ? value.getFullYear() : YEAR;\n var hour = status_1 ? value.getHours() : HOUR;\n var minute = status_1 ? value.getMinutes() : MINUTE;\n var second = status_1 ? value.getSeconds() : SECOND;\n var millisecond = status_1 ? value.getMilliseconds() : MILLISECOND;\n return new Date(year, month, date, hour, minute, second, millisecond);\n }\n }\n return null;\n };\n DateTimePicker.prototype.findNextTimeElement = function (event) {\n var textVal = (this.inputElement).value;\n var value = isNullOrUndefined(this.valueWithMinutes) ? this.createDateObj(textVal) :\n this.getDateObject(this.valueWithMinutes);\n var dateTimeVal = null;\n var listCount = this.liCollections.length;\n if (!isNullOrUndefined(this.checkDateValue(value)) || !isNullOrUndefined(this.activeIndex)) {\n if (event.action === 'home') {\n dateTimeVal = +(this.createDateObj(new Date(this.timeCollections[0])));\n this.activeIndex = 0;\n }\n else if (event.action === 'end') {\n dateTimeVal = +(this.createDateObj(new Date(this.timeCollections[this.timeCollections.length - 1])));\n this.activeIndex = this.timeCollections.length - 1;\n }\n else {\n if (event.action === 'down') {\n for (var i = 0; i < listCount; i++) {\n if (+value < this.timeCollections[i]) {\n dateTimeVal = +(this.createDateObj(new Date(this.timeCollections[i])));\n this.activeIndex = i;\n break;\n }\n }\n }\n else {\n for (var i = listCount - 1; i >= 0; i--) {\n if (+value > this.timeCollections[i]) {\n dateTimeVal = +(this.createDateObj(new Date(this.timeCollections[i])));\n this.activeIndex = i;\n break;\n }\n }\n }\n }\n this.selectedElement = this.liCollections[this.activeIndex];\n this.timeElementValue(isNullOrUndefined(dateTimeVal) ? null : new Date(dateTimeVal));\n }\n };\n DateTimePicker.prototype.setTimeValue = function (date, value) {\n var time;\n var val = this.validateMinMaxRange(value);\n var newval = this.createDateObj(val);\n if (this.getFormattedValue(newval) !== (!isNullOrUndefined(this.value) ? this.getFormattedValue(this.value) : null)) {\n this.valueWithMinutes = isNullOrUndefined(newval) ? null : newval;\n time = new Date(+this.valueWithMinutes);\n }\n else {\n if (this.strictMode) {\n //for strict mode case, when value not present within a range. Reset the nearest range value.\n date = newval;\n }\n this.valueWithMinutes = this.checkDateValue(date);\n time = new Date(+this.valueWithMinutes);\n }\n var dateString = this.globalize.formatDate(time, {\n format: !isNullOrUndefined(this.format) ? this.format : this.cldrDateTimeFormat(), type: 'dateTime', skeleton: 'yMd'\n });\n if (!this.strictMode && isNullOrUndefined(time)) {\n Input.setValue(dateString, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n else {\n Input.setValue(dateString, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n return time;\n };\n DateTimePicker.prototype.timeElementValue = function (value) {\n if (!isNullOrUndefined(this.checkDateValue(value)) && !this.isNullOrEmpty(value)) {\n var date = value instanceof Date ? value : this.getDateObject(value);\n return this.setTimeValue(date, value);\n }\n return null;\n };\n DateTimePicker.prototype.timeKeyHandler = function (event) {\n if (isNullOrUndefined(this.step) || this.step <= 0) {\n return;\n }\n var listCount = this.timeCollections.length;\n if (isNullOrUndefined(this.getTimeActiveElement()) || this.getTimeActiveElement().length === 0) {\n if (this.liCollections.length > 0) {\n if (isNullOrUndefined(this.value) && isNullOrUndefined(this.activeIndex)) {\n this.activeIndex = 0;\n this.selectedElement = this.liCollections[0];\n this.timeElementValue(new Date(this.timeCollections[0]));\n }\n else {\n this.findNextTimeElement(event);\n }\n }\n }\n else {\n var nextItemValue = void 0;\n if ((event.keyCode >= 37) && (event.keyCode <= 40)) {\n var index = (event.keyCode === 40 || event.keyCode === 39) ? ++this.activeIndex : --this.activeIndex;\n this.activeIndex = index = this.activeIndex === (listCount) ? 0 : this.activeIndex;\n this.activeIndex = index = this.activeIndex < 0 ? (listCount - 1) : this.activeIndex;\n nextItemValue = isNullOrUndefined(this.timeCollections[index]) ? this.timeCollections[0] : this.timeCollections[index];\n }\n else if (event.action === 'home') {\n this.activeIndex = 0;\n nextItemValue = this.timeCollections[0];\n }\n else if (event.action === 'end') {\n this.activeIndex = listCount - 1;\n nextItemValue = this.timeCollections[listCount - 1];\n }\n this.selectedElement = this.liCollections[this.activeIndex];\n this.timeElementValue(new Date(nextItemValue));\n }\n this.isNavigate = true;\n this.setTimeHover(this.selectedElement, NAVIGATION);\n this.setTimeActiveDescendant();\n if (this.isTimePopupOpen() && this.selectedElement !== null && (!event || event.type !== 'click')) {\n this.setTimeScrollPosition();\n }\n };\n DateTimePicker.prototype.TimeKeyActionHandle = function (event) {\n if (this.enabled) {\n if (event.action !== 'right' && event.action !== 'left' && event.action !== 'tab') {\n event.preventDefault();\n }\n switch (event.action) {\n case 'up':\n case 'down':\n case 'home':\n case 'end':\n this.timeKeyHandler(event);\n break;\n case 'enter':\n if (this.isNavigate) {\n this.selectedElement = this.liCollections[this.activeIndex];\n this.valueWithMinutes = new Date(this.timeCollections[this.activeIndex]);\n this.setInputValue('time');\n if (+this.previousDateTime !== +this.value) {\n this.changedArgs.value = this.value;\n this.addTimeSelection();\n this.previousDateTime = this.value;\n }\n }\n else {\n this.updateValue(event);\n }\n this.hide(event);\n addClass([this.inputWrapper.container], INPUTFOCUS);\n this.isNavigate = false;\n break;\n case 'escape':\n this.hide(event);\n break;\n default:\n this.isNavigate = false;\n break;\n }\n }\n };\n DateTimePicker.prototype.inputKeyAction = function (event) {\n switch (event.action) {\n case 'altDownArrow':\n this.strictModeUpdate();\n this.updateInput();\n this.toggle(event);\n break;\n }\n };\n DateTimePicker.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'value':\n var options = { format: this.cldrDateTimeFormat(), type: 'dateTime', skeleton: 'yMd' };\n if (typeof newProp.value === 'string') {\n this.setProperties({ value: this.checkDateValue(new Date('' + newProp.value)) }, true);\n newProp.value = this.checkDateValue(new Date('' + newProp.value));\n }\n newProp.value = this.validateValue(newProp.value);\n Input.setValue(this.getFormattedValue(newProp.value), this.inputElement, this.floatLabelType, this.showClearButton);\n this.valueWithMinutes = newProp.value;\n this.setProperties({ value: newProp.value }, true);\n this.previousDateTime = new Date(this.inputElement.value);\n this.updateInput();\n this.changeTrigger(null);\n break;\n case 'min':\n case 'max':\n this.getProperty(newProp, prop);\n this.updateInput();\n break;\n case 'enableRtl':\n Input.setEnableRtl(this.enableRtl, [this.inputWrapper.container]);\n break;\n case 'cssClass':\n Input.setCssClass(newProp.cssClass, [this.inputWrapper.container]);\n if (this.dateTimeWrapper) {\n addClass([this.dateTimeWrapper], [newProp.cssClass]);\n }\n break;\n case 'locale':\n this.globalize = new Internationalization(this.locale);\n this.l10n.setLocale(this.locale);\n this.setProperties({ placeholder: this.l10n.getConstant('placeholder') }, true);\n Input.setPlaceholder(this.l10n.getConstant('placeholder'), this.inputElement);\n this.dateTimeFormat = this.cldrDateTimeFormat();\n _super.prototype.updateInput.call(this);\n break;\n case 'format':\n this.setProperties({ format: newProp.format }, true);\n this.setValue();\n break;\n case 'placeholder':\n Input.setPlaceholder(newProp.placeholder, this.inputElement);\n this.inputElement.setAttribute('aria-placeholder', newProp.placeholder);\n break;\n case 'enabled':\n Input.setEnabled(this.enabled, this.inputElement);\n this.bindEvents();\n break;\n case 'strictMode':\n this.updateInput();\n break;\n case 'width':\n this.setWidth(newProp.width);\n break;\n case 'readonly':\n Input.setReadonly(this.readonly, this.inputElement);\n break;\n case 'floatLabelType':\n this.floatLabelType = newProp.floatLabelType;\n Input.removeFloating(this.inputWrapper);\n Input.addFloating(this.inputElement, this.floatLabelType, this.placeholder);\n break;\n default:\n _super.prototype.onPropertyChanged.call(this, newProp, oldProp);\n break;\n }\n this.hide(null);\n }\n };\n /**\n * To get component name.\n * @private\n */\n DateTimePicker.prototype.getModuleName = function () {\n return 'datetimepicker';\n };\n __decorate([\n Property(null)\n ], DateTimePicker.prototype, \"timeFormat\", void 0);\n __decorate([\n Property(30)\n ], DateTimePicker.prototype, \"step\", void 0);\n __decorate([\n Property(1000)\n ], DateTimePicker.prototype, \"zIndex\", void 0);\n __decorate([\n Property(false)\n ], DateTimePicker.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(true)\n ], DateTimePicker.prototype, \"showClearButton\", void 0);\n __decorate([\n Property(null)\n ], DateTimePicker.prototype, \"placeholder\", void 0);\n __decorate([\n Property(false)\n ], DateTimePicker.prototype, \"strictMode\", void 0);\n __decorate([\n Event()\n ], DateTimePicker.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], DateTimePicker.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], DateTimePicker.prototype, \"blur\", void 0);\n __decorate([\n Event()\n ], DateTimePicker.prototype, \"focus\", void 0);\n __decorate([\n Event()\n ], DateTimePicker.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], DateTimePicker.prototype, \"destroyed\", void 0);\n DateTimePicker = __decorate([\n NotifyPropertyChanges\n ], DateTimePicker);\n return DateTimePicker;\n}(DatePicker));\nexport { DateTimePicker };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty, Complex } from '@syncfusion/ej2-base';\nimport { Theme } from '../model/theme';\n/**\n * Defines the appearance of the connectors\n */\nvar Connector = /** @class */ (function (_super) {\n __extends(Connector, _super);\n function Connector() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Line')\n ], Connector.prototype, \"type\", void 0);\n __decorate([\n Property(null)\n ], Connector.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], Connector.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], Connector.prototype, \"length\", void 0);\n __decorate([\n Property('')\n ], Connector.prototype, \"dashArray\", void 0);\n return Connector;\n}(ChildProperty));\nexport { Connector };\n/**\n * Configures the fonts in charts.\n */\nvar Font = /** @class */ (function (_super) {\n __extends(Font, _super);\n function Font() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('16px')\n ], Font.prototype, \"size\", void 0);\n __decorate([\n Property('')\n ], Font.prototype, \"color\", void 0);\n __decorate([\n Property('Segoe UI')\n ], Font.prototype, \"fontFamily\", void 0);\n __decorate([\n Property('Normal')\n ], Font.prototype, \"fontWeight\", void 0);\n __decorate([\n Property('Normal')\n ], Font.prototype, \"fontStyle\", void 0);\n __decorate([\n Property(1)\n ], Font.prototype, \"opacity\", void 0);\n __decorate([\n Property('Center')\n ], Font.prototype, \"textAlignment\", void 0);\n __decorate([\n Property('Trim')\n ], Font.prototype, \"textOverflow\", void 0);\n return Font;\n}(ChildProperty));\nexport { Font };\n/**\n * Configures the borders in the chart.\n */\nvar Border = /** @class */ (function (_super) {\n __extends(Border, _super);\n function Border() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Border.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], Border.prototype, \"width\", void 0);\n return Border;\n}(ChildProperty));\nexport { Border };\n/**\n * Configures the chart area.\n */\nvar ChartArea = /** @class */ (function (_super) {\n __extends(ChartArea, _super);\n function ChartArea() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({}, Border)\n ], ChartArea.prototype, \"border\", void 0);\n __decorate([\n Property('transparent')\n ], ChartArea.prototype, \"background\", void 0);\n __decorate([\n Property(1)\n ], ChartArea.prototype, \"opacity\", void 0);\n return ChartArea;\n}(ChildProperty));\nexport { ChartArea };\n/**\n * Configures the chart margins.\n */\nvar Margin = /** @class */ (function (_super) {\n __extends(Margin, _super);\n function Margin() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(10)\n ], Margin.prototype, \"left\", void 0);\n __decorate([\n Property(10)\n ], Margin.prototype, \"right\", void 0);\n __decorate([\n Property(10)\n ], Margin.prototype, \"top\", void 0);\n __decorate([\n Property(10)\n ], Margin.prototype, \"bottom\", void 0);\n return Margin;\n}(ChildProperty));\nexport { Margin };\n/**\n * Configures the animation behavior for chart series.\n */\nvar Animation = /** @class */ (function (_super) {\n __extends(Animation, _super);\n function Animation() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], Animation.prototype, \"enable\", void 0);\n __decorate([\n Property(1000)\n ], Animation.prototype, \"duration\", void 0);\n __decorate([\n Property(0)\n ], Animation.prototype, \"delay\", void 0);\n return Animation;\n}(ChildProperty));\nexport { Animation };\n/** @private */\nvar Indexes = /** @class */ (function (_super) {\n __extends(Indexes, _super);\n function Indexes() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], Indexes.prototype, \"series\", void 0);\n __decorate([\n Property(0)\n ], Indexes.prototype, \"point\", void 0);\n return Indexes;\n}(ChildProperty));\nexport { Indexes };\n/**\n * Column series rounded corner options\n */\nvar CornerRadius = /** @class */ (function (_super) {\n __extends(CornerRadius, _super);\n function CornerRadius() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], CornerRadius.prototype, \"topLeft\", void 0);\n __decorate([\n Property(0)\n ], CornerRadius.prototype, \"topRight\", void 0);\n __decorate([\n Property(0)\n ], CornerRadius.prototype, \"bottomLeft\", void 0);\n __decorate([\n Property(0)\n ], CornerRadius.prototype, \"bottomRight\", void 0);\n return CornerRadius;\n}(ChildProperty));\nexport { CornerRadius };\n/**\n * @private\n */\nvar Index = /** @class */ (function () {\n function Index(seriesIndex, pointIndex) {\n this.series = seriesIndex;\n this.point = pointIndex;\n }\n return Index;\n}());\nexport { Index };\n/**\n * Configures the Empty Points of series\n */\nvar EmptyPointSettings = /** @class */ (function (_super) {\n __extends(EmptyPointSettings, _super);\n function EmptyPointSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], EmptyPointSettings.prototype, \"fill\", void 0);\n __decorate([\n Complex({ color: 'transparent', width: 0 }, Border)\n ], EmptyPointSettings.prototype, \"border\", void 0);\n __decorate([\n Property('Gap')\n ], EmptyPointSettings.prototype, \"mode\", void 0);\n return EmptyPointSettings;\n}(ChildProperty));\nexport { EmptyPointSettings };\n/**\n * Configures the ToolTips in the chart.\n */\nvar TooltipSettings = /** @class */ (function (_super) {\n __extends(TooltipSettings, _super);\n function TooltipSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], TooltipSettings.prototype, \"enable\", void 0);\n __decorate([\n Property(false)\n ], TooltipSettings.prototype, \"shared\", void 0);\n __decorate([\n Property(null)\n ], TooltipSettings.prototype, \"fill\", void 0);\n __decorate([\n Property(null)\n ], TooltipSettings.prototype, \"header\", void 0);\n __decorate([\n Property(0.75)\n ], TooltipSettings.prototype, \"opacity\", void 0);\n __decorate([\n Complex(Theme.tooltipLabelFont, Font)\n ], TooltipSettings.prototype, \"textStyle\", void 0);\n __decorate([\n Property(null)\n ], TooltipSettings.prototype, \"format\", void 0);\n __decorate([\n Property(null)\n ], TooltipSettings.prototype, \"template\", void 0);\n __decorate([\n Property(true)\n ], TooltipSettings.prototype, \"enableAnimation\", void 0);\n __decorate([\n Complex({ color: '#cccccc', width: 0.5 }, Border)\n ], TooltipSettings.prototype, \"border\", void 0);\n return TooltipSettings;\n}(ChildProperty));\nexport { TooltipSettings };\n","/**\n * Numeric Range.\n * @private\n */\nvar DoubleRange = /** @class */ (function () {\n function DoubleRange(start, end) {\n /*\n if (!isNaN(start) && !isNaN(end)) {\n this.mIsEmpty = true;\n } else {\n this.mIsEmpty = false;\n }*/\n if (start < end) {\n this.mStart = start;\n this.mEnd = end;\n }\n else {\n this.mStart = end;\n this.mEnd = start;\n }\n }\n Object.defineProperty(DoubleRange.prototype, \"start\", {\n //private mIsEmpty: boolean;\n /** @private */\n get: function () {\n return this.mStart;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DoubleRange.prototype, \"end\", {\n /** @private */\n get: function () {\n return this.mEnd;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DoubleRange.prototype, \"delta\", {\n /*\n get isEmpty(): boolean {\n return this.mIsEmpty;\n }*/\n /** @private */\n get: function () {\n return (this.mEnd - this.mStart);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DoubleRange.prototype, \"median\", {\n /** @private */\n get: function () {\n return this.mStart + (this.mEnd - this.mStart) / 2;\n },\n enumerable: true,\n configurable: true\n });\n return DoubleRange;\n}());\nexport { DoubleRange };\n","import { getMinPointsDelta, getActualDesiredIntervalsCount, setRange, triggerLabelRender } from '../../common/utils/helper';\nimport { DoubleRange } from '../utils/double-range';\nimport { withIn, logBase } from '../../common/utils/helper';\nimport { isNullOrUndefined, extend, getValue } from '@syncfusion/ej2-base';\n/**\n * Numeric module is used to render numeric axis.\n */\nvar Double = /** @class */ (function () {\n /**\n * Constructor for the dateTime module.\n * @private\n */\n function Double(chart) {\n this.chart = chart;\n }\n /**\n * Numeric Nice Interval for the axis.\n * @private\n */\n Double.prototype.calculateNumericNiceInterval = function (axis, delta, size) {\n var actualDesiredIntervalsCount = getActualDesiredIntervalsCount(size, axis);\n var niceInterval = delta / actualDesiredIntervalsCount;\n if (!isNullOrUndefined(axis.desiredIntervals)) {\n return niceInterval;\n }\n var minInterval = Math.pow(10, Math.floor(logBase(niceInterval, 10)));\n for (var _i = 0, _a = axis.intervalDivs; _i < _a.length; _i++) {\n var interval = _a[_i];\n var currentInterval = minInterval * interval;\n if (actualDesiredIntervalsCount < (delta / currentInterval)) {\n break;\n }\n niceInterval = currentInterval;\n }\n return niceInterval;\n };\n /**\n * Actual Range for the axis.\n * @private\n */\n Double.prototype.getActualRange = function (axis, size) {\n this.initializeDoubleRange(axis);\n axis.actualRange.interval = axis.interval || this.calculateNumericNiceInterval(axis, axis.doubleRange.delta, size);\n axis.actualRange.min = axis.doubleRange.start;\n axis.actualRange.max = axis.doubleRange.end;\n };\n /**\n * Range for the axis.\n * @private\n */\n Double.prototype.initializeDoubleRange = function (axis) {\n //Axis Min\n if (axis.minimum !== null) {\n this.min = axis.minimum;\n }\n else if (this.min === null || this.min === Number.POSITIVE_INFINITY) {\n this.min = 0;\n }\n // Axis Max\n if (axis.maximum !== null) {\n this.max = axis.maximum;\n }\n else if (this.max === null || this.max === Number.NEGATIVE_INFINITY) {\n this.max = 5;\n }\n if (this.min === this.max) {\n this.max = axis.valueType.indexOf('Category') > -1 ? this.max : this.min + 1;\n }\n axis.doubleRange = new DoubleRange(this.min, this.max);\n axis.actualRange = {};\n };\n /**\n * The function to calculate the range and labels for the axis.\n * @return {void}\n * @private\n */\n Double.prototype.calculateRangeAndInterval = function (size, axis) {\n this.calculateRange(axis, size);\n this.getActualRange(axis, size);\n this.applyRangePadding(axis, size);\n this.calculateVisibleLabels(axis, this.chart);\n };\n /**\n * Calculate Range for the axis.\n * @private\n */\n Double.prototype.calculateRange = function (axis, size) {\n /*! Generate axis range */\n var series;\n this.min = null;\n this.max = null;\n if (!setRange(axis)) {\n for (var _i = 0, _a = axis.series; _i < _a.length; _i++) {\n var series_1 = _a[_i];\n if (!series_1.visible) {\n continue;\n }\n this.paddingInterval = 0;\n if (((series_1.type.indexOf('Column') > -1 || series_1.type.indexOf('Histogram') > -1) && axis.orientation === 'Horizontal')\n || (series_1.type.indexOf('Bar') > -1 && axis.orientation === 'Vertical')) {\n if ((series_1.xAxis.valueType === 'Double' || series_1.xAxis.valueType === 'DateTime')\n && series_1.xAxis.rangePadding === 'Auto') {\n this.paddingInterval = getMinPointsDelta(series_1.xAxis, axis.series) / 2;\n }\n }\n //For xRange\n if (axis.orientation === 'Horizontal') {\n if (this.chart.requireInvertedAxis) {\n this.findMinMax(series_1.yMin, series_1.yMax);\n }\n else {\n this.findMinMax(series_1.xMin - this.paddingInterval, series_1.xMax + this.paddingInterval);\n }\n }\n // For yRange\n if (axis.orientation === 'Vertical') {\n if (this.chart.requireInvertedAxis) {\n this.findMinMax(series_1.xMin - this.paddingInterval, series_1.xMax + this.paddingInterval);\n }\n else {\n this.findMinMax(series_1.yMin, series_1.yMax);\n }\n }\n }\n }\n };\n Double.prototype.findMinMax = function (min, max) {\n if (this.min === null || this.min > min) {\n this.min = min;\n }\n if (this.max === null || this.max < max) {\n this.max = max;\n }\n };\n /**\n * Apply padding for the range.\n * @private\n */\n Double.prototype.applyRangePadding = function (axis, size) {\n var range;\n var start = axis.actualRange.min;\n var end = axis.actualRange.max;\n if (!setRange(axis)) {\n var interval = axis.actualRange.interval;\n var padding = axis.getRangePadding(this.chart);\n if (padding === 'Additional' || padding === 'Round') {\n this.findAdditional(axis, start, end, interval);\n }\n else if (padding === 'Normal') {\n this.findNormal(axis, start, end, interval, size);\n }\n else {\n this.updateActualRange(axis, start, end, interval);\n }\n }\n axis.actualRange.delta = axis.actualRange.max - axis.actualRange.min;\n this.calculateVisibleRange(size, axis);\n };\n Double.prototype.updateActualRange = function (axis, minimum, maximum, interval) {\n axis.actualRange.min = axis.minimum != null ? axis.minimum : minimum;\n axis.actualRange.max = axis.maximum != null ? axis.maximum : maximum;\n axis.actualRange.interval = axis.interval != null ? axis.interval : interval;\n };\n Double.prototype.findAdditional = function (axis, start, end, interval) {\n var minimum;\n var maximum;\n minimum = Math.floor(start / interval) * interval;\n maximum = Math.ceil(end / interval) * interval;\n if (axis.rangePadding === 'Additional') {\n minimum -= interval;\n maximum += interval;\n }\n this.updateActualRange(axis, minimum, maximum, interval);\n };\n Double.prototype.findNormal = function (axis, start, end, interval, size) {\n var remaining;\n var minimum;\n var maximum;\n var startValue = start;\n if (start < 0) {\n startValue = 0;\n minimum = start + (start / 20);\n remaining = interval + (minimum % interval);\n if ((0.365 * interval) >= remaining) {\n minimum -= interval;\n }\n if (minimum % interval < 0) {\n minimum = (minimum - interval) - (minimum % interval);\n }\n }\n else {\n minimum = start < ((5.0 / 6.0) * end) ? 0 : (start - (end - start) / 2);\n if (minimum % interval > 0) {\n minimum -= (minimum % interval);\n }\n }\n maximum = (end > 0) ? (end + (end - startValue) / 20) : (end - (end - startValue) / 20);\n remaining = interval - (maximum % interval);\n if ((0.365 * interval) >= remaining) {\n maximum += interval;\n }\n if (maximum % interval > 0) {\n maximum = (maximum + interval) - (maximum % interval);\n }\n axis.doubleRange = new DoubleRange(minimum, maximum);\n if (minimum === 0) {\n interval = this.calculateNumericNiceInterval(axis, axis.doubleRange.delta, size);\n maximum = Math.ceil(maximum / interval) * interval;\n }\n this.updateActualRange(axis, minimum, maximum, interval);\n };\n /**\n * Calculate visible range for axis.\n * @private\n */\n Double.prototype.calculateVisibleRange = function (size, axis) {\n axis.visibleRange = {\n max: axis.actualRange.max, min: axis.actualRange.min,\n delta: axis.actualRange.delta, interval: axis.actualRange.interval\n };\n if (axis.zoomFactor < 1 || axis.zoomPosition > 0) {\n axis.calculateVisibleRange(size);\n axis.visibleRange.interval = (axis.enableAutoIntervalOnZooming && axis.valueType !== 'Category') ?\n this.calculateNumericNiceInterval(axis, axis.doubleRange.delta, size)\n : axis.visibleRange.interval;\n }\n axis.triggerRangeRender(this.chart, axis.visibleRange.min, axis.visibleRange.max, axis.visibleRange.interval);\n };\n /**\n * Calculate label for the axis.\n * @private\n */\n Double.prototype.calculateVisibleLabels = function (axis, chart) {\n /*! Generate axis labels */\n axis.visibleLabels = [];\n var tempInterval = axis.visibleRange.min;\n var labelStyle;\n if (axis.zoomFactor < 1 || axis.zoomPosition > 0 || this.paddingInterval) {\n tempInterval = axis.visibleRange.min - (axis.visibleRange.min % axis.visibleRange.interval);\n }\n var format = this.getFormat(axis);\n var isCustom = format.match('{value}') !== null;\n axis.format = chart.intl.getNumberFormat({\n format: isCustom ? '' : format,\n useGrouping: chart.useGroupingSeparator\n });\n axis.startLabel = axis.format(axis.visibleRange.min);\n axis.endLabel = axis.format(axis.visibleRange.max);\n for (; tempInterval <= axis.visibleRange.max; tempInterval += axis.visibleRange.interval) {\n labelStyle = (extend({}, getValue('properties', axis.labelStyle), null, true));\n if (withIn(tempInterval, axis.visibleRange)) {\n triggerLabelRender(chart, tempInterval, this.formatValue(axis, isCustom, format, tempInterval), labelStyle, axis);\n }\n }\n if (axis.getMaxLabelWidth) {\n axis.getMaxLabelWidth(this.chart);\n }\n };\n /**\n * Format of the axis label.\n * @private\n */\n Double.prototype.getFormat = function (axis) {\n if (axis.labelFormat) {\n return axis.labelFormat;\n }\n return axis.isStack100 ? '{value}%' : '';\n };\n /**\n * Formatted the axis label.\n * @private\n */\n Double.prototype.formatValue = function (axis, isCustom, format, tempInterval) {\n return isCustom ? format.replace('{value}', axis.format(tempInterval))\n : axis.format(tempInterval);\n };\n return Double;\n}());\nexport { Double };\n","/**\n * Specifies the chart constant value\n */\n/** @private */\nexport var loaded = 'loaded';\n/** @private */\nexport var load = 'load';\n/** @private */\nexport var animationComplete = 'animationComplete';\n/** @private */\nexport var legendRender = 'legendRender';\n/** @private */\nexport var textRender = 'textRender';\n/** @private */\nexport var pointRender = 'pointRender';\n/** @private */\nexport var seriesRender = 'seriesRender';\n/** @private */\nexport var axisLabelRender = 'axisLabelRender';\n/** @private */\nexport var axisRangeCalculated = 'axisRangeCalculated';\n/** @private */\nexport var axisMultiLabelRender = 'axisMultiLabelRender';\n/** @private */\nexport var tooltipRender = 'tooltipRender';\n/** @private */\nexport var chartMouseMove = 'chartMouseMove';\n/** @private */\nexport var chartMouseClick = 'chartMouseClick';\n/** @private */\nexport var pointClick = 'pointClick';\n/** @private */\nexport var pointMove = 'pointMove';\n/** @private */\nexport var chartMouseLeave = 'chartMouseLeave';\n/** @private */\nexport var chartMouseDown = 'chartMouseDown';\n/** @private */\nexport var chartMouseUp = 'chartMouseUp';\n/** @private */\nexport var zoomComplete = 'zoomComplete';\n/** @private */\nexport var dragComplete = 'dragComplete';\n/** @private */\nexport var resized = 'resized';\n/** @private */\nexport var beforePrint = 'beforePrint';\n/** @private */\nexport var annotationRender = 'annotationRender';\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { ChildProperty, Property, Complex, Collection } from '@syncfusion/ej2-base';\nimport { Theme } from '../../common/model/theme';\nimport { Font, Border } from '../../common/model/base';\n/**\n * Configures the Annotation for chart.\n */\nvar ChartAnnotationSettings = /** @class */ (function (_super) {\n __extends(ChartAnnotationSettings, _super);\n function ChartAnnotationSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('0')\n ], ChartAnnotationSettings.prototype, \"x\", void 0);\n __decorate([\n Property('0')\n ], ChartAnnotationSettings.prototype, \"y\", void 0);\n __decorate([\n Property(null)\n ], ChartAnnotationSettings.prototype, \"content\", void 0);\n __decorate([\n Property('Center')\n ], ChartAnnotationSettings.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Pixel')\n ], ChartAnnotationSettings.prototype, \"coordinateUnits\", void 0);\n __decorate([\n Property('Chart')\n ], ChartAnnotationSettings.prototype, \"region\", void 0);\n __decorate([\n Property('Middle')\n ], ChartAnnotationSettings.prototype, \"verticalAlignment\", void 0);\n __decorate([\n Property(null)\n ], ChartAnnotationSettings.prototype, \"xAxisName\", void 0);\n __decorate([\n Property(null)\n ], ChartAnnotationSettings.prototype, \"yAxisName\", void 0);\n __decorate([\n Property(null)\n ], ChartAnnotationSettings.prototype, \"description\", void 0);\n return ChartAnnotationSettings;\n}(ChildProperty));\nexport { ChartAnnotationSettings };\n/**\n * label border properties.\n */\nvar LabelBorder = /** @class */ (function (_super) {\n __extends(LabelBorder, _super);\n function LabelBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], LabelBorder.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], LabelBorder.prototype, \"width\", void 0);\n __decorate([\n Property('Rectangle')\n ], LabelBorder.prototype, \"type\", void 0);\n return LabelBorder;\n}(ChildProperty));\nexport { LabelBorder };\n/**\n * categories for multi level labels\n */\nvar MultiLevelCategories = /** @class */ (function (_super) {\n __extends(MultiLevelCategories, _super);\n function MultiLevelCategories() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], MultiLevelCategories.prototype, \"start\", void 0);\n __decorate([\n Property(null)\n ], MultiLevelCategories.prototype, \"end\", void 0);\n __decorate([\n Property('')\n ], MultiLevelCategories.prototype, \"text\", void 0);\n __decorate([\n Property(null)\n ], MultiLevelCategories.prototype, \"maximumTextWidth\", void 0);\n return MultiLevelCategories;\n}(ChildProperty));\nexport { MultiLevelCategories };\n/**\n * Strip line properties\n */\nvar StripLineSettings = /** @class */ (function (_super) {\n __extends(StripLineSettings, _super);\n function StripLineSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], StripLineSettings.prototype, \"visible\", void 0);\n __decorate([\n Property(false)\n ], StripLineSettings.prototype, \"startFromAxis\", void 0);\n __decorate([\n Property(null)\n ], StripLineSettings.prototype, \"start\", void 0);\n __decorate([\n Property(null)\n ], StripLineSettings.prototype, \"end\", void 0);\n __decorate([\n Property(null)\n ], StripLineSettings.prototype, \"size\", void 0);\n __decorate([\n Property('#808080')\n ], StripLineSettings.prototype, \"color\", void 0);\n __decorate([\n Complex({ color: 'transparent', width: 1 }, Border)\n ], StripLineSettings.prototype, \"border\", void 0);\n __decorate([\n Property('')\n ], StripLineSettings.prototype, \"text\", void 0);\n __decorate([\n Property(null)\n ], StripLineSettings.prototype, \"rotation\", void 0);\n __decorate([\n Property('Middle')\n ], StripLineSettings.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Middle')\n ], StripLineSettings.prototype, \"verticalAlignment\", void 0);\n __decorate([\n Complex(Theme.stripLineLabelFont, Font)\n ], StripLineSettings.prototype, \"textStyle\", void 0);\n __decorate([\n Property('Behind')\n ], StripLineSettings.prototype, \"zIndex\", void 0);\n __decorate([\n Property(1)\n ], StripLineSettings.prototype, \"opacity\", void 0);\n return StripLineSettings;\n}(ChildProperty));\nexport { StripLineSettings };\n/**\n * MultiLevelLabels properties\n */\nvar MultiLevelLabels = /** @class */ (function (_super) {\n __extends(MultiLevelLabels, _super);\n function MultiLevelLabels() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Center')\n ], MultiLevelLabels.prototype, \"alignment\", void 0);\n __decorate([\n Property('Wrap')\n ], MultiLevelLabels.prototype, \"overflow\", void 0);\n __decorate([\n Complex(Theme.axisLabelFont, Font)\n ], MultiLevelLabels.prototype, \"textStyle\", void 0);\n __decorate([\n Complex({ color: null, width: 1, type: 'Rectangle' }, LabelBorder)\n ], MultiLevelLabels.prototype, \"border\", void 0);\n __decorate([\n Collection([], MultiLevelCategories)\n ], MultiLevelLabels.prototype, \"categories\", void 0);\n return MultiLevelLabels;\n}(ChildProperty));\nexport { MultiLevelLabels };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty, Collection, extend } from '@syncfusion/ej2-base';\nimport { Font, Border } from '../../common/model/base';\nimport { Size, Rect, measureText, rotateTextSize, firstToLowerCase, valueToCoefficient, inside } from '../../common/utils/helper';\nimport { DoubleRange } from '../utils/double-range';\nimport { Double } from '../axis/double-axis';\nimport { Theme } from '../../common/model/theme';\nimport { axisRangeCalculated } from '../../common/model/constants';\nimport { StripLineSettings, MultiLevelLabels, LabelBorder } from '../model/chart-base';\nimport { textWrap } from '../../common/utils/helper';\nvar axisPadding = 10;\n/**\n * Configures the `rows` of the chart.\n */\nvar Row = /** @class */ (function (_super) {\n __extends(Row, _super);\n function Row() {\n /**\n * The height of the row as a string accept input both as '100px' and '100%'.\n * If specified as '100%, row renders to the full height of its chart.\n * @default '100%'\n */\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.axes = [];\n /** @private */\n _this.nearSizes = [];\n /** @private */\n _this.farSizes = [];\n return _this;\n }\n /**\n * Measure the row size\n * @return {void}\n * @private\n */\n Row.prototype.computeSize = function (axis, clipRect, scrollBarHeight) {\n var width = 0;\n var innerPadding = 5;\n if (axis.visible) {\n width += (axis.findTickSize(axis.crossInAxis) + scrollBarHeight +\n axis.findLabelSize(axis.crossInAxis, innerPadding) + axis.lineStyle.width / 2);\n }\n if (axis.opposedPosition) {\n this.farSizes.push(width);\n }\n else {\n this.nearSizes.push(width);\n }\n };\n __decorate([\n Property('100%')\n ], Row.prototype, \"height\", void 0);\n __decorate([\n Complex({}, Border)\n ], Row.prototype, \"border\", void 0);\n return Row;\n}(ChildProperty));\nexport { Row };\n/**\n * Configures the `columns` of the chart.\n */\nvar Column = /** @class */ (function (_super) {\n __extends(Column, _super);\n function Column() {\n /**\n * The width of the column as a string accepts input both as like '100px' or '100%'.\n * If specified as '100%, column renders to the full width of its chart.\n * @default '100%'\n */\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.axes = [];\n /** @private */\n _this.nearSizes = [];\n /** @private */\n _this.farSizes = [];\n /** @private */\n _this.padding = 0;\n return _this;\n }\n /**\n * Measure the column size\n * @return {void}\n * @private\n */\n Column.prototype.computeSize = function (axis, clipRect, scrollBarHeight) {\n var height = 0;\n var innerPadding = 5;\n if (axis.visible) {\n height += (axis.findTickSize(axis.crossInAxis) + scrollBarHeight +\n axis.findLabelSize(axis.crossInAxis, innerPadding) + axis.lineStyle.width / 2);\n }\n if (axis.opposedPosition) {\n this.farSizes.push(height);\n }\n else {\n this.nearSizes.push(height);\n }\n };\n __decorate([\n Property('100%')\n ], Column.prototype, \"width\", void 0);\n __decorate([\n Complex({}, Border)\n ], Column.prototype, \"border\", void 0);\n return Column;\n}(ChildProperty));\nexport { Column };\n/**\n * Configures the major grid lines in the `axis`.\n */\nvar MajorGridLines = /** @class */ (function (_super) {\n __extends(MajorGridLines, _super);\n function MajorGridLines() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], MajorGridLines.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], MajorGridLines.prototype, \"dashArray\", void 0);\n __decorate([\n Property(null)\n ], MajorGridLines.prototype, \"color\", void 0);\n return MajorGridLines;\n}(ChildProperty));\nexport { MajorGridLines };\n/**\n * Configures the minor grid lines in the `axis`.\n */\nvar MinorGridLines = /** @class */ (function (_super) {\n __extends(MinorGridLines, _super);\n function MinorGridLines() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0.7)\n ], MinorGridLines.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], MinorGridLines.prototype, \"dashArray\", void 0);\n __decorate([\n Property(null)\n ], MinorGridLines.prototype, \"color\", void 0);\n return MinorGridLines;\n}(ChildProperty));\nexport { MinorGridLines };\n/**\n * Configures the axis line of a chart.\n */\nvar AxisLine = /** @class */ (function (_super) {\n __extends(AxisLine, _super);\n function AxisLine() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], AxisLine.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], AxisLine.prototype, \"dashArray\", void 0);\n __decorate([\n Property(null)\n ], AxisLine.prototype, \"color\", void 0);\n return AxisLine;\n}(ChildProperty));\nexport { AxisLine };\n/**\n * Configures the major tick lines.\n */\nvar MajorTickLines = /** @class */ (function (_super) {\n __extends(MajorTickLines, _super);\n function MajorTickLines() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], MajorTickLines.prototype, \"width\", void 0);\n __decorate([\n Property(5)\n ], MajorTickLines.prototype, \"height\", void 0);\n __decorate([\n Property(null)\n ], MajorTickLines.prototype, \"color\", void 0);\n return MajorTickLines;\n}(ChildProperty));\nexport { MajorTickLines };\n/**\n * Configures the minor tick lines.\n */\nvar MinorTickLines = /** @class */ (function (_super) {\n __extends(MinorTickLines, _super);\n function MinorTickLines() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0.7)\n ], MinorTickLines.prototype, \"width\", void 0);\n __decorate([\n Property(5)\n ], MinorTickLines.prototype, \"height\", void 0);\n __decorate([\n Property(null)\n ], MinorTickLines.prototype, \"color\", void 0);\n return MinorTickLines;\n}(ChildProperty));\nexport { MinorTickLines };\n/**\n * Configures the crosshair ToolTip.\n */\nvar CrosshairTooltip = /** @class */ (function (_super) {\n __extends(CrosshairTooltip, _super);\n function CrosshairTooltip() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], CrosshairTooltip.prototype, \"enable\", void 0);\n __decorate([\n Property(null)\n ], CrosshairTooltip.prototype, \"fill\", void 0);\n __decorate([\n Complex(Theme.crosshairLabelFont, Font)\n ], CrosshairTooltip.prototype, \"textStyle\", void 0);\n return CrosshairTooltip;\n}(ChildProperty));\nexport { CrosshairTooltip };\n/**\n * Configures the axes in the chart.\n */\nvar Axis = /** @class */ (function (_super) {\n __extends(Axis, _super);\n function Axis() {\n /**\n * Options to customize the axis label.\n */\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.visibleLabels = [];\n /** @private */\n _this.series = [];\n /** @private */\n _this.rect = new Rect(undefined, undefined, 0, 0);\n /** @private */\n _this.axisBottomLine = null;\n /** @private */\n _this.intervalDivs = [10, 5, 2, 1];\n /** @private */\n _this.angle = _this.labelRotation;\n /** @private */\n _this.isStack100 = false;\n /** @private */\n _this.crossAt = null;\n /** @private */\n _this.updatedRect = null;\n /** @private */\n _this.multiLevelLabelHeight = 0;\n /** @private */\n _this.isChart = true;\n return _this;\n }\n /**\n * The function used to find tick size.\n * @return {number}\n * @private\n */\n Axis.prototype.findTickSize = function (crossAxis) {\n if (this.tickPosition === 'Inside') {\n return 0;\n }\n if (crossAxis && (!crossAxis.visibleRange || this.isInside(crossAxis.visibleRange))) {\n return 0;\n }\n return this.majorTickLines.height;\n };\n /**\n * The function used to find axis position.\n * @return {number}\n * @private\n */\n Axis.prototype.isInside = function (range) {\n return (inside(this.crossAt, range) ||\n (!this.opposedPosition && this.crossAt >= range.max) || (this.opposedPosition && this.crossAt <= range.min));\n };\n /**\n * The function used to find label Size.\n * @return {number}\n * @private\n */\n Axis.prototype.findLabelSize = function (crossAxis, innerPadding) {\n var titleSize = 0;\n if (this.title) {\n titleSize = measureText(this.title, this.titleStyle).height + innerPadding;\n }\n if (this.labelPosition === 'Inside') {\n return titleSize + innerPadding;\n }\n var diff;\n var value;\n var labelSize = titleSize + innerPadding + axisPadding +\n ((this.orientation === 'Vertical') ? this.maxLabelSize.width : this.maxLabelSize.height) + this.multiLevelLabelHeight;\n if (crossAxis && this.placeNextToAxisLine) {\n var range = crossAxis.visibleRange;\n var size = (crossAxis.orientation === 'Horizontal') ? crossAxis.rect.width : crossAxis.rect.height;\n if (!range || !size) {\n return 0;\n }\n else if (this.isInside(range)) {\n value = this.findDifference(crossAxis);\n diff = (value) * (size / range.delta);\n diff = (value) * ((size - (diff < labelSize ? (labelSize - diff) : 0)) / range.delta);\n labelSize = (diff < labelSize) ? (labelSize - diff) : 0;\n }\n }\n return labelSize;\n };\n /**\n * The function used to find axis position.\n * @return {number}\n * @private\n */\n Axis.prototype.updateCrossValue = function (chart) {\n var value = this.crossAt;\n if (value === null || !this.isInside(this.crossInAxis.visibleRange)) {\n this.updatedRect = this.rect;\n return null;\n }\n var range = this.crossInAxis.visibleRange;\n if (!this.opposedPosition) {\n if (this.crossAt > range.max) {\n value = range.max;\n }\n }\n else {\n if (this.crossAt < range.min) {\n value = range.min;\n }\n }\n this.updatedRect = extend({}, this.rect, null, true);\n if (this.orientation === 'Horizontal') {\n value = this.crossInAxis.rect.height - (valueToCoefficient(value, this.crossInAxis) * this.crossInAxis.rect.height);\n this.updatedRect.y = this.crossInAxis.rect.y + value;\n }\n else {\n value = valueToCoefficient(value, this.crossInAxis) * this.crossInAxis.rect.width;\n this.updatedRect.x = this.crossInAxis.rect.x + value;\n }\n };\n Axis.prototype.findDifference = function (crossAxis) {\n var value = 0;\n if (this.opposedPosition) {\n value = crossAxis.isInversed ? crossAxis.visibleRange.min : crossAxis.visibleRange.max;\n }\n else {\n value = crossAxis.isInversed ? crossAxis.visibleRange.max : crossAxis.visibleRange.min;\n }\n return Math.abs(this.crossAt - value);\n };\n /**\n * Calculate visible range for axis.\n * @return {void}\n * @private\n */\n Axis.prototype.calculateVisibleRange = function (size) {\n if (this.zoomFactor < 1 || this.zoomPosition > 0) {\n var baseRange = this.actualRange;\n var start = void 0;\n var end = void 0;\n if (!this.isInversed) {\n start = this.actualRange.min + this.zoomPosition * this.actualRange.delta;\n end = start + this.zoomFactor * this.actualRange.delta;\n }\n else {\n start = this.actualRange.max - (this.zoomPosition * this.actualRange.delta);\n end = start - (this.zoomFactor * this.actualRange.delta);\n }\n if (start < baseRange.min) {\n end = end + (baseRange.min - start);\n start = baseRange.min;\n }\n if (end > baseRange.max) {\n start = start - (end - baseRange.max);\n end = baseRange.max;\n }\n this.doubleRange = new DoubleRange(start, end);\n this.visibleRange.min = this.doubleRange.start;\n this.visibleRange.max = this.doubleRange.end;\n this.visibleRange.delta = this.doubleRange.delta;\n }\n };\n /**\n * Triggers the event.\n * @return {void}\n * @private\n */\n Axis.prototype.triggerRangeRender = function (chart, minimum, maximum, interval) {\n var argsData;\n argsData = {\n cancel: false, name: axisRangeCalculated, axis: this,\n minimum: minimum, maximum: maximum, interval: interval\n };\n chart.trigger(axisRangeCalculated, argsData);\n if (!argsData.cancel) {\n this.visibleRange.min = argsData.minimum;\n this.visibleRange.max = argsData.maximum;\n this.visibleRange.interval = argsData.interval;\n this.visibleRange.delta = argsData.maximum - argsData.minimum;\n }\n };\n /**\n * Calculate padding for the axis.\n * @return {string}\n * @private\n */\n Axis.prototype.getRangePadding = function (chart) {\n var padding = this.rangePadding;\n if (padding !== 'Auto') {\n return padding;\n }\n switch (this.orientation) {\n case 'Horizontal':\n if (chart.requireInvertedAxis) {\n padding = (this.isStack100 ? 'Round' : 'Normal');\n }\n else {\n padding = 'None';\n }\n break;\n case 'Vertical':\n if (!chart.requireInvertedAxis) {\n padding = (this.isStack100 ? 'Round' : 'Normal');\n }\n else {\n padding = 'None';\n }\n break;\n }\n return padding;\n };\n /**\n * Calculate maximum label width for the axis.\n * @return {void}\n * @private\n */\n Axis.prototype.getMaxLabelWidth = function (chart) {\n var prevSize = new Size(0, 0);\n var rotatedLabel;\n var pointX;\n var previousEnd = 0;\n var isIntersect = false;\n this.angle = this.labelRotation;\n this.maxLabelSize = new Size(0, 0);\n var action = this.labelIntersectAction;\n var label;\n for (var i = 0; i < this.visibleLabels.length; i++) {\n label = this.visibleLabels[i];\n label.size = measureText(label.text, this.labelStyle);\n if (label.size.width > this.maxLabelSize.width) {\n this.maxLabelSize.width = label.size.width;\n this.rotatedLabel = label.text;\n }\n if (label.size.height > this.maxLabelSize.height) {\n this.maxLabelSize.height = label.size.height;\n }\n if (action === 'None' || action === 'Hide' || action === 'Trim') {\n continue;\n }\n if ((action !== 'None' || this.angle % 360 === 0) && this.orientation === 'Horizontal' &&\n this.rect.width > 0 && !isIntersect) {\n pointX = (valueToCoefficient(label.value, this) * this.rect.width) + this.rect.x;\n pointX -= label.size.width / 2;\n if (this.edgeLabelPlacement === 'Shift') {\n if (i === 0 && pointX < this.rect.x) {\n pointX = this.rect.x;\n }\n if (i === this.visibleLabels.length - 1 && ((pointX + label.size.width) > (this.rect.x + this.rect.width))) {\n pointX = this.rect.x + this.rect.width - label.size.width;\n }\n }\n switch (action) {\n case 'MultipleRows':\n if (i > 0) {\n this.findMultiRows(i, pointX, label);\n }\n break;\n case 'Rotate45':\n case 'Rotate90':\n if (i > 0 && (!this.isInversed ? pointX <= previousEnd : pointX + label.size.width >= previousEnd)) {\n this.angle = (action === 'Rotate45') ? 45 : 90;\n isIntersect = true;\n }\n break;\n default:\n label.text = textWrap(label.text, this.rect.width / this.visibleLabels.length, this.labelStyle);\n var height = (label.size.height * label.text.length);\n if (height > this.maxLabelSize.height) {\n this.maxLabelSize.height = height;\n }\n break;\n }\n previousEnd = this.isInversed ? pointX : pointX + label.size.width;\n }\n }\n if (this.angle !== 0 && this.orientation === 'Horizontal') {\n this.maxLabelSize = rotateTextSize(this.labelStyle, this.rotatedLabel, this.angle, chart);\n }\n if (chart.multiLevelLabelModule && this.multiLevelLabels.length > 0) {\n chart.multiLevelLabelModule.getMultilevelLabelsHeight(this);\n }\n };\n /**\n * Finds the multiple rows for axis.\n * @return {void}\n */\n Axis.prototype.findMultiRows = function (length, currentX, currentLabel) {\n var label;\n var pointX;\n var store = [];\n var isMultiRows;\n for (var i = length - 1; i >= 0; i--) {\n label = this.visibleLabels[i];\n pointX = (valueToCoefficient(label.value, this) * this.rect.width) + this.rect.x;\n isMultiRows = !this.isInversed ? currentX < (pointX + label.size.width / 2) :\n currentX + currentLabel.size.width > (pointX - label.size.width / 2);\n if (isMultiRows) {\n store.push(label.index);\n currentLabel.index = (currentLabel.index > label.index) ? currentLabel.index : label.index + 1;\n }\n else {\n currentLabel.index = store.indexOf(label.index) > -1 ? currentLabel.index : label.index;\n }\n }\n var height = (currentLabel.size.height * currentLabel.index) + (5 * (currentLabel.index - 1));\n if (height > this.maxLabelSize.height) {\n this.maxLabelSize.height = height;\n }\n };\n /**\n * Finds the default module for axis.\n * @return {void}\n * @private\n */\n Axis.prototype.getModule = function (chart) {\n if (this.valueType === 'Double') {\n this.baseModule = new Double(chart);\n }\n else {\n this.baseModule = chart[firstToLowerCase(this.valueType) + 'Module'];\n }\n };\n __decorate([\n Complex(Theme.axisLabelFont, Font)\n ], Axis.prototype, \"labelStyle\", void 0);\n __decorate([\n Complex({}, CrosshairTooltip)\n ], Axis.prototype, \"crosshairTooltip\", void 0);\n __decorate([\n Property('')\n ], Axis.prototype, \"title\", void 0);\n __decorate([\n Complex(Theme.axisTitleFont, Font)\n ], Axis.prototype, \"titleStyle\", void 0);\n __decorate([\n Property('')\n ], Axis.prototype, \"labelFormat\", void 0);\n __decorate([\n Property('')\n ], Axis.prototype, \"skeleton\", void 0);\n __decorate([\n Property('DateTime')\n ], Axis.prototype, \"skeletonType\", void 0);\n __decorate([\n Property(0)\n ], Axis.prototype, \"plotOffset\", void 0);\n __decorate([\n Property(false)\n ], Axis.prototype, \"isIndexed\", void 0);\n __decorate([\n Property(10)\n ], Axis.prototype, \"logBase\", void 0);\n __decorate([\n Property(0)\n ], Axis.prototype, \"columnIndex\", void 0);\n __decorate([\n Property(0)\n ], Axis.prototype, \"rowIndex\", void 0);\n __decorate([\n Property(1)\n ], Axis.prototype, \"span\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"desiredIntervals\", void 0);\n __decorate([\n Property(3)\n ], Axis.prototype, \"maximumLabels\", void 0);\n __decorate([\n Property(1)\n ], Axis.prototype, \"zoomFactor\", void 0);\n __decorate([\n Property(0)\n ], Axis.prototype, \"zoomPosition\", void 0);\n __decorate([\n Property(false)\n ], Axis.prototype, \"opposedPosition\", void 0);\n __decorate([\n Property(true)\n ], Axis.prototype, \"enableAutoIntervalOnZooming\", void 0);\n __decorate([\n Property('Auto')\n ], Axis.prototype, \"rangePadding\", void 0);\n __decorate([\n Property('Double')\n ], Axis.prototype, \"valueType\", void 0);\n __decorate([\n Property('None')\n ], Axis.prototype, \"edgeLabelPlacement\", void 0);\n __decorate([\n Property('Auto')\n ], Axis.prototype, \"intervalType\", void 0);\n __decorate([\n Property('BetweenTicks')\n ], Axis.prototype, \"labelPlacement\", void 0);\n __decorate([\n Property('Outside')\n ], Axis.prototype, \"tickPosition\", void 0);\n __decorate([\n Property('Outside')\n ], Axis.prototype, \"labelPosition\", void 0);\n __decorate([\n Property('')\n ], Axis.prototype, \"name\", void 0);\n __decorate([\n Property(true)\n ], Axis.prototype, \"visible\", void 0);\n __decorate([\n Property(0)\n ], Axis.prototype, \"minorTicksPerInterval\", void 0);\n __decorate([\n Property(0)\n ], Axis.prototype, \"labelRotation\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"crossesAt\", void 0);\n __decorate([\n Property(true)\n ], Axis.prototype, \"placeNextToAxisLine\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"crossesInAxis\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"minimum\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"maximum\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"interval\", void 0);\n __decorate([\n Complex({}, MajorTickLines)\n ], Axis.prototype, \"majorTickLines\", void 0);\n __decorate([\n Complex({}, MinorTickLines)\n ], Axis.prototype, \"minorTickLines\", void 0);\n __decorate([\n Complex({}, MajorGridLines)\n ], Axis.prototype, \"majorGridLines\", void 0);\n __decorate([\n Complex({}, MinorGridLines)\n ], Axis.prototype, \"minorGridLines\", void 0);\n __decorate([\n Complex({}, AxisLine)\n ], Axis.prototype, \"lineStyle\", void 0);\n __decorate([\n Property('Trim')\n ], Axis.prototype, \"labelIntersectAction\", void 0);\n __decorate([\n Property(false)\n ], Axis.prototype, \"isInversed\", void 0);\n __decorate([\n Property(100)\n ], Axis.prototype, \"coefficient\", void 0);\n __decorate([\n Property(0)\n ], Axis.prototype, \"startAngle\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"description\", void 0);\n __decorate([\n Property(2)\n ], Axis.prototype, \"tabIndex\", void 0);\n __decorate([\n Collection([], StripLineSettings)\n ], Axis.prototype, \"stripLines\", void 0);\n __decorate([\n Collection([], MultiLevelLabels)\n ], Axis.prototype, \"multiLevelLabels\", void 0);\n __decorate([\n Complex({ color: null, width: 0, type: 'Rectangle' }, LabelBorder)\n ], Axis.prototype, \"border\", void 0);\n return Axis;\n}(ChildProperty));\nexport { Axis };\n/** @private */\nvar VisibleLabels = /** @class */ (function () {\n function VisibleLabels(text, value, labelStyle, size, index) {\n if (size === void 0) { size = new Size(0, 0); }\n if (index === void 0) { index = 1; }\n this.text = text;\n this.originalText = text;\n this.value = value;\n this.labelStyle = labelStyle;\n this.size = size;\n this.index = 1;\n }\n return VisibleLabels;\n}());\nexport { VisibleLabels };\n","import { createElement, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { DataUtil } from '@syncfusion/ej2-data';\nimport { subtractThickness, valueToCoefficient, sum, subArray, TextOption, inside, measureText } from '../../common/utils/helper';\nimport { Size, Rect, Thickness, PathOption, logBase, createZoomingLabels, getElement, rotateTextSize } from '../../common/utils/helper';\nimport { textElement, textTrim } from '../../common/utils/helper';\n/**\n * Specifies the Cartesian Axis Layout.\n */\nvar axisPadding = 10;\nvar CartesianAxisLayoutPanel = /** @class */ (function () {\n /** @private */\n function CartesianAxisLayoutPanel(chartModule) {\n this.chart = chartModule;\n this.padding = 5;\n }\n /**\n * Measure the axis size.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.measureAxis = function (rect) {\n var chart = this.chart;\n this.crossAt(chart);\n this.seriesClipRect = new Rect(rect.x, rect.y, rect.width, rect.height);\n this.initialClipRect = rect;\n this.leftSize = 0;\n this.rightSize = 0;\n this.topSize = 0;\n this.bottomSize = 0;\n //Measure Axis size with initial Rect\n this.measureRowAxis(chart, this.initialClipRect);\n this.initialClipRect = subtractThickness(this.initialClipRect, new Thickness(this.leftSize, this.rightSize, 0, 0));\n this.measureColumnAxis(chart, this.initialClipRect);\n this.initialClipRect = subtractThickness(this.initialClipRect, new Thickness(0, 0, this.topSize, this.bottomSize));\n if (!this.chart.delayRedraw) {\n this.calculateAxisSize(this.initialClipRect);\n }\n this.leftSize = 0;\n this.rightSize = 0;\n this.topSize = 0;\n this.bottomSize = 0;\n //Measure Axis size with series Rect\n this.measureRowAxis(chart, this.initialClipRect);\n this.seriesClipRect = subtractThickness(this.seriesClipRect, new Thickness(this.leftSize, this.rightSize, 0, 0));\n this.measureColumnAxis(chart, this.initialClipRect);\n this.seriesClipRect = subtractThickness(this.seriesClipRect, new Thickness(0, 0, this.topSize, this.bottomSize));\n if (!this.chart.delayRedraw) {\n chart.refreshAxis();\n this.calculateAxisSize(this.seriesClipRect);\n }\n };\n CartesianAxisLayoutPanel.prototype.measureRowAxis = function (chart, rect) {\n var row;\n this.calculateRowSize(rect);\n for (var _i = 0, _a = chart.rows; _i < _a.length; _i++) {\n var item = _a[_i];\n row = item;\n row.nearSizes = [];\n row.farSizes = [];\n this.arrangeAxis(row);\n this.measureDefinition(row, chart, new Size(chart.availableSize.width, row.computedHeight), rect);\n if (this.leftSize < sum(row.nearSizes)) {\n this.leftSize = sum(row.nearSizes);\n }\n if (this.rightSize < sum(row.farSizes)) {\n this.rightSize = sum(row.farSizes);\n }\n }\n };\n CartesianAxisLayoutPanel.prototype.measureColumnAxis = function (chart, rect) {\n var column;\n this.calculateColumnSize(rect);\n for (var _i = 0, _a = chart.columns; _i < _a.length; _i++) {\n var item = _a[_i];\n column = item;\n column.farSizes = [];\n column.nearSizes = [];\n this.arrangeAxis(column);\n this.measureDefinition(column, chart, new Size(column.computedWidth, chart.availableSize.height), rect);\n if (this.bottomSize < sum(column.nearSizes)) {\n this.bottomSize = sum(column.nearSizes);\n }\n if (this.topSize < sum(column.farSizes)) {\n this.topSize = sum(column.farSizes);\n }\n }\n };\n /**\n * Measure the column and row in chart.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.measureDefinition = function (definition, chart, size, clipRect) {\n var axis;\n var axisType;\n for (var _i = 0, _a = definition.axes; _i < _a.length; _i++) {\n var axis_1 = _a[_i];\n axis_1.scrollBarHeight = chart.scrollBarModule && chart.zoomSettings.enableScrollbar && chart.zoomModule.isZoomed\n && (axis_1.zoomFactor < 1 || axis_1.zoomPosition > 0) ? 16 : 0;\n axis_1.scrollBarHeight = chart.delayRedraw ? (axis_1.zoomingScrollBar && axis_1.zoomingScrollBar.svgObject &&\n axis_1.zoomingScrollBar.svgObject.childElementCount) ? 16 : 0 : axis_1.scrollBarHeight;\n axis_1.getModule(chart);\n axis_1.baseModule.calculateRangeAndInterval(size, axis_1);\n definition.computeSize(axis_1, clipRect, axis_1.scrollBarHeight);\n }\n if (definition.farSizes.length > 0) {\n definition.farSizes[definition.farSizes.length - 1] -= axisPadding;\n }\n if (definition.nearSizes.length > 0) {\n definition.nearSizes[definition.nearSizes.length - 1] -= axisPadding;\n }\n };\n /**\n * Measure the axis.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.calculateAxisSize = function (rect) {\n var chart = this.chart;\n var row;\n var column;\n var definition;\n var axis;\n var nearCount = 0;\n var farCount = 0;\n var size = 0;\n var x;\n var y;\n this.calculateRowSize(rect);\n for (var i = 0, len = chart.rows.length; i < len; i++) {\n row = chart.rows[i];\n nearCount = 0;\n farCount = 0;\n for (var j = 0, len_1 = row.axes.length; j < len_1; j++) {\n axis = row.axes[j];\n if (axis.rect.height === 0) {\n axis.rect.height = row.computedHeight;\n size = 0;\n for (var k = i + 1, len_2 = i + axis.span; k < len_2; k++) {\n definition = chart.rows[k];\n size += definition.computedHeight;\n }\n axis.rect.y = (row.computedTop - size) + axis.plotOffset;\n axis.rect.height = (axis.rect.height + size) - (2 * axis.plotOffset);\n axis.rect.width = 0;\n }\n if (axis.opposedPosition) {\n x = rect.x + rect.width + sum(subArray(row.farSizes, farCount));\n axis.rect.x = axis.rect.x >= x ? axis.rect.x : x;\n farCount++;\n }\n else {\n x = rect.x - sum(subArray(row.nearSizes, nearCount));\n axis.rect.x = axis.rect.x <= x ? axis.rect.x : x;\n nearCount++;\n }\n }\n }\n this.calculateColumnSize(rect);\n for (var i = 0, len = chart.columns.length; i < len; i++) {\n column = chart.columns[i];\n nearCount = 0;\n farCount = 0;\n for (var j = 0, len_3 = column.axes.length; j < len_3; j++) {\n axis = column.axes[j];\n if (axis.rect.width === 0) {\n for (var k = i, len_4 = (i + axis.span); k < len_4; k++) {\n definition = chart.columns[k];\n axis.rect.width += definition.computedWidth;\n }\n axis.rect.x = column.computedLeft + axis.plotOffset;\n axis.rect.width -= (2 * axis.plotOffset);\n axis.rect.height = 0;\n }\n if (axis.opposedPosition) {\n y = rect.y - sum(subArray(column.farSizes, farCount));\n axis.rect.y = axis.rect.y <= y ? axis.rect.y : y;\n farCount++;\n }\n else {\n y = rect.y + rect.height + sum(subArray(column.nearSizes, nearCount));\n axis.rect.y = axis.rect.y >= y ? axis.rect.y : y;\n nearCount++;\n }\n }\n }\n };\n /**\n * Measure the axis.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.measure = function () {\n var chart = this.chart;\n var row;\n var column;\n var definition;\n var axis;\n var actualIndex;\n var span;\n var axisLength;\n for (var _i = 0, _a = chart.axisCollections; _i < _a.length; _i++) {\n var axis_2 = _a[_i];\n //definition.Axes = axis;\n if (axis_2.orientation === 'Vertical') {\n chart.verticalAxes.push(axis_2);\n actualIndex = this.getActualRow(axis_2);\n row = chart.rows[actualIndex];\n this.pushAxis(row, axis_2);\n span = ((actualIndex + axis_2.span) > chart.rows.length ? chart.rows.length : (actualIndex + axis_2.span));\n for (var j = actualIndex + 1; j < span; j++) {\n definition = chart.rows[j];\n definition.axes[row.axes.length - 1] = axis_2;\n chart.rows[j] = definition;\n }\n chart.rows[actualIndex] = row;\n }\n else {\n chart.horizontalAxes.push(axis_2);\n actualIndex = this.getActualColumn(axis_2);\n column = chart.columns[actualIndex];\n this.pushAxis(column, axis_2);\n span = ((actualIndex + axis_2.span) > chart.columns.length ? chart.columns.length : (actualIndex + axis_2.span));\n for (var j = actualIndex + 1; j < span; j++) {\n definition = chart.columns[j];\n definition.axes[column.axes.length - 1] = axis_2;\n chart.columns[j] = definition;\n }\n chart.columns[actualIndex] = column;\n }\n }\n };\n CartesianAxisLayoutPanel.prototype.crossAt = function (chart) {\n for (var _i = 0, _a = chart.axisCollections; _i < _a.length; _i++) {\n var axis = _a[_i];\n if (axis.crossesAt === null) {\n continue;\n }\n var isTransposed = chart.isTransposed;\n if (!axis.crossesInAxis) {\n if (chart.requireInvertedAxis) {\n axis.crossInAxis = ((axis.orientation === 'Horizontal')) ? chart.primaryXAxis : chart.primaryYAxis;\n }\n else {\n axis.crossInAxis = ((axis.orientation === 'Horizontal')) ? chart.primaryYAxis : chart.primaryXAxis;\n }\n axis.crossAt = this.updateCrossAt(axis.crossInAxis, axis.crossesAt);\n continue;\n }\n else {\n for (var i = 2, len = chart.axisCollections.length; i < len; i++) {\n if (axis.crossesInAxis === chart.axisCollections[i].name) {\n axis.crossInAxis = chart.axisCollections[i];\n axis.crossAt = this.updateCrossAt(axis.crossInAxis, axis.crossesAt);\n continue;\n }\n }\n }\n }\n };\n CartesianAxisLayoutPanel.prototype.updateCrossAt = function (axis, crossAt) {\n switch (axis.valueType) {\n case 'DateTime':\n var option = {\n skeleton: 'full',\n type: 'dateTime'\n };\n var dateParser = this.chart.intl.getDateParser(option);\n var dateFormatter = this.chart.intl.getDateFormat(option);\n return Date.parse(dateParser(dateFormatter(new Date(DataUtil.parse.parseJson({ val: crossAt }).val))));\n case 'Category':\n return parseFloat(crossAt) ? parseFloat(crossAt) : axis.labels.indexOf(crossAt);\n case 'Logarithmic':\n return logBase(crossAt, axis.logBase);\n default:\n return crossAt;\n }\n };\n CartesianAxisLayoutPanel.prototype.pushAxis = function (definition, axis) {\n for (var i = 0, len = definition.axes.length; i <= len; i++) {\n if (!definition.axes[i]) {\n definition.axes[i] = axis;\n break;\n }\n }\n };\n CartesianAxisLayoutPanel.prototype.arrangeAxis = function (definition) {\n var axisCollection = [];\n for (var i = 0, len = definition.axes.length; i <= len; i++) {\n if (definition.axes[i]) {\n axisCollection.push(definition.axes[i]);\n }\n }\n definition.axes = axisCollection;\n };\n CartesianAxisLayoutPanel.prototype.getActualColumn = function (axis) {\n var actualLength = this.chart.columns.length;\n var pos = axis.columnIndex;\n var result = pos >= actualLength ? actualLength - 1 : (pos < 0 ? 0 : pos);\n return result;\n };\n CartesianAxisLayoutPanel.prototype.getActualRow = function (axis) {\n var actualLength = this.chart.rows.length;\n var pos = axis.rowIndex;\n var result = pos >= actualLength ? actualLength - 1 : (pos < 0 ? 0 : pos);\n return result;\n };\n /**\n * Measure the row size.\n * @return {void}\n */\n CartesianAxisLayoutPanel.prototype.calculateRowSize = function (rect) {\n /*! Calculate row size */\n var chart = this.chart;\n var row;\n var rowTop = rect.y + rect.height;\n var height = 0;\n var remainingHeight = Math.max(0, rect.height);\n for (var i = 0, len = chart.rows.length; i < len; i++) {\n row = chart.rows[i];\n if (row.height.indexOf('%') !== -1) {\n height = Math.min(remainingHeight, (rect.height * parseInt(row.height, 10) / 100));\n }\n else {\n height = Math.min(remainingHeight, parseInt(row.height, 10));\n }\n height = (i !== (len - 1)) ? height : remainingHeight;\n row.computedHeight = height;\n rowTop -= height;\n row.computedTop = rowTop;\n remainingHeight -= height;\n }\n };\n /**\n * Measure the row size.\n * @return {void}\n */\n CartesianAxisLayoutPanel.prototype.calculateColumnSize = function (rect) {\n /*! Calculate column size */\n var chart = this.chart;\n var column;\n var columnLeft = rect.x;\n var width = 0;\n var remainingWidth = Math.max(0, rect.width);\n for (var i = 0, len = chart.columns.length; i < len; i++) {\n column = chart.columns[i];\n if (column.width.indexOf('%') !== -1) {\n width = Math.min(remainingWidth, (rect.width * parseInt(column.width, 10) / 100));\n }\n else {\n width = Math.min(remainingWidth, parseInt(column.width, 10));\n }\n width = (i !== (len - 1)) ? width : remainingWidth;\n column.computedWidth = width;\n column.computedLeft = columnLeft;\n columnLeft += width;\n remainingWidth -= width;\n }\n };\n /**\n * To render the axis element.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.renderAxes = function () {\n var chart = this.chart;\n var axis;\n var axisElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisInsideCollection' });\n var axisLineElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisOutsideCollection' });\n var outsideElement;\n var isInside;\n for (var i = 0, len = chart.axisCollections.length; i < len; i++) {\n axis = chart.axisCollections[i];\n this.element = chart.renderer.createGroup({ id: chart.element.id + 'AxisGroup' + i + 'Inside' });\n outsideElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisGroup' + i + 'Outside' });\n isInside = this.findAxisPosition(axis);\n if (axis.orientation === 'Horizontal') {\n axis.updateCrossValue(chart);\n if (axis.visible && axis.lineStyle.width > 0) {\n this.drawAxisLine(axis, i, axis.plotOffset, 0, isInside ? outsideElement : this.element, axis.updatedRect);\n }\n if (axis.majorGridLines.width > 0 || axis.majorTickLines.width > 0) {\n this.drawXAxisGridLine(axis, i, (isInside || axis.tickPosition === 'Inside') ? outsideElement : this.element, axis.updatedRect);\n }\n if (axis.visible) {\n this.drawXAxisLabels(axis, i, (isInside || axis.labelPosition === 'Inside') ? outsideElement : this.element, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n this.drawXAxisBorder(axis, i, (isInside || axis.labelPosition === 'Inside') ? outsideElement : this.element, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n this.drawXAxisTitle(axis, i, isInside ? outsideElement : this.element, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n }\n }\n else {\n axis.updateCrossValue(chart);\n if (axis.visible && axis.lineStyle.width > 0) {\n this.drawAxisLine(axis, i, 0, axis.plotOffset, isInside ? outsideElement : this.element, axis.updatedRect);\n }\n if (axis.majorGridLines.width > 0 || axis.majorTickLines.width > 0) {\n this.drawYAxisGridLine(axis, i, (isInside || axis.tickPosition === 'Inside') ? outsideElement : this.element, axis.updatedRect);\n }\n if (axis.visible) {\n this.drawYAxisLabels(axis, i, (isInside || axis.labelPosition === 'Inside') ? outsideElement : this.element, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n this.drawYAxisBorder(axis, i, (isInside || axis.labelPosition === 'Inside') ? outsideElement : this.element, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n this.drawYAxisTitle(axis, i, isInside ? outsideElement : this.element, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n }\n }\n axisElement.appendChild(this.element);\n if (outsideElement && outsideElement.childNodes.length > 0) {\n axisLineElement.appendChild(outsideElement);\n }\n if (chart.scrollBarModule && chart.zoomSettings.enableScrollbar) {\n this.renderScrollbar(chart, axis);\n }\n }\n this.element = chart.renderer.createGroup({ id: chart.element.id + 'DefinitionLine' });\n for (var j = 0, len = chart.rows.length; j < len; j++) {\n var row = chart.rows[j];\n if (row.border.color) {\n this.drawBottomLine(row, j, true);\n }\n }\n for (var j = 0, len = chart.columns.length; j < len; j++) {\n var column = chart.columns[j];\n if (column.border.color) {\n this.drawBottomLine(column, j, false);\n }\n }\n axisElement.appendChild(this.element);\n chart.svgObject.appendChild(axisElement);\n return axisLineElement;\n };\n /**\n * To render scrollbar\n * @param chart\n * @param axis\n */\n CartesianAxisLayoutPanel.prototype.renderScrollbar = function (chart, axis) {\n if (chart.zoomModule.isZoomed && (axis.zoomFactor < 1 || axis.zoomPosition > 0) && !axis.zoomingScrollBar.isScrollUI) {\n var currentScrollSvg = axis.zoomingScrollBar.svgObject;\n if (currentScrollSvg && currentScrollSvg.childElementCount) {\n chart.scrollElement.replaceChild(axis.zoomingScrollBar.render(), currentScrollSvg);\n }\n else {\n if (!chart.scrollElement) {\n chart.scrollElement = createElement('div', { id: chart.element.id + '_scrollElement' });\n }\n chart.scrollElement.appendChild(axis.zoomingScrollBar.render());\n }\n }\n else if (axis.zoomFactor === 1 && axis.zoomPosition === 0 && axis.zoomingScrollBar.svgObject) {\n axis.zoomingScrollBar.destroy();\n }\n if (axis.zoomingScrollBar.isScrollUI) {\n axis.zoomingScrollBar.isScrollUI = false;\n }\n };\n CartesianAxisLayoutPanel.prototype.findAxisPosition = function (axis) {\n return axis.crossAt !== null && axis.isInside(axis.crossInAxis.visibleRange);\n };\n CartesianAxisLayoutPanel.prototype.drawBottomLine = function (definition, index, isRow) {\n var chart = this.chart;\n var optionsLine = {};\n var x1;\n var x2;\n var y1;\n var y2;\n var definitionName;\n if (isRow) {\n definition = definition;\n y1 = y2 = definition.computedTop + definition.computedHeight;\n x1 = this.seriesClipRect.x;\n x2 = x1 + this.seriesClipRect.width;\n definitionName = 'Row';\n }\n else {\n definition = definition;\n x1 = x2 = definition.computedLeft;\n y1 = this.seriesClipRect.y;\n y2 = y1 + this.seriesClipRect.height;\n definitionName = 'Column';\n }\n optionsLine = {\n 'id': chart.element.id + '_AxisBottom_' + definitionName + index,\n x1: x1,\n y1: y1,\n x2: x2,\n y2: y2,\n 'stroke-width': definition.border.width,\n 'stroke': definition.border.color,\n };\n this.htmlObject = chart.renderer.drawLine(optionsLine);\n this.element.appendChild(this.htmlObject);\n };\n CartesianAxisLayoutPanel.prototype.drawAxisLine = function (axis, index, plotX, plotY, parent, rect) {\n var chart = this.chart;\n var optionsLine = {};\n optionsLine = {\n 'id': chart.element.id + 'AxisLine_' + index,\n x1: rect.x - plotX,\n y1: rect.y - plotY,\n x2: rect.x + rect.width + plotX,\n y2: rect.y + rect.height + plotY,\n 'stroke-dasharray': axis.lineStyle.dashArray,\n 'stroke-width': axis.lineStyle.width,\n 'stroke': axis.lineStyle.color || chart.themeStyle.axisLine\n };\n this.htmlObject = chart.renderer.drawLine(optionsLine);\n parent.appendChild(this.htmlObject);\n };\n CartesianAxisLayoutPanel.prototype.drawYAxisGridLine = function (axis, index, parent, rect) {\n var chart = this.chart;\n var tempInterval;\n var pointY = 0;\n var majorGrid = '';\n var majorTick = '';\n var minorGird = '';\n var minorTick = '';\n var minorDirection;\n var tickSize = axis.opposedPosition ? axis.majorTickLines.height : -axis.majorTickLines.height;\n var axisLineSize = (axis.opposedPosition) ? axis.lineStyle.width / 2 : -axis.lineStyle.width / 2;\n var ticksbwtLabel = (axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks') ?\n 0.5 : 0;\n var scrollBarHeight = isNullOrUndefined(axis.crossesAt) ? axis.opposedPosition ? axis.scrollBarHeight :\n -axis.scrollBarHeight : 0;\n var isTickInside = axis.tickPosition === 'Inside';\n var ticks = isTickInside ? (rect.x - tickSize - axisLineSize) : (rect.x + tickSize + axisLineSize + scrollBarHeight);\n var length = axis.visibleLabels.length;\n if (axis.valueType.indexOf('Category') && axis.labelPlacement === 'BetweenTicks' && length > 0) {\n length += 1;\n }\n //Gridlines\n for (var i = 0; i < length; i++) {\n tempInterval = !axis.visibleLabels[i] ? (axis.visibleLabels[i - 1].value + axis.visibleRange.interval) - ticksbwtLabel\n : axis.visibleLabels[i].value - ticksbwtLabel;\n pointY = valueToCoefficient(tempInterval, axis) * rect.height;\n pointY = (pointY * -1) + (rect.y + rect.height);\n if (pointY >= rect.y && (rect.y + rect.height) >= pointY) {\n if ((inside(tempInterval, axis.visibleRange)) || this.isBorder(axis, i, pointY)) {\n majorGrid = majorGrid.concat('M ' + this.seriesClipRect.x + ' ' + (pointY) +\n ' L ' + (this.seriesClipRect.x + this.seriesClipRect.width) + ' ' + pointY + ' ');\n }\n majorTick = majorTick.concat('M ' + (rect.x + axisLineSize + (isTickInside ? scrollBarHeight : 0)) + ' ' + pointY +\n ' L ' + (ticks) + ' ' + pointY + ' ');\n }\n if ((axis.minorGridLines.width > 0 || axis.minorTickLines.width > 0) && axis.minorTicksPerInterval > 0) {\n minorDirection = this.drawAxisMinorLine(axis, tempInterval, minorGird, minorTick, rect, i);\n minorGird = minorDirection[0];\n minorTick = minorDirection[1];\n }\n }\n this.renderGridLine(axis, index, majorGrid, minorGird);\n this.renderTickLine(axis, index, majorTick, minorTick, parent);\n };\n CartesianAxisLayoutPanel.prototype.isBorder = function (axis, index, value) {\n var chart = this.chart;\n var border = chart.chartArea.border;\n var rect = this.seriesClipRect;\n var orientation = axis.orientation;\n var start = (orientation === 'Horizontal') ? rect.x : rect.y;\n var size = (orientation === 'Horizontal') ? rect.width : rect.height;\n var startIndex = (orientation === 'Horizontal') ? 0 : axis.visibleLabels.length - 1;\n var endIndex = (orientation === 'Horizontal') ? axis.visibleLabels.length - 1 : 0;\n if (axis.plotOffset > 0) {\n return true;\n }\n else if ((value === start || value === (start + size)) && (border.width <= 0 || border.color === 'transparent')) {\n return true;\n }\n else if ((value !== start && index === startIndex) || (value !== (start + size) && index === endIndex)) {\n return true;\n }\n return false;\n };\n /**\n * To render the axis label.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.drawYAxisLabels = function (axis, index, parent, rect) {\n var chart = this.chart;\n var pointX = 0;\n var pointY = 0;\n var elementSize;\n var options;\n var isLabelInside = axis.labelPosition === 'Inside';\n var isTickInside = axis.tickPosition === 'Inside';\n var isOpposed = axis.opposedPosition;\n var tickSpace = axis.labelPosition === axis.tickPosition ? axis.majorTickLines.height : 0;\n var padding = tickSpace + this.padding + axis.lineStyle.width / 2;\n padding = (axis.opposedPosition) ? padding : -padding;\n var anchor = ((isOpposed && isLabelInside) || (!isOpposed && !isLabelInside)) ? 'end' : 'start';\n var labelElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisLabels' + index });\n var scrollBarHeight = isNullOrUndefined(axis.crossesAt) ? axis.scrollBarHeight * (isOpposed ? 1 : -1) : 0;\n for (var i = 0, len = axis.visibleLabels.length; i < len; i++) {\n pointX = isLabelInside ? (rect.x - padding) : (rect.x + padding + scrollBarHeight);\n elementSize = axis.visibleLabels[i].size;\n pointY = valueToCoefficient(axis.visibleLabels[i].value, axis) * rect.height;\n pointY = Math.floor((pointY * -1) + (rect.y + rect.height));\n options = new TextOption(chart.element.id + index + '_AxisLabel_' + i, pointX, pointY + (elementSize.height / 4), anchor, axis.visibleLabels[i].text);\n if (axis.edgeLabelPlacement) {\n switch (axis.edgeLabelPlacement) {\n case 'None':\n break;\n case 'Hide':\n if (((i === 0 || (axis.isInversed && i === len - 1)) && options.y > rect.y + rect.height) ||\n (((i === len - 1) || (axis.isInversed && i === 0)) && options.y - elementSize.height / 2 < rect.y)) {\n options.text = '';\n }\n break;\n case 'Shift':\n if ((i === 0 || (axis.isInversed && i === len - 1)) && options.y > rect.y + rect.height) {\n options.y = pointY = rect.y + rect.height;\n }\n else if (((i === len - 1) || (axis.isInversed && i === 0)) && (options.y - elementSize.height / 2 < rect.y)) {\n options.y = pointY = rect.y + elementSize.height / 2;\n }\n break;\n }\n }\n textElement(options, axis.labelStyle, axis.labelStyle.color || chart.themeStyle.axisLabel, labelElement);\n }\n if (!chart.delayRedraw) {\n parent.appendChild(labelElement);\n }\n else if (axis.visible) {\n this.createZoomingLabel(this.chart, labelElement, axis, index, rect);\n }\n };\n /**\n * To render the axis label border.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.drawYAxisBorder = function (axis, index, parent, rect) {\n if (axis.border.width > 0) {\n var startY = void 0;\n var pointY = void 0;\n var scrollBarHeight = axis.labelPosition === 'Outside' ? axis.scrollBarHeight : 0;\n scrollBarHeight = (axis.opposedPosition ? 1 : -1) * scrollBarHeight;\n var gap = (rect.height / axis.visibleRange.delta) * (axis.valueType === 'DateTime' ? axis.dateTimeInterval\n : axis.visibleRange.interval);\n var endY = void 0;\n var length_1 = axis.maxLabelSize.width + 10 + ((axis.tickPosition === axis.labelPosition) ?\n axis.majorTickLines.height : 0);\n var labelBorder = '';\n var ticksbwtLabel = (axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks') ? -0.5 : 0;\n var endX = ((axis.opposedPosition && axis.labelPosition === 'Inside') || (!axis.opposedPosition\n && axis.labelPosition === 'Outside')) ? rect.x - length_1 + scrollBarHeight : rect.x + length_1 + scrollBarHeight;\n for (var i = 0; i < axis.visibleLabels.length; i++) {\n pointY = valueToCoefficient(axis.visibleLabels[i].value + ticksbwtLabel, axis);\n pointY = (axis.isInversed ? (1 - pointY) : pointY) * rect.height;\n if (axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks') {\n startY = Math.floor((pointY * -1) + (rect.y + rect.height));\n endY = Math.floor((pointY * -1) - (gap) + (rect.y + rect.height));\n }\n else {\n startY = Math.floor((pointY * -1) + gap / 2 + (rect.y + rect.height));\n endY = Math.floor((pointY * -1) - gap / 2 + (rect.y + rect.height));\n }\n switch (axis.border.type) {\n case 'Rectangle':\n case 'WithoutTopBorder':\n if (startY > (rect.y + rect.height)) {\n labelBorder += ('M' + ' ' + endX + ' ' + (rect.y + rect.height) + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ');\n }\n else if (Math.floor(rect.y) > (endY)) {\n labelBorder += ('M' + ' ' + (rect.x + scrollBarHeight) + ' ' + startY + ' ' + 'L' + ' ' + endX\n + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + (rect.y) + ' ');\n }\n else {\n labelBorder += ('M' + ' ' + (rect.x + scrollBarHeight) + ' ' + startY + ' ' + 'L' + ' ' + endX +\n ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ');\n if (i === axis.visibleLabels.length - 1) {\n labelBorder += ('M' + ' ' + (rect.x + scrollBarHeight) + ' ' + endY + ' ' + 'L' + ' ' +\n endX + ' ' + endY + ' ');\n }\n }\n break;\n case 'WithoutTopandBottomBorder':\n if (!(startY > rect.y + rect.height) && !((endY) < Math.floor(rect.y))) {\n labelBorder += ('M' + ' ' + (rect.x + scrollBarHeight) + ' ' + startY + ' ' + 'L' + ' ' + endX +\n ' ' + startY + ' ' + 'M' + ' ' + endX + ' ' + endY + ' ' +\n 'L' + ' ' + (rect.x + scrollBarHeight) + ' ' + endY);\n }\n break;\n }\n }\n labelBorder += (axis.border.type === 'Rectangle') ? ('M' + ' ' + (rect.x + scrollBarHeight) + ' ' + rect.y + ' ' + 'L' + ' ' +\n (rect.x + scrollBarHeight) + ' ' + (rect.y + rect.height) + ' ') : '';\n if (labelBorder !== '') {\n this.createAxisBorderElement(axis, index, labelBorder, parent);\n }\n }\n if (axis.multiLevelLabels.length > 0 && this.chart.multiLevelLabelModule) {\n this.chart.multiLevelLabelModule.renderYAxisMultiLevelLabels(axis, index, parent, rect);\n }\n };\n CartesianAxisLayoutPanel.prototype.drawYAxisTitle = function (axis, index, parent, rect) {\n var chart = this.chart;\n var labelRotation = (axis.opposedPosition) ? 90 : -90;\n var elementSize = measureText(axis.title, axis.titleStyle);\n var padding = (axis.tickPosition === 'Inside' ? 0 : axis.majorTickLines.height + this.padding) +\n (axis.labelPosition === 'Inside' ? 0 :\n (axis.maxLabelSize.width + axis.multiLevelLabelHeight + this.padding));\n padding = axis.opposedPosition ? padding + axis.scrollBarHeight : -padding - axis.scrollBarHeight;\n var x = rect.x + padding;\n var y = rect.y + rect.height / 2;\n var options = new TextOption(chart.element.id + '_AxisTitle_' + index, x, y - this.padding, 'middle', axis.title, 'rotate(' + labelRotation + ',' + (x) + ',' + (y) + ')');\n var element = textElement(options, axis.titleStyle, axis.titleStyle.color || chart.themeStyle.axisTitle, parent);\n element.setAttribute('aria-label', axis.description || axis.title);\n element.setAttribute('tabindex', axis.tabIndex.toString());\n };\n CartesianAxisLayoutPanel.prototype.drawXAxisGridLine = function (axis, index, parent, rect) {\n var chart = this.chart;\n var tempInterval;\n var pointX = 0;\n var majorGrid = '';\n var majorTick = '';\n var minorGird = '';\n var minorTick = '';\n var minorDirection;\n var tickSize = (axis.opposedPosition) ? -axis.majorTickLines.height : axis.majorTickLines.height;\n var axisLineSize = (axis.opposedPosition) ? -axis.lineStyle.width / 2 : axis.lineStyle.width / 2;\n var scrollBarHeight = isNullOrUndefined(axis.crossesAt) ? axis.opposedPosition ? -axis.scrollBarHeight :\n axis.scrollBarHeight : 0;\n var ticksbwtLabel = (axis.valueType.indexOf('Category') > -1 && axis.labelPlacement === 'BetweenTicks') ?\n 0.5 : 0;\n var length = axis.visibleLabels.length;\n var isTickInside = axis.tickPosition === 'Inside';\n var ticks = isTickInside ? (rect.y - tickSize - axisLineSize) : (rect.y + tickSize + axisLineSize + scrollBarHeight);\n if (axis.valueType.indexOf('Category') > -1 && length > 0 && axis.labelPlacement === 'BetweenTicks') {\n length += 1;\n }\n //Gridlines\n for (var i = 0; i < length; i++) {\n if (axis.valueType !== 'DateTimeCategory') {\n tempInterval = axis.visibleLabels[i] ? axis.visibleLabels[i].value - ticksbwtLabel\n : (axis.visibleLabels[i - 1].value + axis.visibleRange.interval) - ticksbwtLabel;\n }\n else {\n tempInterval = axis.visibleLabels[i] ?\n axis.visibleLabels[i].value - ticksbwtLabel : axis.visibleRange.max;\n }\n pointX = (valueToCoefficient(tempInterval, axis) * rect.width) + rect.x;\n if (pointX >= rect.x && (rect.x + rect.width) >= pointX) {\n if (inside(tempInterval, axis.visibleRange) || this.isBorder(axis, i, pointX)) {\n majorGrid = majorGrid.concat('M ' + pointX + ' ' + (this.seriesClipRect.y + this.seriesClipRect.height) +\n ' L ' + pointX + ' ' + this.seriesClipRect.y + ' ');\n }\n majorTick = majorTick.concat('M ' + (pointX) + ' ' + (rect.y + axisLineSize + (isTickInside ? scrollBarHeight : 0))\n + ' L ' + (pointX) + ' ' + ticks + ' ');\n }\n if (axis.minorTicksPerInterval > 0 && (axis.minorGridLines.width > 0 || axis.minorTickLines.width > 0)) {\n minorDirection = this.drawAxisMinorLine(axis, tempInterval, minorGird, minorTick, rect, i);\n minorGird = minorDirection[0];\n minorTick = minorDirection[1];\n }\n }\n this.renderGridLine(axis, index, majorGrid, minorGird);\n this.renderTickLine(axis, index, majorTick, minorTick, parent);\n };\n CartesianAxisLayoutPanel.prototype.drawAxisMinorLine = function (axis, tempInterval, minorGird, minorTick, rect, labelIndex) {\n var value = tempInterval;\n var coor = 0;\n var position = 0;\n var range = axis.visibleRange;\n var isTickInside = axis.tickPosition === 'Inside';\n var direction = [];\n var tickSize = axis.opposedPosition ? -axis.minorTickLines.height : axis.minorTickLines.height;\n var logStart;\n var logEnd;\n var logInterval = 1;\n var logPosition = 1;\n var ticksX = isTickInside ? (rect.y - tickSize) : (rect.y + tickSize);\n var ticksY = isTickInside ? (rect.x + tickSize) : (rect.x - tickSize);\n if (axis.valueType === 'Logarithmic') {\n logStart = Math.pow(axis.logBase, value - range.interval);\n logEnd = Math.pow(axis.logBase, value);\n logInterval = (logEnd - logStart) / (axis.minorTicksPerInterval + 1);\n logPosition = logStart + logInterval;\n }\n if (axis.orientation === 'Horizontal') {\n for (var j = 0; j < axis.minorTicksPerInterval; j++) {\n value = this.findLogNumeric(axis, logPosition, logInterval, value, labelIndex);\n logPosition += logInterval;\n if (inside(value, range)) {\n position = ((value - range.min) / (range.max - range.min));\n position = Math.ceil((axis.isInversed ? (1 - position) : position) * rect.width);\n coor = (Math.floor(position + rect.x));\n minorGird = minorGird.concat('M' + ' ' + coor + ' ' + (this.seriesClipRect.y)\n + 'L ' + coor + ' ' + (this.seriesClipRect.y + this.seriesClipRect.height));\n coor = (Math.floor(position + rect.x));\n minorTick = minorTick.concat('M' + ' ' + coor + ' ' + (rect.y)\n + 'L ' + coor + ' ' + ticksX);\n }\n }\n }\n else {\n tickSize = axis.opposedPosition ? axis.minorTickLines.height : -axis.minorTickLines.height;\n for (var j = 0; j < axis.minorTicksPerInterval; j++) {\n value = this.findLogNumeric(axis, logPosition, logInterval, value, labelIndex);\n if (inside(value, range)) {\n position = Math.ceil(((value - range.min) / (range.max - range.min)) * rect.height) * -1;\n coor = (Math.floor(position + rect.y + rect.height));\n minorGird = minorGird.concat('M' + ' ' + (this.seriesClipRect.x) + ' ' + coor\n + 'L ' + (this.seriesClipRect.x + this.seriesClipRect.width) + ' ' + coor);\n coor = (Math.floor(position + rect.y + rect.height));\n minorTick = minorTick.concat('M' + ' ' + rect.x + ' ' + coor + 'L ' + ticksY + ' ' + coor);\n }\n logPosition += logInterval;\n }\n }\n direction.push(minorGird);\n direction.push(minorTick);\n return direction;\n };\n CartesianAxisLayoutPanel.prototype.findLogNumeric = function (axis, logPosition, logInterval, value, labelIndex) {\n var range = axis.visibleRange;\n if (axis.valueType === 'Logarithmic') {\n value = logBase(logPosition, axis.logBase);\n }\n else if (axis.valueType === 'DateTime') {\n value += axis.dateTimeInterval / (axis.minorTicksPerInterval + 1);\n }\n else if (axis.valueType === 'DateTimeCategory') {\n var padding = axis.labelPlacement === 'BetweenTicks' ? 0.5 : 0;\n value += ((axis.visibleLabels[labelIndex + 1] ?\n axis.visibleLabels[labelIndex + 1].value - padding : axis.visibleRange.max) -\n (axis.visibleLabels[labelIndex] ?\n axis.visibleLabels[labelIndex].value - padding : axis.visibleRange.min)) /\n (axis.minorTicksPerInterval + 1);\n }\n else {\n value += range.interval / (axis.minorTicksPerInterval + 1);\n }\n return value;\n };\n /**\n * To render the axis label.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.drawXAxisLabels = function (axis, index, parent, rect) {\n var chart = this.chart;\n var pointX = 0;\n var pointY = 0;\n var elementSize;\n var labelElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisLabels' + index });\n var labelPosition = axis.labelPosition;\n var islabelInside = axis.labelPosition === 'Inside';\n var isTickInside = axis.tickPosition === 'Inside';\n var isOpposed = axis.opposedPosition;\n var tickSpace = axis.labelPosition === axis.tickPosition ? axis.majorTickLines.height : 0;\n var labelPadding;\n var padding = tickSpace + this.padding + axis.lineStyle.width / 2;\n var rotateSize;\n var diffHeight;\n var angle;\n var anglePadding = ((axis.angle === 90 || axis.angle === -90)) ? -2 : 0;\n var options;\n var yLocation;\n var previousEnd = axis.isInversed ? (rect.x + rect.width) : rect.x;\n var width = 0;\n var length = axis.visibleLabels.length;\n var intervalLength;\n var label;\n var scrollBarHeight = !islabelInside && isNullOrUndefined(axis.crossesAt) && (axis.zoomFactor < 1 || axis.zoomPosition > 0)\n ? axis.scrollBarHeight : 0;\n for (var i = 0, len = length; i < len; i++) {\n label = axis.visibleLabels[i];\n pointX = (valueToCoefficient(label.value, axis) * rect.width) + rect.x;\n elementSize = label.size;\n intervalLength = rect.width / length;\n width = ((axis.labelIntersectAction === 'Trim' || axis.labelIntersectAction === 'Wrap')\n && axis.angle === 0 && elementSize.width > intervalLength) ? intervalLength : elementSize.width;\n pointX -= width / 2;\n if (islabelInside && axis.angle) {\n pointY = isOpposed ? (rect.y + padding) : (rect.y - padding);\n }\n else {\n labelPadding = (isOpposed && !islabelInside) || (!isOpposed && islabelInside) ?\n -(padding + scrollBarHeight + (axis.angle ? (3 * (elementSize.height / 4) + (2 * axis.maxLabelSize.height / 5)) :\n (label.index > 1 ? (2 * (elementSize.height / 4)) : 0)))\n : padding + scrollBarHeight + (axis.angle ? (3 * (elementSize.height / 4)) + (2 * axis.maxLabelSize.height / 5)\n : (3 * (elementSize.height / 4)));\n pointY = (rect.y + (labelPadding * label.index));\n }\n options = new TextOption(chart.element.id + index + '_AxisLabel_' + i, pointX, pointY, '');\n if (axis.edgeLabelPlacement) {\n switch (axis.edgeLabelPlacement) {\n case 'None':\n break;\n case 'Hide':\n if (((i === 0 || (axis.isInversed && i === len - 1)) && options.x < rect.x) ||\n ((i === len - 1 || (axis.isInversed && i === 0)) && (options.x + width > rect.x + rect.width))) {\n continue;\n }\n break;\n case 'Shift':\n if ((i === 0 || (axis.isInversed && i === len - 1)) && options.x < rect.x) {\n intervalLength -= (rect.x - options.x);\n options.x = pointX = rect.x;\n }\n else if ((i === len - 1 || (axis.isInversed && i === 0)) && ((options.x + width) > rect.x + rect.width)) {\n if (elementSize.width > intervalLength && axis.labelIntersectAction === 'Trim') {\n intervalLength -= (options.x + width - (rect.x + rect.width));\n }\n else {\n intervalLength = width;\n }\n options.x = pointX = rect.x + rect.width - intervalLength;\n }\n break;\n }\n }\n options.text = this.findAxisLabel(axis, label.text, intervalLength);\n if (axis.angle % 360 === 0 && axis.labelIntersectAction === 'Hide' && i !== 0 &&\n (!axis.isInversed ? options.x <= previousEnd : options.x + width >= previousEnd)) {\n continue;\n }\n previousEnd = axis.isInversed ? options.x : options.x + width;\n if (axis.angle !== 0) {\n angle = (axis.angle > 360) ? axis.angle % 360 : axis.angle;\n rotateSize = rotateTextSize(axis.labelStyle, label.text, angle, chart);\n diffHeight = islabelInside ? rotateSize.height :\n axis.maxLabelSize.height - Math.ceil(rotateSize.height - elementSize.height);\n yLocation = axis.opposedPosition ? diffHeight / 2 : -diffHeight / 2;\n options.transform = 'rotate(' + angle + ',' + (pointX + width / 2 + anglePadding) + ','\n + (pointY + yLocation) + ')';\n options.y += yLocation;\n }\n textElement(options, label.labelStyle, label.labelStyle.color || chart.themeStyle.axisLabel, labelElement, (axis.opposedPosition !== (axis.labelPosition === 'Inside'))).setAttribute('style', 'cursor: default');\n }\n if (!chart.delayRedraw) {\n parent.appendChild(labelElement);\n }\n else if (axis.visible) {\n this.createZoomingLabel(this.chart, labelElement, axis, index, rect);\n }\n };\n /**\n * To render the axis label border.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.drawXAxisBorder = function (axis, index, parent, axisRect) {\n if (axis.border.width > 0) {\n var scrollBarHeight = axis.labelPosition === 'Outside' ? axis.scrollBarHeight : 0;\n var startX = void 0;\n var startY = axisRect.y + ((axis.opposedPosition ? -1 : 1) * scrollBarHeight);\n var padding = 10;\n var pointX = void 0;\n var gap = (axisRect.width / axis.visibleRange.delta) * (axis.valueType === 'DateTime' ? axis.dateTimeInterval\n : axis.visibleRange.interval);\n var endX = void 0;\n var length_2 = axis.maxLabelSize.height +\n ((axis.tickPosition === axis.labelPosition) ? axis.majorTickLines.height : 0);\n var labelBorder = '';\n var ticksbwtLabel = (axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks') ? -0.5 : 0;\n var endY = ((axis.opposedPosition && axis.labelPosition === 'Inside') ||\n (!axis.opposedPosition && axis.labelPosition === 'Outside')) ?\n (axisRect.y + length_2 + padding + scrollBarHeight) : (axisRect.y - length_2 - padding - scrollBarHeight);\n for (var i = 0; i < axis.visibleLabels.length; i++) {\n pointX = valueToCoefficient(axis.visibleLabels[i].value + ticksbwtLabel, axis);\n pointX = (axis.isInversed ? (1 - pointX) : pointX) * axisRect.width;\n if (axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks') {\n startX = pointX + axisRect.x;\n endX = pointX + (gap) + axisRect.x;\n }\n else {\n startX = pointX - gap / 2 + axisRect.x;\n endX = pointX + gap / 2 + axisRect.x;\n }\n switch (axis.border.type) {\n case 'Rectangle':\n case 'WithoutTopBorder':\n if (startX < axisRect.x) {\n labelBorder += ('M' + ' ' + axisRect.x + ' ' + endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ');\n }\n else if (Math.floor(endX) > axisRect.width + axisRect.x) {\n labelBorder += ('M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' +\n 'L' + ' ' + (axisRect.width + axisRect.x) + ' ' + endY + ' ');\n }\n else {\n labelBorder += ('M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' +\n endY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ');\n if (i === axis.visibleLabels.length - 1) {\n labelBorder += ('M' + ' ' + endX + ' ' + startY + ' ' + 'L' + ' ' + endX + ' ' + endY + ' ' +\n 'M ' + endX + ' ' + endY + ' L ' + (axisRect.width + axisRect.x) + ' ' + endY);\n }\n }\n break;\n case 'WithoutTopandBottomBorder':\n if (!(startX < axisRect.x) && !(Math.floor(endX) > axisRect.width + axisRect.x)) {\n labelBorder += ('M' + ' ' + startX + ' ' + startY + ' ' + 'L' + ' ' + startX + ' ' + endY + ' ' +\n 'M ' + endX + ' ' + startY + ' L ' + endX + ' ' + endY);\n }\n break;\n }\n }\n labelBorder += (axis.border.type === 'Rectangle' ? ('M ' + ' ' + axisRect.x + ' ' + startY + 'L' + ' ' +\n (axisRect.x + axisRect.width) + ' ' + startY) : '');\n if (labelBorder !== '') {\n this.createAxisBorderElement(axis, index, labelBorder, parent);\n }\n }\n if (this.chart.multiLevelLabelModule && axis.multiLevelLabels.length > 0) {\n this.chart.multiLevelLabelModule.renderXAxisMultiLevelLabels(axis, index, parent, axisRect);\n }\n };\n /**\n * To create border element for axis.\n * @return {void}\n * @private\n */\n CartesianAxisLayoutPanel.prototype.createAxisBorderElement = function (axis, index, labelBorder, parent) {\n var borderElement = this.chart.renderer.drawPath(new PathOption(this.chart.element.id + '_BorderLine_' + index, 'transparent', axis.border.width, axis.border.color || this.chart.themeStyle.axisLine, 1, '', labelBorder));\n borderElement.setAttribute('style', 'pointer-events: none');\n parent.appendChild(borderElement);\n };\n CartesianAxisLayoutPanel.prototype.findAxisLabel = function (axis, label, width) {\n switch (axis.labelIntersectAction) {\n case 'Trim':\n return (axis.angle === 0) ? textTrim(width, label, axis.labelStyle) : label;\n default:\n return label;\n }\n };\n CartesianAxisLayoutPanel.prototype.drawXAxisTitle = function (axis, index, parent, rect) {\n var chart = this.chart;\n var elementSize = measureText(axis.title, axis.titleStyle);\n var scrollBarHeight = isNullOrUndefined(axis.crossesAt) ? axis.scrollBarHeight : 0;\n var padding = (axis.tickPosition === 'Inside' ? 0 : axis.majorTickLines.height + this.padding) +\n (axis.labelPosition === 'Inside' ? 0 :\n axis.maxLabelSize.height + axis.multiLevelLabelHeight + this.padding);\n padding = axis.opposedPosition ? -(padding + elementSize.height / 4 + scrollBarHeight) : (padding + (3 *\n elementSize.height / 4) + scrollBarHeight);\n var options = new TextOption(chart.element.id + '_AxisTitle_' + index, rect.x + rect.width / 2, rect.y + padding, 'middle', axis.title);\n var element = textElement(options, axis.titleStyle, axis.titleStyle.color || chart.themeStyle.axisTitle, parent);\n element.setAttribute('aria-label', axis.description || axis.title);\n element.setAttribute('tabindex', axis.tabIndex.toString());\n };\n CartesianAxisLayoutPanel.prototype.renderTickLine = function (axis, index, majorTick, minorTick, parent) {\n var options;\n var chart = this.chart;\n if (axis.majorTickLines.width > 0 && axis.visible) {\n options = new PathOption(chart.element.id + '_MajorTickLine_' + index, 'transparent', axis.majorTickLines.width, axis.majorTickLines.color || chart.themeStyle.majorTickLine, null, null, majorTick);\n this.htmlObject = chart.renderer.drawPath(options);\n parent.appendChild(this.htmlObject);\n }\n if (axis.minorTickLines.width > 0 && axis.visible) {\n options = new PathOption(chart.element.id + '_MinorTickLine_' + index, 'transparent', axis.minorTickLines.width, axis.minorTickLines.color || chart.themeStyle.minorTickLine, null, null, minorTick);\n this.htmlObject = chart.renderer.drawPath(options);\n parent.appendChild(this.htmlObject);\n }\n };\n CartesianAxisLayoutPanel.prototype.renderGridLine = function (axis, index, majorGrid, minorGird) {\n var chart = this.chart;\n var options;\n if (axis.majorGridLines.width > 0) {\n options = new PathOption(chart.element.id + '_MajorGridLine_' + index, 'transparent', axis.majorGridLines.width, axis.majorGridLines.color || chart.themeStyle.majorGridLine, null, axis.majorGridLines.dashArray, majorGrid);\n this.htmlObject = chart.renderer.drawPath(options);\n this.element.appendChild(this.htmlObject);\n }\n if (axis.minorGridLines.width > 0) {\n options = new PathOption(chart.element.id + '_MinorGridLine_' + index, 'transparent', axis.minorGridLines.width, axis.minorGridLines.color || chart.themeStyle.minorGridLine, null, axis.minorGridLines.dashArray, minorGird);\n this.htmlObject = chart.renderer.drawPath(options);\n this.element.appendChild(this.htmlObject);\n }\n };\n CartesianAxisLayoutPanel.prototype.findParentNode = function (chart, label, axis, index) {\n if (axis.crossAt === null) {\n return document.getElementById(chart.element.id + 'AxisGroup' + index + 'Inside');\n }\n if (document.getElementById(chart.element.id + 'AxisGroup' + index + 'Inside').contains(document.getElementById(label.id))) {\n return document.getElementById(chart.element.id + 'AxisGroup' + index + 'Inside');\n }\n else {\n return document.getElementById(chart.element.id + 'AxisGroup' + index + 'Outside');\n }\n };\n CartesianAxisLayoutPanel.prototype.createZoomingLabel = function (chart, labelElement, axis, index, rect) {\n var parentNode = this.findParentNode(chart, labelElement, axis, index);\n labelElement.setAttribute('opacity', '0.3');\n var zoomElement = chart.renderer.createGroup({\n id: chart.element.id + 'AxisLabels_Zoom' + index\n });\n zoomElement = createZoomingLabels(chart, axis, zoomElement, index, axis.orientation === 'Vertical', rect);\n parentNode.replaceChild(labelElement, document.getElementById(labelElement.id));\n if (getElement(chart.element.id + 'AxisLabels_Zoom' + index)) {\n parentNode.replaceChild(zoomElement, document.getElementById(zoomElement.id));\n }\n else {\n parentNode.appendChild(zoomElement);\n }\n };\n return CartesianAxisLayoutPanel;\n}());\nexport { CartesianAxisLayoutPanel };\n","import { withInBounds, PointData, Rect, getValueXByPoint, getValueYByPoint } from '../../common/utils/helper';\n/**\n * To get the data on mouse move.\n * @private\n */\nvar ChartData = /** @class */ (function () {\n /**\n * Constructor for the data.\n * @private\n */\n function ChartData(chart) {\n /** @private */\n this.currentPoints = [];\n /** @private */\n this.previousPoints = [];\n this.chart = chart;\n this.lierIndex = 0;\n }\n /**\n * Method to get the Data.\n * @private\n */\n ChartData.prototype.getData = function () {\n var chart = this.chart;\n var point = null;\n var series = null;\n var width;\n var height;\n for (var len = chart.visibleSeries.length, i = len - 1; i >= 0; i--) {\n series = chart.visibleSeries[i];\n width = (series.type === 'Scatter' || series.drawType === 'Scatter' || (!series.isRectSeries && series.marker.visible))\n ? (series.marker.height + 5) / 2 : 0;\n height = (series.type === 'Scatter' || series.drawType === 'Scatter' || (!series.isRectSeries && series.marker.visible))\n ? (series.marker.width + 5) / 2 : 0;\n if (series.visible && withInBounds(chart.mouseX, chart.mouseY, series.clipRect, width, height)) {\n point = this.getRectPoint(series, series.clipRect, chart.mouseX, chart.mouseY);\n }\n if (point) {\n return new PointData(point, series);\n }\n }\n return new PointData(point, series);\n };\n ChartData.prototype.isSelected = function (chart) {\n return (chart.selectionMode.indexOf('Drag') > -1 && chart.selectionModule && chart.selectionModule.rectPoints !== null);\n };\n ChartData.prototype.getRectPoint = function (series, rect, x, y) {\n var currentRect;\n var fromCenterX;\n var fromCenterY;\n var clickAngle;\n var arcAngle = 0;\n var startAngle;\n var endAngle;\n var distanceFromCenter;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n if (!point.regionData) {\n if (!point.regions || !point.regions.length) {\n continue;\n }\n }\n if (point.regionData && this.chart.chartAreaType === 'PolarRadar' && series.drawType.indexOf('Column') > -1) {\n fromCenterX = x - (series.clipRect.width / 2 + series.clipRect.x);\n fromCenterY = y - (series.clipRect.height / 2 + series.clipRect.y);\n arcAngle = 2 * Math.PI * (point.regionData.currentXPosition < 0 ? 1 + point.regionData.currentXPosition\n : point.regionData.currentXPosition);\n clickAngle = (Math.atan2(fromCenterY, fromCenterX) + 0.5 * Math.PI - arcAngle) % (2 * Math.PI);\n clickAngle = clickAngle < 0 ? 2 * Math.PI + clickAngle : clickAngle;\n clickAngle = clickAngle + 2 * Math.PI * series.chart.primaryXAxis.startAngle;\n startAngle = point.regionData.startAngle;\n startAngle -= arcAngle;\n startAngle = startAngle < 0 ? 2 * Math.PI + startAngle : startAngle;\n endAngle = point.regionData.endAngle;\n endAngle -= arcAngle;\n endAngle = endAngle < 0 ? 2 * Math.PI + endAngle : endAngle;\n distanceFromCenter = Math.sqrt(Math.pow(Math.abs(fromCenterX), 2) + Math.pow(Math.abs(fromCenterY), 2));\n if (clickAngle >= startAngle && clickAngle <= endAngle &&\n (((distanceFromCenter >= point.regionData.innerRadius && distanceFromCenter <= point.regionData.radius) ||\n (distanceFromCenter <= point.regionData.innerRadius && distanceFromCenter >= point.regionData.radius))\n && distanceFromCenter <= series.chart.radius)) {\n return point;\n }\n }\n else if (this.checkRegionContainsPoint(point.regions, rect, x, y)) {\n return point;\n }\n }\n return null;\n };\n /**\n * Checks whether the region contains a point\n */\n ChartData.prototype.checkRegionContainsPoint = function (regionRect, rect, x, y) {\n var _this = this;\n return regionRect.some(function (region, index) {\n _this.lierIndex = index;\n return withInBounds(x, y, new Rect((_this.chart.chartAreaType === 'Cartesian' ? rect.x : 0) + region.x, (_this.chart.chartAreaType === 'Cartesian' ? rect.y : 0) + region.y, region.width, region.height));\n });\n };\n ChartData.prototype.getClosest = function (series, value) {\n var xData = series.xData;\n var closest;\n if (value >= series.xMin - 0.5 && value <= series.xMax + 0.5) {\n for (var _i = 0, xData_1 = xData; _i < xData_1.length; _i++) {\n var data = xData_1[_i];\n if (closest == null || Math.abs(data - value) < Math.abs(closest - value)) {\n closest = data;\n }\n }\n }\n return closest;\n };\n ChartData.prototype.getClosestX = function (chart, series) {\n var value;\n var rect = series.clipRect;\n if (!chart.requireInvertedAxis) {\n value = getValueXByPoint(chart.mouseX - rect.x, rect.width, series.xAxis);\n }\n else {\n value = getValueYByPoint(chart.mouseY - rect.y, rect.height, series.xAxis);\n }\n var closest = this.getClosest(series, value);\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n if (closest === point.xValue && point.visible) {\n return new PointData(point, series);\n }\n }\n return null;\n };\n return ChartData;\n}());\nexport { ChartData };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty, Complex, Collection } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, getValue } from '@syncfusion/ej2-base';\nimport { StackValues, RectOption } from '../../common/utils/helper';\nimport { firstToLowerCase, Rect, CircleOption } from '../../common/utils/helper';\nimport { Border, Font, Margin, Animation, EmptyPointSettings, CornerRadius, Connector } from '../../common/model/base';\nimport { DataUtil } from '@syncfusion/ej2-data';\nimport { seriesRender } from '../../common/model/constants';\n/**\n * Configures the data label in the series.\n */\nvar DataLabelSettings = /** @class */ (function (_super) {\n __extends(DataLabelSettings, _super);\n function DataLabelSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], DataLabelSettings.prototype, \"visible\", void 0);\n __decorate([\n Property(null)\n ], DataLabelSettings.prototype, \"name\", void 0);\n __decorate([\n Property('transparent')\n ], DataLabelSettings.prototype, \"fill\", void 0);\n __decorate([\n Property(1)\n ], DataLabelSettings.prototype, \"opacity\", void 0);\n __decorate([\n Property('Auto')\n ], DataLabelSettings.prototype, \"position\", void 0);\n __decorate([\n Property(5)\n ], DataLabelSettings.prototype, \"rx\", void 0);\n __decorate([\n Property(5)\n ], DataLabelSettings.prototype, \"ry\", void 0);\n __decorate([\n Property('Center')\n ], DataLabelSettings.prototype, \"alignment\", void 0);\n __decorate([\n Complex({ width: null, color: null }, Border)\n ], DataLabelSettings.prototype, \"border\", void 0);\n __decorate([\n Complex({ left: 5, right: 5, top: 5, bottom: 5 }, Margin)\n ], DataLabelSettings.prototype, \"margin\", void 0);\n __decorate([\n Complex({ size: '11px', color: null }, Font)\n ], DataLabelSettings.prototype, \"font\", void 0);\n __decorate([\n Property(null)\n ], DataLabelSettings.prototype, \"template\", void 0);\n return DataLabelSettings;\n}(ChildProperty));\nexport { DataLabelSettings };\n/**\n * Configures the marker in the series.\n */\nvar MarkerSettings = /** @class */ (function (_super) {\n __extends(MarkerSettings, _super);\n function MarkerSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], MarkerSettings.prototype, \"visible\", void 0);\n __decorate([\n Property('Circle')\n ], MarkerSettings.prototype, \"shape\", void 0);\n __decorate([\n Property('')\n ], MarkerSettings.prototype, \"imageUrl\", void 0);\n __decorate([\n Property(5)\n ], MarkerSettings.prototype, \"height\", void 0);\n __decorate([\n Property(5)\n ], MarkerSettings.prototype, \"width\", void 0);\n __decorate([\n Complex({ width: 2, color: null }, Border)\n ], MarkerSettings.prototype, \"border\", void 0);\n __decorate([\n Property(null)\n ], MarkerSettings.prototype, \"fill\", void 0);\n __decorate([\n Property(1)\n ], MarkerSettings.prototype, \"opacity\", void 0);\n __decorate([\n Complex({}, DataLabelSettings)\n ], MarkerSettings.prototype, \"dataLabel\", void 0);\n return MarkerSettings;\n}(ChildProperty));\nexport { MarkerSettings };\n/**\n * Points model for the series.\n * @private\n */\nvar Points = /** @class */ (function () {\n function Points() {\n this.symbolLocations = null;\n this.regions = null;\n this.regionData = null;\n this.marker = {\n visible: true\n };\n }\n return Points;\n}());\nexport { Points };\n/**\n * Defines the behavior of the Trendlines\n */\nvar Trendline = /** @class */ (function (_super) {\n __extends(Trendline, _super);\n function Trendline() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.clipRect = new Rect(0, 0, 0, 0);\n return _this;\n }\n /** @private */\n Trendline.prototype.setDataSource = function (series, chart) {\n if (series) {\n this.points = series.points;\n }\n var type = firstToLowerCase(this.type);\n chart.trendLineModule.initDataSource(this, chart);\n chart.visibleSeriesCount++;\n };\n __decorate([\n Property('')\n ], Trendline.prototype, \"name\", void 0);\n __decorate([\n Property('Linear')\n ], Trendline.prototype, \"type\", void 0);\n __decorate([\n Property(2)\n ], Trendline.prototype, \"period\", void 0);\n __decorate([\n Property(2)\n ], Trendline.prototype, \"polynomialOrder\", void 0);\n __decorate([\n Property(0)\n ], Trendline.prototype, \"backwardForecast\", void 0);\n __decorate([\n Property(0)\n ], Trendline.prototype, \"forwardForecast\", void 0);\n __decorate([\n Complex({}, Animation)\n ], Trendline.prototype, \"animation\", void 0);\n __decorate([\n Complex({}, MarkerSettings)\n ], Trendline.prototype, \"marker\", void 0);\n __decorate([\n Property(true)\n ], Trendline.prototype, \"enableTooltip\", void 0);\n __decorate([\n Property(null)\n ], Trendline.prototype, \"intercept\", void 0);\n __decorate([\n Property('')\n ], Trendline.prototype, \"fill\", void 0);\n __decorate([\n Property(1)\n ], Trendline.prototype, \"width\", void 0);\n __decorate([\n Property('SeriesType')\n ], Trendline.prototype, \"legendShape\", void 0);\n return Trendline;\n}(ChildProperty));\nexport { Trendline };\n/**\n * Configures Error bar in series.\n */\nvar ErrorBarCapSettings = /** @class */ (function (_super) {\n __extends(ErrorBarCapSettings, _super);\n function ErrorBarCapSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], ErrorBarCapSettings.prototype, \"width\", void 0);\n __decorate([\n Property(10)\n ], ErrorBarCapSettings.prototype, \"length\", void 0);\n __decorate([\n Property(null)\n ], ErrorBarCapSettings.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], ErrorBarCapSettings.prototype, \"opacity\", void 0);\n return ErrorBarCapSettings;\n}(ChildProperty));\nexport { ErrorBarCapSettings };\nvar ChartSegment = /** @class */ (function (_super) {\n __extends(ChartSegment, _super);\n function ChartSegment() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], ChartSegment.prototype, \"value\", void 0);\n __decorate([\n Property(null)\n ], ChartSegment.prototype, \"color\", void 0);\n __decorate([\n Property('0')\n ], ChartSegment.prototype, \"dashArray\", void 0);\n return ChartSegment;\n}(ChildProperty));\nexport { ChartSegment };\nvar ErrorBarSettings = /** @class */ (function (_super) {\n __extends(ErrorBarSettings, _super);\n function ErrorBarSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], ErrorBarSettings.prototype, \"visible\", void 0);\n __decorate([\n Property('Fixed')\n ], ErrorBarSettings.prototype, \"type\", void 0);\n __decorate([\n Property('Both')\n ], ErrorBarSettings.prototype, \"direction\", void 0);\n __decorate([\n Property('Vertical')\n ], ErrorBarSettings.prototype, \"mode\", void 0);\n __decorate([\n Property(null)\n ], ErrorBarSettings.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], ErrorBarSettings.prototype, \"verticalError\", void 0);\n __decorate([\n Property(1)\n ], ErrorBarSettings.prototype, \"width\", void 0);\n __decorate([\n Property(1)\n ], ErrorBarSettings.prototype, \"horizontalError\", void 0);\n __decorate([\n Property(3)\n ], ErrorBarSettings.prototype, \"verticalPositiveError\", void 0);\n __decorate([\n Property(3)\n ], ErrorBarSettings.prototype, \"verticalNegativeError\", void 0);\n __decorate([\n Property(1)\n ], ErrorBarSettings.prototype, \"horizontalPositiveError\", void 0);\n __decorate([\n Property(1)\n ], ErrorBarSettings.prototype, \"horizontalNegativeError\", void 0);\n __decorate([\n Complex(null, ErrorBarCapSettings)\n ], ErrorBarSettings.prototype, \"errorBarCap\", void 0);\n return ErrorBarSettings;\n}(ChildProperty));\nexport { ErrorBarSettings };\n/**\n * Defines the common behavior of Series and Technical Indicators\n */\nvar SeriesBase = /** @class */ (function (_super) {\n __extends(SeriesBase, _super);\n function SeriesBase() {\n /**\n * The DataSource field that contains the x value.\n * It is applicable for series and technical indicators\n * @default ''\n */\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.currentViewData = [];\n /** @private */\n _this.clipRect = new Rect(0, 0, 0, 0);\n /** @private */\n _this.seriesType = 'XY';\n return _this;\n }\n /**\n * Process data for the series.\n * @hidden\n */\n SeriesBase.prototype.processJsonData = function () {\n var i = 0;\n var point = new Points();\n var xName = (this instanceof Series && this.type === 'Histogram') ? 'x' : this.xName;\n var textMappingName = this instanceof Series && this.marker.dataLabel.name ?\n this.marker.dataLabel.name : '';\n if (this instanceof Series && (this.type === 'Waterfall' || this.type === 'Histogram')) {\n this.currentViewData = this.chart[firstToLowerCase(this.type) + 'SeriesModule'].\n processInternalData(this.currentViewData, this);\n }\n var len = Object.keys(this.currentViewData).length;\n this.points = [];\n this.xMin = Infinity;\n this.xMax = -Infinity;\n this.yMin = Infinity;\n this.yMax = -Infinity;\n this.sizeMax = -Infinity;\n this.getSeriesType();\n if (this.xAxis.valueType === 'Category') {\n while (i < len) {\n point = this.dataPoint(i, textMappingName, xName);\n this.pushCategoryData(point, i, point.x);\n this.pushData(point, i);\n this.setEmptyPoint(point, i);\n i++;\n }\n }\n else if (this.xAxis.valueType.indexOf('DateTime') > -1) {\n var option = {\n skeleton: 'full',\n type: 'dateTime'\n };\n var dateParser = this.chart.intl.getDateParser(option);\n var dateFormatter = this.chart.intl.getDateFormat(option);\n while (i < len) {\n point = this.dataPoint(i, textMappingName, xName);\n point.x = new Date(DataUtil.parse.parseJson({ val: point.x }).val);\n if (this.xAxis.valueType === 'DateTime') {\n point.xValue = Date.parse(dateParser(dateFormatter(point.x)));\n }\n else {\n this.pushCategoryData(point, i, Date.parse(dateParser(dateFormatter(point.x))).toString());\n }\n this.pushData(point, i);\n this.setEmptyPoint(point, i);\n i++;\n }\n }\n else {\n while (i < len) {\n point = this.dataPoint(i, textMappingName, xName);\n point.xValue = point.x;\n this.pushData(point, i);\n this.setEmptyPoint(point, i);\n i++;\n }\n }\n if (this instanceof Series) {\n if (this.type.indexOf('Spline') > -1 || (this.drawType.indexOf('Spline') > -1 && this.chart.chartAreaType === 'PolarRadar')) {\n var isArea = (this.type.indexOf('Area') > -1 || this.drawType === 'Area');\n this.chart['spline' + (isArea ? 'Area' : '') + 'SeriesModule'].findSplinePoint(this);\n }\n }\n };\n SeriesBase.prototype.pushData = function (point, i) {\n point.index = i;\n point.yValue = point.y;\n // To find the min, max for the axis range.\n this.xMin = Math.min(this.xMin, point.xValue);\n this.xMax = Math.max(this.xMax, point.xValue);\n this.xData.push(point.xValue);\n };\n /** @private */\n SeriesBase.prototype.dataPoint = function (i, textMappingName, xName) {\n var point;\n this.points[i] = new Points();\n point = this.points[i];\n var currentViewData = this.currentViewData;\n point.x = getValue(xName, currentViewData[i]);\n point.high = getValue(this.high, currentViewData[i]);\n point.low = getValue(this.low, currentViewData[i]);\n point.open = getValue(this.open, currentViewData[i]);\n point.close = getValue(this.close, currentViewData[i]);\n point.volume = getValue(this.volume, currentViewData[i]);\n point.interior = getValue(this.pointColorMapping, currentViewData[i]);\n if (this instanceof Series) {\n point.y = getValue(this.yName, currentViewData[i]);\n point.size = getValue(this.size, currentViewData[i]);\n point.text = getValue(textMappingName, currentViewData[i]);\n point.tooltip = getValue(this.tooltipMappingName, currentViewData[i]);\n }\n return point;\n };\n /**\n * To set empty point value based on empty point mode\n * @private\n */\n SeriesBase.prototype.setEmptyPoint = function (point, i) {\n if (!this.findVisibility(point)) {\n point.visible = true;\n return null;\n }\n point.isEmpty = true;\n var mode = this instanceof Series ? this.emptyPointSettings.mode : 'Drop';\n switch (mode) {\n case 'Zero':\n point.visible = true;\n if (this instanceof Series && this.seriesType.indexOf('HighLow') > -1) {\n point.high = point.low = 0;\n if (this.seriesType.indexOf('HighLowOpenClose') > -1) {\n point.open = point.close = 0;\n }\n }\n else {\n point.y = point.yValue = this.yData[i] = 0;\n }\n break;\n case 'Average':\n if (this instanceof Series) {\n if (this.seriesType.indexOf('HighLow') > -1) {\n point.high = (isNullOrUndefined(point.high) || isNaN(+point.high)) ? this.getAverage(this.high, i) : point.high;\n point.low = (isNullOrUndefined(point.low) || isNaN(+point.low)) ? this.getAverage(this.low, i) : point.low;\n if (this.seriesType.indexOf('HighLowOpenClose') > -1) {\n point.open = (isNullOrUndefined(point.open) || isNaN(+point.open)) ? this.getAverage(this.open, i) : point.open;\n point.close = (isNullOrUndefined(point.close) || isNaN(+point.close)) ? this.getAverage(this.close, i) :\n point.close;\n }\n }\n else {\n point.y = point.yValue = this.yData[i] = this.getAverage(this.yName, i);\n }\n }\n point.visible = true;\n break;\n case 'Drop':\n case 'Gap':\n this.yData[i] = null;\n point.visible = false;\n break;\n }\n };\n SeriesBase.prototype.findVisibility = function (point) {\n var type = this instanceof Series ? this.seriesType : 'HighLowOpenClose';\n var yValues;\n switch (type) {\n case 'XY':\n this.setXYMinMax(point.yValue);\n this.yData.push(point.yValue);\n if (this instanceof Series && this.type === 'Bubble') {\n this.sizeMax = Math.max(this.sizeMax, (isNullOrUndefined(point.size) || isNaN(+point.size)) ? this.sizeMax\n : point.size);\n }\n return isNullOrUndefined(point.x) || (isNullOrUndefined(point.y) || isNaN(+point.y));\n case 'HighLow':\n this.setHiloMinMax(point.high, point.low);\n return isNullOrUndefined(point.x) || (isNullOrUndefined(point.low) || isNaN(+point.low)) ||\n (isNullOrUndefined(point.high) || isNaN(+point.high));\n case 'HighLowOpenClose':\n this.setHiloMinMax(point.high, point.low);\n return isNullOrUndefined(point.x) || (isNullOrUndefined(point.low) || isNaN(+point.low)) ||\n (isNullOrUndefined(point.open) || isNaN(+point.open)) || (isNullOrUndefined(point.close) || isNaN(+point.close))\n || (isNullOrUndefined(point.high) || isNaN(+point.high));\n case 'BoxPlot':\n yValues = (point.y || [null]).filter(function (value) {\n return !isNullOrUndefined(value) && !isNaN(value);\n }).sort(function (a, b) {\n return a - b;\n });\n point.y = yValues;\n this.yMin = Math.min(this.yMin, Math.min.apply(Math, yValues));\n this.yMax = Math.max(this.yMax, Math.max.apply(Math, yValues));\n return !yValues.length;\n }\n };\n /**\n * To get Y min max for the provided point seriesType XY\n */\n SeriesBase.prototype.setXYMinMax = function (yValue) {\n this.yMin = Math.min(this.yMin, (isNullOrUndefined(yValue) || isNaN(yValue)) ? this.yMin : yValue);\n this.yMax = Math.max(this.yMax, (isNullOrUndefined(yValue) || isNaN(yValue)) ? this.yMax : yValue);\n };\n /**\n * To get Y min max for the provided point seriesType XY\n */\n SeriesBase.prototype.setHiloMinMax = function (high, low) {\n this.yMin = Math.min(this.yMin, Math.min((isNullOrUndefined(low) || isNaN(low)) ? this.yMin : low, (isNullOrUndefined(high) || isNaN(high)) ? this.yMin : high));\n this.yMax = Math.max(this.yMax, Math.max((isNullOrUndefined(low) || isNaN(low)) ? this.yMax : low, (isNullOrUndefined(high) || isNaN(high)) ? this.yMax : high));\n };\n /**\n * Finds the type of the series\n * @private\n */\n SeriesBase.prototype.getSeriesType = function () {\n var type;\n if (this instanceof Series) {\n var seriesType = this.chart.chartAreaType === 'PolarRadar' ? this.drawType : this.type;\n if (seriesType) {\n switch (seriesType) {\n case 'RangeColumn':\n case 'RangeArea':\n case 'Hilo':\n type = 'HighLow';\n break;\n case 'HiloOpenClose':\n case 'Candle':\n type = 'HighLowOpenClose';\n break;\n case 'BoxAndWhisker':\n type = 'BoxPlot';\n break;\n default:\n type = 'XY';\n }\n }\n }\n this.seriesType = type;\n };\n /** @private */\n SeriesBase.prototype.pushCategoryData = function (point, index, pointX) {\n if (!this.xAxis.isIndexed) {\n if (this.xAxis.labels.indexOf(pointX) < 0) {\n this.xAxis.labels.push(pointX);\n }\n point.xValue = this.xAxis.labels.indexOf(pointX);\n }\n else {\n this.xAxis.labels[index] ? this.xAxis.labels[index] += ', ' + pointX :\n this.xAxis.labels.push(pointX);\n point.xValue = index;\n }\n };\n /**\n * To find average of given property\n */\n SeriesBase.prototype.getAverage = function (member, i, data) {\n if (data === void 0) { data = this.currentViewData; }\n var previous = data[i - 1] ? (data[i - 1][member] || 0) : 0;\n var next = data[i + 1] ? (data[i + 1][member] || 0) : 0;\n return (previous + next) / 2;\n };\n /**\n * To find the control points for spline.\n * @return {void}\n * @private\n */\n SeriesBase.prototype.refreshDataManager = function (chart) {\n var _this = this;\n this.chart = chart;\n var dateSource = this.dataSource || chart.dataSource;\n if (isNullOrUndefined(this.query) && !isNullOrUndefined(dateSource)) {\n this.dataManagerSuccess({\n result: dateSource, count: dateSource.length\n }, chart, false);\n return;\n }\n var dataManager = this.dataModule.getData(this.dataModule.generateQuery().requiresCount());\n dataManager.then(function (e) { return _this.dataManagerSuccess(e, chart); });\n };\n SeriesBase.prototype.dataManagerSuccess = function (e, chart, isRemoteData) {\n if (isRemoteData === void 0) { isRemoteData = true; }\n this.currentViewData = e.result !== '' ? e.result : [];\n if (this instanceof Series) {\n var argsData = {\n name: seriesRender, series: this, data: this.currentViewData, fill: this.interior\n };\n this.chart.trigger(seriesRender, argsData);\n this.interior = argsData.fill;\n this.currentViewData = argsData.data;\n }\n this.processJsonData();\n this.recordsCount = e.count;\n this.refreshChart(isRemoteData);\n };\n SeriesBase.prototype.refreshChart = function (isRemoteData) {\n var chart = this.chart;\n if (this instanceof Series) {\n chart.visibleSeriesCount += isRemoteData ? 1 : 0;\n }\n chart.refreshTechnicalIndicator(this);\n if (this instanceof Series && this.category !== 'TrendLine') {\n for (var _i = 0, _a = this.trendlines; _i < _a.length; _i++) {\n var trendline = _a[_i];\n trendline.setDataSource(this, chart);\n }\n }\n //if (chart.visibleSeries.length === (chart.visibleSeriesCount - chart.indicators.length)) {\n if (chart.visibleSeries.length === (chart.visibleSeriesCount)) {\n chart.refreshBound();\n chart.trigger('loaded', { chart: chart });\n }\n if (this instanceof Series) {\n chart.visibleSeriesCount += isRemoteData ? 0 : 1;\n }\n };\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"xName\", void 0);\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"high\", void 0);\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"low\", void 0);\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"open\", void 0);\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"close\", void 0);\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"volume\", void 0);\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"pointColorMapping\", void 0);\n __decorate([\n Property(null)\n ], SeriesBase.prototype, \"xAxisName\", void 0);\n __decorate([\n Property(null)\n ], SeriesBase.prototype, \"yAxisName\", void 0);\n __decorate([\n Complex(null, Animation)\n ], SeriesBase.prototype, \"animation\", void 0);\n __decorate([\n Property(null)\n ], SeriesBase.prototype, \"fill\", void 0);\n __decorate([\n Property(1)\n ], SeriesBase.prototype, \"width\", void 0);\n __decorate([\n Property('0')\n ], SeriesBase.prototype, \"dashArray\", void 0);\n __decorate([\n Property('')\n ], SeriesBase.prototype, \"dataSource\", void 0);\n __decorate([\n Property()\n ], SeriesBase.prototype, \"query\", void 0);\n __decorate([\n Collection([], ChartSegment)\n ], SeriesBase.prototype, \"segments\", void 0);\n __decorate([\n Property('X')\n ], SeriesBase.prototype, \"segmentAxis\", void 0);\n return SeriesBase;\n}(ChildProperty));\nexport { SeriesBase };\n/**\n * Configures the series in charts.\n */\nvar Series = /** @class */ (function (_super) {\n __extends(Series, _super);\n // tslint:disable-next-line:no-any\n function Series(parent, propName, defaultValue, isArray) {\n var _this = _super.call(this, parent, propName, defaultValue, isArray) || this;\n _this.visibleSeriesCount = 0;\n /** @private */\n _this.category = 'Series';\n /** @private */\n _this.isRectSeries = false;\n /** @private */\n _this.drawPoints = [];\n /** @private */\n _this.delayedAnimation = false;\n return _this;\n }\n /**\n * Refresh the axis label.\n * @return {boolean}\n * @private\n */\n Series.prototype.refreshAxisLabel = function () {\n if (this.xAxis.valueType !== 'Category') {\n return null;\n }\n this.xAxis.labels = [];\n for (var _i = 0, _a = this.xAxis.series; _i < _a.length; _i++) {\n var item = _a[_i];\n if (item.visible) {\n item.xMin = Infinity;\n item.xMax = -Infinity;\n for (var _b = 0, _c = item.points; _b < _c.length; _b++) {\n var point = _c[_b];\n item.pushCategoryData(point, point.index, point.x);\n item.xMin = Math.min(item.xMin, point.xValue);\n item.xMax = Math.max(item.xMax, point.xValue);\n }\n }\n }\n };\n /**\n * To get the series collection.\n * @return {void}\n * @private\n */\n Series.prototype.findSeriesCollection = function (column, row, isStack) {\n var seriesCollection = [];\n for (var _i = 0, _a = row.axes; _i < _a.length; _i++) {\n var rowAxis = _a[_i];\n for (var _b = 0, _c = rowAxis.series; _b < _c.length; _b++) {\n var rowSeries = _c[_b];\n for (var _d = 0, _e = column.axes; _d < _e.length; _d++) {\n var axis = _e[_d];\n for (var _f = 0, _g = axis.series; _f < _g.length; _f++) {\n var series = _g[_f];\n if (series === rowSeries && series.visible && this.rectSeriesInChart(series, isStack)) {\n seriesCollection.push(series);\n }\n }\n }\n }\n }\n return seriesCollection;\n };\n /**\n * To get the column type series.\n * @return {void}\n * @private\n */\n Series.prototype.rectSeriesInChart = function (series, isStack) {\n var type = (series.type).toLowerCase();\n return (type.indexOf('column') !== -1 || type.indexOf('bar') !== -1 || type.indexOf('histogram') !== -1 ||\n type.indexOf('hiloopenclose') !== -1 || type.indexOf('candle') !== -1 ||\n type.indexOf('hilo') !== -1 || series.drawType.indexOf('Column') !== -1 ||\n type.indexOf('waterfall') !== -1 || type.indexOf('boxandwhisker') !== -1 || isStack);\n };\n /**\n * To calculate the stacked values.\n * @return {void}\n * @private\n */\n Series.prototype.calculateStackedValue = function (isStacking100, chart) {\n var axisSeries;\n for (var _i = 0, _a = chart.columns; _i < _a.length; _i++) {\n var columnItem = _a[_i];\n for (var _b = 0, _c = chart.rows; _b < _c.length; _b++) {\n var item = _c[_b];\n this.calculateStackingValues(this.findSeriesCollection(columnItem, item, true), isStacking100);\n }\n }\n };\n Series.prototype.calculateStackingValues = function (seriesCollection, isStacking100) {\n var startValues;\n var endValues;\n var yValues = [];\n var lastPositive = [];\n var lastNegative = [];\n var stackingGroup;\n var lastValue;\n var value;\n var frequencies = [];\n if (isStacking100) {\n frequencies = this.findFrequencies(seriesCollection);\n }\n for (var _i = 0, seriesCollection_1 = seriesCollection; _i < seriesCollection_1.length; _i++) {\n var series = seriesCollection_1[_i];\n if (series.type.indexOf('Stacking') !== -1 || (series.drawType.indexOf('Stacking') !== -1 &&\n (series.chart.chartAreaType === 'PolarRadar'))) {\n stackingGroup = (series.type.indexOf('StackingArea') !== -1) ? 'StackingArea100' : series.stackingGroup;\n if (!lastPositive[stackingGroup]) {\n lastPositive[stackingGroup] = [];\n lastNegative[stackingGroup] = [];\n }\n yValues = series.yData;\n startValues = [];\n endValues = [];\n for (var j = 0, pointsLength = series.points.length; j < pointsLength; j++) {\n lastValue = 0;\n value = yValues[j];\n if (lastPositive[stackingGroup][series.points[j].xValue] === undefined) {\n lastPositive[stackingGroup][series.points[j].xValue] = 0;\n }\n if (lastNegative[stackingGroup][series.points[j].xValue] === undefined) {\n lastNegative[stackingGroup][series.points[j].xValue] = 0;\n }\n if (isStacking100) {\n value = value / frequencies[stackingGroup][series.points[j].xValue] * 100;\n value = !isNaN(value) ? value : 0;\n series.points[j].percent = value.toFixed(2);\n }\n if (value >= 0) {\n lastValue = lastPositive[stackingGroup][series.points[j].xValue];\n lastPositive[stackingGroup][series.points[j].xValue] += value;\n }\n else {\n lastValue = lastNegative[stackingGroup][series.points[j].xValue];\n lastNegative[stackingGroup][series.points[j].xValue] += value;\n }\n startValues.push(lastValue);\n endValues.push(value + lastValue);\n if (isStacking100 && (endValues[j] > 100)) {\n endValues[j] = 100;\n }\n }\n series.stackedValues = new StackValues(startValues, endValues);\n series.yMin = Math.min.apply(0, startValues);\n series.yMax = Math.max.apply(0, endValues);\n if (series.yMin > Math.min.apply(0, endValues)) {\n series.yMin = (isStacking100) ? -100 : Math.min.apply(0, endValues);\n }\n if (series.yMax < Math.max.apply(0, startValues)) {\n series.yMax = 0;\n }\n }\n }\n };\n Series.prototype.findFrequencies = function (seriesCollection) {\n var frequencies = [];\n var stackingGroup;\n for (var _i = 0, seriesCollection_2 = seriesCollection; _i < seriesCollection_2.length; _i++) {\n var series = seriesCollection_2[_i];\n series.yAxis.isStack100 = series.type.indexOf('100') !== -1 ? true : false;\n if (series.type.indexOf('Stacking') !== -1) {\n stackingGroup = (series.type.indexOf('StackingArea') !== -1) ? 'StackingArea100' : series.stackingGroup;\n if (!frequencies[stackingGroup]) {\n frequencies[stackingGroup] = [];\n }\n for (var j = 0, pointsLength = series.points.length; j < pointsLength; j++) {\n if (frequencies[stackingGroup][series.points[j].xValue] === undefined) {\n frequencies[stackingGroup][series.points[j].xValue] = 0;\n }\n if (series.yData[j] > 0) {\n frequencies[stackingGroup][series.points[j].xValue] += series.yData[j];\n }\n else {\n frequencies[stackingGroup][series.points[j].xValue] -= series.yData[j];\n }\n }\n }\n }\n return frequencies;\n };\n /* private dataManagerFailure(e: { result: Object[] }): void {\n this.currentViewData = [];\n this.refreshChart();\n }*/\n /** @private */\n Series.prototype.renderSeries = function (chart, index) {\n var seriesType = firstToLowerCase(this.type);\n if (seriesType.indexOf('100') !== -1) {\n seriesType = seriesType.replace('100', '');\n }\n if (chart[seriesType + 'SeriesModule']) {\n if (this.category !== 'Indicator' && this.category !== 'TrendLine') {\n this.createSeriesElements(chart);\n }\n chart[seriesType + 'SeriesModule'].render(this, this.xAxis, this.yAxis, chart.requireInvertedAxis);\n if (this.category !== 'Indicator') {\n if (this.errorBar.visible) {\n this.chart.errorBarModule.render(this);\n }\n if (this.marker.dataLabel.visible) {\n chart.dataLabelModule.render(this, this.chart, this.marker.dataLabel);\n }\n this.appendSeriesElement(chart.seriesElements, chart);\n }\n this.performAnimation(chart, seriesType, this.errorBar, this.marker, this.marker.dataLabel);\n }\n };\n /**\n * To create seris element.\n * @return {void}\n * @private\n */\n Series.prototype.createSeriesElements = function (chart) {\n if (this.category !== 'Indicator') {\n var elementId = chart.element.id;\n var xAxisRect = this.xAxis.rect;\n // 8 for extend border value 5 for extend size value\n var explodeValue = this.marker.border.width + 8 + 5;\n var yAxisRect = this.yAxis.rect;\n var marker = this.marker;\n var render = chart.renderer;\n var index = this.index;\n var markerHeight = (this.type === 'Scatter') ? (this.marker.height + explodeValue) / 2 : 0;\n var markerWidth = (this.type === 'Scatter') ? (this.marker.width + explodeValue) / 2 : 0;\n if (chart.chartAreaType === 'PolarRadar') {\n this.clipRectElement = render.drawCircularClipPath(new CircleOption(elementId + '_ChartSeriesClipRect_' + index, 'transparent', { width: 1, color: 'Gray' }, 1, this.clipRect.width / 2 + this.clipRect.x, this.clipRect.height / 2 + this.clipRect.y, chart.radius));\n }\n else {\n this.clipRectElement = render.drawClipPath(new RectOption(elementId + '_ChartSeriesClipRect_' + index, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: -markerWidth, y: -markerHeight,\n width: this.clipRect.width + markerWidth * 2,\n height: this.clipRect.height + markerHeight * 2\n }));\n }\n var transform = void 0;\n transform = chart.chartAreaType === 'Cartesian' ? 'translate(' + this.clipRect.x + ',' + (this.clipRect.y) + ')' : '';\n this.symbolElement = null;\n this.seriesElement = render.createGroup({\n 'id': elementId + 'SeriesGroup' + index,\n 'transform': transform,\n 'clip-path': 'url(#' + elementId + '_ChartSeriesClipRect_' + index + ')'\n });\n this.seriesElement.appendChild(this.clipRectElement);\n }\n };\n /**\n * To append the series.\n * @return {void}\n * @private\n */\n Series.prototype.appendSeriesElement = function (element, chart) {\n var marker = this.marker;\n var dataLabel = marker.dataLabel;\n if (this.category !== 'TrendLine') {\n chart.seriesElements.appendChild(this.seriesElement);\n var errorBar = this.errorBar;\n if (errorBar.visible) {\n if (chart.chartAreaType === 'PolarRadar') {\n chart.seriesElements.appendChild(this.seriesElement);\n }\n else {\n chart.seriesElements.appendChild(this.errorBarElement);\n }\n }\n if (this.type === 'Scatter' || this.type === 'Bubble') {\n chart.seriesElements.appendChild(this.seriesElement);\n }\n }\n if (marker.visible && ((chart.chartAreaType === 'Cartesian' && (!this.isRectSeries || this.type === 'BoxAndWhisker'))\n || ((this.drawType !== 'Scatter' && !this.isRectSeries) && chart.chartAreaType === 'PolarRadar')) &&\n this.type !== 'Scatter' && this.type !== 'Bubble') {\n chart.seriesElements.appendChild(this.symbolElement);\n }\n if (dataLabel.visible) {\n chart.dataLabelElements.appendChild(this.shapeElement);\n chart.dataLabelElements.appendChild(this.textElement);\n }\n if (chart.dataLabelElements.hasChildNodes()) {\n chart.seriesElements.appendChild(chart.dataLabelElements);\n }\n };\n /**\n * To perform animation for chart series.\n * @return {void}\n * @private\n */\n Series.prototype.performAnimation = function (chart, type, errorBar, marker, dataLabel) {\n if (this.animation.enable && chart.animateSeries) {\n chart[type + 'SeriesModule'].doAnimation(this);\n if (errorBar.visible) {\n chart.errorBarModule.doErrorBarAnimation(this);\n }\n if (marker.visible) {\n chart.markerRender.doMarkerAnimation(this);\n }\n if (dataLabel.visible) {\n chart.dataLabelModule.doDataLabelAnimation(this);\n }\n }\n };\n /**\n * To set border color for empty point\n * @private\n */\n Series.prototype.setPointColor = function (point, color) {\n color = point.interior || color;\n return point.isEmpty ? (this.emptyPointSettings.fill || color) : color;\n };\n /**\n * To set border color for empty point\n * @private\n */\n Series.prototype.setBorderColor = function (point, border) {\n border.width = point.isEmpty ? (this.emptyPointSettings.border.width || border.width) : border.width;\n border.color = point.isEmpty ? (this.emptyPointSettings.border.color || border.color) : border.color;\n return border;\n };\n __decorate([\n Property('')\n ], Series.prototype, \"name\", void 0);\n __decorate([\n Property('')\n ], Series.prototype, \"yName\", void 0);\n __decorate([\n Property('Line')\n ], Series.prototype, \"drawType\", void 0);\n __decorate([\n Property(true)\n ], Series.prototype, \"isClosed\", void 0);\n __decorate([\n Property('#2ecd71')\n ], Series.prototype, \"bearFillColor\", void 0);\n __decorate([\n Property('#e74c3d')\n ], Series.prototype, \"bullFillColor\", void 0);\n __decorate([\n Property(false)\n ], Series.prototype, \"enableSolidCandles\", void 0);\n __decorate([\n Property('')\n ], Series.prototype, \"size\", void 0);\n __decorate([\n Property(null)\n ], Series.prototype, \"binInterval\", void 0);\n __decorate([\n Property(false)\n ], Series.prototype, \"showNormalDistribution\", void 0);\n __decorate([\n Property('')\n ], Series.prototype, \"stackingGroup\", void 0);\n __decorate([\n Property(true)\n ], Series.prototype, \"visible\", void 0);\n __decorate([\n Complex({ color: 'transparent', width: 0 }, Border)\n ], Series.prototype, \"border\", void 0);\n __decorate([\n Property(1)\n ], Series.prototype, \"opacity\", void 0);\n __decorate([\n Property('Line')\n ], Series.prototype, \"type\", void 0);\n __decorate([\n Complex(null, ErrorBarSettings)\n ], Series.prototype, \"errorBar\", void 0);\n __decorate([\n Complex(null, MarkerSettings)\n ], Series.prototype, \"marker\", void 0);\n __decorate([\n Collection([], Trendline)\n ], Series.prototype, \"trendlines\", void 0);\n __decorate([\n Property('')\n ], Series.prototype, \"tooltipMappingName\", void 0);\n __decorate([\n Property(true)\n ], Series.prototype, \"enableTooltip\", void 0);\n __decorate([\n Property('SeriesType')\n ], Series.prototype, \"legendShape\", void 0);\n __decorate([\n Property(null)\n ], Series.prototype, \"selectionStyle\", void 0);\n __decorate([\n Property(1)\n ], Series.prototype, \"minRadius\", void 0);\n __decorate([\n Property(3)\n ], Series.prototype, \"maxRadius\", void 0);\n __decorate([\n Property('Natural')\n ], Series.prototype, \"splineType\", void 0);\n __decorate([\n Property(0.5)\n ], Series.prototype, \"cardinalSplineTension\", void 0);\n __decorate([\n Complex(null, EmptyPointSettings)\n ], Series.prototype, \"emptyPointSettings\", void 0);\n __decorate([\n Property(true)\n ], Series.prototype, \"showMean\", void 0);\n __decorate([\n Property('Normal')\n ], Series.prototype, \"boxPlotMode\", void 0);\n __decorate([\n Property(null)\n ], Series.prototype, \"columnWidth\", void 0);\n __decorate([\n Property(0)\n ], Series.prototype, \"columnSpacing\", void 0);\n __decorate([\n Property('#C64E4A')\n ], Series.prototype, \"negativeFillColor\", void 0);\n __decorate([\n Property('#4E81BC')\n ], Series.prototype, \"summaryFillColor\", void 0);\n __decorate([\n Property()\n ], Series.prototype, \"intermediateSumIndexes\", void 0);\n __decorate([\n Property()\n ], Series.prototype, \"sumIndexes\", void 0);\n __decorate([\n Complex({ color: 'black', width: 2 }, Connector)\n ], Series.prototype, \"connector\", void 0);\n __decorate([\n Complex(null, CornerRadius)\n ], Series.prototype, \"cornerRadius\", void 0);\n return Series;\n}(SeriesBase));\nexport { Series };\n","import { Query, DataManager } from '@syncfusion/ej2-data';\n/**\n * data module is used to generate query and dataSource\n */\nvar Data = /** @class */ (function () {\n /**\n * Constructor for data module\n * @private\n */\n function Data(dataSource, query) {\n this.initDataManager(dataSource, query);\n }\n /**\n * The function used to initialize dataManager and query\n * @return {void}\n * @private\n */\n Data.prototype.initDataManager = function (dataSource, query) {\n this.dataManager = dataSource instanceof DataManager ? dataSource : new DataManager(dataSource);\n this.query = query instanceof Query ? query : new Query();\n };\n /**\n * The function used to generate updated Query from chart model\n * @return {void}\n * @private\n */\n Data.prototype.generateQuery = function () {\n var query = this.query.clone();\n return query;\n };\n /**\n * The function used to get dataSource by executing given Query\n * @param {Query} query - A Query that specifies to generate dataSource\n * @return {void}\n * @private\n */\n Data.prototype.getData = function (query) {\n return this.dataManager.executeQuery(query);\n };\n return Data;\n}());\nexport { Data };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { drawSymbol, PathOption, Size } from '../../common/utils/helper';\nimport { Browser, extend, remove } from '@syncfusion/ej2-base';\nimport { ChartData } from '../../chart/utils/get-data';\nimport { withInBounds, PointData, stopTimer } from '../../common/utils/helper';\nimport { colorNameToHex, convertHexToColor } from '../../common/utils/helper';\n/**\n * Marker Module used to render the marker for line type series.\n */\nvar MarkerExplode = /** @class */ (function (_super) {\n __extends(MarkerExplode, _super);\n /**\n * Constructor for the marker module.\n * @private\n */\n function MarkerExplode(chart) {\n var _this = _super.call(this, chart) || this;\n _this.addEventListener();\n _this.elementId = chart.element.id;\n return _this;\n }\n /**\n * @hidden\n */\n MarkerExplode.prototype.addEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n this.chart.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);\n this.chart.on(Browser.touchEndEvent, this.mouseUpHandler, this);\n };\n /**\n * @hidden\n */\n /* public removeEventListener(): void {\n if (this.chart.isDestroyed) { return; }\n this.chart.off(Browser.touchMoveEvent, this.mouseMoveHandler);\n }*/\n /**\n * @hidden\n */\n MarkerExplode.prototype.mouseUpHandler = function () {\n var chart = this.chart;\n if (chart.isTouch && !chart.crosshair.enable && !this.isSelected(chart)) {\n this.markerMove(true);\n }\n };\n /**\n * @hidden\n */\n MarkerExplode.prototype.mouseMoveHandler = function () {\n var chart = this.chart;\n if ((!chart.crosshair.enable || (chart.tooltip.enable)) && (!chart.isTouch || chart.startMove) && !this.isSelected(chart)) {\n this.markerMove(false);\n }\n };\n MarkerExplode.prototype.markerMove = function (remove) {\n var _this = this;\n var chart = this.chart;\n this.currentPoints = [];\n var data;\n var previous;\n var explodeSeries;\n var series;\n if (!chart.tooltip.shared || !chart.tooltip.enable) {\n data = this.getData();\n series = data.series;\n previous = this.previousPoints[0];\n explodeSeries = series && ((series.type === 'Bubble' || series.drawType === 'Scatter' || series.type === 'Scatter') ||\n ((!series.isRectSeries || series.type === 'BoxAndWhisker') &&\n (series.marker.visible && series.marker.width !== 0 && series.marker.height !== 0)));\n data.lierIndex = this.lierIndex;\n if (data.point && explodeSeries && ((!previous || (previous.point !== data.point)) ||\n (previous && previous.lierIndex > 3 && previous.lierIndex !== this.lierIndex))) {\n this.currentPoints.push(data);\n }\n }\n else {\n if (!withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {\n return null;\n }\n if (chart.tooltip.enable) {\n var pointData = chart.chartAreaType === 'PolarRadar' ? this.getData() : null;\n for (var _i = 0, _a = chart.visibleSeries; _i < _a.length; _i++) {\n var chartSeries = _a[_i];\n if (!chartSeries.enableTooltip || chartSeries.category === 'Indicator') {\n continue;\n }\n if (chart.chartAreaType === 'Cartesian' && chartSeries.visible) {\n data = this.getClosestX(chart, chartSeries);\n }\n else if (chart.chartAreaType === 'PolarRadar' && chartSeries.visible && pointData.point !== null) {\n data = new PointData(chartSeries.points[pointData.point.index], chartSeries);\n }\n if (data) {\n this.currentPoints.push(data);\n data = null;\n }\n }\n }\n }\n var length = this.previousPoints.length;\n if (this.currentPoints.length > 0) {\n if (length === 0 || (length > 0 && this.previousPoints[0].point !== this.currentPoints[0].point)) {\n if (this.previousPoints.length > 0) {\n this.removeHighlightedMarker();\n }\n var _loop_1 = function (data_1) {\n if (data_1 && data_1.point &&\n (!data_1.series.isRectSeries || data_1.series.type === 'BoxAndWhisker')) {\n stopTimer(this_1.markerExplode);\n this_1.isRemove = true;\n data_1.point.symbolLocations.map(function (location, index) {\n if (data_1.point.marker.visible) {\n _this.drawTrackBall(data_1.series, data_1.point, location, index);\n }\n });\n }\n };\n var this_1 = this;\n for (var _b = 0, _c = this.currentPoints; _b < _c.length; _b++) {\n var data_1 = _c[_b];\n _loop_1(data_1);\n }\n this.previousPoints = extend([], this.currentPoints, null, true);\n }\n }\n if (!chart.tooltip.enable && ((this.currentPoints.length === 0 && this.isRemove) || (remove && this.isRemove) ||\n !withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect))) {\n this.isRemove = false;\n this.markerExplode = setTimeout(function () {\n _this.removeHighlightedMarker();\n }, 2000);\n }\n this.currentPoints = [];\n };\n MarkerExplode.prototype.drawTrackBall = function (series, point, location, index) {\n var marker = point.marker;\n var seriesMarker = series.marker;\n var shape = marker.shape || seriesMarker.shape;\n var element = series.symbolElement || series.seriesElement;\n var symbolId = this.elementId + '_Series_' + series.index + '_Point_' + point.index + '_Trackball' +\n (index ? index : '');\n var size = new Size((marker.width || seriesMarker.width) + 5, (marker.height || seriesMarker.height) + 5);\n var border = (marker.border || series.border);\n var explodeSeries = (series.type === 'BoxAndWhisker' || series.type === 'Bubble' || series.type === 'Scatter');\n var borderColor = (border.color && border.color !== 'transparent') ? border.color :\n marker.fill || point.interior || (explodeSeries ? point.color : series.interior);\n var colorValue = convertHexToColor(colorNameToHex(borderColor));\n var borderWidth = marker.border ? marker.border.width : seriesMarker.border.width;\n var markerShadow = series.chart.themeStyle.markerShadow ||\n 'rgba(' + colorValue.r + ',' + colorValue.g + ',' + colorValue.b + ',0.2)';\n for (var i = 0; i < 2; i++) {\n var options = new PathOption(symbolId + '_' + i, i ? (marker.fill || point.color || (explodeSeries ? series.interior : '#ffffff')) : 'transparent', borderWidth + (i ? 0 : 8), i ? borderColor : markerShadow, (marker.opacity || seriesMarker.opacity), null, null);\n var symbol = drawSymbol(location, shape, size, seriesMarker.imageUrl, options, '');\n symbol.setAttribute('style', 'pointer-events:none');\n symbol.setAttribute('class', 'EJ2-Trackball');\n element.appendChild(symbol);\n }\n };\n /**\n * @hidden\n */\n MarkerExplode.prototype.removeHighlightedMarker = function () {\n var elements = document.getElementsByClassName('EJ2-Trackball');\n for (var i = 0, len = elements.length; i < len; i++) {\n remove(elements[0]);\n }\n this.previousPoints = [];\n };\n return MarkerExplode;\n}(ChartData));\nexport { MarkerExplode };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { drawSymbol, PathOption, Size, markerAnimate, CircleOption, RectOption } from '../../common/utils/helper';\nimport { findlElement } from '../../common/utils/helper';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { pointRender } from '../../common/model/constants';\nimport { MarkerExplode } from './marker-explode';\nimport { getSaturationColor } from '../../common/utils/helper';\n/**\n * Marker module used to render the marker for line type series.\n */\nvar Marker = /** @class */ (function (_super) {\n __extends(Marker, _super);\n /**\n * Constructor for the marker module.\n * @private\n */\n function Marker(chart) {\n var _this = _super.call(this, chart) || this;\n _this.addEventListener();\n return _this;\n }\n /**\n * Render the marker for series.\n * @return {void}\n * @private\n */\n Marker.prototype.render = function (series) {\n var _this = this;\n this.createElement(series);\n var _loop_1 = function (point) {\n if (point.visible && point.symbolLocations.length) {\n point.symbolLocations.map(function (location, index) {\n _this.renderMarker(series, point, location, index);\n });\n }\n };\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n _loop_1(point);\n }\n };\n Marker.prototype.renderMarker = function (series, point, location, index) {\n var seriesIndex = series.index;\n var marker = series.marker;\n var border = {\n color: marker.border.color,\n width: marker.border.width\n };\n var borderColor = marker.border.color;\n var symbolId;\n var shapeOption;\n var isBoxPlot = series.type === 'BoxAndWhisker';\n var fill = marker.fill || (isBoxPlot ? point.interior || series.interior : '#ffffff');\n var argsData;\n var parentElement = isBoxPlot ?\n findlElement(series.seriesElement.childNodes, 'Series_' + series.index + '_Point_' + point.index)\n : series.symbolElement;\n border.color = borderColor || series.setPointColor(point, series.interior);\n symbolId = this.elementId + '_Series_' + seriesIndex + '_Point_' + point.index + '_Symbol' +\n (index ? index : '');\n argsData = {\n cancel: false, name: pointRender, series: series, point: point,\n fill: point.isEmpty ? (series.emptyPointSettings.fill || fill) : fill,\n border: {\n color: series.type === 'BoxAndWhisker' ?\n (!isNullOrUndefined(borderColor) && borderColor !== 'transparent') ? borderColor :\n getSaturationColor(fill, -0.6)\n : border.color,\n width: border.width\n },\n height: marker.height,\n width: marker.width,\n shape: marker.shape\n };\n argsData.border = series.setBorderColor(point, { width: argsData.border.width, color: argsData.border.color });\n this.chart.trigger(pointRender, argsData);\n point.color = argsData.fill;\n if (!argsData.cancel) {\n var y = void 0;\n if (series.type === 'RangeArea') {\n y = index ? point.low : point.high;\n }\n else if (isBoxPlot) {\n y = point.outliers[index];\n }\n else {\n y = point.y;\n }\n shapeOption = new PathOption(symbolId, argsData.fill, argsData.border.width, argsData.border.color, marker.opacity, null);\n if (parentElement !== undefined && parentElement !== null) {\n parentElement.appendChild(drawSymbol(location, argsData.shape, new Size(argsData.width, argsData.height), marker.imageUrl, shapeOption, point.x.toString() + ':' + y.toString()));\n }\n point.marker = {\n border: argsData.border,\n fill: argsData.fill,\n height: argsData.height,\n visible: true,\n shape: argsData.shape,\n width: argsData.width\n };\n }\n else {\n location = null;\n point.marker = {\n visible: false\n };\n }\n };\n Marker.prototype.createElement = function (series) {\n var markerClipRect;\n var marker = series.marker;\n // 8 for extend border value 5 for extend size value\n var explodeValue = marker.border.width + 8 + 5;\n var render = series.chart.renderer;\n var transform;\n transform = series.chart.chartAreaType === 'Cartesian' ? 'translate(' + series.clipRect.x + ',' + (series.clipRect.y) + ')' : '';\n if (marker.visible) {\n var markerHeight = (marker.height + explodeValue) / 2;\n var markerWidth = (marker.width + explodeValue) / 2;\n if (series.chart.chartAreaType === 'Cartesian') {\n markerClipRect = render.drawClipPath(new RectOption(this.elementId + '_ChartMarkerClipRect_' + series.index, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: -markerWidth, y: -markerHeight,\n width: series.clipRect.width + markerWidth * 2,\n height: series.clipRect.height + markerHeight * 2\n }));\n }\n else {\n markerClipRect = render.drawCircularClipPath(new CircleOption(this.elementId + '_ChartMarkerClipRect_' + series.index, 'transparent', { width: 1, color: 'Gray' }, 1, series.clipRect.width / 2 + series.clipRect.x, series.clipRect.height / 2 + series.clipRect.y, series.chart.radius + Math.max(markerHeight, markerWidth)));\n }\n series.symbolElement = render.createGroup({\n 'id': this.elementId + 'SymbolGroup' + series.index,\n 'transform': transform,\n 'clip-path': 'url(#' + this.elementId + '_ChartMarkerClipRect_' + series.index + ')'\n });\n series.symbolElement.appendChild(markerClipRect);\n }\n };\n Marker.prototype.getRangeLowPoint = function (region, series) {\n var x = region.x;\n var y = region.y;\n if (series.chart.requireInvertedAxis) {\n y += region.height / 2;\n x += series.yAxis.isInversed ? region.width : 0;\n }\n else {\n y += series.yAxis.isInversed ? 0 : region.height;\n x += region.width / 2;\n }\n return { x: x, y: y };\n };\n /**\n * Animates the marker.\n * @return {void}.\n * @private\n */\n Marker.prototype.doMarkerAnimation = function (series) {\n if (!(series.isRectSeries || series.type === 'Scatter' || series.type === 'Bubble' ||\n (series.chart.chartAreaType === 'PolarRadar' && (series.drawType === 'Scatter' || series.drawType.indexOf('Column') > -1)))) {\n var markerElements = series.symbolElement.childNodes;\n var delay = series.animation.delay + series.animation.duration;\n var j = 1;\n var incFactor = series.type === 'RangeArea' ? 2 : 1;\n for (var i = 0; i < series.points.length; i++) {\n if (!series.points[i].symbolLocations.length || !markerElements[j]) {\n continue;\n }\n markerAnimate(markerElements[j], delay, 200, series, i, series.points[i].symbolLocations[0], false);\n if (incFactor === 2) {\n var lowPoint = this.getRangeLowPoint(series.points[i].regions[0], series);\n markerAnimate(markerElements[j + 1], delay, 200, series, i, lowPoint, false);\n }\n j += incFactor;\n }\n }\n };\n return Marker;\n}(MarkerExplode));\nexport { Marker };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { Font, Border } from '../model/base';\nimport { Theme } from '../model/theme';\nimport { Size, Rect, subtractThickness, Thickness, drawSymbol, measureText, ChartLocation, PathOption } from '../utils/helper';\nimport { RectOption, TextOption, textElement, stringToNumber, removeElement, showTooltip, getElement } from '../utils/helper';\n/**\n * Configures the location for the legend.\n */\nvar Location = /** @class */ (function (_super) {\n __extends(Location, _super);\n function Location() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], Location.prototype, \"x\", void 0);\n __decorate([\n Property(0)\n ], Location.prototype, \"y\", void 0);\n return Location;\n}(ChildProperty));\nexport { Location };\n/**\n * Configures the legends in charts.\n */\nvar LegendSettings = /** @class */ (function (_super) {\n __extends(LegendSettings, _super);\n function LegendSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], LegendSettings.prototype, \"visible\", void 0);\n __decorate([\n Property(null)\n ], LegendSettings.prototype, \"height\", void 0);\n __decorate([\n Property(null)\n ], LegendSettings.prototype, \"width\", void 0);\n __decorate([\n Complex({ x: 0, y: 0 }, Location)\n ], LegendSettings.prototype, \"location\", void 0);\n __decorate([\n Property('Auto')\n ], LegendSettings.prototype, \"position\", void 0);\n __decorate([\n Property(8)\n ], LegendSettings.prototype, \"padding\", void 0);\n __decorate([\n Property('Center')\n ], LegendSettings.prototype, \"alignment\", void 0);\n __decorate([\n Complex(Theme.legendLabelFont, Font)\n ], LegendSettings.prototype, \"textStyle\", void 0);\n __decorate([\n Property(10)\n ], LegendSettings.prototype, \"shapeHeight\", void 0);\n __decorate([\n Property(10)\n ], LegendSettings.prototype, \"shapeWidth\", void 0);\n __decorate([\n Complex({}, Border)\n ], LegendSettings.prototype, \"border\", void 0);\n __decorate([\n Property(5)\n ], LegendSettings.prototype, \"shapePadding\", void 0);\n __decorate([\n Property('transparent')\n ], LegendSettings.prototype, \"background\", void 0);\n __decorate([\n Property(1)\n ], LegendSettings.prototype, \"opacity\", void 0);\n __decorate([\n Property(true)\n ], LegendSettings.prototype, \"toggleVisibility\", void 0);\n __decorate([\n Property(null)\n ], LegendSettings.prototype, \"description\", void 0);\n __decorate([\n Property(3)\n ], LegendSettings.prototype, \"tabIndex\", void 0);\n return LegendSettings;\n}(ChildProperty));\nexport { LegendSettings };\n/**\n * Legend base class for Chart and Accumulation chart.\n * @private\n */\nvar BaseLegend = /** @class */ (function () {\n /**\n * Constructor for the dateTime module.\n * @private\n */\n function BaseLegend(chart) {\n this.rowCount = 0; // legend row counts per page\n this.columnCount = 0; // legend column counts per page\n this.pageButtonSize = 8;\n this.pageXCollections = []; // pages of x locations\n this.maxColumns = 0;\n this.isTrimmed = false;\n this.maxWidth = 0;\n this.currentPage = 1;\n this.chart = chart;\n this.legend = chart.legendSettings;\n this.legendID = chart.element.id + '_chart_legend';\n this.isChartControl = (chart.getModuleName() === 'chart');\n }\n /**\n * Calculate the bounds for the legends.\n * @return {void}\n * @private\n */\n BaseLegend.prototype.calculateLegendBounds = function (rect, availableSize) {\n var legend = this.legend;\n this.getPosition(legend.position, availableSize);\n this.legendBounds = new Rect(rect.x, rect.y, 0, 0);\n this.isVertical = (this.position === 'Left' || this.position === 'Right');\n if (this.isVertical) {\n this.legendBounds.height = stringToNumber(legend.height, availableSize.height - (rect.y - this.chart.margin.top)) || rect.height;\n this.legendBounds.width = stringToNumber(legend.width || '20%', availableSize.width);\n }\n else {\n this.legendBounds.width = stringToNumber(legend.width, availableSize.width) || rect.width;\n this.legendBounds.height = stringToNumber(legend.height || '20%', availableSize.height);\n }\n this.library.getLegendBounds(availableSize, this.legendBounds, legend);\n this.getLocation(this.position, legend.alignment, this.legendBounds, rect, availableSize);\n };\n /**\n * To find legend position based on available size for chart and accumulation chart\n */\n BaseLegend.prototype.getPosition = function (position, availableSize) {\n if (this.isChartControl) {\n this.position = (position !== 'Auto') ? position : 'Bottom';\n }\n else {\n if (position === 'Auto' && this.chart.visibleSeries &&\n (this.chart.visibleSeries[0].type === 'Funnel' || this.chart.visibleSeries[0].type === 'Pyramid')) {\n position = 'Top';\n }\n this.position = (position !== 'Auto') ? position :\n (availableSize.width > availableSize.height ? 'Right' : 'Bottom');\n }\n };\n /**\n * To set bounds for chart and accumulation chart\n */\n BaseLegend.prototype.setBounds = function (computedWidth, computedHeight, legend, legendBounds) {\n computedWidth = computedWidth < legendBounds.width ? computedWidth : legendBounds.width;\n computedHeight = computedHeight < legendBounds.height ? computedHeight : legendBounds.height;\n legendBounds.width = !legend.width ? computedWidth : legendBounds.width;\n legendBounds.height = !legend.height ? computedHeight : legendBounds.height;\n this.rowCount = Math.max(1, Math.ceil((legendBounds.height - legend.padding) / (this.maxItemHeight + legend.padding)));\n };\n /**\n * To find legend location based on position, alignment for chart and accumulation chart\n */\n BaseLegend.prototype.getLocation = function (position, alignment, legendBounds, rect, availableSize) {\n var padding = this.legend.border.width;\n var legendHeight = legendBounds.height + padding;\n var legendWidth = legendBounds.width + padding;\n var marginBottom = this.chart.margin.bottom;\n if (position === 'Bottom') {\n legendBounds.x = this.alignLegend(legendBounds.x, availableSize.width, legendBounds.width, alignment);\n legendBounds.y = rect.y + (rect.height - legendHeight) + padding;\n subtractThickness(rect, new Thickness(0, 0, 0, legendHeight));\n }\n else if (position === 'Top') {\n legendBounds.x = this.alignLegend(legendBounds.x, availableSize.width, legendBounds.width, alignment);\n legendBounds.y = rect.y + padding;\n subtractThickness(rect, new Thickness(0, 0, legendHeight, 0));\n }\n else if (position === 'Right') {\n legendBounds.x = rect.x + (rect.width - legendBounds.width);\n legendBounds.y = rect.y + this.alignLegend(0, availableSize.height - (rect.y + marginBottom), legendBounds.height, alignment);\n subtractThickness(rect, new Thickness(0, legendWidth, 0, 0));\n }\n else if (position === 'Left') {\n legendBounds.y = rect.y + this.alignLegend(0, availableSize.height - (rect.y + marginBottom), legendBounds.height, alignment);\n subtractThickness(rect, new Thickness(legendWidth, 0, 0, 0));\n }\n else {\n legendBounds.x = this.legend.location.x;\n legendBounds.y = this.legend.location.y;\n subtractThickness(rect, new Thickness(0, 0, 0, 0));\n }\n };\n /**\n * To find legend alignment for chart and accumulation chart\n */\n BaseLegend.prototype.alignLegend = function (start, size, legendSize, alignment) {\n switch (alignment) {\n case 'Far':\n start = (size - legendSize) - start;\n break;\n case 'Center':\n start = ((size - legendSize) / 2);\n break;\n }\n return start;\n };\n /**\n * Renders the legend.\n * @return {void}\n * @private\n */\n BaseLegend.prototype.renderLegend = function (chart, legend, legendBounds) {\n var firstLegend = this.findFirstLegendPosition(this.legendCollections);\n var padding = legend.padding;\n this.maxItemHeight = Math.max(this.legendCollections[0].textSize.height, legend.shapeHeight);\n var legendGroup = chart.renderer.createGroup({ id: this.legendID + '_g' });\n var legendTranslateGroup = this.createLegendElements(chart, legendBounds, legendGroup, legend, this.legendID);\n if (firstLegend !== this.legendCollections.length) {\n var legendSeriesGroup = void 0; // legendItem group for each series group element\n var start = void 0; // starting shape center x,y position && to resolve lint error used new line for declaration\n start = new ChartLocation(legendBounds.x + padding + (legend.shapeWidth / 2), legendBounds.y + padding + this.maxItemHeight / 2);\n var textOptions = new TextOption('', start.x, start.y, 'start');\n // initialization for totalPages legend click totalpage again calculate\n this.totalPages = this.isChartControl ? this.totalPages : 0;\n var textPadding = legend.shapePadding + padding + legend.shapeWidth;\n var count = 0;\n this.pageXCollections = [];\n this.legendCollections[firstLegend].location = start;\n var previousLegend = this.legendCollections[firstLegend];\n for (var _i = 0, _a = this.legendCollections; _i < _a.length; _i++) {\n var legendOption = _a[_i];\n if (legendOption.render && legendOption.text !== '') {\n legendSeriesGroup = chart.renderer.createGroup({\n id: this.legendID + this.generateId(legendOption, '_g_', count)\n });\n legendSeriesGroup.setAttribute('tabindex', legend.tabIndex.toString());\n legendSeriesGroup.setAttribute('aria-label', legend.description || 'Click to show or hide the ' + legendOption.text + ' series');\n this.library.getRenderPoint(legendOption, start, textPadding, previousLegend, legendBounds, count, firstLegend);\n this.renderSymbol(legendOption, legendSeriesGroup, count);\n this.renderText(chart, legendOption, legendSeriesGroup, textOptions, count);\n legendSeriesGroup.setAttribute('style', 'cursor: ' + ((!legend.toggleVisibility && chart.selectionMode === 'None') ? 'auto' : 'pointer'));\n legendTranslateGroup.appendChild(legendSeriesGroup);\n previousLegend = legendOption;\n }\n count++;\n }\n if (this.isPaging) {\n this.renderPagingElements(chart, legendBounds, textOptions, legendGroup);\n }\n else {\n this.totalPages = 1;\n }\n }\n chart.svgObject.appendChild(legendGroup);\n };\n /**\n * To find first valid legend text index for chart and accumulation chart\n */\n BaseLegend.prototype.findFirstLegendPosition = function (legendCollection) {\n var count = 0;\n for (var _i = 0, legendCollection_1 = legendCollection; _i < legendCollection_1.length; _i++) {\n var legend = legendCollection_1[_i];\n if (legend.render && legend.text !== '') {\n break;\n }\n count++;\n }\n return count;\n };\n /**\n * To create legend rendering elements for chart and accumulation chart\n */\n BaseLegend.prototype.createLegendElements = function (chart, legendBounds, legendGroup, legend, id) {\n var padding = legend.padding;\n var options = new RectOption(id + '_element', legend.background, legend.border, legend.opacity, legendBounds);\n legendGroup.appendChild(chart.renderer.drawRectangle(options));\n var legendItemsGroup = chart.renderer.createGroup({ id: id + '_collections' });\n legendGroup.appendChild(legendItemsGroup);\n this.legendTranslateGroup = chart.renderer.createGroup({ id: id + '_translate_g' });\n legendItemsGroup.appendChild(this.legendTranslateGroup);\n var clippath = chart.renderer.createClipPath({ id: id + '_clipPath' });\n options.y += padding;\n options.id += '_clipPath_rect';\n options.width = (!this.isChartControl && this.isVertical) ? this.maxWidth - padding : legendBounds.width;\n this.clipRect = chart.renderer.drawRectangle(options);\n clippath.appendChild(this.clipRect);\n chart.svgObject.appendChild(clippath);\n legendItemsGroup.setAttribute('style', 'clip-path:url(#' + clippath.id + ')');\n return this.legendTranslateGroup;\n };\n /**\n * To render legend symbols for chart and accumulation chart\n */\n BaseLegend.prototype.renderSymbol = function (legendOption, group, i) {\n var symbolColor = legendOption.visible ? legendOption.fill : '#D3D3D3';\n var shape = (legendOption.shape === 'SeriesType') ? legendOption.type : legendOption.shape;\n shape = shape === 'Scatter' ? legendOption.markerShape : shape;\n var symbolOption = new PathOption(this.legendID + this.generateId(legendOption, '_shape_', i), symbolColor, 1, symbolColor, 1, '', '');\n group.appendChild(drawSymbol(legendOption.location, shape, new Size(this.legend.shapeWidth, this.legend.shapeHeight), '', symbolOption, 'Click to show or hide the ' + legendOption.text + ' series'));\n if (shape === 'Line' && legendOption.markerVisibility && legendOption.markerShape !== 'Image' ||\n (legendOption.type === 'Doughnut' && this.chart.series[0].legendShape === 'SeriesType')) {\n symbolOption.id = this.legendID + this.generateId(legendOption, '_shape_marker_', i);\n shape = legendOption.type === 'Doughnut' ? 'Circle' : legendOption.markerShape;\n symbolOption.fill = legendOption.type === 'Doughnut' ? '#FFFFFF' : symbolOption.fill;\n group.appendChild(drawSymbol(legendOption.location, shape, new Size(this.legend.shapeWidth / 2, this.legend.shapeHeight / 2), '', symbolOption, 'Click to show or hide the ' + legendOption.text + ' series'));\n }\n };\n /**\n * To render legend text for chart and accumulation chart\n */\n BaseLegend.prototype.renderText = function (chart, legendOption, group, textOptions, i) {\n var legend = chart.legendSettings;\n var hiddenColor = '#D3D3D3';\n textOptions.id = this.legendID + this.generateId(legendOption, '_text_', i);\n var fontcolor = legendOption.visible ? legend.textStyle.color || chart.themeStyle.legendLabel : hiddenColor;\n textOptions.text = legendOption.text;\n textOptions.x = legendOption.location.x + (legend.shapeWidth / 2) + legend.shapePadding;\n textOptions.y = legendOption.location.y + this.maxItemHeight / 4;\n var element = textElement(textOptions, legend.textStyle, fontcolor, group);\n element.setAttribute('aria-label', legend.description || 'Click to show or hide the ' + legendOption.text + ' series');\n };\n /**\n * To render legend paging elements for chart and accumulation chart\n */\n BaseLegend.prototype.renderPagingElements = function (chart, bounds, textOption, legendGroup) {\n var paginggroup = chart.renderer.createGroup({ id: this.legendID + '_navigation' });\n legendGroup.appendChild(paginggroup);\n var grayColor = '#545454';\n var legend = chart.legendSettings; // to solve parameter lint error, legend declaration is here\n var padding = 8; // const padding for paging elements\n if (this.isChartControl || !this.isVertical) {\n this.totalPages = Math.ceil(this.totalPages / Math.max(1, this.rowCount - 1));\n }\n else {\n this.totalPages = Math.ceil(this.totalPages / this.maxColumns);\n }\n var symbolOption = new PathOption(this.legendID + '_pageup', 'transparent', 5, grayColor, 1, '', '');\n var iconSize = this.pageButtonSize;\n paginggroup.setAttribute('style', 'cursor: pointer');\n // Page left arrow drawing calculation started here\n this.clipPathHeight = (this.rowCount - 1) * (this.maxItemHeight + legend.padding);\n this.clipRect.setAttribute('height', this.clipPathHeight.toString());\n var x = bounds.x + iconSize / 2;\n var y = bounds.y + this.clipPathHeight + ((bounds.height - this.clipPathHeight) / 2);\n paginggroup.appendChild(drawSymbol({ x: x, y: y }, 'LeftArrow', new Size(iconSize, iconSize), '', symbolOption, 'LeftArrow'));\n // Page numbering rendering calculation started here\n textOption.x = x + (iconSize / 2) + padding;\n var size = measureText(this.totalPages + '/' + this.totalPages, legend.textStyle);\n textOption.y = y + (size.height / 4);\n textOption.id = this.legendID + '_pagenumber';\n textOption.text = '1/' + this.totalPages;\n var pageTextElement = textElement(textOption, legend.textStyle, legend.textStyle.color, paginggroup);\n // Page right arrow rendering calculation started here\n x = (textOption.x + padding + (iconSize / 2) + size.width);\n symbolOption.id = this.legendID + '_pagedown';\n paginggroup.appendChild(drawSymbol({ x: x, y: y }, 'RightArrow', new Size(iconSize, iconSize), '', symbolOption, 'RightArrow'));\n // placing the navigation buttons and page numbering in legend right corner\n paginggroup.setAttribute('transform', 'translate(' + (bounds.width - (2 * (iconSize + padding) +\n padding + size.width)) + ', ' + 0 + ')');\n this.translatePage(pageTextElement, this.currentPage - 1, this.currentPage);\n };\n /**\n * To translate legend pages for chart and accumulation chart\n */\n BaseLegend.prototype.translatePage = function (pagingText, page, pageNumber) {\n var size = (this.clipPathHeight) * page;\n var translate = 'translate(0,-' + size + ')';\n if (!this.isChartControl && this.isVertical) {\n var pageLength = page * this.maxColumns;\n size = this.pageXCollections[page * this.maxColumns] - this.legendBounds.x;\n size = size < 0 ? 0 : size; // to avoid small pixel variation\n translate = 'translate(-' + size + ',0)';\n }\n this.legendTranslateGroup.setAttribute('transform', translate);\n pagingText.textContent = (pageNumber) + '/' + this.totalPages;\n this.currentPage = pageNumber;\n };\n /**\n * To change legend pages for chart and accumulation chart\n */\n BaseLegend.prototype.changePage = function (event, pageUp) {\n var pageText = document.getElementById(this.legendID + '_pagenumber');\n var page = parseInt(pageText.textContent.split('/')[0], 10);\n if (pageUp && page > 1) {\n this.translatePage(pageText, (page - 2), (page - 1));\n }\n else if (!pageUp && page < this.totalPages) {\n this.translatePage(pageText, page, (page + 1));\n }\n };\n /**\n * To find legend elements id based on chart or accumulation chart\n * @private\n */\n BaseLegend.prototype.generateId = function (option, prefix, count) {\n if (this.isChartControl) {\n return prefix + count;\n }\n else {\n return prefix + option.pointIndex;\n }\n };\n /**\n * To show or hide trimmed text tooltip for legend.\n * @return {void}\n * @private\n */\n BaseLegend.prototype.move = function (event) {\n var _this = this;\n var x = this.chart.mouseX;\n var y = this.chart.mouseY;\n if (event.target.textContent.indexOf('...') > -1) {\n var targetId = event.target.id.split(this.legendID + '_text_');\n if (targetId.length === 2) {\n var index = parseInt(targetId[1], 10);\n var element = this.chart.element;\n if (!isNaN(index)) {\n if (this.chart.isTouch) {\n removeElement(this.chart.element.id + '_EJ2_Legend_Tooltip');\n }\n if (this.isChartControl) {\n showTooltip(this.chart.series[index].name, x, y, element.offsetWidth, element.id + '_EJ2_Legend_Tooltip', getElement(this.chart.element.id + '_Secondary_Element'));\n }\n else {\n showTooltip(this.chart.visibleSeries[0].points[index].x.toString(), x + 10, y + 10, element.offsetWidth, element.id + '_EJ2_Legend_Tooltip', getElement(this.chart.element.id + '_Secondary_Element'));\n }\n }\n }\n }\n else {\n removeElement(this.chart.element.id + '_EJ2_Legend_Tooltip');\n }\n if (this.chart.isTouch) {\n clearTimeout(this.clearTooltip);\n this.clearTooltip = setTimeout(function () { removeElement(_this.chart.element.id + '_EJ2_Legend_Tooltip'); }, 1000);\n }\n };\n return BaseLegend;\n}());\nexport { BaseLegend };\n/**\n * Class for legend options\n * @private\n */\nvar LegendOptions = /** @class */ (function () {\n function LegendOptions(text, fill, shape, visible, type, markerShape, markerVisibility, pointIndex, seriesIndex) {\n this.location = { x: 0, y: 0 };\n this.text = text;\n this.fill = fill;\n this.shape = shape;\n this.visible = visible;\n this.type = type;\n this.markerVisibility = markerVisibility;\n this.markerShape = markerShape;\n this.pointIndex = pointIndex;\n this.seriesIndex = seriesIndex;\n }\n return LegendOptions;\n}());\nexport { LegendOptions };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n///
\nimport { Property, Complex } from '@syncfusion/ej2-base';\nimport { Connector } from '../../common/model/base';\nimport { SeriesBase } from '../series/chart-series';\nimport { Rect, firstToLowerCase } from '../../common/utils/helper';\n/**\n * Defines how to represent the market trend using technical indicators\n */\nvar TechnicalIndicator = /** @class */ (function (_super) {\n __extends(TechnicalIndicator, _super);\n function TechnicalIndicator() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.clipRect = new Rect(0, 0, 0, 0);\n return _this;\n }\n /** @private */\n TechnicalIndicator.prototype.setDataSource = function (series, chart) {\n if (series) {\n this.xData = series.xData;\n this.yData = series.yData;\n this.points = series.points;\n }\n var type = firstToLowerCase(this.type);\n chart[type + 'IndicatorModule'].initDataSource(this, chart);\n chart.visibleSeriesCount += this.targetSeries.length;\n };\n __decorate([\n Property('Sma')\n ], TechnicalIndicator.prototype, \"type\", void 0);\n __decorate([\n Property(14)\n ], TechnicalIndicator.prototype, \"period\", void 0);\n __decorate([\n Property(14)\n ], TechnicalIndicator.prototype, \"kPeriod\", void 0);\n __decorate([\n Property(3)\n ], TechnicalIndicator.prototype, \"dPeriod\", void 0);\n __decorate([\n Property(80)\n ], TechnicalIndicator.prototype, \"overBought\", void 0);\n __decorate([\n Property(20)\n ], TechnicalIndicator.prototype, \"overSold\", void 0);\n __decorate([\n Property(2)\n ], TechnicalIndicator.prototype, \"standardDeviation\", void 0);\n __decorate([\n Property('Close')\n ], TechnicalIndicator.prototype, \"field\", void 0);\n __decorate([\n Property(12)\n ], TechnicalIndicator.prototype, \"slowPeriod\", void 0);\n __decorate([\n Property(26)\n ], TechnicalIndicator.prototype, \"fastPeriod\", void 0);\n __decorate([\n Property(true)\n ], TechnicalIndicator.prototype, \"showZones\", void 0);\n __decorate([\n Complex({ color: '#ff9933', width: 2 }, Connector)\n ], TechnicalIndicator.prototype, \"macdLine\", void 0);\n __decorate([\n Property('Both')\n ], TechnicalIndicator.prototype, \"macdType\", void 0);\n __decorate([\n Property('#2ecd71')\n ], TechnicalIndicator.prototype, \"macdPositiveColor\", void 0);\n __decorate([\n Property('#e74c3d')\n ], TechnicalIndicator.prototype, \"macdNegativeColor\", void 0);\n __decorate([\n Property('rgba(211,211,211,0.25)')\n ], TechnicalIndicator.prototype, \"bandColor\", void 0);\n __decorate([\n Complex({ color: '#ffb735', width: 1 }, Connector)\n ], TechnicalIndicator.prototype, \"upperLine\", void 0);\n __decorate([\n Complex({ color: '#f2ec2f', width: 1 }, Connector)\n ], TechnicalIndicator.prototype, \"lowerLine\", void 0);\n __decorate([\n Complex({ color: '#f2ec2f', width: 1 }, Connector)\n ], TechnicalIndicator.prototype, \"periodLine\", void 0);\n __decorate([\n Property('')\n ], TechnicalIndicator.prototype, \"seriesName\", void 0);\n return TechnicalIndicator;\n}(SeriesBase));\nexport { TechnicalIndicator };\n","/**\n * Dictionary.ts class for EJ2-PDF\n * @private\n * @hidden\n */\nimport { defaultToString } from './utils';\n/**\n * @private\n * @hidden\n */\nvar Dictionary = /** @class */ (function () {\n /**\n * @private\n * @hidden\n */\n function Dictionary(toStringFunction) {\n this.table = {};\n this.nElements = 0;\n this.toStr = toStringFunction || defaultToString;\n }\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.getValue = function (key) {\n var pair = this.table['$' + this.toStr(key)];\n if (typeof pair === 'undefined') {\n return undefined;\n }\n return pair.value;\n };\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.setValue = function (key, value) {\n // if (typeof key === 'undefined' || typeof value === 'undefined') {\n // return undefined;\n // }\n var ret;\n var k = '$' + this.toStr(key);\n var previousElement = this.table[k];\n // if (typeof previousElement === 'undefined') {\n this.nElements++;\n ret = undefined;\n // }\n this.table[k] = {\n key: key,\n value: value\n };\n return ret;\n };\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.remove = function (key) {\n var k = '$' + this.toStr(key);\n var previousElement = this.table[k];\n // if (typeof previousElement !== 'undefined') {\n delete this.table[k];\n this.nElements--;\n return previousElement.value;\n // }\n // return undefined;\n };\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.keys = function () {\n var keysArray = [];\n var namesOfKeys = Object.keys(this.table);\n for (var index1 = 0; index1 < namesOfKeys.length; index1++) {\n // if (Object.prototype.hasOwnProperty.call(this.table, namesOfKeys[index1])) {\n var pair1 = this.table[namesOfKeys[index1]];\n keysArray.push(pair1.key);\n // }\n }\n return keysArray;\n };\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.values = function () {\n var valuesArray = [];\n var namesOfValues = Object.keys(this.table);\n for (var index2 = 0; index2 < namesOfValues.length; index2++) {\n // if (Object.prototype.hasOwnProperty.call(this.table, namesOfValues[index2])) {\n var pair2 = this.table[namesOfValues[index2]];\n valuesArray.push(pair2.value);\n // }\n }\n return valuesArray;\n };\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.containsKey = function (key) {\n var retutnValue = true;\n if (typeof this.getValue(key) === 'undefined') {\n retutnValue = true;\n }\n else {\n retutnValue = false;\n }\n return !retutnValue;\n };\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.clear = function () {\n this.table = {};\n this.nElements = 0;\n };\n /**\n * @private\n * @hidden\n */\n Dictionary.prototype.size = function () {\n return this.nElements;\n };\n return Dictionary;\n}()); // End of dictionary\nexport { Dictionary };\n","/**\n * `PdfName` class is used to perform name (element names) related primitive operations.\n * @private\n */\nvar PdfName = /** @class */ (function () {\n function PdfName(value) {\n /**\n * `Start symbol` of the name object.\n * @default /\n * @private\n */\n this.stringStartMark = '/';\n /**\n * `Value` of the element.\n * @private\n */\n this.internalValue = '';\n /**\n * Indicates if the object is currently in `saving state or not`.\n * @default false\n * @private\n */\n this.isSaving6 = false;\n /**\n * Internal variable to store the `position`.\n * @default -1\n * @private\n */\n this.position6 = -1;\n this.internalValue = this.normalizeValue(value);\n }\n Object.defineProperty(PdfName.prototype, \"status\", {\n //property\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.status6;\n },\n set: function (value) {\n this.status6 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfName.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.isSaving6;\n },\n set: function (value) {\n this.isSaving6 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfName.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index6;\n },\n set: function (value) {\n this.index6 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfName.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.position6;\n },\n set: function (value) {\n this.position6 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfName.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfName.prototype, \"value\", {\n /**\n * Gets or sets the `value` of the object.\n * @private\n */\n get: function () {\n return this.internalValue;\n },\n set: function (value) {\n // if (value !== this.value) {\n var val = value;\n if (value !== null && value.length > 0) {\n // val = (value.substring(0, 1) === this.stringStartMark) ? value.substring(1) : value;\n val = value;\n this.internalValue = this.normalizeValue(val);\n }\n else {\n this.internalValue = val;\n }\n // }\n },\n enumerable: true,\n configurable: true\n });\n //public methods\n /**\n * `Saves` the name using the specified writer.\n * @private\n */\n PdfName.prototype.save = function (writer) {\n // if (writer === null) {\n // throw new Error('ArgumentNullException : writer');\n // }\n writer.write(this.toString());\n };\n /**\n * Gets `string` representation of the primitive.\n * @private\n */\n PdfName.prototype.toString = function () {\n return (this.stringStartMark + this.escapeString(this.value));\n };\n /**\n * Creates a `copy of PdfName`.\n * @private\n */\n PdfName.prototype.clone = function (crossTable) {\n var newName = new PdfName();\n newName.value = this.internalValue;\n return newName;\n };\n /**\n * Replace some characters with its `escape sequences`.\n * @private\n */\n PdfName.prototype.escapeString = function (stringValue) {\n // if (str === null) {\n // throw new Error('ArgumentNullException : str');\n // }\n // if (str === '') {\n // return str;\n // }\n var result = '';\n var len = 0;\n for (var i = 0, len_1 = stringValue.length; i < len_1; i++) {\n var ch = stringValue[i];\n var index = PdfName.delimiters.indexOf(ch);\n // switch (ch) {\n // case '\\r' :\n // result = result + '\\\\r';\n // break;\n // case '\\n' :\n // result = result + '\\n';\n // break;\n // case '(' :\n // case ')' :\n // case '\\\\' :\n // //result.Append( '\\\\' ).Append( ch );\n // result = result + ch;\n // break;\n // default :\n // result = result + ch;\n // break;\n // }\n result = result + ch;\n }\n return result;\n };\n //methiods\n /**\n * Replace a symbol with its code with the precedence of the `sharp sign`.\n * @private\n */\n PdfName.prototype.normalizeValue = function (value, c) {\n // if (typeof c === undefined) {\n // let str : string = value;\n // for (let i : number = 0; i < PdfName.replacements.length; i++) {\n // str = this.normalizeValue(str, c);\n // }\n // return str;\n // } else {\n var strFormat = '#{0:X}';\n //return value.replace(c.toString(),String.format(strFormat,c));\n return value;\n // }\n };\n /**\n * PDF `special characters`.\n * @private\n */\n PdfName.delimiters = '()<>[]{}/%}';\n /**\n * The symbols that are not allowed in PDF names and `should be replaced`.\n * @private\n */\n PdfName.replacements = [' ', '\\t', '\\n', '\\r'];\n return PdfName;\n}());\nexport { PdfName };\n","/**\n * PdfOperators.ts class for EJ2-PDF\n * Class of string PDF common operators.\n * @private\n */\nvar Operators = /** @class */ (function () {\n /**\n * Create an instance of `PdfOperator` class.\n * @private\n */\n function Operators() {\n /**\n * Specifies the value of `test`.\n * @private\n */\n this.forTest = 'test';\n this.forTest = Operators.obj;\n }\n /**\n * Specifies the value of `obj`.\n * @private\n */\n Operators.obj = 'obj';\n /**\n * Specifies the value of `endObj`.\n * @private\n */\n Operators.endObj = 'endobj';\n /**\n * Specifies the value of `R`.\n * @private\n */\n Operators.r = 'R';\n /**\n * Specifies the value of ` `.\n * @private\n */\n Operators.whiteSpace = ' ';\n /**\n * Specifies the value of `/`.\n * @private\n */\n Operators.slash = '/';\n /**\n * Specifies the value of `\\r\\n`.\n * @private\n */\n Operators.newLine = '\\r\\n';\n /**\n * Specifies the value of `stream`.\n * @private\n */\n Operators.stream = 'stream';\n /**\n * Specifies the value of `endStream`.\n * @private\n */\n Operators.endStream = 'endstream';\n /**\n * Specifies the value of `xref`.\n * @private\n */\n Operators.xref = 'xref';\n /**\n * Specifies the value of `f`.\n * @private\n */\n Operators.f = 'f';\n /**\n * Specifies the value of `n`.\n * @private\n */\n Operators.n = 'n';\n /**\n * Specifies the value of `trailer`.\n * @private\n */\n Operators.trailer = 'trailer';\n /**\n * Specifies the value of `startxref`.\n * @private\n */\n Operators.startxref = 'startxref';\n /**\n * Specifies the value of `eof`.\n * @private\n */\n Operators.eof = '%%EOF';\n /**\n * Specifies the value of `header`.\n * @private\n */\n Operators.header = '%PDF-1.5';\n /**\n * Specifies the value of `beginText`.\n * @private\n */\n Operators.beginText = 'BT';\n /**\n * Specifies the value of `endText`.\n * @private\n */\n Operators.endText = 'ET';\n /**\n * Specifies the value of `m`.\n * @private\n */\n Operators.beginPath = 'm';\n /**\n * Specifies the value of `l`.\n * @private\n */\n Operators.appendLineSegment = 'l';\n /**\n * Specifies the value of `S`.\n * @private\n */\n Operators.stroke = 'S';\n /**\n * Specifies the value of `f`.\n * @private\n */\n Operators.fill = 'f';\n /**\n * Specifies the value of `f*`.\n * @private\n */\n Operators.fillEvenOdd = 'f*';\n /**\n * Specifies the value of `B`.\n * @private\n */\n Operators.fillStroke = 'B';\n /**\n * Specifies the value of `B*`.\n * @private\n */\n Operators.fillStrokeEvenOdd = 'B*';\n /**\n * Specifies the value of `c`.\n * @private\n */\n Operators.appendbeziercurve = 'c';\n /**\n * Specifies the value of `re`.\n * @private\n */\n Operators.appendRectangle = 're';\n /**\n * Specifies the value of `q`.\n * @private\n */\n Operators.saveState = 'q';\n /**\n * Specifies the value of `Q`.\n * @private\n */\n Operators.restoreState = 'Q';\n /**\n * Specifies the value of `Do`.\n * @private\n */\n Operators.paintXObject = 'Do';\n /**\n * Specifies the value of `cm`.\n * @private\n */\n Operators.modifyCtm = 'cm';\n /**\n * Specifies the value of `Tm`.\n * @private\n */\n Operators.modifyTM = 'Tm';\n /**\n * Specifies the value of `w`.\n * @private\n */\n Operators.setLineWidth = 'w';\n /**\n * Specifies the value of `J`.\n * @private\n */\n Operators.setLineCapStyle = 'J';\n /**\n * Specifies the value of `j`.\n * @private\n */\n Operators.setLineJoinStyle = 'j';\n /**\n * Specifies the value of `d`.\n * @private\n */\n Operators.setDashPattern = 'd';\n /**\n * Specifies the value of `i`.\n * @private\n */\n Operators.setFlatnessTolerance = 'i';\n /**\n * Specifies the value of `h`.\n * @private\n */\n Operators.closePath = 'h';\n /**\n * Specifies the value of `s`.\n * @private\n */\n Operators.closeStrokePath = 's';\n /**\n * Specifies the value of `b`.\n * @private\n */\n Operators.closeFillStrokePath = 'b';\n /**\n * Specifies the value of `setCharacterSpace`.\n * @private\n */\n Operators.setCharacterSpace = 'Tc';\n /**\n * Specifies the value of `setWordSpace`.\n * @private\n */\n Operators.setWordSpace = 'Tw';\n /**\n * Specifies the value of `setHorizontalScaling`.\n * @private\n */\n Operators.setHorizontalScaling = 'Tz';\n /**\n * Specifies the value of `setTextLeading`.\n * @private\n */\n Operators.setTextLeading = 'TL';\n /**\n * Specifies the value of `setFont`.\n * @private\n */\n Operators.setFont = 'Tf';\n /**\n * Specifies the value of `setRenderingMode`.\n * @private\n */\n Operators.setRenderingMode = 'Tr';\n /**\n * Specifies the value of `setTextRise`.\n * @private\n */\n Operators.setTextRise = 'Ts';\n /**\n * Specifies the value of `setTextScaling`.\n * @private\n */\n Operators.setTextScaling = 'Tz';\n /**\n * Specifies the value of `setCoords`.\n * @private\n */\n Operators.setCoords = 'Td';\n /**\n * Specifies the value of `goToNextLine`.\n * @private\n */\n Operators.goToNextLine = 'T*';\n /**\n * Specifies the value of `setText`.\n * @private\n */\n Operators.setText = 'Tj';\n /**\n * Specifies the value of `setTextWithFormatting`.\n * @private\n */\n Operators.setTextWithFormatting = 'TJ';\n /**\n * Specifies the value of `setTextOnNewLine`.\n * @private\n */\n Operators.setTextOnNewLine = '\\'';\n /**\n * Specifies the value of `selectcolorspaceforstroking`.\n * @private\n */\n Operators.selectcolorspaceforstroking = 'CS';\n /**\n * Specifies the value of `selectcolorspacefornonstroking`.\n * @private\n */\n Operators.selectcolorspacefornonstroking = 'cs';\n /**\n * Specifies the value of `setrbgcolorforstroking`.\n * @private\n */\n Operators.setrbgcolorforstroking = 'RG';\n /**\n * Specifies the value of `setrbgcolorfornonstroking`.\n * @private\n */\n Operators.setrbgcolorfornonstroking = 'rg';\n /**\n * Specifies the value of `K`.\n * @private\n */\n Operators.setcmykcolorforstroking = 'K';\n /**\n * Specifies the value of `k`.\n * @private\n */\n Operators.setcmykcolorfornonstroking = 'k';\n /**\n * Specifies the value of `G`.\n * @private\n */\n Operators.setgraycolorforstroking = 'G';\n /**\n * Specifies the value of `g`.\n * @private\n */\n Operators.setgraycolorfornonstroking = 'g';\n /**\n * Specifies the value of `W`.\n * @private\n */\n Operators.clipPath = 'W';\n /**\n * Specifies the value of `clipPathEvenOdd`.\n * @private\n */\n Operators.clipPathEvenOdd = 'W*';\n /**\n * Specifies the value of `n`.\n * @private\n */\n Operators.endPath = 'n';\n /**\n * Specifies the value of `setGraphicsState`.\n * @private\n */\n Operators.setGraphicsState = 'gs';\n /**\n * Specifies the value of `%`.\n * @private\n */\n Operators.comment = '%';\n /**\n * Specifies the value of `*`.\n * @private\n */\n Operators.evenOdd = '*';\n /**\n * Specifies the value of `M`.\n * @private\n */\n Operators.setMiterLimit = 'M';\n return Operators;\n}());\nexport { Operators };\n","/**\n * dictionaryProperties.ts class for EJ2-PDF\n * PDF dictionary properties.\n * @private\n */\nvar DictionaryProperties = /** @class */ (function () {\n /**\n * Initialize an instance for `PdfDictionaryProperties` class.\n * @private\n */\n function DictionaryProperties() {\n /**\n * Specifies the value of `Pages`.\n * @private\n */\n this.pages = 'Pages';\n /**\n * Specifies the value of `Kids`.\n * @private\n */\n this.kids = 'Kids';\n /**\n * Specifies the value of `Count`.\n * @private\n */\n this.count = 'Count';\n /**\n * Specifies the value of `Resources`.\n * @private\n */\n this.resources = 'Resources';\n /**\n * Specifies the value of `Type`.\n * @private\n */\n this.type = 'Type';\n /**\n * Specifies the value of `Size`.\n * @private\n */\n this.size = 'Size';\n /**\n * Specifies the value of `MediaBox`.\n * @private\n */\n this.mediaBox = 'MediaBox';\n /**\n * Specifies the value of `Parent`.\n * @private\n */\n this.parent = 'Parent';\n /**\n * Specifies the value of `Root`.\n * @private\n */\n this.root = 'Root';\n /**\n * Specifies the value of `DecodeParms`.\n * @private\n */\n this.decodeParms = 'DecodeParms';\n /**\n * Specifies the value of `Filter`.\n * @private\n */\n this.filter = 'Filter';\n /**\n * Specifies the value of `Font`.\n * @private\n */\n this.font = 'Font';\n /**\n * Specifies the value of `Type1`.\n * @private\n */\n this.type1 = 'Type1';\n /**\n * Specifies the value of `BaseFont`.\n * @private\n */\n this.baseFont = 'BaseFont';\n /**\n * Specifies the value of `Encoding`.\n * @private\n */\n this.encoding = 'Encoding';\n /**\n * Specifies the value of `Subtype`.\n * @private\n */\n this.subtype = 'Subtype';\n /**\n * Specifies the value of `Contents`.\n * @private\n */\n this.contents = 'Contents';\n /**\n * Specifies the value of `ProcSet`.\n * @private\n */\n this.procset = 'ProcSet';\n /**\n * Specifies the value of `ColorSpace`.\n * @private\n */\n this.colorSpace = 'ColorSpace';\n /**\n * Specifies the value of `ExtGState`.\n * @private\n */\n this.extGState = 'ExtGState';\n /**\n * Specifies the value of `Pattern`.\n * @private\n */\n this.pattern = 'Pattern';\n /**\n * Specifies the value of `XObject`.\n * @private\n */\n this.xObject = 'XObject';\n /**\n * Specifies the value of `Length`.\n * @private\n */\n this.length = 'Length';\n /**\n * Specifies the value of `Width`.\n * @private\n */\n this.width = 'Width';\n /**\n * Specifies the value of `Height`.\n * @private\n */\n this.height = 'Height';\n /**\n * Specifies the value of `BitsPerComponent`.\n * @private\n */\n this.bitsPerComponent = 'BitsPerComponent';\n /**\n * Specifies the value of `Image`.\n * @private\n */\n this.image = 'Image';\n /**\n * Specifies the value of `dctdecode`.\n * @private\n */\n this.dctdecode = 'DCTDecode';\n /**\n * Specifies the value of `Columns`.\n * @private\n */\n this.columns = 'Columns';\n /**\n * Specifies the value of `BlackIs1`.\n * @private\n */\n this.blackIs1 = 'BlackIs1';\n /**\n * Specifies the value of `K`.\n * @private\n */\n this.k = 'K';\n /**\n * Specifies the value of `S`.\n * @private\n */\n this.s = 'S';\n /**\n * Specifies the value of `Predictor`.\n * @private\n */\n this.predictor = 'Predictor';\n /**\n * Specifies the value of `DeviceRGB`.\n * @private\n */\n this.deviceRgb = 'DeviceRGB';\n /**\n * Specifies the value of `Next`.\n * @private\n */\n this.next = 'Next';\n /**\n * Specifies the value of `Action`.\n * @private\n */\n this.action = 'Action';\n /**\n * Specifies the value of `Link`.\n * @private\n */\n this.link = 'Link';\n /**\n *\n * Specifies the value of `A`.\n * @private\n */\n this.a = 'A';\n /**\n * Specifies the value of `Annot`.\n * @private\n */\n this.annot = 'Annot';\n /**\n * Specifies the value of `P`.\n * @private\n */\n this.p = 'P';\n /**\n * Specifies the value of `C`.\n * @private\n */\n this.c = 'C';\n /**\n * Specifies the value of `Rect`.\n * @private\n */\n this.rect = 'Rect';\n /**\n * Specifies the value of `URI`.\n * @private\n */\n this.uri = 'URI';\n /**\n * Specifies the value of `Annots`.\n * @private\n */\n this.annots = 'Annots';\n /**\n * Specifies the value of `ca`.\n * @private\n */\n this.ca = 'ca';\n /**\n * Specifies the value of `CA`.\n * @private\n */\n this.CA = 'CA';\n /**\n * Specifies the value of `XYZ`.\n * @private\n */\n this.xyz = 'XYZ';\n /**\n * Specifies the value of `Fit`.\n * @private\n */\n this.fit = 'Fit';\n /**\n * Specifies the value of `Dest`.\n * @private\n */\n this.dest = 'Dest';\n /**\n * Specifies the value of `BM`.\n * @private\n */\n this.BM = 'BM';\n /**\n * Specifies the value of `flatedecode`.\n * @private\n */\n this.flatedecode = 'FlateDecode';\n /**\n * Specifies the value of `Rotate`.\n * @private\n */\n this.rotate = 'Rotate';\n /**\n * Specifies the value of 'bBox'.\n * @private\n */\n this.bBox = 'BBox';\n /**\n * Specifies the value of 'form'.\n * @private\n */\n this.form = 'Form';\n /**\n * Specifies the value of 'w'.\n * @private\n */\n this.w = 'W';\n /**\n * Specifies the value of 'cIDFontType2'.\n * @private\n */\n this.cIDFontType2 = 'CIDFontType2';\n /**\n * Specifies the value of 'cIDToGIDMap'.\n * @private\n */\n this.cIDToGIDMap = 'CIDToGIDMap';\n /**\n * Specifies the value of 'identity'.\n * @private\n */\n this.identity = 'Identity';\n /**\n * Specifies the value of 'dw'.\n * @private\n */\n this.dw = 'DW';\n /**\n * Specifies the value of 'fontDescriptor'.\n * @private\n */\n this.fontDescriptor = 'FontDescriptor';\n /**\n * Specifies the value of 'cIDSystemInfo'.\n * @private\n */\n this.cIDSystemInfo = 'CIDSystemInfo';\n /**\n * Specifies the value of 'fontName'.\n * @private\n */\n this.fontName = 'FontName';\n /**\n * Specifies the value of 'flags'.\n * @private\n */\n this.flags = 'Flags';\n /**\n * Specifies the value of 'fontBBox'.\n * @private\n */\n this.fontBBox = 'FontBBox';\n /**\n * Specifies the value of 'missingWidth'.\n * @private\n */\n this.missingWidth = 'MissingWidth';\n /**\n * Specifies the value of 'stemV'.\n * @private\n */\n this.stemV = 'StemV';\n /**\n * Specifies the value of 'italicAngle'.\n * @private\n */\n this.italicAngle = 'ItalicAngle';\n /**\n * Specifies the value of 'capHeight'.\n * @private\n */\n this.capHeight = 'CapHeight';\n /**\n * Specifies the value of 'ascent'.\n * @private\n */\n this.ascent = 'Ascent';\n /**\n * Specifies the value of 'descent'.\n * @private\n */\n this.descent = 'Descent';\n /**\n * Specifies the value of 'leading'.\n * @private\n */\n this.leading = 'Leading';\n /**\n * Specifies the value of 'avgWidth'.\n * @private\n */\n this.avgWidth = 'AvgWidth';\n /**\n * Specifies the value of 'fontFile2'.\n * @private\n */\n this.fontFile2 = 'FontFile2';\n /**\n * Specifies the value of 'maxWidth'.\n * @private\n */\n this.maxWidth = 'MaxWidth';\n /**\n * Specifies the value of 'xHeight'.\n * @private\n */\n this.xHeight = 'XHeight';\n /**\n * Specifies the value of 'stemH'.\n * @private\n */\n this.stemH = 'StemH';\n /**\n * Specifies the value of 'registry'.\n * @private\n */\n this.registry = 'Registry';\n /**\n * Specifies the value of 'ordering'.\n * @private\n */\n this.ordering = 'Ordering';\n /**\n * Specifies the value of 'supplement'.\n * @private\n */\n this.supplement = 'Supplement';\n /**\n * Specifies the value of 'type0'.\n * @private\n */\n this.type0 = 'Type0';\n /**\n * Specifies the value of 'identityH'.\n * @private\n */\n this.identityH = 'Identity-H';\n /**\n * Specifies the value of 'toUnicode'.\n * @private\n */\n this.toUnicode = 'ToUnicode';\n /**\n * Specifies the value of 'descendantFonts'.\n * @private\n */\n this.descendantFonts = 'DescendantFonts';\n //\n }\n return DictionaryProperties;\n}());\nexport { DictionaryProperties };\n","import { Dictionary } from './../collections/dictionary';\nimport { PdfName } from './pdf-name';\nimport { Operators } from './../input-output/pdf-operators';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\n/**\n * `PdfDictionary` class is used to perform primitive operations.\n * @private\n */\nvar PdfDictionary = /** @class */ (function () {\n function PdfDictionary(dictionary) {\n /**\n * Internal variable to store the `position`.\n * @default -1\n * @private\n */\n this.position7 = -1;\n /**\n * The `IPdfSavable` with the specified key.\n * @private\n */\n this.primitiveItems = new Dictionary();\n /**\n * `Start marker` for dictionary.\n * @private\n */\n this.prefix = '<<';\n /**\n * `End marker` for dictionary.\n * @private\n */\n this.suffix = '>>';\n /**\n * @hidden\n * @private\n */\n this.resources = [];\n /**\n * Internal variable to hold `cloned object`.\n * @default null\n * @private\n */\n this.object = null;\n /**\n * Flag for PDF file formar 1.5 is dictionary `archiving` needed.\n * @default true\n * @private\n */\n this.archive = true;\n /**\n * Represents the Font dictionary.\n * @hidden\n * @private\n */\n this.isFont = false;\n if (typeof dictionary === 'undefined') {\n this.primitiveItems = new Dictionary();\n this.encrypt = true;\n this.dictionaryProperties = new DictionaryProperties();\n }\n else {\n this.primitiveItems = new Dictionary();\n var keys = dictionary.items.keys();\n var values = dictionary.items.values();\n for (var index = 0; index < dictionary.items.size(); index++) {\n this.primitiveItems.setValue(keys[index], values[index]);\n }\n this.status = dictionary.status;\n this.freezeChanges(this);\n this.encrypt = true;\n this.dictionaryProperties = new DictionaryProperties();\n }\n }\n Object.defineProperty(PdfDictionary.prototype, \"items\", {\n //Properties\n /**\n * Gets or sets the `IPdfSavable` with the specified key.\n * @private\n */\n get: function () {\n return this.primitiveItems;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDictionary.prototype, \"status\", {\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.status7;\n },\n set: function (value) {\n this.status7 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDictionary.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.isSaving7;\n },\n set: function (value) {\n this.isSaving7 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDictionary.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index7;\n },\n set: function (value) {\n this.index7 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDictionary.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n return this.object;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDictionary.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.position7;\n },\n set: function (value) {\n this.position7 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDictionary.prototype, \"Count\", {\n /**\n * Gets the `count`.\n * @private\n */\n get: function () {\n return this.primitiveItems.size();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDictionary.prototype, \"Dictionary\", {\n /**\n * Collection of `items` in the object.\n * @private\n */\n get: function () {\n return this;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get flag if need to `archive` dictionary.\n * @private\n */\n PdfDictionary.prototype.getArchive = function () {\n return this.archive;\n };\n /**\n * Set flag if need to `archive` dictionary.\n * @private\n */\n PdfDictionary.prototype.setArchive = function (value) {\n this.archive = value;\n };\n /**\n * Sets flag if `encryption` is needed.\n * @private\n */\n PdfDictionary.prototype.setEncrypt = function (value) {\n this.encrypt = value;\n this.modify();\n };\n /**\n * Gets flag if `encryption` is needed.\n * @private\n */\n PdfDictionary.prototype.getEncrypt = function () {\n return this.encrypt;\n };\n /**\n * `Freezes` the changes.\n * @private\n */\n PdfDictionary.prototype.freezeChanges = function (freezer) {\n this.bChanged = false;\n };\n /**\n * Creates a `copy of PdfDictionary`.\n * @private\n */\n PdfDictionary.prototype.clone = function (crossTable) {\n //Need to add more codings\n var newDict = new PdfDictionary();\n return newDict;\n };\n /**\n * `Mark` this instance modified.\n * @private\n */\n PdfDictionary.prototype.modify = function () {\n this.bChanged = true;\n };\n /**\n * `Removes` the specified key.\n * @private\n */\n PdfDictionary.prototype.remove = function (key) {\n if (typeof key !== 'string') {\n this.primitiveItems.remove(key.value);\n this.modify();\n }\n else {\n this.remove(new PdfName(key));\n }\n };\n /**\n * `Determines` whether the dictionary contains the key.\n * @private\n */\n PdfDictionary.prototype.containsKey = function (key) {\n var returnValue = false;\n returnValue = this.primitiveItems.containsKey(key.toString());\n return returnValue;\n };\n /**\n * Raises event `BeginSave`.\n * @private\n */\n PdfDictionary.prototype.onBeginSave = function () {\n this.beginSave.sender.beginSave();\n };\n /**\n * Raises event `Font Dictionary BeginSave`.\n * @private\n */\n PdfDictionary.prototype.onFontDictionaryBeginSave = function () {\n this.fontDictionaryBeginSave.sender.fontDictionaryBeginSave();\n };\n /**\n * Raises event `Descendant Font BeginSave`.\n * @private\n */\n PdfDictionary.prototype.onDescendantFontBeginSave = function () {\n this.descendantFontBeginSave.sender.descendantFontBeginSave();\n };\n /**\n * Raises event 'BeginSave'.\n * @private\n */\n PdfDictionary.prototype.onTemplateBeginSave = function () {\n this.pageBeginDrawTemplate.sender.pageBeginSave();\n };\n /**\n * Raises event `BeginSave`.\n * @private\n */\n PdfDictionary.prototype.onBeginAnnotationSave = function () {\n this.annotationBeginSave.sender.beginSave();\n };\n /**\n * Raises event `BeginSave`.\n * @private\n */\n PdfDictionary.prototype.onSectionBeginSave = function (writer) {\n var saveEvent = this.sectionBeginSave;\n saveEvent.sender.beginSave(saveEvent.state, writer);\n };\n PdfDictionary.prototype.save = function (writer, bRaiseEvent) {\n if (typeof bRaiseEvent === 'undefined') {\n this.save(writer, true);\n }\n else {\n writer.write(this.prefix);\n if (typeof this.beginSave !== 'undefined') {\n this.onBeginSave();\n }\n if (typeof this.descendantFontBeginSave !== 'undefined') {\n this.onDescendantFontBeginSave();\n }\n if (typeof this.fontDictionaryBeginSave !== 'undefined') {\n this.onFontDictionaryBeginSave();\n }\n if (typeof this.annotationBeginSave !== 'undefined') {\n this.onBeginAnnotationSave();\n }\n if (typeof this.sectionBeginSave !== 'undefined') {\n this.onSectionBeginSave(writer);\n }\n if (typeof this.pageBeginDrawTemplate !== 'undefined') {\n this.onTemplateBeginSave();\n }\n // }\n if (this.Count > 0) {\n this.saveItems(writer);\n }\n writer.write(this.suffix);\n writer.write(Operators.newLine);\n }\n };\n /**\n * `Save dictionary items`.\n * @private\n */\n PdfDictionary.prototype.saveItems = function (writer) {\n writer.write(Operators.newLine);\n var keys = this.primitiveItems.keys();\n var values = this.primitiveItems.values();\n for (var index = 0; index < keys.length; index++) {\n var key = keys[index];\n var name_1 = new PdfName(key);\n name_1.save(writer);\n writer.write(Operators.whiteSpace);\n var resources = values[index];\n resources.save(writer);\n writer.write(Operators.newLine);\n }\n };\n return PdfDictionary;\n}());\nexport { PdfDictionary };\nvar SaveSectionCollectionEventHandler = /** @class */ (function () {\n /**\n * New instance for `save section collection event handler` class.\n * @private\n */\n function SaveSectionCollectionEventHandler(sender) {\n this.sender = sender;\n }\n return SaveSectionCollectionEventHandler;\n}());\nexport { SaveSectionCollectionEventHandler };\nvar SaveDescendantFontEventHandler = /** @class */ (function () {\n /**\n * New instance for `save section collection event handler` class.\n * @private\n */\n function SaveDescendantFontEventHandler(sender) {\n this.sender = sender;\n }\n return SaveDescendantFontEventHandler;\n}());\nexport { SaveDescendantFontEventHandler };\nvar SaveFontDictionaryEventHandler = /** @class */ (function () {\n /**\n * New instance for `save section collection event handler` class.\n * @private\n */\n function SaveFontDictionaryEventHandler(sender) {\n this.sender = sender;\n }\n return SaveFontDictionaryEventHandler;\n}());\nexport { SaveFontDictionaryEventHandler };\nvar SaveAnnotationEventHandler = /** @class */ (function () {\n /**\n * New instance for `save annotation event handler` class.\n * @private\n */\n function SaveAnnotationEventHandler(sender) {\n this.sender = sender;\n }\n return SaveAnnotationEventHandler;\n}());\nexport { SaveAnnotationEventHandler };\nvar SaveSectionEventHandler = /** @class */ (function () {\n // constructors\n /**\n * New instance for `save section event handler` class.\n * @private\n */\n function SaveSectionEventHandler(sender, state) {\n this.sender = sender;\n this.state = state;\n }\n return SaveSectionEventHandler;\n}());\nexport { SaveSectionEventHandler };\n/**\n * SaveTemplateEventHandler class used to store information about template elements.\n * @private\n * @hidden\n */\nvar SaveTemplateEventHandler = /** @class */ (function () {\n /**\n * New instance for save section collection event handler class.\n * @public\n */\n function SaveTemplateEventHandler(sender) {\n this.sender = sender;\n }\n return SaveTemplateEventHandler;\n}());\nexport { SaveTemplateEventHandler };\n","/**\n * `PdfNumber` class is used to perform number related primitive operations.\n * @private\n */\nvar PdfNumber = /** @class */ (function () {\n /**\n * Initializes a new instance of the `PdfNumber` class.\n * @private\n */\n function PdfNumber(value) {\n /**\n * Sotres the `position`.\n * @default -1\n * @private\n */\n this.position5 = -1;\n this.value = value;\n }\n Object.defineProperty(PdfNumber.prototype, \"intValue\", {\n /**\n * Gets or sets the `integer` value.\n * @private\n */\n get: function () {\n return this.value;\n },\n set: function (value) {\n this.value = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfNumber.prototype, \"isInteger\", {\n /**\n * Gets or sets a value indicating whether this instance `is integer`.\n * @private\n */\n get: function () {\n return this.integer;\n },\n set: function (value) {\n this.integer = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfNumber.prototype, \"status\", {\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.status5;\n },\n set: function (value) {\n this.status5 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfNumber.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.isSaving5;\n },\n set: function (value) {\n this.isSaving5 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfNumber.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index5;\n },\n set: function (value) {\n this.index5 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfNumber.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.position5;\n },\n set: function (value) {\n this.position5 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfNumber.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n var rValue = null;\n return rValue;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Saves the object`.\n * @private\n */\n PdfNumber.prototype.save = function (writer) {\n writer.write(this.intValue.toString()); //tostring(CultureInfo.InletiantCulture)\n };\n /**\n * Creates a `copy of PdfNumber`.\n * @private\n */\n PdfNumber.prototype.clone = function (crossTable) {\n var newNumber = new PdfNumber(this.value);\n return newNumber;\n };\n /**\n * Converts a `float value to a string` using Adobe PDF rules.\n * @private\n */\n PdfNumber.floatToString = function (number) {\n // let tempString1 : string = number.toString();\n // let tempString2 : string = tempString1.indexOf('.') != -1 ? tempString1.substring(0, tempString1.indexOf('.')) : tempString1;\n var returnString = number.toFixed(2);\n if (returnString === '0.00') {\n returnString = '.00';\n }\n // let prefixLength : number = (22 - tempString2.length) >= 0 ? (22 - tempString2.length) : 0;\n // for (let index : number = 0; index < prefixLength; index++) {\n // returnString += '0';\n // }\n // returnString += tempString2 + '.00';\n // returnString += (tempString3.length > 6) ? tempString3.substring(0,6) : tempString3;\n // let suffixLength : number = (6 - tempString3.length) >= 0 ? (6 - tempString3.length) : 0;\n // for (let index : number = 0; index < suffixLength; index++) {\n // returnString += '0';\n // }\n return returnString;\n };\n /**\n * Determines the `minimum of the three values`.\n * @private\n */\n PdfNumber.min = function (x, y, z) {\n var r = Math.min(x, y);\n return Math.min(z, r);\n };\n return PdfNumber;\n}());\nexport { PdfNumber };\n","import { PdfNumber } from './pdf-number';\nimport { Operators } from './../input-output/pdf-operators';\n/**\n * `PdfArray` class is used to perform array related primitive operations.\n * @private\n */\nvar PdfArray = /** @class */ (function () {\n function PdfArray(array) {\n //Fields\n /**\n * `startMark` - '['\n * @private\n */\n this.startMark = '[';\n /**\n * `endMark` - ']'.\n * @private\n */\n this.endMark = ']';\n /**\n * Internal variable to store the `position`.\n * @default -1\n * @private\n */\n this.position9 = -1;\n /**\n * Internal variable to hold `cloned object`.\n * @default null\n * @private\n */\n this.clonedObject9 = null;\n /**\n * Represents the Font dictionary.\n * @hidden\n * @private\n */\n this.isFont = false;\n if (typeof array === 'undefined') {\n this.internalElements = [];\n }\n else {\n if (typeof array !== 'undefined' && !(array instanceof PdfArray)) {\n var tempNumberArray = array;\n for (var index = 0; index < tempNumberArray.length; index++) {\n var pdfNumber = new PdfNumber(tempNumberArray[index]);\n this.add(pdfNumber);\n }\n // } else if (typeof array !== 'undefined' && (array instanceof PdfArray)) {\n }\n else {\n var tempArray = array;\n // if (tempArray.Elements.length > 0) {\n this.internalElements = [];\n for (var index = 0; index < tempArray.elements.length; index++) {\n this.internalElements.push(tempArray.elements[index]);\n }\n // }\n }\n }\n }\n //property\n /**\n * Gets the `IPdfSavable` at the specified index.\n * @private\n */\n PdfArray.prototype.items = function (index) {\n // if (index < 0 || index >= this.Count) {\n // throw new Error('ArgumentOutOfRangeException : index, The index can\"t be less then zero or greater then Count.');\n // }\n return this.internalElements[index];\n };\n Object.defineProperty(PdfArray.prototype, \"count\", {\n /**\n * Gets the `count`.\n * @private\n */\n get: function () {\n return this.internalElements.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfArray.prototype, \"status\", {\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.status9;\n },\n set: function (value) {\n this.status9 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfArray.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.isSaving9;\n },\n set: function (value) {\n this.isSaving9 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfArray.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n return this.clonedObject9;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfArray.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.position9;\n },\n set: function (value) {\n this.position9 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfArray.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index9;\n },\n set: function (value) {\n this.index9 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfArray.prototype, \"CrossTable\", {\n /**\n * Returns `PdfCrossTable` associated with the object.\n * @private\n */\n get: function () {\n return this.pdfCrossTable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfArray.prototype, \"elements\", {\n /**\n * Gets the `elements` of the Pdf Array.\n * @private\n */\n get: function () {\n return this.internalElements;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Adds` the specified element to the PDF array.\n * @private\n */\n PdfArray.prototype.add = function (element) {\n // if (element === null) {\n // throw new Error('ArgumentNullException : obj');\n // }\n if (typeof this.internalElements === 'undefined') {\n this.internalElements = [];\n }\n this.internalElements.push(element);\n this.markedChange();\n };\n /**\n * `Marks` the object changed.\n * @private\n */\n PdfArray.prototype.markedChange = function () {\n this.bChanged = true;\n };\n /**\n * `Determines` whether the specified element is within the array.\n * @private\n */\n PdfArray.prototype.contains = function (element) {\n var returnValue = false;\n for (var index = 0; index < this.internalElements.length; index++) {\n var tempElement = this.internalElements[index];\n var inputElement = element;\n if (tempElement != null && typeof tempElement !== 'undefined' && inputElement != null && typeof inputElement !== 'undefined') {\n if (tempElement.value === inputElement.value) {\n return true;\n }\n }\n // if (this.internalElements[index] === element) {\n // returnValue = true;\n // }\n }\n return returnValue;\n };\n /**\n * Returns the `primitive object` of input index.\n * @private\n */\n PdfArray.prototype.getItems = function (index) {\n // if (index < 0 || index >= this.Count) {\n // throw new Error('ArgumentOutOfRangeException : index , The index can\"t be less then zero or greater then Count.');\n // }\n return this.internalElements[index];\n };\n /**\n * `Saves` the object using the specified writer.\n * @private\n */\n PdfArray.prototype.save = function (writer) {\n // if (writer === null) {\n // throw new Error('ArgumentNullException : writer');\n // }\n writer.write(this.startMark);\n for (var i = 0, len = this.count; i < len; i++) {\n this.getItems(i).save(writer);\n if (i + 1 !== len) {\n writer.write(Operators.whiteSpace);\n }\n }\n writer.write(this.endMark);\n };\n /**\n * Creates a `copy of PdfArray`.\n * @private\n */\n PdfArray.prototype.clone = function (crossTable) {\n // if (this.clonedObject9 !== null && this.clonedObject9.CrossTable === crossTable) {\n // return this.clonedObject9;\n // } else {\n this.clonedObject9 = null;\n // Else clone the object.\n var newArray = new PdfArray();\n for (var index = 0; index < this.internalElements.length; index++) {\n var obj = this.internalElements[index];\n newArray.add(obj.clone(crossTable));\n }\n newArray.pdfCrossTable = crossTable;\n this.clonedObject9 = newArray;\n return newArray;\n };\n /**\n * Creates filled PDF array `from the rectangle`.\n * @private\n */\n PdfArray.fromRectangle = function (bounds) {\n var values = [bounds.x, bounds.y, bounds.width, bounds.height];\n var array = new PdfArray(values);\n return array;\n };\n // /**\n // * Creates the rectangle from filled PDF array.\n // * @private\n // */\n // public ToRectangle() : RectangleF {\n // if (this.Count < 4) {\n // throw Error('InvalidOperationException-Can not convert to rectangle.');\n // }\n // let x1 : number;\n // let x2 : number;\n // let y1 : number;\n // let y2 : number;\n // let num : PdfNumber = this.getItems(0) as PdfNumber;\n // x1 = num.IntValue;\n // num = this.getItems(1) as PdfNumber;\n // y1 = num.IntValue;\n // num = this.getItems(2) as PdfNumber;\n // x2 = num.IntValue;\n // num = this.getItems(3) as PdfNumber;\n // y2 = num.IntValue;\n // let x : number = Math.min(x1, x2);\n // let y : number = Math.min(y1, y2);\n // let width : number = Math.abs(x1 - x2);\n // let height : number = Math.abs(y1 - y2);\n // let rect : RectangleF = new RectangleF(new PointF(x, y), new SizeF(width, height));\n // return rect;\n // }\n /**\n * `Inserts` the element into the array.\n * @private\n */\n PdfArray.prototype.insert = function (index, element) {\n if (index < this.internalElements.length && index > 0) {\n var tempElements = [];\n for (var i = 0; i < index; i++) {\n tempElements.push(this.internalElements[i]);\n }\n tempElements.push(element);\n for (var i = index; i < this.internalElements.length; i++) {\n tempElements.push(this.internalElements[i]);\n }\n this.internalElements = tempElements;\n }\n else {\n this.internalElements.push(element);\n }\n this.markChanged();\n };\n /**\n * `Checks whether array contains the element`.\n * @private\n */\n PdfArray.prototype.indexOf = function (element) {\n return this.internalElements.indexOf(element);\n };\n /**\n * `Removes` element from the array.\n * @private\n */\n PdfArray.prototype.remove = function (element) {\n // if (element === null) {\n // throw new Error('ArgumentNullException : element');\n // }\n var index = this.internalElements.indexOf(element);\n // if (index >= 0 && index < this.internalElements.length) {\n this.internalElements[index] = null;\n // }\n this.markChanged();\n };\n /**\n * `Remove` the element from the array by its index.\n * @private\n */\n PdfArray.prototype.removeAt = function (index) {\n // this.internalElements.RemoveAt(index);\n if (this.internalElements.length > index) {\n var tempArray = [];\n for (var i = 0; i < index; i++) {\n tempArray.push(this.internalElements[i]);\n }\n for (var i = index + 1; i < this.internalElements.length; i++) {\n tempArray.push(this.internalElements[i]);\n }\n this.internalElements = tempArray;\n }\n this.markChanged();\n };\n /**\n * `Clear` the array.\n * @private\n */\n PdfArray.prototype.clear = function () {\n this.internalElements = [];\n this.markChanged();\n };\n /**\n * `Marks` the object changed.\n * @private\n */\n PdfArray.prototype.markChanged = function () {\n this.bChanged = true;\n };\n return PdfArray;\n}());\nexport { PdfArray };\n","/**\n * Save class provide method to save file\n * ```typescript\n * let blob : Blob = new Blob([''], { type: 'text/plain' });\n * Save.save('fileName.txt',blob);\n */\nvar Save = /** @class */ (function () {\n /**\n * Initialize new instance of {save}\n */\n function Save() {\n // tslint:disable\n }\n /**\n * Saves the file with specified name and sends the file to client browser\n * @param {string} fileName- file name to save.\n * @param {Blob} buffer- the content to write in file\n * @param {boolean} isMicrosoftBrowser- specify whether microsoft browser or not\n * @returns {void}\n */\n Save.save = function (fileName, buffer) {\n if (fileName === null || fileName === undefined || fileName === '') {\n throw new Error('ArgumentException: fileName cannot be undefined, null or empty');\n }\n var extension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);\n var mimeType = this.getMimeType(extension);\n if (mimeType !== '') {\n buffer = new Blob([buffer], { type: mimeType });\n }\n if (this.isMicrosoftBrowser) {\n navigator.msSaveBlob(buffer, fileName);\n }\n else {\n var downloadLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');\n this.saveInternal(fileName, extension, buffer, downloadLink, 'download' in downloadLink);\n }\n };\n Save.saveInternal = function (fileName, extension, buffer, downloadLink, hasDownloadAttribute) {\n if (hasDownloadAttribute) {\n downloadLink.download = fileName;\n var dataUrl_1 = window.URL.createObjectURL(buffer);\n downloadLink.href = dataUrl_1;\n var event_1 = document.createEvent('MouseEvent');\n event_1.initEvent('click', true, true);\n downloadLink.dispatchEvent(event_1);\n setTimeout(function () {\n window.URL.revokeObjectURL(dataUrl_1);\n dataUrl_1 = undefined;\n });\n }\n else {\n if (extension !== 'docx' && extension !== 'xlsx') {\n var url = window.URL.createObjectURL(buffer);\n var isPopupBlocked = window.open(url, '_blank');\n if (!isPopupBlocked) {\n window.location.href = url;\n }\n }\n else {\n var reader_1 = new FileReader();\n reader_1.onloadend = function () {\n var isPopupBlocked = window.open(reader_1.result, '_blank');\n if (!isPopupBlocked) {\n window.location.href = reader_1.result;\n }\n };\n reader_1.readAsDataURL(buffer);\n }\n }\n };\n /**\n *\n * @param {string} extension - get mime type of the specified extension\n * @private\n */\n Save.getMimeType = function (extension) {\n var mimeType = '';\n switch (extension) {\n case 'html':\n mimeType = 'text/html';\n break;\n case 'pdf':\n mimeType = 'application/pdf';\n break;\n case 'docx':\n mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';\n break;\n case 'xlsx':\n mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';\n break;\n case 'txt':\n mimeType = 'text/plain';\n break;\n }\n return mimeType;\n };\n return Save;\n}());\nexport { Save };\n","import { Save } from './save';\n/**\n * XmlWriter class provide method to create XML data\n */\nvar XmlWriter = /** @class */ (function () {\n /**\n * Initialize new instance of {XmlWriter}\n */\n function XmlWriter() {\n this.contentPos = 0;\n this.bufferText = '';\n this.bufferBlob = new Blob([''], { type: 'text/plain' });\n this.currentState = 'Initial';\n this.namespaceStack = [];\n this.namespaceStack.push(new Namespace());\n this.namespaceStack[0].set('xmlns', 'http://www.w3.org/2000/xmlns/', 'Special');\n this.namespaceStack.push(new Namespace());\n this.namespaceStack[1].set('xml', 'http://www.w3.org/XML/1998/namespace', 'Special');\n this.namespaceStack.push(new Namespace());\n this.namespaceStack[2].set('', '', 'Implied');\n this.elementStack = [];\n this.elementStack.push(new XmlElement());\n this.elementStack[0].set('', '', '', this.namespaceStack.length - 1);\n this.attributeStack = [];\n Save.isMicrosoftBrowser = !(!navigator.msSaveBlob);\n }\n Object.defineProperty(XmlWriter.prototype, \"buffer\", {\n /**\n * Gets the content written to the {XmlWriter} as Blob.\n * @returns {Blob}\n */\n get: function () {\n this.flush();\n return this.bufferBlob;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Writes processing instruction with a space between the name and text\n * @param {string} name - name of the processing instruction\n * @param {string} text - text to write in the processing instruction\n * @throws ArgumentException\n * @throws InvalidArgumentException\n * @throws InvalidOperationException\n */\n XmlWriter.prototype.writeProcessingInstruction = function (name, text) {\n if (name === undefined || name === null || name.length === 0) {\n throw new Error('ArgumentException: name should not be undefined, null or empty');\n }\n this.checkName(name);\n if (text === undefined || text === null) {\n text = '';\n }\n if (name.length === 3 && name === 'xml') {\n if (this.currentState !== 'Initial') {\n // tslint:disable-next-line:max-line-length\n throw new Error('InvalidArgumentException: Cannot write XML declaration.WriteStartDocument method has already written it');\n }\n }\n if (this.currentState !== 'Initial' || this.bufferBlob === undefined) {\n throw new Error('InvalidOperationException: Wrong Token');\n }\n else {\n this.writeStartDocument();\n this.writeProcessingInstructionInternal(name, text);\n }\n };\n /**\n * Writes Xml declaration with version and standalone attribute\n * @param {boolean} standalone - if true it write standalone=yes else standalone=no\n * @throws InvalidOperation\n */\n XmlWriter.prototype.writeStartDocument = function (standalone) {\n if (this.currentState !== 'Initial' || this.bufferBlob === undefined) {\n throw new Error('InvalidOperationException: Wrong Token');\n }\n this.currentState = 'StartDocument';\n this.rawText('');\n };\n /**\n * Closes any open tag or attribute and write the state back to start\n */\n XmlWriter.prototype.writeEndDocument = function () {\n while (this.elementStack.length - 1 > 0) {\n this.writeEndElement();\n }\n this.currentState = 'EndDocument';\n this.flush();\n };\n /**\n * Writes the specified start tag and associates it with the given namespace and prefix.\n * @param {string} prefix - namespace prefix of element\n * @param {string} localName -localName of element\n * @param {string} namespace - namespace URI associate with element\n * @throws ArgumentException\n * @throws InvalidOperationException\n */\n XmlWriter.prototype.writeStartElement = function (prefix, localName, namespace) {\n if (this.bufferBlob === undefined) {\n throw new Error('InvalidOperationException: Wrong Token');\n }\n if (localName === undefined || localName === null || localName.length === 0) {\n throw new Error('ArgumentException: localName cannot be undefined, null or empty');\n }\n this.checkName(localName);\n if (this.currentState === 'Initial') {\n this.writeStartDocument();\n }\n if (this.currentState === 'StartElement') {\n this.startElementContent();\n }\n this.currentState = 'StartElement';\n if (prefix === undefined || prefix === null) {\n if (namespace !== undefined && namespace !== null) {\n prefix = this.lookupPrefix(namespace);\n }\n if (prefix === undefined || prefix === null) {\n prefix = '';\n }\n }\n else if (prefix.length > 0) {\n if (namespace === undefined || namespace === null) {\n namespace = this.lookupNamespace(prefix);\n }\n if (namespace === undefined || namespace === null || (namespace !== undefined && namespace.length === 0)) {\n throw new Error('ArgumentException: Cannot use a prefix with an empty namespace');\n }\n }\n if (namespace === undefined || namespace === null) {\n namespace = this.lookupNamespace(prefix);\n }\n this.writeStartElementInternal(prefix, localName, namespace);\n };\n /**\n * Closes one element and pop corresponding namespace scope\n */\n XmlWriter.prototype.writeEndElement = function () {\n if (this.currentState === 'StartElement') {\n this.startElementContent();\n this.currentState = 'ElementContent';\n }\n else if (this.currentState === 'ElementContent') {\n this.currentState = 'ElementContent';\n }\n this.currentState = 'EndElement';\n var top = this.elementStack.length - 1;\n this.writeEndElementInternal(this.elementStack[top].prefix, this.elementStack[top].localName);\n this.namespaceStack.splice(this.elementStack[top].previousTop + 1);\n this.elementStack.splice(top);\n if (this.bufferText.length > 10240) {\n this.flush();\n }\n };\n /**\n * Writes an element with the specified prefix, local name, namespace URI, and value.\n * @param {string} prefix - namespace prefix of element\n * @param {string} localName - localName of element\n * @param {string} namespace - namespace URI associate with element\n * @param {string} value - value of element\n */\n XmlWriter.prototype.writeElementString = function (prefix, localName, namespace, value) {\n this.writeStartElement(prefix, localName, namespace);\n if (value !== undefined && value !== null && value.length !== 0) {\n this.writeString(value);\n }\n this.writeEndElement();\n };\n /**\n * Writes out the attribute with the specified prefix, local name, namespace URI, and value\n * @param {string} prefix - namespace prefix of element\n * @param {string} localName - localName of element\n * @param {string} namespace - namespace URI associate with element\n * @param {string} value - value of element\n */\n XmlWriter.prototype.writeAttributeString = function (prefix, localName, namespace, value) {\n this.writeStartAttribute(prefix, localName, namespace, value);\n this.writeStringInternal(value, true);\n this.writeEndAttribute();\n };\n /**\n * Writes the given text content\n * @param {string} text - text to write\n * @throws InvalidOperationException\n */\n XmlWriter.prototype.writeString = function (text) {\n this.writeInternal(text, false);\n };\n /**\n * Write given text as raw data\n * @param {string} text - text to write\n * @throws InvalidOperationException\n */\n XmlWriter.prototype.writeRaw = function (text) {\n this.writeInternal(text, true);\n };\n XmlWriter.prototype.writeInternal = function (text, isRawString) {\n if (text === undefined || text === null) {\n return;\n }\n else {\n if (this.currentState !== 'StartElement' && this.currentState !== 'ElementContent') {\n throw new Error('InvalidOperationException: Wrong Token');\n }\n if (this.currentState === 'StartElement') {\n this.startElementContent();\n }\n this.currentState = 'ElementContent';\n if (isRawString) {\n this.rawText(text);\n }\n else {\n this.writeStringInternal(text, false);\n }\n }\n };\n /**\n * Saves the file with specified name and sends the file to client browser\n * @param {string} fileName - file name\n */\n XmlWriter.prototype.save = function (fileName) {\n while (this.elementStack.length - 1 > 0) {\n this.writeEndElement();\n }\n if (this.bufferText !== '') {\n this.flush();\n }\n Save.save(fileName, this.buffer);\n };\n /**\n * Releases the resources used by XmlWriter.\n */\n XmlWriter.prototype.destroy = function () {\n this.bufferBlob = undefined;\n for (var i = 0; i < this.namespaceStack.length; i++) {\n this.namespaceStack[i].destroy();\n }\n this.namespaceStack = [];\n for (var i = 0; i < this.elementStack.length; i++) {\n this.elementStack[i].destroy();\n }\n this.elementStack = [];\n this.bufferText = '';\n this.contentPos = 0;\n };\n XmlWriter.prototype.flush = function () {\n if (this.bufferBlob === undefined) {\n return;\n }\n this.bufferBlob = new Blob([this.bufferBlob, this.bufferText], { type: 'text/plain' });\n this.bufferText = '';\n };\n XmlWriter.prototype.writeProcessingInstructionInternal = function (name, text) {\n this.bufferText += '';\n this.rawText(name);\n if (text.length > 0) {\n this.bufferText += ' ';\n text = text.replace(/\\?\\>/g, '? >');\n this.bufferText += text;\n }\n this.bufferText += '?';\n this.bufferText += '>';\n };\n XmlWriter.prototype.writeStartAttribute = function (prefix, localName, namespace, value) {\n if (localName === undefined || localName === null || localName.length === 0) {\n if (prefix === 'xmlns') {\n localName = 'xmlns';\n prefix = '';\n }\n else {\n throw new Error('ArgumentException: localName cannot be undefined, null or empty');\n }\n }\n if (this.currentState !== 'StartElement') {\n throw new Error('InvalidOperationException: Wrong Token');\n }\n this.checkName(localName);\n this.writeStartAttributePrefixAndNameSpace(prefix, localName, namespace, value);\n };\n XmlWriter.prototype.writeStartAttributePrefixAndNameSpace = function (prefix, localName, namespace, value) {\n if (prefix === undefined || prefix === null) {\n if (namespace !== undefined && namespace !== null) {\n if (!(localName === 'xmlns' && namespace === 'http://www.w3.org/2000/xmlns/')) {\n prefix = this.lookupPrefix(namespace);\n }\n }\n if (prefix === undefined || prefix === null) {\n prefix = '';\n }\n }\n if (namespace === undefined || namespace === null) {\n if (prefix !== undefined && prefix !== null && prefix.length > 0) {\n namespace = this.lookupNamespace(prefix);\n }\n if (namespace === undefined || namespace === null) {\n namespace = '';\n }\n }\n this.writeStartAttributeSpecialAttribute(prefix, localName, namespace, value);\n };\n XmlWriter.prototype.writeStartAttributeSpecialAttribute = function (prefix, localName, namespace, value) {\n if (prefix.length === 0) {\n if (localName[0] === 'x' && localName === 'xmlns') {\n this.skipPushAndWrite(prefix, localName, namespace);\n this.pushNamespaceExplicit('', value);\n return;\n }\n else if (namespace.length > 0) {\n prefix = this.lookupPrefix(namespace);\n }\n }\n else {\n if (prefix[0] === 'x') {\n if (prefix === 'xmlns') {\n this.skipPushAndWrite(prefix, localName, namespace);\n this.pushNamespaceExplicit(localName, value);\n return;\n }\n else if (prefix === 'xml') {\n if (localName === 'space' || localName === 'lang') {\n this.skipPushAndWrite(prefix, localName, namespace);\n return;\n }\n }\n }\n if (namespace.length === 0) {\n prefix = '';\n }\n }\n if (prefix !== undefined && prefix !== null && prefix.length !== 0) {\n this.pushNamespaceImplicit(prefix, namespace);\n }\n this.skipPushAndWrite(prefix, localName, namespace);\n };\n XmlWriter.prototype.writeEndAttribute = function () {\n this.currentState = 'StartElement';\n this.bufferText += '\"';\n };\n XmlWriter.prototype.writeStartElementInternal = function (prefix, localName, namespace) {\n this.bufferText += '<';\n if (prefix.length > 0) {\n this.rawText(prefix);\n this.bufferText += ':';\n }\n this.rawText(localName);\n var top = this.elementStack.length;\n this.elementStack.push(new XmlElement());\n this.elementStack[top].set(prefix, localName, namespace, this.namespaceStack.length - 1);\n this.pushNamespaceImplicit(prefix, namespace);\n for (var i = 0; i < this.attributeStack.length; i++) {\n this.attributeStack[i].destroy();\n }\n this.attributeStack = [];\n };\n XmlWriter.prototype.writeEndElementInternal = function (prefix, localName) {\n if (this.contentPos !== this.bufferText.length + 1) {\n this.bufferText += '';\n if (prefix !== undefined && prefix !== null && prefix.length !== 0) {\n this.rawText(prefix);\n this.bufferText += ':';\n }\n this.rawText(localName);\n this.bufferText += '>';\n }\n else {\n this.bufferText = this.bufferText.substring(0, this.bufferText.length - 1);\n this.bufferText += ' />';\n }\n };\n XmlWriter.prototype.writeStartAttributeInternal = function (prefix, localName, namespaceName) {\n this.bufferText += ' ';\n if (prefix !== undefined && prefix !== null && prefix.length > 0) {\n this.rawText(prefix);\n this.bufferText += ':';\n }\n this.rawText(localName);\n this.bufferText += '=';\n this.bufferText += '\"';\n };\n XmlWriter.prototype.writeNamespaceDeclaration = function (prefix, namespaceUri) {\n this.writeStartNamespaceDeclaration(prefix);\n this.writeStringInternal(namespaceUri, true);\n this.bufferText += '\"';\n };\n XmlWriter.prototype.writeStartNamespaceDeclaration = function (prefix) {\n if (prefix === undefined || prefix === null || prefix.length === 0) {\n this.rawText(' xmlns=\\\"');\n }\n else {\n this.rawText(' xmlns:');\n this.rawText(prefix);\n this.bufferText += '=';\n this.bufferText += '\"';\n }\n };\n XmlWriter.prototype.writeStringInternal = function (text, inAttributeValue) {\n if (text === null || text === undefined) {\n text = '';\n }\n var tempText = '';\n text = text.replace(/\\&/g, '&');\n text = text.replace(/\\/g, '>');\n if (inAttributeValue) {\n text = text.replace(/\\\"/g, '"');\n }\n this.bufferText += text;\n if (!inAttributeValue) {\n this.contentPos = 0;\n }\n };\n XmlWriter.prototype.startElementContent = function () {\n var start = this.elementStack[this.elementStack.length - 1].previousTop;\n for (var i = this.namespaceStack.length - 1; i > start; i--) {\n if (this.namespaceStack[i].kind === 'NeedToWrite') {\n this.writeNamespaceDeclaration(this.namespaceStack[i].prefix, this.namespaceStack[i].namespaceUri);\n }\n }\n this.bufferText += '>';\n this.contentPos = this.bufferText.length + 1;\n };\n XmlWriter.prototype.rawText = function (text) {\n this.bufferText += text;\n };\n XmlWriter.prototype.addNamespace = function (prefix, ns, kind) {\n var top = this.namespaceStack.length;\n this.namespaceStack.push(new Namespace());\n this.namespaceStack[top].set(prefix, ns, kind);\n };\n XmlWriter.prototype.lookupPrefix = function (namespace) {\n for (var i = this.namespaceStack.length - 1; i >= 0; i--) {\n if (this.namespaceStack[i].namespaceUri === namespace) {\n return this.namespaceStack[i].prefix;\n }\n }\n return undefined;\n };\n XmlWriter.prototype.lookupNamespace = function (prefix) {\n for (var i = this.namespaceStack.length - 1; i >= 0; i--) {\n if (this.namespaceStack[i].prefix === prefix) {\n return this.namespaceStack[i].namespaceUri;\n }\n }\n return undefined;\n };\n XmlWriter.prototype.lookupNamespaceIndex = function (prefix) {\n for (var i = this.namespaceStack.length - 1; i >= 0; i--) {\n if (this.namespaceStack[i].prefix === prefix) {\n return i;\n }\n }\n return -1;\n };\n XmlWriter.prototype.pushNamespaceImplicit = function (prefix, ns) {\n var kind;\n var existingNsIndex = this.lookupNamespaceIndex(prefix);\n if (existingNsIndex !== -1) {\n if (existingNsIndex > this.elementStack[this.elementStack.length - 1].previousTop) {\n if (this.namespaceStack[existingNsIndex].namespaceUri !== ns) {\n throw new Error('XmlException namespace Uri needs to be the same as the one that is already declared');\n }\n return;\n }\n else {\n if (this.namespaceStack[existingNsIndex].kind === 'Special') {\n if (prefix === 'xml') {\n if (ns !== this.namespaceStack[existingNsIndex].namespaceUri) {\n throw new Error('InvalidArgumentException: Xml String');\n }\n else {\n kind = 'Implied';\n }\n }\n else {\n throw new Error('InvalidArgumentException: Prefix \"xmlns\" is reserved for use by XML.');\n }\n }\n else {\n kind = (this.namespaceStack[existingNsIndex].namespaceUri === ns) ? 'Implied' : 'NeedToWrite';\n }\n }\n }\n else {\n if ((ns === 'http://www.w3.org/XML/1998/namespace' && prefix !== 'xml') ||\n (ns === 'http://www.w3.org/2000/xmlns/' && prefix !== 'xmlns')) {\n throw new Error('InvalidArgumentException');\n }\n kind = 'NeedToWrite';\n }\n this.addNamespace(prefix, ns, kind);\n };\n XmlWriter.prototype.pushNamespaceExplicit = function (prefix, ns) {\n var existingNsIndex = this.lookupNamespaceIndex(prefix);\n if (existingNsIndex !== -1) {\n if (existingNsIndex > this.elementStack[this.elementStack.length - 1].previousTop) {\n this.namespaceStack[existingNsIndex].kind = 'Written';\n return;\n }\n }\n this.addNamespace(prefix, ns, 'Written');\n return;\n };\n XmlWriter.prototype.addAttribute = function (prefix, localName, namespaceName) {\n var top = this.attributeStack.length;\n this.attributeStack.push(new XmlAttribute());\n this.attributeStack[top].set(prefix, localName, namespaceName);\n for (var i = 0; i < top; i++) {\n if (this.attributeStack[i].isDuplicate(prefix, localName, namespaceName)) {\n throw new Error('XmlException: duplicate attribute name');\n }\n }\n };\n XmlWriter.prototype.skipPushAndWrite = function (prefix, localName, namespace) {\n this.addAttribute(prefix, localName, namespace);\n this.writeStartAttributeInternal(prefix, localName, namespace);\n };\n XmlWriter.prototype.checkName = function (text) {\n var format = /[ !@#$%^&*()+\\=\\[\\]{};':\"\\\\|,<>\\/?]/;\n if (format.test(text)) {\n throw new Error('InvalidArgumentException: invalid name character');\n }\n };\n return XmlWriter;\n}());\nexport { XmlWriter };\n/**\n * class for managing namespace collection\n */\nvar Namespace = /** @class */ (function () {\n function Namespace() {\n }\n /**\n * set value for current namespace instance\n * @param {string} prefix namespace's prefix\n * @param {string} namespaceUri namespace URI\n * @param {string} kind namespace kind\n */\n Namespace.prototype.set = function (prefix, namespaceUri, kind) {\n this.prefix = prefix;\n this.namespaceUri = namespaceUri;\n this.kind = kind;\n };\n /**\n * Releases the resources used by Namespace\n */\n Namespace.prototype.destroy = function () {\n this.prefix = undefined;\n this.namespaceUri = undefined;\n this.kind = undefined;\n };\n return Namespace;\n}());\nexport { Namespace };\n/**\n * class for managing element collection\n */\nvar XmlElement = /** @class */ (function () {\n function XmlElement() {\n }\n /**\n * set value of current element\n * @param {string} prefix - element prefix\n * @param {string} localName - element local name\n * @param {string} namespaceUri -namespace URI\n * @param {string} previousTop - previous namespace top\n */\n XmlElement.prototype.set = function (prefix, localName, namespaceUri, previousTop) {\n this.previousTop = previousTop;\n this.prefix = prefix;\n this.namespaceUri = namespaceUri;\n this.localName = localName;\n };\n /**\n * Releases the resources used by XmlElement\n */\n XmlElement.prototype.destroy = function () {\n this.previousTop = undefined;\n this.prefix = undefined;\n this.localName = undefined;\n this.namespaceUri = undefined;\n };\n return XmlElement;\n}());\nexport { XmlElement };\n/**\n * class for managing attribute collection\n */\nvar XmlAttribute = /** @class */ (function () {\n function XmlAttribute() {\n }\n /**\n * set value of current attribute\n * @param {string} prefix - namespace's prefix\n * @param {string} namespaceUri - namespace URI\n * @param {string} localName - attribute localName\n */\n XmlAttribute.prototype.set = function (prefix, localName, namespaceUri) {\n this.prefix = prefix;\n this.namespaceUri = namespaceUri;\n this.localName = localName;\n };\n /**\n * get whether the attribute is duplicate or not\n * @param {string} prefix - namespace's prefix\n * @param {string} namespaceUri - namespace URI\n * @param {string} localName - attribute localName\n */\n XmlAttribute.prototype.isDuplicate = function (prefix, localName, namespaceUri) {\n return ((this.localName === localName) && ((this.prefix === prefix) || (this.namespaceUri === namespaceUri)));\n };\n /**\n * Releases the resources used by XmlAttribute\n */\n XmlAttribute.prototype.destroy = function () {\n this.prefix = undefined;\n this.namespaceUri = undefined;\n this.localName = undefined;\n };\n return XmlAttribute;\n}());\nexport { XmlAttribute };\n","import { Encoding, validateNullOrUndefined } from './encoding';\nimport { Save } from './save';\n/**\n * StreamWriter class contains the implementation for writing characters to a file in a particular encoding\n * ```typescript\n * let writer = new StreamWriter();\n * writer.write('Hello World');\n * writer.save('Sample.txt');\n * writer.dispose();\n * ```\n */\nvar StreamWriter = /** @class */ (function () {\n /**\n * Initializes a new instance of the StreamWriter class by using the specified encoding.\n * @param {Encoding} encoding?- The character encoding to use.\n */\n function StreamWriter(encoding) {\n this.bufferBlob = new Blob(['']);\n this.bufferText = '';\n this.init(encoding);\n Save.isMicrosoftBrowser = !(!navigator.msSaveBlob);\n }\n Object.defineProperty(StreamWriter.prototype, \"buffer\", {\n /**\n * Gets the content written to the StreamWriter as Blob.\n * @returns Blob\n */\n get: function () {\n this.flush();\n return this.bufferBlob;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StreamWriter.prototype, \"encoding\", {\n /**\n * Gets the encoding.\n * @returns Encoding\n */\n get: function () {\n return this.enc;\n },\n enumerable: true,\n configurable: true\n });\n StreamWriter.prototype.init = function (encoding) {\n if (encoding === null || encoding === undefined) {\n this.enc = new Encoding(false);\n this.enc.type = 'Utf8';\n }\n else {\n this.enc = encoding;\n this.setBomByte();\n }\n };\n /**\n * Private method to set Byte Order Mark(BOM) value based on EncodingType\n */\n StreamWriter.prototype.setBomByte = function () {\n if (this.encoding.includeBom) {\n switch (this.encoding.type) {\n case 'Unicode':\n var arrayUnicode = new ArrayBuffer(2);\n var uint8 = new Uint8Array(arrayUnicode);\n uint8[0] = 255;\n uint8[1] = 254;\n this.bufferBlob = new Blob([arrayUnicode]);\n break;\n case 'Utf8':\n var arrayUtf8 = new ArrayBuffer(3);\n var utf8 = new Uint8Array(arrayUtf8);\n utf8[0] = 239;\n utf8[1] = 187;\n utf8[2] = 191;\n this.bufferBlob = new Blob([arrayUtf8]);\n break;\n default:\n this.bufferBlob = new Blob(['']);\n break;\n }\n }\n };\n /**\n * Saves the file with specified name and sends the file to client browser\n * @param {string} fileName - The file name to save\n * @returns {void}\n */\n StreamWriter.prototype.save = function (fileName) {\n if (this.bufferText !== '') {\n this.flush();\n }\n Save.save(fileName, this.buffer);\n };\n /**\n * Writes the specified string.\n * @param {string} value - The string to write. If value is null or undefined, nothing is written.\n * @returns {void}\n */\n StreamWriter.prototype.write = function (value) {\n if (this.encoding === undefined) {\n throw new Error('Object Disposed Exception: current writer is disposed');\n }\n validateNullOrUndefined(value, 'string');\n this.bufferText += value;\n if (this.bufferText.length >= 10240) {\n this.flush();\n }\n };\n StreamWriter.prototype.flush = function () {\n if (this.bufferText === undefined || this.bufferText === null || this.bufferText.length === 0) {\n return;\n }\n var bufferArray = this.encoding.getBytes(this.bufferText, 0, this.bufferText.length);\n this.bufferText = '';\n this.bufferBlob = new Blob([this.bufferBlob, bufferArray]);\n };\n /**\n * Writes the specified string followed by a line terminator\n * @param {string} value - The string to write. If value is null or undefined, nothing is written\n * @returns {void}\n */\n StreamWriter.prototype.writeLine = function (value) {\n if (this.encoding === undefined) {\n throw new Error('Object Disposed Exception: current writer is disposed');\n }\n validateNullOrUndefined(value, 'string');\n this.bufferText = this.bufferText + value + '\\r\\n';\n if (this.bufferText.length >= 10240) {\n this.flush();\n }\n };\n /**\n * Releases the resources used by the StreamWriter\n * @returns {void}\n */\n StreamWriter.prototype.destroy = function () {\n this.bufferBlob = undefined;\n this.bufferText = undefined;\n if (this.enc instanceof Encoding) {\n this.enc.destroy();\n }\n this.enc = undefined;\n };\n return StreamWriter;\n}());\nexport { StreamWriter };\n","import { Encoding } from '@syncfusion/ej2-file-utils';\n/**\n * array literal codes\n */\nvar arrLiteralCodes = new Int16Array(286);\nvar arrLiteralLengths = new Uint8Array(286);\nvar arrDistanceCodes = new Int16Array(30);\nvar arrDistanceLengths = new Uint8Array(30);\n/**\n * represent compression stream writer\n * ```typescript\n * let compressedWriter = new CompressedStreamWriter();\n * let text: string = 'Hello world!!!';\n * compressedWriter.write(text, 0, text.length);\n * compressedWriter.close();\n * ```\n */\nvar CompressedStreamWriter = /** @class */ (function () {\n /**\n * Initializes compressor and writes ZLib header if needed.\n * @param {boolean} noWrap - optional if true, ZLib header and checksum will not be written.\n */\n function CompressedStreamWriter(noWrap) {\n this.pendingBuffer = new Uint8Array(1 << 16);\n this.pendingBufLength = 0;\n this.pendingBufCache = 0;\n this.pendingBufBitsInCache = 0;\n this.bufferPosition = 0;\n this.extraBits = 0;\n this.currentHash = 0;\n this.matchStart = 0;\n this.matchLength = 0;\n this.matchPrevAvail = false;\n this.blockStart = 0;\n this.stringStart = 0;\n this.lookAhead = 0;\n this.totalBytesIn = 0;\n this.inputOffset = 0;\n this.inputEnd = 0;\n this.windowSize = 1 << 15;\n this.windowMask = this.windowSize - 1;\n this.hashSize = 1 << 15;\n this.hashMask = this.hashSize - 1;\n this.hashShift = Math.floor((15 + 3 - 1) / 3);\n this.maxDist = this.windowSize - 262;\n this.checkSum = 1;\n this.noWrap = false;\n this.treeLiteral = new CompressorHuffmanTree(this, 286, 257, 15);\n this.treeDistances = new CompressorHuffmanTree(this, 30, 1, 15);\n this.treeCodeLengths = new CompressorHuffmanTree(this, 19, 4, 7);\n this.arrDistances = new Uint16Array((1 << 14));\n this.arrLiterals = new Uint8Array((1 << 14));\n this.stream = [];\n this.dataWindow = new Uint8Array(2 * this.windowSize);\n this.hashHead = new Int16Array(this.hashSize);\n this.hashPrevious = new Int16Array(this.windowSize);\n this.blockStart = this.stringStart = 1;\n this.noWrap = noWrap;\n if (!noWrap) {\n this.writeZLibHeader();\n }\n }\n Object.defineProperty(CompressedStreamWriter.prototype, \"compressedData\", {\n /**\n * get compressed data\n */\n get: function () {\n return this.stream;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CompressedStreamWriter.prototype, \"getCompressedString\", {\n get: function () {\n var compressedString = '';\n if (this.stream !== undefined) {\n for (var i = 0; i < this.stream.length; i++) {\n compressedString += String.fromCharCode.apply(null, this.stream[i]);\n }\n }\n return compressedString;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Compresses data and writes it to the stream.\n * @param {Uint8Array} data - data to compress\n * @param {number} offset - offset in data\n * @param {number} length - length of the data\n * @returns {void}\n */\n CompressedStreamWriter.prototype.write = function (data, offset, length) {\n if (data === undefined || data === null) {\n throw new Error('ArgumentException: data cannot null or undefined');\n }\n var end = offset + length;\n if (0 > offset || offset > end || end > data.length) {\n throw new Error('ArgumentOutOfRangeException: Offset or length is incorrect');\n }\n if (typeof data === 'string') {\n var encode = new Encoding(false);\n encode.type = 'Utf8';\n data = new Uint8Array(encode.getBytes(data, 0, data.length));\n end = offset + data.length;\n }\n this.inputBuffer = data;\n this.inputOffset = offset;\n this.inputEnd = end;\n if (!this.noWrap) {\n this.checkSum = ChecksumCalculator.checksumUpdate(this.checkSum, this.inputBuffer, this.inputOffset, end);\n }\n while (!(this.inputEnd === this.inputOffset) || !(this.pendingBufLength === 0)) {\n this.pendingBufferFlush();\n this.compressData(false);\n }\n };\n /**\n * write ZLib header to the compressed data\n * @return {void}\n */\n CompressedStreamWriter.prototype.writeZLibHeader = function () {\n /* Initialize header.*/\n var headerDate = (8 + (7 << 4)) << 8;\n /* Save compression level.*/\n headerDate |= ((5 >> 2) & 3) << 6;\n /* Align header.*/\n headerDate += 31 - (headerDate % 31);\n /* Write header to stream.*/\n this.pendingBufferWriteShortBytes(headerDate);\n };\n /**\n * Write Most Significant Bytes in to stream\n * @param {number} s - check sum value\n */\n CompressedStreamWriter.prototype.pendingBufferWriteShortBytes = function (s) {\n this.pendingBuffer[this.pendingBufLength++] = s >> 8;\n this.pendingBuffer[this.pendingBufLength++] = s;\n };\n CompressedStreamWriter.prototype.compressData = function (finish) {\n var success;\n do {\n this.fillWindow();\n var canFlush = (finish && this.inputEnd === this.inputOffset);\n success = this.compressSlow(canFlush, finish);\n } while (this.pendingBufLength === 0 && success);\n return success;\n };\n CompressedStreamWriter.prototype.compressSlow = function (flush, finish) {\n if (this.lookAhead < 262 && !flush) {\n return false;\n }\n while (this.lookAhead >= 262 || flush) {\n if (this.lookAhead === 0) {\n return this.lookAheadCompleted(finish);\n }\n if (this.stringStart >= 2 * this.windowSize - 262) {\n this.slideWindow();\n }\n var prevMatch = this.matchStart;\n var prevLen = this.matchLength;\n if (this.lookAhead >= 3) {\n this.discardMatch();\n }\n if (prevLen >= 3 && this.matchLength <= prevLen) {\n prevLen = this.matchPreviousBest(prevMatch, prevLen);\n }\n else {\n this.matchPreviousAvailable();\n }\n if (this.bufferPosition >= (1 << 14)) {\n return this.huffmanIsFull(finish);\n }\n }\n return true;\n };\n CompressedStreamWriter.prototype.discardMatch = function () {\n var hashHead = this.insertString();\n if (hashHead !== 0 && this.stringStart - hashHead <= this.maxDist && this.findLongestMatch(hashHead)) {\n if (this.matchLength <= 5 && (this.matchLength === 3 && this.stringStart - this.matchStart > 4096)) {\n this.matchLength = 3 - 1;\n }\n }\n };\n CompressedStreamWriter.prototype.matchPreviousAvailable = function () {\n if (this.matchPrevAvail) {\n this.huffmanTallyLit(this.dataWindow[this.stringStart - 1] & 0xff);\n }\n this.matchPrevAvail = true;\n this.stringStart++;\n this.lookAhead--;\n };\n CompressedStreamWriter.prototype.matchPreviousBest = function (prevMatch, prevLen) {\n this.huffmanTallyDist(this.stringStart - 1 - prevMatch, prevLen);\n prevLen -= 2;\n do {\n this.stringStart++;\n this.lookAhead--;\n if (this.lookAhead >= 3) {\n this.insertString();\n }\n } while (--prevLen > 0);\n this.stringStart++;\n this.lookAhead--;\n this.matchPrevAvail = false;\n this.matchLength = 3 - 1;\n return prevLen;\n };\n CompressedStreamWriter.prototype.lookAheadCompleted = function (finish) {\n if (this.matchPrevAvail) {\n this.huffmanTallyLit(this.dataWindow[this.stringStart - 1] & 0xff);\n }\n this.matchPrevAvail = false;\n this.huffmanFlushBlock(this.dataWindow, this.blockStart, this.stringStart - this.blockStart, finish);\n this.blockStart = this.stringStart;\n return false;\n };\n CompressedStreamWriter.prototype.huffmanIsFull = function (finish) {\n var len = this.stringStart - this.blockStart;\n if (this.matchPrevAvail) {\n len--;\n }\n var lastBlock = (finish && this.lookAhead === 0 && !this.matchPrevAvail);\n this.huffmanFlushBlock(this.dataWindow, this.blockStart, len, lastBlock);\n this.blockStart += len;\n return !lastBlock;\n };\n CompressedStreamWriter.prototype.fillWindow = function () {\n if (this.stringStart >= this.windowSize + this.maxDist) {\n this.slideWindow();\n }\n while (this.lookAhead < 262 && this.inputOffset < this.inputEnd) {\n var more = 2 * this.windowSize - this.lookAhead - this.stringStart;\n if (more > this.inputEnd - this.inputOffset) {\n more = this.inputEnd - this.inputOffset;\n }\n this.dataWindow.set(this.inputBuffer.subarray(this.inputOffset, this.inputOffset + more), this.stringStart + this.lookAhead);\n this.inputOffset += more;\n this.totalBytesIn += more;\n this.lookAhead += more;\n }\n if (this.lookAhead >= 3) {\n this.updateHash();\n }\n };\n CompressedStreamWriter.prototype.slideWindow = function () {\n this.dataWindow.set(this.dataWindow.subarray(this.windowSize, this.windowSize + this.windowSize), 0);\n this.matchStart -= this.windowSize;\n this.stringStart -= this.windowSize;\n this.blockStart -= this.windowSize;\n for (var i = 0; i < this.hashSize; ++i) {\n var m = this.hashHead[i] & 0xffff;\n this.hashHead[i] = (((m >= this.windowSize) ? (m - this.windowSize) : 0));\n }\n for (var i = 0; i < this.windowSize; i++) {\n var m = this.hashPrevious[i] & 0xffff;\n this.hashPrevious[i] = ((m >= this.windowSize) ? (m - this.windowSize) : 0);\n }\n };\n CompressedStreamWriter.prototype.insertString = function () {\n var match;\n var hash = ((this.currentHash << this.hashShift) ^ this.dataWindow[this.stringStart + (3 - 1)]) & this.hashMask;\n this.hashPrevious[this.stringStart & this.windowMask] = match = this.hashHead[hash];\n this.hashHead[hash] = this.stringStart;\n this.currentHash = hash;\n return match & 0xffff;\n };\n CompressedStreamWriter.prototype.findLongestMatch = function (curMatch) {\n var chainLen = 4096;\n var niceLen = 258;\n var scan = this.stringStart;\n var match;\n var bestEnd = this.stringStart + this.matchLength;\n var bestLength = Math.max(this.matchLength, 3 - 1);\n var limit = Math.max(this.stringStart - this.maxDist, 0);\n var stringEnd = this.stringStart + 258 - 1;\n var scanEnd1 = this.dataWindow[bestEnd - 1];\n var scanEnd = this.dataWindow[bestEnd];\n var data = this.dataWindow;\n if (bestLength >= 32) {\n chainLen >>= 2;\n }\n if (niceLen > this.lookAhead) {\n niceLen = this.lookAhead;\n }\n do {\n if (data[curMatch + bestLength] !== scanEnd ||\n data[curMatch + bestLength - 1] !== scanEnd1 ||\n data[curMatch] !== data[scan] ||\n data[curMatch + 1] !== data[scan + 1]) {\n continue;\n }\n match = curMatch + 2;\n scan += 2;\n /* tslint:disable */\n while (data[++scan] === data[++match] && data[++scan] === data[++match] &&\n data[++scan] === data[++match] && data[++scan] === data[++match] &&\n data[++scan] === data[++match] && data[++scan] === data[++match] &&\n data[++scan] === data[++match] && data[++scan] === data[++match] && scan < stringEnd) {\n /* tslint:disable */\n }\n if (scan > bestEnd) {\n this.matchStart = curMatch;\n bestEnd = scan;\n bestLength = scan - this.stringStart;\n if (bestLength >= niceLen) {\n break;\n }\n scanEnd1 = data[bestEnd - 1];\n scanEnd = data[bestEnd];\n }\n scan = this.stringStart;\n } while ((curMatch = (this.hashPrevious[curMatch & this.windowMask] & 0xffff)) > limit && --chainLen !== 0);\n this.matchLength = Math.min(bestLength, this.lookAhead);\n return this.matchLength >= 3;\n };\n CompressedStreamWriter.prototype.updateHash = function () {\n this.currentHash = (this.dataWindow[this.stringStart] << this.hashShift) ^ this.dataWindow[this.stringStart + 1];\n };\n CompressedStreamWriter.prototype.huffmanTallyLit = function (literal) {\n this.arrDistances[this.bufferPosition] = 0;\n this.arrLiterals[this.bufferPosition++] = literal;\n this.treeLiteral.codeFrequencies[literal]++;\n return this.bufferPosition >= (1 << 14);\n };\n CompressedStreamWriter.prototype.huffmanTallyDist = function (dist, len) {\n this.arrDistances[this.bufferPosition] = dist;\n this.arrLiterals[this.bufferPosition++] = (len - 3);\n var lc = this.huffmanLengthCode(len - 3);\n this.treeLiteral.codeFrequencies[lc]++;\n if (lc >= 265 && lc < 285) {\n this.extraBits += Math.floor((lc - 261) / 4);\n }\n var dc = this.huffmanDistanceCode(dist - 1);\n this.treeDistances.codeFrequencies[dc]++;\n if (dc >= 4) {\n this.extraBits += Math.floor((dc / 2 - 1));\n }\n return this.bufferPosition >= (1 << 14);\n };\n CompressedStreamWriter.prototype.huffmanFlushBlock = function (stored, storedOffset, storedLength, lastBlock) {\n this.treeLiteral.codeFrequencies[256]++;\n this.treeLiteral.buildTree();\n this.treeDistances.buildTree();\n this.treeLiteral.calculateBLFreq(this.treeCodeLengths);\n this.treeDistances.calculateBLFreq(this.treeCodeLengths);\n this.treeCodeLengths.buildTree();\n var blTreeCodes = 4;\n for (var i = 18; i > blTreeCodes; i--) {\n if (this.treeCodeLengths.codeLengths[CompressorHuffmanTree.huffCodeLengthOrders[i]] > 0) {\n blTreeCodes = i + 1;\n }\n }\n var opt_len = 14 + blTreeCodes * 3 + this.treeCodeLengths.getEncodedLength() +\n this.treeLiteral.getEncodedLength() + this.treeDistances.getEncodedLength() + this.extraBits;\n var static_len = this.extraBits;\n for (var i = 0; i < 286; i++) {\n static_len += this.treeLiteral.codeFrequencies[i] * arrLiteralLengths[i];\n }\n for (var i = 0; i < 30; i++) {\n static_len += this.treeDistances.codeFrequencies[i] * arrDistanceLengths[i];\n }\n if (opt_len >= static_len) {\n // Force static trees.\n opt_len = static_len;\n }\n if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) {\n this.huffmanFlushStoredBlock(stored, storedOffset, storedLength, lastBlock);\n }\n else if (opt_len == static_len) {\n // Encode with static tree.\n this.pendingBufferWriteBits((1 << 1) + (lastBlock ? 1 : 0), 3);\n this.treeLiteral.setStaticCodes(arrLiteralCodes, arrLiteralLengths);\n this.treeDistances.setStaticCodes(arrDistanceCodes, arrDistanceLengths);\n this.huffmanCompressBlock();\n this.huffmanReset();\n }\n else {\n this.pendingBufferWriteBits((2 << 1) + (lastBlock ? 1 : 0), 3);\n this.huffmanSendAllTrees(blTreeCodes);\n this.huffmanCompressBlock();\n this.huffmanReset();\n }\n };\n CompressedStreamWriter.prototype.huffmanFlushStoredBlock = function (stored, storedOffset, storedLength, lastBlock) {\n this.pendingBufferWriteBits((0 << 1) + (lastBlock ? 1 : 0), 3);\n this.pendingBufferAlignToByte();\n this.pendingBufferWriteShort(storedLength);\n this.pendingBufferWriteShort(~storedLength);\n this.pendingBufferWriteByteBlock(stored, storedOffset, storedLength);\n this.huffmanReset();\n };\n CompressedStreamWriter.prototype.huffmanLengthCode = function (len) {\n if (len === 255) {\n return 285;\n }\n var code = 257;\n while (len >= 8) {\n code += 4;\n len >>= 1;\n }\n return code + len;\n };\n CompressedStreamWriter.prototype.huffmanDistanceCode = function (distance) {\n var code = 0;\n while (distance >= 4) {\n code += 2;\n distance >>= 1;\n }\n return code + distance;\n };\n CompressedStreamWriter.prototype.huffmanSendAllTrees = function (blTreeCodes) {\n this.treeCodeLengths.buildCodes();\n this.treeLiteral.buildCodes();\n this.treeDistances.buildCodes();\n this.pendingBufferWriteBits(this.treeLiteral.treeLength - 257, 5);\n this.pendingBufferWriteBits(this.treeDistances.treeLength - 1, 5);\n this.pendingBufferWriteBits(blTreeCodes - 4, 4);\n for (var rank = 0; rank < blTreeCodes; rank++) {\n this.pendingBufferWriteBits(this.treeCodeLengths.codeLengths[CompressorHuffmanTree.huffCodeLengthOrders[rank]], 3);\n }\n this.treeLiteral.writeTree(this.treeCodeLengths);\n this.treeDistances.writeTree(this.treeCodeLengths);\n };\n CompressedStreamWriter.prototype.huffmanReset = function () {\n this.bufferPosition = 0;\n this.extraBits = 0;\n this.treeLiteral.reset();\n this.treeDistances.reset();\n this.treeCodeLengths.reset();\n };\n CompressedStreamWriter.prototype.huffmanCompressBlock = function () {\n for (var i = 0; i < this.bufferPosition; i++) {\n var literalLen = this.arrLiterals[i] & 255;\n var dist = this.arrDistances[i];\n if (dist-- !== 0) {\n var lc = this.huffmanLengthCode(literalLen);\n this.treeLiteral.writeCodeToStream(lc);\n var bits = Math.floor((lc - 261) / 4);\n if (bits > 0 && bits <= 5) {\n this.pendingBufferWriteBits(literalLen & ((1 << bits) - 1), bits);\n }\n var dc = this.huffmanDistanceCode(dist);\n this.treeDistances.writeCodeToStream(dc);\n bits = Math.floor(dc / 2 - 1);\n if (bits > 0) {\n this.pendingBufferWriteBits(dist & ((1 << bits) - 1), bits);\n }\n }\n else {\n this.treeLiteral.writeCodeToStream(literalLen);\n }\n }\n this.treeLiteral.writeCodeToStream(256);\n };\n /**\n * write bits in to internal buffer\n * @param {number} b - source of bits\n * @param {number} count - count of bits to write\n */\n CompressedStreamWriter.prototype.pendingBufferWriteBits = function (b, count) {\n var uint = new Uint32Array(1);\n uint[0] = this.pendingBufCache | (b << this.pendingBufBitsInCache);\n this.pendingBufCache = uint[0];\n this.pendingBufBitsInCache += count;\n this.pendingBufferFlushBits();\n };\n CompressedStreamWriter.prototype.pendingBufferFlush = function (isClose) {\n this.pendingBufferFlushBits();\n if (this.pendingBufLength > 0) {\n var array = new Uint8Array(this.pendingBufLength);\n array.set(this.pendingBuffer.subarray(0, this.pendingBufLength), 0);\n this.stream.push(array);\n }\n this.pendingBufLength = 0;\n };\n CompressedStreamWriter.prototype.pendingBufferFlushBits = function () {\n var result = 0;\n while (this.pendingBufBitsInCache >= 8 && this.pendingBufLength < (1 << 16)) {\n this.pendingBuffer[this.pendingBufLength++] = this.pendingBufCache;\n this.pendingBufCache >>= 8;\n this.pendingBufBitsInCache -= 8;\n result++;\n }\n return result;\n };\n CompressedStreamWriter.prototype.pendingBufferWriteByteBlock = function (data, offset, length) {\n var array = data.subarray(offset, offset + length);\n this.pendingBuffer.set(array, this.pendingBufLength);\n this.pendingBufLength += length;\n };\n CompressedStreamWriter.prototype.pendingBufferWriteShort = function (s) {\n this.pendingBuffer[this.pendingBufLength++] = s;\n this.pendingBuffer[this.pendingBufLength++] = (s >> 8);\n };\n CompressedStreamWriter.prototype.pendingBufferAlignToByte = function () {\n if (this.pendingBufBitsInCache > 0) {\n this.pendingBuffer[this.pendingBufLength++] = this.pendingBufCache;\n }\n this.pendingBufCache = 0;\n this.pendingBufBitsInCache = 0;\n };\n /**\n * close the stream and write all pending buffer in to stream\n * @returns {void}\n */\n CompressedStreamWriter.prototype.close = function () {\n do {\n this.pendingBufferFlush(true);\n if (!this.compressData(true)) {\n this.pendingBufferFlush(true);\n this.pendingBufferAlignToByte();\n if (!this.noWrap) {\n this.pendingBufferWriteShortBytes(this.checkSum >> 16);\n this.pendingBufferWriteShortBytes(this.checkSum & 0xffff);\n }\n this.pendingBufferFlush(true);\n }\n } while (!(this.inputEnd === this.inputOffset) ||\n !(this.pendingBufLength === 0));\n };\n /**\n * release allocated un-managed resource\n * @returns {void}\n */\n CompressedStreamWriter.prototype.destroy = function () {\n this.stream = [];\n this.stream = undefined;\n this.pendingBuffer = undefined;\n this.treeLiteral = undefined;\n this.treeDistances = undefined;\n this.treeCodeLengths = undefined;\n this.arrLiterals = undefined;\n this.arrDistances = undefined;\n this.hashHead = undefined;\n this.hashPrevious = undefined;\n this.dataWindow = undefined;\n this.inputBuffer = undefined;\n this.pendingBufLength = undefined;\n this.pendingBufCache = undefined;\n this.pendingBufBitsInCache = undefined;\n this.bufferPosition = undefined;\n this.extraBits = undefined;\n this.currentHash = undefined;\n this.matchStart = undefined;\n this.matchLength = undefined;\n this.matchPrevAvail = undefined;\n this.blockStart = undefined;\n this.stringStart = undefined;\n this.lookAhead = undefined;\n this.totalBytesIn = undefined;\n this.inputOffset = undefined;\n this.inputEnd = undefined;\n this.windowSize = undefined;\n this.windowMask = undefined;\n this.hashSize = undefined;\n this.hashMask = undefined;\n this.hashShift = undefined;\n this.maxDist = undefined;\n this.checkSum = undefined;\n this.noWrap = undefined;\n };\n return CompressedStreamWriter;\n}());\nexport { CompressedStreamWriter };\n/**\n * represent the Huffman Tree\n */\nvar CompressorHuffmanTree = /** @class */ (function () {\n /**\n * Create new Huffman Tree\n * @param {CompressedStreamWriter} writer instance\n * @param {number} elementCount - element count\n * @param {number} minCodes - minimum count\n * @param {number} maxLength - maximum count\n */\n function CompressorHuffmanTree(writer, elementCount, minCodes, maxLength) {\n this.writer = writer;\n this.codeMinCount = minCodes;\n this.maxLength = maxLength;\n this.codeFrequency = new Uint16Array(elementCount);\n this.lengthCount = new Int32Array(maxLength);\n }\n Object.defineProperty(CompressorHuffmanTree.prototype, \"treeLength\", {\n get: function () {\n return this.codeCount;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CompressorHuffmanTree.prototype, \"codeLengths\", {\n get: function () {\n return this.codeLength;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CompressorHuffmanTree.prototype, \"codeFrequencies\", {\n get: function () {\n return this.codeFrequency;\n },\n enumerable: true,\n configurable: true\n });\n CompressorHuffmanTree.prototype.setStaticCodes = function (codes, lengths) {\n var temp = new Int16Array(codes.length);\n temp.set(codes, 0);\n this.codes = temp;\n var lengthTemp = new Uint8Array(lengths.length);\n lengthTemp.set(lengths, 0);\n this.codeLength = lengthTemp;\n };\n /**\n * reset all code data in tree\n * @returns {void}\n */\n CompressorHuffmanTree.prototype.reset = function () {\n for (var i = 0; i < this.codeFrequency.length; i++) {\n this.codeFrequency[i] = 0;\n }\n this.codes = undefined;\n this.codeLength = undefined;\n };\n /**\n * write code to the compressor output stream\n * @param {number} code - code to be written\n * @returns {void}\n */\n CompressorHuffmanTree.prototype.writeCodeToStream = function (code) {\n this.writer.pendingBufferWriteBits(this.codes[code] & 0xffff, this.codeLength[code]);\n };\n /**\n * calculate code from their frequencies\n * @returns {void}\n */\n CompressorHuffmanTree.prototype.buildCodes = function () {\n var nextCode = new Int32Array(this.maxLength);\n this.codes = new Int16Array(this.codeCount);\n var code = 0;\n for (var bitsCount = 0; bitsCount < this.maxLength; bitsCount++) {\n nextCode[bitsCount] = code;\n code += this.lengthCount[bitsCount] << (15 - bitsCount);\n }\n for (var i = 0; i < this.codeCount; i++) {\n var bits = this.codeLength[i];\n if (bits > 0) {\n this.codes[i] = CompressorHuffmanTree.bitReverse(nextCode[bits - 1]);\n nextCode[bits - 1] += 1 << (16 - bits);\n }\n }\n };\n CompressorHuffmanTree.bitReverse = function (value) {\n return (CompressorHuffmanTree.reverseBits[value & 15] << 12\n | CompressorHuffmanTree.reverseBits[(value >> 4) & 15] << 8\n | CompressorHuffmanTree.reverseBits[(value >> 8) & 15] << 4\n | CompressorHuffmanTree.reverseBits[value >> 12]);\n };\n /**\n * calculate length of compressed data\n * @returns {number}\n */\n CompressorHuffmanTree.prototype.getEncodedLength = function () {\n var len = 0;\n for (var i = 0; i < this.codeFrequency.length; i++) {\n len += this.codeFrequency[i] * this.codeLength[i];\n }\n return len;\n };\n /**\n * calculate code frequencies\n * @param {CompressorHuffmanTree} blTree\n * @returns {void}\n */\n CompressorHuffmanTree.prototype.calculateBLFreq = function (blTree) {\n var maxCount;\n var minCount;\n var count;\n var curLen = -1;\n var i = 0;\n while (i < this.codeCount) {\n count = 1;\n var nextLen = this.codeLength[i];\n if (nextLen === 0) {\n maxCount = 138;\n minCount = 3;\n }\n else {\n maxCount = 6;\n minCount = 3;\n if (curLen !== nextLen) {\n blTree.codeFrequency[nextLen]++;\n count = 0;\n }\n }\n curLen = nextLen;\n i++;\n while (i < this.codeCount && curLen === this.codeLength[i]) {\n i++;\n if (++count >= maxCount) {\n break;\n }\n }\n if (count < minCount) {\n blTree.codeFrequency[curLen] += count;\n }\n else if (curLen !== 0) {\n blTree.codeFrequency[16]++;\n }\n else if (count <= 10) {\n blTree.codeFrequency[17]++;\n }\n else {\n blTree.codeFrequency[18]++;\n }\n }\n };\n /**\n * @param {CompressorHuffmanTree} blTree - write tree to output stream\n * @returns {void}\n */\n CompressorHuffmanTree.prototype.writeTree = function (blTree) {\n var maxRepeatCount;\n var minRepeatCount;\n var currentRepeatCount;\n var currentCodeLength = -1;\n var i = 0;\n while (i < this.codeCount) {\n currentRepeatCount = 1;\n var nextLen = this.codeLength[i];\n if (nextLen === 0) {\n maxRepeatCount = 138;\n minRepeatCount = 3;\n }\n else {\n maxRepeatCount = 6;\n minRepeatCount = 3;\n if (currentCodeLength !== nextLen) {\n blTree.writeCodeToStream(nextLen);\n currentRepeatCount = 0;\n }\n }\n currentCodeLength = nextLen;\n i++;\n while (i < this.codeCount && currentCodeLength === this.codeLength[i]) {\n i++;\n if (++currentRepeatCount >= maxRepeatCount) {\n break;\n }\n }\n if (currentRepeatCount < minRepeatCount) {\n while (currentRepeatCount-- > 0) {\n blTree.writeCodeToStream(currentCodeLength);\n }\n }\n else if (currentCodeLength !== 0) {\n blTree.writeCodeToStream(16);\n this.writer.pendingBufferWriteBits(currentRepeatCount - 3, 2);\n }\n else if (currentRepeatCount <= 10) {\n blTree.writeCodeToStream(17);\n this.writer.pendingBufferWriteBits(currentRepeatCount - 3, 3);\n }\n else {\n blTree.writeCodeToStream(18);\n this.writer.pendingBufferWriteBits(currentRepeatCount - 11, 7);\n }\n }\n };\n /**\n * Build huffman tree\n * @returns {void}\n */\n CompressorHuffmanTree.prototype.buildTree = function () {\n var codesCount = this.codeFrequency.length;\n var arrTree = new Int32Array(codesCount);\n var treeLength = 0;\n var maxCount = 0;\n for (var n = 0; n < codesCount; n++) {\n var freq = this.codeFrequency[n];\n if (freq !== 0) {\n var pos = treeLength++;\n var pPos = 0;\n while (pos > 0 && this.codeFrequency[arrTree[pPos = Math.floor((pos - 1) / 2)]] > freq) {\n arrTree[pos] = arrTree[pPos];\n pos = pPos;\n }\n arrTree[pos] = n;\n maxCount = n;\n }\n }\n while (treeLength < 2) {\n arrTree[treeLength++] =\n (maxCount < 2) ? ++maxCount : 0;\n }\n this.codeCount = Math.max(maxCount + 1, this.codeMinCount);\n var leafsCount = treeLength;\n var nodesCount = leafsCount;\n var child = new Int32Array(4 * treeLength - 2);\n var values = new Int32Array(2 * treeLength - 1);\n for (var i = 0; i < treeLength; i++) {\n var node = arrTree[i];\n var iIndex = 2 * i;\n child[iIndex] = node;\n child[iIndex + 1] = -1;\n values[i] = (this.codeFrequency[node] << 8);\n arrTree[i] = i;\n }\n this.constructHuffmanTree(arrTree, treeLength, values, nodesCount, child);\n this.buildLength(child);\n };\n CompressorHuffmanTree.prototype.constructHuffmanTree = function (arrTree, treeLength, values, nodesCount, child) {\n do {\n var first = arrTree[0];\n var last = arrTree[--treeLength];\n var lastVal = values[last];\n var pPos = 0;\n var path = 1;\n while (path < treeLength) {\n if (path + 1 < treeLength && values[arrTree[path]] > values[arrTree[path + 1]]) {\n path++;\n }\n arrTree[pPos] = arrTree[path];\n pPos = path;\n path = pPos * 2 + 1;\n }\n while ((path = pPos) > 0 && values[arrTree[pPos = Math.floor((path - 1) / 2)]] > lastVal) {\n arrTree[path] = arrTree[pPos];\n }\n arrTree[path] = last;\n var second = arrTree[0];\n last = nodesCount++;\n child[2 * last] = first;\n child[2 * last + 1] = second;\n var minDepth = Math.min(values[first] & 0xff, values[second] & 0xff);\n values[last] = lastVal = values[first] + values[second] - minDepth + 1;\n pPos = 0;\n path = 1;\n /* tslint:disable */\n while (path < treeLength) {\n if (path + 1 < treeLength && values[arrTree[path]] > values[arrTree[path + 1]]) {\n path++;\n }\n arrTree[pPos] = arrTree[path];\n pPos = path;\n path = pPos * 2 + 1;\n } /* tslint:disable */\n while ((path = pPos) > 0 && values[arrTree[pPos = Math.floor((path - 1) / 2)]] > lastVal) {\n arrTree[path] = arrTree[pPos];\n }\n arrTree[path] = last;\n } while (treeLength > 1);\n };\n CompressorHuffmanTree.prototype.buildLength = function (child) {\n this.codeLength = new Uint8Array(this.codeFrequency.length);\n var numNodes = Math.floor(child.length / 2);\n var numLeafs = Math.floor((numNodes + 1) / 2);\n var overflow = 0;\n for (var i = 0; i < this.maxLength; i++) {\n this.lengthCount[i] = 0;\n }\n overflow = this.calculateOptimalCodeLength(child, overflow, numNodes);\n if (overflow === 0) {\n return;\n }\n var iIncreasableLength = this.maxLength - 1;\n do {\n while (this.lengthCount[--iIncreasableLength] === 0) {\n /* tslint:disable */\n }\n do {\n this.lengthCount[iIncreasableLength]--;\n this.lengthCount[++iIncreasableLength]++;\n overflow -= (1 << (this.maxLength - 1 - iIncreasableLength));\n } while (overflow > 0 && iIncreasableLength < this.maxLength - 1);\n } while (overflow > 0);\n this.recreateTree(child, overflow, numLeafs);\n };\n CompressorHuffmanTree.prototype.recreateTree = function (child, overflow, numLeafs) {\n this.lengthCount[this.maxLength - 1] += overflow;\n this.lengthCount[this.maxLength - 2] -= overflow;\n var nodePtr = 2 * numLeafs;\n for (var bits = this.maxLength; bits !== 0; bits--) {\n var n = this.lengthCount[bits - 1];\n while (n > 0) {\n var childPtr = 2 * child[nodePtr++];\n if (child[childPtr + 1] === -1) {\n this.codeLength[child[childPtr]] = bits;\n n--;\n }\n }\n }\n };\n CompressorHuffmanTree.prototype.calculateOptimalCodeLength = function (child, overflow, numNodes) {\n var lengths = new Int32Array(numNodes);\n lengths[numNodes - 1] = 0;\n for (var i = numNodes - 1; i >= 0; i--) {\n var childIndex = 2 * i + 1;\n if (child[childIndex] !== -1) {\n var bitLength = lengths[i] + 1;\n if (bitLength > this.maxLength) {\n bitLength = this.maxLength;\n overflow++;\n }\n lengths[child[childIndex - 1]] = lengths[child[childIndex]] = bitLength;\n }\n else {\n var bitLength = lengths[i];\n this.lengthCount[bitLength - 1]++;\n this.codeLength[child[childIndex - 1]] = lengths[i];\n }\n }\n return overflow;\n };\n CompressorHuffmanTree.reverseBits = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];\n CompressorHuffmanTree.huffCodeLengthOrders = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];\n return CompressorHuffmanTree;\n}());\nexport { CompressorHuffmanTree };\n/**\n * Checksum calculator, based on Adler32 algorithm.\n */\nvar ChecksumCalculator = /** @class */ (function () {\n function ChecksumCalculator() {\n }\n /**\n * Updates checksum by calculating checksum of the\n * given buffer and adding it to current value.\n * @param {number} checksum - current checksum.\n * @param {Uint8Array} buffer - data byte array.\n * @param {number} offset - offset in the buffer.\n * @param {number} length - length of data to be used from the stream.\n * @returns {number}\n */\n ChecksumCalculator.checksumUpdate = function (checksum, buffer, offset, length) {\n var uint = new Uint32Array(1);\n uint[0] = checksum;\n var checksum_uint = uint[0];\n var s1 = uint[0] = checksum_uint & 65535;\n var s2 = uint[0] = checksum_uint >> ChecksumCalculator.checkSumBitOffset;\n while (length > 0) {\n var steps = Math.min(length, ChecksumCalculator.checksumIterationCount);\n length -= steps;\n while (--steps >= 0) {\n s1 = s1 + (uint[0] = (buffer[offset++] & 255));\n s2 = s2 + s1;\n }\n s1 %= ChecksumCalculator.checksumBase;\n s2 %= ChecksumCalculator.checksumBase;\n }\n checksum_uint = (s2 << ChecksumCalculator.checkSumBitOffset) | s1;\n return checksum_uint;\n };\n ChecksumCalculator.checkSumBitOffset = 16;\n ChecksumCalculator.checksumBase = 65521;\n ChecksumCalculator.checksumIterationCount = 3800;\n return ChecksumCalculator;\n}());\nexport { ChecksumCalculator };\n/**\n * Huffman Tree literal calculation\n */\n(function () {\n var i = 0;\n while (i < 144) {\n arrLiteralCodes[i] = CompressorHuffmanTree.bitReverse((0x030 + i) << 8);\n arrLiteralLengths[i++] = 8;\n }\n while (i < 256) {\n arrLiteralCodes[i] = CompressorHuffmanTree.bitReverse((0x190 - 144 + i) << 7);\n arrLiteralLengths[i++] = 9;\n }\n while (i < 280) {\n arrLiteralCodes[i] = CompressorHuffmanTree.bitReverse((0x000 - 256 + i) << 9);\n arrLiteralLengths[i++] = 7;\n }\n while (i < 286) {\n arrLiteralCodes[i] = CompressorHuffmanTree.bitReverse((0x0c0 - 280 + i) << 8);\n arrLiteralLengths[i++] = 8;\n }\n for (i = 0; i < 30; i++) {\n arrDistanceCodes[i] = CompressorHuffmanTree.bitReverse(i << 11);\n arrDistanceLengths[i] = 5;\n }\n})();\n","import { CompressedStreamWriter } from './compression-writer';\nimport { Save } from '@syncfusion/ej2-file-utils';\nvar crc32Table = [];\n/**\n * class provide compression library\n * ```typescript\n * let archive = new ZipArchive();\n * archive.compressionLevel = 'Normal';\n * let archiveItem = new ZipArchiveItem(archive, 'directoryName\\fileName.txt');\n * archive.addItem(archiveItem);\n * archive.save(fileName.zip);\n * ```\n */\nvar ZipArchive = /** @class */ (function () {\n /**\n * constructor for creating ZipArchive instance\n */\n function ZipArchive() {\n this.files = [];\n this.level = 'Normal';\n Save.isMicrosoftBrowser = !(!navigator.msSaveBlob);\n }\n Object.defineProperty(ZipArchive.prototype, \"compressionLevel\", {\n /**\n * gets compression level\n */\n get: function () {\n return this.level;\n },\n /**\n * sets compression level\n */\n set: function (level) {\n this.level = level;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ZipArchive.prototype, \"length\", {\n /**\n * gets items count\n */\n get: function () {\n if (this.files === undefined) {\n return 0;\n }\n return this.files.length;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * add new item to archive\n * @param {ZipArchiveItem} item - item to be added\n * @returns {void}\n */\n ZipArchive.prototype.addItem = function (item) {\n if (item === null || item === undefined) {\n throw new Error('ArgumentException: item cannot be null or undefined');\n }\n for (var i = 0; i < this.files.length; i++) {\n var file = this.files[i];\n if (file instanceof ZipArchiveItem) {\n if (file.name === item.name) {\n throw new Error('item with same name already exist');\n }\n }\n }\n this.files.push(item);\n };\n /**\n * add new directory to archive\n * @param directoryName directoryName to be created\n * @returns {void}\n */\n ZipArchive.prototype.addDirectory = function (directoryName) {\n if (directoryName === null || directoryName === undefined) {\n throw new Error('ArgumentException: string cannot be null or undefined');\n }\n if (directoryName.length === 0) {\n throw new Error('ArgumentException: string cannot be empty');\n }\n if (directoryName.slice(-1) !== '/') {\n directoryName += '/';\n }\n if (this.files.indexOf(directoryName) !== -1) {\n throw new Error('item with same name already exist');\n }\n this.files.push(directoryName);\n };\n /**\n * gets item at specified index\n * @param {number} index - item index\n * @returns {ZipArchiveItem}\n */\n ZipArchive.prototype.getItem = function (index) {\n if (index >= 0 && index < this.files.length) {\n return this.files[index];\n }\n return undefined;\n };\n /**\n * determines whether an element is in the collection\n * @param {string | ZipArchiveItem} item - item to search\n * @returns {boolean}\n */\n ZipArchive.prototype.contains = function (item) {\n return this.files.indexOf(item) !== -1 ? true : false;\n };\n /**\n * save archive with specified file name\n * @param {string} fileName save archive with specified file name\n * @returns {Promise
}\n */\n ZipArchive.prototype.save = function (fileName) {\n if (fileName === null || fileName === undefined || fileName.length === 0) {\n throw new Error('ArgumentException: fileName cannot be null or undefined');\n }\n if (this.files.length === 0) {\n throw new Error('InvalidOperation');\n }\n var zipArchive = this;\n var promise;\n return promise = new Promise(function (resolve, reject) {\n zipArchive.saveInternal(fileName, false).then(function () {\n resolve(zipArchive);\n });\n });\n };\n /**\n * Save archive as blob\n * @return {Promise}\n */\n ZipArchive.prototype.saveAsBlob = function () {\n var zipArchive = this;\n var promise;\n return promise = new Promise(function (resolve, reject) {\n zipArchive.saveInternal('', true).then(function (blob) {\n resolve(blob);\n });\n });\n };\n ZipArchive.prototype.saveInternal = function (fileName, skipFileSave) {\n var _this = this;\n var zipArchive = this;\n var promise;\n return promise = new Promise(function (resolve, reject) {\n var zipData = [];\n var dirLength = 0;\n for (var i = 0; i < zipArchive.files.length; i++) {\n var compressedObject = _this.getCompressedData(_this.files[i]);\n compressedObject.then(function (data) {\n dirLength = zipArchive.constructZippedObject(zipData, data, dirLength, data.isDirectory);\n if (zipData.length === zipArchive.files.length) {\n var blob = zipArchive.writeZippedContent(fileName, zipData, dirLength, skipFileSave);\n resolve(blob);\n }\n });\n }\n });\n };\n /**\n * release allocated un-managed resource\n * @returns {void}\n */\n ZipArchive.prototype.destroy = function () {\n if (this.files !== undefined && this.files.length > 0) {\n for (var i = 0; i < this.files.length; i++) {\n var file = this.files[i];\n if (file instanceof ZipArchiveItem) {\n file.destroy();\n }\n file = undefined;\n }\n this.files = [];\n }\n this.files = undefined;\n this.level = undefined;\n };\n ZipArchive.prototype.getCompressedData = function (item) {\n var zipArchive = this;\n var promise = new Promise(function (resolve, reject) {\n if (item instanceof ZipArchiveItem) {\n var reader_1 = new FileReader();\n reader_1.onload = function () {\n var input = new Uint8Array(reader_1.result);\n var data = {\n fileName: item.name, crc32Value: 0, compressedData: [],\n compressedSize: undefined, uncompressedDataSize: input.length, compressionType: undefined,\n isDirectory: false\n };\n if (zipArchive.level === 'Normal') {\n zipArchive.compressData(input, data, crc32Table);\n var length_1 = 0;\n for (var i = 0; i < data.compressedData.length; i++) {\n length_1 += data.compressedData[i].length;\n }\n data.compressedSize = length_1;\n data.compressionType = '\\x08\\x00'; //Deflated = 8\n }\n else {\n data.compressedSize = input.length;\n data.crc32Value = zipArchive.calculateCrc32Value(0, input, crc32Table);\n data.compressionType = '\\x00\\x00'; // Stored = 0\n data.compressedData.push(input);\n }\n resolve(data);\n };\n reader_1.readAsArrayBuffer(item.data);\n }\n else {\n var data = {\n fileName: item, crc32Value: 0, compressedData: '', compressedSize: 0, uncompressedDataSize: 0,\n compressionType: '\\x00\\x00', isDirectory: true\n };\n resolve(data);\n }\n });\n return promise;\n };\n ZipArchive.prototype.compressData = function (input, data, crc32Table) {\n var compressor = new CompressedStreamWriter(true);\n var currentIndex = 0;\n var nextIndex = 0;\n do {\n if (currentIndex >= input.length) {\n compressor.close();\n break;\n }\n nextIndex = Math.min(input.length, currentIndex + 16384);\n var subArray = input.subarray(currentIndex, nextIndex);\n data.crc32Value = this.calculateCrc32Value(data.crc32Value, subArray, crc32Table);\n compressor.write(subArray, 0, nextIndex - currentIndex);\n currentIndex = nextIndex;\n } while (currentIndex <= input.length);\n data.compressedData = compressor.compressedData;\n compressor.destroy();\n };\n ZipArchive.prototype.constructZippedObject = function (zipParts, data, dirLength, isDirectory) {\n var extFileAttr = 0;\n var date = new Date();\n if (isDirectory) {\n extFileAttr = extFileAttr | 0x00010; // directory flag\n }\n extFileAttr = extFileAttr | (0 & 0x3F);\n var header = this.writeHeader(data, date);\n var localHeader = 'PK\\x03\\x04' + header + data.fileName;\n var centralDir = this.writeCentralDirectory(data, header, dirLength, extFileAttr);\n zipParts.push({ localHeader: localHeader, centralDir: centralDir, compressedData: data });\n return dirLength + localHeader.length + data.compressedSize;\n };\n ZipArchive.prototype.writeHeader = function (data, date) {\n var zipHeader = '';\n zipHeader += '\\x0A\\x00' + '\\x00\\x00'; // version needed to extract & general purpose bit flag\n zipHeader += data.compressionType; // compression method Deflate=8,Stored=0\n zipHeader += this.getBytes(this.getModifiedTime(date), 2); // last modified Time\n zipHeader += this.getBytes(this.getModifiedDate(date), 2); // last modified date\n zipHeader += this.getBytes(data.crc32Value, 4); // crc-32 value\n zipHeader += this.getBytes(data.compressedSize, 4); // compressed file size\n zipHeader += this.getBytes(data.uncompressedDataSize, 4); // uncompressed file size\n zipHeader += this.getBytes(data.fileName.length, 2); // file name length\n zipHeader += this.getBytes(0, 2); // extra field length\n return zipHeader;\n };\n ZipArchive.prototype.writeZippedContent = function (fileName, zipData, localDirLen, skipFileSave) {\n var cenDirLen = 0;\n var buffer = [];\n for (var i = 0; i < zipData.length; i++) {\n var item = zipData[i];\n cenDirLen += item.centralDir.length;\n buffer.push(this.getArrayBuffer(item.localHeader));\n while (item.compressedData.compressedData.length) {\n buffer.push(item.compressedData.compressedData.shift().buffer);\n }\n }\n for (var i = 0; i < zipData.length; i++) {\n buffer.push(this.getArrayBuffer(zipData[i].centralDir));\n }\n buffer.push(this.getArrayBuffer(this.writeFooter(zipData, cenDirLen, localDirLen)));\n var blob = new Blob(buffer, { type: 'application/zip' });\n if (!skipFileSave) {\n Save.save(fileName, blob);\n }\n return blob;\n };\n ZipArchive.prototype.writeCentralDirectory = function (data, localHeader, offset, externalFileAttribute) {\n var directoryHeader = 'PK\\x01\\x02' +\n this.getBytes(0x0014, 2) + localHeader + // inherit from file header\n this.getBytes(0, 2) + // comment length\n '\\x00\\x00' + '\\x00\\x00' + // internal file attributes \n this.getBytes(externalFileAttribute, 4) + // external file attributes\n this.getBytes(offset, 4) + // local fileHeader relative offset\n data.fileName;\n return directoryHeader;\n };\n ZipArchive.prototype.writeFooter = function (zipData, centralLength, localLength) {\n var dirEnd = 'PK\\x05\\x06' + '\\x00\\x00' + '\\x00\\x00' +\n this.getBytes(zipData.length, 2) + this.getBytes(zipData.length, 2) +\n this.getBytes(centralLength, 4) + this.getBytes(localLength, 4) +\n this.getBytes(0, 2);\n return dirEnd;\n };\n ZipArchive.prototype.getArrayBuffer = function (input) {\n var a = new Uint8Array(input.length);\n for (var j = 0; j < input.length; ++j) {\n a[j] = input.charCodeAt(j) & 0xFF;\n }\n return a.buffer;\n };\n ZipArchive.prototype.getBytes = function (value, offset) {\n var bytes = '';\n for (var i = 0; i < offset; i++) {\n bytes += String.fromCharCode(value & 0xff);\n value = value >>> 8;\n }\n return bytes;\n };\n ZipArchive.prototype.getModifiedTime = function (date) {\n var modTime = date.getHours();\n modTime = modTime << 6;\n modTime = modTime | date.getMinutes();\n modTime = modTime << 5;\n return modTime = modTime | date.getSeconds() / 2;\n };\n ZipArchive.prototype.getModifiedDate = function (date) {\n var modiDate = date.getFullYear() - 1980;\n modiDate = modiDate << 4;\n modiDate = modiDate | (date.getMonth() + 1);\n modiDate = modiDate << 5;\n return modiDate = modiDate | date.getDate();\n };\n ZipArchive.prototype.calculateCrc32Value = function (crc32Value, input, crc32Table) {\n crc32Value ^= -1;\n for (var i = 0; i < input.length; i++) {\n crc32Value = (crc32Value >>> 8) ^ crc32Table[(crc32Value ^ input[i]) & 0xFF];\n }\n return (crc32Value ^ (-1));\n };\n return ZipArchive;\n}());\nexport { ZipArchive };\n/**\n * Class represent unique ZipArchive item\n * ```typescript\n * let archiveItem = new ZipArchiveItem(archive, 'directoryName\\fileName.txt');\n * ```\n */\nvar ZipArchiveItem = /** @class */ (function () {\n /**\n * constructor for creating {ZipArchiveItem} instance\n * @param {Blob|ArrayBuffer} data file data\n * @param {itemName} itemName absolute file path\n */\n function ZipArchiveItem(data, itemName) {\n if (data === null || data === undefined) {\n throw new Error('ArgumentException: data cannot be null or undefined');\n }\n if (itemName === null || itemName === undefined) {\n throw new Error('ArgumentException: string cannot be null or undefined');\n }\n if (itemName.length === 0) {\n throw new Error('string cannot be empty');\n }\n this.data = data;\n this.name = itemName;\n }\n Object.defineProperty(ZipArchiveItem.prototype, \"name\", {\n /**\n * Get the name of archive item\n * @returns string\n */\n get: function () {\n return this.fileName;\n },\n /**\n * Set the name of archive item\n * @param {string} value\n */\n set: function (value) {\n this.fileName = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * release allocated un-managed resource\n * @returns {void}\n */\n ZipArchiveItem.prototype.destroy = function () {\n this.fileName = undefined;\n this.data = undefined;\n };\n return ZipArchiveItem;\n}());\nexport { ZipArchiveItem };\n/**\n * construct cyclic redundancy code table\n */\n(function () {\n var i;\n for (var j = 0; j < 256; j++) {\n i = j;\n for (var k = 0; k < 8; k++) {\n i = ((i & 1) ? (0xEDB88320 ^ (i >>> 1)) : (i >>> 1));\n }\n crc32Table[j] = i;\n }\n})();\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfDictionary } from './pdf-dictionary';\nimport { PdfNumber } from './pdf-number';\nimport { Operators } from './../input-output/pdf-operators';\nimport { PdfName } from './pdf-name';\nimport { PdfArray } from './pdf-array';\nimport { PdfReferenceHolder } from './pdf-reference';\nimport { CompressedStreamWriter } from '@syncfusion/ej2-compression';\n/**\n * `PdfStream` class is used to perform stream related primitive operations.\n * @private\n */\nvar PdfStream = /** @class */ (function (_super) {\n __extends(PdfStream, _super);\n function PdfStream(dictionary, data) {\n var _this = _super.call(this, dictionary) || this;\n //Constants\n /**\n * @hidden\n * @private\n */\n _this.dicPrefix = 'stream';\n /**\n * @hidden\n * @private\n */\n _this.dicSuffix = 'endstream';\n /**\n * Internal variable to hold `cloned object`.\n * @private\n */\n _this.clonedObject2 = null;\n /**\n * @hidden\n * @private\n */\n _this.bCompress = true;\n /**\n * @hidden\n * @private\n */\n _this.isImageStream = false;\n /**\n * @hidden\n * @private\n */\n _this.isFontStream = false;\n if (typeof dictionary !== 'undefined' || typeof data !== 'undefined') {\n _this.dataStream2 = [];\n _this.dataStream2 = data;\n _this.bCompress2 = false;\n }\n else {\n _this.dataStream2 = [];\n _this.bCompress2 = true;\n //Pending\n }\n return _this;\n }\n Object.defineProperty(PdfStream.prototype, \"internalStream\", {\n /**\n * Gets the `internal` stream.\n * @private\n */\n get: function () {\n return this.dataStream2;\n },\n set: function (value) {\n this.dataStream2 = [];\n this.dataStream2 = value;\n this.modify();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStream.prototype, \"isImage\", {\n /**\n * Gets or sets 'is image' flag.\n * @private\n */\n get: function () {\n return this.isImageStream;\n },\n set: function (value) {\n this.isImageStream = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStream.prototype, \"isFont\", {\n /**\n * Gets or sets 'is font' flag.\n * @private\n */\n get: function () {\n return this.isFontStream;\n },\n set: function (value) {\n this.isFontStream = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStream.prototype, \"compress\", {\n /**\n * Gets or sets `compression` flag.\n * @private\n */\n get: function () {\n return this.bCompress;\n },\n set: function (value) {\n this.bCompress = value;\n this.modify();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStream.prototype, \"data\", {\n /**\n * Gets or sets the `data`.\n * @private\n */\n get: function () {\n return this.dataStream2;\n },\n set: function (value) {\n this.dataStream2 = [];\n this.dataStream2 = value;\n this.modify();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Clear` the internal stream.\n * @private\n */\n PdfStream.prototype.clearStream = function () {\n this.internalStream = [];\n if (this.items.containsKey(this.dictionaryProperties.filter)) {\n this.remove(this.dictionaryProperties.filter);\n }\n this.bCompress = true;\n this.modify();\n };\n /**\n * `Writes` the specified string.\n * @private\n */\n PdfStream.prototype.write = function (text) {\n if (text == null) {\n throw new Error('ArgumentNullException:text');\n }\n if (text.length <= 0) {\n throw new Error('ArgumentException: Can not write an empty string, text');\n }\n this.dataStream2.push(text);\n this.modify();\n };\n /**\n * `Writes` the specified bytes.\n * @private\n */\n PdfStream.prototype.writeBytes = function (data) {\n if (data === null) {\n throw new Error('ArgumentNullException:data');\n }\n if (data.length <= 0) {\n throw new Error('ArgumentException: Can not write an empty bytes, data');\n }\n var text = '';\n for (var i = 0; i < data.length; i++) {\n text += String.fromCharCode(data[i]);\n }\n this.dataStream2.push(text);\n this.modify();\n };\n /**\n * Raises event `Cmap BeginSave`.\n * @private\n */\n PdfStream.prototype.onCmapBeginSave = function () {\n this.cmapBeginSave.sender.cmapBeginSave();\n };\n /**\n * Raises event `Font Program BeginSave`.\n * @private\n */\n PdfStream.prototype.onFontProgramBeginSave = function () {\n this.fontProgramBeginSave.sender.fontProgramBeginSave();\n };\n /**\n * `Compresses the content` if it's required.\n * @private\n */\n PdfStream.prototype.compressContent = function (data, writer) {\n if (this.bCompress) {\n var byteArray = [];\n for (var i = 0; i < data.length; i++) {\n byteArray.push(data.charCodeAt(i));\n }\n var dataArray = new Uint8Array(byteArray);\n var sw = new CompressedStreamWriter();\n // data = 'Hello World!!!';\n sw.write(dataArray, 0, dataArray.length);\n sw.close();\n data = sw.getCompressedString;\n this.addFilter(this.dictionaryProperties.flatedecode);\n }\n return data;\n };\n /**\n * `Adds a filter` to the filter array.\n * @private\n */\n PdfStream.prototype.addFilter = function (filterName) {\n var obj = this.items.getValue(this.dictionaryProperties.filter);\n if (obj instanceof PdfReferenceHolder) {\n var rh = obj;\n obj = rh.object;\n }\n var array = obj;\n var name = obj;\n if (name != null) {\n array = new PdfArray();\n array.insert(0, name);\n this.items.setValue(this.dictionaryProperties.filter, array);\n }\n name = new PdfName(filterName);\n if (array == null) {\n this.items.setValue(this.dictionaryProperties.filter, name);\n }\n else {\n array.insert(0, name);\n }\n };\n /**\n * `Saves` the object using the specified writer.\n * @private\n */\n PdfStream.prototype.save = function (writer) {\n if (typeof this.cmapBeginSave !== 'undefined') {\n this.onCmapBeginSave();\n }\n if (typeof this.fontProgramBeginSave !== 'undefined') {\n this.onFontProgramBeginSave();\n }\n var data = '';\n for (var i = 0; i < this.data.length; i++) {\n data = data + this.data[i];\n }\n if (data.length > 1 && !this.isImage && !this.isFont) {\n data = 'q\\r\\n' + data + 'Q\\r\\n';\n }\n data = this.compressContent(data, writer);\n var length = data.length;\n this.items.setValue(this.dictionaryProperties.length, new PdfNumber(length));\n _super.prototype.save.call(this, writer, false);\n writer.write(this.dicPrefix);\n writer.write(Operators.newLine);\n if (data.length > 0) {\n writer.write(data);\n }\n writer.write(Operators.newLine);\n writer.write(this.dicSuffix);\n writer.write(Operators.newLine);\n };\n /**\n * Converts `bytes to string`.\n * @private\n */\n PdfStream.bytesToString = function (byteArray) {\n var output = '';\n for (var i = 0; i < byteArray.length; i++) {\n output = output + String.fromCharCode(byteArray[i]);\n }\n return output;\n };\n return PdfStream;\n}(PdfDictionary));\nexport { PdfStream };\nvar SaveCmapEventHandler = /** @class */ (function () {\n /**\n * New instance for `save section collection event handler` class.\n * @private\n */\n function SaveCmapEventHandler(sender) {\n this.sender = sender;\n }\n return SaveCmapEventHandler;\n}());\nexport { SaveCmapEventHandler };\nvar SaveFontProgramEventHandler = /** @class */ (function () {\n /**\n * New instance for `save section collection event handler` class.\n * @private\n */\n function SaveFontProgramEventHandler(sender) {\n this.sender = sender;\n }\n return SaveFontProgramEventHandler;\n}());\nexport { SaveFontProgramEventHandler };\n","/**\n * `PdfString` class is used to perform string related primitive operations.\n * @private\n */\nexport var InternalEnum;\n(function (InternalEnum) {\n //Internals\n /**\n * public Enum for `ForceEncoding`.\n * @private\n */\n var ForceEncoding;\n (function (ForceEncoding) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n ForceEncoding[ForceEncoding[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `Ascii`.\n * @private\n */\n ForceEncoding[ForceEncoding[\"Ascii\"] = 1] = \"Ascii\";\n /**\n * Specifies the type of `Unicode`.\n * @private\n */\n ForceEncoding[ForceEncoding[\"Unicode\"] = 2] = \"Unicode\";\n })(ForceEncoding = InternalEnum.ForceEncoding || (InternalEnum.ForceEncoding = {}));\n /**\n * public Enum for `SourceType`.\n * @private\n */\n var SourceType;\n (function (SourceType) {\n /**\n * Specifies the type of `StringValue`.\n * @private\n */\n SourceType[SourceType[\"StringValue\"] = 0] = \"StringValue\";\n /**\n * Specifies the type of `ByteBuffer`.\n * @private\n */\n SourceType[SourceType[\"ByteBuffer\"] = 1] = \"ByteBuffer\";\n })(SourceType || (SourceType = {}));\n})(InternalEnum || (InternalEnum = {}));\nvar PdfString = /** @class */ (function () {\n function PdfString(value) {\n /**\n * Value indicating whether the string was converted to hex.\n * @default false\n * @private\n */\n this.bHex = false;\n /**\n * Internal variable to store the `position`.\n * @default -1\n * @private\n */\n this.position1 = -1;\n /**\n * Internal variable to hold `cloned object`.\n * @default null\n * @private\n */\n this.clonedObject1 = null;\n /**\n * `Shows` if the data of the stream was decrypted.\n * @default false\n * @private\n */\n this.bDecrypted = false;\n /**\n * Shows if the data of the stream `was decrypted`.\n * @default false\n * @private\n */\n this.isParentDecrypted = false;\n /**\n * Gets a value indicating whether the object is `packed or not`.\n * @default false\n * @private\n */\n this.isPacked = false;\n /**\n * @hidden\n * @private\n */\n this.isFormField = false;\n /**\n * @hidden\n * @private\n */\n this.isColorSpace = false;\n /**\n * @hidden\n * @private\n */\n this.isHexString = true;\n if (typeof value === 'undefined') {\n this.bHex = false;\n }\n else {\n if (!(value.length > 0 && value[0] === '0xfeff')) {\n this.stringValue = value;\n this.data = [];\n for (var i = 0; i < value.length; ++i) {\n this.data.push(value.charCodeAt(i));\n }\n }\n }\n }\n Object.defineProperty(PdfString.prototype, \"hex\", {\n //Property\n /**\n * Gets a value indicating whether string is in `hex`.\n * @private\n */\n get: function () {\n return this.bHex;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"value\", {\n /**\n * Gets or sets string `value` of the object.\n * @private\n */\n get: function () {\n return this.stringValue;\n },\n set: function (value) {\n this.stringValue = value;\n this.data = null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"status\", {\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.status1;\n },\n set: function (value) {\n this.status1 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.isSaving1;\n },\n set: function (value) {\n this.isSaving1 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index1;\n },\n set: function (value) {\n this.index1 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n return this.clonedObject1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.position1;\n },\n set: function (value) {\n this.position1 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"CrossTable\", {\n /**\n * Returns `PdfCrossTable` associated with the object.\n * @private\n */\n get: function () {\n return this.crossTable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"converted\", {\n /**\n * Gets a value indicating whether to check if the value has unicode characters.\n * @private\n */\n get: function () {\n return this.bConverted;\n },\n /**\n * sets a value indicating whether to check if the value has unicode characters.\n * @private\n */\n set: function (value) {\n this.bConverted = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfString.prototype, \"encode\", {\n /**\n * Gets value indicating whether we should convert data to Unicode.\n */\n get: function () {\n return this.bForceEncoding;\n },\n set: function (value) {\n this.bForceEncoding = value;\n },\n enumerable: true,\n configurable: true\n });\n //Methods\n /**\n * Converts `bytes to string using hex format` for representing string.\n * @private\n */\n PdfString.bytesToHex = function (bytes) {\n if (bytes == null) {\n return '';\n }\n var builder = '';\n return builder;\n };\n /**\n * `Saves` the object using the specified writer.\n * @private\n */\n PdfString.prototype.save = function (writer) {\n if (writer === null) {\n throw new Error('ArgumentNullException : writer');\n }\n if (this.encode !== undefined && this.encode === InternalEnum.ForceEncoding.Ascii) {\n writer.write(this.pdfEncode());\n }\n else {\n writer.write(PdfString.stringMark[0] + this.value + PdfString.stringMark[1]);\n }\n };\n PdfString.prototype.pdfEncode = function () {\n var result = '';\n if (this.encode !== undefined && this.encode === InternalEnum.ForceEncoding.Ascii) {\n var data = this.escapeSymbols(this.value);\n for (var i = 0; i < data.length; i++) {\n result += String.fromCharCode(data[i]);\n }\n result = PdfString.stringMark[0] + result + PdfString.stringMark[1];\n }\n else {\n result = this.value;\n }\n return result;\n };\n PdfString.prototype.escapeSymbols = function (value) {\n var data = [];\n for (var i = 0; i < value.length; i++) {\n var currentData = value.charCodeAt(i);\n switch (currentData) {\n case 40:\n case 41:\n data.push(92);\n data.push(currentData);\n break;\n case 13:\n data.push(92);\n data.push(114);\n break;\n case 92:\n data.push(92);\n data.push(currentData);\n break;\n default:\n data.push(currentData);\n break;\n }\n }\n return data;\n };\n /**\n * Creates a `copy of PdfString`.\n * @private\n */\n PdfString.prototype.clone = function (crossTable) {\n if (this.clonedObject1 !== null && this.clonedObject1.CrossTable === crossTable) {\n return this.clonedObject1;\n }\n else {\n this.clonedObject1 = null;\n }\n var newString = new PdfString(this.stringValue);\n newString.bHex = this.bHex;\n newString.crossTable = crossTable;\n newString.isColorSpace = this.isColorSpace;\n this.clonedObject1 = newString;\n return newString;\n };\n /**\n * Converts string to array of unicode symbols.\n */\n PdfString.toUnicodeArray = function (value, bAddPrefix) {\n if (value == null) {\n throw new Error('Argument Null Exception : value');\n }\n var startIndex = 0;\n var output = [];\n for (var i = 0; i < value.length; i++) {\n output.push(0);\n output.push(value.charCodeAt(i));\n }\n return output;\n };\n /**\n * Converts byte data to string.\n */\n PdfString.byteToString = function (data) {\n if (data == null) {\n throw new Error('Argument Null Exception : stream');\n }\n var result = '';\n for (var i = 0; i < data.length; ++i) {\n result += String.fromCharCode(data[i]);\n }\n return result;\n };\n //constants = ;\n /**\n * `General markers` for string.\n * @private\n */\n PdfString.stringMark = '()';\n /**\n * `Hex markers` for string.\n * @private\n */\n PdfString.hexStringMark = '<>';\n /**\n * Format of password data.\n * @private\n */\n PdfString.hexFormatPattern = '{0:X2}';\n return PdfString;\n}());\nexport { PdfString };\n","/**\n * public Enum for `PdfHorizontalAlignment`.\n * @private\n */\nexport var PdfHorizontalAlignment;\n(function (PdfHorizontalAlignment) {\n /**\n * Specifies the type of `Left`.\n * @private\n */\n PdfHorizontalAlignment[PdfHorizontalAlignment[\"Left\"] = 0] = \"Left\";\n /**\n * Specifies the type of `Center`.\n * @private\n */\n PdfHorizontalAlignment[PdfHorizontalAlignment[\"Center\"] = 1] = \"Center\";\n /**\n * Specifies the type of `Right`.\n * @private\n */\n PdfHorizontalAlignment[PdfHorizontalAlignment[\"Right\"] = 2] = \"Right\";\n})(PdfHorizontalAlignment || (PdfHorizontalAlignment = {}));\n/**\n * public Enum for `PdfVerticalAlignment`.\n * @private\n */\nexport var PdfVerticalAlignment;\n(function (PdfVerticalAlignment) {\n /**\n * Specifies the type of `Top`.\n * @private\n */\n PdfVerticalAlignment[PdfVerticalAlignment[\"Top\"] = 0] = \"Top\";\n /**\n * Specifies the type of `Middle`.\n * @private\n */\n PdfVerticalAlignment[PdfVerticalAlignment[\"Middle\"] = 1] = \"Middle\";\n /**\n * Specifies the type of `Bottom`.\n * @private\n */\n PdfVerticalAlignment[PdfVerticalAlignment[\"Bottom\"] = 2] = \"Bottom\";\n})(PdfVerticalAlignment || (PdfVerticalAlignment = {}));\n/**\n * public Enum for `public`.\n * @private\n */\nexport var PdfTextAlignment;\n(function (PdfTextAlignment) {\n /**\n * Specifies the type of `Left`.\n * @private\n */\n PdfTextAlignment[PdfTextAlignment[\"Left\"] = 0] = \"Left\";\n /**\n * Specifies the type of `Center`.\n * @private\n */\n PdfTextAlignment[PdfTextAlignment[\"Center\"] = 1] = \"Center\";\n /**\n * Specifies the type of `Right`.\n * @private\n */\n PdfTextAlignment[PdfTextAlignment[\"Right\"] = 2] = \"Right\";\n /**\n * Specifies the type of `Justify`.\n * @private\n */\n PdfTextAlignment[PdfTextAlignment[\"Justify\"] = 3] = \"Justify\";\n})(PdfTextAlignment || (PdfTextAlignment = {}));\n/**\n * public Enum for `TextRenderingMode`.\n * @private\n */\nexport var TextRenderingMode;\n(function (TextRenderingMode) {\n /**\n * Specifies the type of `Fill`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"Fill\"] = 0] = \"Fill\";\n /**\n * Specifies the type of `Stroke`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"Stroke\"] = 1] = \"Stroke\";\n /**\n * Specifies the type of `FillStroke`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"FillStroke\"] = 2] = \"FillStroke\";\n /**\n * Specifies the type of `None`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"None\"] = 3] = \"None\";\n /**\n * Specifies the type of `ClipFlag`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"ClipFlag\"] = 4] = \"ClipFlag\";\n /**\n * Specifies the type of `ClipFill`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"ClipFill\"] = 4] = \"ClipFill\";\n /**\n * Specifies the type of `ClipStroke`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"ClipStroke\"] = 5] = \"ClipStroke\";\n /**\n * Specifies the type of `ClipFillStroke`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"ClipFillStroke\"] = 6] = \"ClipFillStroke\";\n /**\n * Specifies the type of `Clip`.\n * @private\n */\n TextRenderingMode[TextRenderingMode[\"Clip\"] = 7] = \"Clip\";\n})(TextRenderingMode || (TextRenderingMode = {}));\n/**\n * public Enum for `PdfLineJoin`.\n * @private\n */\nexport var PdfLineJoin;\n(function (PdfLineJoin) {\n /**\n * Specifies the type of `Miter`.\n * @private\n */\n PdfLineJoin[PdfLineJoin[\"Miter\"] = 0] = \"Miter\";\n /**\n * Specifies the type of `Round`.\n * @private\n */\n PdfLineJoin[PdfLineJoin[\"Round\"] = 1] = \"Round\";\n /**\n * Specifies the type of `Bevel`.\n * @private\n */\n PdfLineJoin[PdfLineJoin[\"Bevel\"] = 2] = \"Bevel\";\n})(PdfLineJoin || (PdfLineJoin = {}));\n/**\n * public Enum for `PdfLineCap`.\n * @private\n */\nexport var PdfLineCap;\n(function (PdfLineCap) {\n /**\n * Specifies the type of `Flat`.\n * @private\n */\n PdfLineCap[PdfLineCap[\"Flat\"] = 0] = \"Flat\";\n /**\n * Specifies the type of `Round`.\n * @private\n */\n PdfLineCap[PdfLineCap[\"Round\"] = 1] = \"Round\";\n /**\n * Specifies the type of `Square`.\n * @private\n */\n PdfLineCap[PdfLineCap[\"Square\"] = 2] = \"Square\";\n})(PdfLineCap || (PdfLineCap = {}));\n/**\n * public Enum for `PdfDashStyle`.\n * @private\n */\nexport var PdfDashStyle;\n(function (PdfDashStyle) {\n /**\n * Specifies the type of `Solid`.\n * @private\n */\n PdfDashStyle[PdfDashStyle[\"Solid\"] = 0] = \"Solid\";\n /**\n * Specifies the type of `Dash`.\n * @private\n */\n PdfDashStyle[PdfDashStyle[\"Dash\"] = 1] = \"Dash\";\n /**\n * Specifies the type of `Dot`.\n * @private\n */\n PdfDashStyle[PdfDashStyle[\"Dot\"] = 2] = \"Dot\";\n /**\n * Specifies the type of `DashDot`.\n * @private\n */\n PdfDashStyle[PdfDashStyle[\"DashDot\"] = 3] = \"DashDot\";\n /**\n * Specifies the type of `DashDotDot`.\n * @private\n */\n PdfDashStyle[PdfDashStyle[\"DashDotDot\"] = 4] = \"DashDotDot\";\n /**\n * Specifies the type of `Custom`.\n * @private\n */\n PdfDashStyle[PdfDashStyle[\"Custom\"] = 5] = \"Custom\";\n})(PdfDashStyle || (PdfDashStyle = {}));\n/**\n * public Enum for `PdfFillMode`.\n * @private\n */\nexport var PdfFillMode;\n(function (PdfFillMode) {\n /**\n * Specifies the type of `Winding`.\n * @private\n */\n PdfFillMode[PdfFillMode[\"Winding\"] = 0] = \"Winding\";\n /**\n * Specifies the type of `Alternate`.\n * @private\n */\n PdfFillMode[PdfFillMode[\"Alternate\"] = 1] = \"Alternate\";\n})(PdfFillMode || (PdfFillMode = {}));\n/**\n * public Enum for `PdfColorSpace`.\n * @private\n */\nexport var PdfColorSpace;\n(function (PdfColorSpace) {\n /**\n * Specifies the type of `Rgb`.\n * @private\n */\n PdfColorSpace[PdfColorSpace[\"Rgb\"] = 0] = \"Rgb\";\n /**\n * Specifies the type of `Cmyk`.\n * @private\n */\n PdfColorSpace[PdfColorSpace[\"Cmyk\"] = 1] = \"Cmyk\";\n /**\n * Specifies the type of `GrayScale`.\n * @private\n */\n PdfColorSpace[PdfColorSpace[\"GrayScale\"] = 2] = \"GrayScale\";\n /**\n * Specifies the type of `Indexed`.\n * @private\n */\n PdfColorSpace[PdfColorSpace[\"Indexed\"] = 3] = \"Indexed\";\n})(PdfColorSpace || (PdfColorSpace = {}));\n/**\n * public Enum for `PdfBlendMode`.\n * @private\n */\nexport var PdfBlendMode;\n(function (PdfBlendMode) {\n /**\n * Specifies the type of `Normal`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Normal\"] = 0] = \"Normal\";\n /**\n * Specifies the type of `Multiply`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Multiply\"] = 1] = \"Multiply\";\n /**\n * Specifies the type of `Screen`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Screen\"] = 2] = \"Screen\";\n /**\n * Specifies the type of `Overlay`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Overlay\"] = 3] = \"Overlay\";\n /**\n * Specifies the type of `Darken`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Darken\"] = 4] = \"Darken\";\n /**\n * Specifies the type of `Lighten`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Lighten\"] = 5] = \"Lighten\";\n /**\n * Specifies the type of `ColorDodge`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"ColorDodge\"] = 6] = \"ColorDodge\";\n /**\n * Specifies the type of `ColorBurn`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"ColorBurn\"] = 7] = \"ColorBurn\";\n /**\n * Specifies the type of `HardLight`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"HardLight\"] = 8] = \"HardLight\";\n /**\n * Specifies the type of `SoftLight`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"SoftLight\"] = 9] = \"SoftLight\";\n /**\n * Specifies the type of `Difference`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Difference\"] = 10] = \"Difference\";\n /**\n * Specifies the type of `Exclusion`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Exclusion\"] = 11] = \"Exclusion\";\n /**\n * Specifies the type of `Hue`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Hue\"] = 12] = \"Hue\";\n /**\n * Specifies the type of `Saturation`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Saturation\"] = 13] = \"Saturation\";\n /**\n * Specifies the type of `Color`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Color\"] = 14] = \"Color\";\n /**\n * Specifies the type of `Luminosity`.\n * @private\n */\n PdfBlendMode[PdfBlendMode[\"Luminosity\"] = 15] = \"Luminosity\";\n})(PdfBlendMode || (PdfBlendMode = {}));\n/**\n * public Enum for `PdfGraphicsUnit`.\n * @private\n */\nexport var PdfGraphicsUnit;\n(function (PdfGraphicsUnit) {\n /**\n * Specifies the type of `Centimeter`.\n * @private\n */\n PdfGraphicsUnit[PdfGraphicsUnit[\"Centimeter\"] = 0] = \"Centimeter\";\n /**\n * Specifies the type of `Pica`.\n * @private\n */\n PdfGraphicsUnit[PdfGraphicsUnit[\"Pica\"] = 1] = \"Pica\";\n /**\n * Specifies the type of `Pixel`.\n * @private\n */\n PdfGraphicsUnit[PdfGraphicsUnit[\"Pixel\"] = 2] = \"Pixel\";\n /**\n * Specifies the type of `Point`.\n * @private\n */\n PdfGraphicsUnit[PdfGraphicsUnit[\"Point\"] = 3] = \"Point\";\n /**\n * Specifies the type of `Inch`.\n * @private\n */\n PdfGraphicsUnit[PdfGraphicsUnit[\"Inch\"] = 4] = \"Inch\";\n /**\n * Specifies the type of `Document`.\n * @private\n */\n PdfGraphicsUnit[PdfGraphicsUnit[\"Document\"] = 5] = \"Document\";\n /**\n * Specifies the type of `Millimeter`.\n * @private\n */\n PdfGraphicsUnit[PdfGraphicsUnit[\"Millimeter\"] = 6] = \"Millimeter\";\n})(PdfGraphicsUnit || (PdfGraphicsUnit = {}));\n/**\n * public Enum for `PdfGridImagePosition`.\n * @private\n */\nexport var PdfGridImagePosition;\n(function (PdfGridImagePosition) {\n /**\n * Specifies the type of `Fit`.\n * @private\n */\n PdfGridImagePosition[PdfGridImagePosition[\"Fit\"] = 0] = \"Fit\";\n /**\n * Specifies the type of `Center`.\n * @private\n */\n PdfGridImagePosition[PdfGridImagePosition[\"Center\"] = 1] = \"Center\";\n /**\n * Specifies the type of `Stretch`.\n * @private\n */\n PdfGridImagePosition[PdfGridImagePosition[\"Stretch\"] = 2] = \"Stretch\";\n /**\n * Specifies the type of `Tile`.\n * @private\n */\n PdfGridImagePosition[PdfGridImagePosition[\"Tile\"] = 3] = \"Tile\";\n})(PdfGridImagePosition || (PdfGridImagePosition = {}));\n","import { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { PdfStream } from './../primitives/pdf-stream';\nimport { PdfArray } from './../primitives/pdf-array';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { PdfString } from './../primitives/pdf-string';\n/**\n * `PdfReference` class is used to perform reference related primitive operations.\n * @private\n */\nvar PdfReference = /** @class */ (function () {\n function PdfReference(objNumber, genNumber) {\n /**\n * Holds the `index` number of the object.\n * @default -1\n * @private\n */\n this.index3 = -1;\n /**\n * Internal variable to store the `position`.\n * @default -1\n * @private\n */\n this.position3 = -1;\n /**\n * Holds the `object number`.\n * @default 0\n * @private\n */\n this.objNumber = 0;\n /**\n * Holds the `generation number` of the object.\n * @default 0\n * @private\n */\n this.genNumber = 0;\n if (typeof objNumber === 'number' && typeof genNumber === 'number') {\n this.objNumber = objNumber;\n this.genNumber = genNumber;\n // } else if (typeof objNum === 'string' && typeof genNum === 'string') {\n }\n else {\n this.objNumber = Number(objNumber);\n this.genNumber = Number(genNumber);\n }\n }\n Object.defineProperty(PdfReference.prototype, \"status\", {\n //Property\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.status3;\n },\n set: function (value) {\n this.status3 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReference.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.isSaving3;\n },\n set: function (value) {\n this.isSaving3 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReference.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index3;\n },\n set: function (value) {\n this.index3 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReference.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.position3;\n },\n set: function (value) {\n this.position3 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReference.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n var returnObject3 = null;\n return returnObject3;\n },\n enumerable: true,\n configurable: true\n });\n //IPdfPrimitives methods\n /**\n * `Saves` the object.\n * @private\n */\n PdfReference.prototype.save = function (writer) {\n writer.write(this.toString());\n };\n /**\n * Returns a `string` representing the object.\n * @private\n */\n PdfReference.prototype.toString = function () {\n return this.objNumber.toString() + ' ' + this.genNumber.toString() + ' R';\n };\n /**\n * Creates a `deep copy` of the IPdfPrimitive object.\n * @private\n */\n PdfReference.prototype.clone = function (crossTable) {\n return null;\n };\n return PdfReference;\n}());\nexport { PdfReference };\n/**\n * `PdfReferenceHolder` class is used to perform reference holder related primitive operations.\n * @private\n */\nvar PdfReferenceHolder = /** @class */ (function () {\n function PdfReferenceHolder(obj1, obj2) {\n /**\n * Holds the `index` number of the object.\n * @default -1\n * @private\n */\n this.index4 = -1;\n /**\n * Internal variable to store the `position`.\n * @default -1\n * @private\n */\n this.position4 = -1;\n /**\n * The `index` of the object within the object collection.\n * @default -1\n * @private\n */\n this.objectIndex = -1;\n /**\n * @hidden\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n // if (typeof obj2 === 'undefined') {\n if (obj1 instanceof PdfArray\n || obj1 instanceof PdfDictionary\n || obj1 instanceof PdfName\n || obj1 instanceof PdfNumber\n || obj1 instanceof PdfStream\n || obj1 instanceof PdfReference\n || obj1 instanceof PdfString) {\n // if (obj1 === null) {\n // throw new Error('ArgumentNullException : obj');\n // }\n this.primitiveObject = obj1;\n // } else if (obj1 instanceof PdfPageBase\n // || obj1 instanceof PdfPage\n // || obj1 instanceof PdfSection\n // || obj1 instanceof PdfSectionCollection) {\n }\n else {\n var tempObj = obj1;\n this.constructor(tempObj.element);\n }\n // }\n // else {\n // if (obj2 === null) {\n // throw new Error('ArgumentNullException : crossTable');\n // }\n // if (obj1 === null) {\n // throw new Error('ArgumentNullException : reference');\n // }\n // this.crossTable = obj2;\n // let tempObj1 : PdfReference = obj1;\n // this.reference = tempObj1;\n // }\n }\n Object.defineProperty(PdfReferenceHolder.prototype, \"status\", {\n //Properties\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.status4;\n },\n set: function (value) {\n this.status4 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.isSaving4;\n },\n set: function (value) {\n this.isSaving4 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index4;\n },\n set: function (value) {\n this.index4 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.position4;\n },\n set: function (value) {\n this.position4 = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n return null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"object\", {\n /**\n * Gets the `object` the reference is of.\n * @private\n */\n get: function () {\n // if ((this.reference != null) || (this.object == null)) {\n // this.object = this.GetterObject();\n // }\n return this.primitiveObject;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"reference\", {\n /**\n * Gets the `reference`.\n * @private\n */\n get: function () {\n return this.pdfReference;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"index\", {\n /**\n * Gets the `index` of the object.\n * @private\n */\n get: function () {\n // let items : PdfMainObjectCollection = this.crossTable.PdfObjects;\n // this.objectIndex = items.GetObjectIndex(this.reference);\n // if (this.objectIndex < 0) {\n // let obj : IPdfPrimitive = this.crossTable.GetObject(this.reference);\n // this.objectIndex = items.Count - 1;\n // }\n return this.objectIndex;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfReferenceHolder.prototype, \"element\", {\n /**\n * Gets the `element`.\n * @private\n */\n get: function () {\n return this.primitiveObject;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Writes` a reference into a PDF document.\n * @private\n */\n PdfReferenceHolder.prototype.save = function (writer) {\n // if (writer == null) {\n // throw new Error('ArgumentNullException : writer');\n // }\n var position = writer.position;\n var cTable = writer.document.crossTable;\n // if (cTable.Document instanceof PdfDocument) {\n this.object.isSaving = true;\n // }\n var reference = null;\n // if (writer.Document.FileStructure.IncrementalUpdate === true && writer.Document.isStreamCopied === true) {\n // if (this.reference === null) {\n // reference = cTable.GetReference(this.Object);\n // } else {\n // reference = this.reference;\n // }\n // } else {\n // reference = cTable.GetReference(this.Object);\n // }\n // if (!(writer.Document.FileStructure.IncrementalUpdate === true && writer.Document.isStreamCopied === true)) {\n reference = cTable.getReference(this.object);\n // }\n // if (writer.Position !== position) {\n // writer.Position = position;\n // }\n reference.save(writer);\n };\n /**\n * Creates a `copy of PdfReferenceHolder`.\n * @private\n */\n PdfReferenceHolder.prototype.clone = function (crossTable) {\n var refHolder = null;\n var temp = null;\n var refNum = '';\n var reference = null;\n // Restricts addition of same object multiple time.\n /* if (this.Reference != null && this.crossTable != null && this.crossTable.PageCorrespondance.containsKey(this.Reference)) {\n refHolder = new PdfReferenceHolder(this.crossTable.PageCorrespondance.getValue(this.Reference) as PdfReference, crossTable);\n return refHolder;\n }\n if (Object instanceof PdfNumber) {\n return new PdfNumber((Object as PdfNumber).IntValue);\n }\n */\n // if (Object instanceof PdfDictionary) {\n // // Meaning the referenced page is not available for import.\n // let type : PdfName = new PdfName(this.dictionaryProperties.type);\n // let dict : PdfDictionary = Object as PdfDictionary;\n // if (dict.ContainsKey(type)) {\n // let pageName : PdfName = dict.Items.getValue(type.Value) as PdfName;\n // if (pageName !== null) {\n // if (pageName.Value === 'Page') {\n // return new PdfNull();\n // }\n // }\n // }\n // }\n /* if (Object instanceof PdfName) {\n return new PdfName ((Object as PdfName ).Value);\n }\n */\n // Resolves circular references.\n // if (crossTable.PrevReference !== null && (crossTable.PrevReference.indexOf(this.Reference) !== -1)) {\n // let obj : IPdfPrimitive = this.crossTable.GetObject(this.Reference).ClonedObject;\n // if (obj !== null) {\n // reference = crossTable.GetReference(obj);\n // return new PdfReferenceHolder(reference, crossTable);\n // } else {\n // return new PdfNull();\n // }\n // }\n /*if (this.Reference !== null) {\n crossTable.PrevReference.push(this.Reference);\n }\n reference = crossTable.GetReference(temp);\n refHolder = new PdfReferenceHolder(reference, crossTable);\n return refHolder;\n */\n return null;\n };\n return PdfReferenceHolder;\n}());\nexport { PdfReferenceHolder };\n","import { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { PdfName } from './../primitives/pdf-name';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\n/**\n * `PdfAction` class represents base class for all action types.\n * @private\n */\nvar PdfAction = /** @class */ (function () {\n // Constructors\n /**\n * Initialize instance for `Action` class.\n * @private\n */\n function PdfAction() {\n /**\n * Specifies the Next `action` to perform.\n * @private\n */\n this.action = null;\n /**\n * Specifies the Internal variable to store `dictionary properties`.\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n // super(); -> Object()\n this.initialize();\n }\n Object.defineProperty(PdfAction.prototype, \"next\", {\n // Properties\n /**\n * Gets and Sets the `Next` action to perform.\n * @private\n */\n get: function () {\n return this.action;\n },\n set: function (value) {\n // if (this.action !== value) {\n this.action = value;\n this.dictionary.items.setValue(this.dictionaryProperties.next, new PdfReferenceHolder(this.action));\n // }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAction.prototype, \"dictionary\", {\n /**\n * Gets and Sets the instance of PdfDictionary class for `Dictionary`.\n * @private\n */\n get: function () {\n if (typeof this.pdfDictionary === 'undefined') {\n this.pdfDictionary = new PdfDictionary();\n }\n return this.pdfDictionary;\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Initialize` the action type.\n * @private\n */\n PdfAction.prototype.initialize = function () {\n this.dictionary.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.action));\n };\n Object.defineProperty(PdfAction.prototype, \"element\", {\n // IPdfWrapper Members\n /**\n * Gets the `Element` as IPdfPrimitive class.\n * @private\n */\n get: function () {\n return this.dictionary;\n },\n enumerable: true,\n configurable: true\n });\n return PdfAction;\n}());\nexport { PdfAction };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfAction } from './action';\nimport { PdfString } from './../primitives/pdf-string';\nimport { PdfName } from './../primitives/pdf-name';\n/**\n * `PdfUriAction` class for initialize the uri related internals.\n * @private\n */\nvar PdfUriAction = /** @class */ (function (_super) {\n __extends(PdfUriAction, _super);\n function PdfUriAction(uri) {\n var _this = _super.call(this) || this;\n // Fields\n /**\n * Specifies the `uri` string.\n * @default ''.\n * @private\n */\n _this.uniformResourceIdentifier = '';\n return _this;\n }\n Object.defineProperty(PdfUriAction.prototype, \"uri\", {\n // Properties\n /**\n * Gets and Sets the value of `Uri`.\n * @private\n */\n get: function () {\n return this.uniformResourceIdentifier;\n },\n set: function (value) {\n this.uniformResourceIdentifier = value;\n this.dictionary.items.setValue(this.dictionaryProperties.uri, new PdfString(this.uniformResourceIdentifier));\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Initialize` the internals.\n * @private\n */\n PdfUriAction.prototype.initialize = function () {\n _super.prototype.initialize.call(this);\n this.dictionary.items.setValue(this.dictionaryProperties.s, new PdfName(this.dictionaryProperties.uri));\n };\n return PdfUriAction;\n}(PdfAction));\nexport { PdfUriAction };\n","import { PdfColorSpace } from './enum';\nimport { Operators } from './../input-output/pdf-operators';\nimport { Dictionary } from './../collections/dictionary';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { PdfArray } from './../primitives/pdf-array';\n/**\n * Implements structures and routines working with `color`.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * // set the font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * //\n * // set color\n * let brushColor : PdfColor = new PdfColor(0, 0, 0);\n * //\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(brushColor);\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n * @default black color\n */\nvar PdfColor = /** @class */ (function () {\n function PdfColor(color1, color2, color3, color4) {\n if (color1 instanceof PdfColor) {\n this.redColor = color1.r;\n this.greenColor = color1.g;\n this.blueColor = color1.b;\n this.grayColor = color1.gray;\n this.alpha = color1.alpha;\n this.filled = (this.alpha !== 0);\n }\n else if (typeof color1 === 'number' && typeof color2 === 'number' && typeof color3 === 'number' &&\n typeof color4 === 'undefined') {\n this.constructor(PdfColor.maxColourChannelValue, color1, color2, color3); //doubt-byte/float\n }\n else if (typeof color1 === 'number' && typeof color2 === 'number' && typeof color3 === 'number' && typeof color4 === 'number') {\n this.redColor = color2;\n this.cyanColor = 0;\n this.greenColor = color3;\n this.magentaColor = 0;\n this.blueColor = color4;\n this.yellowColor = 0;\n this.blackColor = 0;\n this.grayColor = 0;\n this.alpha = color1;\n this.filled = true;\n this.assignCMYK(color2, color3, color4);\n }\n }\n /**\n * `Calculate and assign` cyan, megenta, yellow colors from rgb values..\n * @private\n */\n PdfColor.prototype.assignCMYK = function (r, g, b) {\n var red = r / PdfColor.maxColourChannelValue;\n var green = g / PdfColor.maxColourChannelValue;\n var blue = b / PdfColor.maxColourChannelValue;\n var black = PdfNumber.min(1 - red, 1 - green, 1 - blue);\n var cyan = (black === 1.0) ? 0 : (1 - red - black) / (1 - black);\n var magenta = (black === 1.0) ? 0 : (1 - green - black) / (1 - black);\n var yellow = (black === 1.0) ? 0 : (1 - blue - black) / (1 - black);\n this.blackColor = black;\n this.cyanColor = cyan;\n this.magentaColor = magenta;\n this.yellowColor = yellow;\n };\n Object.defineProperty(PdfColor.prototype, \"r\", {\n //Properties\n // public static get Empty():PdfColor\n // {\n // return this.s_emptyColor\n // }\n /**\n * Gets or sets `Red` channel value.\n * @private\n */\n get: function () {\n return this.redColor;\n },\n set: function (value) {\n this.redColor = value;\n this.assignCMYK(this.redColor, this.greenColor, this.blueColor);\n this.filled = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"red\", {\n /**\n * Gets the `Red` color\n * @private\n */\n get: function () {\n return (this.r / PdfColor.maxColourChannelValue);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"b\", {\n /**\n * Gets or sets `Blue` channel value.\n * @private\n */\n get: function () {\n return this.blueColor;\n },\n set: function (value) {\n this.blueColor = value;\n this.assignCMYK(this.redColor, this.greenColor, this.blueColor);\n this.filled = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"blue\", {\n /**\n * Gets the `blue` color.\n * @private\n */\n get: function () {\n return (this.b / PdfColor.maxColourChannelValue);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"g\", {\n /**\n * Gets or sets `Green` channel value.\n * @private\n */\n get: function () {\n return this.greenColor;\n },\n set: function (value) {\n this.greenColor = value;\n this.assignCMYK(this.redColor, this.greenColor, this.blueColor);\n this.filled = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"green\", {\n /**\n * Gets the `Green` color.\n * @private\n */\n get: function () {\n return (this.g / PdfColor.maxColourChannelValue);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"gray\", {\n /**\n * Gets or sets `Gray` channel value.\n * @private\n */\n get: function () {\n return ((((this.redColor + this.greenColor) + this.blueColor)) / (PdfColor.maxColourChannelValue * 3));\n },\n set: function (value) {\n if (value < 0) {\n this.grayColor = 0;\n }\n else if (value > 1) {\n this.grayColor = 1;\n }\n else {\n this.grayColor = value;\n }\n this.r = (this.grayColor * PdfColor.maxColourChannelValue);\n this.g = (this.grayColor * PdfColor.maxColourChannelValue);\n this.b = (this.grayColor * PdfColor.maxColourChannelValue);\n this.assignCMYK(this.redColor, this.greenColor, this.blueColor);\n this.filled = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"isEmpty\", {\n /**\n * Gets whether the PDFColor `is Empty` or not.\n * @private\n */\n get: function () {\n return !this.filled;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfColor.prototype, \"a\", {\n /**\n * Gets or sets `Alpha` channel value.\n * @private\n */\n get: function () {\n return this.alpha;\n },\n set: function (value) {\n if (value < 0) {\n this.alpha = 0;\n }\n else {\n // if (this.alpha !== value) {\n this.alpha = value;\n // }\n }\n this.filled = true;\n },\n enumerable: true,\n configurable: true\n });\n //Public methods\n /**\n * Converts `PDFColor to PDF string` representation.\n * @private\n */\n PdfColor.prototype.toString = function (colorSpace, stroke) {\n if (this.isEmpty) {\n return '';\n }\n return this.rgbToString(stroke);\n };\n /**\n * Sets `RGB` color.\n * @private\n */\n PdfColor.prototype.rgbToString = function (ifStroking) {\n var r = this.r;\n var g = this.g;\n var b = this.b;\n var key = (r << 16) + (g << 8) + b;\n if (ifStroking) {\n key += 1 << 24;\n }\n var colour = '';\n var obj = null;\n if (PdfColor.rgbStrings.containsKey(key)) {\n obj = PdfColor.rgbStrings.getValue(key);\n }\n if (obj == null) {\n var red = r / PdfColor.maxColourChannelValue;\n var green = g / PdfColor.maxColourChannelValue;\n var blue = b / PdfColor.maxColourChannelValue;\n if (ifStroking) {\n colour = red.toString() + ' ' + green.toString() + ' ' + blue.toString() + ' RG';\n }\n else {\n colour = red.toString() + ' ' + green.toString() + ' ' + blue.toString() + ' rg';\n }\n PdfColor.rgbStrings.setValue(key, colour);\n }\n else {\n colour = obj.toString();\n }\n return colour + Operators.newLine;\n };\n /**\n * Converts `colour to a PDF array`.\n * @private\n */\n PdfColor.prototype.toArray = function (colorSpace) {\n var array = new PdfArray();\n switch (colorSpace) {\n case PdfColorSpace.Rgb:\n array.add(new PdfNumber(this.red));\n array.add(new PdfNumber(this.green));\n array.add(new PdfNumber(this.blue));\n break;\n default:\n throw new Error('NotSupportedException : Unsupported colour space.');\n }\n return array;\n };\n //Fields\n /**\n * Holds `RGB colors` converted into strings.\n * @private\n */\n PdfColor.rgbStrings = new Dictionary();\n /**\n * Holds Gray scale colors converted into strings for `stroking`.\n * @private\n */\n PdfColor.grayStringsSroke = new Dictionary();\n /**\n * Holds Gray scale colors converted into strings for `filling`.\n * @private\n */\n PdfColor.grayStringsFill = new Dictionary();\n /**\n * `Max value` of color channel.\n * @private\n */\n PdfColor.maxColourChannelValue = 255.0;\n return PdfColor;\n}());\nexport { PdfColor };\n","/**\n * public Enum for `PdfFontStyle`.\n * @private\n */\nexport var PdfFontStyle;\n(function (PdfFontStyle) {\n /**\n * Specifies the type of `Regular`.\n * @private\n */\n PdfFontStyle[PdfFontStyle[\"Regular\"] = 0] = \"Regular\";\n /**\n * Specifies the type of `Bold`.\n * @private\n */\n PdfFontStyle[PdfFontStyle[\"Bold\"] = 1] = \"Bold\";\n /**\n * Specifies the type of `Italic`.\n * @private\n */\n PdfFontStyle[PdfFontStyle[\"Italic\"] = 2] = \"Italic\";\n /**\n * Specifies the type of `Underline`.\n * @private\n */\n PdfFontStyle[PdfFontStyle[\"Underline\"] = 4] = \"Underline\";\n /**\n * Specifies the type of `Strikeout`.\n * @private\n */\n PdfFontStyle[PdfFontStyle[\"Strikeout\"] = 8] = \"Strikeout\";\n})(PdfFontStyle || (PdfFontStyle = {}));\n/**\n * Specifies the font family from the standard font.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * // create new standard font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * // save the document\n * document.save('output.pdf');\n * ```\n */\nexport var PdfFontFamily;\n(function (PdfFontFamily) {\n /**\n * Specifies the `Helvetica` font.\n */\n PdfFontFamily[PdfFontFamily[\"Helvetica\"] = 0] = \"Helvetica\";\n /**\n * Specifies the `Courier` font.\n */\n PdfFontFamily[PdfFontFamily[\"Courier\"] = 1] = \"Courier\";\n /**\n * Specifies the `TimesRoman` font.\n */\n PdfFontFamily[PdfFontFamily[\"TimesRoman\"] = 2] = \"TimesRoman\";\n /**\n * Specifies the `Symbol` font.\n */\n PdfFontFamily[PdfFontFamily[\"Symbol\"] = 3] = \"Symbol\";\n /**\n * Specifies the `ZapfDingbats` font.\n */\n PdfFontFamily[PdfFontFamily[\"ZapfDingbats\"] = 4] = \"ZapfDingbats\";\n})(PdfFontFamily || (PdfFontFamily = {}));\n/**\n * public Enum for `PdfFontType`.\n * @private\n */\nexport var PdfFontType;\n(function (PdfFontType) {\n /**\n * Specifies the type of `Standard`.\n * @private\n */\n PdfFontType[PdfFontType[\"Standard\"] = 0] = \"Standard\";\n /**\n * Specifies the type of `TrueType`.\n * @private\n */\n PdfFontType[PdfFontType[\"TrueType\"] = 1] = \"TrueType\";\n /**\n * Specifies the type of `TrueTypeEmbedded`.\n * @private\n */\n PdfFontType[PdfFontType[\"TrueTypeEmbedded\"] = 2] = \"TrueTypeEmbedded\";\n})(PdfFontType || (PdfFontType = {}));\n/**\n * public Enum for `PdfWordWrapType`.\n * @private\n */\nexport var PdfWordWrapType;\n(function (PdfWordWrapType) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n PdfWordWrapType[PdfWordWrapType[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `Word`.\n * @private\n */\n PdfWordWrapType[PdfWordWrapType[\"Word\"] = 1] = \"Word\";\n /**\n * Specifies the type of `WordOnly`.\n * @private\n */\n PdfWordWrapType[PdfWordWrapType[\"WordOnly\"] = 2] = \"WordOnly\";\n /**\n * Specifies the type of `Character`.\n * @private\n */\n PdfWordWrapType[PdfWordWrapType[\"Character\"] = 3] = \"Character\";\n})(PdfWordWrapType || (PdfWordWrapType = {}));\n/**\n * public Enum for `PdfSubSuperScript`.\n * @private\n */\nexport var PdfSubSuperScript;\n(function (PdfSubSuperScript) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n PdfSubSuperScript[PdfSubSuperScript[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `SuperScript`.\n * @private\n */\n PdfSubSuperScript[PdfSubSuperScript[\"SuperScript\"] = 1] = \"SuperScript\";\n /**\n * Specifies the type of `SubScript`.\n * @private\n */\n PdfSubSuperScript[PdfSubSuperScript[\"SubScript\"] = 2] = \"SubScript\";\n})(PdfSubSuperScript || (PdfSubSuperScript = {}));\n/**\n * public Enum for `FontEncoding`.\n * @private\n */\nexport var FontEncoding;\n(function (FontEncoding) {\n /**\n * Specifies the type of `Unknown`.\n * @private\n */\n FontEncoding[FontEncoding[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * Specifies the type of `StandardEncoding`.\n * @private\n */\n FontEncoding[FontEncoding[\"StandardEncoding\"] = 1] = \"StandardEncoding\";\n /**\n * Specifies the type of `MacRomanEncoding`.\n * @private\n */\n FontEncoding[FontEncoding[\"MacRomanEncoding\"] = 2] = \"MacRomanEncoding\";\n /**\n * Specifies the type of `MacExpertEncoding`.\n * @private\n */\n FontEncoding[FontEncoding[\"MacExpertEncoding\"] = 3] = \"MacExpertEncoding\";\n /**\n * Specifies the type of `WinAnsiEncoding`.\n * @private\n */\n FontEncoding[FontEncoding[\"WinAnsiEncoding\"] = 4] = \"WinAnsiEncoding\";\n /**\n * Specifies the type of `PdfDocEncoding`.\n * @private\n */\n FontEncoding[FontEncoding[\"PdfDocEncoding\"] = 5] = \"PdfDocEncoding\";\n /**\n * Specifies the type of `IdentityH`.\n * @private\n */\n FontEncoding[FontEncoding[\"IdentityH\"] = 6] = \"IdentityH\";\n})(FontEncoding || (FontEncoding = {}));\n/**\n * public Enum for `TtfCmapFormat`.\n * @private\n */\nexport var TtfCmapFormat;\n(function (TtfCmapFormat) {\n /**\n * This is the Apple standard character to glyph index mapping table.\n * @private\n */\n TtfCmapFormat[TtfCmapFormat[\"Apple\"] = 0] = \"Apple\";\n /**\n * This is the Microsoft standard character to glyph index mapping table.\n * @private\n */\n TtfCmapFormat[TtfCmapFormat[\"Microsoft\"] = 4] = \"Microsoft\";\n /**\n * Format 6: Trimmed table mapping.\n * @private\n */\n TtfCmapFormat[TtfCmapFormat[\"Trimmed\"] = 6] = \"Trimmed\";\n})(TtfCmapFormat || (TtfCmapFormat = {}));\n/**\n * Enumerator that implements CMAP encodings.\n * @private\n */\nexport var TtfCmapEncoding;\n(function (TtfCmapEncoding) {\n /**\n * Unknown encoding.\n * @private\n */\n TtfCmapEncoding[TtfCmapEncoding[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * When building a symbol font for Windows.\n * @private\n */\n TtfCmapEncoding[TtfCmapEncoding[\"Symbol\"] = 1] = \"Symbol\";\n /**\n * When building a Unicode font for Windows.\n * @private\n */\n TtfCmapEncoding[TtfCmapEncoding[\"Unicode\"] = 2] = \"Unicode\";\n /**\n * For font that will be used on a Macintosh.\n * @private\n */\n TtfCmapEncoding[TtfCmapEncoding[\"Macintosh\"] = 3] = \"Macintosh\";\n})(TtfCmapEncoding || (TtfCmapEncoding = {}));\n/**\n * Ttf platform ID.\n * @private\n */\nexport var TtfPlatformID;\n(function (TtfPlatformID) {\n /**\n * Apple platform.\n * @private\n */\n TtfPlatformID[TtfPlatformID[\"AppleUnicode\"] = 0] = \"AppleUnicode\";\n /**\n * Macintosh platform.\n * @private\n */\n TtfPlatformID[TtfPlatformID[\"Macintosh\"] = 1] = \"Macintosh\";\n /**\n * Iso platform.\n * @private\n */\n TtfPlatformID[TtfPlatformID[\"Iso\"] = 2] = \"Iso\";\n /**\n * Microsoft platform.\n * @private\n */\n TtfPlatformID[TtfPlatformID[\"Microsoft\"] = 3] = \"Microsoft\";\n})(TtfPlatformID || (TtfPlatformID = {}));\n/**\n * Microsoft encoding ID.\n * @private\n */\nexport var TtfMicrosoftEncodingID;\n(function (TtfMicrosoftEncodingID) {\n /**\n * Undefined encoding.\n * @private\n */\n TtfMicrosoftEncodingID[TtfMicrosoftEncodingID[\"Undefined\"] = 0] = \"Undefined\";\n /**\n * Unicode encoding.\n * @private\n */\n TtfMicrosoftEncodingID[TtfMicrosoftEncodingID[\"Unicode\"] = 1] = \"Unicode\";\n})(TtfMicrosoftEncodingID || (TtfMicrosoftEncodingID = {}));\n/**\n * Macintosh encoding ID.\n * @private\n */\nexport var TtfMacintoshEncodingID;\n(function (TtfMacintoshEncodingID) {\n /**\n * Roman encoding.\n * @private\n */\n TtfMacintoshEncodingID[TtfMacintoshEncodingID[\"Roman\"] = 0] = \"Roman\";\n /**\n * Japanese encoding.\n * @private\n */\n TtfMacintoshEncodingID[TtfMacintoshEncodingID[\"Japanese\"] = 1] = \"Japanese\";\n /**\n * Chinese encoding.\n * @private\n */\n TtfMacintoshEncodingID[TtfMacintoshEncodingID[\"Chinese\"] = 2] = \"Chinese\";\n})(TtfMacintoshEncodingID || (TtfMacintoshEncodingID = {}));\n/**\n * Enumerator that implements font descriptor flags.\n * @private\n */\nexport var FontDescriptorFlags;\n(function (FontDescriptorFlags) {\n /**\n * All glyphs have the same width (as opposed to proportional or variable-pitch fonts, which have different widths).\n * @private\n */\n FontDescriptorFlags[FontDescriptorFlags[\"FixedPitch\"] = 1] = \"FixedPitch\";\n /**\n * Glyphs have serifs, which are short strokes drawn at an angle on the top and\n * bottom of glyph stems (as opposed to sans serif fonts, which do not).\n * @private\n */\n FontDescriptorFlags[FontDescriptorFlags[\"Serif\"] = 2] = \"Serif\";\n /**\n * Font contains glyphs outside the Adobe standard Latin character set. The\n * flag and the nonsymbolic flag cannot both be set or both be clear.\n * @private\n */\n FontDescriptorFlags[FontDescriptorFlags[\"Symbolic\"] = 4] = \"Symbolic\";\n /**\n * Glyphs resemble cursive handwriting.\n * @private\n */\n FontDescriptorFlags[FontDescriptorFlags[\"Script\"] = 8] = \"Script\";\n /**\n * Font uses the Adobe standard Latin character set or a subset of it.\n * @private\n */\n FontDescriptorFlags[FontDescriptorFlags[\"Nonsymbolic\"] = 32] = \"Nonsymbolic\";\n /**\n * Glyphs have dominant vertical strokes that are slanted.\n * @private\n */\n FontDescriptorFlags[FontDescriptorFlags[\"Italic\"] = 64] = \"Italic\";\n /**\n * Bold font.\n * @private\n */\n FontDescriptorFlags[FontDescriptorFlags[\"ForceBold\"] = 262144] = \"ForceBold\";\n})(FontDescriptorFlags || (FontDescriptorFlags = {}));\n/**\n * true type font composite glyph flags.\n * @private\n */\nexport var TtfCompositeGlyphFlags;\n(function (TtfCompositeGlyphFlags) {\n /**\n * The Arg1And2AreWords.\n * @private\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"Arg1And2AreWords\"] = 1] = \"Arg1And2AreWords\";\n /**\n * The ArgsAreXyValues.\n * @private\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"ArgsAreXyValues\"] = 2] = \"ArgsAreXyValues\";\n /**\n * The RoundXyToGrid.\n * @private\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"RoundXyToGrid\"] = 4] = \"RoundXyToGrid\";\n /**\n * The WeHaveScale.\n * @private\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"WeHaveScale\"] = 8] = \"WeHaveScale\";\n /**\n * The Reserved.\n * @private\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"Reserved\"] = 16] = \"Reserved\";\n /**\n * The MoreComponents.\n * @private\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"MoreComponents\"] = 32] = \"MoreComponents\";\n /**\n * The WeHaveAnXyScale.\n * @private\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"WeHaveAnXyScale\"] = 64] = \"WeHaveAnXyScale\";\n /**\n * The WeHaveTwoByTwo\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"WeHaveTwoByTwo\"] = 128] = \"WeHaveTwoByTwo\";\n /**\n * The WeHaveInstructions.\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"WeHaveInstructions\"] = 256] = \"WeHaveInstructions\";\n /**\n * The UseMyMetrics.\n */\n TtfCompositeGlyphFlags[TtfCompositeGlyphFlags[\"UseMyMetrics\"] = 512] = \"UseMyMetrics\";\n})(TtfCompositeGlyphFlags || (TtfCompositeGlyphFlags = {}));\n","/**\n * Coordinates of Position for `PointF`.\n * @private\n */\nvar PointF = /** @class */ (function () {\n function PointF(x, y) {\n if (typeof x === 'undefined') {\n this.x = 0;\n this.y = 0;\n }\n else {\n if (x !== null) {\n this.x = x;\n }\n else {\n this.x = 0;\n }\n if (y !== null) {\n this.y = y;\n }\n else {\n this.y = 0;\n }\n }\n }\n return PointF;\n}());\nexport { PointF };\n/**\n * Width and Height as `Size`.\n * @private\n */\nvar SizeF = /** @class */ (function () {\n function SizeF(width, height) {\n if (typeof height === 'undefined') {\n this.height = 0;\n this.width = 0;\n }\n else {\n if (height !== null) {\n this.height = height;\n }\n else {\n this.height = 0;\n }\n if (width !== null) {\n this.width = width;\n }\n else {\n this.width = 0;\n }\n }\n }\n return SizeF;\n}());\nexport { SizeF };\n/**\n * `RectangleF` with Position and size.\n * @private\n */\nvar RectangleF = /** @class */ (function () {\n function RectangleF(arg1, arg2, arg3, arg4) {\n if (typeof arg1 === typeof arg1 && typeof arg1 === 'undefined') {\n this.x = 0;\n this.y = 0;\n this.height = 0;\n this.width = 0;\n }\n else {\n if (arg1 instanceof PointF && arg2 instanceof SizeF && typeof arg3 === 'undefined') {\n var pointf = arg1;\n this.x = pointf.x;\n this.y = pointf.y;\n var sizef = arg2;\n this.height = sizef.height;\n this.width = sizef.width;\n }\n else {\n var x = arg1;\n var y = arg2;\n var width = arg3;\n var height = arg4;\n this.x = x;\n this.y = y;\n this.height = height;\n this.width = width;\n }\n }\n }\n return RectangleF;\n}());\nexport { RectangleF };\n/**\n * `Rectangle` with left, right, top and bottom.\n * @private\n */\nvar Rectangle = /** @class */ (function () {\n /**\n * Instance of `RectangleF` class with X, Y, Width and Height.\n * @private\n */\n function Rectangle(left, top, right, bottom) {\n this.left = left;\n this.top = top;\n this.right = right;\n this.bottom = bottom;\n }\n Object.defineProperty(Rectangle.prototype, \"width\", {\n /**\n * Gets a value of width\n */\n get: function () {\n return this.right - this.left;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rectangle.prototype, \"height\", {\n /**\n * Gets a value of height\n */\n get: function () {\n return this.bottom - this.top;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rectangle.prototype, \"topLeft\", {\n /**\n * Gets a value of Top and Left\n */\n get: function () {\n return new PointF(this.left, this.top);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rectangle.prototype, \"size\", {\n /**\n * Gets a value of size\n */\n get: function () {\n return new SizeF(this.width, this.height);\n },\n enumerable: true,\n configurable: true\n });\n Rectangle.prototype.toString = function () {\n return this.topLeft + 'x' + this.size;\n };\n return Rectangle;\n}());\nexport { Rectangle };\n","/**\n * `PdfBrush` class provides objects used to fill the interiors of graphical shapes such as rectangles,\n * ellipses, pies, polygons, and paths.\n * @private\n */\nvar PdfBrush = /** @class */ (function () {\n /**\n * Creates instanceof `PdfBrush` class.\n * @hidden\n * @private\n */\n function PdfBrush() {\n //\n }\n return PdfBrush;\n}());\nexport { PdfBrush };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfColor } from './../pdf-color';\nimport { PdfColorSpace } from './../enum';\nimport { PdfBrush } from './pdf-brush';\n/**\n * Represents a brush that fills any object with a solid color.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfSolidBrush = /** @class */ (function (_super) {\n __extends(PdfSolidBrush, _super);\n //Constructors\n /**\n * Initializes a new instance of the `PdfSolidBrush` class.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n * @param color color of the brush\n */\n function PdfSolidBrush(color) {\n var _this = _super.call(this) || this;\n _this.pdfColor = color;\n return _this;\n }\n Object.defineProperty(PdfSolidBrush.prototype, \"color\", {\n //Properties\n /**\n * Gets or sets the `color` of the brush.\n * @private\n */\n get: function () {\n return this.pdfColor;\n },\n set: function (value) {\n this.pdfColor = value;\n },\n enumerable: true,\n configurable: true\n });\n //Implementation\n /**\n * `Monitors` the changes of the brush and modify PDF state respectively.\n * @private\n */\n PdfSolidBrush.prototype.monitorChanges = function (brush, streamWriter, getResources, saveChanges, currentColorSpace) {\n if (streamWriter == null) {\n throw new Error('ArgumentNullException:streamWriter');\n }\n var diff = false;\n if (brush == null) {\n diff = true;\n streamWriter.setColorAndSpace(this.pdfColor, currentColorSpace, false);\n return diff;\n }\n else {\n var sBrush = brush;\n diff = true;\n streamWriter.setColorAndSpace(this.pdfColor, currentColorSpace, false);\n return diff;\n }\n };\n /**\n * `Resets` the changes, which were made by the brush.\n * @private\n */\n PdfSolidBrush.prototype.resetChanges = function (streamWriter) {\n streamWriter.setColorAndSpace(new PdfColor(0, 0, 0), PdfColorSpace.Rgb, false);\n };\n return PdfSolidBrush;\n}(PdfBrush));\nexport { PdfSolidBrush };\n","/**\n * PdfStringFormat.ts class for EJ2-PDF\n */\nimport { PdfVerticalAlignment } from './../../graphics/enum';\nimport { PdfSubSuperScript, PdfWordWrapType } from './../../graphics/fonts/enum';\n/**\n * `PdfStringFormat` class represents the text layout information on PDF.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * //\n * // set the format for string\n * let stringFormat : PdfStringFormat = new PdfStringFormat();\n * // set the text alignment\n * stringFormat.alignment = PdfTextAlignment.Center;\n * // set the vertical alignment\n * stringFormat.lineAlignment = PdfVerticalAlignment.Middle;\n * //\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat);\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfStringFormat = /** @class */ (function () {\n function PdfStringFormat(arg1, arg2) {\n /**\n * The `scaling factor` of the text being drawn.\n * @private\n */\n this.scalingFactor = 100.0;\n if (typeof arg1 === 'undefined') {\n this.internalLineLimit = true;\n this.wordWrapType = PdfWordWrapType.Word;\n }\n else if (typeof arg1 === 'string') {\n this.constructor();\n }\n else {\n if (typeof arg2 === 'undefined') {\n this.constructor();\n this.textAlignment = arg1;\n }\n else {\n this.constructor(arg1);\n this.verticalAlignment = arg2;\n }\n }\n }\n Object.defineProperty(PdfStringFormat.prototype, \"alignment\", {\n //Properties\n /**\n * Gets or sets the `horizontal` text alignment\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * //\n * // set the format for string\n * let stringFormat : PdfStringFormat = new PdfStringFormat();\n * // set the text alignment\n * stringFormat.alignment = PdfTextAlignment.Center;\n * //\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat);\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n return this.textAlignment;\n },\n set: function (value) {\n this.textAlignment = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"lineAlignment\", {\n /**\n * Gets or sets the `vertical` text alignment.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * //\n * // set the format for string\n * let stringFormat : PdfStringFormat = new PdfStringFormat();\n * // set the vertical alignment\n * stringFormat.lineAlignment = PdfVerticalAlignment.Middle;\n * //\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat);\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n if (typeof this.verticalAlignment === 'undefined' || this.verticalAlignment == null) {\n return PdfVerticalAlignment.Top;\n }\n else {\n return this.verticalAlignment;\n }\n },\n set: function (value) {\n this.verticalAlignment = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"rightToLeft\", {\n /**\n * Gets or sets the value that indicates text `direction` mode.\n * @private\n */\n get: function () {\n if (typeof this.isRightToLeft === 'undefined' || this.isRightToLeft == null) {\n return false;\n }\n else {\n return this.isRightToLeft;\n }\n },\n set: function (value) {\n this.isRightToLeft = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"characterSpacing\", {\n /**\n * Gets or sets value that indicates a `size` among the characters in the text.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * //\n * // set the format for string\n * let stringFormat : PdfStringFormat = new PdfStringFormat();\n * // set character spacing\n * stringFormat.characterSpacing = 10;\n * //\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat);\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n if (typeof this.internalCharacterSpacing === 'undefined' || this.internalCharacterSpacing == null) {\n return 0;\n }\n else {\n return this.internalCharacterSpacing;\n }\n },\n set: function (value) {\n this.internalCharacterSpacing = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"wordSpacing\", {\n /**\n * Gets or sets value that indicates a `size` among the words in the text.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * //\n * // set the format for string\n * let stringFormat : PdfStringFormat = new PdfStringFormat();\n * // set word spacing\n * stringFormat.wordSpacing = 10;\n * //\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat);\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n if (typeof this.internalWordSpacing === 'undefined' || this.internalWordSpacing == null) {\n return 0;\n }\n else {\n return this.internalWordSpacing;\n }\n },\n set: function (value) {\n this.internalWordSpacing = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"lineSpacing\", {\n /**\n * Gets or sets value that indicates the `vertical distance` between the baselines of adjacent lines of text.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // set string\n * let text : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\n * incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitati';\n * // set rectangle bounds\n * let rectangle : RectangleF = new RectangleF({x : 0, y : 0}, {width : 300, height : 100})\n * //\n * // set the format for string\n * let stringFormat : PdfStringFormat = new PdfStringFormat();\n * // set line spacing\n * stringFormat.lineSpacing = 10;\n * //\n * // draw the text\n * page1.graphics.drawString(text, font, blackBrush, rectangle, stringFormat);\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n if (typeof this.leading === 'undefined' || this.leading == null) {\n return 0;\n }\n else {\n return this.leading;\n }\n },\n set: function (value) {\n this.leading = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"clipPath\", {\n /**\n * Gets or sets a value indicating whether the text is `clipped` or not.\n * @private\n */\n get: function () {\n if (typeof this.clip === 'undefined' || this.clip == null) {\n return false;\n }\n else {\n return this.clip;\n }\n },\n set: function (value) {\n this.clip = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"subSuperScript\", {\n /**\n * Gets or sets value indicating whether the text is in `subscript or superscript` mode.\n * @private\n */\n get: function () {\n if (typeof this.pdfSubSuperScript === 'undefined' || this.pdfSubSuperScript == null) {\n return PdfSubSuperScript.None;\n }\n else {\n return this.pdfSubSuperScript;\n }\n },\n set: function (value) {\n this.pdfSubSuperScript = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"paragraphIndent\", {\n /**\n * Gets or sets the `indent` of the first line in the paragraph.\n * @private\n */\n get: function () {\n if (typeof this.internalParagraphIndent === 'undefined' || this.internalParagraphIndent == null) {\n return 0;\n }\n else {\n return this.internalParagraphIndent;\n }\n },\n set: function (value) {\n this.internalParagraphIndent = value;\n this.firstLineIndent = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"lineLimit\", {\n /**\n * Gets or sets a value indicating whether [`line limit`].\n * @private\n */\n get: function () {\n return this.internalLineLimit;\n },\n set: function (value) {\n this.internalLineLimit = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"measureTrailingSpaces\", {\n /**\n * Gets or sets a value indicating whether [`measure trailing spaces`].\n * @private\n */\n get: function () {\n if (typeof this.trailingSpaces === 'undefined' || this.trailingSpaces == null) {\n return false;\n }\n else {\n return this.trailingSpaces;\n }\n },\n set: function (value) {\n this.trailingSpaces = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"noClip\", {\n /**\n * Gets or sets a value indicating whether [`no clip`].\n * @private\n */\n get: function () {\n if (typeof this.isNoClip === 'undefined' || this.isNoClip == null) {\n return false;\n }\n else {\n return this.isNoClip;\n }\n },\n set: function (value) {\n this.isNoClip = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"wordWrap\", {\n /**\n * Gets or sets value indicating type of the text `wrapping`.\n * @private\n */\n get: function () {\n // if (typeof this.wrapType === 'undefined' || this.wrapType == null) {\n // return PdfWordWrapType.Word;\n // } else {\n return this.wordWrapType;\n // }\n },\n set: function (value) {\n this.wordWrapType = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"horizontalScalingFactor\", {\n /**\n * Gets or sets the `scaling factor`.\n * @private\n */\n get: function () {\n // if (typeof this.scalingFactor === 'undefined' || this.scalingFactor == null) {\n // return 100;\n // } else {\n return this.scalingFactor;\n // }\n },\n set: function (value) {\n if (value <= 0) {\n throw new Error('ArgumentOutOfRangeException:The scaling factor cant be less of equal to zero, ScalingFactor');\n }\n this.scalingFactor = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringFormat.prototype, \"firstLineIndent\", {\n /**\n * Gets or sets the `indent` of the first line in the text.\n * @private\n */\n get: function () {\n if (typeof this.initialLineIndent === 'undefined' || this.initialLineIndent == null) {\n return 0;\n }\n else {\n return this.initialLineIndent;\n }\n },\n set: function (value) {\n this.initialLineIndent = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Clones` the object.\n * @private\n */\n //IClonable implementation\n PdfStringFormat.prototype.clone = function () {\n var format = this;\n return format;\n };\n return PdfStringFormat;\n}());\nexport { PdfStringFormat };\n","import { SizeF, RectangleF, PointF } from './../../drawing/pdf-drawing';\nimport { PdfWordWrapType } from './enum';\nimport { StringTokenizer } from './string-tokenizer';\n/**\n * Class `lay outing the text`.\n */\nvar PdfStringLayouter = /** @class */ (function () {\n // Constructors\n /**\n * Initializes a new instance of the `StringLayouter` class.\n * @private\n */\n function PdfStringLayouter() {\n /**\n * Checks whether the x co-ordinate is need to set as client size or not.\n * @hidden\n * @private\n */\n this.isOverloadWithPosition = false;\n //\n }\n PdfStringLayouter.prototype.layout = function (arg1, arg2, arg3, arg4, arg5, arg6, arg7) {\n if (arg4 instanceof RectangleF) {\n this.initialize(arg1, arg2, arg3, arg4, arg5);\n this.isOverloadWithPosition = arg6;\n this.clientSize = arg7;\n var result = this.doLayout();\n this.clear();\n return result;\n }\n else {\n this.initialize(arg1, arg2, arg3, arg4);\n this.isOverloadWithPosition = arg5;\n this.clientSize = arg6;\n var result = this.doLayout();\n this.clear();\n return result;\n }\n };\n PdfStringLayouter.prototype.initialize = function (text, font, format, rectSize, pageHeight) {\n if (typeof pageHeight === 'number') {\n if (text == null) {\n throw new Error('ArgumentNullException:text');\n }\n if (font == null) {\n throw new Error('ArgumentNullException:font');\n }\n this.text = text;\n this.font = font;\n this.format = format;\n this.size = new SizeF(rectSize.width, rectSize.height);\n this.rectangle = rectSize;\n this.pageHeight = pageHeight;\n this.reader = new StringTokenizer(text);\n }\n else {\n this.initialize(text, font, format, new RectangleF(new PointF(0, 0), rectSize), 0);\n }\n };\n /**\n * `Clear` all resources.\n * @private\n */\n PdfStringLayouter.prototype.clear = function () {\n this.font = null;\n this.format = null;\n this.reader.close();\n this.reader = null;\n this.text = null;\n };\n /**\n * `Layouts` the text.\n * @private\n */\n PdfStringLayouter.prototype.doLayout = function () {\n var result = new PdfStringLayoutResult();\n var lineResult = new PdfStringLayoutResult();\n var lines = [];\n var line = this.reader.peekLine();\n var lineIndent = this.getLineIndent(true);\n while (line != null) {\n lineResult = this.layoutLine(line, lineIndent);\n // if (!lineResult.Empty) {\n var numSymbolsInserted = 0;\n /* tslint:disable */\n var returnedValue = this.copyToResult(result, lineResult, lines, /*out*/ numSymbolsInserted);\n /* tslint:enable */\n var success = returnedValue.success;\n numSymbolsInserted = returnedValue.numInserted;\n this.reader.readLine();\n line = this.reader.peekLine();\n lineIndent = this.getLineIndent(false);\n }\n this.finalizeResult(result, lines);\n return result;\n };\n /**\n * Returns `line indent` for the line.\n * @private\n */\n PdfStringLayouter.prototype.getLineIndent = function (firstLine) {\n var lineIndent = 0;\n if (this.format != null) {\n lineIndent = (firstLine) ? this.format.firstLineIndent : this.format.paragraphIndent;\n lineIndent = (this.size.width > 0) ? Math.min(this.size.width, lineIndent) : lineIndent;\n }\n return lineIndent;\n };\n /**\n * Calculates `height` of the line.\n * @private\n */\n PdfStringLayouter.prototype.getLineHeight = function () {\n var height = this.font.height;\n if (this.format != null && this.format.lineSpacing !== 0) {\n height = this.format.lineSpacing + this.font.height;\n }\n return height;\n };\n /**\n * Calculates `width` of the line.\n * @private\n */\n PdfStringLayouter.prototype.getLineWidth = function (line) {\n var width = this.font.getLineWidth(line, this.format);\n return width;\n };\n // tslint:disable\n /**\n * `Layouts` line.\n * @private\n */\n PdfStringLayouter.prototype.layoutLine = function (line, lineIndent) {\n var lineResult = new PdfStringLayoutResult();\n lineResult.layoutLineHeight = this.getLineHeight();\n var lines = [];\n var maxWidth = this.size.width;\n var lineWidth = this.getLineWidth(line) + lineIndent;\n var lineType = LineType.FirstParagraphLine;\n var readWord = true;\n // line is in bounds.\n if (maxWidth <= 0 || Math.round(lineWidth) <= Math.round(maxWidth)) {\n this.addToLineResult(lineResult, lines, line, lineWidth, LineType.NewLineBreak | lineType);\n }\n else {\n var builder = '';\n var curLine = '';\n lineWidth = lineIndent;\n var curIndent = lineIndent;\n var reader = new StringTokenizer(line);\n var word = reader.peekWord();\n var isSingleWord = false;\n while (word != null) {\n curLine = curLine + word;\n var curLineWidth = this.getLineWidth(curLine.toString()) + curIndent /*)*/;\n if (curLineWidth > maxWidth) {\n if (this.getWrapType() == PdfWordWrapType.None)\n break;\n if (this.getWrapType() != PdfWordWrapType.Character || !readWord) {\n var ln = builder.toString();\n if (ln.indexOf(' ') === -1) {\n isSingleWord = true;\n this.addToLineResult(lineResult, lines, curLine, lineWidth, LineType.LayoutBreak | lineType);\n }\n else {\n this.addToLineResult(lineResult, lines, ln, lineWidth, LineType.LayoutBreak | lineType);\n }\n if (this.isOverloadWithPosition) {\n maxWidth = this.clientSize.width;\n }\n curLine = '';\n builder = '';\n lineWidth = 0;\n curIndent = 0;\n curLineWidth = 0;\n lineType = LineType.None;\n if (isSingleWord) {\n reader.readWord();\n readWord = false;\n }\n word = (readWord) ? word : reader.peekWord();\n isSingleWord = false;\n readWord = true;\n }\n else {\n readWord = false;\n curLine = curLine + builder.toString();\n word = reader.peek().toString();\n }\n continue;\n }\n builder = builder + word;\n lineWidth = curLineWidth;\n if (readWord) {\n reader.readWord();\n word = reader.peekWord();\n isSingleWord = false;\n }\n else {\n reader.read();\n word = reader.peek().toString();\n }\n }\n if (builder.length > 0) {\n var ln = builder.toString();\n this.addToLineResult(lineResult, lines, ln, lineWidth, LineType.NewLineBreak | LineType.LastParagraphLine);\n }\n reader.close();\n }\n lineResult.layoutLines = [];\n for (var index = 0; index < lines.length; index++) {\n lineResult.layoutLines.push(lines[index]);\n }\n lines = [];\n return lineResult;\n };\n /**\n * `Adds` line to line result.\n * @private\n */\n PdfStringLayouter.prototype.addToLineResult = function (lineResult, lines, line, lineWidth, breakType) {\n var info = new LineInfo();\n info.text = line;\n info.width = lineWidth;\n info.lineType = breakType;\n lines.push(info);\n var size = lineResult.actualSize;\n size.height += this.getLineHeight();\n size.width = Math.max(size.width, lineWidth);\n lineResult.size = size;\n };\n /**\n * `Copies` layout result from line result to entire result. Checks whether we can proceed lay outing or not.\n * @private\n */\n PdfStringLayouter.prototype.copyToResult = function (result, lineResult, lines, \n /*out*/ numInserted) {\n var success = true;\n var allowPartialLines = (this.format != null && !this.format.lineLimit);\n var height = result.actualSize.height;\n var maxHeight = this.size.height;\n if ((this.pageHeight > 0) && (maxHeight + this.rectangle.y > this.pageHeight)) {\n maxHeight = this.rectangle.y - this.pageHeight;\n maxHeight = Math.max(maxHeight, -maxHeight);\n }\n numInserted = 0;\n for (var i = 0, len = lineResult.lines.length; i < len; i++) {\n var expHeight = height + lineResult.lineHeight;\n var info = lineResult.lines[i];\n numInserted += info.text.length;\n info = this.trimLine(info, (lines.length === 0));\n lines.push(info);\n // Update width.\n var size_1 = result.actualSize;\n size_1.width = Math.max(size_1.width, info.width);\n result.size = size_1;\n height = expHeight;\n }\n var size = result.actualSize;\n size.height = height;\n result.size = size;\n return { success: success, numInserted: numInserted };\n };\n /**\n * `Finalizes` final result.\n * @private\n */\n PdfStringLayouter.prototype.finalizeResult = function (result, lines) {\n result.layoutLines = [];\n for (var index = 0; index < lines.length; index++) {\n result.layoutLines.push(lines[index]);\n }\n result.layoutLineHeight = this.getLineHeight();\n lines = [];\n };\n /**\n * `Trims` whitespaces at the line.\n * @private\n */\n PdfStringLayouter.prototype.trimLine = function (info, firstLine) {\n var line = info.text;\n var lineWidth = info.width;\n // Trim start whitespaces if the line is not a start of the paragraph only.\n // let trimStartSpaces : boolean = ((info.LineType & LineType.FirstParagraphLine) === 0);\n var start = (this.format == null || !this.format.rightToLeft);\n var spaces = StringTokenizer.spaces;\n line = (start) ? line.trim() : line.trim();\n // Recalculate line width.\n if (line.length !== info.text.length) {\n lineWidth = this.getLineWidth(line);\n lineWidth += this.getLineIndent(firstLine);\n }\n info.text = line;\n info.width = lineWidth;\n return info;\n };\n /**\n * Returns `wrap` type.\n * @private\n */\n PdfStringLayouter.prototype.getWrapType = function () {\n var wrapType = (this.format != null) ? this.format.wordWrap : PdfWordWrapType.Word;\n return wrapType;\n };\n return PdfStringLayouter;\n}());\nexport { PdfStringLayouter };\n//Internal declaration\nvar PdfStringLayoutResult = /** @class */ (function () {\n function PdfStringLayoutResult() {\n }\n Object.defineProperty(PdfStringLayoutResult.prototype, \"remainder\", {\n // Properties\n /**\n * Gets the `text` which is not lay outed.\n * @private\n */\n get: function () {\n return this.textRemainder;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringLayoutResult.prototype, \"actualSize\", {\n /**\n * Gets the actual layout text `bounds`.\n * @private\n */\n get: function () {\n if (typeof this.size === 'undefined') {\n this.size = new SizeF(0, 0);\n }\n return this.size;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringLayoutResult.prototype, \"lines\", {\n /**\n * Gets layout `lines` information.\n * @private\n */\n get: function () {\n return this.layoutLines;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringLayoutResult.prototype, \"lineHeight\", {\n /**\n * Gets the `height` of the line.\n * @private\n */\n get: function () {\n return this.layoutLineHeight;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringLayoutResult.prototype, \"empty\", {\n /**\n * Gets value that indicates whether any layout text [`empty`].\n * @private\n */\n get: function () {\n return (this.layoutLines == null || this.layoutLines.length === 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStringLayoutResult.prototype, \"lineCount\", {\n /**\n * Gets `number of` the layout lines.\n * @private\n */\n get: function () {\n var count = (!this.empty) ? this.layoutLines.length : 0;\n return count;\n },\n enumerable: true,\n configurable: true\n });\n return PdfStringLayoutResult;\n}());\nexport { PdfStringLayoutResult };\nvar LineInfo = /** @class */ (function () {\n function LineInfo() {\n }\n Object.defineProperty(LineInfo.prototype, \"lineType\", {\n //Properties\n /**\n * Gets the `type` of the line text.\n * @private\n */\n get: function () {\n return this.type;\n },\n set: function (value) {\n this.type = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LineInfo.prototype, \"text\", {\n /**\n * Gets the line `text`.\n * @private\n */\n get: function () {\n return this.content;\n },\n set: function (value) {\n this.content = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LineInfo.prototype, \"width\", {\n /**\n * Gets `width` of the line text.\n * @private\n */\n get: function () {\n return this.lineWidth;\n },\n set: function (value) {\n this.lineWidth = value;\n },\n enumerable: true,\n configurable: true\n });\n return LineInfo;\n}());\nexport { LineInfo };\n/**\n* Break type of the `line`.\n* @private\n*/\nexport var LineType;\n(function (LineType) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n LineType[LineType[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `NewLineBreak`.\n * @private\n */\n LineType[LineType[\"NewLineBreak\"] = 1] = \"NewLineBreak\";\n /**\n * Specifies the type of `LayoutBreak`.\n * @private\n */\n LineType[LineType[\"LayoutBreak\"] = 2] = \"LayoutBreak\";\n /**\n * Specifies the type of `FirstParagraphLine`.\n * @private\n */\n LineType[LineType[\"FirstParagraphLine\"] = 4] = \"FirstParagraphLine\";\n /**\n * Specifies the type of `LastParagraphLine`.\n * @private\n */\n LineType[LineType[\"LastParagraphLine\"] = 8] = \"LastParagraphLine\";\n})(LineType || (LineType = {}));\n","/**\n * StringTokenizer.ts class for EJ2-PDF\n * Utility class for working with strings.\n * @private\n */\nvar StringTokenizer = /** @class */ (function () {\n // Constructors\n /**\n * Initializes a new instance of the `StringTokenizer` class.\n * @private\n */\n function StringTokenizer(textValue) {\n /**\n * Current `position`.\n * @private\n */\n this.currentPosition = 0;\n if (textValue == null) {\n throw new Error('ArgumentNullException:text');\n }\n this.text = textValue;\n }\n Object.defineProperty(StringTokenizer.prototype, \"length\", {\n // Properties\n /**\n * Gets text `length`.\n * @private\n */\n get: function () {\n return this.text.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StringTokenizer.prototype, \"position\", {\n /**\n * Gets or sets the position.\n * @private\n */\n get: function () {\n return this.currentPosition;\n },\n set: function (value) {\n this.currentPosition = value;\n },\n enumerable: true,\n configurable: true\n });\n StringTokenizer.getCharsCount = function (text, symbols) {\n if (typeof symbols === 'string') {\n if (text == null) {\n throw new Error('ArgumentNullException:wholeText');\n }\n var numSymbols = 0;\n var curIndex = 0;\n for (;;) {\n curIndex = text.indexOf(symbols, curIndex);\n if (curIndex === -1) {\n break;\n }\n else {\n numSymbols++;\n curIndex++;\n }\n }\n return numSymbols;\n }\n else {\n if (text == null) {\n throw new Error('ArgumentNullException:text');\n }\n if (symbols == null) {\n throw new Error('ArgumentNullException:symbols');\n }\n var count = 0;\n for (var i = 0, len = text.length; i < len; i++) {\n var ch = text[i];\n if (this.contains(symbols, ch)) {\n count++;\n }\n }\n return count;\n }\n };\n /**\n * Reads line of the text.\n * @private\n */\n StringTokenizer.prototype.readLine = function () {\n var pos = this.currentPosition;\n while (pos < this.length) {\n var ch = this.text[pos];\n switch (ch) {\n case '\\r':\n case '\\n': {\n var text = this.text.substring(this.currentPosition, pos - this.currentPosition);\n this.currentPosition = pos + 1;\n this.currentPosition++;\n return text;\n }\n }\n pos++;\n }\n // The remaining text.\n if (pos > this.currentPosition) {\n var text2 = this.text.substring(this.currentPosition, pos - this.currentPosition);\n this.currentPosition = pos;\n return text2;\n }\n return null;\n };\n /**\n * Reads line of the text.\n * @private\n */\n StringTokenizer.prototype.peekLine = function () {\n var pos = this.currentPosition;\n var line = this.readLine();\n this.currentPosition = pos;\n return line;\n };\n /**\n * Reads a word from the text.\n * @private\n */\n StringTokenizer.prototype.readWord = function () {\n var pos = this.currentPosition;\n while (pos < this.length) {\n var ch = this.text[pos];\n switch (ch) {\n case '\\r':\n case '\\n':\n var textValue = this.text.substr(this.currentPosition, pos - this.currentPosition);\n this.currentPosition = pos + 1;\n if (((ch === '\\r') && (this.currentPosition < this.length)) && (this.text[this.currentPosition] === '\\n')) {\n this.currentPosition++;\n }\n return textValue;\n case ' ':\n case '\\t': {\n if (pos === this.currentPosition) {\n pos++;\n }\n var text = this.text.substr(this.currentPosition, pos - this.currentPosition);\n this.currentPosition = pos;\n return text;\n }\n }\n pos++;\n }\n // The remaining text.\n if (pos > this.currentPosition) {\n var text2 = this.text.substr(this.currentPosition, pos - this.currentPosition);\n this.currentPosition = pos;\n return text2;\n }\n return null;\n };\n /**\n * Peeks a word from the text.\n * @private\n */\n StringTokenizer.prototype.peekWord = function () {\n var pos = this.currentPosition;\n var word = this.readWord();\n this.currentPosition = pos;\n return word;\n };\n StringTokenizer.prototype.read = function (count) {\n if (typeof count === 'undefined') {\n var ch = '0';\n return ch;\n }\n else {\n var num = 0;\n var builder = '';\n return builder;\n }\n };\n /**\n * Peeks char form the data.\n * @private\n */\n StringTokenizer.prototype.peek = function () {\n var ch = '0';\n return ch;\n };\n /**\n * Closes a reader.\n * @private\n */\n StringTokenizer.prototype.close = function () {\n this.text = null;\n };\n //Implementation\n /**\n * Checks whether array contains a symbol.\n * @private\n */\n StringTokenizer.contains = function (array, symbol) {\n var contains = false;\n for (var i = 0; i < array.length; i++) {\n if (array[i] === symbol) {\n contains = true;\n break;\n }\n }\n return contains;\n };\n // Constants\n /**\n * `Whitespace` symbol.\n * @private\n */\n StringTokenizer.whiteSpace = ' ';\n /**\n * `tab` symbol.\n * @private\n */\n StringTokenizer.tab = '\\t';\n /**\n * Array of `spaces`.\n * @private\n */\n StringTokenizer.spaces = [StringTokenizer.whiteSpace, StringTokenizer.tab];\n /**\n * `Pattern` for WhiteSpace.\n * @private\n */\n StringTokenizer.whiteSpacePattern = '^[ \\t]+$';\n return StringTokenizer;\n}());\nexport { StringTokenizer };\n","/**\n * PdfFont.ts class for EJ2-PDF\n */\nimport { PdfFontStyle } from './enum';\nimport { SizeF } from './../../drawing/pdf-drawing';\nimport { PdfStringFormat } from './pdf-string-format';\nimport { PdfStringLayouter } from './string-layouter';\nimport { StringTokenizer } from './string-tokenizer';\n/**\n * Defines a particular format for text, including font face, size, and style attributes.\n * @private\n */\nvar PdfFont = /** @class */ (function () {\n function PdfFont(size, style) {\n /**\n * `Style` of the font.\n * @private\n */\n this.fontStyle = PdfFontStyle.Regular;\n if (typeof size === 'number' && typeof style === 'undefined') {\n this.fontSize = size;\n }\n else {\n this.fontSize = size;\n this.setStyle(style);\n }\n }\n Object.defineProperty(PdfFont.prototype, \"name\", {\n //Properties\n /**\n * Gets the face name of this Font.\n * @private\n */\n get: function () {\n return this.metrics.name;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"size\", {\n /**\n * Gets the size of this font.\n * @private\n */\n get: function () {\n return this.fontSize;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"height\", {\n /**\n * Gets the height of the font in points.\n * @private\n */\n get: function () {\n return this.metrics.getHeight(null);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"style\", {\n /**\n * Gets the style information for this font.\n * @private\n */\n get: function () {\n return this.fontStyle;\n },\n set: function (value) {\n this.fontStyle = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"bold\", {\n /**\n * Gets a value indicating whether this `PdfFont` is `bold`.\n * @private\n */\n get: function () {\n return ((this.style & PdfFontStyle.Bold) > 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"italic\", {\n /**\n * Gets a value indicating whether this `PdfFont` has the `italic` style applied.\n * @private\n */\n get: function () {\n return ((this.style & PdfFontStyle.Italic) > 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"strikeout\", {\n /**\n * Gets a value indicating whether this `PdfFont` is `strikeout`.\n * @private\n */\n get: function () {\n return ((this.style & PdfFontStyle.Strikeout) > 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"underline\", {\n /**\n * Gets a value indicating whether this `PdfFont` is `underline`.\n * @private\n */\n get: function () {\n return ((this.style & PdfFontStyle.Underline) > 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"metrics\", {\n /**\n * Gets or sets the `metrics` for this font.\n * @private\n */\n get: function () {\n return this.fontMetrics;\n },\n set: function (value) {\n this.fontMetrics = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfFont.prototype, \"element\", {\n // /**\n // * Gets and Sets the font `internals`.\n // * @private\n // */\n // public get fontInternal() : IPdfPrimitive {\n // return this.pdfFontInternals;\n // }\n // public set fontInternal(value : IPdfPrimitive) {\n // this.pdfFontInternals = value;\n // }\n //IPdfWrapper Members\n /**\n * Gets the `element` representing the font.\n * @private\n */\n get: function () {\n return this.pdfFontInternals;\n },\n enumerable: true,\n configurable: true\n });\n PdfFont.prototype.measureString = function (text, arg2, arg3, arg4, arg5) {\n if (typeof text === 'string' && typeof arg2 === 'undefined') {\n return this.measureString(text, null);\n }\n else if (typeof text === 'string' && (arg2 instanceof PdfStringFormat || arg2 == null) && typeof arg3 === 'undefined' && typeof arg4 === 'undefined') {\n var temparg2 = arg2;\n var charactersFitted = 0;\n var linesFilled = 0;\n return this.measureString(text, temparg2, charactersFitted, linesFilled);\n }\n else if (typeof text === 'string' && (arg2 instanceof PdfStringFormat || arg2 == null) && typeof arg3 === 'number' && typeof arg4 === 'number') {\n var temparg2 = arg2;\n return this.measureString(text, 0, temparg2, arg3, arg4);\n // } else if (typeof text === 'string' && typeof arg2 === 'number' && typeof arg3 === 'undefined') {\n // return this.measureString(text, arg2, null);\n // } else if (typeof text === 'string' && typeof arg2 === 'number' && (arg3 instanceof PdfStringFormat || arg3 == null) && typeof arg4 === 'undefined' && typeof arg5 === 'undefined') {\n // let temparg3 : PdfStringFormat = arg3 as PdfStringFormat;\n // let charactersFitted : number = 0;\n // let linesFilled : number = 0;\n // return this.measureString(text, arg2, temparg3, charactersFitted, linesFilled);\n }\n else if (typeof text === 'string' && typeof arg2 === 'number' && (arg3 instanceof PdfStringFormat || arg3 == null) && typeof arg4 === 'number' && typeof arg5 === 'number') {\n var layoutArea = new SizeF(arg2, 0);\n var temparg3 = arg3;\n return this.measureString(text, layoutArea, temparg3, arg4, arg5);\n // } else if (typeof text === 'string' && arg2 instanceof SizeF && typeof arg3 === 'undefined') {\n // return this.measureString(text, arg2, null);\n // } else if (typeof text === 'string' && arg2 instanceof SizeF && (arg3 instanceof PdfStringFormat || arg3 == null) && typeof arg4 === 'undefined' && typeof arg5 === 'undefined') {\n // let temparg3 : PdfStringFormat = arg3 as PdfStringFormat;\n // let charactersFitted : number = 0;\n // let linesFilled : number = 0;\n // return this.measureString(text, arg2, temparg3, charactersFitted, linesFilled);\n }\n else {\n if (text == null) {\n throw Error(\"ArgumentNullException(\\\"text\\\")\");\n }\n var temparg2 = arg2;\n var temparg3 = arg3;\n var layouter = new PdfStringLayouter();\n var result = layouter.layout(text, this, temparg3, temparg2, false, new SizeF(0, 0));\n // arg4 = (result.Remainder == null) ? text.length : text.length - result.Remainder.length;\n arg4 = text.length;\n arg5 = (result.empty) ? 0 : result.lines.length;\n return result.actualSize;\n }\n };\n /* tslint:enable */\n //IPdfCache Members\n /**\n * `Checks` whether the object is similar to another object.\n * @private\n */\n PdfFont.prototype.equalsTo = function (obj) {\n var result = this.equalsToFont(obj);\n return result;\n };\n /**\n * Returns `internals` of the object.\n * @private\n */\n PdfFont.prototype.getInternals = function () {\n return this.pdfFontInternals;\n };\n /**\n * Sets `internals` to the object.\n * @private\n */\n PdfFont.prototype.setInternals = function (internals) {\n if (internals == null) {\n throw new Error('ArgumentNullException:internals');\n }\n this.pdfFontInternals = internals;\n };\n /**\n * Sets the `style` of the font.\n * @private\n */\n PdfFont.prototype.setStyle = function (style) {\n this.fontStyle = style;\n };\n /**\n * Applies `settings` to the default line width.\n * @private\n */\n PdfFont.prototype.applyFormatSettings = function (line, format, width) {\n // if (line == null) {\n // throw new Error(`ArgumentNullException:line`);\n // }\n var realWidth = width;\n if (format != null && width > 0) {\n // Space among characters is not default.\n if (format.characterSpacing !== 0) {\n realWidth += (line.length - 1) * format.characterSpacing;\n }\n // Space among words is not default.\n if (format.wordSpacing !== 0) {\n var symbols = StringTokenizer.spaces;\n var whitespacesCount = StringTokenizer.getCharsCount(line, symbols);\n realWidth += whitespacesCount * format.wordSpacing;\n }\n }\n return realWidth;\n };\n //Constants\n /**\n * `Multiplier` of the symbol width.\n * @default 0.001\n * @private\n */\n PdfFont.charSizeMultiplier = 0.001;\n /**\n * `Synchronization` object.\n * @private\n */\n PdfFont.syncObject = new Object();\n return PdfFont;\n}());\nexport { PdfFont };\n","/**\n * public Enum for `CompositeFontType`.\n * @private\n */\nexport var ObjectStatus;\n(function (ObjectStatus) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n ObjectStatus[ObjectStatus[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `Registered`.\n * @private\n */\n ObjectStatus[ObjectStatus[\"Registered\"] = 1] = \"Registered\";\n})(ObjectStatus || (ObjectStatus = {}));\n","/**\n * Used to `write a string` into output file.\n * @private\n */\nvar PdfWriter = /** @class */ (function () {\n /**\n * Initialize an instance of `PdfWriter` class.\n * @private\n */\n function PdfWriter(stream) {\n this.streamWriter = stream;\n }\n Object.defineProperty(PdfWriter.prototype, \"document\", {\n //properties\n /**\n * Gets and Sets the `document`.\n * @private\n */\n get: function () {\n return this.pdfDocument;\n },\n set: function (value) {\n this.pdfDocument = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfWriter.prototype, \"position\", {\n /**\n * Gets the `position`.\n * @private\n */\n get: function () {\n return this.streamWriter.buffer.size;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfWriter.prototype, \"length\", {\n /**\n * Gets the `length` of the stream'.\n * @private\n */\n get: function () {\n return this.streamWriter.buffer.size;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfWriter.prototype, \"stream\", {\n /**\n * Gets the `stream`.\n * @private\n */\n get: function () {\n var result = this.streamWriter;\n return result;\n },\n enumerable: true,\n configurable: true\n });\n //public Methods\n /**\n * `Writes the specified data`.\n * @private\n */\n PdfWriter.prototype.write = function (overload) {\n var data = [];\n var tempOverload = overload;\n this.streamWriter.write(tempOverload);\n };\n return PdfWriter;\n}());\nexport { PdfWriter };\n","/**\n * PdfMainObjectCollection.ts class for EJ2-PDF\n */\nimport { Dictionary } from './../collections/dictionary';\nimport { ObjectStatus } from './enum';\n/**\n * The collection of all `objects` within a PDF document.\n * @private\n */\nvar PdfMainObjectCollection = /** @class */ (function () {\n function PdfMainObjectCollection() {\n //Fields\n /**\n * The collection of the `indirect objects`.\n * @default []\n * @private\n */\n this.objectCollections = [];\n /**\n * The collection of the `Indirect objects`.\n * @default new Dictionary()\n * @private\n */\n this.mainObjectCollection = new Dictionary();\n /**\n * The collection of `primitive objects`.\n * @private\n */\n this.primitiveObjectCollection = new Dictionary();\n }\n Object.defineProperty(PdfMainObjectCollection.prototype, \"count\", {\n //Properties\n /**\n * Gets the `count`.\n * @private\n */\n get: function () {\n return this.objectCollections.length;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the value of `ObjectInfo` from object collection.\n * @private\n */\n PdfMainObjectCollection.prototype.items = function (index) {\n return this.objectCollections[index];\n };\n Object.defineProperty(PdfMainObjectCollection.prototype, \"outIsNew\", {\n //Methods\n /**\n * Specifies the value of `IsNew`.\n * @private\n */\n get: function () {\n return this.isNew;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Adds` the specified element.\n * @private\n */\n PdfMainObjectCollection.prototype.add = function (element) {\n var objInfo = new ObjectInfo(element);\n this.objectCollections.push(objInfo);\n if (!this.primitiveObjectCollection.containsKey(element)) {\n this.primitiveObjectCollection.setValue(element, this.objectCollections.length - 1);\n }\n element.position = this.index = this.objectCollections.length - 1;\n element.status = ObjectStatus.Registered;\n };\n /**\n * `Looks` through the collection for the object specified.\n * @private\n */\n PdfMainObjectCollection.prototype.lookFor = function (obj) {\n var index = -1;\n if (obj.position !== -1) {\n return obj.position;\n }\n if (this.primitiveObjectCollection.containsKey(obj) && this.count === this.primitiveObjectCollection.size()) {\n index = this.primitiveObjectCollection.getValue(obj);\n }\n else {\n for (var i = this.count - 1; i >= 0; i--) {\n var oi = this.objectCollections[i];\n if (oi.object === obj) {\n index = i;\n break;\n }\n }\n }\n return index;\n };\n /**\n * Gets the `reference of the object`.\n * @private\n */\n PdfMainObjectCollection.prototype.getReference = function (index, isNew) {\n this.index = this.lookFor(index);\n var reference;\n this.isNew = false;\n var oi = this.objectCollections[this.index];\n reference = oi.reference;\n var obj = { reference: reference, wasNew: isNew };\n return obj;\n };\n /**\n * Tries to set the `reference to the object`.\n * @private\n */\n PdfMainObjectCollection.prototype.trySetReference = function (obj, reference, found) {\n var result = true;\n found = true;\n this.index = this.lookFor(obj);\n var oi = this.objectCollections[this.index];\n oi.setReference(reference);\n return result;\n };\n PdfMainObjectCollection.prototype.destroy = function () {\n for (var _i = 0, _a = this.objectCollections; _i < _a.length; _i++) {\n var obj = _a[_i];\n if (obj !== undefined) {\n obj.pdfObject.position = -1;\n obj.pdfObject.isSaving = undefined;\n obj.pdfObject.objectCollectionIndex = undefined;\n obj.pdfObject.position = undefined;\n }\n }\n this.objectCollections = [];\n this.mainObjectCollection = new Dictionary();\n this.primitiveObjectCollection = new Dictionary();\n };\n return PdfMainObjectCollection;\n}());\nexport { PdfMainObjectCollection };\nvar ObjectInfo = /** @class */ (function () {\n function ObjectInfo(obj, reference) {\n this.pdfObject = obj;\n this.pdfReference = reference;\n }\n Object.defineProperty(ObjectInfo.prototype, \"object\", {\n //Properties\n /**\n * Gets the `object`.\n * @private\n */\n get: function () {\n return this.pdfObject;\n },\n set: function (value) {\n this.pdfObject = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ObjectInfo.prototype, \"reference\", {\n /**\n * Gets the `reference`.\n * @private\n */\n get: function () {\n return this.pdfReference;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets the `reference`.\n * @private\n */\n ObjectInfo.prototype.setReference = function (reference) {\n this.pdfReference = reference;\n };\n return ObjectInfo;\n}());\nexport { ObjectInfo };\n","/**\n * public Enum for `ObjectType`.\n * @private\n */\nexport var ObjectType;\n(function (ObjectType) {\n /**\n * Specifies the type of `Free`.\n * @private\n */\n ObjectType[ObjectType[\"Free\"] = 0] = \"Free\";\n /**\n * Specifies the type of `Normal`.\n * @private\n */\n ObjectType[ObjectType[\"Normal\"] = 1] = \"Normal\";\n /**\n * Specifies the type of `Packed`.\n * @private\n */\n ObjectType[ObjectType[\"Packed\"] = 2] = \"Packed\";\n})(ObjectType || (ObjectType = {}));\n","import { StreamWriter } from '@syncfusion/ej2-file-utils';\nimport { Encoding } from '@syncfusion/ej2-file-utils';\nimport { PdfDocument } from './pdf-document';\n/**\n * `PdfDocumentBase` class represent common properties of PdfDocument classes.\n * @private\n */\nvar PdfDocumentBase = /** @class */ (function () {\n function PdfDocumentBase(document) {\n /**\n * If the stream is copied, then it specifies true.\n * @private\n */\n this.isStreamCopied = false;\n if (document instanceof PdfDocument) {\n this.document = document;\n }\n }\n Object.defineProperty(PdfDocumentBase.prototype, \"pdfObjects\", {\n //Prpperties\n /**\n * Gets the `PDF objects` collection, which stores all objects and references to it..\n * @private\n */\n get: function () {\n return this.objects;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentBase.prototype, \"crossTable\", {\n /**\n * Gets the `cross-reference` table.\n * @private\n */\n get: function () {\n return this.pdfCrossTable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentBase.prototype, \"currentSavingObj\", {\n /**\n * Gets or sets the current saving `object number`.\n * @private\n */\n get: function () {\n return this.currentSavingObject;\n },\n set: function (value) {\n this.currentSavingObject = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentBase.prototype, \"catalog\", {\n /**\n * Gets the PDF document `catalog`.\n * @private\n */\n get: function () {\n return this.pdfCatalog;\n },\n set: function (value) {\n this.pdfCatalog = value;\n },\n enumerable: true,\n configurable: true\n });\n //Public methods\n /**\n * Sets the `main object collection`.\n * @private\n */\n PdfDocumentBase.prototype.setMainObjectCollection = function (mainObjectCollection) {\n this.objects = mainObjectCollection;\n };\n /**\n * Sets the `cross table`.\n * @private\n */\n PdfDocumentBase.prototype.setCrossTable = function (cTable) {\n this.pdfCrossTable = cTable;\n };\n /**\n * Sets the `catalog`.\n * @private\n */\n PdfDocumentBase.prototype.setCatalog = function (catalog) {\n this.pdfCatalog = catalog;\n };\n PdfDocumentBase.prototype.save = function (filename) {\n var _this = this;\n var encoding = new Encoding(true);\n var SW = new StreamWriter(encoding);\n if (typeof filename === 'undefined') {\n var encoding_1 = new Encoding(true);\n var SW_1 = new StreamWriter(encoding_1);\n return new Promise(function (resolve, reject) {\n /* tslint:disable-next-line:no-any */\n var obj = {};\n obj.blobData = new Blob([_this.document.docSave(SW_1, true)], { type: 'application/pdf' });\n resolve(obj);\n });\n }\n else {\n this.document.docSave(SW, filename, true);\n }\n };\n /**\n * `Clone` of parent object - PdfDocument.\n * @private\n */\n PdfDocumentBase.prototype.clone = function () {\n return this.document;\n };\n return PdfDocumentBase;\n}());\nexport { PdfDocumentBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfCatalog.ts class for EJ2-PDF\n */\nimport { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\n/**\n * `PdfCatalog` class represents internal catalog of the Pdf document.\n * @private\n */\nvar PdfCatalog = /** @class */ (function (_super) {\n __extends(PdfCatalog, _super);\n //constructor\n /**\n * Initializes a new instance of the `PdfCatalog` class.\n * @private\n */\n function PdfCatalog() {\n var _this = _super.call(this) || this;\n //fields\n /**\n * Internal variable to store collection of `sections`.\n * @default null\n * @private\n */\n _this.sections = null;\n /**\n * Internal variable for accessing fields from `DictionryProperties` class.\n * @private\n */\n _this.tempDictionaryProperties = new DictionaryProperties();\n _this.items.setValue(new DictionaryProperties().type, new PdfName('Catalog'));\n return _this;\n }\n Object.defineProperty(PdfCatalog.prototype, \"pages\", {\n //Properties\n /**\n * Gets or sets the sections, which contain `pages`.\n * @private\n */\n get: function () {\n return this.sections;\n },\n set: function (value) {\n var dictionary = value.element;\n // if (this.sections !== value) {\n // this.sections = value;\n // this.Items.setValue(this.tempDictionaryProperties.pages, new PdfReferenceHolder(value));\n // }\n this.sections = value;\n this.items.setValue(this.tempDictionaryProperties.pages, new PdfReferenceHolder(value));\n },\n enumerable: true,\n configurable: true\n });\n return PdfCatalog;\n}(PdfDictionary));\nexport { PdfCatalog };\n","/**\n * public Enum for `PdfPageOrientation`.\n * @private\n */\nexport var PdfPageOrientation;\n(function (PdfPageOrientation) {\n /**\n * Specifies the type of `Portrait`.\n * @private\n */\n PdfPageOrientation[PdfPageOrientation[\"Portrait\"] = 0] = \"Portrait\";\n /**\n * Specifies the type of `Landscape`.\n * @private\n */\n PdfPageOrientation[PdfPageOrientation[\"Landscape\"] = 1] = \"Landscape\";\n})(PdfPageOrientation || (PdfPageOrientation = {}));\n/**\n * public Enum for `PdfPageRotateAngle`.\n * @private\n */\nexport var PdfPageRotateAngle;\n(function (PdfPageRotateAngle) {\n /**\n * Specifies the type of `RotateAngle0`.\n * @private\n */\n PdfPageRotateAngle[PdfPageRotateAngle[\"RotateAngle0\"] = 0] = \"RotateAngle0\";\n /**\n * Specifies the type of `RotateAngle90`.\n * @private\n */\n PdfPageRotateAngle[PdfPageRotateAngle[\"RotateAngle90\"] = 1] = \"RotateAngle90\";\n /**\n * Specifies the type of `RotateAngle180`.\n * @private\n */\n PdfPageRotateAngle[PdfPageRotateAngle[\"RotateAngle180\"] = 2] = \"RotateAngle180\";\n /**\n * Specifies the type of `RotateAngle270`.\n * @private\n */\n PdfPageRotateAngle[PdfPageRotateAngle[\"RotateAngle270\"] = 3] = \"RotateAngle270\";\n})(PdfPageRotateAngle || (PdfPageRotateAngle = {}));\n/**\n * public Enum for `PdfNumberStyle`.\n * @private\n */\nexport var PdfNumberStyle;\n(function (PdfNumberStyle) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n PdfNumberStyle[PdfNumberStyle[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `Numeric`.\n * @private\n */\n PdfNumberStyle[PdfNumberStyle[\"Numeric\"] = 1] = \"Numeric\";\n /**\n * Specifies the type of `LowerLatin`.\n * @private\n */\n PdfNumberStyle[PdfNumberStyle[\"LowerLatin\"] = 2] = \"LowerLatin\";\n /**\n * Specifies the type of `LowerRoman`.\n * @private\n */\n PdfNumberStyle[PdfNumberStyle[\"LowerRoman\"] = 3] = \"LowerRoman\";\n /**\n * Specifies the type of `UpperLatin`.\n * @private\n */\n PdfNumberStyle[PdfNumberStyle[\"UpperLatin\"] = 4] = \"UpperLatin\";\n /**\n * Specifies the type of `UpperRoman`.\n * @private\n */\n PdfNumberStyle[PdfNumberStyle[\"UpperRoman\"] = 5] = \"UpperRoman\";\n})(PdfNumberStyle || (PdfNumberStyle = {}));\n/**\n * public Enum for `PdfDockStyle`.\n * @private\n */\nexport var PdfDockStyle;\n(function (PdfDockStyle) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n PdfDockStyle[PdfDockStyle[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `Bottom`.\n * @private\n */\n PdfDockStyle[PdfDockStyle[\"Bottom\"] = 1] = \"Bottom\";\n /**\n * Specifies the type of `Top`.\n * @private\n */\n PdfDockStyle[PdfDockStyle[\"Top\"] = 2] = \"Top\";\n /**\n * Specifies the type of `Left`.\n * @private\n */\n PdfDockStyle[PdfDockStyle[\"Left\"] = 3] = \"Left\";\n /**\n * Specifies the type of `Right`.\n * @private\n */\n PdfDockStyle[PdfDockStyle[\"Right\"] = 4] = \"Right\";\n /**\n * Specifies the type of `Fill`.\n * @private\n */\n PdfDockStyle[PdfDockStyle[\"Fill\"] = 5] = \"Fill\";\n})(PdfDockStyle || (PdfDockStyle = {}));\n/**\n * public Enum for `PdfAlignmentStyle`.\n * @private\n */\nexport var PdfAlignmentStyle;\n(function (PdfAlignmentStyle) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `TopLeft`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"TopLeft\"] = 1] = \"TopLeft\";\n /**\n * Specifies the type of `TopCenter`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"TopCenter\"] = 2] = \"TopCenter\";\n /**\n * Specifies the type of `TopRight`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"TopRight\"] = 3] = \"TopRight\";\n /**\n * Specifies the type of `MiddleLeft`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"MiddleLeft\"] = 4] = \"MiddleLeft\";\n /**\n * Specifies the type of `MiddleCenter`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"MiddleCenter\"] = 5] = \"MiddleCenter\";\n /**\n * Specifies the type of `MiddleRight`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"MiddleRight\"] = 6] = \"MiddleRight\";\n /**\n * Specifies the type of `BottomLeft`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"BottomLeft\"] = 7] = \"BottomLeft\";\n /**\n * Specifies the type of `BottomCenter`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"BottomCenter\"] = 8] = \"BottomCenter\";\n /**\n * Specifies the type of `BottomRight`.\n * @private\n */\n PdfAlignmentStyle[PdfAlignmentStyle[\"BottomRight\"] = 9] = \"BottomRight\";\n})(PdfAlignmentStyle || (PdfAlignmentStyle = {}));\n/**\n * public Enum for `TemplateType`.\n * @private\n */\nexport var TemplateType;\n(function (TemplateType) {\n /**\n * Specifies the type of `None`.\n * @private\n */\n TemplateType[TemplateType[\"None\"] = 0] = \"None\";\n /**\n * Specifies the type of `Top`.\n * @private\n */\n TemplateType[TemplateType[\"Top\"] = 1] = \"Top\";\n /**\n * Specifies the type of `Bottom`.\n * @private\n */\n TemplateType[TemplateType[\"Bottom\"] = 2] = \"Bottom\";\n /**\n * Specifies the type of `Left`.\n * @private\n */\n TemplateType[TemplateType[\"Left\"] = 3] = \"Left\";\n /**\n * Specifies the type of `Right`.\n * @private\n */\n TemplateType[TemplateType[\"Right\"] = 4] = \"Right\";\n})(TemplateType || (TemplateType = {}));\n","import { ObjectStatus } from './../input-output/enum';\nimport { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { DictionaryProperties } from './pdf-dictionary-properties';\nimport { Operators } from './pdf-operators';\nimport { Dictionary } from './../collections/dictionary';\nimport { PdfReference } from './../primitives/pdf-reference';\nimport { ObjectType } from './cross-table';\nimport { PdfStream } from './../primitives/pdf-stream';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { PdfCatalog } from './../document/pdf-catalog';\n/**\n * `PdfCrossTable` is responsible for intermediate level parsing\n * and savingof a PDF document.\n * @private\n */\nvar PdfCrossTable = /** @class */ (function () {\n function PdfCrossTable() {\n /**\n * The modified `objects` that should be saved.\n * @private\n */\n this.objects = new Dictionary();\n /**\n * Holds `maximal generation number` or offset to object.\n * @default 0\n * @private\n */\n this.maxGenNumIndex = 0;\n /**\n * The `number of the objects`.\n * @default 0\n * @private\n */\n this.objectCount = 0;\n /**\n * Internal variable for accessing fields from `DictionryProperties` class.\n * @default new PdfDictionaryProperties()\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n }\n Object.defineProperty(PdfCrossTable.prototype, \"isMerging\", {\n //Properties\n /**\n * Gets or sets if the document `is merged`.\n * @private\n */\n get: function () {\n return this.merging;\n },\n set: function (value) {\n this.merging = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCrossTable.prototype, \"trailer\", {\n /**\n * Gets the `trailer`.\n * @private\n */\n get: function () {\n if (this.internalTrailer == null) {\n this.internalTrailer = new PdfStream();\n }\n return this.internalTrailer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCrossTable.prototype, \"document\", {\n /**\n * Gets or sets the main `PdfDocument` class instance.\n * @private\n */\n get: function () {\n return this.pdfDocument;\n },\n set: function (value) {\n this.pdfDocument = value;\n this.items = this.pdfDocument.pdfObjects;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCrossTable.prototype, \"pdfObjects\", {\n /**\n * Gets the catched `PDF object` main collection.\n * @private\n */\n get: function () {\n return this.items;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCrossTable.prototype, \"objectCollection\", {\n /**\n * Gets the `object collection`.\n * @private\n */\n get: function () {\n return this.pdfDocument.pdfObjects;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCrossTable.prototype, \"count\", {\n /**\n * Gets or sets the `number of the objects` within the document.\n * @private\n */\n get: function () {\n return this.objectCount;\n },\n set: function (value) {\n this.objectCount = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCrossTable.prototype, \"nextObjNumber\", {\n /**\n * Returns `next available object number`.\n * @private\n */\n get: function () {\n this.count = this.count + 1;\n return this.count;\n },\n enumerable: true,\n configurable: true\n });\n PdfCrossTable.prototype.save = function (writer, filename) {\n this.saveHead(writer);\n var state = false;\n this.mappedReferences = null;\n this.objects.clear();\n this.markTrailerReferences();\n this.saveObjects(writer);\n var saveCount = this.count;\n var xrefPos = writer.position;\n this.registerObject(0, new PdfReference(0, -1), true);\n var prevXRef = 0;\n writer.write(Operators.xref);\n writer.write(Operators.newLine);\n this.saveSections(writer);\n this.saveTrailer(writer, this.count, prevXRef);\n this.saveTheEndess(writer, xrefPos);\n this.count = saveCount;\n for (var i = 0; i < this.objectCollection.count; ++i) {\n var oi = this.objectCollection.items(i);\n oi.object.isSaving = false;\n }\n if (typeof filename === 'undefined') {\n return writer.stream.buffer;\n }\n else {\n writer.stream.save(filename);\n }\n };\n /**\n * `Saves the endess` of the file.\n * @private\n */\n PdfCrossTable.prototype.saveTheEndess = function (writer, xrefPos) {\n writer.write(Operators.newLine + Operators.startxref + Operators.newLine);\n writer.write(xrefPos.toString() + Operators.newLine);\n writer.write(Operators.eof + Operators.newLine);\n };\n /**\n * `Saves the new trailer` dictionary.\n * @private\n */\n PdfCrossTable.prototype.saveTrailer = function (writer, count, prevXRef) {\n writer.write(Operators.trailer + Operators.newLine);\n // Save the dictionary.\n var trailer = this.trailer;\n trailer.items.setValue(this.dictionaryProperties.size, new PdfNumber(this.objectCount + 1));\n trailer = new PdfDictionary(trailer); // Make it real dictionary.\n trailer.setEncrypt(false);\n trailer.save(writer);\n };\n /**\n * `Saves the xref section`.\n * @private\n */\n PdfCrossTable.prototype.saveSections = function (writer) {\n var objectNum = 0;\n var count = 0;\n do {\n count = this.prepareSubsection(objectNum);\n this.saveSubsection(writer, objectNum, count);\n objectNum += count;\n } while (count !== 0);\n };\n /**\n * `Saves a subsection`.\n * @private\n */\n PdfCrossTable.prototype.saveSubsection = function (writer, objectNum, count) {\n if (count <= 0 || objectNum >= this.count) {\n return;\n }\n var subsectionHead = '{0} {1}{2}';\n writer.write(objectNum + ' ' + (count + 1) + Operators.newLine);\n for (var i = objectNum; i <= objectNum + count; ++i) {\n var obj = this.objects.getValue(i);\n var str = '';\n if (obj.type === ObjectType.Free) {\n str = this.getItem(obj.offset, 65535, true);\n }\n else {\n str = this.getItem(obj.offset, obj.generation, false);\n }\n writer.write(str);\n }\n };\n /**\n * Generates string for `xref table item`.\n * @private\n */\n PdfCrossTable.prototype.getItem = function (offset, genNumber, isFree) {\n var returnString = '';\n var addOffsetLength = 10 - offset.toString().length;\n if (genNumber <= 0) {\n genNumber = 0;\n }\n var addGenNumberLength = (5 - genNumber.toString().length) <= 0 ? 0 : (5 - genNumber.toString().length);\n for (var index = 0; index < addOffsetLength; index++) {\n returnString = returnString + '0';\n }\n returnString = returnString + offset.toString() + ' ';\n for (var index = 0; index < addGenNumberLength; index++) {\n returnString = returnString + '0';\n }\n returnString = returnString + genNumber.toString() + ' ';\n returnString = returnString + ((isFree) ? Operators.f : Operators.n) + Operators.newLine;\n return returnString;\n };\n /**\n * `Prepares a subsection` of the current section within the cross-reference table.\n * @private\n */\n PdfCrossTable.prototype.prepareSubsection = function (objectNum) {\n var count = 0;\n var i;\n var total = this.count;\n for (var k = 0; k < this.document.pdfObjects.count; k++) {\n var reference = this.document.pdfObjects.items(k).reference;\n var refString = reference.toString();\n var refArray = refString.split(' ');\n }\n if (objectNum >= total) {\n return count;\n }\n // search for first changed indirect object.\n for (i = objectNum; i < total; ++i) {\n break;\n }\n objectNum = i;\n // look up for all indirect objects in one subsection.\n for (; i < total; ++i) {\n ++count;\n }\n return count;\n };\n /**\n * `Marks the trailer references` being saved.\n * @private\n */\n PdfCrossTable.prototype.markTrailerReferences = function () {\n var tempArray;\n var keys = this.trailer.items.keys();\n var values = this.trailer.items.values();\n };\n /**\n * `Saves the head`.\n * @private\n */\n PdfCrossTable.prototype.saveHead = function (writer) {\n var version = this.generateFileVersion(writer.document);\n writer.write('%PDF-' + version);\n writer.write(Operators.newLine);\n };\n /**\n * Generates the `version` of the file.\n * @private\n */\n PdfCrossTable.prototype.generateFileVersion = function (document) {\n var iVersion = 4;\n var version = '1.' + iVersion.toString();\n return version;\n };\n PdfCrossTable.prototype.getReference = function (obj, bNew) {\n if (typeof bNew === 'undefined') {\n var wasNew = false;\n return this.getReference(obj, wasNew);\n }\n else {\n //code splitted for reducing lines of code exceeds 100.\n return this.getSubReference(obj, bNew);\n }\n };\n /**\n * Retrieves the `reference` of the object given.\n * @private\n */\n PdfCrossTable.prototype.getSubReference = function (obj, bNew) {\n var isNew = false;\n var wasNew;\n var reference = null;\n // if (obj.IsSaving) {\n if (this.items.count > 0 && obj.objectCollectionIndex > 0 && this.items.count > obj.objectCollectionIndex - 1) {\n var tempObj = this.document.pdfObjects.getReference(obj, wasNew);\n reference = tempObj.reference;\n wasNew = tempObj.wasNew;\n }\n if (reference == null) {\n if (obj.status === ObjectStatus.Registered) {\n wasNew = false;\n }\n else {\n wasNew = true;\n }\n }\n else {\n wasNew = false;\n }\n // need to add mapped reference code\n if (reference == null) {\n var objnumber = this.nextObjNumber;\n reference = new PdfReference(objnumber, 0);\n var found = void 0;\n if (wasNew) {\n this.document.pdfObjects.add(obj);\n this.document.pdfObjects.trySetReference(obj, reference, found);\n var tempIndex = this.document.pdfObjects.count - 1;\n var tempkey = this.document.pdfObjects.objectCollections[tempIndex].reference.objNumber;\n var tempvalue = this.document.pdfObjects.objectCollections[this.document.pdfObjects.count - 1];\n this.document.pdfObjects.mainObjectCollection.setValue(tempkey, tempvalue);\n obj.position = -1;\n }\n else {\n this.document.pdfObjects.trySetReference(obj, reference, found);\n }\n obj.objectCollectionIndex = reference.objNumber;\n obj.status = ObjectStatus.None;\n isNew = true;\n }\n bNew = isNew || this.bForceNew;\n return reference;\n };\n /**\n * `Saves all objects` in the collection.\n * @private\n */\n PdfCrossTable.prototype.saveObjects = function (writer) {\n var objectCollection = this.objectCollection;\n for (var i = 0; i < objectCollection.count; ++i) {\n var oi = objectCollection.items(i);\n var obj = oi.object;\n obj.isSaving = true;\n this.saveIndirectObject(obj, writer);\n }\n };\n /**\n * `Saves indirect object`.\n * @private\n */\n PdfCrossTable.prototype.saveIndirectObject = function (obj, writer) {\n var reference = this.getReference(obj);\n if (obj instanceof PdfCatalog) {\n this.trailer.items.setValue(this.dictionaryProperties.root, reference);\n }\n // NOTE : This is needed for correct string objects encryption.\n this.pdfDocument.currentSavingObj = reference;\n var tempArchive = false;\n tempArchive = obj.getArchive();\n var allowedType = !((obj instanceof PdfStream) || !tempArchive || (obj instanceof PdfCatalog));\n var sigFlag = false;\n this.registerObject(writer.position, reference);\n this.doSaveObject(obj, reference, writer);\n };\n /**\n * Performs `real saving` of the save object.\n * @private\n */\n PdfCrossTable.prototype.doSaveObject = function (obj, reference, writer) {\n var correctPosition = writer.length;\n writer.write(reference.objNumber.toString());\n writer.write(Operators.whiteSpace);\n writer.write(reference.genNumber.toString());\n writer.write(Operators.whiteSpace);\n writer.write(Operators.obj);\n writer.write(Operators.newLine);\n obj.save(writer);\n var stream = writer.stream;\n writer.write(Operators.endObj);\n writer.write(Operators.newLine);\n };\n PdfCrossTable.prototype.registerObject = function (offset, reference, free) {\n if (typeof free === 'boolean') {\n // Register the object by its number.\n this.objects.setValue(reference.objNumber, new RegisteredObject(offset, reference, free));\n this.maxGenNumIndex = Math.max(this.maxGenNumIndex, reference.genNumber);\n }\n else if (typeof free === 'undefined') {\n // Register the object by its number.\n this.objects.setValue(reference.objNumber, new RegisteredObject(offset, reference));\n this.maxGenNumIndex = Math.max(this.maxGenNumIndex, reference.genNumber);\n }\n };\n /**\n * `Dereferences` the specified primitive object.\n * @private\n */\n PdfCrossTable.dereference = function (obj) {\n var rh = obj;\n if (rh != null) {\n obj = rh.object;\n }\n return obj;\n };\n return PdfCrossTable;\n}());\nexport { PdfCrossTable };\nvar RegisteredObject = /** @class */ (function () {\n function RegisteredObject(offset, reference, free) {\n if (typeof free === 'undefined') {\n var tempOffset = offset;\n this.offsetNumber = tempOffset;\n var tempReference = reference;\n this.generation = tempReference.genNumber;\n this.object = tempReference.objNumber;\n this.type = ObjectType.Normal;\n }\n else {\n var tempOffset = offset;\n var tempReference = reference;\n this.constructor(tempOffset, tempReference);\n var tempFree = free;\n this.type = ObjectType.Free;\n }\n }\n Object.defineProperty(RegisteredObject.prototype, \"objectNumber\", {\n //Properties\n /**\n * Gets the `object number`.\n * @private\n */\n get: function () {\n return this.object;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RegisteredObject.prototype, \"offset\", {\n /**\n * Gets the `offset`.\n * @private\n */\n get: function () {\n var result;\n result = this.offsetNumber;\n return result;\n },\n enumerable: true,\n configurable: true\n });\n return RegisteredObject;\n}());\nexport { RegisteredObject };\n","/**\n * PdfPageSize.ts class for EJ2-PDF\n */\nimport { SizeF } from './../drawing/pdf-drawing';\n/**\n * Represents information about various predefined `page sizes`.\n */\nvar PdfPageSize = /** @class */ (function () {\n //constructor\n /**\n * Initialize an instance for `PdfPageSize` class.\n * @private\n */\n function PdfPageSize() {\n // \n }\n /**\n * Specifies the size of `letter`.\n * @private\n */\n PdfPageSize.letter = new SizeF(612, 792);\n /**\n * Specifies the size of `note`.\n * @private\n */\n PdfPageSize.note = new SizeF(540, 720);\n /**\n * Specifies the size of `legal`.\n * @private\n */\n PdfPageSize.legal = new SizeF(612, 1008);\n /**\n * Specifies the size of `a0`.\n * @private\n */\n PdfPageSize.a0 = new SizeF(2380, 3368);\n /**\n * Specifies the size of `a1`.\n * @private\n */\n PdfPageSize.a1 = new SizeF(1684, 2380);\n /**\n * Specifies the size of `a2`.\n * @private\n */\n PdfPageSize.a2 = new SizeF(1190, 1684);\n /**\n * Specifies the size of `a3`.\n * @private\n */\n PdfPageSize.a3 = new SizeF(842, 1190);\n /**\n * Specifies the size of `a4`.\n * @private\n */\n PdfPageSize.a4 = new SizeF(595, 842);\n /**\n * Specifies the size of `a5`.\n * @private\n */\n PdfPageSize.a5 = new SizeF(421, 595);\n /**\n * Specifies the size of `a6`.\n * @private\n */\n PdfPageSize.a6 = new SizeF(297, 421);\n /**\n * Specifies the size of `a7`.\n * @private\n */\n PdfPageSize.a7 = new SizeF(210, 297);\n /**\n * Specifies the size of `a8`.\n * @private\n */\n PdfPageSize.a8 = new SizeF(148, 210);\n /**\n * Specifies the size of `a9`.\n * @private\n */\n PdfPageSize.a9 = new SizeF(105, 148);\n /**\n * Specifies the size of `a10`.\n * @private\n */\n PdfPageSize.a10 = new SizeF(74, 105);\n /**\n * Specifies the size of `b0`.\n * @private\n */\n PdfPageSize.b0 = new SizeF(2836, 4008);\n /**\n * Specifies the size of `b1`.\n * @private\n */\n PdfPageSize.b1 = new SizeF(2004, 2836);\n /**\n * Specifies the size of `b2`.\n * @private\n */\n PdfPageSize.b2 = new SizeF(1418, 2004);\n /**\n * Specifies the size of `b3`.\n * @private\n */\n PdfPageSize.b3 = new SizeF(1002, 1418);\n /**\n * Specifies the size of `b4`.\n * @private\n */\n PdfPageSize.b4 = new SizeF(709, 1002);\n /**\n * Specifies the size of `b5`.\n * @private\n */\n PdfPageSize.b5 = new SizeF(501, 709);\n /**\n * Specifies the size of `archE`.\n * @private\n */\n PdfPageSize.archE = new SizeF(2592, 3456);\n /**\n * Specifies the size of `archD`.\n * @private\n */\n PdfPageSize.archD = new SizeF(1728, 2592);\n /**\n * Specifies the size of `archC`.\n * @private\n */\n PdfPageSize.archC = new SizeF(1296, 1728);\n /**\n * Specifies the size of `archB`.\n * @private\n */\n PdfPageSize.archB = new SizeF(864, 1296);\n /**\n * Specifies the size of `archA`.\n * @private\n */\n PdfPageSize.archA = new SizeF(648, 864);\n /**\n * Specifies the size of `flsa`.\n * @private\n */\n PdfPageSize.flsa = new SizeF(612, 936);\n /**\n * Specifies the size of `halfLetter`.\n * @private\n */\n PdfPageSize.halfLetter = new SizeF(396, 612);\n /**\n * Specifies the size of `letter11x17`.\n * @private\n */\n PdfPageSize.letter11x17 = new SizeF(792, 1224);\n /**\n * Specifies the size of `ledger`.\n * @private\n */\n PdfPageSize.ledger = new SizeF(1224, 792);\n return PdfPageSize;\n}());\nexport { PdfPageSize };\n","/**\n * PdfMargins.ts class for EJ2-PDF\n * A class representing PDF page margins.\n */\nvar PdfMargins = /** @class */ (function () {\n /**\n * Initializes a new instance of the `PdfMargins` class.\n * @private\n */\n function PdfMargins() {\n /**\n * Represents the `Default Page Margin` value.\n * @default 0.0\n * @private\n */\n this.pdfMargin = 40.0;\n this.setMargins(this.pdfMargin);\n }\n Object.defineProperty(PdfMargins.prototype, \"left\", {\n //Properties\n /**\n * Gets or sets the `left margin` size.\n * @private\n */\n get: function () {\n return this.leftMargin;\n },\n set: function (value) {\n this.leftMargin = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfMargins.prototype, \"top\", {\n /**\n * Gets or sets the `top margin` size.\n * @private\n */\n get: function () {\n return this.topMargin;\n },\n set: function (value) {\n this.topMargin = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfMargins.prototype, \"right\", {\n /**\n * Gets or sets the `right margin` size.\n * @private\n */\n get: function () {\n return this.rightMargin;\n },\n set: function (value) {\n this.rightMargin = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfMargins.prototype, \"bottom\", {\n /**\n * Gets or sets the `bottom margin` size.\n * @private\n */\n get: function () {\n return this.bottomMargin;\n },\n set: function (value) {\n this.bottomMargin = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfMargins.prototype, \"all\", {\n /**\n * Sets the `margins`.\n * @private\n */\n set: function (value) {\n this.setMargins(value);\n },\n enumerable: true,\n configurable: true\n });\n PdfMargins.prototype.setMargins = function (margin1, margin2, margin3, margin4) {\n if (typeof margin2 === 'undefined') {\n this.leftMargin = this.topMargin = this.rightMargin = this.bottomMargin = margin1;\n }\n else {\n if (typeof margin3 === 'undefined') {\n this.leftMargin = this.rightMargin = margin1;\n this.bottomMargin = this.topMargin = margin2;\n }\n else {\n this.leftMargin = margin1;\n this.topMargin = margin2;\n this.rightMargin = margin3;\n this.bottomMargin = margin4;\n }\n }\n };\n /**\n * `Clones` the object.\n * @private\n */\n PdfMargins.prototype.clone = function () {\n return this;\n };\n return PdfMargins;\n}());\nexport { PdfMargins };\n","/**\n * ImageDecoder class\n */\nimport { ByteArray } from './byte-array';\nimport { PdfStream } from './../../primitives/pdf-stream';\nimport { DictionaryProperties } from './../../input-output/pdf-dictionary-properties';\nimport { PdfName } from './../../primitives/pdf-name';\nimport { PdfNumber } from './../../primitives/pdf-number';\nimport { PdfBoolean } from './../../primitives/pdf-boolean';\nimport { PdfDictionary } from './../../primitives/pdf-dictionary';\n/**\n * Specifies the image `format`.\n * @private\n */\nexport var ImageFormat;\n(function (ImageFormat) {\n /**\n * Specifies the type of `Unknown`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * Specifies the type of `Bmp`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Bmp\"] = 1] = \"Bmp\";\n /**\n * Specifies the type of `Emf`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Emf\"] = 2] = \"Emf\";\n /**\n * Specifies the type of `Gif`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Gif\"] = 3] = \"Gif\";\n /**\n * Specifies the type of `Jpeg`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Jpeg\"] = 4] = \"Jpeg\";\n /**\n * Specifies the type of `Png`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Png\"] = 5] = \"Png\";\n /**\n * Specifies the type of `Wmf`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Wmf\"] = 6] = \"Wmf\";\n /**\n * Specifies the type of `Icon`.\n * @hidden\n * @private\n */\n ImageFormat[ImageFormat[\"Icon\"] = 7] = \"Icon\";\n})(ImageFormat || (ImageFormat = {}));\n/**\n * `Decode the image stream`.\n * @private\n */\nvar ImageDecoder = /** @class */ (function () {\n /**\n * Initialize the new instance for `image-decoder` class.\n * @private\n */\n function ImageDecoder(stream) {\n /**\n * Specifies `format` of image.\n * @hidden\n * @private\n */\n this.mFormat = ImageFormat.Unknown;\n /**\n * `Bits per component`.\n * @default 8\n * @hidden\n * @private\n */\n this.mbitsPerComponent = 8;\n /**\n * Internal variable for accessing fields from `DictionryProperties` class.\n * @hidden\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n this.mStream = stream;\n this.initialize();\n }\n Object.defineProperty(ImageDecoder.prototype, \"height\", {\n /**\n * Gets the `height` of image.\n * @hidden\n * @private\n */\n get: function () {\n return this.mHeight;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageDecoder.prototype, \"width\", {\n /**\n * Gets the `width` of image.\n * @hidden\n * @private\n */\n get: function () {\n return this.mWidth;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageDecoder.prototype, \"bitsPerComponent\", {\n /**\n * Gets `bits per component`.\n * @hidden\n * @private\n */\n get: function () {\n return this.mbitsPerComponent;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageDecoder.prototype, \"size\", {\n /**\n * Gets the `size` of an image data.\n * @hidden\n * @private\n */\n get: function () {\n return this.mImageData.count;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageDecoder.prototype, \"imageData\", {\n /**\n * Gets the value of an `image data`.\n * @hidden\n * @private\n */\n get: function () {\n return this.mImageData;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageDecoder.prototype, \"imageDataAsNumberArray\", {\n /**\n * Gets the value of an `image data as number array`.\n * @hidden\n * @private\n */\n get: function () {\n return this.mImageData.internalBuffer.buffer;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Initialize` image data and image stream.\n * @hidden\n * @private\n */\n ImageDecoder.prototype.initialize = function () {\n if (this.mFormat === ImageFormat.Unknown && this.checkIfJpeg()) {\n this.mFormat = ImageFormat.Jpeg;\n this.parseJpegImage();\n }\n this.reset();\n this.mImageData = new ByteArray(this.mStream.count);\n this.mStream.read(this.mImageData, 0, this.mImageData.count);\n };\n /**\n * `Reset` stream position into 0.\n * @hidden\n * @private\n */\n ImageDecoder.prototype.reset = function () {\n this.mStream.position = 0;\n };\n /**\n * `Parse` Jpeg image.\n * @hidden\n * @private\n */\n ImageDecoder.prototype.parseJpegImage = function () {\n this.reset();\n var imgData = new ByteArray(this.mStream.count);\n this.mStream.read(imgData, 0, imgData.count);\n var i = 4;\n /* tslint:disable */\n if (String.fromCharCode(imgData.getBuffer(i + 2)) === 'J' && String.fromCharCode(imgData.getBuffer(i + 3)) === 'F' && String.fromCharCode(imgData.getBuffer(i + 4)) === 'I' && String.fromCharCode(imgData.getBuffer(i + 5)) === 'F' && imgData.getBuffer(i + 6) === 0) {\n var length_1 = imgData.getBuffer(i) * 256 + imgData.getBuffer(i + 1);\n while (i + length_1 < imgData.count) {\n i += length_1;\n if (imgData.getBuffer(i + 1) === 192) {\n this.mHeight = imgData.getBuffer(i + 5) * 256 + imgData.getBuffer(i + 6);\n this.mWidth = imgData.getBuffer(i + 7) * 256 + imgData.getBuffer(i + 8);\n return;\n }\n else {\n i += 2;\n length_1 = imgData.getBuffer(i) * 256 + imgData.getBuffer(i + 1);\n }\n }\n }\n /* tslint:enable */\n };\n Object.defineProperty(ImageDecoder.prototype, \"format\", {\n /**\n * Gets the image `format`.\n * @private\n * @hidden\n */\n get: function () {\n return this.mFormat;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Checks if JPG`.\n * @private\n * @hidden\n */\n ImageDecoder.prototype.checkIfJpeg = function () {\n this.reset();\n for (var i = 0; i < ImageDecoder.mJpegHeader.length; i++) {\n if (ImageDecoder.mJpegHeader[i] !== this.mStream.readByte(i)) {\n return false;\n }\n this.mStream.position++;\n }\n return true;\n };\n /**\n * Return image `dictionary`.\n * @hidden\n * @private\n */\n ImageDecoder.prototype.getImageDictionary = function () {\n if (this.mFormat === ImageFormat.Jpeg) {\n var tempArrayBuffer = this.imageData.internalBuffer.length;\n this.imageStream = new PdfStream();\n this.imageStream.isImage = true;\n var tempString = '';\n var decodedString = '';\n for (var i = 0; i < this.imageDataAsNumberArray.byteLength; i++) {\n tempString += String.fromCharCode(null, this.mStream.readByte(i));\n }\n for (var i = 0; i < tempString.length; i++) {\n if (i % 2 !== 0) {\n decodedString += tempString[i];\n }\n }\n this.imageStream.data = [decodedString];\n this.imageStream.compress = false;\n this.imageStream.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.xObject));\n this.imageStream.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.image));\n this.imageStream.items.setValue(this.dictionaryProperties.width, new PdfNumber(this.width));\n this.imageStream.items.setValue(this.dictionaryProperties.height, new PdfNumber(this.height));\n this.imageStream.items.setValue(this.dictionaryProperties.bitsPerComponent, new PdfNumber(this.bitsPerComponent));\n this.imageStream.items.setValue(this.dictionaryProperties.filter, new PdfName(this.dictionaryProperties.dctdecode));\n this.imageStream.items.setValue(this.dictionaryProperties.colorSpace, new PdfName(this.getColorSpace()));\n this.imageStream.items.setValue(this.dictionaryProperties.decodeParms, this.getDecodeParams());\n return this.imageStream;\n }\n else {\n return this.imageStream;\n }\n };\n /**\n * Return `colorSpace` of an image.\n * @hidden\n * @private\n */\n ImageDecoder.prototype.getColorSpace = function () {\n return this.dictionaryProperties.deviceRgb;\n };\n /**\n * Return `decode parameters` of an image.\n * @hidden\n * @private\n */\n ImageDecoder.prototype.getDecodeParams = function () {\n var decodeParams = new PdfDictionary();\n decodeParams.items.setValue(this.dictionaryProperties.columns, new PdfNumber(this.width));\n decodeParams.items.setValue(this.dictionaryProperties.blackIs1, new PdfBoolean(true));\n decodeParams.items.setValue(this.dictionaryProperties.k, new PdfNumber(-1));\n decodeParams.items.setValue(this.dictionaryProperties.predictor, new PdfNumber(15));\n decodeParams.items.setValue(this.dictionaryProperties.bitsPerComponent, new PdfNumber(this.bitsPerComponent));\n return decodeParams;\n };\n /**\n * Number array for `png header`.\n * @hidden\n * @private\n */\n ImageDecoder.mPngHeader = [137, 80, 78, 71, 13, 10, 26, 10];\n /**\n * Number Array for `jpeg header`.\n * @hidden\n * @private\n */\n ImageDecoder.mJpegHeader = [255, 216];\n /**\n * Number array for `gif header`.\n * @hidden\n * @private\n */\n ImageDecoder.GIF_HEADER = 'G,I,F,8';\n /**\n * Number array for `bmp header.`\n * @hidden\n * @private\n */\n ImageDecoder.BMP_HEADER = 'B,M';\n return ImageDecoder;\n}());\nexport { ImageDecoder };\n","/**\n * PdfPageSettings.ts class for EJ2-PDF\n */\nimport { SizeF, PointF } from './../drawing/pdf-drawing';\nimport { PdfPageSize } from './pdf-page-size';\nimport { PdfPageRotateAngle, PdfPageOrientation } from './enum';\nimport { PdfMargins } from './../graphics/pdf-margins';\n/**\n * The class provides various `setting` related with PDF pages.\n */\nvar PdfPageSettings = /** @class */ (function () {\n function PdfPageSettings(margins) {\n //Fields\n /**\n * The page `margins`.\n * @private\n */\n this.pageMargins = new PdfMargins();\n /**\n * The page `size`.\n * @default a4\n * @private\n */\n this.pageSize = PdfPageSize.a4;\n /**\n * The page `rotation angle`.\n * @default PdfPageRotateAngle.RotateAngle0\n * @private\n */\n this.rotateAngle = PdfPageRotateAngle.RotateAngle0;\n /**\n * The page `orientation`.\n * @default PdfPageOrientation.Portrait\n * @private\n */\n this.pageOrientation = PdfPageOrientation.Portrait;\n /**\n * The page `origin`.\n * @default 0,0\n * @private\n */\n this.pageOrigin = new PointF(0, 0);\n /**\n * Checks the Whether the `rotation` is applied or not.\n * @default false\n * @private\n */\n this.isRotation = false;\n if (typeof margins === 'number') {\n this.pageMargins.setMargins(margins);\n }\n }\n Object.defineProperty(PdfPageSettings.prototype, \"size\", {\n //Properties\n /**\n * Gets or sets the `size` of the page.\n * @private\n */\n get: function () {\n return this.pageSize;\n },\n set: function (value) {\n this.setSize(value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageSettings.prototype, \"orientation\", {\n /**\n * Gets or sets the page `orientation`.\n * @private\n */\n get: function () {\n return this.pageOrientation;\n },\n set: function (orientation) {\n if (this.pageOrientation !== orientation) {\n this.pageOrientation = orientation;\n this.updateSize(orientation);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageSettings.prototype, \"margins\", {\n /**\n * Gets or sets the `margins` of the page.\n * @private\n */\n get: function () {\n return this.pageMargins;\n },\n set: function (value) {\n this.pageMargins = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageSettings.prototype, \"width\", {\n /**\n * Gets or sets the `width` of the page.\n * @private\n */\n get: function () {\n return this.pageSize.width;\n },\n set: function (value) {\n this.pageSize.width = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageSettings.prototype, \"height\", {\n /**\n * Gets or sets the `height` of the page.\n * @private\n */\n get: function () {\n return this.pageSize.height;\n },\n set: function (value) {\n this.pageSize.height = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageSettings.prototype, \"origin\", {\n /**\n * Gets or sets the `origin` of the page.\n * @private\n */\n get: function () {\n return this.pageOrigin;\n },\n set: function (value) {\n this.pageOrigin = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageSettings.prototype, \"rotate\", {\n /**\n * Gets or sets the number of degrees by which the page should be `rotated` clockwise when displayed or printed.\n * @private\n */\n get: function () {\n return this.rotateAngle;\n },\n set: function (value) {\n this.rotateAngle = value;\n this.isRotation = true;\n },\n enumerable: true,\n configurable: true\n });\n //Methods\n /**\n * `Update page size` depending on orientation.\n * @private\n */\n PdfPageSettings.prototype.updateSize = function (orientation) {\n var min = Math.min(this.pageSize.width, this.pageSize.height);\n var max = Math.max(this.pageSize.width, this.pageSize.height);\n switch (orientation) {\n case PdfPageOrientation.Portrait:\n this.pageSize = new SizeF(min, max);\n break;\n case PdfPageOrientation.Landscape:\n this.pageSize = new SizeF(max, min);\n break;\n }\n };\n /**\n * Creates a `clone` of the object.\n * @private\n */\n PdfPageSettings.prototype.clone = function () {\n var settings = this;\n settings.pageMargins = this.pageMargins.clone();\n // if (GetTransition() != null)\n // {\n // settings.Transition = (PdfPageTransition)Transition.clone();\n // }\n return settings;\n };\n /**\n * Returns `size`, shrinked by the margins.\n * @private\n */\n PdfPageSettings.prototype.getActualSize = function () {\n var width = this.width - (this.margins.left + this.margins.right);\n var height = this.height - (this.margins.top + this.margins.bottom);\n var size = new SizeF(width, height);\n return size;\n };\n /**\n * Sets `size` to the page aaccording to the orientation.\n * @private\n */\n PdfPageSettings.prototype.setSize = function (size) {\n var min = Math.min(size.width, size.height);\n var max = Math.max(size.width, size.height);\n if (this.orientation === PdfPageOrientation.Portrait) {\n this.pageSize = new SizeF(min, max);\n }\n else {\n this.pageSize = new SizeF(max, min);\n }\n };\n return PdfPageSettings;\n}());\nexport { PdfPageSettings };\n","import { Operators } from './pdf-operators';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { PointF, RectangleF } from './../drawing/pdf-drawing';\nimport { PdfString } from './../primitives/pdf-string';\nimport { PdfName } from './../primitives/pdf-name';\n/**\n * Helper class to `write PDF graphic streams` easily.\n * @private\n */\nvar PdfStreamWriter = /** @class */ (function () {\n /**\n * Initialize an instance of `PdfStreamWriter` class.\n * @private\n */\n function PdfStreamWriter(stream) {\n if (stream == null) {\n throw new Error('ArgumentNullException:stream');\n }\n this.stream = stream;\n }\n //Implementation\n /**\n * `Clear` the stream.\n * @public\n */\n PdfStreamWriter.prototype.clear = function () {\n this.stream.clearStream();\n };\n PdfStreamWriter.prototype.setGraphicsState = function (dictionaryName) {\n if (dictionaryName instanceof PdfName) {\n this.stream.write(dictionaryName.toString());\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setGraphicsState);\n }\n else {\n this.stream.write(Operators.slash);\n this.stream.write(dictionaryName);\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setGraphicsState);\n }\n };\n /**\n * `Executes the XObject`.\n * @private\n */\n PdfStreamWriter.prototype.executeObject = function (name) {\n this.stream.write(name.toString());\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.paintXObject);\n this.stream.write(Operators.newLine);\n };\n /**\n * `Closes path object`.\n * @private\n */\n PdfStreamWriter.prototype.closePath = function () {\n this.writeOperator(Operators.closePath);\n };\n /**\n * `Clips the path`.\n * @private\n */\n PdfStreamWriter.prototype.clipPath = function (useEvenOddRule) {\n this.stream.write(Operators.clipPath);\n if (useEvenOddRule) {\n this.stream.write(Operators.evenOdd);\n }\n this.stream.write(Operators.whiteSpace);\n this.stream.write(Operators.endPath);\n this.stream.write(Operators.newLine);\n };\n /**\n * `Closes, then fills and strokes the path`.\n * @private\n */\n PdfStreamWriter.prototype.closeFillStrokePath = function (useEvenOddRule) {\n this.stream.write(Operators.closeFillStrokePath);\n if (useEvenOddRule) {\n this.stream.write(Operators.evenOdd);\n this.stream.write(Operators.newLine);\n }\n else {\n this.stream.write(Operators.newLine);\n }\n };\n /**\n * `Fills and strokes path`.\n * @private\n */\n PdfStreamWriter.prototype.fillStrokePath = function (useEvenOddRule) {\n this.stream.write(Operators.fillStroke);\n if (useEvenOddRule) {\n this.stream.write(Operators.evenOdd);\n this.stream.write(Operators.newLine);\n }\n else {\n this.stream.write(Operators.newLine);\n }\n };\n /**\n * `Fills path`.\n * @private\n */\n PdfStreamWriter.prototype.fillPath = function (useEvenOddRule) {\n this.stream.write(Operators.fill);\n if (useEvenOddRule) {\n this.stream.write(Operators.evenOdd);\n this.stream.write(Operators.newLine);\n }\n else {\n this.stream.write(Operators.newLine);\n }\n };\n /**\n * `Ends the path`.\n * @private\n */\n PdfStreamWriter.prototype.endPath = function () {\n this.writeOperator(Operators.n);\n };\n /**\n * `Closes and fills the path`.\n * @private\n */\n PdfStreamWriter.prototype.closeFillPath = function (useEvenOddRule) {\n this.writeOperator(Operators.closePath);\n this.stream.write(Operators.fill);\n if (useEvenOddRule) {\n this.stream.write(Operators.evenOdd);\n this.stream.write(Operators.newLine);\n }\n else {\n this.stream.write(Operators.newLine);\n }\n };\n /**\n * `Closes and strokes the path`.\n * @private\n */\n PdfStreamWriter.prototype.closeStrokePath = function () {\n this.writeOperator(Operators.closeStrokePath);\n };\n /**\n * `Sets the text scaling`.\n * @private\n */\n PdfStreamWriter.prototype.setTextScaling = function (textScaling) {\n this.stream.write(PdfNumber.floatToString(textScaling));\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setTextScaling);\n };\n /**\n * `Strokes path`.\n * @private\n */\n PdfStreamWriter.prototype.strokePath = function () {\n this.writeOperator(Operators.stroke);\n };\n /**\n * `Restores` the graphics state.\n * @private\n */\n PdfStreamWriter.prototype.restoreGraphicsState = function () {\n this.writeOperator(Operators.restoreState);\n };\n /**\n * `Saves` the graphics state.\n * @private\n */\n PdfStreamWriter.prototype.saveGraphicsState = function () {\n this.writeOperator(Operators.saveState);\n };\n PdfStreamWriter.prototype.startNextLine = function (arg1, arg2) {\n if (typeof arg1 === 'undefined') {\n this.writeOperator(Operators.goToNextLine);\n }\n else if (arg1 instanceof PointF) {\n this.writePoint(arg1);\n this.writeOperator(Operators.setCoords);\n }\n else {\n this.writePoint(arg1, arg2);\n this.writeOperator(Operators.setCoords);\n }\n };\n /**\n * Shows the `text`.\n * @private\n */\n PdfStreamWriter.prototype.showText = function (text) {\n this.checkTextParam(text);\n this.writeText(text);\n this.writeOperator(Operators.setText);\n };\n /**\n * Sets `text leading`.\n * @private\n */\n PdfStreamWriter.prototype.setLeading = function (leading) {\n this.stream.write(PdfNumber.floatToString(leading));\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setTextLeading);\n };\n /**\n * `Begins the path`.\n * @private\n */\n PdfStreamWriter.prototype.beginPath = function (x, y) {\n this.writePoint(x, y);\n this.writeOperator(Operators.beginPath);\n };\n /**\n * `Begins text`.\n * @private\n */\n PdfStreamWriter.prototype.beginText = function () {\n this.writeOperator(Operators.beginText);\n };\n /**\n * `Ends text`.\n * @private\n */\n PdfStreamWriter.prototype.endText = function () {\n this.writeOperator(Operators.endText);\n };\n PdfStreamWriter.prototype.appendRectangle = function (arg1, arg2, arg3, arg4) {\n if (arg1 instanceof RectangleF) {\n this.appendRectangle(arg1.x, arg1.y, arg1.width, arg1.height);\n }\n else {\n this.writePoint(arg1, arg2);\n this.writePoint(arg3, arg4);\n this.writeOperator(Operators.appendRectangle);\n }\n };\n PdfStreamWriter.prototype.appendLineSegment = function (arg1, arg2) {\n if (arg1 instanceof PointF) {\n this.appendLineSegment(arg1.x, arg1.y);\n }\n else {\n this.writePoint(arg1, arg2);\n this.writeOperator(Operators.appendLineSegment);\n }\n };\n /**\n * Sets the `text rendering mode`.\n * @private\n */\n PdfStreamWriter.prototype.setTextRenderingMode = function (renderingMode) {\n this.stream.write(renderingMode.toString());\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setRenderingMode);\n };\n /**\n * Sets the `character spacing`.\n * @private\n */\n PdfStreamWriter.prototype.setCharacterSpacing = function (charSpacing) {\n this.stream.write(PdfNumber.floatToString(charSpacing));\n this.stream.write(Operators.whiteSpace);\n this.stream.write(Operators.setCharacterSpace);\n this.stream.write(Operators.newLine);\n };\n /**\n * Sets the `word spacing`.\n * @private\n */\n PdfStreamWriter.prototype.setWordSpacing = function (wordSpacing) {\n this.stream.write(PdfNumber.floatToString(wordSpacing));\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setWordSpace);\n };\n PdfStreamWriter.prototype.showNextLineText = function (arg1, arg2) {\n if (arg1 instanceof PdfString) {\n this.checkTextParam(arg1);\n this.writeText(arg1);\n this.writeOperator(Operators.setTextOnNewLine);\n }\n else {\n this.checkTextParam(arg1);\n this.writeText(arg1, arg2);\n this.writeOperator(Operators.setTextOnNewLine);\n }\n };\n PdfStreamWriter.prototype.setColorSpace = function (arg1, arg2) {\n if (arg1 instanceof PdfName && typeof arg2 === 'boolean') {\n var temparg1 = arg1;\n var temparg2 = arg2;\n // if (temparg1 == null) {\n // throw new Error('ArgumentNullException:name');\n // }\n var op = (temparg2) ? Operators.selectcolorspaceforstroking : Operators.selectcolorspacefornonstroking;\n this.stream.write(temparg1.toString());\n this.stream.write(Operators.whiteSpace);\n this.stream.write(op);\n this.stream.write(Operators.newLine);\n }\n else {\n var temparg1 = arg1;\n var temparg2 = arg2;\n this.setColorSpace(new PdfName(temparg1), temparg2);\n }\n };\n /**\n * Modifies current `transformation matrix`.\n * @private\n */\n PdfStreamWriter.prototype.modifyCtm = function (matrix) {\n if (matrix == null) {\n throw new Error('ArgumentNullException:matrix');\n }\n this.stream.write(matrix.toString());\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.modifyCtm);\n };\n PdfStreamWriter.prototype.setFont = function (font, name, size) {\n if (typeof name === 'string') {\n this.setFont(font, new PdfName(name), size);\n }\n else {\n if (font == null) {\n throw new Error('ArgumentNullException:font');\n }\n this.stream.write(name.toString());\n this.stream.write(Operators.whiteSpace);\n this.stream.write(PdfNumber.floatToString(size));\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setFont);\n }\n };\n /**\n * `Writes the operator`.\n * @private\n */\n PdfStreamWriter.prototype.writeOperator = function (opcode) {\n this.stream.write(opcode);\n this.stream.write(Operators.newLine);\n };\n PdfStreamWriter.prototype.checkTextParam = function (text) {\n if (text == null) {\n throw new Error('ArgumentNullException:text');\n }\n if (typeof text === 'string' && text === '') {\n throw new Error('ArgumentException:The text can not be an empty string, text');\n }\n };\n PdfStreamWriter.prototype.writeText = function (arg1, arg2) {\n if ((arg1 instanceof PdfString) && (typeof arg2 === 'undefined')) {\n this.stream.write(arg1.pdfEncode());\n }\n else {\n var start = void 0;\n var end = void 0;\n if (arg2) {\n start = PdfString.hexStringMark[0];\n end = PdfString.hexStringMark[1];\n }\n else {\n start = PdfString.stringMark[0];\n end = PdfString.stringMark[1];\n }\n this.stream.write(start);\n this.stream.write(arg1);\n this.stream.write(end);\n }\n };\n PdfStreamWriter.prototype.writePoint = function (arg1, arg2) {\n if ((arg1 instanceof PointF) && (typeof arg2 === 'undefined')) {\n this.writePoint(arg1.x, arg1.y);\n }\n else {\n var temparg1 = arg1;\n this.stream.write(PdfNumber.floatToString(temparg1));\n this.stream.write(Operators.whiteSpace);\n // NOTE: Change Y co-ordinate because we shifted co-ordinate system only.\n arg2 = this.updateY(arg2);\n this.stream.write(PdfNumber.floatToString(arg2));\n this.stream.write(Operators.whiteSpace);\n }\n };\n /**\n * `Updates y` co-ordinate.\n * @private\n */\n PdfStreamWriter.prototype.updateY = function (arg) {\n return -arg;\n };\n /**\n * `Writes string` to the file.\n * @private\n */\n PdfStreamWriter.prototype.write = function (string) {\n var builder = '';\n builder += string;\n builder += Operators.newLine;\n this.writeOperator(builder);\n };\n /**\n * `Writes comment` to the file.\n * @private\n */\n PdfStreamWriter.prototype.writeComment = function (comment) {\n if (comment != null && comment.length > 0) {\n var builder = '';\n builder += Operators.comment;\n builder += Operators.whiteSpace;\n builder += comment;\n //builder.Append( Operators.NewLine );\n this.writeOperator(builder);\n }\n else {\n throw new Error('Invalid comment');\n }\n };\n /**\n * Sets the `color and space`.\n * @private\n */\n PdfStreamWriter.prototype.setColorAndSpace = function (color, colorSpace, forStroking) {\n if (!color.isEmpty) {\n // bool test = color is PdfExtendedColor;\n this.stream.write(color.toString(colorSpace, forStroking));\n this.stream.write(Operators.newLine);\n }\n };\n // public setLineDashPattern(pattern : number[], patternOffset : number) : void\n // {\n // let pat : PdfArray = new PdfArray(pattern);\n // let off : PdfNumber = new PdfNumber(patternOffset);\n // this.setLineDashPatternHelper(pat, off);\n // }\n // private setLineDashPatternHelper(pattern : PdfArray, patternOffset : PdfNumber) : void\n // {\n // pattern.Save(this);\n // this.m_stream.write(Operators.whiteSpace);\n // patternOffset.Save(this);\n // this.m_stream.write(Operators.whiteSpace);\n // this.writeOperator(Operators.setDashPattern);\n // }\n /**\n * Sets the `line dash pattern`.\n * @private\n */\n PdfStreamWriter.prototype.setLineDashPattern = function (pattern, patternOffset) {\n // let pat : PdfArray = new PdfArray(pattern);\n // let off : PdfNumber = new PdfNumber(patternOffset);\n // this.setLineDashPatternHelper(pat, off);\n this.setLineDashPatternHelper(pattern, patternOffset);\n };\n /**\n * Sets the `line dash pattern`.\n * @private\n */\n PdfStreamWriter.prototype.setLineDashPatternHelper = function (pattern, patternOffset) {\n var tempPattern = '[';\n if (pattern.length > 1) {\n for (var index = 0; index < pattern.length; index++) {\n if (index === pattern.length - 1) {\n tempPattern += pattern[index].toString();\n }\n else {\n tempPattern += pattern[index].toString() + ' ';\n }\n }\n }\n tempPattern += '] ';\n tempPattern += patternOffset.toString();\n tempPattern += ' ' + Operators.setDashPattern;\n this.stream.write(tempPattern);\n this.stream.write(Operators.newLine);\n };\n /**\n * Sets the `miter limit`.\n * @private\n */\n PdfStreamWriter.prototype.setMiterLimit = function (miterLimit) {\n this.stream.write(PdfNumber.floatToString(miterLimit));\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setMiterLimit);\n };\n /**\n * Sets the `width of the line`.\n * @private\n */\n PdfStreamWriter.prototype.setLineWidth = function (width) {\n this.stream.write(PdfNumber.floatToString(width));\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setLineWidth);\n };\n /**\n * Sets the `line cap`.\n * @private\n */\n PdfStreamWriter.prototype.setLineCap = function (lineCapStyle) {\n this.stream.write((lineCapStyle).toString());\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setLineCapStyle);\n };\n /**\n * Sets the `line join`.\n * @private\n */\n PdfStreamWriter.prototype.setLineJoin = function (lineJoinStyle) {\n this.stream.write((lineJoinStyle).toString());\n this.stream.write(Operators.whiteSpace);\n this.writeOperator(Operators.setLineJoinStyle);\n };\n Object.defineProperty(PdfStreamWriter.prototype, \"position\", {\n //IPdfWriter members\n /**\n * Gets or sets the current `position` within the stream.\n * @private\n */\n get: function () {\n return this.stream.position;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStreamWriter.prototype, \"length\", {\n /**\n * Gets `stream length`.\n * @private\n */\n get: function () {\n var returnValue = 0;\n if (this.stream.data.length !== 0 && this.stream.data.length !== -1) {\n for (var index = 0; index < this.stream.data.length; index++) {\n returnValue += this.stream.data[index].length;\n }\n }\n return returnValue;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfStreamWriter.prototype, \"document\", {\n /**\n * Gets and Sets the `current document`.\n * @private\n */\n get: function () {\n return null;\n },\n enumerable: true,\n configurable: true\n });\n return PdfStreamWriter;\n}());\nexport { PdfStreamWriter };\n","/**\n * PdfPen.ts class for EJ2-PDF\n */\nimport { PdfColor } from './pdf-color';\nimport { PdfDashStyle, PdfColorSpace } from './enum';\nimport { PdfBrush } from './brushes/pdf-brush';\n/**\n * `PdfPen` class defining settings for drawing operations, that determines the color,\n * width, and style of the drawing elements.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create a new page\n * let page1 : PdfPage = document.pages.add();\n * // set pen\n * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0));\n * // draw rectangle\n * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfPen = /** @class */ (function () {\n function PdfPen(arg1, arg2) {\n //Fields\n /**\n * Specifies the `color of the pen`.\n * @default new PdfColor()\n * @private\n */\n this.pdfColor = new PdfColor(0, 0, 0);\n /**\n * Specifies the `dash offset of the pen`.\n * @default 0\n * @private\n */\n this.dashOffsetValue = 0;\n /**\n * Specifies the `dash pattern of the pen`.\n * @default [0]\n * @private\n */\n this.penDashPattern = [0];\n /**\n * Specifies the `dash style of the pen`.\n * @default Solid\n * @private\n */\n this.pdfDashStyle = PdfDashStyle.Solid;\n /**\n * Specifies the `line cap of the pen`.\n * @default 0\n * @private\n */\n this.pdfLineCap = 0;\n /**\n * Specifies the `line join of the pen`.\n * @default 0\n * @private\n */\n this.pdfLineJoin = 0;\n /**\n * Specifies the `width of the pen`.\n * @default 1.0\n * @private\n */\n this.penWidth = 1.0;\n /**\n * Specifies the `mitter limit of the pen`.\n * @default 0.0\n * @private\n */\n this.internalMiterLimit = 0.0;\n /**\n * Stores the `colorspace` value.\n * @default Rgb\n * @private\n */\n this.colorSpace = PdfColorSpace.Rgb;\n if (typeof arg2 === 'number') {\n this.constructor(arg1);\n this.width = arg2;\n }\n else if (typeof arg2 === 'undefined' && arg1 instanceof PdfBrush) {\n this.setBrush(arg1);\n }\n else if (typeof arg2 === 'undefined' && arg1 instanceof PdfColor) {\n this.color = arg1;\n }\n }\n Object.defineProperty(PdfPen.prototype, \"color\", {\n //Properties\n /**\n * Gets or sets the `color of the pen`.\n * @private\n */\n get: function () {\n return this.pdfColor;\n },\n set: function (value) {\n this.pdfColor = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPen.prototype, \"dashOffset\", {\n /**\n * Gets or sets the `dash offset of the pen`.\n * @private\n */\n get: function () {\n if (typeof this.dashOffsetValue === 'undefined' || this.dashOffsetValue == null) {\n return 0;\n }\n else {\n return this.dashOffsetValue;\n }\n },\n set: function (value) {\n this.dashOffsetValue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPen.prototype, \"dashPattern\", {\n /**\n * Gets or sets the `dash pattern of the pen`.\n * @private\n */\n get: function () {\n return this.penDashPattern;\n },\n set: function (value) {\n this.penDashPattern = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPen.prototype, \"dashStyle\", {\n /**\n * Gets or sets the `dash style of the pen`.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create a new page\n * let page1 : PdfPage = document.pages.add();\n * // set pen\n * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0));\n * //\n * // set pen style\n * pen.dashStyle = PdfDashStyle.DashDot;\n * // get pen style\n * let style : PdfDashStyle = pen.dashStyle;\n * //\n * // draw rectangle\n * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n return this.pdfDashStyle;\n },\n set: function (value) {\n if (this.pdfDashStyle !== value) {\n this.pdfDashStyle = value;\n switch (this.pdfDashStyle) {\n case PdfDashStyle.Custom:\n break;\n case PdfDashStyle.Dash:\n this.penDashPattern = [3, 1];\n break;\n case PdfDashStyle.Dot:\n this.penDashPattern = [1, 1];\n break;\n case PdfDashStyle.DashDot:\n this.penDashPattern = [3, 1, 1, 1];\n break;\n case PdfDashStyle.DashDotDot:\n this.penDashPattern = [3, 1, 1, 1, 1, 1];\n break;\n case PdfDashStyle.Solid:\n break;\n default:\n this.pdfDashStyle = PdfDashStyle.Solid;\n this.penDashPattern = [0];\n break;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPen.prototype, \"lineCap\", {\n /**\n * Gets or sets the `line cap of the pen`.\n * @private\n */\n get: function () {\n return this.pdfLineCap;\n },\n set: function (value) {\n this.pdfLineCap = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPen.prototype, \"lineJoin\", {\n /**\n * Gets or sets the `line join style of the pen`.\n * @private\n */\n get: function () {\n return this.pdfLineJoin;\n },\n set: function (value) {\n this.pdfLineJoin = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPen.prototype, \"miterLimit\", {\n /**\n * Gets or sets the `miter limit`.\n * @private\n */\n get: function () {\n return this.internalMiterLimit;\n },\n set: function (value) {\n this.internalMiterLimit = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPen.prototype, \"width\", {\n /**\n * Gets or sets the `width of the pen`.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create a new page\n * let page1 : PdfPage = document.pages.add();\n * // set pen\n * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0));\n * //\n * // set pen width\n * pen.width = 2;\n * //\n * // draw rectangle\n * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n return this.penWidth;\n },\n set: function (value) {\n this.penWidth = value;\n },\n enumerable: true,\n configurable: true\n });\n //Helper\n /**\n * `Clones` this instance of PdfPen class.\n * @private\n */\n PdfPen.prototype.clone = function () {\n var pen = this;\n return pen;\n };\n /**\n * `Sets the brush`.\n * @private\n */\n PdfPen.prototype.setBrush = function (brush) {\n var sBrush = brush;\n this.color = sBrush.color;\n this.pdfBrush = sBrush;\n };\n /**\n * `Monitors the changes`.\n * @private\n */\n PdfPen.prototype.monitorChanges = function (currentPen, streamWriter, getResources, saveState, currentColorSpace, matrix) {\n var diff = false;\n saveState = true;\n if (currentPen == null) {\n diff = true;\n }\n diff = this.dashControl(currentPen, saveState, streamWriter);\n streamWriter.setLineWidth(this.width);\n streamWriter.setLineJoin(this.lineJoin);\n streamWriter.setLineCap(this.lineCap);\n var miterLimit = this.miterLimit;\n if (miterLimit > 0) {\n streamWriter.setMiterLimit(miterLimit);\n diff = true;\n }\n var brush = this.pdfBrush;\n streamWriter.setColorAndSpace(this.color, currentColorSpace, true);\n diff = true;\n return diff;\n };\n /**\n * `Controls the dash style` and behaviour of each line.\n * @private\n */\n PdfPen.prototype.dashControl = function (pen, saveState, streamWriter) {\n saveState = true;\n var lineWidth = this.width;\n var pattern = this.getPattern();\n streamWriter.setLineDashPattern(pattern, this.dashOffset * lineWidth);\n return saveState;\n };\n /**\n * `Gets the pattern` of PdfPen.\n * @private\n */\n PdfPen.prototype.getPattern = function () {\n var pattern = this.dashPattern;\n for (var i = 0; i < pattern.length; ++i) {\n pattern[i] *= this.width;\n }\n return pattern;\n };\n return PdfPen;\n}());\nexport { PdfPen };\n","/**\n * PdfTransformationMatrix.ts class for EJ2-PDF\n */\nimport { PointF } from './../drawing/pdf-drawing';\nimport { PdfNumber } from './../primitives/pdf-number';\n/**\n * Class for representing Root `transformation matrix`.\n */\nvar PdfTransformationMatrix = /** @class */ (function () {\n function PdfTransformationMatrix(value) {\n /**\n * Value for `angle converting`.\n * @default 180.0 / Math.PI\n * @private\n */\n this.radDegFactor = 180.0 / Math.PI;\n if (typeof value === 'undefined') {\n this.transformationMatrix = new Matrix(1.00, 0.00, 0.00, 1.00, 0.00, 0.00);\n }\n else {\n this.transformationMatrix = new Matrix(1.00, 0.00, 0.00, -1.00, 0.00, 0.00);\n }\n }\n Object.defineProperty(PdfTransformationMatrix.prototype, \"matrix\", {\n // Properties\n /**\n * Gets or sets the `internal matrix object`.\n * @private\n */\n get: function () {\n return this.transformationMatrix;\n },\n set: function (value) {\n this.transformationMatrix = value;\n },\n enumerable: true,\n configurable: true\n });\n // Public methods\n /**\n * `Translates` coordinates by specified coordinates.\n * @private\n */\n PdfTransformationMatrix.prototype.translate = function (offsetX, offsetY) {\n this.transformationMatrix.translate(offsetX, offsetY);\n };\n /**\n * `Scales` coordinates by specified coordinates.\n * @private\n */\n PdfTransformationMatrix.prototype.scale = function (scaleX, scaleY) {\n this.transformationMatrix.elements[0] = scaleX;\n this.transformationMatrix.elements[3] = scaleY;\n };\n /**\n * `Rotates` coordinate system in counterclockwise direction.\n * @private\n */\n PdfTransformationMatrix.prototype.rotate = function (angle) {\n //Convert from degree to radian \n angle = (angle * Math.PI) / 180;\n //Rotation \n this.transformationMatrix.elements[0] = Math.cos(angle);\n this.transformationMatrix.elements[1] = Math.sin(angle);\n this.transformationMatrix.elements[2] = -Math.sin(angle);\n this.transformationMatrix.elements[3] = Math.cos(angle);\n };\n // Overrides\n /**\n * Gets `PDF representation`.\n * @private\n */\n PdfTransformationMatrix.prototype.toString = function () {\n var builder = '';\n var whitespace = ' ';\n for (var i = 0, len = this.transformationMatrix.elements.length; i < len; i++) {\n var temp = this.matrix.elements[i];\n builder += PdfNumber.floatToString(this.transformationMatrix.elements[i]);\n builder += whitespace;\n }\n return builder;\n };\n // Implementation\n /**\n * `Multiplies` matrices (changes coordinate system.)\n * @private\n */\n PdfTransformationMatrix.prototype.multiply = function (matrix) {\n this.transformationMatrix.multiply(matrix.matrix);\n };\n /**\n * Converts `degrees to radians`.\n * @private\n */\n PdfTransformationMatrix.degreesToRadians = function (degreesX) {\n return this.degRadFactor * degreesX;\n };\n /**\n * Converts `radians to degrees`.\n * @private\n */\n PdfTransformationMatrix.prototype.radiansToDegrees = function (radians) {\n return this.radDegFactor * radians;\n };\n /**\n * `Clones` this instance of PdfTransformationMatrix.\n * @private\n */\n PdfTransformationMatrix.prototype.clone = function () {\n return this;\n };\n // Constants\n /**\n * Value for `angle converting`.\n * @default Math.PI / 180.0\n * @private\n */\n PdfTransformationMatrix.degRadFactor = Math.PI / 180.0;\n return PdfTransformationMatrix;\n}());\nexport { PdfTransformationMatrix };\nvar Matrix = /** @class */ (function () {\n function Matrix(arg1, arg2, arg3, arg4, arg5, arg6) {\n if (typeof arg1 === 'undefined') {\n this.metrixElements = [];\n }\n else if (typeof arg1 === 'number') {\n this.constructor();\n this.metrixElements.push(arg1);\n this.metrixElements.push(arg2);\n this.metrixElements.push(arg3);\n this.metrixElements.push(arg4);\n this.metrixElements.push(arg5);\n this.metrixElements.push(arg6);\n }\n else {\n this.metrixElements = arg1;\n }\n }\n Object.defineProperty(Matrix.prototype, \"elements\", {\n // Properties\n /**\n * Gets the `elements`.\n * @private\n */\n get: function () {\n return this.metrixElements;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Matrix.prototype, \"offsetX\", {\n /**\n * Gets the off set `X`.\n * @private\n */\n get: function () {\n return this.metrixElements[4];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Matrix.prototype, \"offsetY\", {\n /**\n * Gets the off set `Y`.\n * @private\n */\n get: function () {\n return this.metrixElements[5];\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Translates` coordinates by specified coordinates.\n * @private\n */\n Matrix.prototype.translate = function (offsetX, offsetY) {\n this.metrixElements[4] = offsetX;\n this.metrixElements[5] = offsetY;\n };\n /**\n * `Translates` the specified offset X.\n * @private\n */\n Matrix.prototype.transform = function (point) {\n var x = point.x;\n var y = point.y;\n var x2 = x * this.elements[0] + y * this.elements[2] + this.offsetX;\n var y2 = x * this.elements[1] + y * this.elements[3] + this.offsetY;\n return new PointF(x2, y2);\n };\n /**\n * `Multiplies matrices` (changes coordinate system.)\n * @private\n */\n Matrix.prototype.multiply = function (matrix) {\n var tempMatrix = [];\n tempMatrix.push(this.elements[0] * matrix.elements[0] + this.elements[1] * matrix.elements[2]);\n tempMatrix[1] = (this.elements[0] * matrix.elements[1] + this.elements[1] * matrix.elements[3]);\n tempMatrix[2] = (this.elements[2] * matrix.elements[0] + this.elements[3] * matrix.elements[2]);\n tempMatrix[3] = (this.elements[2] * matrix.elements[1] + this.elements[3] * matrix.elements[3]);\n tempMatrix[4] = (this.offsetX * matrix.elements[0] + this.offsetY * matrix.elements[2] + matrix.offsetX);\n tempMatrix[5] = (this.offsetX * matrix.elements[1] + this.offsetY * matrix.elements[3] + matrix.offsetY);\n for (var i = 0; i < tempMatrix.length; i++) {\n this.elements[i] = tempMatrix[i];\n }\n };\n // IDisposable Members\n /**\n * `Dispose` this instance of PdfTransformationMatrix class.\n * @private\n */\n Matrix.prototype.dispose = function () {\n this.metrixElements = null;\n };\n // ICloneable Members\n /**\n * `Clones` this instance of PdfTransformationMatrix class.\n * @private\n */\n Matrix.prototype.clone = function () {\n var m = new Matrix(this.metrixElements);\n return m;\n };\n return Matrix;\n}());\nexport { Matrix };\n","/**\n * `constants.ts` class for EJ2-PDF\n * @private\n */\nvar ProcedureSets = /** @class */ (function () {\n function ProcedureSets() {\n /**\n * Specifies the `PDF` procedure set.\n * @private\n */\n this.pdf = 'PDF';\n /**\n * Specifies the `Text` procedure set.\n * @private\n */\n this.text = 'Text';\n /**\n * Specifies the `ImageB` procedure set.\n * @private\n */\n this.imageB = 'ImageB';\n /**\n * Specifies the `ImageC` procedure set.\n * @private\n */\n this.imageC = 'ImageC';\n /**\n * Specifies the `ImageI` procedure set.\n * @private\n */\n this.imageI = 'ImageI';\n }\n return ProcedureSets;\n}());\nexport { ProcedureSets };\n","/**\n * Dictionary class\n * @private\n * @hidden\n */\nvar TemporaryDictionary = /** @class */ (function () {\n function TemporaryDictionary() {\n /**\n * @hidden\n * @private\n */\n this.mKeys = [];\n /**\n * @hidden\n * @private\n */\n this.mValues = [];\n }\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.size = function () {\n return this.mKeys.length;\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.add = function (key, value) {\n if (key === undefined || key === null || value === undefined || value === null) {\n throw new ReferenceError('Provided key or value is not valid.');\n }\n var index = this.mKeys.indexOf(key);\n if (index < 0) {\n this.mKeys.push(key);\n this.mValues.push(value);\n return 1;\n }\n else {\n throw new RangeError('An item with the same key has already been added.');\n }\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.keys = function () {\n return this.mKeys;\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.values = function () {\n return this.mValues;\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.getValue = function (key) {\n if (key === undefined || key === null) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.mKeys.indexOf(key);\n if (index < 0) {\n throw new RangeError('No item with the specified key has been added.');\n }\n else {\n return this.mValues[index];\n }\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.setValue = function (key, value) {\n if (key === undefined || key === null) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.mKeys.indexOf(key);\n if (index < 0) {\n this.mKeys.push(key);\n this.mValues.push(value);\n }\n else {\n this.mValues[index] = value;\n }\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.remove = function (key) {\n if (key === undefined || key === null) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.mKeys.indexOf(key);\n if (index < 0) {\n throw new RangeError('No item with the specified key has been added.');\n }\n else {\n this.mKeys.splice(index, 1);\n this.mValues.splice(index, 1);\n return true;\n }\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.containsKey = function (key) {\n if (key === undefined || key === null) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.mKeys.indexOf(key);\n if (index < 0) {\n return false;\n }\n return true;\n };\n /**\n * @hidden\n * @private\n */\n TemporaryDictionary.prototype.clear = function () {\n this.mKeys = [];\n this.mValues = [];\n };\n return TemporaryDictionary;\n}());\nexport { TemporaryDictionary };\n","import { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { PdfName } from './../primitives/pdf-name';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\n/**\n * Represents a simple `transparency`.\n * @private\n */\nvar PdfTransparency = /** @class */ (function () {\n // Properties\n // /**\n // * Gets the `stroke` operation alpha value.\n // * @private\n // */\n // public get stroke() : number {\n // let result : number = this.getNumber(this.dictionaryProperties.CA);\n // return result;\n // }\n // /**\n // * Gets the `fill` operation alpha value.\n // * @private\n // */\n // public get fill() : number {\n // let result : number = this.getNumber(this.dictionaryProperties.ca);\n // return result;\n // }\n // /**\n // * Gets the `blend mode`.\n // * @private\n // */\n // public get mode() : PdfBlendMode {\n // let result : string = this.getName(this.dictionaryProperties.ca);\n // return PdfBlendMode.Normal;\n // }\n // Constructors\n /**\n * Initializes a new instance of the `Transparency` class.\n * @private\n */\n function PdfTransparency(stroke, fill, mode) {\n // Fields\n /**\n * Internal variable to store `dictionary`.\n * @default new PdfDictionary()\n * @private\n */\n this.dictionary = new PdfDictionary();\n /**\n * Internal variable for accessing fields from `DictionryProperties` class.\n * @default new DictionaryProperties()\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n this.dictionary.items.setValue(this.dictionaryProperties.CA, new PdfNumber(stroke));\n this.dictionary.items.setValue(this.dictionaryProperties.ca, new PdfNumber(fill));\n this.dictionary.items.setValue(this.dictionaryProperties.BM, new PdfName(mode.toString()));\n }\n Object.defineProperty(PdfTransparency.prototype, \"element\", {\n // // Implementation\n // /**\n // * Gets the `number value`.\n // * @private\n // */\n // private getNumber(keyName : string) : number {\n // let result : number = 0.0;\n // let numb : PdfNumber = this.dictionary.items.getValue(keyName) as PdfNumber;\n // result = numb.intValue;\n // return result;\n // }\n // /**\n // * Gets the `name value`.\n // * @private\n // */\n // private getName(keyName : string) : string {\n // let result : string = null;\n // let name : PdfName = this.dictionary.items.getValue(keyName) as PdfName;\n // result = name.value;\n // return result;\n // }\n // IPdfWrapper Members\n /**\n * Gets the `element`.\n * @private\n */\n get: function () {\n return this.dictionary;\n },\n enumerable: true,\n configurable: true\n });\n return PdfTransparency;\n}());\nexport { PdfTransparency };\n","/**\n * Represent a `collection of automatic fields information`.\n * @private\n */\nvar PdfAutomaticFieldInfoCollection = /** @class */ (function () {\n /**\n * Initializes a new instance of the 'PdfPageNumberFieldInfoCollection' class.\n * @private\n */\n function PdfAutomaticFieldInfoCollection() {\n /**\n * Internal variable to store instance of `pageNumberFields` class.\n * @private\n */\n this.automaticFieldsInformation = [];\n //\n }\n Object.defineProperty(PdfAutomaticFieldInfoCollection.prototype, \"automaticFields\", {\n /**\n * Gets the `page number fields collection`.\n * @private\n */\n get: function () {\n return this.automaticFieldsInformation;\n },\n enumerable: true,\n configurable: true\n });\n // Public methods\n /// Adds the specified field info.\n /**\n * Add page number field into collection.\n * @private\n */\n PdfAutomaticFieldInfoCollection.prototype.add = function (fieldInfo) {\n return this.automaticFields.push(fieldInfo);\n };\n return PdfAutomaticFieldInfoCollection;\n}());\nexport { PdfAutomaticFieldInfoCollection };\n","/**\n * Represents a base class for all page graphics elements.\n */\nvar PdfGraphicsElement = /** @class */ (function () {\n // Constructors\n function PdfGraphicsElement() {\n //\n }\n /**\n * `Draws` the page number field.\n * @public\n */\n PdfGraphicsElement.prototype.drawHelper = function (graphics, x, y) {\n var bNeedSave = (x !== 0 || y !== 0);\n var gState = null;\n // Translate co-ordinates.\n if (bNeedSave) {\n // Save state.\n gState = graphics.save();\n graphics.translateTransform(x, y);\n }\n this.drawInternal(graphics);\n if (bNeedSave) {\n // Restore state.\n graphics.restore(gState);\n }\n };\n return PdfGraphicsElement;\n}());\nexport { PdfGraphicsElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfAutomaticField.ts class for EJ2-PDF\n */\nimport { RectangleF, SizeF, PointF } from './../../drawing/pdf-drawing';\nimport { PdfSolidBrush } from './../../graphics/brushes/pdf-solid-brush';\nimport { PdfColor } from './../../graphics/pdf-color';\nimport { PdfDocument } from './../pdf-document';\nimport { PdfGraphicsElement } from './../../graphics/figures/base/graphics-element';\nimport { PdfAutomaticFieldInfo } from './automatic-field-info';\n/**\n * Represents a fields which is calculated before the document saves.\n */\nvar PdfAutomaticField = /** @class */ (function (_super) {\n __extends(PdfAutomaticField, _super);\n // Constructors\n function PdfAutomaticField() {\n var _this = _super.call(this) || this;\n // Fields\n _this.internalBounds = new RectangleF(0, 0, 0, 0);\n _this.internalTemplateSize = new SizeF(0, 0);\n return _this;\n }\n Object.defineProperty(PdfAutomaticField.prototype, \"bounds\", {\n // Properties\n get: function () {\n return this.internalBounds;\n },\n set: function (value) {\n this.internalBounds = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticField.prototype, \"size\", {\n get: function () {\n return new SizeF(this.bounds.width, this.bounds.height);\n },\n set: function (value) {\n this.bounds.width = value.width;\n this.bounds.height = value.height;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticField.prototype, \"location\", {\n get: function () {\n return new PointF(this.bounds.x, this.bounds.y);\n },\n set: function (value) {\n this.bounds.x = value.x;\n this.bounds.y = value.y;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticField.prototype, \"font\", {\n get: function () {\n return this.internalFont;\n },\n set: function (value) {\n this.internalFont = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticField.prototype, \"brush\", {\n get: function () {\n return this.internalBrush;\n },\n set: function (value) {\n this.internalBrush = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticField.prototype, \"pen\", {\n get: function () {\n return this.internalPen;\n },\n set: function (value) {\n this.internalPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticField.prototype, \"stringFormat\", {\n get: function () {\n return this.internalStringFormat;\n },\n set: function (value) {\n this.internalStringFormat = value;\n },\n enumerable: true,\n configurable: true\n });\n PdfAutomaticField.prototype.performDrawHelper = function (graphics, location, scalingX, scalingY) {\n if (this.bounds.height === 0 || this.bounds.width === 0) {\n var text = this.getValue(graphics);\n this.internalTemplateSize = this.getFont().measureString(text, this.size, this.stringFormat);\n }\n };\n PdfAutomaticField.prototype.draw = function (arg1, arg2, arg3) {\n if (typeof arg2 === 'undefined') {\n var location_1 = new PointF(0, 0);\n this.draw(arg1, location_1);\n }\n else if (arg2 instanceof PointF) {\n this.draw(arg1, arg2.x, arg2.y);\n }\n else {\n this.drawHelper(arg1, arg2, arg3);\n var info = new PdfAutomaticFieldInfo(this, new PointF(arg2, arg3));\n arg1.automaticFields.add(info);\n }\n };\n PdfAutomaticField.prototype.getSize = function () {\n if (this.bounds.height === 0 || this.bounds.width === 0) {\n return this.internalTemplateSize;\n }\n else {\n return this.size;\n }\n };\n PdfAutomaticField.prototype.drawInternal = function (graphics) {\n //\n };\n /* tslint:disable */\n PdfAutomaticField.prototype.getBrush = function () {\n return (typeof this.internalBrush === 'undefined' || this.internalBrush == null) ? new PdfSolidBrush(new PdfColor(0, 0, 0)) : this.internalBrush;\n };\n PdfAutomaticField.prototype.getFont = function () {\n return (typeof this.internalFont === 'undefined' || this.internalFont == null) ? PdfDocument.defaultFont : this.internalFont;\n };\n /* tslint:enable */\n PdfAutomaticField.prototype.getPageFromGraphics = function (graphics) {\n if (typeof graphics.page !== 'undefined' && graphics.page !== null) {\n var page = graphics.page;\n return page;\n }\n else {\n var page = graphics.currentPage;\n return page;\n }\n };\n return PdfAutomaticField;\n}(PdfGraphicsElement));\nexport { PdfAutomaticField };\n","/**\n * PdfAutomaticFieldInfo.ts class for EJ2-PDF\n * @private\n */\nimport { PointF } from './../../drawing/pdf-drawing';\nimport { PdfAutomaticField } from './automatic-field';\n/**\n * Represents information about the automatic field.\n * @private\n */\nvar PdfAutomaticFieldInfo = /** @class */ (function () {\n function PdfAutomaticFieldInfo(field, location, scaleX, scaleY) {\n // Fields\n /**\n * Internal variable to store location of the field.\n * @private\n */\n this.pageNumberFieldLocation = new PointF();\n /**\n * Internal variable to store field.\n * @private\n */\n this.pageNumberField = null;\n /**\n * Internal variable to store x scaling factor.\n * @private\n */\n this.scaleX = 1;\n /**\n * Internal variable to store y scaling factor.\n * @private\n */\n this.scaleY = 1;\n if (typeof location === 'undefined' && field instanceof PdfAutomaticFieldInfo) {\n this.pageNumberField = field.field;\n this.pageNumberFieldLocation = field.location;\n this.scaleX = field.scalingX;\n this.scaleY = field.scalingY;\n }\n else if (typeof scaleX === 'undefined' && location instanceof PointF && field instanceof PdfAutomaticField) {\n this.pageNumberField = field;\n this.pageNumberFieldLocation = location;\n }\n else {\n this.pageNumberField = field;\n this.pageNumberFieldLocation = location;\n this.scaleX = scaleX;\n this.scaleY = scaleY;\n }\n }\n Object.defineProperty(PdfAutomaticFieldInfo.prototype, \"location\", {\n /* tslint:enable */\n // Properties\n /**\n * Gets or sets the location.\n * @private\n */\n get: function () {\n return this.pageNumberFieldLocation;\n },\n set: function (value) {\n this.pageNumberFieldLocation = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticFieldInfo.prototype, \"field\", {\n /**\n * Gets or sets the field.\n * @private\n */\n get: function () {\n return this.pageNumberField;\n },\n set: function (value) {\n this.pageNumberField = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticFieldInfo.prototype, \"scalingX\", {\n /**\n * Gets or sets the scaling X factor.\n * @private\n */\n get: function () {\n return this.scaleX;\n },\n set: function (value) {\n this.scaleX = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAutomaticFieldInfo.prototype, \"scalingY\", {\n /**\n * Gets or sets the scaling Y factor.\n * @private\n */\n get: function () {\n return this.scaleY;\n },\n set: function (value) {\n this.scaleY = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfAutomaticFieldInfo;\n}());\nexport { PdfAutomaticFieldInfo };\n","/**\n * ByteArray class\n * Used to keep information about image stream as byte array.\n * @private\n */\nvar ByteArray = /** @class */ (function () {\n /**\n * Initialize the new instance for `byte-array` class\n * @hidden\n * @private\n */\n function ByteArray(length) {\n /**\n * Current stream `position`.\n * @default 0\n * @private\n */\n this.mPosition = 0;\n this.buffer = new Uint8Array(length);\n this.dataView = new DataView(this.buffer.buffer);\n }\n Object.defineProperty(ByteArray.prototype, \"position\", {\n /**\n * Gets and Sets a current `position` of byte array.\n * @hidden\n * @private\n */\n get: function () {\n return this.mPosition;\n },\n set: function (value) {\n this.mPosition = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Read` from current stream position.\n * @default 0\n * @hidden\n * @private\n */\n ByteArray.prototype.read = function (buffer, offset, count) {\n for (var index = offset; index < count; index++) {\n var position = this.position;\n buffer.buffer[index] = this.readByte(position);\n this.position++;\n }\n };\n /**\n * @hidden\n */\n ByteArray.prototype.getBuffer = function (index) {\n return this.buffer[index];\n };\n /**\n * @hidden\n */\n ByteArray.prototype.writeFromBase64String = function (base64) {\n var arr = this.encodedString(base64);\n this.buffer = arr;\n };\n /**\n * @hidden\n */\n ByteArray.prototype.encodedString = function (input) {\n var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n var chr1;\n var chr2;\n var chr3;\n var enc1;\n var enc2;\n var enc3;\n var enc4;\n var i = 0;\n var resultIndex = 0;\n var dataUrlPrefix = 'data:';\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n var totalLength = input.length * 3 / 4;\n if (input.charAt(input.length - 1) === keyStr.charAt(64)) {\n totalLength--;\n }\n var output = new Uint8Array(totalLength | 0);\n while (i < input.length) {\n enc1 = keyStr.indexOf(input.charAt(i++));\n enc2 = keyStr.indexOf(input.charAt(i++));\n enc3 = keyStr.indexOf(input.charAt(i++));\n enc4 = keyStr.indexOf(input.charAt(i++));\n chr1 = (enc1 << 2) | (enc2 >> 4);\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);\n chr3 = ((enc3 & 3) << 6) | enc4;\n output[resultIndex++] = chr1;\n output[resultIndex++] = chr2;\n output[resultIndex++] = chr3;\n }\n return output;\n };\n /**\n * @hidden\n */\n ByteArray.prototype.readByte = function (offset) {\n return (this.buffer[offset]);\n };\n Object.defineProperty(ByteArray.prototype, \"internalBuffer\", {\n /**\n * @hidden\n */\n get: function () {\n return this.buffer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ByteArray.prototype, \"count\", {\n /**\n * @hidden\n */\n get: function () {\n return this.buffer.byteLength;\n },\n enumerable: true,\n configurable: true\n });\n return ByteArray;\n}());\nexport { ByteArray };\n","/**\n * `PdfBoolean` class is used to perform boolean related primitive operations.\n * @private\n */\nvar PdfBoolean = /** @class */ (function () {\n //constructor\n /**\n * Initializes a new instance of the `PdfBoolean` class.\n * @private\n */\n function PdfBoolean(value) {\n /**\n * Internal variable to store the `position`.\n * @default -1\n * @private\n */\n this.currentPosition = -1;\n this.value = value;\n }\n Object.defineProperty(PdfBoolean.prototype, \"status\", {\n //Properties\n /**\n * Gets or sets the `Status` of the specified object.\n * @private\n */\n get: function () {\n return this.objectStatus;\n },\n set: function (value) {\n this.objectStatus = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBoolean.prototype, \"isSaving\", {\n /**\n * Gets or sets a value indicating whether this document `is saving` or not.\n * @private\n */\n get: function () {\n return this.saving;\n },\n set: function (value) {\n this.saving = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBoolean.prototype, \"objectCollectionIndex\", {\n /**\n * Gets or sets the `index` value of the specified object.\n * @private\n */\n get: function () {\n return this.index;\n },\n set: function (value) {\n this.index = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBoolean.prototype, \"position\", {\n /**\n * Gets or sets the `position` of the object.\n * @private\n */\n get: function () {\n return this.currentPosition;\n },\n set: function (value) {\n this.currentPosition = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBoolean.prototype, \"clonedObject\", {\n /**\n * Returns `cloned object`.\n * @private\n */\n get: function () {\n var rValue = null;\n return rValue;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Saves` the object using the specified writer.\n * @private\n */\n PdfBoolean.prototype.save = function (writer) {\n writer.write(this.boolToStr(this.value));\n };\n /**\n * Creates a `copy of PdfBoolean`.\n * @private\n */\n PdfBoolean.prototype.clone = function (crossTable) {\n var newNumber = new PdfBoolean(this.value);\n return newNumber;\n };\n // Implementation\n /**\n * Converts `boolean to string` - 0/1 'true'/'false'.\n * @private\n */\n PdfBoolean.prototype.boolToStr = function (value) {\n return value ? 'true' : 'false';\n };\n return PdfBoolean;\n}());\nexport { PdfBoolean };\n","/**\n * public Enum for `PdfLayoutType`.\n * @private\n */\nexport var PdfLayoutType;\n(function (PdfLayoutType) {\n /**\n * Specifies the type of `Paginate`.\n * @private\n */\n PdfLayoutType[PdfLayoutType[\"Paginate\"] = 0] = \"Paginate\";\n /**\n * Specifies the type of `OnePage`.\n * @private\n */\n PdfLayoutType[PdfLayoutType[\"OnePage\"] = 1] = \"OnePage\";\n})(PdfLayoutType || (PdfLayoutType = {}));\n/**\n * public Enum for `PdfLayoutBreakType`.\n * @private\n */\nexport var PdfLayoutBreakType;\n(function (PdfLayoutBreakType) {\n /**\n * Specifies the type of `FitPage`.\n * @private\n */\n PdfLayoutBreakType[PdfLayoutBreakType[\"FitPage\"] = 0] = \"FitPage\";\n /**\n * Specifies the type of `FitElement`.\n * @private\n */\n PdfLayoutBreakType[PdfLayoutBreakType[\"FitElement\"] = 1] = \"FitElement\";\n /**\n * Specifies the type of `FitColumnsToPage`.\n * @private\n */\n PdfLayoutBreakType[PdfLayoutBreakType[\"FitColumnsToPage\"] = 2] = \"FitColumnsToPage\";\n})(PdfLayoutBreakType || (PdfLayoutBreakType = {}));\n","/**\n * Used to perform `convertion between pixels and points`.\n * @private\n */\nvar PdfUnitConverter = /** @class */ (function () {\n //constructors\n /**\n * Initializes a new instance of the `UnitConvertor` class with DPI value.\n * @private\n */\n function PdfUnitConverter(dpi) {\n this.updateProportionsHelper(dpi);\n }\n /**\n * `Converts` the value, from one graphics unit to another graphics unit.\n * @private\n */\n PdfUnitConverter.prototype.convertUnits = function (value, from, to) {\n return this.convertFromPixels(this.convertToPixels(value, from), to);\n };\n /**\n * Converts the value `to pixel` from specified graphics unit.\n * @private\n */\n PdfUnitConverter.prototype.convertToPixels = function (value, from) {\n var index = from;\n var result = (value * this.proportions[index]);\n return result;\n };\n /**\n * Converts value, to specified graphics unit `from Pixel`.\n * @private\n */\n PdfUnitConverter.prototype.convertFromPixels = function (value, to) {\n var index = to;\n var result = (value / this.proportions[index]);\n return result;\n };\n /**\n * `Update proportions` matrix according to Graphics settings.\n * @private\n */\n PdfUnitConverter.prototype.updateProportionsHelper = function (pixelPerInch) {\n this.proportions = [\n pixelPerInch / 2.54,\n pixelPerInch / 6.0,\n 1,\n pixelPerInch / 72.0,\n pixelPerInch,\n pixelPerInch / 300.0,\n pixelPerInch / 25.4 // Millimeter\n ];\n };\n //Fields\n /**\n * Indicates default `horizontal resolution`.\n * @default 96\n * @private\n */\n PdfUnitConverter.horizontalResolution = 96;\n /**\n * Indicates default `vertical resolution`.\n * @default 96\n * @private\n */\n PdfUnitConverter.verticalResolution = 96;\n return PdfUnitConverter;\n}());\nexport { PdfUnitConverter };\n","import { SizeF } from './../../drawing/pdf-drawing';\nimport { PdfGraphicsUnit } from './../enum';\nimport { PdfUnitConverter } from './../unit-convertor';\n/**\n * `PdfImage` class represents the base class for images and provides functionality for the 'PdfBitmap' class.\n * @private\n */\nvar PdfImage = /** @class */ (function () {\n function PdfImage() {\n }\n Object.defineProperty(PdfImage.prototype, \"width\", {\n /**\n * Gets and Sets the `width` of an image.\n * @private\n */\n get: function () {\n return this.imageWidth;\n },\n set: function (value) {\n this.imageWidth = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfImage.prototype, \"height\", {\n /**\n * Gets and Sets the `height` of an image.\n * @private\n */\n get: function () {\n return this.imageHeight;\n },\n set: function (value) {\n this.imageHeight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfImage.prototype, \"size\", {\n /**\n * Gets or sets the size of the image.\n * @private\n */\n set: function (value) {\n this.width = value.width;\n this.height = value.height;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfImage.prototype, \"physicalDimension\", {\n /**\n * Gets the `physical dimension` of an image.\n * @private\n */\n get: function () {\n this.imagePhysicalDimension = this.getPointSize(this.width, this.height, this.horizontalResolution, this.verticalResolution);\n return new SizeF(this.width, this.height);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfImage.prototype, \"element\", {\n // /**\n // * Gets the `image stream as string`.\n // * @private\n // */\n // public static fromString(string : string) : PdfImage {\n // let image : PdfImage = new PdfBitmap(string);\n // return image;\n // }\n /**\n * Gets the `element` image stream.\n * @private\n */\n get: function () {\n return this.imageStream;\n },\n enumerable: true,\n configurable: true\n });\n PdfImage.prototype.getPointSize = function (width, height, horizontalResolution, verticalResolution) {\n if (typeof horizontalResolution === 'undefined') {\n var dpiX = PdfUnitConverter.horizontalResolution;\n var dpiY = PdfUnitConverter.verticalResolution;\n var size = this.getPointSize(width, height, dpiX, dpiY);\n return size;\n }\n else {\n var ucX = new PdfUnitConverter(horizontalResolution);\n var ucY = new PdfUnitConverter(verticalResolution);\n var ptWidth = ucX.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);\n var ptHeight = ucY.convertUnits(height, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);\n var size = new SizeF(ptWidth, ptHeight);\n return size;\n }\n };\n return PdfImage;\n}());\nexport { PdfImage };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfBitmap.ts class for EJ2-PDF\n */\nimport { ImageDecoder } from './../../graphics/images/image-decoder';\nimport { ByteArray } from './../../graphics/images/byte-array';\nimport { DictionaryProperties } from './../../input-output/pdf-dictionary-properties';\nimport { PdfImage } from './pdf-image';\n/**\n * The 'PdfBitmap' contains methods and properties to handle the Bitmap images.\n * ```typescript\n * // create a new PDF document.\n * let document : PdfDocument = new PdfDocument();\n * // add a page to the document.\n * let page1 : PdfPage = document.pages.add();\n * // base64 string of an image\n * let imageString : string = '/9j/3+2w7em7HzY/KiijFw … 1OEYRUYrQ45yc5OUtz/9k=';\n * // load the image from the base64 string of original image.\n * let image : PdfBitmap = new PdfBitmap(imageString);\n * // draw the image\n * page1.graphics.drawImage(image, new RectangleF({x : 10, y : 10}, {width : 200, height : 200}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfBitmap = /** @class */ (function (_super) {\n __extends(PdfBitmap, _super);\n /**\n * Create an instance for `PdfBitmap` class.\n * @param encodedString Base64 string of an image.\n * ```typescript\n * // create a new PDF document.\n * let document : PdfDocument = new PdfDocument();\n * // add a page to the document.\n * let page1 : PdfPage = document.pages.add();\n * // base64 string of an image\n * let imageString : string = '/9j/3+2w7em7HzY/KiijFw … 1OEYRUYrQ45yc5OUtz/9k=';\n * //\n * // load the image from the base64 string of original image.\n * let image : PdfBitmap = new PdfBitmap(imageString);\n * //\n * // draw the image\n * page1.graphics.drawImage(image, new RectangleF({x : 10, y : 10}, {width : 200, height : 200}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n function PdfBitmap(encodedString) {\n var _this = _super.call(this) || this;\n //Fields\n /**\n * Specifies the `status` of an image.\n * @default true.\n * @hidden\n * @private\n */\n _this.imageStatus = true;\n /**\n * Internal variable for accessing fields from `DictionryProperties` class.\n * @hidden\n * @private\n */\n _this.dictionaryProperties = new DictionaryProperties();\n _this.loadImage(encodedString);\n return _this;\n }\n /**\n * `Load image`.\n * @hidden\n * @private\n */\n PdfBitmap.prototype.loadImage = function (encodedString) {\n var task = this.initializeAsync(encodedString);\n };\n /**\n * `Initialize` image parameters.\n * @private\n */\n PdfBitmap.prototype.initializeAsync = function (encodedString) {\n var byteArray = new ByteArray(encodedString.length);\n byteArray.writeFromBase64String(encodedString);\n this.decoder = new ImageDecoder(byteArray);\n this.height = this.decoder.height;\n this.width = this.decoder.width;\n // FrameCount = BitmapImageDecoder.FrameCount;\n this.bitsPerComponent = this.decoder.bitsPerComponent;\n };\n /**\n * `Saves` the image into stream.\n * @private\n */\n PdfBitmap.prototype.save = function () {\n this.imageStatus = true;\n this.imageStream = this.decoder.getImageDictionary();\n };\n return PdfBitmap;\n}(PdfImage));\nexport { PdfBitmap };\n","/**\n * TtfTableInfo.ts class for EJ2-PDF\n */\nvar TtfTableInfo = /** @class */ (function () {\n function TtfTableInfo() {\n }\n Object.defineProperty(TtfTableInfo.prototype, \"empty\", {\n //Properties\n /**\n * Gets a value indicating whether this table is empty.\n * @private\n */\n get: function () {\n var empty = (this.offset === this.length && this.length === this.checksum && this.checksum === 0);\n return empty;\n },\n enumerable: true,\n configurable: true\n });\n return TtfTableInfo;\n}());\nexport { TtfTableInfo };\n","var TtfNameTable = /** @class */ (function () {\n function TtfNameTable() {\n }\n return TtfNameTable;\n}());\nexport { TtfNameTable };\n","/**\n * TtfNameRecord.ts class for EJ2-PDF\n */\nvar TtfNameRecord = /** @class */ (function () {\n function TtfNameRecord() {\n }\n return TtfNameRecord;\n}());\nexport { TtfNameRecord };\n","/**\n * TtfHeadTable.ts class for EJ2-PDF\n */\nvar TtfHeadTable = /** @class */ (function () {\n function TtfHeadTable() {\n }\n return TtfHeadTable;\n}());\nexport { TtfHeadTable };\n","var TtfMetrics = /** @class */ (function () {\n function TtfMetrics() {\n }\n Object.defineProperty(TtfMetrics.prototype, \"isItalic\", {\n //Properties\n /**\n * Gets a value indicating whether this instance is italic.\n */\n get: function () {\n return ((this.macStyle & 2) !== 0);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TtfMetrics.prototype, \"isBold\", {\n /**\n * Gets a value indicating whether this instance is bold.\n */\n get: function () {\n return ((this.macStyle & 1) !== 0);\n },\n enumerable: true,\n configurable: true\n });\n return TtfMetrics;\n}());\nexport { TtfMetrics };\n","/**\n * TtfHorizontalHeaderTable.ts class for EJ2-PDF\n */\nvar TtfHorizontalHeaderTable = /** @class */ (function () {\n function TtfHorizontalHeaderTable() {\n }\n return TtfHorizontalHeaderTable;\n}());\nexport { TtfHorizontalHeaderTable };\n","/**\n * TtfOS2Table.ts class for EJ2-PDF\n * The OS/2 table consists of a set of metrics that are required by Windows and OS/2.\n */\nvar TtfOS2Table = /** @class */ (function () {\n function TtfOS2Table() {\n }\n return TtfOS2Table;\n}());\nexport { TtfOS2Table };\n","/**\n * TtfPostTable.ts class for EJ2-PDF\n */\nvar TtfPostTable = /** @class */ (function () {\n function TtfPostTable() {\n }\n return TtfPostTable;\n}());\nexport { TtfPostTable };\n","/**\n * TtfLongHorMetric.ts class for EJ2-PDF\n */\nvar TtfLongHorMetric = /** @class */ (function () {\n function TtfLongHorMetric() {\n }\n return TtfLongHorMetric;\n}());\nexport { TtfLongHorMetric };\n","/**\n * TtfCmapSubTable.ts class for EJ2-PDF\n */\nvar TtfCmapSubTable = /** @class */ (function () {\n function TtfCmapSubTable() {\n }\n return TtfCmapSubTable;\n}());\nexport { TtfCmapSubTable };\n","/**\n * TtfCmapTable.ts class for EJ2-PDF\n */\nvar TtfCmapTable = /** @class */ (function () {\n function TtfCmapTable() {\n }\n return TtfCmapTable;\n}());\nexport { TtfCmapTable };\n","/**\n * TtfGlyphInfo.ts class for EJ2-PDF\n */\nvar TtfGlyphInfo = /** @class */ (function () {\n function TtfGlyphInfo() {\n }\n Object.defineProperty(TtfGlyphInfo.prototype, \"empty\", {\n //Properties\n /**\n * Gets a value indicating whether this TtfGlyphInfo is empty.\n */\n get: function () {\n var empty = (this.index === this.width && this.width === this.charCode && this.charCode === 0);\n return empty;\n },\n enumerable: true,\n configurable: true\n });\n //IComparable implementation\n /**\n * Compares two WidthDescriptor objects.\n */\n TtfGlyphInfo.prototype.compareTo = function (obj) {\n var glyph = obj;\n return this.index - glyph.index;\n };\n return TtfGlyphInfo;\n}());\nexport { TtfGlyphInfo };\n","/**\n * TtfLocaTable.ts class for EJ2-PDF\n */\nvar TtfLocaTable = /** @class */ (function () {\n function TtfLocaTable() {\n }\n return TtfLocaTable;\n}());\nexport { TtfLocaTable };\n","/**\n * TtfAppleCmapSubTable.ts class for EJ2-PDF\n */\nvar TtfAppleCmapSubTable = /** @class */ (function () {\n function TtfAppleCmapSubTable() {\n }\n return TtfAppleCmapSubTable;\n}());\nexport { TtfAppleCmapSubTable };\n","/**\n * TtfMicrosoftCmapSubTable.ts class for EJ2-PDF\n */\nvar TtfMicrosoftCmapSubTable = /** @class */ (function () {\n function TtfMicrosoftCmapSubTable() {\n }\n return TtfMicrosoftCmapSubTable;\n}());\nexport { TtfMicrosoftCmapSubTable };\n","/**\n * TtfTrimmedCmapSubTable.ts class for EJ2-PDF\n */\nvar TtfTrimmedCmapSubTable = /** @class */ (function () {\n function TtfTrimmedCmapSubTable() {\n }\n return TtfTrimmedCmapSubTable;\n}());\nexport { TtfTrimmedCmapSubTable };\n","/**\n * TtfLocaTable.ts class for EJ2-PDF\n */\nvar TtfGlyphHeader = /** @class */ (function () {\n function TtfGlyphHeader() {\n }\n return TtfGlyphHeader;\n}());\nexport { TtfGlyphHeader };\n","/**\n * Writes data in BigEndian order.\n */\nvar BigEndianWriter = /** @class */ (function () {\n //Constructors\n /**\n * Creates a new writer.\n */\n function BigEndianWriter(capacity) {\n //Constants\n /**\n * Size of Int32 type.\n */\n this.int32Size = 4;\n /**\n * Size of Int16 type.\n */\n this.int16Size = 2;\n /**\n * Size of long type.\n */\n this.int64Size = 8;\n this.bufferLength = capacity;\n this.buffer = [];\n }\n Object.defineProperty(BigEndianWriter.prototype, \"data\", {\n //Properties\n /**\n * Gets data written to the writer.\n */\n get: function () {\n if (this.buffer.length < this.bufferLength) {\n var length_1 = this.bufferLength - this.buffer.length;\n for (var i = 0; i < length_1; i++) {\n this.buffer.push(0);\n }\n }\n return this.buffer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BigEndianWriter.prototype, \"position\", {\n /// \n /// Gets position of the internal buffer.\n /// \n get: function () {\n if (this.internalPosition === undefined || this.internalPosition === null) {\n this.internalPosition = 0;\n }\n return this.internalPosition;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Writes short value.\n */\n BigEndianWriter.prototype.writeShort = function (value) {\n var bytes = [((value & 0x0000ff00) >> 8), value & 0x000000ff];\n this.flush(bytes);\n };\n /**\n * Writes int value.\n */\n BigEndianWriter.prototype.writeInt = function (value) {\n var i1 = (value & 0xff000000) >> 24;\n i1 = i1 < 0 ? 256 + i1 : i1;\n var i2 = (value & 0x00ff0000) >> 16;\n i2 = i2 < 0 ? 256 + i2 : i2;\n var i3 = (value & 0x0000ff00) >> 8;\n i3 = i3 < 0 ? 256 + i3 : i3;\n var i4 = value & 0x000000ff;\n i4 = i4 < 0 ? 256 + i4 : i4;\n var bytes = [(value & 0xff000000) >> 24, (value & 0x00ff0000) >> 16, (value & 0x0000ff00) >> 8, value & 0x000000ff];\n this.flush(bytes);\n };\n /**\n * Writes u int value.\n */\n BigEndianWriter.prototype.writeUInt = function (value) {\n var buff = [(value & 0xff000000) >> 24, (value & 0x00ff0000) >> 16, (value & 0x0000ff00) >> 8, value & 0x000000ff];\n this.flush(buff);\n };\n /**\n * Writes string value.\n */\n BigEndianWriter.prototype.writeString = function (value) {\n if (value == null) {\n throw new Error('Argument Null Exception : value');\n }\n var bytes = [];\n for (var i = 0; i < value.length; i++) {\n bytes.push(value.charCodeAt(i));\n }\n this.flush(bytes);\n };\n /**\n * Writes byte[] value.\n */\n BigEndianWriter.prototype.writeBytes = function (value) {\n this.flush(value);\n };\n // //Implementation\n BigEndianWriter.prototype.flush = function (buff) {\n if (buff === null) {\n throw new Error('Argument Null Exception : buff');\n }\n var result = [];\n for (var i = 0; i < this.position; i++) {\n result.push(this.buffer[i]);\n }\n for (var i = 0; i < buff.length; i++) {\n result.push(buff[i]);\n }\n for (var i = this.position; i < this.buffer.length; i++) {\n result.push(this.buffer[i]);\n }\n this.buffer = result;\n this.internalPosition += buff.length;\n };\n return BigEndianWriter;\n}());\nexport { BigEndianWriter };\n","/**\n * TtfReader.ts class for EJ2-PDF\n */\nimport { TtfTableInfo } from './ttf-table-info';\nimport { Dictionary } from './../../collections/dictionary';\nimport { TtfNameTable } from './ttf-name-table';\nimport { TtfNameRecord } from './ttf-name-record';\nimport { TtfHeadTable } from './ttf-head-table';\nimport { TtfMetrics } from './ttf-metrics';\nimport { TtfHorizontalHeaderTable } from './ttf-horizontal-header-table';\nimport { TtfOS2Table } from './ttf-OS2-Table';\nimport { TtfPostTable } from './ttf-post-table';\nimport { TtfLongHorMetric } from './ttf-long-hor-metric';\nimport { TtfCmapSubTable } from './ttf-cmap-sub-table';\nimport { TtfCmapTable } from './ttf-cmap-table';\nimport { TtfGlyphInfo } from './ttf-glyph-info';\nimport { TtfLocaTable } from './ttf-loca-table';\nimport { TtfAppleCmapSubTable } from './ttf-apple-cmap-sub-table';\nimport { TtfMicrosoftCmapSubTable } from './ttf-microsoft-cmap-sub-table';\nimport { TtfTrimmedCmapSubTable } from './ttf-trimmed-cmap-sub-table';\nimport { TtfGlyphHeader } from './ttf-glyph-header';\nimport { Rectangle } from './../../drawing/pdf-drawing';\nimport { StringTokenizer } from './string-tokenizer';\nimport { TtfCmapFormat, TtfCmapEncoding, TtfPlatformID } from './enum';\nimport { TtfMicrosoftEncodingID, TtfMacintoshEncodingID, TtfCompositeGlyphFlags } from './enum';\nimport { BigEndianWriter } from './../../input-output/big-endian-writer';\nvar TtfReader = /** @class */ (function () {\n //Constructors\n function TtfReader(fontData) {\n this.int32Size = 4;\n this.isTtcFont = false;\n this.isMacTtf = false;\n this.metricsName = '';\n this.isMacTTF = false;\n this.missedGlyphs = 0;\n this.tableNames = ['cvt ', 'fpgm', 'glyf', 'head', 'hhea', 'hmtx', 'loca', 'maxp', 'prep'];\n this.entrySelectors = [0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4];\n this.fontData = fontData;\n this.initialize();\n }\n Object.defineProperty(TtfReader.prototype, \"macintosh\", {\n //Properties\n /**\n * Gets glyphs for Macintosh or Symbol fonts (char - key, glyph - value).\n */\n get: function () {\n if (this.macintoshDictionary === null || this.macintoshDictionary === undefined) {\n this.macintoshDictionary = new Dictionary();\n }\n return this.macintoshDictionary;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TtfReader.prototype, \"microsoft\", {\n /**\n * Gets glyphs for Microsoft or Symbol fonts (char - key, glyph - value).\n */\n get: function () {\n if (this.microsoftDictionary === null || this.microsoftDictionary === undefined) {\n this.microsoftDictionary = new Dictionary();\n }\n return this.microsoftDictionary;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TtfReader.prototype, \"macintoshGlyphs\", {\n /**\n * Gets glyphs for Macintosh or Symbol fonts (glyph index - key, glyph - value).\n */\n get: function () {\n if (this.internalMacintoshGlyphs === null || this.internalMacintoshGlyphs === undefined) {\n this.internalMacintoshGlyphs = new Dictionary();\n }\n return this.internalMacintoshGlyphs;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TtfReader.prototype, \"microsoftGlyphs\", {\n /**\n * Gets glyphs for Microsoft Unicode fonts (glyph index - key, glyph - value).\n */\n get: function () {\n if (this.internalMicrosoftGlyphs === null || this.internalMicrosoftGlyphs === undefined) {\n this.internalMicrosoftGlyphs = new Dictionary();\n }\n return this.internalMicrosoftGlyphs;\n },\n enumerable: true,\n configurable: true\n });\n //Implementation\n TtfReader.prototype.initialize = function () {\n if (this.metrics === undefined) {\n this.metrics = new TtfMetrics();\n }\n this.readFontDictionary();\n var nameTable = this.readNameTable();\n var headTable = this.readHeadTable();\n this.initializeFontName(nameTable);\n this.metrics.macStyle = headTable.macStyle;\n };\n TtfReader.prototype.readFontDictionary = function () {\n this.offset = 0;\n var version = this.checkPreambula();\n //this.offset += 4;\n var numTables = this.readInt16(this.offset);\n var searchRange = this.readInt16(this.offset);\n var entrySelector = this.readInt16(this.offset);\n var rangeShift = this.readInt16(this.offset);\n if (this.tableDirectory === undefined) {\n this.tableDirectory = new Dictionary();\n }\n for (var i = 0; i < numTables; ++i) {\n var table = new TtfTableInfo();\n var tableKey = this.readString(this.int32Size);\n table.checksum = this.readInt32(this.offset);\n table.offset = this.readInt32(this.offset);\n table.length = this.readInt32(this.offset);\n this.tableDirectory.setValue(tableKey, table);\n }\n this.lowestPosition = this.offset;\n if (!this.isTtcFont) {\n this.fixOffsets();\n }\n };\n TtfReader.prototype.fixOffsets = function () {\n var minOffset = Number.MAX_VALUE;\n // Search for a smallest offset and compare it with the lowest position found.\n var tableKeys = this.tableDirectory.keys();\n for (var i = 0; i < tableKeys.length; i++) {\n var value = this.tableDirectory.getValue(tableKeys[i]);\n var offset = value.offset;\n if (minOffset > offset) {\n minOffset = offset;\n if (minOffset <= this.lowestPosition) {\n break;\n }\n }\n }\n var shift = minOffset - this.lowestPosition;\n if (shift !== 0) {\n var table = new Dictionary();\n for (var i = 0; i < tableKeys.length; i++) {\n var value = this.tableDirectory.getValue(tableKeys[i]);\n value.offset -= shift;\n table.setValue(tableKeys[i], value);\n }\n this.tableDirectory = table;\n }\n };\n TtfReader.prototype.checkPreambula = function () {\n var version = this.readInt32(this.offset);\n this.isMacTtf = (version === 0x74727565) ? true : false;\n if (version !== 0x10000 && version !== 0x74727565 && version !== 0x4f54544f) {\n this.isTtcFont = true;\n this.offset = 0;\n var fontTag = this.readString(4);\n if (fontTag !== 'ttcf') {\n throw new Error('Can not read TTF font data');\n }\n //skip 4\n this.offset += 4;\n var ttcIdentificationNumber = this.readInt32(this.offset);\n if (ttcIdentificationNumber < 0) {\n throw new Error('Can not read TTF font data');\n }\n this.offset = this.readInt32(this.offset);\n version = this.readInt32(this.offset);\n }\n return version;\n };\n TtfReader.prototype.readNameTable = function () {\n var tableInfo = this.getTable('name');\n this.offset = tableInfo.offset;\n var table = new TtfNameTable();\n table.formatSelector = this.readUInt16(this.offset);\n table.recordsCount = this.readUInt16(this.offset);\n table.offset = this.readUInt16(this.offset);\n table.nameRecords = [];\n var recordSize = 12;\n var position = this.offset;\n for (var i = 0; i < table.recordsCount; i++) {\n this.offset = position;\n var record = new TtfNameRecord();\n record.platformID = this.readUInt16(this.offset);\n record.encodingID = this.readUInt16(this.offset);\n record.languageID = this.readUInt16(this.offset);\n record.nameID = this.readUInt16(this.offset);\n record.length = this.readUInt16(this.offset);\n record.offset = this.readUInt16(this.offset);\n this.offset = tableInfo.offset + table.offset + record.offset;\n var unicode = (record.platformID === 0 || record.platformID === 3);\n record.name = this.readString(record.length, unicode);\n table.nameRecords[i] = record;\n position += recordSize;\n }\n return table;\n };\n TtfReader.prototype.readHeadTable = function () {\n var tableInfo = this.getTable('head');\n this.offset = tableInfo.offset;\n var table = new TtfHeadTable();\n table.version = this.readFixed(this.offset);\n table.fontRevision = this.readFixed(this.offset);\n table.checkSumAdjustment = this.readUInt32(this.offset);\n table.magicNumber = this.readUInt32(this.offset);\n table.flags = this.readUInt16(this.offset);\n table.unitsPerEm = this.readUInt16(this.offset);\n table.created = this.readInt64(this.offset);\n table.modified = this.readInt64(this.offset);\n table.xMin = this.readInt16(this.offset);\n table.yMin = this.readInt16(this.offset);\n table.xMax = this.readInt16(this.offset);\n table.yMax = this.readInt16(this.offset);\n table.macStyle = this.readUInt16(this.offset);\n table.lowestReadableSize = this.readUInt16(this.offset);\n table.fontDirectionHint = this.readInt16(this.offset);\n table.indexToLocalFormat = this.readInt16(this.offset);\n table.glyphDataFormat = this.readInt16(this.offset);\n return table;\n };\n TtfReader.prototype.readHorizontalHeaderTable = function () {\n var tableInfo = this.getTable('hhea');\n this.offset = tableInfo.offset;\n var table = new TtfHorizontalHeaderTable();\n table.version = this.readFixed(this.offset);\n table.ascender = this.readInt16(this.offset);\n table.descender = this.readInt16(this.offset);\n table.lineGap = this.readInt16(this.offset);\n table.advanceWidthMax = this.readUInt16(this.offset);\n table.minLeftSideBearing = this.readInt16(this.offset);\n table.minRightSideBearing = this.readInt16(this.offset);\n table.xMaxExtent = this.readInt16(this.offset);\n table.caretSlopeRise = this.readInt16(this.offset);\n table.caretSlopeRun = this.readInt16(this.offset);\n //skip 2 * 5\n this.offset += 10;\n table.metricDataFormat = this.readInt16(this.offset);\n table.numberOfHMetrics = this.readUInt16(this.offset);\n return table;\n };\n TtfReader.prototype.readOS2Table = function () {\n var tableInfo = this.getTable('OS/2');\n this.offset = tableInfo.offset;\n var table = new TtfOS2Table();\n table.version = this.readUInt16(this.offset);\n table.xAvgCharWidth = this.readInt16(this.offset);\n table.usWeightClass = this.readUInt16(this.offset);\n table.usWidthClass = this.readUInt16(this.offset);\n table.fsType = this.readInt16(this.offset);\n table.ySubscriptXSize = this.readInt16(this.offset);\n table.ySubscriptYSize = this.readInt16(this.offset);\n table.ySubscriptXOffset = this.readInt16(this.offset);\n table.ySubscriptYOffset = this.readInt16(this.offset);\n table.ySuperscriptXSize = this.readInt16(this.offset);\n table.ySuperscriptYSize = this.readInt16(this.offset);\n table.ySuperscriptXOffset = this.readInt16(this.offset);\n table.ySuperscriptYOffset = this.readInt16(this.offset);\n table.yStrikeoutSize = this.readInt16(this.offset);\n table.yStrikeoutPosition = this.readInt16(this.offset);\n table.sFamilyClass = this.readInt16(this.offset);\n table.panose = this.readBytes(10);\n table.ulUnicodeRange1 = this.readUInt32(this.offset);\n table.ulUnicodeRange2 = this.readUInt32(this.offset);\n table.ulUnicodeRange3 = this.readUInt32(this.offset);\n table.ulUnicodeRange4 = this.readUInt32(this.offset);\n table.vendorIdentifier = this.readBytes(4);\n table.fsSelection = this.readUInt16(this.offset);\n table.usFirstCharIndex = this.readUInt16(this.offset);\n table.usLastCharIndex = this.readUInt16(this.offset);\n table.sTypoAscender = this.readInt16(this.offset);\n table.sTypoDescender = this.readInt16(this.offset);\n table.sTypoLineGap = this.readInt16(this.offset);\n table.usWinAscent = this.readUInt16(this.offset);\n table.usWinDescent = this.readUInt16(this.offset);\n table.ulCodePageRange1 = this.readUInt32(this.offset);\n table.ulCodePageRange2 = this.readUInt32(this.offset);\n if (table.version > 1) {\n table.sxHeight = this.readInt16(this.offset);\n table.sCapHeight = this.readInt16(this.offset);\n table.usDefaultChar = this.readUInt16(this.offset);\n table.usBreakChar = this.readUInt16(this.offset);\n table.usMaxContext = this.readUInt16(this.offset);\n }\n else {\n table.sxHeight = 0;\n table.sCapHeight = 0;\n table.usDefaultChar = 0;\n table.usBreakChar = 0;\n table.usMaxContext = 0;\n }\n return table;\n };\n TtfReader.prototype.readPostTable = function () {\n var tableInfo = this.getTable('post');\n this.offset = tableInfo.offset;\n var table = new TtfPostTable();\n table.formatType = this.readFixed(this.offset);\n table.italicAngle = this.readFixed(this.offset);\n table.underlinePosition = this.readInt16(this.offset);\n table.underlineThickness = this.readInt16(this.offset);\n table.isFixedPitch = this.readUInt32(this.offset);\n table.minType42 = this.readUInt32(this.offset);\n table.maxType42 = this.readUInt32(this.offset);\n table.minType1 = this.readUInt32(this.offset);\n table.maxType1 = this.readUInt32(this.offset);\n return table;\n };\n /**\n * Reads Width of the glyphs.\n */\n TtfReader.prototype.readWidthTable = function (glyphCount, unitsPerEm) {\n var tableInfo = this.getTable('hmtx');\n this.offset = tableInfo.offset;\n var width = [];\n for (var i = 0; i < glyphCount; i++) {\n var glyph = new TtfLongHorMetric();\n glyph.advanceWidth = this.readUInt16(this.offset);\n glyph.lsb = this.readInt16(this.offset);\n var glyphWidth = glyph.advanceWidth * 1000 / unitsPerEm;\n width.push(Math.floor(glyphWidth));\n }\n return width;\n };\n /**\n * Reads the cmap table.\n */\n TtfReader.prototype.readCmapTable = function () {\n var tableInfo = this.getTable('cmap');\n this.offset = tableInfo.offset;\n var table = new TtfCmapTable();\n table.version = this.readUInt16(this.offset);\n table.tablesCount = this.readUInt16(this.offset);\n var position = this.offset;\n var subTables = [];\n for (var i = 0; i < table.tablesCount; i++) {\n this.offset = position;\n var subTable = new TtfCmapSubTable();\n subTable.platformID = this.readUInt16(this.offset);\n subTable.encodingID = this.readUInt16(this.offset);\n subTable.offset = this.readUInt32(this.offset);\n position = this.offset;\n this.readCmapSubTable(subTable);\n subTables[i] = subTable;\n }\n return subTables;\n };\n /**\n * Reads the cmap sub table.\n */\n TtfReader.prototype.readCmapSubTable = function (subTable) {\n var tableInfo = this.getTable('cmap');\n this.offset = tableInfo.offset + subTable.offset;\n var format = this.readUInt16(this.offset);\n var encoding = this.getCmapEncoding(subTable.platformID, subTable.encodingID);\n var platform = (encoding === TtfCmapEncoding.Macintosh) ? TtfPlatformID.Macintosh : TtfPlatformID.Microsoft;\n if (encoding !== TtfCmapEncoding.Unknown) {\n switch (format) {\n case TtfCmapFormat.Apple:\n this.readAppleCmapTable(subTable, encoding);\n break;\n case TtfCmapFormat.Microsoft:\n this.readMicrosoftCmapTable(subTable, encoding);\n break;\n case TtfCmapFormat.Trimmed:\n this.readTrimmedCmapTable(subTable, encoding);\n break;\n }\n }\n };\n /**\n * Reads Symbol cmap table.\n */\n TtfReader.prototype.readAppleCmapTable = function (subTable, encoding) {\n var tableInfo = this.getTable('cmap');\n this.offset = tableInfo.offset + subTable.offset;\n var table = new TtfAppleCmapSubTable();\n table.format = this.readUInt16(this.offset);\n table.length = this.readUInt16(this.offset);\n table.version = this.readUInt16(this.offset);\n if (this.maxMacIndex === null || this.maxMacIndex === undefined) {\n this.maxMacIndex = 0;\n }\n for (var i = 0; i < 256; ++i) {\n var glyphInfo = new TtfGlyphInfo();\n glyphInfo.index = this.readByte(this.offset);\n glyphInfo.width = this.getWidth(glyphInfo.index);\n glyphInfo.charCode = i;\n this.macintosh.setValue(i, glyphInfo);\n this.addGlyph(glyphInfo, encoding);\n // NOTE: this code fixes char codes that extends 0x100. However, it might corrupt something.\n this.maxMacIndex = Math.max(i, this.maxMacIndex);\n }\n };\n /**\n * Reads Symbol cmap table.\n */\n TtfReader.prototype.readMicrosoftCmapTable = function (subTable, encoding) {\n var tableInfo = this.getTable('cmap');\n this.offset = tableInfo.offset + subTable.offset;\n var collection = (encoding === TtfCmapEncoding.Unicode) ? this.microsoft : this.macintosh;\n var table = new TtfMicrosoftCmapSubTable();\n table.format = this.readUInt16(this.offset);\n table.length = this.readUInt16(this.offset);\n table.version = this.readUInt16(this.offset);\n table.segCountX2 = this.readUInt16(this.offset);\n table.searchRange = this.readUInt16(this.offset);\n table.entrySelector = this.readUInt16(this.offset);\n table.rangeShift = this.readUInt16(this.offset);\n var segCount = table.segCountX2 / 2;\n table.endCount = this.readUshortArray(segCount);\n table.reservedPad = this.readUInt16(this.offset);\n table.startCount = this.readUshortArray(segCount);\n table.idDelta = this.readUshortArray(segCount);\n table.idRangeOffset = this.readUshortArray(segCount);\n var length = (table.length / 2 - 8) - (segCount * 4);\n table.glyphID = this.readUshortArray(length);\n // Process glyphIdArray array.\n var codeOffset = 0;\n var index = 0;\n for (var j = 0; j < segCount; j++) {\n for (var k = table.startCount[j]; k <= table.endCount[j] && k !== 65535; k++) {\n if (table.idRangeOffset[j] === 0) {\n codeOffset = (k + table.idDelta[j]) & 65535;\n }\n else {\n index = j + table.idRangeOffset[j] / 2 - segCount + k - table.startCount[j];\n if (index >= table.glyphID.length) {\n continue;\n }\n codeOffset = (table.glyphID[index] + table.idDelta[j]) & 65535;\n }\n var glyph = new TtfGlyphInfo();\n glyph.index = codeOffset;\n glyph.width = this.getWidth(glyph.index);\n var id = (encoding === TtfCmapEncoding.Symbol) ? ((k & 0xff00) === 0xf000 ? k & 0xff : k) : k;\n glyph.charCode = id;\n collection.setValue(id, glyph);\n this.addGlyph(glyph, encoding);\n }\n }\n };\n /**\n * Reads Trimed cmap table.\n */\n TtfReader.prototype.readTrimmedCmapTable = function (subTable, encoding) {\n var tableInfo = this.getTable('cmap');\n this.offset = tableInfo.offset + subTable.offset;\n var table = new TtfTrimmedCmapSubTable();\n table.format = this.readUInt16(this.offset);\n table.length = this.readUInt16(this.offset);\n table.version = this.readUInt16(this.offset);\n table.firstCode = this.readUInt16(this.offset);\n table.entryCount = this.readUInt16(this.offset);\n for (var i = 0; i < table.entryCount; ++i) {\n var glyphInfo = new TtfGlyphInfo();\n glyphInfo.index = this.readUInt16(this.offset);\n glyphInfo.width = this.getWidth(glyphInfo.index);\n glyphInfo.charCode = i + table.firstCode;\n this.macintosh.setValue(i, glyphInfo);\n this.addGlyph(glyphInfo, encoding);\n // NOTE: this code fixes char codes that extends 0x100. However, it might corrupt something.\n this.maxMacIndex = Math.max(i, this.maxMacIndex);\n }\n };\n TtfReader.prototype.initializeFontName = function (nameTable) {\n for (var i = 0; i < nameTable.recordsCount; i++) {\n var record = nameTable.nameRecords[i];\n if (record.nameID === 1) {\n //font family\n this.metrics.fontFamily = record.name;\n }\n else if (record.nameID === 6) {\n //post script name\n this.metrics.postScriptName = record.name;\n }\n /* tslint:disable */\n if (this.metrics.fontFamily !== null && this.metrics.fontFamily !== undefined && this.metrics.postScriptName !== null && this.metrics.postScriptName !== undefined) {\n break;\n }\n /* tslint:disable */\n }\n };\n TtfReader.prototype.getTable = function (name) {\n // if (name === null) {\n // throw new Error('Argument Null Exception : name');\n // }\n var table = new TtfTableInfo();\n var obj;\n if (this.tableDirectory.containsKey(name)) {\n obj = this.tableDirectory.getValue(name);\n }\n if (obj !== null && obj !== undefined) {\n table = obj;\n }\n return table;\n };\n /**\n * Returns width of the glyph.\n */\n TtfReader.prototype.getWidth = function (glyphCode) {\n glyphCode = (glyphCode < this.width.length) ? glyphCode : this.width.length - 1;\n return this.width[glyphCode];\n };\n /**\n * Gets CMAP encoding based on platform ID and encoding ID.\n */\n /* tslint:disable */\n TtfReader.prototype.getCmapEncoding = function (platformID, encodingID) {\n var format = TtfCmapEncoding.Unknown;\n if (platformID == TtfPlatformID.Microsoft && encodingID == TtfMicrosoftEncodingID.Undefined) {\n // When building a symbol font for Windows,\n // the platform ID should be 3 and the encoding ID should be 0.\n format = TtfCmapEncoding.Symbol;\n }\n else if (platformID == TtfPlatformID.Microsoft && encodingID == TtfMicrosoftEncodingID.Unicode) {\n // When building a Unicode font for Windows,\n // the platform ID should be 3 and the encoding ID should be 1.\n format = TtfCmapEncoding.Unicode;\n }\n else if (platformID == TtfPlatformID.Macintosh && encodingID == TtfMacintoshEncodingID.Roman) {\n // When building a font that will be used on the Macintosh,\n // the platform ID should be 1 and the encoding ID should be 0.\n format = TtfCmapEncoding.Macintosh;\n }\n return format;\n };\n /* tslint:enable */\n /**\n * Adds glyph to the collection.\n */\n TtfReader.prototype.addGlyph = function (glyph, encoding) {\n var collection = null;\n switch (encoding) {\n case TtfCmapEncoding.Unicode:\n collection = this.microsoftGlyphs;\n break;\n case TtfCmapEncoding.Macintosh:\n case TtfCmapEncoding.Symbol:\n collection = this.macintoshGlyphs;\n break;\n }\n collection.setValue(glyph.index, glyph);\n };\n /**\n * Initializes metrics.\n */\n /* tslint:disable */\n TtfReader.prototype.initializeMetrics = function (nameTable, headTable, horizontalHeadTable, os2Table, postTable, cmapTables) {\n /* tslint:enable */\n // if (cmapTables === null) {\n // throw new Error('ArgumentNullException : cmapTables');\n // }\n this.initializeFontName(nameTable);\n // Get font encoding.\n var bSymbol = false;\n for (var i = 0; i < cmapTables.length; i++) {\n var subTable = cmapTables[i];\n var encoding = this.getCmapEncoding(subTable.platformID, subTable.encodingID);\n if (encoding === TtfCmapEncoding.Symbol) {\n bSymbol = true;\n break;\n }\n }\n this.metrics.isSymbol = bSymbol;\n this.metrics.macStyle = headTable.macStyle;\n this.metrics.isFixedPitch = (postTable.isFixedPitch !== 0);\n this.metrics.italicAngle = postTable.italicAngle;\n var factor = 1000 / headTable.unitsPerEm;\n this.metrics.winAscent = os2Table.sTypoAscender * factor;\n this.metrics.macAscent = horizontalHeadTable.ascender * factor;\n //m_metrics.MacAscent = os2Table.UsWinAscent * factor;\n // NOTE: This is stange workaround. The value is good if os2Table.SCapHeight != 0, otherwise it should be properly computed.\n this.metrics.capHeight = (os2Table.sCapHeight !== 0) ? os2Table.sCapHeight : 0.7 * headTable.unitsPerEm * factor;\n this.metrics.winDescent = os2Table.sTypoDescender * factor;\n this.metrics.macDescent = horizontalHeadTable.descender * factor;\n //m_metrics.MacDescent = -os2Table.UsWinDescent * factor;\n this.metrics.leading = (os2Table.sTypoAscender - os2Table.sTypoDescender + os2Table.sTypoLineGap) * factor;\n this.metrics.lineGap = Math.ceil(horizontalHeadTable.lineGap * factor);\n var left = headTable.xMin * factor;\n var top = Math.ceil(this.metrics.macAscent + this.metrics.lineGap);\n var right = headTable.xMax * factor;\n var bottom = this.metrics.macDescent;\n this.metrics.fontBox = new Rectangle(left, top, right, bottom);\n // NOTE: Strange!\n this.metrics.stemV = 80;\n this.metrics.widthTable = this.updateWidth();\n this.metrics.contains = this.tableDirectory.containsKey('CFF');\n this.metrics.subScriptSizeFactor = headTable.unitsPerEm / os2Table.ySubscriptYSize;\n this.metrics.superscriptSizeFactor = headTable.unitsPerEm / os2Table.ySuperscriptYSize;\n };\n /**\n * Updates chars structure which is used in the case of ansi encoding (256 bytes).\n */\n TtfReader.prototype.updateWidth = function () {\n var count = 256;\n var bytes = [];\n if (this.metrics.isSymbol) {\n for (var i = 0; i < count; i++) {\n var glyphInfo = this.getGlyph(String.fromCharCode(i));\n bytes[i] = (glyphInfo.empty) ? 0 : glyphInfo.width;\n }\n }\n else {\n var byteToProcess = [];\n var unknown = '?';\n var space = String.fromCharCode(32);\n for (var i = 0; i < count; i++) {\n byteToProcess[0] = i;\n var text = this.getString(byteToProcess, 0, byteToProcess.length);\n var ch = (text.length > 0) ? text[0] : unknown;\n var glyphInfo = this.getGlyph(ch);\n if (!glyphInfo.empty) {\n bytes[i] = glyphInfo.width;\n }\n else {\n glyphInfo = this.getGlyph(space);\n bytes[i] = (glyphInfo.empty) ? 0 : glyphInfo.width;\n }\n }\n }\n return bytes;\n };\n /**\n * Returns default glyph.\n */\n TtfReader.prototype.getDefaultGlyph = function () {\n var glyph = this.getGlyph(StringTokenizer.whiteSpace);\n return glyph;\n };\n /**\n * Reads unicode string from byte array.\n */\n TtfReader.prototype.getString = function (byteToProcess, start, length) {\n var result = '';\n for (var index = 0; index < length; index++) {\n result += String.fromCharCode(byteToProcess[index + start]);\n }\n return result;\n };\n /**\n * Reads loca table.\n */\n TtfReader.prototype.readLocaTable = function (bShort) {\n var tableInfo = this.getTable('loca');\n this.offset = tableInfo.offset;\n var table = new TtfLocaTable();\n var buffer = null;\n if (bShort) {\n var len = tableInfo.length / 2;\n buffer = [];\n for (var i = 0; i < len; i++) {\n buffer[i] = this.readUInt16(this.offset) * 2;\n }\n }\n else {\n var len = tableInfo.length / 4;\n buffer = [];\n for (var i = 0; i < len; i++) {\n buffer[i] = this.readUInt32(this.offset);\n }\n }\n table.offsets = buffer;\n return table;\n };\n /**\n * Updates hash table of used glyphs.\n */\n TtfReader.prototype.updateGlyphChars = function (glyphChars, locaTable) {\n // if (glyphChars === null) {\n // throw new Error('Argument Null Exception : glyphChars');\n // }\n // Add zero key.\n if (!glyphChars.containsKey(0)) {\n glyphChars.setValue(0, 0);\n }\n var clone = new Dictionary();\n var glyphCharKeys = glyphChars.keys();\n for (var i = 0; i < glyphCharKeys.length; i++) {\n clone.setValue(glyphCharKeys[0], glyphChars.getValue(glyphCharKeys[0]));\n }\n for (var i = 0; i < glyphCharKeys.length; i++) {\n var nextKey = glyphCharKeys[0];\n this.processCompositeGlyph(glyphChars, nextKey, locaTable);\n }\n };\n /**\n * Checks if glyph is composite or not.\n */\n TtfReader.prototype.processCompositeGlyph = function (glyphChars, glyph, locaTable) {\n // if (glyphChars === null) {\n // throw new Error('Argument Null Exception : glyphChars');\n // }\n // Is in range.\n if (glyph < locaTable.offsets.length - 1) {\n var glyphOffset = locaTable.offsets[glyph];\n if (glyphOffset !== locaTable.offsets[glyph + 1]) {\n var tableInfo = this.getTable('glyf');\n this.offset = tableInfo.offset + glyphOffset;\n var glyphHeader = new TtfGlyphHeader();\n glyphHeader.numberOfContours = this.readInt16(this.offset);\n glyphHeader.xMin = this.readInt16(this.offset);\n glyphHeader.yMin = this.readInt16(this.offset);\n glyphHeader.xMax = this.readInt16(this.offset);\n glyphHeader.yMax = this.readInt16(this.offset);\n // Glyph is composite.\n if (glyphHeader.numberOfContours < 0) {\n var skipBytes = 0;\n var entry = true;\n while (entry) {\n var flags = this.readUInt16(this.offset);\n var glyphIndex = this.readUInt16(this.offset);\n if (!glyphChars.containsKey(glyphIndex)) {\n glyphChars.setValue(glyphIndex, 0);\n }\n if ((flags & TtfCompositeGlyphFlags.MoreComponents) === 0) {\n break;\n }\n skipBytes = ((flags & TtfCompositeGlyphFlags.Arg1And2AreWords) !== 0) ? 4 : 2;\n if ((flags & TtfCompositeGlyphFlags.WeHaveScale) !== 0) {\n skipBytes += 2;\n }\n else if ((flags & TtfCompositeGlyphFlags.WeHaveAnXyScale) !== 0) {\n skipBytes += 4;\n }\n else if ((flags & TtfCompositeGlyphFlags.WeHaveTwoByTwo) !== 0) {\n skipBytes += 2 * 4;\n }\n this.offset += skipBytes;\n }\n }\n }\n }\n };\n /**\n * Creates new glyph tables based on chars that are used for output.\n */\n /* tslint:disable */\n TtfReader.prototype.generateGlyphTable = function (glyphChars, locaTable, newLocaTable, newGlyphTable) {\n /* tslint:enable */\n // if (glyphChars === null) {\n // throw new Error('Argument Null Exception : glyphChars');\n // }\n newLocaTable = [];\n // Sorting used glyphs keys.\n var activeGlyphs = glyphChars.keys();\n activeGlyphs.sort(function (a, b) { return a - b; });\n var glyphSize = 0;\n for (var i = 0; i < activeGlyphs.length; i++) {\n var glyphIndex = activeGlyphs[i];\n if (locaTable.offsets.length > 0) {\n glyphSize += locaTable.offsets[glyphIndex + 1] - locaTable.offsets[glyphIndex];\n }\n }\n var glyphSizeAligned = this.align(glyphSize);\n newGlyphTable = [];\n for (var i = 0; i < glyphSizeAligned; i++) {\n newGlyphTable.push(0);\n }\n var nextGlyphOffset = 0;\n var nextGlyphIndex = 0;\n var table = this.getTable('glyf');\n // Creating NewLocaTable - that would hold offsets for filtered glyphs.\n for (var i = 0; i < locaTable.offsets.length; i++) {\n newLocaTable.push(nextGlyphOffset);\n if (nextGlyphIndex < activeGlyphs.length && activeGlyphs[nextGlyphIndex] === i) {\n ++nextGlyphIndex;\n newLocaTable[i] = nextGlyphOffset;\n var oldGlyphOffset = locaTable.offsets[i];\n var oldNextGlyphOffset = locaTable.offsets[i + 1] - oldGlyphOffset;\n if (oldNextGlyphOffset > 0) {\n this.offset = table.offset + oldGlyphOffset;\n var result = this.read(newGlyphTable, nextGlyphOffset, oldNextGlyphOffset);\n newGlyphTable = result.buffer;\n nextGlyphOffset += oldNextGlyphOffset;\n }\n }\n }\n return { glyphTableSize: glyphSize, newLocaTable: newLocaTable, newGlyphTable: newGlyphTable };\n };\n /**\n * Updates new Loca table.\n */\n /* tslint:disable */\n TtfReader.prototype.updateLocaTable = function (newLocaTable, bLocaIsShort, newLocaTableOut) {\n /* tslint:enable */\n if (newLocaTable === null) {\n throw new Error('Argument Null Exception : newLocaTable');\n }\n var size = (bLocaIsShort) ? newLocaTable.length * 2 : newLocaTable.length * 4;\n var count = this.align(size);\n //BigEndianWiter\n var writer = new BigEndianWriter(count);\n for (var i = 0; i < newLocaTable.length; i++) {\n var value = newLocaTable[i];\n if (bLocaIsShort) {\n value /= 2;\n writer.writeShort(value);\n }\n else {\n writer.writeInt(value);\n }\n }\n return { newLocaUpdated: writer.data, newLocaSize: size };\n };\n /**\n * Aligns number to be divisible on 4.\n */\n TtfReader.prototype.align = function (value) {\n return (value + 3) & (~3);\n };\n /**\n * Returns font program data.\n */\n /* tslint:disable */\n TtfReader.prototype.getFontProgram = function (newLocaTableOut, newGlyphTable, glyphTableSize, locaTableSize) {\n /* tslint:enable */\n if (newLocaTableOut === null) {\n throw new Error('Argument Null Exception : newLocaTableOut');\n }\n if (newGlyphTable === null) {\n throw new Error('Argument Null Exception : newGlyphTable');\n }\n var tableNames = this.tableNames;\n var result = this.getFontProgramLength(newLocaTableOut, newGlyphTable, 0);\n var fontProgramLength = result.fontProgramLength;\n var numTables = result.numTables;\n var writer = new BigEndianWriter(fontProgramLength);\n writer.writeInt(0x10000);\n writer.writeShort(numTables);\n var entrySelector = this.entrySelectors[numTables];\n writer.writeShort((1 << (entrySelector & 31)) * 16);\n writer.writeShort(entrySelector);\n writer.writeShort((numTables - (1 << (entrySelector & 31))) * 16);\n // Writing to destination buffer - checksums && sizes of used tables.\n this.writeCheckSums(writer, numTables, newLocaTableOut, newGlyphTable, glyphTableSize, locaTableSize);\n // // Writing to destination buffer - used glyphs.\n this.writeGlyphs(writer, newLocaTableOut, newGlyphTable);\n return writer.data;\n };\n /* tslint:disable */\n TtfReader.prototype.getFontProgramLength = function (newLocaTableOut, newGlyphTable, numTables) {\n /* tslint:enable */\n if (newLocaTableOut === null) {\n throw new Error('Argument Null Exception : newLocaTableOut');\n }\n if (newGlyphTable === null) {\n throw new Error('Argument Null Exception : newGlyphTable');\n }\n // glyf and loca are used by default;\n numTables = 2;\n var tableNames = this.tableNames;\n var fontProgramLength = 0;\n for (var i = 0; i < tableNames.length; i++) {\n var tableName = tableNames[i];\n if (tableName !== 'glyf' && tableName !== 'loca') {\n var table = this.getTable(tableName);\n if (!table.empty) {\n ++numTables;\n fontProgramLength += this.align(table.length);\n }\n }\n }\n fontProgramLength += newLocaTableOut.length;\n fontProgramLength += newGlyphTable.length;\n var usedTablesSize = numTables * 16 + (3 * 4);\n fontProgramLength += usedTablesSize;\n return { fontProgramLength: fontProgramLength, numTables: numTables };\n };\n /**\n * Writing to destination buffer - checksums and sizes of used tables.\n */\n /* tslint:disable */\n TtfReader.prototype.writeCheckSums = function (writer, numTables, newLocaTableOut, newGlyphTable, glyphTableSize, locaTableSize) {\n /* tslint:enable */\n if (writer === null) {\n throw new Error('Argument Null Exception : writer');\n }\n if (newLocaTableOut === null) {\n throw new Error('Argument Null Exception : newLocaTableOut');\n }\n if (newGlyphTable === null) {\n throw new Error('Argument Null Exception : newGlyphTable');\n }\n var tableNames = this.tableNames;\n var usedTablesSize = numTables * 16 + (3 * 4);\n var nextTableSize = 0;\n for (var i = 0; i < tableNames.length; i++) {\n var tableName = tableNames[i];\n var tableInfo = this.getTable(tableName);\n if (tableInfo.empty) {\n continue;\n }\n writer.writeString(tableName);\n if (tableName === 'glyf') {\n var checksum = this.calculateCheckSum(newGlyphTable);\n writer.writeInt(checksum);\n nextTableSize = glyphTableSize;\n }\n else if (tableName === 'loca') {\n var checksum = this.calculateCheckSum(newLocaTableOut);\n writer.writeInt(checksum);\n nextTableSize = locaTableSize;\n }\n else {\n writer.writeInt(tableInfo.checksum);\n nextTableSize = tableInfo.length;\n }\n writer.writeUInt(usedTablesSize);\n writer.writeUInt(nextTableSize);\n usedTablesSize += this.align(nextTableSize);\n }\n };\n /**\n * Gets checksum from source buffer.\n */\n TtfReader.prototype.calculateCheckSum = function (bytes) {\n if (bytes === null) {\n throw new Error('Argument Null Exception : bytes');\n }\n var pos = 0;\n var byte1 = 0;\n var byte2 = 0;\n var byte3 = 0;\n var byte4 = 0;\n for (var i = 0; i < (bytes.length + 1) / 4; i++) {\n byte4 += (bytes[pos++] & 255);\n byte3 += (bytes[pos++] & 255);\n byte2 += (bytes[pos++] & 255);\n byte1 += (bytes[pos++] & 255);\n }\n var result = byte1;\n result += (byte2 << 8);\n result += (byte3 << 16);\n result += (byte4 << 24);\n return result;\n };\n /**\n * Writing to destination buffer - used glyphs.\n */\n TtfReader.prototype.writeGlyphs = function (writer, newLocaTable, newGlyphTable) {\n if (writer === null) {\n throw new Error('Argument Null Exception : writer');\n }\n if (newLocaTable === null) {\n throw new Error('Argument Null Exception : newLocaTableOut');\n }\n if (newGlyphTable === null) {\n throw new Error('Argument Null Exception : newGlyphTable');\n }\n var tableNames = this.tableNames;\n for (var i = 0; i < tableNames.length; i++) {\n var tableName = tableNames[i];\n var tableInfo = this.getTable(tableName);\n if (tableInfo.empty) {\n continue;\n }\n if (tableName === 'glyf') {\n writer.writeBytes(newGlyphTable);\n }\n else if (tableName === 'loca') {\n writer.writeBytes(newLocaTable);\n }\n else {\n var count = this.align(tableInfo.length);\n var buff = [];\n for (var i_1 = 0; i_1 < count; i_1++) {\n buff.push(0);\n }\n this.offset = tableInfo.offset;\n var result = this.read(buff, 0, tableInfo.length);\n writer.writeBytes(result.buffer);\n }\n }\n };\n //public methods\n /**\n * Sets position value of font data.\n */\n TtfReader.prototype.setOffset = function (offset) {\n this.offset = offset;\n };\n /**\n * Creates font Internals\n * @private\n */\n TtfReader.prototype.createInternals = function () {\n this.metrics = new TtfMetrics();\n var nameTable = this.readNameTable();\n var headTable = this.readHeadTable();\n this.bIsLocaShort = (headTable.indexToLocalFormat === 0);\n var horizontalHeadTable = this.readHorizontalHeaderTable();\n var os2Table = this.readOS2Table();\n var postTable = this.readPostTable();\n this.width = this.readWidthTable(horizontalHeadTable.numberOfHMetrics, headTable.unitsPerEm);\n var subTables = this.readCmapTable();\n this.initializeMetrics(nameTable, headTable, horizontalHeadTable, os2Table, postTable, subTables);\n };\n /**\n * Gets glyph's info by char code.\n */\n TtfReader.prototype.getGlyph = function (charCode) {\n var obj = null;\n var code = charCode.charCodeAt(0);\n if (!this.metrics.isSymbol && this.microsoft !== null) {\n if (this.microsoft.containsKey(code)) {\n obj = this.microsoft.getValue(code);\n if (code !== StringTokenizer.whiteSpace.charCodeAt(0)) {\n this.isFontPresent = true;\n }\n }\n else if (code !== StringTokenizer.whiteSpace.charCodeAt(0)) {\n this.isFontPresent = false;\n }\n }\n else if (this.metrics.isSymbol && this.macintosh !== null || this.isMacTTF) {\n // NOTE: this code fixes char codes that extends 0x100. However, it might corrupt something.\n if (this.maxMacIndex !== 0) {\n code %= this.maxMacIndex + 1;\n }\n else {\n code = ((code & 0xff00) === 0xf000 ? code & 0xff : code);\n }\n if (this.macintosh.containsKey(code)) {\n obj = this.macintosh.getValue(code);\n this.isFontPresent = true;\n }\n }\n // Fix for StackOverFlow exception in XPS to PDF converter\n if (charCode === StringTokenizer.whiteSpace && obj === null) {\n obj = new TtfGlyphInfo();\n }\n var glyph = (obj !== null) ? obj : this.getDefaultGlyph();\n return glyph;\n };\n /**\n * Gets hash table with chars indexed by glyph index.\n */\n TtfReader.prototype.getGlyphChars = function (chars) {\n if (chars === null || chars === undefined) {\n throw new Error('Argument Null Exception : chars');\n }\n var dictionary = new Dictionary();\n var charKeys = chars.keys();\n for (var i = 0; i < charKeys.length; i++) {\n var ch = charKeys[i];\n var glyph = this.getGlyph(ch);\n if (!glyph.empty) {\n dictionary.setValue(glyph.index, ch.charCodeAt(0));\n }\n }\n return dictionary;\n };\n /**\n * Gets all glyphs.\n */\n TtfReader.prototype.getAllGlyphs = function () {\n var allGlyphInfo = [];\n var info = new TtfGlyphInfo();\n var index = 0;\n for (var i = 0; i < this.width.length; i++) {\n var width = this.width[i];\n info.index = index;\n info.width = width;\n allGlyphInfo.push(info);\n index++;\n }\n return allGlyphInfo;\n };\n /**\n * Reads a font's program.\n * @private\n */\n TtfReader.prototype.readFontProgram = function (chars) {\n var glyphChars = this.getGlyphChars(chars);\n var locaTable = this.readLocaTable(this.bIsLocaShort);\n if (glyphChars.size() < chars.size()) {\n this.missedGlyphs = chars.size() - glyphChars.size();\n }\n this.updateGlyphChars(glyphChars, locaTable);\n /* tslint:disable */\n var result1 = this.generateGlyphTable(glyphChars, locaTable, null, null);\n /* tslint:enable */\n var glyphTableSize = result1.glyphTableSize;\n var newLocaTable = result1.newLocaTable;\n var newGlyphTable = result1.newGlyphTable;\n var result2 = this.updateLocaTable(newLocaTable, this.bIsLocaShort, null);\n var newLocaSize = result2.newLocaSize;\n var newLocaUpdated = result2.newLocaUpdated;\n var fontProgram = this.getFontProgram(newLocaUpdated, newGlyphTable, glyphTableSize, newLocaSize);\n return fontProgram;\n };\n /**\n * Reconverts string to be in proper format saved into PDF file.\n */\n TtfReader.prototype.convertString = function (text) {\n if (text === null) {\n throw new Error('Argument Null Exception : text');\n }\n var glyph = '';\n var i = 0;\n for (var k = 0; k < text.length; k++) {\n var ch = text[k];\n var glyphInfo = this.getGlyph(ch);\n if (!glyphInfo.empty) {\n glyph += String.fromCharCode(glyphInfo.index);\n i++;\n }\n }\n return glyph;\n };\n /**\n * Gets char width.\n */\n TtfReader.prototype.getCharWidth = function (code) {\n var glyphInfo = this.getGlyph(code);\n glyphInfo = (!glyphInfo.empty) ? glyphInfo : this.getDefaultGlyph();\n var codeWidth = (!glyphInfo.empty) ? glyphInfo.width : 0;\n return codeWidth;\n };\n TtfReader.prototype.readString = function (length, isUnicode) {\n if (isUnicode === undefined) {\n return this.readString(length, false);\n }\n else {\n //let buffer : number[] = this.readBytes(length);\n var result = '';\n if (isUnicode) {\n for (var i = 0; i < length; i++) {\n if (i % 2 !== 0) {\n result += String.fromCharCode(this.fontData[this.offset]);\n }\n this.offset += 1;\n }\n }\n else {\n for (var i = 0; i < length; i++) {\n result += String.fromCharCode(this.fontData[this.offset]);\n this.offset += 1;\n }\n }\n return result;\n }\n };\n TtfReader.prototype.readFixed = function (offset) {\n var integer = this.readInt16(offset);\n var sFraction = this.readInt16(offset + 2);\n var fraction = sFraction / 16384;\n return integer + fraction;\n };\n TtfReader.prototype.readInt32 = function (offset) {\n var i1 = this.fontData[offset + 3];\n var i2 = this.fontData[offset + 2];\n var i3 = this.fontData[offset + 1];\n var i4 = this.fontData[offset];\n this.offset += 4;\n return i1 + (i2 << 8) + (i3 << 16) + (i4 << 24);\n };\n TtfReader.prototype.readUInt32 = function (offset) {\n var i1 = this.fontData[offset + 3];\n var i2 = this.fontData[offset + 2];\n var i3 = this.fontData[offset + 1];\n var i4 = this.fontData[offset];\n this.offset += 4;\n return (i1 | i2 << 8 | i3 << 16 | i4 << 24);\n };\n // private readInt16(offset : number) : number {\n // let result : number = (this.fontData[offset] << 8) + this.fontData[offset + 1];\n // this.offset += 2;\n // return result;\n // }\n TtfReader.prototype.readInt16 = function (offset) {\n var result = (this.fontData[offset] << 8) + this.fontData[offset + 1];\n result = result & (1 << 15) ? result - 0x10000 : result;\n this.offset += 2;\n return result;\n };\n TtfReader.prototype.readInt64 = function (offset) {\n var low = this.readInt32(offset + 4);\n var n = this.readInt32(offset) * 4294967296.0 + low;\n if (low < 0) {\n n += 4294967296;\n }\n return n;\n };\n TtfReader.prototype.readUInt16 = function (offset) {\n var result = (this.fontData[offset] << 8) | this.fontData[offset + 1];\n this.offset += 2;\n return result;\n };\n /**\n * Reads ushort array.\n */\n TtfReader.prototype.readUshortArray = function (length) {\n var buffer = [];\n for (var i = 0; i < length; i++) {\n buffer[i] = this.readUInt16(this.offset);\n }\n return buffer;\n };\n TtfReader.prototype.readBytes = function (length) {\n var result = [];\n for (var i = 0; i < length; i++) {\n result.push(this.fontData[this.offset]);\n this.offset += 1;\n }\n return result;\n };\n TtfReader.prototype.readByte = function (offset) {\n var result = this.fontData[offset];\n this.offset += 1;\n return result;\n };\n /**\n * Reads bytes to array in BigEndian order.\n * @private\n */\n TtfReader.prototype.read = function (buffer, index, count) {\n if (buffer === null) {\n throw new Error('Argument Null Exception : buffer');\n }\n var written = 0;\n var read = 0;\n do {\n for (var i = 0; (i < count - written) && (this.offset + i < this.fontData.length); i++) {\n buffer[index + i] = this.fontData[this.offset + i];\n }\n read = count - written;\n this.offset += read;\n written += read;\n } while (written < count);\n return { buffer: buffer, written: written };\n };\n return TtfReader;\n}());\nexport { TtfReader };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfFont } from './pdf-font';\nimport { PdfSubSuperScript } from './enum';\nimport { PdfArray } from './../../primitives/pdf-array';\n/**\n * `Metrics` of the font.\n * @private\n */\nvar PdfFontMetrics = /** @class */ (function () {\n function PdfFontMetrics() {\n /**\n * `Line gap`.\n * @private\n */\n this.lineGap = 0;\n }\n // Public methods\n /**\n * Returns `ascent` taking into consideration font`s size.\n * @private\n */\n PdfFontMetrics.prototype.getAscent = function (format) {\n var returnValue = this.ascent * PdfFont.charSizeMultiplier * this.getSize(format);\n return returnValue;\n };\n /**\n * Returns `descent` taking into consideration font`s size.\n * @private\n */\n PdfFontMetrics.prototype.getDescent = function (format) {\n var returnValue = this.descent * PdfFont.charSizeMultiplier * this.getSize(format);\n return returnValue;\n };\n /**\n * Returns `Line gap` taking into consideration font`s size.\n * @private\n */\n PdfFontMetrics.prototype.getLineGap = function (format) {\n var returnValue = this.lineGap * PdfFont.charSizeMultiplier * this.getSize(format);\n return returnValue;\n };\n /**\n * Returns `height` taking into consideration font`s size.\n * @private\n */\n PdfFontMetrics.prototype.getHeight = function (format) {\n var height;\n var clearTypeFonts = ['cambria', 'candara', 'constantia', 'corbel', 'cariadings'];\n var clearTypeFontCollection = [];\n for (var index = 0; index < clearTypeFonts.length; index++) {\n var font = clearTypeFonts[index];\n clearTypeFontCollection.push(font);\n }\n if (this.getDescent(format) < 0) {\n // if ((clearTypeFontCollection.indexOf(this.name.toLowerCase()) !== -1) && !this.isUnicodeFont) {\n // height = (this.GetAscent(format) - this.GetDescent(format) - this.GetLineGap(format));\n // } else {\n height = (this.getAscent(format) - this.getDescent(format) + this.getLineGap(format));\n // }\n }\n else {\n height = (this.getAscent(format) + this.getDescent(format) + this.getLineGap(format));\n }\n return height;\n };\n /**\n * Calculates `size` of the font depending on the subscript/superscript value.\n * @private\n */\n PdfFontMetrics.prototype.getSize = function (format) {\n var size = this.size;\n if (format != null) {\n switch (format.subSuperScript) {\n case PdfSubSuperScript.SubScript:\n size /= this.subScriptSizeFactor;\n break;\n case PdfSubSuperScript.SuperScript:\n size /= this.superscriptSizeFactor;\n break;\n }\n }\n return size;\n };\n /**\n * `Clones` the metrics.\n * @private\n */\n PdfFontMetrics.prototype.clone = function () {\n var metrics = this;\n metrics.widthTable = WidthTable.clone();\n return metrics;\n };\n Object.defineProperty(PdfFontMetrics.prototype, \"widthTable\", {\n // Properies\n /**\n * Gets or sets the `width table`.\n * @private\n */\n get: function () {\n return this.internalWidthTable;\n },\n set: function (value) {\n this.internalWidthTable = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfFontMetrics;\n}());\nexport { PdfFontMetrics };\nvar WidthTable = /** @class */ (function () {\n function WidthTable() {\n }\n /**\n * Static `clones` this instance of the WidthTable class.\n * @private\n */\n WidthTable.clone = function () {\n return null;\n };\n return WidthTable;\n}());\nexport { WidthTable };\nvar StandardWidthTable = /** @class */ (function (_super) {\n __extends(StandardWidthTable, _super);\n // Constructors\n /**\n * Initializes a new instance of the `StandardWidthTable` class.\n * @private\n */\n function StandardWidthTable(widths) {\n var _this = _super.call(this) || this;\n if (widths == null) {\n throw new Error('ArgumentNullException:widths');\n }\n _this.widths = widths;\n return _this;\n }\n //Properties\n /**\n * Gets the `32 bit number` at the specified index.\n * @private\n */\n StandardWidthTable.prototype.items = function (index) {\n if (index < 0 || index >= this.widths.length) {\n throw new Error('ArgumentOutOfRangeException:index, The character is not supported by the font.');\n }\n var result = this.widths[index];\n return result;\n };\n Object.defineProperty(StandardWidthTable.prototype, \"length\", {\n /**\n * Gets the `length` of the internal array.\n * @private\n */\n get: function () {\n return this.widths.length;\n },\n enumerable: true,\n configurable: true\n });\n //Overrides\n /**\n * `Clones` this instance of the WidthTable class.\n * @private\n */\n StandardWidthTable.prototype.clone = function () {\n var swt = this;\n swt.widths = this.widths;\n return swt;\n };\n /**\n * Converts width table to a `PDF array`.\n * @private\n */\n StandardWidthTable.prototype.toArray = function () {\n var arr = new PdfArray(this.widths);\n return arr;\n };\n return StandardWidthTable;\n}(WidthTable));\nexport { StandardWidthTable };\n","/**\n * TrueTypeFont.ts class for EJ2-PDF\n */\nimport { ByteArray } from './../../graphics/images/index';\nimport { TtfReader } from './ttf-reader';\nimport { PdfDictionary, SaveDescendantFontEventHandler, SaveFontDictionaryEventHandler } from './../../primitives/pdf-dictionary';\nimport { SaveFontProgramEventHandler, SaveCmapEventHandler } from './../../primitives/pdf-stream';\nimport { PdfStream } from './../../primitives/pdf-stream';\nimport { PdfArray } from './../../primitives/pdf-array';\nimport { PdfName } from './../../primitives/pdf-name';\nimport { PdfNumber } from './../../primitives/pdf-number';\nimport { PdfString } from './../../primitives/pdf-string';\nimport { PdfReferenceHolder } from './../../primitives/pdf-reference';\nimport { PdfFontMetrics } from './pdf-font-metrics';\nimport { StandardWidthTable } from './pdf-font-metrics';\nimport { DictionaryProperties } from './../../input-output/pdf-dictionary-properties';\nimport { Dictionary } from './../../collections/dictionary';\nimport { FontDescriptorFlags } from './enum';\nimport { RectangleF } from './../../drawing/pdf-drawing';\nimport { Operators } from './../../input-output/pdf-operators';\nvar UnicodeTrueTypeFont = /** @class */ (function () {\n /* tslint:enable */\n //Constructors\n /**\n * Initializes a new instance of the `PdfTrueTypeFont` class.\n * @private\n */\n function UnicodeTrueTypeFont(base64String, size) {\n // Fields\n this.nameString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n /**\n * Specifies the Internal variable to store fields of `PdfDictionaryProperties`.\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n /**\n * Indicates whether the font program is compressed or not.\n * @private\n */\n this.isCompress = false;\n /**\n * Cmap table's start prefix.\n */\n /* tslint:disable */\n this.cmapPrefix = '/CIDInit /ProcSet findresource begin\\n12 dict begin\\nbegincmap' + Operators.newLine + '/CIDSystemInfo << /Registry (Adobe)/Ordering (UCS)/Supplement 0>> def\\n/CMapName ' + '/Adobe-Identity-UCS def\\n/CMapType 2 def\\n1 begincodespacerange' + Operators.newLine;\n /* tslint:enable */\n /**\n * Cmap table's start suffix.\n */\n this.cmapEndCodespaceRange = 'endcodespacerange' + Operators.newLine;\n /**\n * Cmap's begin range marker.\n */\n this.cmapBeginRange = 'beginbfrange' + Operators.newLine;\n /**\n * Cmap's end range marker.\n */\n this.cmapEndRange = 'endbfrange' + Operators.newLine;\n /**\n * Cmap table's end\n */\n /* tslint:disable */\n this.cmapSuffix = 'endbfrange\\nendcmap\\nCMapName currentdict ' + '/CMap defineresource pop\\nend end' + Operators.newLine;\n if (base64String === null || base64String === undefined) {\n throw new Error('ArgumentNullException:base64String');\n }\n this.fontSize = size;\n this.fontString = base64String;\n this.Initialize();\n }\n //Implementation\n /**\n * Returns width of the char symbol.\n */\n UnicodeTrueTypeFont.prototype.getCharWidth = function (charCode) {\n var codeWidth = this.ttfReader.getCharWidth(charCode);\n return codeWidth;\n };\n /**\n * Initializes a new instance of the `PdfTrueTypeFont` class.\n * @private\n */\n UnicodeTrueTypeFont.prototype.Initialize = function () {\n var byteArray = new ByteArray(this.fontString.length);\n byteArray.writeFromBase64String(this.fontString);\n this.fontData = byteArray.internalBuffer;\n this.ttfReader = new TtfReader(this.fontData);\n this.ttfMetrics = this.ttfReader.metrics;\n };\n UnicodeTrueTypeFont.prototype.createInternals = function () {\n this.fontDictionary = new PdfDictionary();\n this.fontProgram = new PdfStream();\n this.cmap = new PdfStream();\n this.descendantFont = new PdfDictionary();\n this.metrics = new PdfFontMetrics();\n this.ttfReader.createInternals();\n this.ttfMetrics = this.ttfReader.metrics;\n this.initializeMetrics();\n // Create all the dictionaries of the font.\n this.subsetName = this.getFontName();\n this.createDescendantFont();\n this.createCmap();\n this.createFontDictionary();\n this.createFontProgram();\n };\n UnicodeTrueTypeFont.prototype.getInternals = function () {\n return this.fontDictionary;\n };\n /**\n * Initializes metrics.\n */\n UnicodeTrueTypeFont.prototype.initializeMetrics = function () {\n var ttfMetrics = this.ttfReader.metrics;\n this.metrics.ascent = ttfMetrics.macAscent;\n this.metrics.descent = ttfMetrics.macDescent;\n this.metrics.height = ttfMetrics.macAscent - ttfMetrics.macDescent + ttfMetrics.lineGap;\n this.metrics.name = ttfMetrics.fontFamily;\n this.metrics.postScriptName = ttfMetrics.postScriptName;\n this.metrics.size = this.fontSize;\n this.metrics.widthTable = new StandardWidthTable(ttfMetrics.widthTable);\n this.metrics.lineGap = ttfMetrics.lineGap;\n this.metrics.subScriptSizeFactor = ttfMetrics.subScriptSizeFactor;\n this.metrics.superscriptSizeFactor = ttfMetrics.superscriptSizeFactor;\n this.metrics.isBold = ttfMetrics.isBold;\n };\n /**\n * Gets random string.\n */\n UnicodeTrueTypeFont.prototype.getFontName = function () {\n var builder = '';\n var name;\n // if (this.isEmbed === false) {\n for (var i = 0; i < 6; i++) {\n var index = Math.floor(Math.random() * (25 - 0 + 1)) + 0;\n builder += this.nameString[index];\n }\n builder += '+';\n // }\n builder += this.ttfReader.metrics.postScriptName;\n name = builder.toString();\n // if (name === '') {\n // name = this.ttfReader.metrics.fontFamily;\n // }\n name = this.formatName(name);\n return name;\n };\n /**\n * Generates name of the font.\n */\n UnicodeTrueTypeFont.prototype.formatName = function (fontName) {\n // if (fontName === null) {\n // throw new Error('ArgumentNullException : fontName');\n // }\n // if (fontName === '') {\n // throw new Error('ArgumentOutOfRangeException : fontName, Parameter can not be empty');\n // }\n var ret = fontName.replace('(', '#28');\n ret = ret.replace(')', '#29');\n ret = ret.replace('[', '#5B');\n ret = ret.replace(']', '#5D');\n ret = ret.replace('<', '#3C');\n ret = ret.replace('>', '#3E');\n ret = ret.replace('{', '#7B');\n ret = ret.replace('}', '#7D');\n ret = ret.replace('/', '#2F');\n ret = ret.replace('%', '#25');\n return ret.replace(' ', '#20');\n };\n /**\n * Creates descendant font.\n */\n UnicodeTrueTypeFont.prototype.createDescendantFont = function () {\n // Set property used to clone Font every time\n this.descendantFont.isFont = true;\n this.descendantFont.descendantFontBeginSave = new SaveDescendantFontEventHandler(this);\n this.descendantFont.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.font));\n this.descendantFont.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.cIDFontType2));\n this.descendantFont.items.setValue(this.dictionaryProperties.baseFont, new PdfName(this.subsetName));\n this.descendantFont.items.setValue(this.dictionaryProperties.cIDToGIDMap, new PdfName(this.dictionaryProperties.identity));\n this.descendantFont.items.setValue(this.dictionaryProperties.dw, new PdfNumber(1000));\n this.fontDescriptor = this.createFontDescriptor();\n this.descendantFont.items.setValue(this.dictionaryProperties.fontDescriptor, new PdfReferenceHolder(this.fontDescriptor));\n var systemInfo = this.createSystemInfo();\n this.descendantFont.items.setValue(this.dictionaryProperties.cIDSystemInfo, systemInfo);\n };\n /**\n * Creates font descriptor.\n */\n UnicodeTrueTypeFont.prototype.createFontDescriptor = function () {\n var descriptor = new PdfDictionary();\n var metrics = this.ttfReader.metrics;\n // Set property used to clone Font every time\n descriptor.isFont = true;\n descriptor.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.fontDescriptor));\n descriptor.items.setValue(this.dictionaryProperties.fontName, new PdfName(this.subsetName));\n descriptor.items.setValue(this.dictionaryProperties.flags, new PdfNumber(this.getDescriptorFlags()));\n descriptor.items.setValue(this.dictionaryProperties.fontBBox, PdfArray.fromRectangle(this.getBoundBox()));\n descriptor.items.setValue(this.dictionaryProperties.missingWidth, new PdfNumber(metrics.widthTable[32]));\n descriptor.items.setValue(this.dictionaryProperties.stemV, new PdfNumber(metrics.stemV));\n descriptor.items.setValue(this.dictionaryProperties.italicAngle, new PdfNumber(metrics.italicAngle));\n descriptor.items.setValue(this.dictionaryProperties.capHeight, new PdfNumber(metrics.capHeight));\n descriptor.items.setValue(this.dictionaryProperties.ascent, new PdfNumber(metrics.winAscent));\n descriptor.items.setValue(this.dictionaryProperties.descent, new PdfNumber(metrics.winDescent));\n descriptor.items.setValue(this.dictionaryProperties.leading, new PdfNumber(metrics.leading));\n descriptor.items.setValue(this.dictionaryProperties.avgWidth, new PdfNumber(metrics.widthTable[32]));\n descriptor.items.setValue(this.dictionaryProperties.fontFile2, new PdfReferenceHolder(this.fontProgram));\n descriptor.items.setValue(this.dictionaryProperties.maxWidth, new PdfNumber(metrics.widthTable[32]));\n descriptor.items.setValue(this.dictionaryProperties.xHeight, new PdfNumber(0));\n descriptor.items.setValue(this.dictionaryProperties.stemH, new PdfNumber(0));\n return descriptor;\n };\n /**\n * Generates cmap.\n * @private\n */\n UnicodeTrueTypeFont.prototype.createCmap = function () {\n this.cmap.cmapBeginSave = new SaveCmapEventHandler(this);\n };\n /**\n * Generates font dictionary.\n */\n UnicodeTrueTypeFont.prototype.createFontDictionary = function () {\n // Set property used to clone Font every time\n this.fontDictionary.isFont = true;\n this.fontDictionary.fontDictionaryBeginSave = new SaveFontDictionaryEventHandler(this);\n this.fontDictionary.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.font));\n this.fontDictionary.items.setValue(this.dictionaryProperties.baseFont, new PdfName(this.subsetName));\n this.fontDictionary.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.type0));\n this.fontDictionary.items.setValue(this.dictionaryProperties.encoding, new PdfName(this.dictionaryProperties.identityH));\n var descFonts = new PdfArray();\n var reference = new PdfReferenceHolder(this.descendantFont);\n // Set property used to clone Font every time\n descFonts.isFont = true;\n descFonts.add(reference);\n this.fontDictionary.items.setValue(this.dictionaryProperties.descendantFonts, descFonts);\n };\n /**\n * Creates font program.\n */\n UnicodeTrueTypeFont.prototype.createFontProgram = function () {\n this.fontProgram.fontProgramBeginSave = new SaveFontProgramEventHandler(this);\n };\n /**\n * Creates system info dictionary for CID font.\n * @private\n */\n UnicodeTrueTypeFont.prototype.createSystemInfo = function () {\n var systemInfo = new PdfDictionary();\n systemInfo.items.setValue(this.dictionaryProperties.registry, new PdfString('Adobe'));\n systemInfo.items.setValue(this.dictionaryProperties.ordering, new PdfString(this.dictionaryProperties.identity));\n systemInfo.items.setValue(this.dictionaryProperties.supplement, new PdfNumber(0));\n return systemInfo;\n };\n /**\n * Runs before font Dictionary will be saved.\n */\n UnicodeTrueTypeFont.prototype.descendantFontBeginSave = function () {\n if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0) {\n var width = this.getDescendantWidth();\n if (width !== null) {\n this.descendantFont.items.setValue(this.dictionaryProperties.w, width);\n }\n }\n };\n /**\n * Runs before font Dictionary will be saved.\n */\n UnicodeTrueTypeFont.prototype.cmapBeginSave = function () {\n this.generateCmap();\n };\n /**\n * Runs before font Dictionary will be saved.\n */\n /* tslint:disable */\n UnicodeTrueTypeFont.prototype.fontDictionaryBeginSave = function () {\n if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0 && !this.fontDictionary.containsKey(this.dictionaryProperties.toUnicode)) {\n this.fontDictionary.items.setValue(this.dictionaryProperties.toUnicode, new PdfReferenceHolder(this.cmap));\n }\n };\n /* tslint:enable */\n /**\n * Runs before font program stream save.\n */\n UnicodeTrueTypeFont.prototype.fontProgramBeginSave = function () {\n this.isCompress = true;\n this.generateFontProgram();\n };\n /**\n * Gets width description pad array for c i d font.\n */\n UnicodeTrueTypeFont.prototype.getDescendantWidth = function () {\n var array = new PdfArray();\n if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0) {\n var glyphInfo = [];\n // if (!this.isEmbedFont) {\n var keys = this.usedChars.keys();\n for (var i = 0; i < keys.length; i++) {\n var chLen = keys[i];\n var glyph = this.ttfReader.getGlyph(chLen);\n if (glyph.empty) {\n continue;\n }\n glyphInfo.push(glyph);\n }\n // } else {\n // glyphInfo = this.ttfReader.getAllGlyphs();\n // }\n glyphInfo.sort(function (a, b) { return a.index - b.index; });\n var firstGlyphIndex = 0;\n var lastGlyphIndex = 0;\n var firstGlyphIndexWasSet = false;\n var widthDetails = new PdfArray();\n // if (!this.isEmbedFont) {\n for (var i = 0; i < glyphInfo.length; i++) {\n var glyph = glyphInfo[i];\n if (!firstGlyphIndexWasSet) {\n firstGlyphIndexWasSet = true;\n firstGlyphIndex = glyph.index;\n lastGlyphIndex = glyph.index - 1;\n }\n if ((lastGlyphIndex + 1 !== glyph.index || (i + 1 === glyphInfo.length)) && glyphInfo.length > 1) {\n // Add glyph index / width.\n array.add(new PdfNumber(firstGlyphIndex));\n if (i !== 0) {\n array.add(widthDetails);\n }\n firstGlyphIndex = glyph.index;\n widthDetails = new PdfArray();\n }\n widthDetails.add(new PdfNumber(glyph.width));\n if (i + 1 === glyphInfo.length) {\n array.add(new PdfNumber(firstGlyphIndex));\n array.add(widthDetails);\n }\n lastGlyphIndex = glyph.index;\n }\n // } else {\n // for (let i : number = 0; i < glyphInfo.length; i++) {\n // let glyph : TtfGlyphInfo = glyphInfo[i];\n // if (!firstGlyphIndexWasSet) {\n // firstGlyphIndexWasSet = true;\n // lastGlyphIndex = glyph.index - 1;\n // }\n // firstGlyphIndex = glyph.index;\n // if ((lastGlyphIndex + 1 === glyph.index || (i + 1 === glyphInfo.length)) && glyphInfo.length > 1) {\n // // Add glyph index / width.\n // widthDetails.add(new PdfNumber(glyph.width));\n // array.add(new PdfNumber(firstGlyphIndex));\n // array.add(widthDetails);\n // widthDetails = new PdfArray();\n // }\n // lastGlyphIndex = glyph.index;\n // }\n // }\n }\n return array;\n };\n /**\n * Creates cmap.\n */\n UnicodeTrueTypeFont.prototype.generateCmap = function () {\n if (this.usedChars !== null && this.usedChars !== undefined && this.usedChars.size() > 0) {\n var glyphChars = this.ttfReader.getGlyphChars(this.usedChars);\n if (glyphChars.size() > 0) {\n var keys = glyphChars.keys().sort();\n // add first and last glyph indexes\n var first = keys[0];\n var last = keys[keys.length - 1];\n var middlePart = this.toHexString(first, false) + this.toHexString(last, false) + Operators.newLine;\n var builder = '';\n builder += this.cmapPrefix;\n builder += middlePart;\n builder += this.cmapEndCodespaceRange;\n var nextRange = 0;\n for (var i = 0; i < keys.length; i++) {\n if (nextRange === 0) {\n if (i !== 0) {\n builder += this.cmapEndRange;\n }\n nextRange = Math.min(100, keys.length - i);\n builder += nextRange;\n builder += Operators.whiteSpace;\n builder += this.cmapBeginRange;\n }\n nextRange -= 1;\n var key = keys[i];\n /* tslint:disable */\n builder += this.toHexString(key, true) + this.toHexString(key, true) + this.toHexString(glyphChars.getValue(key), true) + '\\n';\n /* tslint:enable */\n }\n builder += this.cmapSuffix;\n this.cmap.clearStream();\n this.cmap.isFont = true;\n this.cmap.write(builder);\n }\n }\n };\n /**\n * Generates font program.\n */\n UnicodeTrueTypeFont.prototype.generateFontProgram = function () {\n var fontProgram = null;\n this.usedChars = (this.usedChars === null || this.usedChars === undefined) ? new Dictionary() : this.usedChars;\n this.ttfReader.setOffset(0);\n fontProgram = this.ttfReader.readFontProgram(this.usedChars);\n this.fontProgram.clearStream();\n this.fontProgram.isFont = true;\n this.fontProgram.writeBytes(fontProgram);\n };\n /**\n * Calculates flags for the font descriptor.\n * @private\n */\n UnicodeTrueTypeFont.prototype.getDescriptorFlags = function () {\n var flags = 0;\n var metrics = this.ttfReader.metrics;\n if (metrics.isFixedPitch) {\n flags |= FontDescriptorFlags.FixedPitch;\n }\n if (metrics.isSymbol) {\n flags |= FontDescriptorFlags.Symbolic;\n }\n else {\n flags |= FontDescriptorFlags.Nonsymbolic;\n }\n if (metrics.isItalic) {\n flags |= FontDescriptorFlags.Italic;\n }\n if (metrics.isBold) {\n flags |= FontDescriptorFlags.ForceBold;\n }\n return flags;\n };\n /**\n * Calculates BoundBox of the descriptor.\n * @private\n */\n UnicodeTrueTypeFont.prototype.getBoundBox = function () {\n var rect = this.ttfReader.metrics.fontBox;\n var width = Math.abs(rect.right - rect.left);\n var height = Math.abs(rect.top - rect.bottom);\n var rectangle = new RectangleF(rect.left, rect.bottom, width, height);\n return rectangle;\n };\n /**\n * Converts integer of decimal system to hex integer.\n */\n UnicodeTrueTypeFont.prototype.toHexString = function (n, isCaseChange) {\n var s = n.toString(16);\n if (isCaseChange) {\n s = s.toUpperCase();\n }\n return '<0000'.substring(0, 5 - s.length) + s + '>';\n };\n /**\n * Stores used symbols.\n */\n UnicodeTrueTypeFont.prototype.setSymbols = function (text) {\n if (text === null) {\n throw new Error('Argument Null Exception : text');\n }\n if (this.usedChars === null || this.usedChars === undefined) {\n this.usedChars = new Dictionary();\n }\n for (var i = 0; i < text.length; i++) {\n var ch = text[i];\n this.usedChars.setValue(ch, String.fromCharCode(0));\n }\n this.getDescendantWidth();\n };\n return UnicodeTrueTypeFont;\n}());\nexport { UnicodeTrueTypeFont };\n","/**\n * PdfGraphics.ts class for EJ2-PDF\n */\nimport { PdfColorSpace, TextRenderingMode, PdfFillMode, PdfTextAlignment } from './enum';\nimport { PdfVerticalAlignment, PdfBlendMode } from './enum';\nimport { PdfSubSuperScript } from './fonts/enum';\nimport { PdfStreamWriter } from './../input-output/pdf-stream-writer';\nimport { PdfPen } from './pdf-pen';\nimport { PdfBrush } from './brushes/pdf-brush';\nimport { PdfSolidBrush } from './brushes/pdf-solid-brush';\nimport { PdfFont } from './fonts/pdf-font';\nimport { PdfTransformationMatrix } from './pdf-transformation-matrix';\nimport { PointF, SizeF, RectangleF } from './../drawing/pdf-drawing';\nimport { ProcedureSets } from './constants';\nimport { PdfString } from './../primitives/pdf-string';\nimport { PdfStringFormat } from './fonts/pdf-string-format';\nimport { TemporaryDictionary } from './../collections/object-object-pair/dictionary';\nimport { PdfTransparency } from './pdf-transparency';\nimport { PdfStringLayouter, LineType } from './fonts/string-layouter';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { StringTokenizer } from './fonts/string-tokenizer';\nimport { PdfAutomaticFieldInfoCollection } from './../document/automatic-fields/automatic-field-info-collection';\nimport { PdfAutomaticFieldInfo } from './../document/automatic-fields/automatic-field-info';\nimport { Operators } from './../input-output/pdf-operators';\nimport { UnicodeTrueTypeFont } from './fonts/unicode-true-type-font';\nimport { InternalEnum } from './../primitives/pdf-string';\n/**\n * `PdfGraphics` class represents a graphics context of the objects.\n * It's used for performing all the graphics operations.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * // set the font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * //\n * //graphics of the page\n * let page1Graphics : PdfGraphics = page1.graphics;\n * // draw the text on the page1 graphics\n * page1Graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * //\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfGraphics = /** @class */ (function () {\n function PdfGraphics(arg1, arg2, arg3) {\n /**\n * Represents the `Current color space`.\n * @private\n */\n this.currentColorSpace = PdfColorSpace.Rgb;\n /**\n * Stores `previous rendering mode`.\n * @private\n */\n this.previousTextRenderingMode = TextRenderingMode.Fill;\n /**\n * Previous `character spacing` value or 0.\n * @private\n */\n this.previousCharacterSpacing = 0.0;\n /**\n * Previous `word spacing` value or 0.\n * @private\n */\n this.previousWordSpacing = 0.0;\n /**\n * The `previously used text scaling` value.\n * @private\n */\n this.previousTextScaling = 100.0;\n /**\n * Instance of `ProcedureSets` class.\n * @private\n */\n this.procedureSets = new ProcedureSets();\n /**\n * To check wihether it is a `direct text rendering`.\n * @default true\n * @private\n */\n this.isNormalRender = true;\n /**\n * check whether to `use font size` to calculate the shift.\n * @default false\n * @private\n */\n this.isUseFontSize = false;\n /**\n * check whether the font is in `italic type`.\n * @default false\n * @private\n */\n this.isItalic = false;\n /**\n * Check whether it is an `emf Text Matrix`.\n * @default false\n * @private\n */\n this.isEmfTextScaled = false;\n /**\n * Check whether it is an `emf` call.\n * @default false\n * @private\n */\n this.isEmf = false;\n /**\n * Check whether it is an `emf plus` call.\n * @default false\n * @private\n */\n this.isEmfPlus = false;\n /**\n * Check whether it is in `base line format`.\n * @default true\n * @private\n */\n this.isBaselineFormat = true;\n /**\n * Emf Text `Scaling Factor`.\n * @private\n */\n this.emfScalingFactor = new SizeF(0, 0);\n /**\n * To check whether the `last color space` of document and garphics is saved.\n * @private\n */\n this.colorSpaceChanged = false;\n /**\n * Stores an instance of `DictionaryProperties`.\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n /**\n * Checks whether the x co-ordinate is need to set as client size or not.\n * @hidden\n * @private\n */\n this.isOverloadWithPosition = false;\n /**\n * Checks whether the x co-ordinate is need to set as client size or not.\n * @hidden\n * @private\n */\n this.isPointOverload = false;\n /**\n * Current colorspaces.\n * @hidden\n * @private\n */\n this.currentColorSpaces = ['RGB', 'CMYK', 'GrayScale', 'Indexed'];\n /**\n * Checks the current image `is optimized` or not.\n * @default false.\n * @private\n */\n this.isImageOptimized = false;\n /**\n * Stores the `graphics states`.\n * @private\n */\n this.graphicsState = [];\n /**\n * Indicates whether the object `had trasparency`.\n * @default false\n * @private\n */\n this.istransparencySet = false;\n /**\n * Stores the instance of `PdfAutomaticFieldInfoCollection` class .\n * @default null\n * @private\n */\n this.internalAutomaticFields = null;\n /**\n * Stores the index of the start line that should draw with in the next page.\n * @private\n */\n this.startCutIndex = -1;\n if (arg3 instanceof PdfStreamWriter) {\n this.pdfStreamWriter = arg3;\n this.getResources = arg2;\n this.canvasSize = arg1;\n this.initialize();\n }\n else {\n this.constructor(arg1, arg2, new PdfStreamWriter(arg3));\n }\n }\n Object.defineProperty(PdfGraphics.prototype, \"stringLayoutResult\", {\n // Properties\n /**\n * Returns the `result` after drawing string.\n * @private\n */\n get: function () {\n return this.pdfStringLayoutResult;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"size\", {\n /**\n * Gets the `size` of the canvas.\n * @private\n */\n get: function () {\n return this.canvasSize;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"mediaBoxUpperRightBound\", {\n /**\n * Gets and Sets the value of `MediaBox upper right bound`.\n * @private\n */\n get: function () {\n if (typeof this.internalMediaBoxUpperRightBound === 'undefined') {\n this.internalMediaBoxUpperRightBound = 0;\n }\n return this.internalMediaBoxUpperRightBound;\n },\n set: function (value) {\n this.internalMediaBoxUpperRightBound = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"clientSize\", {\n /**\n * Gets the `size` of the canvas reduced by margins and page templates.\n * @private\n */\n get: function () {\n return new SizeF(this.clipBounds.width, this.clipBounds.height);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"colorSpace\", {\n /**\n * Gets or sets the current `color space` of the document\n * @private\n */\n get: function () {\n return this.currentColorSpace;\n },\n set: function (value) {\n this.currentColorSpace = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"streamWriter\", {\n /**\n * Gets the `stream writer`.\n * @private\n */\n get: function () {\n return this.pdfStreamWriter;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"matrix\", {\n /**\n * Gets the `transformation matrix` reflecting current transformation.\n * @private\n */\n get: function () {\n if (this.transformationMatrix == null) {\n this.transformationMatrix = new PdfTransformationMatrix();\n }\n return this.transformationMatrix;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"layer\", {\n /**\n * Gets the `layer` for the graphics, if exists.\n * @private\n */\n get: function () {\n return this.pageLayer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"page\", {\n /**\n * Gets the `page` for this graphics, if exists.\n * @private\n */\n get: function () {\n return this.pageLayer.page;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphics.prototype, \"automaticFields\", {\n get: function () {\n if (this.internalAutomaticFields == null || typeof this.internalAutomaticFields === 'undefined') {\n this.internalAutomaticFields = new PdfAutomaticFieldInfoCollection();\n }\n return this.internalAutomaticFields;\n },\n enumerable: true,\n configurable: true\n });\n //Implementation\n /**\n * `Initializes` this instance.\n * @private\n */\n PdfGraphics.prototype.initialize = function () {\n this.bStateSaved = false;\n this.currentPen = null;\n this.currentBrush = null;\n this.currentFont = null;\n this.currentColorSpace = PdfColorSpace.Rgb;\n this.bCSInitialized = false;\n this.transformationMatrix = null;\n this.previousTextRenderingMode = (-1); //.Fill;\n this.previousCharacterSpacing = -1.0;\n this.previousWordSpacing = -1.0;\n this.previousTextScaling = -100.0;\n // this.m_trasparencies = null;\n this.currentStringFormat = null;\n this.clipBounds = new RectangleF(new PointF(0, 0), this.size);\n this.getResources.getResources().requireProcedureSet(this.procedureSets.pdf);\n };\n PdfGraphics.prototype.drawPdfTemplate = function (template, location, size) {\n if (typeof size === 'undefined') {\n if (template == null) {\n throw Error('ArgumentNullException-template');\n }\n this.drawPdfTemplate(template, location, template.size);\n }\n else {\n // let crossTable : PdfCrossTable = null;\n // if (this.pageLayer != null) {\n // crossTable = (this.page as PdfPage).section.parentDocument.crossTable;\n // }\n if (template == null) {\n throw Error('ArgumentNullException-template');\n }\n var scaleX = (template.width > 0) ? size.width / template.width : 1;\n var scaleY = (template.height > 0) ? size.height / template.height : 1;\n var bNeedScale = !(scaleX === 1 && scaleY === 1);\n // Save state.\n var state = this.save();\n // Take into consideration that rect location is bottom/left.\n var matrix = new PdfTransformationMatrix();\n if (this.pageLayer != null) {\n this.getTranslateTransform(location.x, location.y + size.height, matrix);\n }\n if (bNeedScale) {\n this.getScaleTransform(scaleX, scaleY, matrix);\n }\n this.pdfStreamWriter.modifyCtm(matrix);\n // Output template.\n var resources = this.getResources.getResources();\n var name_1 = resources.getName(template);\n this.pdfStreamWriter.executeObject(name_1);\n // Restore state.\n this.restore(state);\n //Transfer automatic fields from template.\n var g = template.graphics;\n if (g != null) {\n for (var index = 0; index < g.automaticFields.automaticFields.length; index++) {\n var fieldInfo = g.automaticFields.automaticFields[index];\n var newLocation = new PointF(fieldInfo.location.x + location.x, fieldInfo.location.y + location.y);\n var scalingX = template.size.width == 0 ? 0 : size.width / template.size.width;\n var scalingY = template.size.height == 0 ? 0 : size.height / template.size.height;\n this.automaticFields.add(new PdfAutomaticFieldInfo(fieldInfo.field, newLocation, scalingX, scalingY));\n this.page.dictionary.modify();\n }\n }\n this.getResources.getResources().requireProcedureSet(this.procedureSets.imageB);\n this.getResources.getResources().requireProcedureSet(this.procedureSets.imageC);\n this.getResources.getResources().requireProcedureSet(this.procedureSets.imageI);\n this.getResources.getResources().requireProcedureSet(this.procedureSets.text);\n }\n };\n /* tslint:disable */\n /**\n * @public\n */\n PdfGraphics.prototype.drawString = function (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {\n if (typeof arg1 === 'string' && arg2 instanceof PdfFont && (arg3 instanceof PdfPen || arg3 === null) && (arg4 instanceof PdfBrush || arg4 === null) && typeof arg5 === 'number' && typeof arg6 === 'number' && (arg7 instanceof PdfStringFormat || arg7 === null) && typeof arg8 === 'undefined') {\n this.isOverloadWithPosition = true;\n this.drawString(arg1, arg2, arg3, arg4, arg5, arg6, (this.clientSize.width - arg5), 0, arg7);\n }\n else {\n var temparg3 = arg3;\n var temparg4 = arg4;\n var temparg5 = arg5;\n var temparg6 = arg6;\n var temparg7 = arg7;\n var temparg8 = arg8;\n var temparg9 = arg9;\n var layouter = new PdfStringLayouter();\n var result = layouter.layout(arg1, arg2, temparg9, new SizeF(temparg7, 0), this.isOverloadWithPosition, this.clientSize);\n if (!result.empty) {\n var rect = this.checkCorrectLayoutRectangle(result.actualSize, temparg5, temparg6, temparg9);\n if (temparg7 <= 0) {\n temparg5 = rect.x;\n temparg7 = rect.width;\n }\n if (temparg8 <= 0) {\n temparg6 = rect.y;\n temparg8 = rect.height;\n }\n this.drawStringLayoutResult(result, arg2, temparg3, temparg4, new RectangleF(temparg5, temparg6, temparg7, temparg8), temparg9);\n this.isEmfTextScaled = false;\n this.emfScalingFactor = new SizeF(0, 0);\n }\n this.getResources.getResources().requireProcedureSet(this.procedureSets.text);\n this.isNormalRender = true;\n this.pdfStringLayoutResult = result;\n this.isUseFontSize = false;\n }\n }; /* tslint:enable */\n PdfGraphics.prototype.drawLine = function (arg1, arg2, arg3, arg4, arg5) {\n if (arg2 instanceof PointF) {\n var temparg2 = arg2;\n var temparg3 = arg3;\n this.drawLine(arg1, temparg2.x, temparg2.y, temparg3.x, temparg3.y);\n }\n else {\n var temparg2 = arg2;\n var temparg3 = arg3;\n var temparg4 = arg4;\n var temparg5 = arg5;\n this.stateControl(arg1, null, null);\n var sw = this.streamWriter;\n sw.beginPath(temparg2, temparg3);\n sw.appendLineSegment(temparg4, temparg5);\n sw.strokePath();\n this.getResources.getResources().requireProcedureSet(this.procedureSets.pdf);\n }\n };\n /* tslint:disable */\n PdfGraphics.prototype.drawRectangle = function (arg1, arg2, arg3, arg4, arg5, arg6) {\n if (arg1 instanceof PdfPen && typeof arg2 === 'number') {\n var temparg3 = arg3;\n this.drawRectangle(arg1, null, arg2, temparg3, arg4, arg5);\n }\n else if (arg1 instanceof PdfBrush && typeof arg2 === 'number') {\n var temparg3 = arg3;\n this.drawRectangle(null, arg1, arg2, temparg3, arg4, arg5);\n }\n else {\n var temparg3 = arg3;\n var temparg4 = arg4;\n var temparg5 = arg5;\n var temparg6 = arg6;\n if (arg2 instanceof PdfSolidBrush && arg2.color.isEmpty) {\n arg2 = null;\n }\n var temparg1 = arg1;\n var temparg2 = arg2;\n this.stateControl(temparg1, temparg2, null);\n this.streamWriter.appendRectangle(temparg3, temparg4, temparg5, temparg6);\n this.drawPath(temparg1, temparg2, false);\n }\n };\n PdfGraphics.prototype.drawPath = function (arg1, arg2, arg3, arg4) {\n if (typeof arg3 === 'boolean') {\n var temparg3 = arg3;\n this.drawPath(arg1, arg2, PdfFillMode.Winding, temparg3);\n }\n else {\n var temparg3 = arg3;\n var temparg4 = arg4;\n var isPen = arg1 != null;\n var isBrush = arg2 != null;\n var isEvenOdd = (temparg3 === PdfFillMode.Alternate);\n if (isPen && isBrush) {\n this.streamWriter.fillStrokePath(isEvenOdd);\n }\n else if (!isPen && !isBrush) {\n this.streamWriter.endPath();\n }\n else if (isPen) {\n this.streamWriter.strokePath();\n }\n else {\n this.streamWriter.fillPath(isEvenOdd);\n }\n }\n };\n /* tslint:disable */\n PdfGraphics.prototype.drawImage = function (arg1, arg2, arg3, arg4, arg5) {\n if (typeof arg2 === 'number' && typeof arg3 === 'number' && typeof arg4 === 'undefined') {\n var size = arg1.physicalDimension;\n this.drawImage(arg1, arg2, arg3, size.width, size.height);\n }\n else {\n var temparg2 = arg2;\n var temparg3 = arg3;\n var temparg4 = arg4;\n var temparg5 = arg5;\n arg1.save();\n var matrix = new PdfTransformationMatrix();\n this.getTranslateTransform(temparg2, (temparg3 + temparg5), matrix);\n this.getScaleTransform(arg4, arg5, matrix);\n this.pdfStreamWriter.write('q');\n this.pdfStreamWriter.modifyCtm(matrix);\n // Output template.\n var resources = this.getResources.getResources();\n if (typeof this.pageLayer !== 'undefined' && this.page != null) {\n resources.document = this.page.document;\n }\n var name_2 = resources.getName(arg1);\n if (typeof this.pageLayer !== 'undefined') {\n this.page.setResources(resources);\n }\n this.pdfStreamWriter.executeObject(name_2);\n this.pdfStreamWriter.write(Operators.restoreState);\n this.pdfStreamWriter.write(Operators.newLine);\n var resource = this.getResources.getResources();\n resource.requireProcedureSet(this.procedureSets.imageB);\n resource.requireProcedureSet(this.procedureSets.imageC);\n resource.requireProcedureSet(this.procedureSets.imageI);\n resource.requireProcedureSet(this.procedureSets.text);\n }\n };\n //Implementation\n /* tslint:disable */\n /**\n * Returns `bounds` of the line info.\n * @private\n */\n PdfGraphics.prototype.getLineBounds = function (lineIndex, result, font, layoutRectangle, format) {\n var bounds;\n if (!result.empty && lineIndex < result.lineCount && lineIndex >= 0) {\n var line = result.lines[lineIndex];\n var vShift = this.getTextVerticalAlignShift(result.actualSize.height, layoutRectangle.height, format);\n var y = vShift + layoutRectangle.y + (result.lineHeight * lineIndex);\n var lineWidth = line.width;\n var hShift = this.getHorizontalAlignShift(lineWidth, layoutRectangle.width, format);\n var lineIndent = this.getLineIndent(line, format, layoutRectangle, (lineIndex === 0));\n hShift += (!this.rightToLeft(format)) ? lineIndent : 0;\n var x = layoutRectangle.x + hShift;\n /* tslint:disable */\n var width = (!this.shouldJustify(line, layoutRectangle.width, format)) ? lineWidth - lineIndent : layoutRectangle.width - lineIndent; /* tslint:enable */\n var height = result.lineHeight;\n bounds = new RectangleF(x, y, width, height);\n }\n else {\n bounds = new RectangleF(0, 0, 0, 0);\n }\n return bounds;\n };\n /**\n * Creates `lay outed rectangle` depending on the text settings.\n * @private\n */\n PdfGraphics.prototype.checkCorrectLayoutRectangle = function (textSize, x, y, format) {\n var layoutedRectangle = new RectangleF(x, y, textSize.width, textSize.width);\n if (format != null) {\n switch (format.alignment) {\n case PdfTextAlignment.Center:\n layoutedRectangle.x -= layoutedRectangle.width / 2;\n break;\n case PdfTextAlignment.Right:\n layoutedRectangle.x -= layoutedRectangle.width;\n break;\n }\n switch (format.lineAlignment) {\n case PdfVerticalAlignment.Middle:\n layoutedRectangle.y -= layoutedRectangle.height / 2;\n break;\n case PdfVerticalAlignment.Bottom:\n layoutedRectangle.y -= layoutedRectangle.height;\n break;\n }\n }\n return layoutedRectangle;\n };\n /**\n * Sets the `layer` for the graphics.\n * @private\n */\n PdfGraphics.prototype.setLayer = function (layer) {\n this.pageLayer = layer;\n var page = layer.page;\n if (page != null && typeof page !== 'undefined') {\n page.beginSave = this.pageSave;\n }\n };\n /**\n * Adding page number field before page saving.\n * @private\n */\n /* tslint:disable */\n PdfGraphics.prototype.pageSave = function (page) {\n if (page.graphics.automaticFields != null) {\n for (var i = 0; i < page.graphics.automaticFields.automaticFields.length; i++) {\n var fieldInfo = page.graphics.automaticFields.automaticFields[i];\n fieldInfo.field.performDraw(page.graphics, fieldInfo.location, fieldInfo.scalingX, fieldInfo.scalingY);\n }\n }\n };\n /**\n * `Draws a layout result`.\n * @private\n */\n PdfGraphics.prototype.drawStringLayoutResult = function (result, font, pen, brush, layoutRectangle, format) {\n if (!result.empty) {\n this.applyStringSettings(font, pen, brush, format, layoutRectangle);\n // Set text scaling\n var textScaling = (format != null) ? format.horizontalScalingFactor : 100.0;\n if (textScaling !== this.previousTextScaling && !this.isEmfTextScaled) {\n this.pdfStreamWriter.setTextScaling(textScaling);\n this.previousTextScaling = textScaling;\n }\n var height = (format == null || format.lineSpacing === 0) ? font.height : format.lineSpacing + font.height;\n var subScript = (format != null && format.subSuperScript === PdfSubSuperScript.SubScript);\n var shift = 0;\n shift = (subScript) ? height - (font.height + font.metrics.getDescent(format)) : (height - font.metrics.getAscent(format));\n this.shift = shift;\n this.pdfStreamWriter.startNextLine(layoutRectangle.x, layoutRectangle.y - shift);\n this.pdfStreamWriter.setLeading(+height);\n var resultHeight = 0;\n var remainingString = '';\n for (var i = 0; i < result.lines.length; i++) {\n resultHeight += result.lineHeight;\n if ((layoutRectangle.y + resultHeight) > this.clientSize.height) {\n this.startCutIndex = i;\n break;\n }\n }\n for (var j = this.startCutIndex; (j < result.lines.length && j >= 0); j++) {\n remainingString += result.lines[j].text;\n }\n var bounds = new RectangleF(layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height);\n this.drawLayoutResult(result, font, format, layoutRectangle);\n this.underlineStrikeoutText(pen, brush, result, font, bounds, format);\n this.isEmfPlus = false;\n this.isUseFontSize = false;\n if (this.startCutIndex !== -1) {\n var page = this.getNextPage();\n page.graphics.drawString(remainingString, font, pen, brush, layoutRectangle.x, 0, layoutRectangle.width, 0, format);\n }\n }\n else {\n throw new Error('ArgumentNullException:result');\n }\n };\n /**\n * Gets the `next page`.\n * @private\n */\n PdfGraphics.prototype.getNextPage = function () {\n var section = this.currentPage.section;\n var nextPage = null;\n var index = section.indexOf(this.currentPage);\n if (index === section.count - 1) {\n nextPage = section.add();\n }\n else {\n nextPage = section.getPages()[index + 1];\n }\n return nextPage;\n };\n PdfGraphics.prototype.setClip = function (rectangle, mode) {\n if (typeof mode === 'undefined') {\n this.setClip(rectangle, PdfFillMode.Winding);\n }\n else {\n this.pdfStreamWriter.appendRectangle(rectangle);\n this.pdfStreamWriter.clipPath((mode === PdfFillMode.Alternate));\n }\n };\n /**\n * Applies all the `text settings`.\n * @private\n */\n PdfGraphics.prototype.applyStringSettings = function (font, pen, brush, format, bounds) {\n var setLineWidth = false;\n var tm = this.getTextRenderingMode(pen, brush, format);\n this.stateControl(pen, brush, font, format);\n this.pdfStreamWriter.beginText();\n if ((tm) !== this.previousTextRenderingMode) {\n this.pdfStreamWriter.setTextRenderingMode(tm);\n this.previousTextRenderingMode = tm;\n }\n // Set character spacing.\n var cs = (format != null) ? format.characterSpacing : 0;\n if (cs !== this.previousCharacterSpacing && !this.isEmfTextScaled) {\n this.pdfStreamWriter.setCharacterSpacing(cs);\n this.previousCharacterSpacing = cs;\n }\n // Set word spacing.\n // NOTE: it works only if the space code is equal to 32 (0x20).\n var ws = (format != null) ? format.wordSpacing : 0;\n if (ws !== this.previousWordSpacing) {\n this.pdfStreamWriter.setWordSpacing(ws);\n this.previousWordSpacing = ws;\n }\n };\n /**\n * Calculates `shift value` if the text is vertically aligned.\n * @private\n */\n PdfGraphics.prototype.getTextVerticalAlignShift = function (textHeight, boundsHeight, format) {\n var shift = 0;\n if (boundsHeight >= 0 && format != null && format.lineAlignment !== PdfVerticalAlignment.Top) {\n switch (format.lineAlignment) {\n case PdfVerticalAlignment.Middle:\n shift = (boundsHeight - textHeight) / 2;\n break;\n case PdfVerticalAlignment.Bottom:\n shift = boundsHeight - textHeight;\n break;\n }\n }\n return shift;\n };\n /* tslint:disable */\n /**\n * `Draws layout result`.\n * @private\n */\n PdfGraphics.prototype.drawLayoutResult = function (result, font, format, layoutRectangle) {\n var vAlignShift = this.getTextVerticalAlignShift(result.actualSize.height, layoutRectangle.height, format);\n if (vAlignShift !== 0) {\n this.pdfStreamWriter.startNextLine(0, vAlignShift);\n }\n var ttfFont = font;\n var unicode = (ttfFont != null && ttfFont.isUnicode);\n var embed = (ttfFont != null && ttfFont.isEmbedFont);\n var lines = result.lines;\n for (var i = 0, len = lines.length; (i < len && i !== this.startCutIndex); i++) {\n var lineInfo = lines[i];\n var line = lineInfo.text;\n var lineWidth = lineInfo.width;\n var hAlignShift = this.getHorizontalAlignShift(lineWidth, layoutRectangle.width, format);\n var lineIndent = this.getLineIndent(lineInfo, format, layoutRectangle, (i === 0));\n hAlignShift += (!this.rightToLeft(format)) ? lineIndent : 0;\n if (hAlignShift !== 0 && !this.isEmfTextScaled) {\n this.pdfStreamWriter.startNextLine(hAlignShift, 0);\n }\n if (unicode) {\n this.drawUnicodeLine(lineInfo, layoutRectangle, font, format);\n }\n else {\n this.drawAsciiLine(lineInfo, layoutRectangle, font, format);\n }\n if (hAlignShift !== 0 && !this.isEmfTextScaled) {\n this.pdfStreamWriter.startNextLine(-hAlignShift, 0);\n }\n if (this.isOverloadWithPosition && lines.length > 1) {\n this.pdfStreamWriter.startNextLine(-(layoutRectangle.x), 0);\n layoutRectangle.x = 0;\n layoutRectangle.width = this.clientSize.width;\n this.isOverloadWithPosition = false;\n this.isPointOverload = true;\n }\n }\n this.getResources.getResources().requireProcedureSet(this.procedureSets.text);\n if (vAlignShift !== 0) {\n this.pdfStreamWriter.startNextLine(0, -(vAlignShift - result.lineHeight));\n }\n this.pdfStreamWriter.endText();\n };\n /**\n * Draws unicode line.\n * @private\n */\n PdfGraphics.prototype.drawUnicodeLine = function (lineInfo, layoutRectangle, font, format) {\n var line = lineInfo.text;\n var lineWidth = lineInfo.width;\n var rtl = (format !== null && format.rightToLeft);\n var useWordSpace = (format !== null && (format.wordSpacing !== 0 || format.alignment === PdfTextAlignment.Justify));\n var ttfFont = font;\n var wordSpacing = this.justifyLine(lineInfo, layoutRectangle.width, format);\n if (useWordSpace) {\n var result = this.breakUnicodeLine(line, ttfFont, null);\n var blocks = result.tokens;\n var words = result.words;\n this.drawUnicodeBlocks(blocks, words, ttfFont, format, wordSpacing);\n }\n else {\n var token = this.convertToUnicode(line, ttfFont);\n var value = this.getUnicodeString(token);\n this.streamWriter.showNextLineText(value);\n }\n };\n /**\n * Draws array of unicode tokens.\n */\n /* tslint:disable */\n PdfGraphics.prototype.drawUnicodeBlocks = function (blocks, words, font, format, wordSpacing) {\n /* tslint:enable */\n if (blocks == null) {\n throw new Error('Argument Null Exception : blocks');\n }\n if (words == null) {\n throw new Error('Argument Null Exception : words');\n }\n this.streamWriter.startNextLine();\n var x = 0;\n var xShift = 0;\n var firstLineIndent = 0;\n var paragraphIndent = 0;\n try {\n if (format !== null) {\n firstLineIndent = format.firstLineIndent;\n paragraphIndent = format.paragraphIndent;\n format.firstLineIndent = 0;\n format.paragraphIndent = 0;\n }\n var spaceWidth = font.getCharWidth(StringTokenizer.whiteSpace, format) + wordSpacing;\n var characterSpacing = (format != null) ? format.characterSpacing : 0;\n var wordSpace = (format !== null && wordSpacing === 0) ? format.wordSpacing : 0;\n spaceWidth += characterSpacing + wordSpace;\n for (var i = 0; i < blocks.length; i++) {\n var token = blocks[i];\n var word = words[i];\n var tokenWidth = 0;\n if (x !== 0) {\n this.streamWriter.startNextLine(x, 0);\n }\n if (word.length > 0) {\n tokenWidth += /*Utils.Round(*/ font.measureString(word, format).width /*)*/;\n tokenWidth += characterSpacing;\n var val = this.getUnicodeString(token);\n this.streamWriter.showText(val);\n }\n if (i !== blocks.length - 1) {\n x = tokenWidth + spaceWidth;\n xShift += x;\n }\n }\n // Rolback current line position.\n if (xShift > 0) {\n this.streamWriter.startNextLine(-xShift, 0);\n }\n }\n finally {\n if (format !== null) {\n format.firstLineIndent = firstLineIndent;\n format.paragraphIndent = paragraphIndent;\n }\n }\n };\n /**\n * Breakes the unicode line to the words and converts symbols to glyphs.\n */\n PdfGraphics.prototype.breakUnicodeLine = function (line, ttfFont, words) {\n if (line === null) {\n throw new Error('Argument Null Exception : line');\n }\n words = line.split(null);\n var tokens = [];\n for (var i = 0; i < words.length; i++) {\n // Reconvert string according to unicode standard.\n var word = words[i];\n var token = this.convertToUnicode(word, ttfFont);\n tokens[i] = token;\n }\n return { tokens: tokens, words: words };\n };\n /**\n * Creates PdfString from the unicode text.\n */\n PdfGraphics.prototype.getUnicodeString = function (token) {\n if (token === null) {\n throw new Error('Argument Null Exception : token');\n }\n var val = new PdfString(token);\n val.converted = true;\n val.encode = InternalEnum.ForceEncoding.Ascii;\n return val;\n };\n /**\n * Converts to unicode format.\n */\n PdfGraphics.prototype.convertToUnicode = function (text, ttfFont) {\n var token = null;\n if (text == null) {\n throw new Error('Argument Null Exception : text');\n }\n if (ttfFont == null) {\n throw new Error('Argument Null Exception : ttfFont');\n }\n if (ttfFont.fontInternal instanceof UnicodeTrueTypeFont) {\n var ttfReader = ttfFont.fontInternal.ttfReader;\n ttfFont.setSymbols(text);\n token = ttfReader.convertString(text);\n var bytes = PdfString.toUnicodeArray(token, false);\n token = PdfString.byteToString(bytes);\n }\n return token;\n };\n /**\n * `Draws Ascii line`.\n * @private\n */\n PdfGraphics.prototype.drawAsciiLine = function (lineInfo, layoutRectangle, font, format) {\n this.justifyLine(lineInfo, layoutRectangle.width, format);\n var value = '';\n if (lineInfo.text.indexOf('(') !== -1 || lineInfo.text.indexOf(')') !== -1) {\n for (var i = 0; i < lineInfo.text.length; i++) {\n if (lineInfo.text[i] === '(') {\n value += '\\\\\\(';\n }\n else if (lineInfo.text[i] === ')') {\n value += '\\\\\\)';\n }\n else {\n value += lineInfo.text[i];\n }\n }\n }\n if (value === '') {\n value = lineInfo.text;\n }\n var line = '(' + value + ')';\n this.pdfStreamWriter.showNextLineText(new PdfString(line));\n };\n /**\n * `Justifies` the line if needed.\n * @private\n */\n PdfGraphics.prototype.justifyLine = function (lineInfo, boundsWidth, format) {\n var line = lineInfo.text;\n var lineWidth = lineInfo.width;\n var shouldJustify = this.shouldJustify(lineInfo, boundsWidth, format);\n var hasWordSpacing = (format != null && format.wordSpacing !== 0);\n var symbols = StringTokenizer.spaces;\n var whitespacesCount = StringTokenizer.getCharsCount(line, symbols);\n var wordSpace = 0;\n if (shouldJustify) {\n // Correct line width.\n if (hasWordSpacing) {\n lineWidth -= (whitespacesCount * format.wordSpacing);\n }\n var difference = boundsWidth - lineWidth;\n wordSpace = difference / whitespacesCount;\n this.pdfStreamWriter.setWordSpacing(wordSpace);\n }\n else {\n // If there is justifying, but the line shouldn't be justified, restore default word spacing.\n if (hasWordSpacing) {\n this.pdfStreamWriter.setWordSpacing(format.wordSpacing);\n }\n else {\n this.pdfStreamWriter.setWordSpacing(0);\n }\n }\n return wordSpace;\n };\n /**\n * `Reset` or reinitialize the current graphic value.\n * @private\n */\n PdfGraphics.prototype.reset = function (size) {\n this.canvasSize = size;\n this.streamWriter.clear();\n this.initialize();\n this.initializeCoordinates();\n };\n /**\n * Checks whether the line should be `justified`.\n * @private\n */\n PdfGraphics.prototype.shouldJustify = function (lineInfo, boundsWidth, format) {\n var line = lineInfo.text;\n var lineWidth = lineInfo.width;\n var justifyStyle = (format != null && format.alignment === PdfTextAlignment.Justify);\n var goodWidth = (boundsWidth >= 0 && lineWidth < boundsWidth);\n var symbols = StringTokenizer.spaces;\n var whitespacesCount = StringTokenizer.getCharsCount(line, symbols);\n var hasSpaces = (whitespacesCount > 0 && line[0] !== StringTokenizer.whiteSpace);\n var goodLineBreakStyle = ((lineInfo.lineType & LineType.LayoutBreak) > 0);\n /* tslint:disable */\n var shouldJustify = (justifyStyle && goodWidth && hasSpaces && (goodLineBreakStyle || format.alignment === PdfTextAlignment.Justify)); /* tslint:enable */\n return shouldJustify;\n };\n /* tslint:disable */\n /**\n * Emulates `Underline, Strikeout` of the text if needed.\n * @private\n */\n PdfGraphics.prototype.underlineStrikeoutText = function (pen, brush, result, font, layoutRectangle, format) {\n if (font.underline || font.strikeout) {\n // Calculate line width.\n var linePen = this.createUnderlineStikeoutPen(pen, brush, font, format);\n if (linePen != null) {\n // Approximate line positions.\n var vShift = this.getTextVerticalAlignShift(result.actualSize.height, layoutRectangle.height, format);\n var underlineYOffset = 0;\n underlineYOffset = layoutRectangle.y + vShift + font.metrics.getAscent(format) + 1.5 * linePen.width;\n var strikeoutYOffset = layoutRectangle.y + vShift + font.metrics.getHeight(format) / 2 + 1.5 * linePen.width;\n var lines = result.lines;\n // Run through the text and draw lines.\n for (var i = 0, len = result.lineCount; i < len; i++) {\n var lineInfo = lines[i];\n var line = lineInfo.text;\n var lineWidth = lineInfo.width;\n var hShift = this.getHorizontalAlignShift(lineWidth, layoutRectangle.width, format);\n var lineIndent = this.getLineIndent(lineInfo, format, layoutRectangle, (i === 0));\n hShift += (!this.rightToLeft(format)) ? lineIndent : 0;\n var x1 = layoutRectangle.x + hShift;\n /* tslint:disable */\n var x2 = (!this.shouldJustify(lineInfo, layoutRectangle.width, format)) ? x1 + lineWidth - lineIndent : x1 + layoutRectangle.width - lineIndent;\n /* tslint:enable */\n if (font.underline) {\n var y = underlineYOffset;\n this.drawLine(linePen, x1, y, x2, y);\n underlineYOffset += result.lineHeight;\n }\n if (font.strikeout) {\n var y = strikeoutYOffset;\n this.drawLine(linePen, x1, y, x2, y);\n strikeoutYOffset += result.lineHeight;\n }\n if (this.isPointOverload && lines.length > 1) {\n layoutRectangle.x = 0;\n layoutRectangle.width = this.clientSize.width;\n }\n }\n this.isPointOverload = false;\n }\n }\n };\n /**\n * `Creates a pen` for drawing lines in the text.\n * @private\n */\n PdfGraphics.prototype.createUnderlineStikeoutPen = function (pen, brush, font, format) {\n // Calculate line width.\n var lineWidth = font.metrics.getSize(format) / 20;\n var linePen = null;\n // Create a pen fo the lines.\n if (pen != null) {\n linePen = new PdfPen(pen.color, lineWidth);\n }\n else if (brush != null) {\n linePen = new PdfPen(brush, lineWidth);\n }\n return linePen;\n };\n /**\n * Return `text rendering mode`.\n * @private\n */\n PdfGraphics.prototype.getTextRenderingMode = function (pen, brush, format) {\n var tm = TextRenderingMode.None;\n if (pen != null && brush != null) {\n tm = TextRenderingMode.FillStroke;\n }\n else if (pen != null) {\n tm = TextRenderingMode.Stroke;\n }\n else {\n tm = TextRenderingMode.Fill;\n }\n if (format != null && format.clipPath) {\n tm |= TextRenderingMode.ClipFlag;\n }\n return tm;\n };\n /**\n * Returns `line indent` for the line.\n * @private\n */\n PdfGraphics.prototype.getLineIndent = function (lineInfo, format, layoutBounds, firstLine) {\n var lineIndent = 0;\n var firstParagraphLine = ((lineInfo.lineType & LineType.FirstParagraphLine) > 0);\n if (format != null && firstParagraphLine) {\n lineIndent = (firstLine) ? format.firstLineIndent : format.paragraphIndent;\n lineIndent = (layoutBounds.width > 0) ? Math.min(layoutBounds.width, lineIndent) : lineIndent;\n }\n return lineIndent;\n };\n /**\n * Calculates shift value if the line is `horizontaly aligned`.\n * @private\n */\n PdfGraphics.prototype.getHorizontalAlignShift = function (lineWidth, boundsWidth, format) {\n var shift = 0;\n if (boundsWidth >= 0 && format != null && format.alignment !== PdfTextAlignment.Left) {\n switch (format.alignment) {\n case PdfTextAlignment.Center:\n shift = (boundsWidth - lineWidth) / 2;\n break;\n case PdfTextAlignment.Right:\n shift = boundsWidth - lineWidth;\n break;\n }\n }\n return shift;\n };\n /**\n * Gets or sets the value that indicates `text direction` mode.\n * @private\n */\n PdfGraphics.prototype.rightToLeft = function (format) {\n var rtl = (format != null && format.rightToLeft);\n return rtl;\n };\n PdfGraphics.prototype.stateControl = function (pen, brush, font, format) {\n if (typeof format === 'undefined') {\n this.stateControl(pen, brush, font, null);\n }\n else {\n var saveState = false;\n if (brush !== null) {\n var solidBrush = brush;\n if (typeof this.pageLayer !== 'undefined' && this.pageLayer != null) {\n if (this.colorSpaceChanged === false) {\n this.lastDocumentCS = this.pageLayer.page.document.colorSpace;\n this.lastGraphicsCS = this.pageLayer.page.graphics.colorSpace;\n this.colorSpace = this.pageLayer.page.document.colorSpace;\n this.currentColorSpace = this.pageLayer.page.document.colorSpace;\n this.colorSpaceChanged = true;\n }\n }\n this.initCurrentColorSpace(this.currentColorSpace);\n }\n else if (pen != null) {\n var pdfPen = pen;\n if (typeof this.pageLayer !== 'undefined' && this.pageLayer != null) {\n /* tslint:disable */\n this.colorSpace = this.pageLayer.page.document.colorSpace;\n this.currentColorSpace = this.pageLayer.page.document.colorSpace;\n }\n this.initCurrentColorSpace(this.currentColorSpace);\n }\n this.penControl(pen, saveState);\n this.brushControl(brush, saveState);\n this.fontControl(font, format, saveState);\n }\n };\n /**\n * Initializes the `current color space`.\n * @private\n */\n PdfGraphics.prototype.initCurrentColorSpace = function (colorspace) {\n var re = this.getResources.getResources();\n if (!this.bCSInitialized) {\n this.pdfStreamWriter.setColorSpace('Device' + this.currentColorSpaces[this.currentColorSpace], true);\n this.pdfStreamWriter.setColorSpace('Device' + this.currentColorSpaces[this.currentColorSpace], false);\n this.bCSInitialized = true;\n }\n };\n /**\n * Controls the `pen state`.\n * @private\n */\n PdfGraphics.prototype.penControl = function (pen, saveState) {\n if (pen != null) {\n this.currentPen = pen;\n this.colorSpace = PdfColorSpace.Rgb;\n /* tslint:disable */\n pen.monitorChanges(this.currentPen, this.pdfStreamWriter, this.getResources, saveState, this.colorSpace, this.matrix.clone());\n /* tslint:enable */\n this.currentPen = pen.clone();\n }\n };\n /**\n * Controls the `brush state`.\n * @private\n */\n PdfGraphics.prototype.brushControl = function (brush, saveState) {\n if (brush != null) {\n this.currentBrush = brush;\n /* tslint:disable */\n brush.monitorChanges(this.currentBrush, this.pdfStreamWriter, this.getResources, saveState, this.colorSpace);\n /* tslint:enable */\n this.currentBrush = brush;\n brush = null;\n }\n };\n /**\n * Saves the font and other `font settings`.\n * @private\n */\n PdfGraphics.prototype.fontControl = function (font, format, saveState) {\n if (font != null) {\n var curSubSuper = (format != null) ? format.subSuperScript : PdfSubSuperScript.None;\n /* tslint:disable */\n var prevSubSuper = (this.currentStringFormat != null) ? this.currentStringFormat.subSuperScript : PdfSubSuperScript.None; /* tslint:enable */\n if (saveState || font !== this.currentFont || curSubSuper !== prevSubSuper) {\n var resources = this.getResources.getResources();\n this.currentFont = font;\n this.currentStringFormat = format;\n var size = font.metrics.getSize(format);\n /* tslint:disable */\n this.isEmfTextScaled = false;\n var fontName = resources.getName(font);\n this.pdfStreamWriter.setFont(font, fontName, size);\n }\n }\n };\n PdfGraphics.prototype.setTransparency = function (arg1, arg2, arg3) {\n if (typeof arg2 === 'undefined') {\n this.istransparencySet = true;\n this.setTransparency(arg1, arg1, PdfBlendMode.Normal);\n }\n else if (typeof arg2 === 'number' && typeof arg3 === 'undefined') {\n this.setTransparency(arg1, arg2, PdfBlendMode.Normal);\n }\n else {\n if (this.trasparencies == null) {\n this.trasparencies = new TemporaryDictionary();\n }\n var transp = null;\n var td = new TransparencyData(arg1, arg2, arg3);\n if (this.trasparencies.containsKey(td)) {\n transp = this.trasparencies.getValue(td);\n }\n if (transp == null) {\n transp = new PdfTransparency(arg1, arg2, arg3);\n this.trasparencies.setValue(td, transp);\n }\n var resources = this.getResources.getResources();\n var name_3 = resources.getName(transp);\n var sw = this.streamWriter;\n sw.setGraphicsState(name_3);\n }\n };\n PdfGraphics.prototype.clipTranslateMargins = function (x, y, left, top, right, bottom) {\n if (x instanceof RectangleF && typeof y === 'undefined') {\n this.clipBounds = x;\n this.pdfStreamWriter.writeComment('Clip margins.');\n this.pdfStreamWriter.appendRectangle(x);\n this.pdfStreamWriter.closePath();\n this.pdfStreamWriter.clipPath(false);\n this.pdfStreamWriter.writeComment('Translate co-ordinate system.');\n this.translateTransform(x.x, x.y);\n }\n else if (typeof x === 'number') {\n var clipArea = new RectangleF(left, top, this.size.width - left - right, this.size.height - top - bottom);\n this.clipBounds = clipArea;\n this.pdfStreamWriter.writeComment(\"Clip margins.\");\n this.pdfStreamWriter.appendRectangle(clipArea);\n this.pdfStreamWriter.closePath();\n this.pdfStreamWriter.clipPath(false);\n this.pdfStreamWriter.writeComment(\"Translate co-ordinate system.\");\n this.translateTransform(x, y);\n }\n };\n /**\n * `Updates y` co-ordinate.\n * @private\n */\n PdfGraphics.prototype.updateY = function (y) {\n return -y;\n };\n /**\n * Used to `translate the transformation`.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create a new page\n * let page1 : PdfPage = document.pages.add();\n * // set pen\n * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0));\n * //\n * // set translate transform\n * page1.graphics.translateTransform(100, 100);\n * //\n * // draw the rectangle after applying translate transform\n * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n * @param offsetX The x-coordinate of the translation.\n * @param offsetY The y-coordinate of the translation.\n */\n PdfGraphics.prototype.translateTransform = function (offsetX, offsetY) {\n var matrix = new PdfTransformationMatrix();\n this.getTranslateTransform(offsetX, offsetY, matrix);\n this.pdfStreamWriter.modifyCtm(matrix);\n this.matrix.multiply(matrix);\n };\n /**\n * `Translates` coordinates of the input matrix.\n * @private\n */\n PdfGraphics.prototype.getTranslateTransform = function (x, y, input) {\n input.translate(x, this.updateY(y));\n return input;\n };\n /* tslint:disable */\n /**\n * Applies the specified `scaling operation` to the transformation matrix of this Graphics by prepending it to the object's transformation matrix.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create a new page\n * let page1 : PdfPage = document.pages.add();\n * // create pen\n * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0));\n * //\n * // apply scaling trasformation\n * page1.graphics.scaleTransform(1.5, 2);\n * //\n * // draw the rectangle after applying scaling transform\n * page1.graphics.drawRectangle(pen, new RectangleF({x : 100, y : 100}, {width : 100, height : 50}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n * @param scaleX Scale factor in the x direction.\n * @param scaleY Scale factor in the y direction.\n */\n /* tslint:enable */\n PdfGraphics.prototype.scaleTransform = function (scaleX, scaleY) {\n var matrix = new PdfTransformationMatrix();\n this.getScaleTransform(scaleX, scaleY, matrix);\n this.pdfStreamWriter.modifyCtm(matrix);\n this.matrix.multiply(matrix);\n };\n /**\n * `Scales` coordinates of the input matrix.\n * @private\n */\n PdfGraphics.prototype.getScaleTransform = function (x, y, input) {\n if (input == null) {\n input = new PdfTransformationMatrix();\n }\n input.scale(x, y);\n return input;\n };\n /**\n * Applies the specified `rotation` to the transformation matrix of this Graphics.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create a new page\n * let page1 : PdfPage = document.pages.add();\n * // create pen\n * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0));\n * //\n * // set RotateTransform with 25 degree of angle\n * page1.graphics.rotateTransform(25);\n * //\n * // draw the rectangle after RotateTransformation\n * page1.graphics.drawRectangle(pen, new RectangleF({x : 100, y : 100}, {width : 100, height : 50}));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n * @param angle Angle of rotation in degrees.\n */\n PdfGraphics.prototype.rotateTransform = function (angle) {\n var matrix = new PdfTransformationMatrix();\n this.getRotateTransform(angle, matrix);\n this.pdfStreamWriter.modifyCtm(matrix);\n this.matrix.multiply(matrix);\n };\n /**\n * `Initializes coordinate system`.\n * @private\n */\n PdfGraphics.prototype.initializeCoordinates = function () {\n // Matrix equation: TM(T-1)=M', where T=[1 0 0 -1 0 h]\n this.pdfStreamWriter.writeComment('Change co-ordinate system to left/top.');\n // Translate co-ordinates only, don't flip.\n if (this.mediaBoxUpperRightBound !== -(this.size.height)) {\n if (this.cropBox == null) {\n if (this.mediaBoxUpperRightBound === this.size.height || this.mediaBoxUpperRightBound === 0) {\n this.translateTransform(0, this.updateY(this.size.height));\n }\n else {\n this.translateTransform(0, this.updateY(this.mediaBoxUpperRightBound));\n }\n }\n }\n };\n /**\n * `Rotates` coordinates of the input matrix.\n * @private\n */\n PdfGraphics.prototype.getRotateTransform = function (angle, input) {\n if (input == null || typeof input === 'undefined') {\n input = new PdfTransformationMatrix();\n }\n input.rotate(this.updateY(angle));\n return input;\n };\n /**\n * `Saves` the current state of this Graphics and identifies the saved state with a GraphicsState.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create a new page\n * let page1 : PdfPage = document.pages.add();\n * // create pen\n * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0));\n * //\n * // save the graphics state\n * let state1 : PdfGraphicsState = page1.graphics.save();\n * //\n * page1.graphics.scaleTransform(1.5, 2);\n * // draw the rectangle\n * page1.graphics.drawRectangle(pen, new RectangleF({x : 100, y : 100}, {width : 100, height : 50}));\n * // restore the graphics state\n * page1.graphics.restore(state1);\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n PdfGraphics.prototype.save = function () {\n var state = new PdfGraphicsState(this, this.matrix.clone());\n state.brush = this.currentBrush;\n state.pen = this.currentPen;\n state.font = this.currentFont;\n state.colorSpace = this.currentColorSpace;\n state.characterSpacing = this.previousCharacterSpacing;\n state.wordSpacing = this.previousWordSpacing;\n state.textScaling = this.previousTextScaling;\n state.textRenderingMode = this.previousTextRenderingMode;\n this.graphicsState.push(state);\n this.pdfStreamWriter.saveGraphicsState();\n return state;\n };\n PdfGraphics.prototype.restore = function (state) {\n if (typeof state === 'undefined') {\n if (this.graphicsState.length > 0) {\n this.doRestoreState();\n }\n }\n else {\n if (this.graphicsState.indexOf(state) !== -1) {\n for (;;) {\n if (this.graphicsState.length === 0) {\n break;\n }\n var popState = this.doRestoreState();\n if (popState === state) {\n break;\n }\n }\n }\n }\n };\n /**\n * `Restores graphics state`.\n * @private\n */\n PdfGraphics.prototype.doRestoreState = function () {\n var state = this.graphicsState.pop();\n this.transformationMatrix = state.matrix;\n this.currentBrush = state.brush;\n this.currentPen = state.pen;\n this.currentFont = state.font;\n this.currentColorSpace = state.colorSpace;\n this.previousCharacterSpacing = state.characterSpacing;\n this.previousWordSpacing = state.wordSpacing;\n this.previousTextScaling = state.textScaling;\n this.previousTextRenderingMode = state.textRenderingMode;\n this.pdfStreamWriter.restoreGraphicsState();\n return state;\n };\n // Constants\n /**\n * Specifies the mask of `path type values`.\n * @private\n */\n PdfGraphics.pathTypesValuesMask = 0xf;\n /**\n * Checks whether the object is `transparencyObject`.\n * @hidden\n * @private\n */\n PdfGraphics.transparencyObject = false;\n return PdfGraphics;\n}());\nexport { PdfGraphics };\n/**\n * `GetResourceEventHandler` class is alternate for event handlers and delegates.\n * @private\n * @hidden\n */\nvar GetResourceEventHandler = /** @class */ (function () {\n /**\n * Initialize instance of `GetResourceEventHandler` class.\n * Alternate for event handlers and delegates.\n * @private\n */\n function GetResourceEventHandler(sender) {\n this.sender = sender;\n }\n /**\n * Return the instance of `PdfResources` class.\n * @private\n */\n GetResourceEventHandler.prototype.getResources = function () {\n return this.sender.getResources();\n };\n return GetResourceEventHandler;\n}());\nexport { GetResourceEventHandler };\nvar PdfGraphicsState = /** @class */ (function () {\n function PdfGraphicsState(graphics, matrix) {\n /**\n * Stores `previous rendering mode`.\n * @default TextRenderingMode.Fill\n * @private\n */\n this.internalTextRenderingMode = TextRenderingMode.Fill;\n /**\n * `Previous character spacing` value or 0.\n * @default 0.0\n * @private\n */\n this.internalCharacterSpacing = 0.0;\n /**\n * `Previous word spacing` value or 0.\n * @default 0.0\n * @private\n */\n this.internalWordSpacing = 0.0;\n /**\n * The previously used `text scaling value`.\n * @default 100.0\n * @private\n */\n this.internalTextScaling = 100.0;\n /**\n * `Current color space`.\n * @default PdfColorSpace.Rgb\n * @private\n */\n this.pdfColorSpace = PdfColorSpace.Rgb;\n if (typeof graphics !== 'undefined') {\n this.pdfGraphics = graphics;\n this.transformationMatrix = matrix;\n }\n }\n Object.defineProperty(PdfGraphicsState.prototype, \"graphics\", {\n // Properties\n /**\n * Gets the parent `graphics object`.\n * @private\n */\n get: function () {\n return this.pdfGraphics;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"matrix\", {\n /**\n * Gets the `current matrix`.\n * @private\n */\n get: function () {\n return this.transformationMatrix;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"characterSpacing\", {\n /**\n * Gets or sets the `current character spacing`.\n * @private\n */\n get: function () {\n return this.internalCharacterSpacing;\n },\n set: function (value) {\n this.internalCharacterSpacing = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"wordSpacing\", {\n /**\n * Gets or sets the `word spacing` value.\n * @private\n */\n get: function () {\n return this.internalWordSpacing;\n },\n set: function (value) {\n this.internalWordSpacing = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"textScaling\", {\n /**\n * Gets or sets the `text scaling` value.\n * @private\n */\n get: function () {\n return this.internalTextScaling;\n },\n set: function (value) {\n this.internalTextScaling = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"pen\", {\n /**\n * Gets or sets the `current pen` object.\n * @private\n */\n get: function () {\n return this.pdfPen;\n },\n set: function (value) {\n this.pdfPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"brush\", {\n /**\n * Gets or sets the `brush`.\n * @private\n */\n get: function () {\n return this.pdfBrush;\n },\n set: function (value) {\n this.pdfBrush = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"font\", {\n /**\n * Gets or sets the `current font` object.\n * @private\n */\n get: function () {\n return this.pdfFont;\n },\n set: function (value) {\n this.pdfFont = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"colorSpace\", {\n /**\n * Gets or sets the `current color space` value.\n * @private\n */\n get: function () {\n return this.pdfColorSpace;\n },\n set: function (value) {\n this.pdfColorSpace = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGraphicsState.prototype, \"textRenderingMode\", {\n /**\n * Gets or sets the `text rendering mode`.\n * @private\n */\n get: function () {\n return this.internalTextRenderingMode;\n },\n set: function (value) {\n this.internalTextRenderingMode = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGraphicsState;\n}());\nexport { PdfGraphicsState };\nvar TransparencyData = /** @class */ (function () {\n // Constructors\n /**\n * Initializes a new instance of the `TransparencyData` class.\n * @private\n */\n function TransparencyData(alphaPen, alphaBrush, blendMode) {\n this.alphaPen = alphaPen;\n this.alphaBrush = alphaBrush;\n this.blendMode = blendMode;\n }\n return TransparencyData;\n}());\n","import { PdfStream } from './../primitives/pdf-stream';\nimport { PdfGraphics, GetResourceEventHandler } from './../graphics/pdf-graphics';\nimport { PdfPageLayerCollection } from './pdf-page-layer-collection';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { PdfColorSpace } from './../graphics/enum';\n/**\n * The `PdfPageLayer` used to create layers in PDF document.\n * @private\n */\nvar PdfPageLayer = /** @class */ (function () {\n function PdfPageLayer(page, streamClipPageTemplates) {\n // private bSaved : boolean;\n /**\n * Local Variable to store the `color space` of the document.\n * @private\n */\n this.pdfColorSpace = PdfColorSpace.Rgb;\n /**\n * Local Variable to set `visibility`.\n * @default true\n * @private\n */\n this.isVisible = true;\n /**\n * Indicates if `Sublayer` is present.\n * @default false\n * @private\n */\n this.sublayer = false;\n /**\n * Local variable to store `length` of the graphics.\n * @default 0\n * @private\n */\n this.contentLength = 0;\n /**\n * Instance for `PdfDictionaryProperties` Class.\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n if (typeof streamClipPageTemplates === 'undefined') {\n this.pdfPage = page;\n this.clipPageTemplates = true;\n this.content = new PdfStream();\n }\n else if (streamClipPageTemplates instanceof PdfStream || streamClipPageTemplates === null) {\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n if (streamClipPageTemplates == null) {\n throw new Error('ArgumentNullException:stream');\n }\n this.pdfPage = page;\n this.content = streamClipPageTemplates;\n }\n else {\n this.constructor(page);\n this.clipPageTemplates = streamClipPageTemplates;\n }\n }\n Object.defineProperty(PdfPageLayer.prototype, \"colorSpace\", {\n // Properties\n /**\n * Get or set the `color space`.\n * @private\n */\n get: function () {\n return this.pdfColorSpace;\n },\n set: function (value) {\n this.pdfColorSpace = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageLayer.prototype, \"page\", {\n /**\n * Gets parent `page` of the layer.\n * @private\n */\n get: function () {\n return this.pdfPage;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageLayer.prototype, \"layerId\", {\n /**\n * Gets and Sets the `id of the layer`.\n * @private\n */\n get: function () {\n return this.layerid;\n },\n set: function (value) {\n this.layerid = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageLayer.prototype, \"name\", {\n /**\n * Gets or sets the `name` of the layer.\n * @private\n */\n get: function () {\n return this.layerName;\n },\n set: function (value) {\n this.layerName = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageLayer.prototype, \"visible\", {\n /**\n * Gets or sets the `visibility` of the layer.\n * @private\n */\n get: function () {\n return this.isVisible;\n },\n set: function (value) {\n this.isVisible = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageLayer.prototype, \"graphics\", {\n /**\n * Gets `Graphics` context of the layer, used to draw various graphical content on layer.\n * @private\n */\n get: function () {\n if ((this.pdfGraphics == null)) {\n this.initializeGraphics(this.page);\n }\n return this.pdfGraphics;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageLayer.prototype, \"layers\", {\n /**\n * Gets the collection of `PdfPageLayer`, this collection handle by the class 'PdfPageLayerCollection'.\n * @private\n */\n get: function () {\n if (this.layer == null) {\n this.layer = new PdfPageLayerCollection(this.page);\n this.layer.sublayer = true;\n return this.layer;\n }\n else {\n return this.layer;\n }\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Adds` a new PDF Page layer.\n * @private\n */\n PdfPageLayer.prototype.add = function () {\n var layer = new PdfPageLayer(this.pdfPage);\n layer.name = '';\n return layer;\n };\n /**\n * Returns a value indicating the `sign` of a single-precision floating-point number.\n * @private\n */\n PdfPageLayer.prototype.sign = function (number) {\n if (number === 0) {\n return 0;\n }\n else if (number > 0) {\n return 1;\n }\n else {\n return -1;\n }\n };\n /**\n * `Initializes Graphics context` of the layer.\n * @private\n */\n PdfPageLayer.prototype.initializeGraphics = function (page) {\n var oPage = page;\n var gr = new GetResourceEventHandler(this.page);\n var cropBox = null;\n this.pdfGraphics = new PdfGraphics(page.size, gr, this.content);\n this.pdfGraphics.mediaBoxUpperRightBound = 0;\n if (oPage != null) {\n var sc = oPage.section.parent;\n if (sc != null) {\n this.pdfGraphics.colorSpace = sc.document.colorSpace;\n this.colorSpace = sc.document.colorSpace;\n }\n }\n // Transform coordinates to the left/top and activate margins.\n var isSame = (this.sign(page.origin.y) === this.sign(page.origin.x));\n // if (page != null) {\n if (page.origin.x >= 0 && page.origin.y >= 0 || !(isSame)) {\n this.pdfGraphics.initializeCoordinates();\n }\n else {\n // this.m_graphics.InitializeCoordinates(page);\n }\n var clipRect = oPage.section.getActualBounds(oPage, true);\n var margins = oPage.section.pageSettings.margins;\n if (this.clipPageTemplates) {\n if (page.origin.x >= 0 && page.origin.y >= 0) {\n this.pdfGraphics.clipTranslateMargins(clipRect);\n }\n }\n else {\n this.graphics.clipTranslateMargins(clipRect.x, clipRect.y, margins.left, margins.top, margins.right, margins.bottom);\n }\n this.pdfGraphics.setLayer(this);\n // this.bSaved = false;\n };\n Object.defineProperty(PdfPageLayer.prototype, \"element\", {\n // IPdfWrapper Members\n /**\n * Gets the wrapped `element`.\n * @private\n */\n get: function () {\n return this.content;\n },\n enumerable: true,\n configurable: true\n });\n return PdfPageLayer;\n}());\nexport { PdfPageLayer };\n","/**\n * PdfCollection.ts class for EJ2-PDF\n * The class used to handle the collection of PdF objects.\n */\nvar PdfCollection = /** @class */ (function () {\n // Constructors\n /**\n * Initializes a new instance of the `Collection` class.\n * @private\n */\n function PdfCollection() {\n //\n }\n Object.defineProperty(PdfCollection.prototype, \"count\", {\n // Properties\n /**\n * Gets the `Count` of stored objects.\n * @private\n */\n get: function () {\n if (typeof this.collection === 'undefined') {\n this.collection = [];\n }\n return this.collection.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCollection.prototype, \"list\", {\n /**\n * Gets the `list` of stored objects.\n * @private\n */\n get: function () {\n if (typeof this.collection === 'undefined') {\n this.collection = [];\n }\n return this.collection;\n },\n enumerable: true,\n configurable: true\n });\n return PdfCollection;\n}());\nexport { PdfCollection };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfPageLayerCollection.ts class for EJ2-PDF\n */\nimport { PdfPageBase } from './pdf-page-base';\nimport { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { PdfPageLayer } from './pdf-page-layer';\nimport { PdfCollection } from './../general/pdf-collection';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { PdfStream } from './../primitives/pdf-stream';\n/**\n * The class provides methods and properties to handle the collections of `PdfPageLayer`.\n */\nvar PdfPageLayerCollection = /** @class */ (function (_super) {\n __extends(PdfPageLayerCollection, _super);\n function PdfPageLayerCollection(page) {\n var _this = _super.call(this) || this;\n /**\n * Stores the `number of first level layers` in the document.\n * @default 0\n * @private\n */\n _this.parentLayerCount = 0;\n /**\n * Indicates if `Sublayer` is present.\n * @default false\n * @private\n */\n _this.sublayer = false;\n /**\n * Stores the `optional content dictionary`.\n * @private\n */\n _this.optionalContent = new PdfDictionary();\n if (page instanceof PdfPageBase) {\n // if (page == null) {\n // throw new Error('ArgumentNullException:page');\n // }\n _this.page = page;\n var lPage = page;\n // if (lPage != null) {\n _this.parseLayers(lPage);\n // }\n }\n return _this;\n }\n PdfPageLayerCollection.prototype.items = function (index, value) {\n if (typeof index === 'number' && typeof value === 'undefined') {\n var obj = this.list[index];\n return obj;\n }\n else {\n if (value == null) {\n throw new Error('ArgumentNullException: layer');\n }\n if (value.page !== this.page) {\n throw new Error('ArgumentException: The layer belongs to another page');\n }\n // // Add/remove the layer.\n // let layer : PdfPageLayer = this.items(index);\n // if (layer != null) {\n // this.RemoveLayer(layer);\n // }\n // this.List[index] = value;\n // this.InsertLayer(index, value);\n }\n };\n PdfPageLayerCollection.prototype.add = function (firstArgument, secondArgument) {\n if (typeof firstArgument === 'undefined') {\n var layer = new PdfPageLayer(this.page);\n layer.name = '';\n this.add(layer);\n return layer;\n }\n else if (firstArgument instanceof PdfPageLayer) {\n // if (layer == null)\n // throw new ArgumentNullException(\"layer\");\n // if (layer.Page != m_page)\n // throw new ArgumentException(\"The layer belongs to another page\");\n var index = this.list.push(firstArgument);\n // Register layer.\n this.addLayer(index, firstArgument);\n return index;\n }\n else {\n return 0;\n }\n };\n /**\n * Registers `layer` at the page.\n * @private\n */\n PdfPageLayerCollection.prototype.addLayer = function (index, layer) {\n var reference = new PdfReferenceHolder(layer);\n this.page.contents.add(reference);\n };\n // private RemoveLayer(layer : PdfPageLayer) : void {\n // if (layer == null) {\n // throw new Error('ArgumentNullException:layer');\n // }\n // let reference : PdfReferenceHolder = new PdfReferenceHolder(layer);\n // if (this.page != null) {\n // this.page.Contents.Remove(reference);\n // }\n // }\n /**\n * Inserts `PdfPageLayer` into the collection at specified index.\n * @private\n */\n PdfPageLayerCollection.prototype.insert = function (index, layer) {\n // if (index < 0)\n // throw new ArgumentOutOfRangeException(\"index\", \"Value can not be less 0\");\n // if (layer == null)\n // throw new ArgumentNullException(\"layer\");\n // if (layer.Page != m_page)\n // throw new ArgumentException(\"The layer belongs to another page\");\n var list = [];\n var length = this.list.length;\n for (var i = index; i < length; i++) {\n list.push(this.list.pop());\n }\n this.list.push(layer);\n for (var i = 0; i < list.length; i++) {\n this.list.push(list[i]);\n }\n // Register layer.\n this.insertLayer(index, layer);\n };\n /**\n * Registers layer at the page.\n * @private\n */\n PdfPageLayerCollection.prototype.insertLayer = function (index, layer) {\n if (layer == null) {\n throw new Error('ArgumentNullException:layer');\n }\n var reference = new PdfReferenceHolder(layer);\n this.page.contents.insert(index, reference);\n };\n // tslint:disable\n /**\n * `Parses the layers`.\n * @private\n */\n PdfPageLayerCollection.prototype.parseLayers = function (loadedPage) {\n // if (loadedPage == null) {\n // throw new Error('ArgumentNullException:loadedPage');\n // }\n var contents = this.page.contents;\n var resource = this.page.getResources();\n var crossTable = null;\n var ocproperties = null;\n var propertie = null;\n var isLayerAdded = false;\n // if (loadedPage instanceof PdfPage) {\n crossTable = loadedPage.crossTable;\n // } else {\n // crossTable = (loadedPage as PdfLoadedPage).CrossTable;\n // Propertie = PdfCrossTable.Dereference(Resource[DictionaryProperties.Properties]) as PdfDictionary;\n // ocproperties = PdfCrossTable.Dereference((loadedPage as PdfLoadedPage).\n // Document.Catalog[DictionaryProperties.OCProperties]) as PdfDictionary;\n // }\n var saveStream = new PdfStream();\n var restoreStream = new PdfStream();\n var saveState = 'q';\n var newLine = '\\n';\n var restoreState = 'Q';\n // for (let index : number = 0; index < contents.Items.length; index++) {\n // let obj : IPdfPrimitive = contents[index];\n // let stream : PdfStream = crossTable.GetObject(obj) as PdfStream;\n // if (stream == null)\n // throw new PdfDocumentException(\"Invalid contents array.\");\n // // if (stream.Compress)\n // {\n // if (!loadedPage.Imported)\n // stream.Decompress();\n // }\n // byte[] contentId = stream.Data;\n // string str = PdfString.ByteToString(contentId);\n // if (!loadedPage.Imported && (contents.Count == 1) && ((stream.Data[stream.Data.Length - 2] ==\n // RestoreState) || (stream.Data[stream.Data.Length - 1] == RestoreState)))\n // {\n // byte[] content = stream.Data;\n // byte[] data = new byte[content.Length + 4];\n // data[0] = SaveState;\n // data[1] = NewLine;\n // content.CopyTo(data, 2);\n // data[data.Length - 2] = NewLine;\n // data[data.Length - 1] = RestoreState;\n // stream.Data = data;\n // }\n // if (ocproperties != null)\n // {\n // if (Propertie != null)\n // {\n // foreach (KeyValuePair prop in Propertie.Items)\n // {\n // String Key = prop.Key.ToString();\n // PdfReferenceHolder refh = prop.Value as PdfReferenceHolder;\n // PdfDictionary Dict = null;\n // if (refh != null)\n // {\n // Dict = refh.Object as PdfDictionary;\n // }\n // else\n // {\n // Dict = prop.Value as PdfDictionary;\n // }\n // PdfDictionary m_usage = PdfCrossTable.Dereference(Dict[DictionaryProperties.Usage]) as PdfDictionary;\n // if (m_usage != null)\n // {\n // if (str.Contains(Key))\n // {\n // PdfPageLayer layer = new PdfPageLayer(loadedPage, stream);\n // PdfDictionary printoption = PdfCrossTable.Dereference(m_usage[DictionaryProperties.Print])\n // as PdfDictionary;\n // if (printoption != null)\n // {\n // layer.m_printOption = printoption;\n // foreach (KeyValuePair value in printoption.Items)\n // {\n // if (value.Key.Value.Equals(DictionaryProperties.PrintState))\n // {\n // string printState = (value.Value as PdfName).Value;\n // if (printState.Equals(DictionaryProperties.OCGON))\n // {\n // layer.PrintState = PdfPrintState.AlwaysPrint;\n // break;\n // }\n // else\n // {\n // layer.PrintState = PdfPrintState.NeverPrint;\n // break;\n // }\n // }\n // }\n // }\n // PdfString layerName = PdfCrossTable.Dereference(Dict[DictionaryProperties.Name]) as PdfString;\n // layer.Name = layerName.Value;\n // List.add(layer);\n // isLayerAdded = true;\n // if(!str.Contains(\"EMC\"))\n // break;\n // }\n // }\n // else\n // {\n // if (str.Contains(Key))\n // {\n // PdfPageLayer layer = new PdfPageLayer(loadedPage, stream);\n // List.add(layer);\n // if(Dict.ContainsKey(DictionaryProperties.Name))\n // {\n // PdfString layerName = PdfCrossTable.Dereference(Dict[DictionaryProperties.Name]) as PdfString;\n // layer.Name = layerName.Value;\n // }\n // isLayerAdded = true;\n // break;\n // }\n // }\n // }\n // }\n // }\n // if (!isLayerAdded)\n // {\n // PdfPageLayer layer = new PdfPageLayer(loadedPage, stream);\n // List.add(layer);\n // }\n // else\n // isLayerAdded = false;\n // }\n var saveData = [];\n saveData.push(saveState);\n saveStream.data = saveData;\n contents.insert(0, new PdfReferenceHolder(saveStream));\n saveData = [];\n saveData.push(restoreState);\n restoreStream.data = saveData;\n contents.insert(contents.count, new PdfReferenceHolder(restoreStream));\n };\n /**\n * Returns `index of` the `PdfPageLayer` in the collection if exists, -1 otherwise.\n * @private\n */\n PdfPageLayerCollection.prototype.indexOf = function (layer) {\n if (layer == null) {\n throw new Error('ArgumentNullException: layer');\n }\n var index = this.list.indexOf(layer);\n return index;\n };\n return PdfPageLayerCollection;\n}(PdfCollection));\nexport { PdfPageLayerCollection };\n","/**\n * PdfTemplate.ts class for EJ2-PDF\n */\nimport { PdfStream } from './../../primitives/pdf-stream';\nimport { DictionaryProperties } from './../../input-output/pdf-dictionary-properties';\nimport { PdfArray } from './../../primitives/pdf-array';\nimport { PdfGraphics } from './../pdf-graphics';\nimport { PdfResources } from './../pdf-resources';\nimport { PdfName } from './../../primitives/pdf-name';\nimport { PointF, SizeF, RectangleF } from './../../drawing/pdf-drawing';\nimport { GetResourceEventHandler } from './../pdf-graphics';\n/**\n * Represents `Pdf Template` object.\n * @private\n */\nvar PdfTemplate = /** @class */ (function () {\n function PdfTemplate(arg1, arg2) {\n /**\n * Initialize an instance for `DictionaryProperties` class.\n * @private\n * @hidden\n */\n this.dictionaryProperties = new DictionaryProperties();\n /**\n * Checks whether the transformation 'is performed'.\n * @default true\n * @private\n */\n this.writeTransformation = true;\n if (typeof arg1 === 'undefined') {\n //\n }\n else if (arg1 instanceof SizeF && typeof arg2 === 'undefined') {\n this.content = new PdfStream();\n var tempSize = new SizeF(arg1.width, arg1.height);\n this.setSize(tempSize);\n this.initialize();\n }\n else {\n this.content = new PdfStream();\n this.setSize(new SizeF(arg1, arg2));\n this.initialize();\n }\n }\n Object.defineProperty(PdfTemplate.prototype, \"size\", {\n //Properties\n /**\n * Gets the size of the 'PdfTemplate'.\n */\n get: function () {\n return this.templateSize;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTemplate.prototype, \"width\", {\n /**\n * Gets the width of the 'PdfTemplate'.\n */\n get: function () {\n return this.size.width;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTemplate.prototype, \"height\", {\n /**\n * Gets the height of the 'PdfTemplate'.\n */\n get: function () {\n return this.size.height;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTemplate.prototype, \"graphics\", {\n /**\n * Gets the `graphics` of the 'PdfTemplate'.\n */\n get: function () {\n if (this.pdfGraphics == null || typeof this.pdfGraphics === 'undefined') {\n var gr = new GetResourceEventHandler(this);\n var g = new PdfGraphics(this.size, gr, this.content);\n this.pdfGraphics = g;\n // if(this.writeTransformation) {\n // Transform co-ordinates to Top/Left.\n this.pdfGraphics.initializeCoordinates();\n // }\n }\n return this.pdfGraphics;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the resources and modifies the template dictionary.\n * @private\n */\n PdfTemplate.prototype.getResources = function () {\n if (this.resources == null) {\n this.resources = new PdfResources();\n this.content.items.setValue(this.dictionaryProperties.resources, this.resources);\n }\n return this.resources;\n };\n // Public methods\n /**\n * `Initialize` the type and subtype of the template.\n * @private\n */\n PdfTemplate.prototype.initialize = function () {\n this.addType();\n this.addSubType();\n };\n /**\n * `Adds type key`.\n * @private\n */\n PdfTemplate.prototype.addType = function () {\n var value = new PdfName(this.dictionaryProperties.xObject);\n this.content.items.setValue(this.dictionaryProperties.type, value);\n };\n /**\n * `Adds SubType key`.\n * @private\n */\n PdfTemplate.prototype.addSubType = function () {\n var value = new PdfName(this.dictionaryProperties.form);\n this.content.items.setValue(this.dictionaryProperties.subtype, value);\n };\n PdfTemplate.prototype.reset = function (size) {\n if (typeof size === 'undefined') {\n if (this.resources != null) {\n this.resources = null;\n this.content.remove(this.dictionaryProperties.resources);\n }\n if (this.graphics != null) {\n this.graphics.reset(this.size);\n }\n }\n else {\n this.setSize(size);\n this.reset();\n }\n };\n /**\n * `Set the size` of the 'PdfTemplate'.\n * @private\n */\n PdfTemplate.prototype.setSize = function (size) {\n var rect = new RectangleF(new PointF(0, 0), size);\n var val = PdfArray.fromRectangle(rect);\n this.content.items.setValue(this.dictionaryProperties.bBox, val);\n this.templateSize = size;\n };\n Object.defineProperty(PdfTemplate.prototype, \"element\", {\n // /**\n // * Returns the value of current graphics.\n // * @private\n // */\n // public GetGraphics(g : PdfGraphics) : PdfGraphics {\n // if (this.graphics == null || typeof this.graphics === 'undefined') {\n // this.graphics = g;\n // this.graphics.Size = this.Size;\n // this.graphics.StreamWriter = new PdfStreamWriter(this.content)\n // this.graphics.Initialize();\n // if(this.writeTransformation) {\n // this.graphics.InitializeCoordinates();\n // }\n // }\n // return this.graphics;\n // }\n // IPdfWrapper Members\n /**\n * Gets the `content stream` of 'PdfTemplate' class.\n * @private\n */\n get: function () {\n return this.content;\n },\n enumerable: true,\n configurable: true\n });\n return PdfTemplate;\n}());\nexport { PdfTemplate };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfResources.ts class for EJ2-PDF\n */\nimport { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { TemporaryDictionary } from './../collections/object-object-pair/dictionary';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfArray } from './../primitives/pdf-array';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { PdfCrossTable } from './../input-output/pdf-cross-table';\nimport { PdfFont } from './fonts/pdf-font';\nimport { PdfTemplate } from './figures/pdf-template';\nimport { PdfBrush } from './brushes/pdf-brush';\nimport { PdfTransparency } from './pdf-transparency';\nimport { PdfBitmap } from './../graphics/images/pdf-bitmap';\nimport { PdfImage } from './../graphics/images/pdf-image';\n/**\n * `PdfResources` class used to set resource contents like font, image.\n * @private\n */\nvar PdfResources = /** @class */ (function (_super) {\n __extends(PdfResources, _super);\n function PdfResources(baseDictionary) {\n var _this = _super.call(this) || this;\n /**\n * Dictionary for the `properties names`.\n * @private\n */\n _this.properties = new PdfDictionary();\n if (baseDictionary instanceof PdfDictionary) {\n _this = _super.call(this, baseDictionary) || this;\n }\n return _this;\n }\n Object.defineProperty(PdfResources.prototype, \"names\", {\n //Properties\n /**\n * Gets the `font names`.\n * @private\n */\n get: function () {\n return this.getNames();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfResources.prototype, \"document\", {\n /**\n * Get or set the `page document`.\n * @private\n */\n get: function () {\n return this.pdfDocument;\n },\n set: function (value) {\n this.pdfDocument = value;\n },\n enumerable: true,\n configurable: true\n });\n //Public Methods\n /**\n * `Generates name` for the object and adds to the resource if the object is new.\n * @private\n */\n PdfResources.prototype.getName = function (obj) {\n var primitive = obj.element;\n var name = null;\n if (this.names.containsKey(primitive)) {\n name = this.names.getValue(primitive);\n }\n // Object is new.\n if (name == null) {\n var sName = this.generateName();\n name = new PdfName(sName);\n this.names.setValue(primitive, name);\n if (obj instanceof PdfFont) {\n this.add(obj, name);\n }\n else if (obj instanceof PdfTemplate) {\n this.add(obj, name);\n }\n else if (obj instanceof PdfTransparency) {\n this.add(obj, name);\n }\n else if (obj instanceof PdfImage || obj instanceof PdfBitmap) {\n this.add(obj, name);\n }\n }\n return name;\n };\n /**\n * Gets `resource names` to font dictionaries.\n * @private\n */\n PdfResources.prototype.getNames = function () {\n if (this.pdfNames == null) {\n this.pdfNames = new TemporaryDictionary();\n }\n var fonts = this.items.getValue(this.dictionaryProperties.font);\n if (fonts != null) {\n var reference = fonts;\n var dictionary = fonts;\n dictionary = PdfCrossTable.dereference(fonts);\n }\n return this.pdfNames;\n };\n /**\n * Add `RequireProcedureSet` into procset array.\n * @private\n */\n PdfResources.prototype.requireProcedureSet = function (procedureSetName) {\n if (procedureSetName == null) {\n throw new Error('ArgumentNullException:procedureSetName');\n }\n var procSets = this.items.getValue(this.dictionaryProperties.procset);\n if (procSets == null) {\n procSets = new PdfArray();\n this.items.setValue(this.dictionaryProperties.procset, procSets);\n }\n var name = new PdfName(procedureSetName);\n if (!procSets.contains(name)) {\n procSets.add(name);\n }\n };\n //Helper Methods\n /**\n * `Remove font` from array.\n * @private\n */\n PdfResources.prototype.removeFont = function (name) {\n var key = null;\n var keys = this.pdfNames.keys();\n for (var index = 0; index < this.pdfNames.size(); index++) {\n if (this.pdfNames.getValue(keys[index]) === new PdfName(name)) {\n key = keys[index];\n break;\n }\n }\n if (key != null) {\n this.pdfNames.remove(key);\n }\n };\n /**\n * Generates `Unique string name`.\n * @private\n */\n PdfResources.prototype.generateName = function () {\n var name = Guid.getNewGuidString();\n return name;\n };\n PdfResources.prototype.add = function (arg1, arg2) {\n if (arg1 instanceof PdfFont) {\n var dictionary = null;\n var fonts = this.items.getValue(this.dictionaryProperties.font);\n if (fonts != null) {\n var reference = fonts;\n dictionary = fonts;\n dictionary = fonts;\n }\n else {\n dictionary = new PdfDictionary();\n this.items.setValue(this.dictionaryProperties.font, dictionary);\n }\n dictionary.items.setValue(arg2.value, new PdfReferenceHolder(arg1.element));\n }\n else if (arg1 instanceof PdfTemplate) {\n var xobjects = void 0;\n xobjects = this.items.getValue(this.dictionaryProperties.xObject);\n // Create fonts dictionary.\n if (xobjects == null) {\n xobjects = new PdfDictionary();\n this.items.setValue(this.dictionaryProperties.xObject, xobjects);\n }\n xobjects.items.setValue(arg2.value, new PdfReferenceHolder(arg1.element));\n }\n else if (arg1 instanceof PdfBrush) {\n // let savable : IPdfPrimitive = (arg1 as IPdfWrapper).Element;\n // if (savable != null)\n // {\n // let pattern : PdfDictionary = this.Items.getValue(this.dictionaryProperties.pattern) as PdfDictionary;\n // // Create a new pattern dictionary.\n // if (pattern == null) {\n // pattern = new PdfDictionary();\n // this.Items.setValue(this.dictionaryProperties.pattern, pattern);\n // }\n // pattern.Items.setValue(name, new PdfReferenceHolder(savable));\n // }\n }\n else if (arg1 instanceof PdfTransparency) {\n var savable = arg1.element;\n var transDic = null;\n transDic = this.items.getValue(this.dictionaryProperties.extGState);\n // Create a new pattern dictionary.\n if (transDic == null) {\n transDic = new PdfDictionary();\n this.items.setValue(this.dictionaryProperties.extGState, transDic);\n }\n transDic.items.setValue(arg2.value, new PdfReferenceHolder(savable));\n }\n else {\n /* tslint:disable */\n var xobjects = this.Dictionary.items.getValue(this.dictionaryProperties.xObject);\n var parentXObjects = void 0;\n if (typeof this.pdfDocument !== 'undefined') {\n parentXObjects = this.pdfDocument.sections.element.items.getValue(this.dictionaryProperties.resources).items.getValue(this.dictionaryProperties.xObject);\n }\n var values = this.Dictionary.items.values();\n var hasSameImageStream = false;\n var oldReference = void 0;\n if (typeof this.pdfDocument !== 'undefined' && (typeof parentXObjects === undefined || parentXObjects == null)) {\n parentXObjects = new PdfDictionary();\n this.pdfDocument.sections.element.items.getValue(this.dictionaryProperties.resources).items.setValue(this.dictionaryProperties.xObject, parentXObjects);\n }\n else if (typeof this.pdfDocument !== 'undefined') {\n var values_1 = parentXObjects.items.values();\n for (var i = 0; i < values_1.length; i++) {\n if (typeof values_1[i] !== 'undefined' && typeof values_1[i].element !== 'undefined') {\n if (values_1[i].element.data[0] === arg1.element.data[0]) {\n oldReference = values_1[i];\n hasSameImageStream = true;\n }\n }\n }\n }\n if (xobjects == null) {\n xobjects = new PdfDictionary();\n this.Dictionary.items.setValue(this.dictionaryProperties.xObject, xobjects);\n }\n if (hasSameImageStream && typeof oldReference !== 'undefined') {\n xobjects.items.setValue(arg2.value, oldReference);\n }\n else {\n var reference = new PdfReferenceHolder(arg1.element);\n xobjects.items.setValue(arg2.value, reference);\n if (typeof this.pdfDocument !== 'undefined') {\n parentXObjects.items.setValue(arg2.value, reference);\n }\n }\n /* tslint:enable */\n }\n };\n return PdfResources;\n}(PdfDictionary));\nexport { PdfResources };\n/**\n * Used to create new guid for resources.\n * @private\n */\nvar Guid = /** @class */ (function () {\n /**\n * Initialize an `instance of GUID` class.\n * @private\n */\n function Guid(stringValue) {\n this.stringValue = stringValue || Guid.getNewGuidString();\n }\n Object.defineProperty(Guid, \"randomNumber\", {\n /**\n * Generate `Random number` for GUID.\n * @private\n */\n get: function () {\n Guid.guid = Guid.guid + 1;\n Guid.guid = Guid.guid > 999999999999 ? 0 : Guid.guid;\n return Guid.guid;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Return the value of `GUID as string`.\n * @private\n */\n Guid.prototype.toString = function () {\n return this.stringValue;\n };\n /**\n * Generate `new GUID`.\n * @private\n */\n Guid.getNewGuidString = function () {\n var guid = 'abc7def4-ghi9-jkl2-m6n3-';\n var temproaryString = 'opqrstuvwxyz';\n var randomString = Guid.randomNumber.toString();\n randomString = guid + temproaryString.substr(0, (12 - randomString.length)) + randomString;\n return randomString;\n };\n /**\n * static field to store `endding value of current GUID`.\n * @private\n */\n Guid.guid = 0;\n return Guid;\n}());\nexport { Guid };\n","import { PdfArray } from './../primitives/pdf-array';\nimport { PdfPageLayerCollection } from './pdf-page-layer-collection';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { PdfResources } from './../graphics/pdf-resources';\n/**\n * The abstract base class for all pages,\n * `PdfPageBase` class provides methods and properties to create PDF pages and its elements.\n * @private\n */\nvar PdfPageBase = /** @class */ (function () {\n //constructors\n /**\n * Initializes a new instance of the `PdfPageBase` class.\n * @private\n */\n function PdfPageBase(dictionary) {\n /**\n * `Index` of the default layer.\n * @default -1.\n * @private\n */\n this.defLayerIndex = -1;\n /**\n * Local variable to store if page `updated`.\n * @default false.\n * @private\n */\n this.modified = false;\n /**\n * Instance of `DictionaryProperties` class.\n * @hidden\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n this.pageDictionary = dictionary;\n }\n Object.defineProperty(PdfPageBase.prototype, \"section\", {\n //Properties\n /**\n * Gets the `section` of a page.\n * @private\n */\n get: function () {\n // if (this.pdfSection === null) {\n // throw new Error('PdfException : Page must be added to some section before using.');\n // }\n return this.pdfSection;\n },\n set: function (value) {\n this.pdfSection = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageBase.prototype, \"dictionary\", {\n /**\n * Gets the page `dictionary`.\n * @private\n */\n get: function () {\n return this.pageDictionary;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageBase.prototype, \"element\", {\n /**\n * Gets the wrapped `element`.\n * @private\n */\n get: function () {\n return this.pageDictionary;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageBase.prototype, \"defaultLayer\", {\n /**\n * Gets the `default layer` of the page (Read only).\n * @private\n */\n get: function () {\n var layer = this.layers;\n var index = this.defaultLayerIndex;\n var returnlayer = layer.items(index);\n return returnlayer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageBase.prototype, \"defaultLayerIndex\", {\n /**\n * Gets or sets `index of the default layer`.\n * @private\n */\n get: function () {\n if (this.layerCollection.count === 0 || this.defLayerIndex === -1) {\n var layer = this.layerCollection.add();\n this.defLayerIndex = this.layerCollection.indexOf(layer);\n }\n return this.defLayerIndex;\n },\n /**\n * Gets or sets` index of the default layer`.\n * @private\n */\n set: function (value) {\n if (value < 0 || value > this.layers.count - 1) {\n throw new Error('ArgumentOutOfRangeException : value, Index can not be less 0 and greater Layers.Count - 1');\n }\n else {\n this.defLayerIndex = value;\n this.modified = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageBase.prototype, \"layers\", {\n /**\n * Gets the collection of the page's `layers` (Read only).\n * @private\n */\n get: function () {\n if (this.layerCollection == null || typeof this.layerCollection === 'undefined') {\n this.layerCollection = new PdfPageLayerCollection(this);\n }\n return this.layerCollection;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Return an instance of `PdfResources` class.\n * @private\n */\n PdfPageBase.prototype.getResources = function () {\n if (this.resources == null) {\n this.resources = new PdfResources();\n this.dictionary.items.setValue(this.dictionaryProperties.resources, this.resources);\n }\n return this.resources;\n };\n Object.defineProperty(PdfPageBase.prototype, \"contents\", {\n /**\n * Gets `array of page's content`.\n * @private\n */\n get: function () {\n var obj = this.pageDictionary.items.getValue(this.dictionaryProperties.contents);\n var contents = obj;\n var rh = obj;\n if (contents == null) {\n contents = new PdfArray();\n this.pageDictionary.items.setValue(this.dictionaryProperties.contents, contents);\n }\n return contents;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Sets the `resources`.\n * @private\n */\n PdfPageBase.prototype.setResources = function (res) {\n this.resources = res;\n this.dictionary.items.setValue(this.dictionaryProperties.resources, this.resources);\n this.modified = true;\n };\n return PdfPageBase;\n}());\nexport { PdfPageBase };\n","import { PdfArray } from './../primitives/pdf-array';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { SizeF, RectangleF, PointF } from './../drawing/pdf-drawing';\nimport { PdfStringLayouter } from './../graphics/fonts/string-layouter';\nimport { PdfColorSpace } from './../graphics/enum';\n/**\n * `PdfAnnotationCollection` class represents the collection of 'PdfAnnotation' objects.\n * @private\n */\nvar PdfAnnotationCollection = /** @class */ (function () {\n function PdfAnnotationCollection(page) {\n // Constants\n /**\n * `Error` constant message.\n * @private\n */\n this.alreadyExistsAnnotationError = 'This annotatation had been already added to page';\n /**\n * `Error` constant message.\n * @private\n */\n this.missingAnnotationException = 'Annotation is not contained in collection.';\n /**\n * Specifies the Internal variable to store fields of `PdfDictionaryProperties`.\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n /**\n * Array of the `annotations`.\n * @private\n */\n this.internalAnnotations = new PdfArray();\n /**\n * privte `list` for the annotations.\n * @private\n */\n this.lists = [];\n if (typeof page !== 'undefined') {\n this.page = page;\n }\n }\n Object.defineProperty(PdfAnnotationCollection.prototype, \"annotations\", {\n /**\n * Gets the `PdfAnnotation` object at the specified index. Read-Only.\n * @private\n */\n get: function () {\n return this.internalAnnotations;\n },\n set: function (value) {\n this.internalAnnotations = value;\n },\n enumerable: true,\n configurable: true\n });\n // Public methods\n /**\n * `Adds` a new annotation to the collection.\n * @private\n */\n PdfAnnotationCollection.prototype.add = function (annotation) {\n // this.SetPrint(annotation);\n this.doAdd(annotation);\n };\n /**\n * `Adds` a Annotation to collection.\n * @private\n */\n /* tslint:disable */\n PdfAnnotationCollection.prototype.doAdd = function (annotation) {\n if (typeof annotation.destination !== 'undefined') {\n var layout = new PdfStringLayouter();\n var layoutResult = layout.layout(annotation.text, annotation.font, annotation.stringFormat, new SizeF((annotation.bounds.width), 0), false, new SizeF(0, 0));\n var lastPosition = annotation.bounds.y;\n if (layoutResult.lines.length === 1) {\n var size = annotation.font.measureString(layoutResult.lines[0].text);\n annotation.bounds = new RectangleF(new PointF(annotation.bounds.x, lastPosition), size);\n annotation.text = layoutResult.lines[0].text;\n //Draw Annotation Text.\n this.page.graphics.drawString(annotation.text, annotation.font, null, annotation.brush, annotation.bounds.x, annotation.bounds.y, annotation.bounds.width, annotation.bounds.height, null);\n //Add annotation to dictionary.\n annotation.setPage(this.page);\n this.setColor(annotation);\n this.internalAnnotations.add(new PdfReferenceHolder(annotation));\n this.lists.push(annotation);\n }\n else {\n for (var i = 0; i < layoutResult.lines.length; i++) {\n var size = annotation.font.measureString(layoutResult.lines[i].text);\n if (i === 0) {\n annotation.bounds = new RectangleF(annotation.bounds.x, lastPosition, size.width, size.height);\n annotation.text = layoutResult.lines[i].text;\n //Draw Annotation Text.\n this.page.graphics.drawString(annotation.text, annotation.font, null, annotation.brush, annotation.bounds.x, lastPosition, size.width, size.height, null);\n //Add annotation to dictionary.\n annotation.setPage(this.page);\n this.setColor(annotation);\n this.internalAnnotations.add(new PdfReferenceHolder(annotation));\n this.lists.push(annotation);\n //Update y for drawing next line of the text.\n lastPosition += annotation.bounds.height;\n }\n else {\n var annot = annotation.clone();\n annot.bounds = new RectangleF(new PointF(annotation.bounds.x, lastPosition), size);\n annot.text = layoutResult.lines[i].text;\n //Draw Annotation Text.\n this.page.graphics.drawString(annot.text, annot.font, null, annot.brush, annot.bounds.x, annot.bounds.y, annot.bounds.width, annot.bounds.height, null);\n //Add annotation to dictionary.\n annot.setPage(this.page);\n this.setColor(annot);\n this.internalAnnotations.add(new PdfReferenceHolder(annot));\n this.lists.push(annot);\n //Update y for drawing next line of the text.\n lastPosition += annot.bounds.height;\n }\n }\n }\n }\n else {\n annotation.setPage(this.page);\n this.internalAnnotations.add(new PdfReferenceHolder(annotation));\n return this.lists.push(annotation);\n }\n };\n /* tslint:enable */\n /**\n * `Set a color of an annotation`.\n * @private\n */\n PdfAnnotationCollection.prototype.setColor = function (annotation) {\n var cs = PdfColorSpace.Rgb;\n var colours = annotation.color.toArray(cs);\n annotation.dictionary.items.setValue(this.dictionaryProperties.c, colours);\n };\n Object.defineProperty(PdfAnnotationCollection.prototype, \"element\", {\n // IPdfWrapper Members\n /**\n * Gets the `Element` representing this object.\n * @private\n */\n get: function () {\n return this.internalAnnotations;\n },\n enumerable: true,\n configurable: true\n });\n return PdfAnnotationCollection;\n}());\nexport { PdfAnnotationCollection };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfPageBase } from './pdf-page-base';\nimport { PdfDictionary, SaveTemplateEventHandler } from './../primitives/pdf-dictionary';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { SizeF } from './../drawing/pdf-drawing';\nimport { PdfAnnotationCollection } from './../annotations/annotation-collection';\nimport { PdfPageLayer } from './pdf-page-layer';\n/**\n * Provides methods and properties to create pages and its elements.\n * `PdfPage` class inherited from the `PdfPageBase` class.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * //\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * //\n * // set the font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfPage = /** @class */ (function (_super) {\n __extends(PdfPage, _super);\n //constructors\n /**\n * Initialize the new instance for `PdfPage` class.\n * @private\n */\n function PdfPage() {\n var _this = _super.call(this, new PdfDictionary()) || this;\n /**\n * Stores the instance of `PdfAnnotationCollection` class.\n * @hidden\n * @default null\n * @private\n */\n _this.annotationCollection = null;\n /**\n * Stores the instance of `PageBeginSave` event for Page Number Field.\n * @default null\n * @private\n */\n _this.beginSave = null;\n _this.initialize();\n return _this;\n }\n Object.defineProperty(PdfPage.prototype, \"document\", {\n //Properties\n /**\n * Gets current `document`.\n * @private\n */\n get: function () {\n if (this.section !== null && this.section.parent !== null) {\n return this.section.parent.document;\n }\n else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPage.prototype, \"graphics\", {\n /**\n * Get the current `graphics`.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * //\n * // get graphics\n * let graphics : PdfGraphics = page1.graphics;\n * //\n * // set the font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n var result = this.defaultLayer.graphics;\n result.currentPage = this;\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPage.prototype, \"crossTable\", {\n /**\n * Gets the `cross table`.\n * @private\n */\n get: function () {\n if (this.section === null) {\n throw new Error('PdfDocumentException : Page is not created');\n }\n return this.section.parent === null ? this.section.parentDocument.crossTable : this.section.parent.document.crossTable;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPage.prototype, \"size\", {\n /**\n * Gets the size of the PDF page- Read only.\n * @public\n */\n get: function () {\n return this.section.pageSettings.size;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPage.prototype, \"origin\", {\n /**\n * Gets the `origin` of the page.\n * @private\n */\n get: function () {\n return this.section.pageSettings.origin;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPage.prototype, \"annotations\", {\n /**\n * Gets a collection of the `annotations` of the page- Read only.\n * @private\n */\n get: function () {\n if (this.annotationCollection == null) {\n this.annotationCollection = new PdfAnnotationCollection(this);\n // if (!this.Dictionary.ContainsKey(this.dictionaryProperties.annots)) {\n this.dictionary.items.setValue(this.dictionaryProperties.annots, this.annotationCollection.element);\n // }\n this.annotationCollection.annotations = this.dictionary.items.getValue(this.dictionaryProperties.annots);\n }\n return this.annotationCollection;\n },\n enumerable: true,\n configurable: true\n });\n //Implementation\n /**\n * `Initializes` a page.\n * @private\n */\n PdfPage.prototype.initialize = function () {\n this.dictionary.items.setValue(this.dictionaryProperties.type, new PdfName('Page'));\n this.dictionary.pageBeginDrawTemplate = new SaveTemplateEventHandler(this);\n };\n /**\n * Sets parent `section` to the page.\n * @private\n */\n PdfPage.prototype.setSection = function (section) {\n this.section = section;\n this.dictionary.items.setValue(this.dictionaryProperties.parent, new PdfReferenceHolder(section));\n };\n /**\n * `Resets the progress`.\n * @private\n */\n PdfPage.prototype.resetProgress = function () {\n this.isProgressOn = false;\n };\n /**\n * Get the page size reduced by page margins and page template dimensions.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // create new standard font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * //\n * // set the specified point using `getClientSize` method\n * let point : PointF = new PointF(page1.getClientSize().width - 200, page1.getClientSize().height - 200);\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, point);\n * //\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n PdfPage.prototype.getClientSize = function () {\n var returnValue = this.section.getActualBounds(this, true);\n return new SizeF(returnValue.width, returnValue.height);\n };\n /**\n * Helper method to retrive the instance of `PageBeginSave` event for header and footer elements.\n * @private\n */\n PdfPage.prototype.pageBeginSave = function () {\n var doc = this.document;\n if (typeof doc !== undefined && doc != null) {\n this.drawPageTemplates(doc);\n }\n if (this.beginSave != null && typeof this.beginSave !== 'undefined') {\n this.beginSave(this);\n }\n };\n /**\n * Helper method to draw template elements.\n * @private\n */\n PdfPage.prototype.drawPageTemplates = function (document) {\n // Draw Background templates.\n var hasBackTemplates = this.section.containsTemplates(document, this, false);\n if (hasBackTemplates) {\n var backLayer = new PdfPageLayer(this, false);\n this.layers.insert(0, backLayer);\n this.section.drawTemplates(this, backLayer, document, false);\n if (backLayer.graphics !== null && typeof backLayer.graphics !== 'undefined') {\n for (var i = 0; i < backLayer.graphics.automaticFields.automaticFields.length; i++) {\n var fieldInfo = backLayer.graphics.automaticFields.automaticFields[i];\n fieldInfo.field.performDraw(backLayer.graphics, fieldInfo.location, fieldInfo.scalingX, fieldInfo.scalingY);\n }\n }\n }\n // Draw Foreground templates.\n var hasFrontTemplates = this.section.containsTemplates(document, this, true);\n if (hasFrontTemplates) {\n var frontLayer = new PdfPageLayer(this, false);\n this.layers.add(frontLayer);\n this.section.drawTemplates(this, frontLayer, document, true);\n }\n };\n return PdfPage;\n}(PdfPageBase));\nexport { PdfPage };\n","/**\n * Provides data for `PageAddedEventHandler` event.\n * This event raises when adding the new PDF page to the PDF document.\n */\nvar PageAddedEventArgs = /** @class */ (function () {\n function PageAddedEventArgs(page) {\n if (typeof page !== 'undefined') {\n this.pdfPage = page;\n }\n else {\n this.pdfPage = null;\n }\n }\n Object.defineProperty(PageAddedEventArgs.prototype, \"page\", {\n /**\n * Gets the `newly added page`.\n * @private\n */\n get: function () {\n return this.pdfPage;\n },\n enumerable: true,\n configurable: true\n });\n return PageAddedEventArgs;\n}());\nexport { PageAddedEventArgs };\n","/**\n * Represents the `collection of pages in a section`.\n * @private\n */\nvar PdfSectionPageCollection = /** @class */ (function () {\n // Constructors\n /**\n * Initializes a new instance of the `PdfSectionPageCollection` class.\n * @private\n */\n function PdfSectionPageCollection(section) {\n // Fields\n /**\n * @hidden\n * @private\n */\n this.pdfSection = null;\n if (section == null) {\n throw Error('ArgumentNullException(\"section\")');\n }\n this.section = section;\n }\n Object.defineProperty(PdfSectionPageCollection.prototype, \"section\", {\n // Properties\n /**\n * Gets the `PdfPage` at the specified index.\n * @private\n */\n get: function () {\n return this.pdfSection;\n },\n set: function (value) {\n this.pdfSection = value;\n },\n enumerable: true,\n configurable: true\n });\n // Public Methods\n /**\n * `Determines` whether the specified page is within the collection.\n * @private\n */\n PdfSectionPageCollection.prototype.contains = function (page) {\n return this.section.contains(page);\n };\n /**\n * `Removes` the specified page from collection.\n * @private\n */\n PdfSectionPageCollection.prototype.remove = function (page) {\n this.section.remove(page);\n };\n /**\n * `Adds` a new page from collection.\n * @private\n */\n PdfSectionPageCollection.prototype.add = function () {\n return this.section.add();\n };\n return PdfSectionPageCollection;\n}());\nexport { PdfSectionPageCollection };\n","import { TemplateType } from './../pages/enum';\n// import { PdfStampCollection } from `./../Pages/PdfStampCollection`;\n/**\n * `PdfDocumentTemplate` class encapsulates a page template for all the pages in the document.\n * @private\n */\nvar PdfDocumentTemplate = /** @class */ (function () {\n // Constructors\n /**\n * Initializes a new instance of the `PdfDocumentTemplate` class.\n * @public\n */\n function PdfDocumentTemplate() {\n //\n }\n Object.defineProperty(PdfDocumentTemplate.prototype, \"left\", {\n // private m_stamps : PdfStampCollection;\n // Properties\n /**\n * `Left` page template object.\n * @public\n */\n get: function () {\n return this.leftTemplate;\n },\n set: function (value) {\n this.leftTemplate = this.checkElement(value, TemplateType.Left);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"top\", {\n /**\n * `Top` page template object.\n * @public\n */\n get: function () {\n return this.topTemplate;\n },\n set: function (value) {\n this.topTemplate = this.checkElement(value, TemplateType.Top);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"right\", {\n /**\n * `Right` page template object.\n * @public\n */\n get: function () {\n return this.rightTemplate;\n },\n set: function (value) {\n this.rightTemplate = this.checkElement(value, TemplateType.Right);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"bottom\", {\n /**\n * `Bottom` page template object.\n * @public\n */\n get: function () {\n return this.bottomTemplate;\n },\n set: function (value) {\n this.bottomTemplate = this.checkElement(value, TemplateType.Bottom);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"EvenLeft\", {\n /**\n * `EvenLeft` page template object.\n * @public\n */\n get: function () {\n return this.evenLeft;\n },\n set: function (value) {\n this.evenLeft = this.checkElement(value, TemplateType.Left);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"EvenTop\", {\n /**\n * `EvenTop` page template object.\n * @public\n */\n get: function () {\n return this.evenTop;\n },\n set: function (value) {\n this.evenTop = this.checkElement(value, TemplateType.Top);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"EvenRight\", {\n /**\n * `EvenRight` page template object.\n * @public\n */\n get: function () {\n return this.evenRight;\n },\n set: function (value) {\n this.evenRight = this.checkElement(value, TemplateType.Right);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"EvenBottom\", {\n /**\n * `EvenBottom` page template object.\n * @public\n */\n get: function () {\n return this.evenBottom;\n },\n set: function (value) {\n this.evenBottom = this.checkElement(value, TemplateType.Bottom);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"OddLeft\", {\n /**\n * `OddLeft` page template object.\n * @public\n */\n get: function () {\n return this.oddLeft;\n },\n set: function (value) {\n this.oddLeft = this.checkElement(value, TemplateType.Left);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"OddTop\", {\n /**\n * `OddTop` page template object.\n * @public\n */\n get: function () {\n return this.oddTop;\n },\n set: function (value) {\n this.oddTop = this.checkElement(value, TemplateType.Top);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"OddRight\", {\n /**\n * `OddRight` page template object.\n * @public\n */\n get: function () {\n return this.oddRight;\n },\n set: function (value) {\n this.oddRight = this.checkElement(value, TemplateType.Right);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentTemplate.prototype, \"OddBottom\", {\n /**\n * `OddBottom` page template object.\n * @public\n */\n get: function () {\n return this.oddBottom;\n },\n set: function (value) {\n this.oddBottom = this.checkElement(value, TemplateType.Bottom);\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * Returns `left` template.\n * @public\n */\n PdfDocumentTemplate.prototype.getLeft = function (page) {\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var template = null;\n // if (page.Document.Pages != null) {\n var even = this.isEven(page);\n if (even) {\n template = (this.EvenLeft != null) ? this.EvenLeft : this.left;\n }\n else {\n template = (this.OddLeft != null) ? this.OddLeft : this.left;\n }\n // }\n return template;\n };\n /**\n * Returns `top` template.\n * @public\n */\n PdfDocumentTemplate.prototype.getTop = function (page) {\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var template = null;\n // if (page.Document.Pages != null) {\n var even = this.isEven(page);\n if (even) {\n template = (this.EvenTop != null) ? this.EvenTop : this.top;\n }\n else {\n template = (this.OddTop != null) ? this.OddTop : this.top;\n }\n // }\n return template;\n };\n /**\n * Returns `right` template.\n * @public\n */\n PdfDocumentTemplate.prototype.getRight = function (page) {\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var template = null;\n // if (page.Document.Pages != null) {\n var even = this.isEven(page);\n if (even) {\n template = (this.EvenRight != null) ? this.EvenRight : this.right;\n }\n else {\n template = (this.OddRight != null) ? this.OddRight : this.right;\n }\n // }\n return template;\n };\n /**\n * Returns `bottom` template.\n * @public\n */\n PdfDocumentTemplate.prototype.getBottom = function (page) {\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var template = null;\n // if (page.Document.Pages != null) {\n var even = this.isEven(page);\n if (even) {\n template = (this.EvenBottom != null) ? this.EvenBottom : this.bottom;\n }\n else {\n template = (this.OddBottom != null) ? this.OddBottom : this.bottom;\n }\n // }\n return template;\n };\n /**\n * Checks whether the page `is even`.\n * @private\n */\n PdfDocumentTemplate.prototype.isEven = function (page) {\n var pages = page.section.document.pages;\n var index = 0;\n if (pages.pageCollectionIndex.containsKey(page)) {\n index = pages.pageCollectionIndex.getValue(page) + 1;\n }\n else {\n index = pages.indexOf(page) + 1;\n }\n var even = ((index % 2) === 0);\n return even;\n };\n /**\n * Checks a `template element`.\n * @private\n */\n PdfDocumentTemplate.prototype.checkElement = function (templateElement, type) {\n if (templateElement != null) {\n if ((typeof templateElement.type !== 'undefined') && (templateElement.type !== TemplateType.None)) {\n throw new Error('NotSupportedException:Can not reassign the template element. Please, create new one.');\n }\n templateElement.type = type;\n }\n return templateElement;\n };\n return PdfDocumentTemplate;\n}());\nexport { PdfDocumentTemplate };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfSectionTemplate.ts class for EJ2-PDF\n */\nimport { PdfDocumentTemplate } from './../document/pdf-document-template';\n/**\n * Represents a `page template` for all the pages in the section.\n */\nvar PdfSectionTemplate = /** @class */ (function (_super) {\n __extends(PdfSectionTemplate, _super);\n // Constructors\n /**\n * `Creates a new object`.\n * @private\n */\n function PdfSectionTemplate() {\n var _this = _super.call(this) || this;\n _this.leftValue = _this.topValue = _this.rightValue = _this.bottomValue = _this.stampValue = true;\n return _this;\n }\n Object.defineProperty(PdfSectionTemplate.prototype, \"applyDocumentLeftTemplate\", {\n // Properties\n /**\n * Gets or sets value indicating whether parent `Left page template should be used or not`.\n * @private\n */\n get: function () {\n return this.leftValue;\n },\n set: function (value) {\n this.leftValue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSectionTemplate.prototype, \"applyDocumentTopTemplate\", {\n /**\n * Gets or sets value indicating whether parent `Top page template should be used or not`.\n * @private\n */\n get: function () {\n return this.topValue;\n },\n set: function (value) {\n this.topValue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSectionTemplate.prototype, \"applyDocumentRightTemplate\", {\n /**\n * Gets or sets value indicating whether parent `Right page template should be used or not`.\n * @private\n */\n get: function () {\n return this.rightValue;\n },\n set: function (value) {\n this.rightValue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSectionTemplate.prototype, \"applyDocumentBottomTemplate\", {\n /**\n * Gets or sets value indicating whether parent `Bottom page template should be used or not`.\n * @private\n */\n get: function () {\n return this.bottomValue;\n },\n set: function (value) {\n this.bottomValue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSectionTemplate.prototype, \"applyDocumentStamps\", {\n /**\n * Gets or sets value indicating whether the `stamp value` is true or not.\n * @private\n */\n get: function () {\n return this.stampValue;\n },\n set: function (value) {\n this.stampValue = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfSectionTemplate;\n}(PdfDocumentTemplate));\nexport { PdfSectionTemplate };\n","import { PdfPage } from './pdf-page';\nimport { PageAddedEventArgs } from './page-added-event-arguments';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { PdfArray } from './../primitives/pdf-array';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfDictionary } from './../primitives/pdf-dictionary';\nimport { SaveSectionEventHandler } from './../primitives/pdf-dictionary';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { PdfSectionCollection } from './pdf-section-collection';\nimport { PdfSectionPageCollection } from './pdf-section-page-collection';\nimport { RectangleF } from './../drawing/pdf-drawing';\nimport { PdfSectionTemplate } from './pdf-section-templates';\n/**\n * Represents a `section` entity. A section it's a set of the pages with similar page settings.\n */\nvar PdfSection = /** @class */ (function () {\n function PdfSection(document, pageSettings) {\n //Fields\n //public PageAdded() : PageAddedEventArgs.PageAddedEventHandler = new PageAddedEventArgs.PageAddedEventHandler(Object,args)\n /**\n * @hidden\n * @private\n */\n this.pageAdded = new PageAddedEventArgs();\n /**\n * @hidden\n * @private\n */\n this.pdfPages = [];\n /**\n * @hidden\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n if (typeof pageSettings === 'undefined') {\n this.constructor(document, document.pageSettings);\n }\n else {\n this.pdfDocument = document;\n this.settings = pageSettings.clone();\n this.initialSettings = this.settings.clone();\n this.initialize();\n }\n }\n Object.defineProperty(PdfSection.prototype, \"parent\", {\n //Property\n /**\n * Gets or sets the `parent`.\n * @private\n */\n get: function () {\n return this.sectionCollection;\n },\n set: function (value) {\n this.sectionCollection = value;\n this.section.items.setValue(this.dictionaryProperties.parent, new PdfReferenceHolder(value));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSection.prototype, \"parentDocument\", {\n /**\n * Gets the `parent document`.\n * @private\n */\n get: function () {\n return this.pdfDocument;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSection.prototype, \"pageSettings\", {\n /**\n * Gets or sets the `page settings` of the section.\n * @private\n */\n get: function () {\n return this.settings;\n },\n set: function (value) {\n if (value != null) {\n this.settings = value;\n }\n else {\n throw Error('Value can not be null.');\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSection.prototype, \"element\", {\n /**\n * Gets the wrapped `element`.\n * @private\n */\n get: function () {\n return this.section;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSection.prototype, \"count\", {\n /**\n * Gets the `count` of the pages in the section.\n * @private\n */\n get: function () {\n return this.pagesReferences.count;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSection.prototype, \"template\", {\n /**\n * Gets or sets a `template` for the pages in the section.\n * @private\n */\n get: function () {\n if (this.pageTemplate == null) {\n this.pageTemplate = new PdfSectionTemplate();\n }\n return this.pageTemplate;\n },\n set: function (value) {\n this.pageTemplate = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSection.prototype, \"document\", {\n /**\n * Gets the `document`.\n * @private\n */\n get: function () {\n return this.sectionCollection.document;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSection.prototype, \"pages\", {\n /**\n * Gets the collection of `pages` in a section (Read only)\n * @private\n */\n get: function () {\n if (this.pagesCollection == null || typeof this.pagesCollection === 'undefined') {\n this.pagesCollection = new PdfSectionPageCollection(this);\n }\n return this.pagesCollection;\n },\n enumerable: true,\n configurable: true\n });\n //methods\n /**\n * `Return the page collection` of current section.\n * @private\n */\n PdfSection.prototype.getPages = function () {\n return this.pdfPages;\n };\n /**\n * `Translates` point into native coordinates of the page.\n * @private\n */\n PdfSection.prototype.pointToNativePdf = function (page, point) {\n var bounds = this.getActualBounds(page, true);\n point.x += bounds.x;\n point.y = this.pageSettings.height - (point.y);\n return point;\n };\n /**\n * Sets the page setting of the current section.\n * @public\n * @param settings Instance of `PdfPageSettings`\n */\n PdfSection.prototype.setPageSettings = function (settings) {\n this.settings = settings;\n this.state.orientation = settings.orientation;\n this.state.rotate = settings.rotate;\n this.state.size = settings.size;\n this.state.origin = settings.origin;\n };\n /**\n * `Initializes` the object.\n * @private\n */\n PdfSection.prototype.initialize = function () {\n this.pagesReferences = new PdfArray();\n this.section = new PdfDictionary();\n this.state = new PageSettingsState(this.pdfDocument);\n this.section.sectionBeginSave = new SaveSectionEventHandler(this, this.state);\n this.pageCount = new PdfNumber(0);\n this.section.items.setValue(this.dictionaryProperties.count, this.pageCount);\n this.section.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.pages));\n this.section.items.setValue(this.dictionaryProperties.kids, this.pagesReferences);\n };\n /**\n * Checks whether any template should be printed on this layer.\n * @private\n * @param document The parent document.\n * @param page The parent page.\n * @param foreground Layer z-order.\n * @returns True - if some content should be printed on the layer, False otherwise.\n */\n PdfSection.prototype.containsTemplates = function (document, page, foreground) {\n var documentHeaders = this.getDocumentTemplates(document, page, true, foreground);\n var documentTemplates = this.getDocumentTemplates(document, page, false, foreground);\n var contains = (documentHeaders.length > 0 || documentTemplates.length > 0);\n return contains;\n };\n /**\n * Returns array of the document templates.\n * @private\n * @param document The parent document.\n * @param page The parent page.\n * @param headers If true - return headers/footers, if false - return simple templates.\n * @param foreground If true - return foreground templates, if false - return background templates.\n * @returns Returns array of the document templates.\n */\n /* tslint:disable */\n PdfSection.prototype.getDocumentTemplates = function (document, page, headers, foreground) {\n var templates = [];\n if (headers) {\n if (this.template.applyDocumentTopTemplate && document.template.getTop(page) != null) {\n if ((!(document.template.getTop(page).foreground || foreground)) || (document.template.getTop(page).foreground && foreground)) {\n templates.push(document.template.getTop(page));\n }\n }\n if (this.template.applyDocumentBottomTemplate && document.template.getBottom(page) != null) {\n if ((!(document.template.getBottom(page).foreground || foreground)) || (document.template.getBottom(page).foreground && foreground)) {\n templates.push(document.template.getBottom(page));\n }\n }\n if (this.template.applyDocumentLeftTemplate && document.template.getLeft(page) != null) {\n if ((!(document.template.getLeft(page).foreground || foreground)) || (document.template.getLeft(page).foreground && foreground)) {\n templates.push(document.template.getLeft(page));\n }\n }\n if (this.template.applyDocumentRightTemplate && document.template.getRight(page) != null) {\n if ((!(document.template.getRight(page).foreground || foreground)) || (document.template.getRight(page).foreground && foreground)) {\n templates.push(document.template.getRight(page));\n }\n }\n }\n return templates;\n };\n /* tslint:enable */\n /**\n * `Adds` the specified page.\n * @private\n */\n PdfSection.prototype.add = function (page) {\n if (typeof page === 'undefined') {\n var page_1 = new PdfPage();\n this.add(page_1);\n return page_1;\n }\n else {\n var r = this.checkPresence(page);\n this.pdfPages.push(page);\n this.pagesReferences.add(r);\n page.setSection(this);\n page.resetProgress();\n this.pageAddedMethod(page);\n }\n };\n /**\n * `Checks the presence`.\n * @private\n */\n PdfSection.prototype.checkPresence = function (page) {\n var rh = new PdfReferenceHolder(page);\n var contains = false;\n var sc = this.parent;\n for (var index = 0; index < sc.section.length; index++) {\n var section = sc.section[index];\n contains = contains || section.contains(page);\n }\n return rh;\n };\n /**\n * `Determines` whether the page in within the section.\n * @private\n */\n PdfSection.prototype.contains = function (page) {\n var index = this.indexOf(page);\n return (0 <= index);\n };\n /**\n * Get the `index of` the page.\n * @private\n */\n PdfSection.prototype.indexOf = function (page) {\n for (var index = 0; index < this.pdfPages.length; index++) {\n if (this.pdfPages[index] === page) {\n return this.pdfPages.indexOf(page);\n }\n }\n var r = new PdfReferenceHolder(page);\n return this.pagesReferences.indexOf(r);\n };\n /**\n * Call two event's methods.\n * @hidden\n * @private\n */\n PdfSection.prototype.pageAddedMethod = function (page) {\n //Create event's arguments\n var args = new PageAddedEventArgs(page);\n this.onPageAdded(args);\n var parent = this.parent;\n parent.document.pages.onPageAdded(args);\n this.pageCount.intValue = this.count;\n };\n /**\n * Called when the page has been added.\n * @hidden\n * @private\n */\n PdfSection.prototype.onPageAdded = function (args) {\n //\n };\n PdfSection.prototype.getActualBounds = function (arg1, arg2, arg3) {\n if (arg1 instanceof PdfPage && typeof arg2 === 'boolean') {\n var result = void 0;\n var document_1 = this.parent.document;\n result = this.getActualBounds(document_1, arg1, arg2);\n return result;\n }\n else {\n arg1 = arg1;\n arg2 = arg2;\n arg3 = arg3;\n var bounds = new RectangleF(0, 0, 0, 0);\n bounds.height = (arg3) ? this.pageSettings.size.height : this.pageSettings.getActualSize().height;\n bounds.width = (arg3) ? this.pageSettings.size.width : this.pageSettings.getActualSize().width;\n var left = this.getLeftIndentWidth(arg1, arg2, arg3);\n var top_1 = this.getTopIndentHeight(arg1, arg2, arg3);\n var right = this.getRightIndentWidth(arg1, arg2, arg3);\n var bottom = this.getBottomIndentHeight(arg1, arg2, arg3);\n bounds.x += left;\n bounds.y += top_1;\n bounds.width -= (left + right);\n bounds.height -= (top_1 + bottom);\n return bounds;\n }\n };\n /**\n * Calculates width of the `left indent`.\n * @private\n */\n PdfSection.prototype.getLeftIndentWidth = function (document, page, includeMargins) {\n if (document == null) {\n throw new Error('ArgumentNullException:document');\n }\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var value = (includeMargins) ? this.pageSettings.margins.left : 0;\n var templateWidth = (this.template.getLeft(page) != null) ? this.template.getLeft(page).width : 0;\n var docTemplateWidth = (document.template.getLeft(page) != null) ? document.template.getLeft(page).width : 0;\n value += (this.template.applyDocumentLeftTemplate) ? Math.max(templateWidth, docTemplateWidth) : templateWidth;\n return value;\n };\n /**\n * Calculates `Height` of the top indent.\n * @private\n */\n PdfSection.prototype.getTopIndentHeight = function (document, page, includeMargins) {\n if (document == null) {\n throw new Error('ArgumentNullException:document');\n }\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var value = (includeMargins) ? this.pageSettings.margins.top : 0;\n var templateHeight = (this.template.getTop(page) != null) ? this.template.getTop(page).height : 0;\n var docTemplateHeight = (document.template.getTop(page) != null) ? document.template.getTop(page).height : 0;\n value += (this.template.applyDocumentTopTemplate) ? Math.max(templateHeight, docTemplateHeight) : templateHeight;\n return value;\n };\n /**\n * Calculates `width` of the right indent.\n * @private\n */\n PdfSection.prototype.getRightIndentWidth = function (document, page, includeMargins) {\n if (document == null) {\n throw new Error('ArgumentNullException:document');\n }\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var value = (includeMargins) ? this.pageSettings.margins.right : 0;\n var templateWidth = (this.template.getRight(page) != null) ? this.template.getRight(page).width : 0;\n var docTemplateWidth = (document.template.getRight(page) != null) ? document.template.getRight(page).width : 0;\n value += (this.template.applyDocumentRightTemplate) ? Math.max(templateWidth, docTemplateWidth) : templateWidth;\n return value;\n };\n /**\n * Calculates `Height` of the bottom indent.\n * @private\n */\n PdfSection.prototype.getBottomIndentHeight = function (document, page, includeMargins) {\n if (document == null) {\n throw new Error('ArgumentNullException:document');\n }\n if (page == null) {\n throw new Error('ArgumentNullException:page');\n }\n var value = (includeMargins) ? this.pageSettings.margins.bottom : 0;\n var templateHeight = (this.template.getBottom(page) != null) ? this.template.getBottom(page).height : 0;\n var docTemplateHeight = (document.template.getBottom(page) != null) ? document.template.getBottom(page).height : 0;\n value += (this.template.applyDocumentBottomTemplate) ? Math.max(templateHeight, docTemplateHeight) : templateHeight;\n return value;\n };\n /**\n * `Removes` the page from the section.\n * @private\n */\n PdfSection.prototype.remove = function (page) {\n if (page == null) {\n throw Error('ArgumentNullException(\"page\")');\n }\n var index = this.pdfPages.indexOf(page);\n this.pagesReferences.removeAt(index);\n var temproaryPages = [];\n for (var j = 0; j < index; j++) {\n temproaryPages.push(this.pdfPages[j]);\n }\n for (var j = index + 1; j < this.pdfPages.length; j++) {\n temproaryPages.push(this.pdfPages[j]);\n }\n this.pdfPages = temproaryPages;\n };\n /**\n * In fills dictionary by the data from `Page settings`.\n * @private\n */\n PdfSection.prototype.applyPageSettings = function (container, parentSettings, state) {\n var bounds = new RectangleF(state.origin, state.size);\n container.items.setValue(this.dictionaryProperties.mediaBox, PdfArray.fromRectangle(bounds));\n var rotate = 0;\n rotate = PdfSectionCollection.rotateFactor * state.rotate;\n var angle = new PdfNumber(rotate);\n container.items.setValue(this.dictionaryProperties.rotate, angle);\n };\n /**\n * Catches the Save event of the dictionary.\n * @hidden\n * @private\n */\n PdfSection.prototype.beginSave = function (state, writer) {\n var doc = writer.document;\n this.applyPageSettings(this.section, doc.pageSettings, state);\n };\n /**\n * Draws page templates on the page.\n * @private\n */\n PdfSection.prototype.drawTemplates = function (page, layer, document, foreground) {\n var documentHeaders = this.getDocumentTemplates(document, page, true, foreground);\n var documentTemplates = this.getDocumentTemplates(document, page, false, foreground);\n if (foreground) {\n this.drawTemplatesHelper(layer, document, documentHeaders);\n this.drawTemplatesHelper(layer, document, documentTemplates);\n }\n else {\n this.drawTemplatesHelper(layer, document, documentHeaders);\n this.drawTemplatesHelper(layer, document, documentTemplates);\n }\n };\n /**\n * Draws page templates on the page.\n * @private\n */\n PdfSection.prototype.drawTemplatesHelper = function (layer, document, templates) {\n if (templates != null && templates.length > 0) {\n var len = templates.length;\n for (var i = 0; i < len; i++) {\n var template = templates[i];\n template.draw(layer, document);\n }\n }\n };\n return PdfSection;\n}());\nexport { PdfSection };\nvar PageSettingsState = /** @class */ (function () {\n //Public Constructor\n /**\n * New instance to store the `PageSettings`.\n * @private\n */\n function PageSettingsState(document) {\n this.pageOrientation = document.pageSettings.orientation;\n this.pageRotate = document.pageSettings.rotate;\n this.pageSize = document.pageSettings.size;\n this.pageOrigin = document.pageSettings.origin;\n }\n Object.defineProperty(PageSettingsState.prototype, \"orientation\", {\n //public Properties\n /**\n * @hidden\n * @private\n */\n get: function () {\n return this.pageOrientation;\n },\n set: function (value) {\n this.pageOrientation = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PageSettingsState.prototype, \"rotate\", {\n /**\n * @hidden\n * @private\n */\n get: function () {\n return this.pageRotate;\n },\n set: function (value) {\n this.pageRotate = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PageSettingsState.prototype, \"size\", {\n /**\n * @hidden\n * @private\n */\n get: function () {\n return this.pageSize;\n },\n set: function (value) {\n this.pageSize = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PageSettingsState.prototype, \"origin\", {\n /**\n * @hidden\n * @private\n */\n get: function () {\n return this.pageOrigin;\n },\n set: function (value) {\n this.pageOrigin = value;\n },\n enumerable: true,\n configurable: true\n });\n return PageSettingsState;\n}());\nexport { PageSettingsState };\n","import { PdfNumber } from './../primitives/pdf-number';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfArray } from './../primitives/pdf-array';\nimport { PdfDictionary, SaveSectionCollectionEventHandler } from './../primitives/pdf-dictionary';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { RectangleF, PointF } from './../drawing/pdf-drawing';\nimport { PdfSection } from './pdf-section';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\n/**\n * Represents the `collection of the sections`.\n * @private\n */\nvar PdfSectionCollection = /** @class */ (function () {\n //constructor\n /**\n * Initializes a new instance of the `PdfSectionCollection` class.\n * @private\n */\n function PdfSectionCollection(document) {\n /**\n * @hidden\n * @private\n */\n this.sections = [];\n /**\n * @hidden\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n // if (document === null) {\n // throw new Error('ArgumentNullException : document');\n // }\n this.pdfDocument = document.clone();\n this.initialize();\n }\n Object.defineProperty(PdfSectionCollection.prototype, \"section\", {\n //Properties\n /**\n * Gets the `Section` collection.\n */\n get: function () {\n return this.sections;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSectionCollection.prototype, \"document\", {\n /**\n * Gets a parent `document`.\n * @private\n */\n get: function () {\n return this.pdfDocument;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSectionCollection.prototype, \"count\", {\n /**\n * Gets the `number of sections` in a document.\n * @private\n */\n get: function () {\n return this.sections.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfSectionCollection.prototype, \"element\", {\n /**\n * Gets the wrapped `element`.\n * @private\n */\n get: function () {\n return this.pages;\n },\n enumerable: true,\n configurable: true\n });\n //Methods\n /**\n * `Initializes the object`.\n * @private\n */\n PdfSectionCollection.prototype.initialize = function () {\n this.sectionCount = new PdfNumber(0);\n this.sectionCollection = new PdfArray();\n this.pages = new PdfDictionary();\n this.pages.beginSave = new SaveSectionCollectionEventHandler(this);\n this.pages.items.setValue(this.dictionaryProperties.type, new PdfName('Pages'));\n this.pages.items.setValue(this.dictionaryProperties.kids, this.sectionCollection);\n this.pages.items.setValue(this.dictionaryProperties.count, this.sectionCount);\n this.pages.items.setValue(this.dictionaryProperties.resources, new PdfDictionary());\n this.setPageSettings(this.pages, this.pdfDocument.pageSettings);\n };\n /**\n * Initializes a new instance of the `PdfSectionCollection` class.\n * @private\n */\n PdfSectionCollection.prototype.pdfSectionCollection = function (index) {\n if (index < 0 || index >= this.count) {\n throw new Error('IndexOutOfRangeException()');\n }\n return this.sections[index];\n };\n /**\n * In fills dictionary by the data from `Page settings`.\n * @private\n */\n PdfSectionCollection.prototype.setPageSettings = function (container, pageSettings) {\n // if (container === null) {\n // throw new Error('ArgumentNullException : container');\n // }\n // if (pageSettings === null) {\n // throw new Error('ArgumentNullException : pageSettings');\n // }\n var bounds = new RectangleF(new PointF(), pageSettings.size);\n container.items.setValue(this.dictionaryProperties.mediaBox, PdfArray.fromRectangle(bounds));\n };\n /**\n * `Adds` the specified section.\n * @private\n */\n PdfSectionCollection.prototype.add = function (section) {\n if (typeof section === 'undefined') {\n var section_1 = new PdfSection(this.pdfDocument);\n this.add(section_1);\n return section_1;\n }\n else {\n // if (section === null) {\n // throw new Error('ArgumentNullException : section');\n // }\n var r = this.checkSection(section);\n this.sections.push(section);\n section.parent = this;\n this.sectionCollection.add(r);\n return this.sections.indexOf(section);\n }\n };\n /**\n * `Checks` if the section is within the collection.\n * @private\n */\n PdfSectionCollection.prototype.checkSection = function (section) {\n var r = new PdfReferenceHolder(section);\n var contains = this.sectionCollection.contains(r);\n // if (contains) {\n // throw new Error('ArgumentException : The object can not be added twice to the collection,section');\n // }\n return r;\n };\n /**\n * Catches the Save event of the dictionary to `count the pages`.\n * @private\n */\n PdfSectionCollection.prototype.countPages = function () {\n var count = 0;\n this.sections.forEach(function (n) { return (count += n.count); });\n return count;\n };\n /**\n * Catches the Save event of the dictionary to `count the pages`.\n * @hidden\n * @private\n */\n PdfSectionCollection.prototype.beginSave = function () {\n this.sectionCount.intValue = this.countPages();\n };\n //Fields\n /**\n * Rotate factor for page `rotation`.\n * @default 90\n * @private\n */\n PdfSectionCollection.rotateFactor = 90;\n return PdfSectionCollection;\n}());\nexport { PdfSectionCollection };\n","import { PdfPage } from './pdf-page';\nimport { Dictionary } from './../collections/dictionary';\nimport { PdfPageOrientation } from './enum';\n/**\n * Represents a virtual collection of all the pages in the document.\n * @private\n */\nvar PdfDocumentPageCollection = /** @class */ (function () {\n //constructor\n /**\n * Initializes a new instance of the `PdfPageCollection` class.\n * @private\n */\n function PdfDocumentPageCollection(document) {\n /**\n * It holds the page collection with the `index`.\n * @private\n */\n this.pdfPageCollectionIndex = new Dictionary();\n /**\n * Stores the previous pages's `orientation`.\n * @default PdfPageOrientation.Portrait\n * @private\n */\n this.previousPageOrientation = PdfPageOrientation.Portrait;\n this.document = document;\n }\n Object.defineProperty(PdfDocumentPageCollection.prototype, \"count\", {\n //Property\n /**\n * Gets the total `number of the pages`.\n * @private\n */\n get: function () {\n return this.countPages();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocumentPageCollection.prototype, \"pageCollectionIndex\", {\n /**\n * Gets a `page index` from the document.\n * @private\n */\n get: function () {\n return this.pdfPageCollectionIndex;\n },\n enumerable: true,\n configurable: true\n });\n PdfDocumentPageCollection.prototype.add = function (page) {\n if (typeof page === 'undefined') {\n var page_1 = new PdfPage();\n this.add(page_1);\n return page_1;\n }\n else {\n var section = this.getLastSection();\n if (section.pageSettings.orientation !== this.previousPageOrientation) {\n section = this.document.sections.add();\n section.pageSettings.orientation = this.document.pageSettings.orientation;\n }\n section.add(page);\n }\n };\n /**\n * Returns `last section` in the document.\n * @private\n */\n PdfDocumentPageCollection.prototype.getLastSection = function () {\n var sc = this.document.sections;\n if (sc.section.length === 0) {\n sc.add();\n }\n var section = sc.section[sc.section.length - 1];\n return section;\n };\n /**\n * Called when `new page has been added`.\n * @private\n */\n PdfDocumentPageCollection.prototype.onPageAdded = function (args) {\n // if (PageAdded !== null)\n // {\n // PageAdded(this, args);\n // }\n };\n /**\n * Gets the `total number of pages`.\n * @private\n */\n PdfDocumentPageCollection.prototype.countPages = function () {\n var sc = this.document.sections;\n var count = 0;\n for (var index = 0; index < sc.section.length; index++) {\n count += sc.section[index].count;\n }\n return count;\n };\n /**\n * Gets the `page object` from page index.\n * @private\n */\n PdfDocumentPageCollection.prototype.getPageByIndex = function (index) {\n return this.getPage(index);\n };\n /**\n * Gets a page by its `index` in the document.\n * @private\n */\n PdfDocumentPageCollection.prototype.getPage = function (index) {\n if ((index < 0) || (index >= this.count)) {\n throw Error('ArgumentOutOfRangeException(\"index\", \"Value can not be less 0\")');\n }\n var page = null;\n var sectionStartIndex = 0;\n var sectionCount = 0;\n var pageIndex = 0;\n var length = this.document.sections.count;\n for (var i = 0; i < length; i++) {\n var section = this.document.sections.section[i];\n sectionCount = section.count;\n pageIndex = index - sectionStartIndex;\n // We found a section containing the page.\n if ((index >= sectionStartIndex && pageIndex < sectionCount)) {\n page = section.getPages()[pageIndex];\n break;\n }\n sectionStartIndex += sectionCount;\n }\n return page;\n };\n /**\n * Gets the `index of` the page in the document.\n * @private\n */\n PdfDocumentPageCollection.prototype.indexOf = function (page) {\n var index = -1;\n if (page == null) {\n throw new Error('ArgumentNullException: page');\n }\n else {\n var numPages = 0;\n for (var i = 0, len = this.document.sections.count; i < len; i++) {\n var section = this.document.sections.pdfSectionCollection(i);\n index = section.indexOf(page);\n if (index >= 0) {\n index += numPages;\n break;\n }\n else {\n index = -1;\n }\n numPages += section.count;\n }\n }\n return index;\n };\n /**\n * `Removes` the specified page.\n * @private\n */\n PdfDocumentPageCollection.prototype.remove = function (page) {\n if (page == null) {\n throw Error('ArgumentNullException(\"page\")');\n }\n var section = null;\n var len;\n for (var i = 0, len_1 = this.document.sections.count; i < len_1; i++) {\n section = this.document.sections.pdfSectionCollection(i);\n if (section.pages.contains(page)) {\n section.pages.remove(page);\n break;\n }\n }\n return section;\n };\n return PdfDocumentPageCollection;\n}());\nexport { PdfDocumentPageCollection };\n","/**\n * PdfCacheCollection.ts class for EJ2-PDF\n */\nimport { Dictionary } from './../collections/dictionary';\n/**\n * `Collection of the cached objects`.\n * @private\n */\nvar PdfCacheCollection = /** @class */ (function () {\n // Constructors\n /**\n * Initializes a new instance of the `PdfCacheCollection` class.\n * @private\n */\n function PdfCacheCollection() {\n this.referenceObjects = [];\n this.pdfFontCollection = new Dictionary();\n }\n // Public methods\n /**\n * `Searches` for the similar cached object. If is not found - adds the object to the cache.\n * @private\n */\n PdfCacheCollection.prototype.search = function (obj) {\n var result = null;\n var group = this.getGroup(obj);\n if (group == null) {\n group = this.createNewGroup();\n }\n else if (group.length > 0) {\n result = group[0];\n }\n group.push(obj);\n return result;\n };\n // Implementation\n /**\n * `Creates` a new group.\n * @private\n */\n PdfCacheCollection.prototype.createNewGroup = function () {\n var group = [];\n this.referenceObjects.push(group);\n return group;\n };\n PdfCacheCollection.prototype.destroy = function () {\n this.pdfFontCollection = undefined;\n this.referenceObjects = undefined;\n };\n /**\n * `Find and Return` a group.\n * @private\n */\n PdfCacheCollection.prototype.getGroup = function (result) {\n var group = null;\n if (result !== null) {\n var len = this.referenceObjects.length;\n for (var i = 0; i < len; i++) {\n if (this.referenceObjects.length > 0) {\n var tGroup = this.referenceObjects[i];\n if (tGroup.length > 0) {\n var representative = tGroup[0];\n if (result.equalsTo(representative)) {\n group = tGroup;\n break;\n }\n }\n else {\n this.removeGroup(tGroup);\n }\n }\n len = this.referenceObjects.length;\n }\n }\n return group;\n };\n /**\n * Remove a group from the storage.\n */\n PdfCacheCollection.prototype.removeGroup = function (group) {\n if (group !== null) {\n var index = this.referenceObjects.indexOf(group);\n this.referenceObjects.slice(index, index + 1);\n }\n };\n return PdfCacheCollection;\n}());\nexport { PdfCacheCollection };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfWriter } from './../input-output/pdf-writer';\nimport { PdfMainObjectCollection } from './../input-output/pdf-main-object-collection';\nimport { PdfDocumentBase } from './pdf-document-base';\nimport { PdfCrossTable } from './../input-output/pdf-cross-table';\nimport { PdfCatalog } from './pdf-catalog';\nimport { PdfPageSettings } from './../pages/pdf-page-settings';\nimport { PdfSectionCollection } from './../pages/pdf-section-collection';\nimport { PdfDocumentPageCollection } from './../pages/pdf-document-page-collection';\nimport { PdfCacheCollection } from './../general/pdf-cache-collection';\nimport { PdfColorSpace } from './../graphics/enum';\nimport { PdfDocumentTemplate } from './pdf-document-template';\nimport { PdfFontFamily } from './../graphics/fonts/enum';\nimport { PdfStandardFont } from './../graphics/fonts/pdf-standard-font';\n/**\n * Represents a PDF document and can be used to create a new PDF document from the scratch.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * // set the font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfDocument = /** @class */ (function (_super) {\n __extends(PdfDocument, _super);\n function PdfDocument(isMerging) {\n var _this = _super.call(this) || this;\n /**\n * Default `margin` value.\n * @default 40.0\n * @private\n */\n _this.defaultMargin = 40.0;\n /**\n * Internal variable to store instance of `StreamWriter` classes..\n * @default null\n * @private\n */\n _this.streamWriter = null;\n _this = _super.call(this, _this) || this;\n if (isMerging === true || isMerging === false || typeof isMerging !== 'undefined') {\n var objects = new PdfMainObjectCollection();\n _this.setMainObjectCollection(objects);\n var crossTable = new PdfCrossTable();\n crossTable.isMerging = isMerging;\n crossTable.document = _this;\n _this.setCrossTable(crossTable);\n var catalog = new PdfCatalog();\n _this.setCatalog(catalog);\n objects.add(catalog);\n catalog.position = -1;\n _this.sectionCollection = new PdfSectionCollection(_this);\n _this.documentPageCollection = new PdfDocumentPageCollection(_this);\n catalog.pages = _this.sectionCollection;\n }\n else {\n PdfDocument.cacheCollection = new PdfCacheCollection();\n _this.constructor(false);\n }\n return _this;\n }\n Object.defineProperty(PdfDocument, \"defaultFont\", {\n //Properties\n /**\n * Gets the `default font`. It is used for complex objects when font is not explicitly defined.\n * @private\n */\n get: function () {\n if (this.defaultStandardFont == null) {\n this.defaultStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 8);\n }\n return this.defaultStandardFont;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocument.prototype, \"sections\", {\n /**\n * Gets the collection of the `sections` in the document.\n * @private\n */\n get: function () {\n return this.sectionCollection;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocument.prototype, \"pageSettings\", {\n /**\n * Gets the document's page setting.\n * @public\n */\n get: function () {\n if (this.settings == null) {\n this.settings = new PdfPageSettings(this.defaultMargin);\n }\n return this.settings;\n },\n /**\n * Sets the document's page setting.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n *\n * // sets the right margin of the page\n * document.pageSettings.margins.right = 0;\n * // set the page size.\n * document.pageSettings.size = new SizeF(500, 500);\n * // change the page orientation to landscape\n * document.pageSettings.orientation = PdfPageOrientation.Landscape;\n * // apply 90 degree rotation on the page\n * document.pageSettings.rotate = PdfPageRotateAngle.RotateAngle90;\n *\n * // add a pages to the document\n * let page1 : PdfPage = document.pages.add();\n * // set font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // set brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // set the specified Point\n * let point : PointF = new PointF(page1.getClientSize().width - 200, page1.getClientSize().height - 200);\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, point);\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n set: function (value) {\n this.settings = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocument.prototype, \"pages\", {\n /**\n * Represents the collection of pages in the PDF document.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * //\n * // get the collection of pages in the document\n * let pageCollection : PdfDocumentPageCollection = document.pages;\n * //\n * // add pages\n * let page1 : PdfPage = pageCollection.add();\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n return this.documentPageCollection;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocument, \"cache\", {\n /**\n * Gets collection of the `cached objects`.\n * @private\n */\n get: function () {\n if (typeof PdfDocument.cacheCollection === 'undefined' || PdfDocument.cacheCollection == null) {\n return new PdfCacheCollection();\n }\n return PdfDocument.cacheCollection;\n },\n /**\n * Sets collection of the `cached objects`.\n * @private\n */\n set: function (value) {\n this.cacheCollection = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocument, \"enableCache\", {\n /**\n * Gets the value of enable cache.\n * @private\n */\n get: function () {\n return this.isCacheEnabled;\n },\n /**\n * Sets thie value of enable cache.\n * @private\n */\n set: function (value) {\n this.isCacheEnabled = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocument.prototype, \"colorSpace\", {\n /* tslint:disable */\n /**\n * Gets or sets the `color space` of the document. This property can be used to create PDF document in RGB, Gray scale or CMYK color spaces.\n * @private\n */\n get: function () {\n if ((this.pdfColorSpace === PdfColorSpace.Rgb) || ((this.pdfColorSpace === PdfColorSpace.Cmyk)\n || (this.pdfColorSpace === PdfColorSpace.GrayScale))) {\n return this.pdfColorSpace;\n }\n else {\n return PdfColorSpace.Rgb;\n }\n },\n set: function (value) {\n if ((value === PdfColorSpace.Rgb) || ((value === PdfColorSpace.Cmyk) ||\n (value === PdfColorSpace.GrayScale))) {\n this.pdfColorSpace = value;\n }\n else {\n this.pdfColorSpace = PdfColorSpace.Rgb;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDocument.prototype, \"template\", {\n /* tslint:enable */\n /**\n * Gets or sets a `template` to all pages in the document.\n * @private\n */\n get: function () {\n if (this.pageTemplate == null) {\n this.pageTemplate = new PdfDocumentTemplate();\n }\n return this.pageTemplate;\n },\n set: function (value) {\n this.pageTemplate = value;\n },\n enumerable: true,\n configurable: true\n });\n PdfDocument.prototype.docSave = function (stream, arg2, arg3) {\n this.checkPagesPresence();\n if (stream === null) {\n throw new Error('ArgumentNullException : stream');\n }\n this.streamWriter = stream;\n var writer = new PdfWriter(stream);\n writer.document = this;\n if (typeof arg2 === 'boolean' && typeof arg3 === 'undefined') {\n return this.crossTable.save(writer);\n }\n else {\n this.crossTable.save(writer, arg2);\n }\n };\n /**\n * Checks the pages `presence`.\n * @private\n */\n PdfDocument.prototype.checkPagesPresence = function () {\n if (this.pages.count === 0) {\n this.pages.add();\n }\n };\n /**\n * disposes the current instance of `PdfDocument` class.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * // set the font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n PdfDocument.prototype.destroy = function () {\n this.catalog = undefined;\n this.colorSpace = undefined;\n this.currentSavingObj = undefined;\n this.documentPageCollection = undefined;\n this.isStreamCopied = undefined;\n this.pageSettings = undefined;\n this.pageTemplate = undefined;\n this.pdfColorSpace = undefined;\n this.sectionCollection = undefined;\n PdfDocument.cache.destroy();\n this.crossTable.pdfObjects.destroy();\n PdfDocument.cache = undefined;\n this.streamWriter.destroy();\n };\n /**\n * `Font` used in complex objects to draw strings and text when it is not defined explicitly.\n * @default null\n * @private\n */\n PdfDocument.defaultStandardFont = null;\n /**\n * Indicates whether enable cache or not\n * @default true\n * @private\n */\n PdfDocument.isCacheEnabled = true;\n return PdfDocument;\n}(PdfDocumentBase));\nexport { PdfDocument };\n","/**\n * PdfStandardFontMetricsFactory.ts class for EJ2-PDF\n */\nimport { PdfFontStyle, PdfFontFamily } from './enum';\nimport { PdfFontMetrics, StandardWidthTable } from './pdf-font-metrics';\n/**\n * @private\n * `Factory of the standard fonts metrics`.\n */\nvar PdfStandardFontMetricsFactory = /** @class */ (function () {\n function PdfStandardFontMetricsFactory() {\n }\n /**\n * Returns `metrics` of the font.\n * @private\n */\n PdfStandardFontMetricsFactory.getMetrics = function (fontFamily, fontStyle, size) {\n var metrics = null;\n switch (fontFamily) {\n case PdfFontFamily.Helvetica:\n metrics = this.getHelveticaMetrics(fontFamily, fontStyle, size);\n break;\n case PdfFontFamily.Courier:\n metrics = this.getCourierMetrics(fontFamily, fontStyle, size);\n break;\n case PdfFontFamily.TimesRoman:\n metrics = this.getTimesMetrics(fontFamily, fontStyle, size);\n break;\n case PdfFontFamily.Symbol:\n metrics = this.getSymbolMetrics(fontFamily, fontStyle, size);\n break;\n case PdfFontFamily.ZapfDingbats:\n metrics = this.getZapfDingbatsMetrics(fontFamily, fontStyle, size);\n break;\n default:\n metrics = this.getHelveticaMetrics(PdfFontFamily.Helvetica, fontStyle, size);\n break;\n }\n metrics.name = fontFamily.toString();\n metrics.subScriptSizeFactor = this.subSuperScriptFactor;\n metrics.superscriptSizeFactor = this.subSuperScriptFactor;\n return metrics;\n };\n // Implementation\n /**\n * Creates `Helvetica font metrics`.\n * @private\n */\n PdfStandardFontMetricsFactory.getHelveticaMetrics = function (fontFamily, fontStyle, size) {\n var metrics = new PdfFontMetrics();\n if ((fontStyle & PdfFontStyle.Bold) > 0 && (fontStyle & PdfFontStyle.Italic) > 0) {\n metrics.ascent = this.helveticaBoldItalicAscent;\n metrics.descent = this.helveticaBoldItalicDescent;\n metrics.postScriptName = this.helveticaBoldItalicName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.arialBoldWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else if ((fontStyle & PdfFontStyle.Bold) > 0) {\n metrics.ascent = this.helveticaBoldAscent;\n metrics.descent = this.helveticaBoldDescent;\n metrics.postScriptName = this.helveticaBoldName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.arialBoldWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else if ((fontStyle & PdfFontStyle.Italic) > 0) {\n metrics.ascent = this.helveticaItalicAscent;\n metrics.descent = this.helveticaItalicDescent;\n metrics.postScriptName = this.helveticaItalicName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.arialWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else {\n metrics.ascent = this.helveticaAscent;\n metrics.descent = this.helveticaDescent;\n metrics.postScriptName = this.helveticaName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.arialWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n return metrics;\n };\n /**\n * Creates `Courier font metrics`.\n * @private\n */\n PdfStandardFontMetricsFactory.getCourierMetrics = function (fontFamily, fontStyle, size) {\n var metrics = new PdfFontMetrics();\n if ((fontStyle & PdfFontStyle.Bold) > 0 && (fontStyle & PdfFontStyle.Italic) > 0) {\n metrics.ascent = this.courierBoldItalicAscent;\n metrics.descent = this.courierBoldItalicDescent;\n metrics.postScriptName = this.courierBoldItalicName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.fixedWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else if ((fontStyle & PdfFontStyle.Bold) > 0) {\n metrics.ascent = this.courierBoldAscent;\n metrics.descent = this.courierBoldDescent;\n metrics.postScriptName = this.courierBoldName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.fixedWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else if ((fontStyle & PdfFontStyle.Italic) > 0) {\n metrics.ascent = this.courierItalicAscent;\n metrics.descent = this.courierItalicDescent;\n metrics.postScriptName = this.courierItalicName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.fixedWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else {\n metrics.ascent = this.courierAscent;\n metrics.descent = this.courierDescent;\n metrics.postScriptName = this.courierName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.fixedWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n return metrics;\n };\n /**\n * Creates `Times font metrics`.\n * @private\n */\n PdfStandardFontMetricsFactory.getTimesMetrics = function (fontFamily, fontStyle, size) {\n var metrics = new PdfFontMetrics();\n if ((fontStyle & PdfFontStyle.Bold) > 0 && (fontStyle & PdfFontStyle.Italic) > 0) {\n metrics.ascent = this.timesBoldItalicAscent;\n metrics.descent = this.timesBoldItalicDescent;\n metrics.postScriptName = this.timesBoldItalicName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.timesRomanBoldItalicWidths);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else if ((fontStyle & PdfFontStyle.Bold) > 0) {\n metrics.ascent = this.timesBoldAscent;\n metrics.descent = this.timesBoldDescent;\n metrics.postScriptName = this.timesBoldName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.timesRomanBoldWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else if ((fontStyle & PdfFontStyle.Italic) > 0) {\n metrics.ascent = this.timesItalicAscent;\n metrics.descent = this.timesItalicDescent;\n metrics.postScriptName = this.timesItalicName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.timesRomanItalicWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n else {\n metrics.ascent = this.timesAscent;\n metrics.descent = this.timesDescent;\n metrics.postScriptName = this.timesName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.timesRomanWidth);\n metrics.height = metrics.ascent - metrics.descent;\n }\n return metrics;\n };\n /**\n * Creates `Symbol font metrics`.\n * @private\n */\n PdfStandardFontMetricsFactory.getSymbolMetrics = function (fontFamily, fontStyle, size) {\n var metrics = new PdfFontMetrics();\n metrics.ascent = this.symbolAscent;\n metrics.descent = this.symbolDescent;\n metrics.postScriptName = this.symbolName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.symbolWidth);\n metrics.height = metrics.ascent - metrics.descent;\n return metrics;\n };\n /**\n * Creates `ZapfDingbats font metrics`.\n * @private\n */\n PdfStandardFontMetricsFactory.getZapfDingbatsMetrics = function (fontFamily, fontStyle, size) {\n var metrics = new PdfFontMetrics();\n metrics.ascent = this.zapfDingbatsAscent;\n metrics.descent = this.zapfDingbatsDescent;\n metrics.postScriptName = this.zapfDingbatsName;\n metrics.size = size;\n metrics.widthTable = new StandardWidthTable(this.zapfDingbatsWidth);\n metrics.height = metrics.ascent - metrics.descent;\n return metrics;\n };\n /**\n * `Multiplier` os subscript superscript.\n * @private\n */\n PdfStandardFontMetricsFactory.subSuperScriptFactor = 1.52;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaAscent = 931;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaDescent = -225;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaName = 'Helvetica';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaBoldAscent = 962;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaBoldDescent = -228;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaBoldName = 'Helvetica-Bold';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaItalicAscent = 931;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaItalicDescent = -225;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaItalicName = 'Helvetica-Oblique';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaBoldItalicAscent = 962;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaBoldItalicDescent = -228;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.helveticaBoldItalicName = 'Helvetica-BoldOblique';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierAscent = 805;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierDescent = -250;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.courierName = 'Courier';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierBoldAscent = 801;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierBoldDescent = -250;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.courierBoldName = 'Courier-Bold';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierItalicAscent = 805;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierItalicDescent = -250;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.courierItalicName = 'Courier-Oblique';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierBoldItalicAscent = 801;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.courierBoldItalicDescent = -250;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.courierBoldItalicName = 'Courier-BoldOblique';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesAscent = 898;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesDescent = -218;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.timesName = 'Times-Roman';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesBoldAscent = 935;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesBoldDescent = -218;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.timesBoldName = 'Times-Bold';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesItalicAscent = 883;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesItalicDescent = -217;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.timesItalicName = 'Times-Italic';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesBoldItalicAscent = 921;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.timesBoldItalicDescent = -218;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.timesBoldItalicName = 'Times-BoldItalic';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.symbolAscent = 1010;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.symbolDescent = -293;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.symbolName = 'Symbol';\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.zapfDingbatsAscent = 820;\n /**\n * `Ascender` value for the font.\n * @private\n */\n PdfStandardFontMetricsFactory.zapfDingbatsDescent = -143;\n /**\n * `Font type`.\n * @private\n */\n PdfStandardFontMetricsFactory.zapfDingbatsName = 'ZapfDingbats';\n /**\n * `Arial` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.arialWidth = [\n 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333,\n 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584,\n 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833,\n 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278,\n 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833,\n 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334,\n 584, 0, 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0,\n 611, 0, 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0,\n 500, 667, 0, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 0,\n 737, 333, 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834,\n 834, 611, 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278,\n 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667,\n 667, 611, 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278,\n 278, 278, 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500,\n 556, 500\n ];\n /**\n * `Arial bold` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.arialBoldWidth = [\n 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333,\n 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584,\n 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833,\n 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333,\n 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889,\n 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389,\n 584, 0, 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0,\n 611, 0, 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0,\n 500, 667, 0, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 0,\n 737, 333, 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834,\n 834, 611, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278,\n 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667,\n 667, 611, 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278,\n 278, 278, 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556,\n 611, 556\n ];\n /**\n * `Fixed` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.fixedWidth = [\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600\n ];\n /**\n * `Times` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.timesRomanWidth = [\n 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333,\n 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564,\n 564, 444, 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889,\n 722, 722, 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333,\n 469, 500, 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778,\n 500, 500, 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480,\n 541, 0, 500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0,\n 611, 0, 0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0,\n 444, 722, 0, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 0,\n 760, 333, 400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750,\n 750, 444, 722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333,\n 333, 333, 722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722,\n 556, 500, 444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278,\n 278, 278, 500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500,\n 500, 500\n ];\n /**\n * `Times bold` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.timesRomanBoldWidth = [\n 250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333,\n 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570,\n 570, 500, 930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944,\n 722, 778, 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333,\n 581, 500, 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833,\n 556, 500, 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394,\n 520, 0, 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 1000, 0,\n 667, 0, 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0,\n 444, 722, 0, 333, 500, 500, 500, 500, 220, 500, 333, 747, 300, 500, 570, 0,\n 747, 333, 400, 570, 300, 300, 333, 556, 540, 250, 333, 300, 330, 500, 750, 750,\n 750, 500, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 389, 389,\n 389, 389, 722, 722, 778, 778, 778, 778, 778, 570, 778, 722, 722, 722, 722, 722,\n 611, 556, 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278,\n 278, 278, 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 500,\n 556, 500\n ];\n /**\n * `Times italic` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.timesRomanItalicWidth = [\n 250, 333, 420, 500, 500, 833, 778, 214, 333, 333, 500, 675, 250, 333,\n 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675,\n 675, 500, 920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833,\n 667, 722, 611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389,\n 422, 500, 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722,\n 500, 500, 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400,\n 541, 0, 500, 0, 333, 500, 556, 889, 500, 500, 333, 1000, 500, 333, 944, 0,\n 556, 0, 0, 333, 333, 556, 556, 350, 500, 889, 333, 980, 389, 333, 667, 0,\n 389, 556, 0, 389, 500, 500, 500, 500, 275, 500, 333, 760, 276, 500, 675, 0,\n 760, 333, 400, 675, 300, 300, 333, 500, 523, 250, 333, 300, 310, 500, 750, 750,\n 750, 500, 611, 611, 611, 611, 611, 611, 889, 667, 611, 611, 611, 611, 333, 333,\n 333, 333, 722, 667, 722, 722, 722, 722, 722, 675, 722, 722, 722, 722, 722, 556,\n 611, 500, 500, 500, 500, 500, 500, 500, 667, 444, 444, 444, 444, 444, 278, 278,\n 278, 278, 500, 500, 500, 500, 500, 500, 500, 675, 500, 500, 500, 500, 500, 444,\n 500, 444\n ];\n /**\n * `Times bold italic` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.timesRomanBoldItalicWidths = [\n 250, 389, 555, 500, 500, 833, 778, 278, 333, 333, 500, 570, 250, 333,\n 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570,\n 570, 500, 832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889,\n 722, 722, 611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333,\n 570, 500, 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778,\n 556, 500, 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348,\n 570, 0, 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 944, 0,\n 611, 0, 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0,\n 389, 611, 0, 389, 500, 500, 500, 500, 220, 500, 333, 747, 266, 500, 606, 0,\n 747, 333, 400, 570, 300, 300, 333, 576, 500, 250, 333, 300, 300, 500, 750, 750,\n 750, 500, 667, 667, 667, 667, 667, 667, 944, 667, 667, 667, 667, 667, 389, 389,\n 389, 389, 722, 722, 722, 722, 722, 722, 722, 570, 722, 722, 722, 722, 722, 611,\n 611, 500, 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278,\n 278, 278, 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 444,\n 500, 444\n ];\n /**\n * `Symbol` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.symbolWidth = [\n 250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549,\n 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278,\n 549, 549, 549, 444, 549, 722, 667, 722, 612, 611, 763, 603, 722, 333,\n 631, 722, 686, 889, 722, 722, 768, 741, 556, 592, 611, 690, 439, 768,\n 645, 795, 611, 333, 863, 333, 658, 500, 500, 631, 549, 549, 494, 439,\n 521, 411, 603, 329, 603, 549, 549, 576, 521, 549, 549, 521, 549, 603,\n 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 750, 620, 247,\n 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, 400,\n 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000,\n 658, 823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713,\n 713, 713, 713, 768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603,\n 1042, 987, 603, 987, 603, 494, 329, 790, 790, 786, 713, 384, 384, 384,\n 384, 384, 384, 494, 494, 494, 494, 329, 274, 686, 686, 686, 384, 384,\n 384, 384, 384, 384, 494, 494, 494, -1\n ];\n /**\n * `Zip dingbats` widths table.\n * @private\n */\n PdfStandardFontMetricsFactory.zapfDingbatsWidth = [\n 278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855,\n 911, 933, 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759,\n 754, 494, 552, 537, 577, 692, 786, 788, 788, 790, 793, 794, 816, 823,\n 789, 841, 823, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 776,\n 768, 792, 759, 707, 708, 682, 701, 826, 815, 789, 789, 707, 687, 696,\n 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, 762, 759, 759, 892,\n 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 390, 390, 317,\n 317, 276, 276, 509, 509, 410, 410, 234, 234, 334, 334, 732, 544, 544,\n 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918,\n 927, 928, 928, 834, 873, 828, 924, 924, 917, 930, 931, 463, 883, 836,\n 836, 867, 867, 696, 696, 874, 874, 760, 946, 771, 865, 771, 888, 967,\n 888, 831, 873, 927, 970, 918\n ];\n return PdfStandardFontMetricsFactory;\n}());\nexport { PdfStandardFontMetricsFactory };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfFontFamily, PdfFontStyle, FontEncoding } from './enum';\nimport { PdfFont } from './pdf-font';\nimport { PdfDocument } from './../../document/pdf-document';\nimport { PdfStandardFontMetricsFactory } from './pdf-standard-font-metrics-factory';\nimport { PdfDictionary } from './../../primitives/pdf-dictionary';\nimport { DictionaryProperties } from './../../input-output/pdf-dictionary-properties';\nimport { PdfName } from './../../primitives/pdf-name';\n/**\n * Represents one of the 14 standard fonts.\n * It's used to create a standard PDF font to draw the text in to the PDF.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // add a new page to the document\n * let page1 : PdfPage = document.pages.add();\n * //\n * // create new standard font\n * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20);\n * //\n * // create black brush\n * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n * // draw the text\n * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(0, 0));\n * // save the document\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfStandardFont = /** @class */ (function (_super) {\n __extends(PdfStandardFont, _super);\n function PdfStandardFont(fontFamilyPrototype, size, style) {\n var _this = _super.call(this, size, style) || this;\n /**\n * Gets `ascent` of the font.\n * @private\n */\n _this.dictionaryProperties = new DictionaryProperties();\n /**\n * Gets `encodings` for internal class use.\n * @hidden\n * @private\n */\n _this.encodings = ['Unknown', 'StandardEncoding', 'MacRomanEncoding', 'MacExpertEncoding',\n 'WinAnsiEncoding', 'PDFDocEncoding', 'IdentityH'];\n if ((typeof fontFamilyPrototype === 'number') && (typeof style === 'undefined')) {\n _this.constructor(fontFamilyPrototype, size, PdfFontStyle.Regular);\n }\n else if ((typeof fontFamilyPrototype === 'number') && (typeof style !== 'undefined')) {\n _this = _super.call(this, size, style) || this;\n _this.pdfFontFamily = fontFamilyPrototype;\n _this.checkStyle();\n _this.initializeInternals();\n }\n else if ((fontFamilyPrototype instanceof PdfStandardFont) && (typeof style === 'undefined')) {\n _this.constructor(fontFamilyPrototype.fontFamily, size, fontFamilyPrototype.style);\n }\n else if ((fontFamilyPrototype instanceof PdfStandardFont) && (typeof style !== 'undefined')) {\n _this.constructor(fontFamilyPrototype.fontFamily, size, style);\n }\n return _this;\n }\n Object.defineProperty(PdfStandardFont.prototype, \"fontFamily\", {\n //Properties\n /**\n * Gets the `FontFamily`.\n * @private\n */\n get: function () {\n return this.pdfFontFamily;\n },\n enumerable: true,\n configurable: true\n });\n //methods\n /**\n * Checks font `style` of the font.\n * @private\n */\n PdfStandardFont.prototype.checkStyle = function () {\n if (this.fontFamily === PdfFontFamily.Symbol || this.fontFamily === PdfFontFamily.ZapfDingbats) {\n var style = this.style;\n style &= ~(PdfFontStyle.Bold | PdfFontStyle.Italic);\n this.setStyle(style);\n }\n };\n /**\n * Returns `width` of the line.\n * @public\n */\n PdfStandardFont.prototype.getLineWidth = function (line, format) {\n if (line == null) {\n throw new Error('ArgumentNullException:line');\n }\n var width = 0;\n var name = this.name;\n line = PdfStandardFont.convert(line);\n for (var i = 0, len = line.length; i < len; i++) {\n var ch = line[i];\n var charWidth = this.getCharWidthInternal(ch, format);\n width += charWidth;\n }\n var size = this.metrics.getSize(format);\n width *= (PdfFont.charSizeMultiplier * size);\n width = this.applyFormatSettings(line, format, width);\n return width;\n };\n /**\n * Checks whether fonts are `equals`.\n * @private\n */\n PdfStandardFont.prototype.equalsToFont = function (font) {\n var equal = false;\n var stFont = font;\n if (stFont != null) {\n var fontFamilyEqual = (this.fontFamily === stFont.fontFamily);\n var lineReducer = (~(PdfFontStyle.Underline | PdfFontStyle.Strikeout));\n var styleEqual = (this.style & lineReducer) === (stFont.style & lineReducer);\n equal = (fontFamilyEqual && styleEqual);\n }\n return equal;\n };\n /**\n * `Initializes` font internals..\n * @private\n */\n PdfStandardFont.prototype.initializeInternals = function () {\n var equalFont = null;\n // if (PdfDocument.EnableCache) {\n equalFont = PdfDocument.cache.search(this);\n // }\n var internals = null;\n // if (equalFont == null) {\n // Create font metrics.\n var metrics = PdfStandardFontMetricsFactory.getMetrics(this.pdfFontFamily, this.style, this.size);\n this.metrics = metrics;\n internals = this.createInternals();\n this.setInternals(internals);\n };\n /**\n * `Creates` font`s dictionary.\n * @private\n */\n PdfStandardFont.prototype.createInternals = function () {\n var dictionary = new PdfDictionary();\n dictionary.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.font));\n dictionary.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.type1));\n dictionary.items.setValue(this.dictionaryProperties.baseFont, new PdfName(this.metrics.postScriptName));\n if (this.fontFamily !== PdfFontFamily.Symbol && this.fontFamily !== PdfFontFamily.ZapfDingbats) {\n var encoding = this.encodings[FontEncoding.WinAnsiEncoding];\n dictionary.items.setValue(this.dictionaryProperties.encoding, new PdfName(encoding));\n }\n return dictionary;\n };\n /**\n * Returns `width` of the char. This methods doesn`t takes into consideration font`s size.\n * @private\n */\n PdfStandardFont.prototype.getCharWidthInternal = function (charCode, format) {\n var width = 0;\n var code = 0;\n code = charCode.charCodeAt(0);\n if (this.name === '0' || this.name === '1' || this.name === '2' ||\n this.name === '3' || this.name === '4') {\n code = code - PdfStandardFont.charOffset;\n }\n code = (code >= 0 && code !== 128) ? code : 0;\n var metrics = this.metrics;\n var widthTable = metrics.widthTable;\n width = widthTable.items(code);\n return width;\n };\n /**\n * `Converts` the specified text.\n * @private\n */\n PdfStandardFont.convert = function (text) {\n return text;\n };\n //Constants\n /**\n * First character `position`.\n * @private\n */\n PdfStandardFont.charOffset = 32;\n return PdfStandardFont;\n}(PdfFont));\nexport { PdfStandardFont };\n","import { PdfColor } from './../graphics/pdf-color';\nimport { RectangleF, PointF } from './../drawing/pdf-drawing';\nimport { PdfDictionary, SaveAnnotationEventHandler } from './../primitives/pdf-dictionary';\nimport { PdfArray } from './../primitives/pdf-array';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { PdfString } from './../primitives/pdf-string';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfSolidBrush } from './../graphics/brushes/pdf-solid-brush';\nimport { PdfStandardFont } from './../graphics/fonts/pdf-standard-font';\nimport { PdfFontFamily } from './../graphics/fonts/enum';\nimport { PdfStringFormat } from './../graphics/fonts/pdf-string-format';\nimport { PdfTextAlignment } from './../graphics/enum';\n/**\n * `PdfAnnotation` class represents the base class for annotation objects.\n * @private\n */\nvar PdfAnnotation = /** @class */ (function () {\n function PdfAnnotation(arg1) {\n // Fields\n /**\n * Specifies the Internal variable to store fields of `PdfDictionaryProperties`.\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n /**\n * `Color` of the annotation\n * @private\n */\n this.pdfColor = new PdfColor(255, 255, 255);\n /**\n * `Bounds` of the annotation.\n * @private\n */\n this.rectangle = new RectangleF(0, 0, 0, 0);\n /**\n * Parent `page` of the annotation.\n * @private\n */\n this.pdfPage = null;\n /**\n * `Brush of the text` of the annotation.\n * @default new PdfSolidBrush(new PdfColor(0, 0, 0))\n * @private\n */\n this.textBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n /**\n * `Font of the text` of the annotation.\n * @default new PdfStandardFont(PdfFontFamily.TimesRoman, 10)\n * @private\n */\n this.textFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);\n /**\n * `StringFormat of the text` of the annotation.\n * @default new PdfStringFormat(PdfTextAlignment.Left)\n * @private\n */\n this.format = new PdfStringFormat(PdfTextAlignment.Left);\n /**\n * `Text` of the annotation.\n * @private\n */\n this.content = '';\n /**\n * Internal variable to store `dictionary`.\n * @private\n */\n this.pdfDictionary = new PdfDictionary();\n /**\n * To specifying the `Inner color` with which to fill the annotation\n * @private\n */\n this.internalColor = new PdfColor();\n /**\n * `opacity or darkness` of the annotation.\n * @private\n * @default 1.0\n */\n this.darkness = 1.0;\n if (typeof arg1 === 'undefined') {\n this.initialize();\n }\n else {\n this.initialize();\n this.bounds = arg1;\n }\n }\n Object.defineProperty(PdfAnnotation.prototype, \"color\", {\n // Properties\n /**\n * `Color` of the annotation\n * @private\n */\n get: function () {\n return this.pdfColor;\n },\n set: function (value) {\n this.pdfColor = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"innerColor\", {\n /**\n * To specifying the `Inner color` with which to fill the annotation\n * @private\n */\n get: function () {\n return this.internalColor;\n },\n set: function (value) {\n this.internalColor = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"bounds\", {\n /**\n * `bounds` of the annotation.\n * @private\n */\n get: function () {\n return this.rectangle;\n },\n set: function (value) {\n this.rectangle = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"page\", {\n /**\n * Parent `page` of the annotation.\n * @private\n */\n get: function () {\n return this.pdfPage;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"font\", {\n /**\n * To specifying the `Font of the text` in the annotation.\n * @private\n */\n get: function () {\n return this.textFont;\n },\n set: function (value) {\n this.textFont = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"stringFormat\", {\n /**\n * To specifying the `StringFormat of the text` in the annotation.\n * @private\n */\n get: function () {\n return this.format;\n },\n set: function (value) {\n this.format = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"brush\", {\n /**\n * To specifying the `Brush of the text` in the annotation.\n * @private\n */\n get: function () {\n return this.textBrush;\n },\n set: function (value) {\n this.textBrush = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"text\", {\n /**\n * `Text` of the annotation.\n * @private\n */\n get: function () {\n return this.content;\n },\n set: function (value) {\n this.content = value;\n this.dictionary.items.setValue(this.dictionaryProperties.contents, new PdfString(this.content));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfAnnotation.prototype, \"dictionary\", {\n /**\n * Internal variable to store `dictionary`.\n * @hidden\n */\n get: function () {\n return this.pdfDictionary;\n },\n set: function (value) {\n this.pdfDictionary = value;\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Initialize` the annotation event handler and specifies the type of the annotation.\n * @private\n */\n PdfAnnotation.prototype.initialize = function () {\n this.pdfDictionary.annotationBeginSave = new SaveAnnotationEventHandler(this);\n this.pdfDictionary.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.annot));\n };\n /**\n * Sets related `page` of the annotation.\n * @private\n */\n PdfAnnotation.prototype.setPage = function (page) {\n this.pdfPage = page;\n this.pdfDictionary.items.setValue(this.dictionaryProperties.p, new PdfReferenceHolder(this.pdfPage));\n };\n /**\n * Handles the `BeginSave` event of the Dictionary.\n * @private\n */\n PdfAnnotation.prototype.beginSave = function () {\n this.save();\n };\n /**\n * `Saves` an annotation.\n * @private\n */\n /* tslint:disable */\n PdfAnnotation.prototype.save = function () {\n var nativeRectangle = new RectangleF(this.rectangle.x, this.rectangle.y, this.rectangle.width, this.rectangle.height);\n var section = this.pdfPage.section;\n var initialHeight = nativeRectangle.height;\n var tempLoacation = section.pointToNativePdf(this.page, new PointF(nativeRectangle.x, nativeRectangle.y));\n nativeRectangle.x = tempLoacation.x;\n nativeRectangle.width = tempLoacation.x + nativeRectangle.width;\n nativeRectangle.y = (tempLoacation.y - this.page.document.pageSettings.margins.top);\n nativeRectangle.height = nativeRectangle.y - initialHeight;\n this.pdfDictionary.items.setValue(this.dictionaryProperties.rect, PdfArray.fromRectangle(nativeRectangle));\n this.dictionary.items.setValue(this.dictionaryProperties.ca, new PdfNumber(this.darkness));\n };\n Object.defineProperty(PdfAnnotation.prototype, \"element\", {\n /* tslint:enable */\n // IPdfWrapper Members\n /**\n * Gets the `element`.\n * @private\n */\n get: function () {\n return this.pdfDictionary;\n },\n enumerable: true,\n configurable: true\n });\n return PdfAnnotation;\n}());\nexport { PdfAnnotation };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfAnnotation } from './annotation';\nimport { PdfName } from './../primitives/pdf-name';\n/**\n * `PdfLinkAnnotation` class represents the ink annotation class.\n * @private\n */\nvar PdfLinkAnnotation = /** @class */ (function (_super) {\n __extends(PdfLinkAnnotation, _super);\n function PdfLinkAnnotation(rectangle) {\n var _this = this;\n if (typeof rectangle === 'undefined') {\n _this = _super.call(this) || this;\n }\n else {\n _this = _super.call(this, rectangle) || this;\n }\n return _this;\n }\n // Implementation\n /**\n * `Initializes` annotation object.\n * @private\n */\n PdfLinkAnnotation.prototype.initialize = function () {\n _super.prototype.initialize.call(this);\n this.dictionary.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.link));\n };\n return PdfLinkAnnotation;\n}(PdfAnnotation));\nexport { PdfLinkAnnotation };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfLinkAnnotation } from './link-annotation';\n/**\n * Represents base class for `link annotations` with associated action.\n * @private\n */\nvar PdfActionLinkAnnotation = /** @class */ (function (_super) {\n __extends(PdfActionLinkAnnotation, _super);\n // Constructors\n /**\n * Specifies the constructor for `ActionLinkAnnotation`.\n * @private\n */\n function PdfActionLinkAnnotation(rectangle) {\n var _this = _super.call(this, rectangle) || this;\n // Fields\n /**\n * Internal variable to store annotation's `action`.\n * @default null\n * @private\n */\n _this.pdfAction = null;\n return _this;\n }\n //Public method\n /**\n * get and set the `action`.\n * @hidden\n */\n PdfActionLinkAnnotation.prototype.getSetAction = function (value) {\n if (typeof value === 'undefined') {\n return this.pdfAction;\n }\n else {\n this.pdfAction = value;\n }\n };\n return PdfActionLinkAnnotation;\n}(PdfLinkAnnotation));\nexport { PdfActionLinkAnnotation };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfLinkAnnotation } from './link-annotation';\n/**\n * `PdfDocumentLinkAnnotation` class represents an annotation object with holds link on another location within a document.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create new pages\n * let page1 : PdfPage = document.pages.add();\n * let page2 : PdfPage = document.pages.add();\n * // create a new rectangle\n * let bounds : RectangleF = new RectangleF({x : 10, y : 200}, {width : 300, height : 25});\n * //\n * // create a new document link annotation\n * let documentLinkAnnotation : PdfDocumentLinkAnnotation = new PdfDocumentLinkAnnotation(bounds);\n * // set the annotation text\n * documentLinkAnnotation.text = 'Document link annotation';\n * // set the destination\n * documentLinkAnnotation.destination = new PdfDestination(page2);\n * // set the documentlink annotation location\n * documentLinkAnnotation.destination.location = new PointF(10, 0);\n * // add this annotation to a new page\n * page1.annotations.add(documentLinkAnnotation);\n * //\n * // save the document to disk\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfDocumentLinkAnnotation = /** @class */ (function (_super) {\n __extends(PdfDocumentLinkAnnotation, _super);\n function PdfDocumentLinkAnnotation(rectangle, destination) {\n var _this = _super.call(this, rectangle) || this;\n // Fields\n /**\n * `Destination` of the annotation.\n * @default null\n * @private\n */\n _this.pdfDestination = null;\n if (typeof destination !== 'undefined') {\n _this.destination = destination;\n }\n return _this;\n }\n Object.defineProperty(PdfDocumentLinkAnnotation.prototype, \"destination\", {\n // Properties\n /**\n * Gets or sets the `destination` of the annotation.\n * ```typescript\n * // create a new PDF document\n * let document : PdfDocument = new PdfDocument();\n * // create new pages\n * let page1 : PdfPage = document.pages.add();\n * let page2 : PdfPage = document.pages.add();\n * // create a new rectangle\n * let bounds : RectangleF = new RectangleF({x : 10, y : 200}, {width : 300, height : 25});\n * //\n * // create a new document link annotation\n * let documentLinkAnnotation : PdfDocumentLinkAnnotation = new PdfDocumentLinkAnnotation(bounds);\n * // set the annotation text\n * documentLinkAnnotation.text = 'Document link annotation';\n * // set the destination\n * documentLinkAnnotation.destination = new PdfDestination(page2);\n * // set the documentlink annotation location\n * documentLinkAnnotation.destination.location = new PointF(10, 0);\n * // add this annotation to a new page\n * page1.annotations.add(documentLinkAnnotation);\n * //\n * // save the document to disk\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n * @default null\n */\n get: function () {\n return this.pdfDestination;\n },\n set: function (value) {\n // if (this.pdfDestination !== value) {\n this.pdfDestination = value;\n // }\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Saves` annotation object.\n * @private\n */\n PdfDocumentLinkAnnotation.prototype.save = function () {\n _super.prototype.save.call(this);\n if (this.pdfDestination != null) {\n this.dictionary.items.setValue(this.dictionaryProperties.dest, this.pdfDestination.element);\n }\n };\n /**\n * `Clone` the document link annotation.\n * @private\n */\n PdfDocumentLinkAnnotation.prototype.clone = function () {\n var annot = new PdfDocumentLinkAnnotation(this.bounds, this.destination);\n annot.color = this.color;\n annot.brush = this.brush;\n annot.destination = this.destination;\n annot.font = this.font;\n return annot;\n };\n return PdfDocumentLinkAnnotation;\n}(PdfLinkAnnotation));\nexport { PdfDocumentLinkAnnotation };\n","/**\n * ElementLayouter.ts class for EJ2-PDF\n */\nimport { RectangleF } from './../../../drawing/pdf-drawing';\nimport { PdfLayoutType, PdfLayoutBreakType } from './../enum';\n/**\n * Base class for `elements lay outing`.\n * @private\n */\nvar ElementLayouter = /** @class */ (function () {\n // Constructor\n /**\n * Initializes a new instance of the `ElementLayouter` class.\n * @private\n */\n function ElementLayouter(element) {\n this.layoutElement = element;\n }\n Object.defineProperty(ElementLayouter.prototype, \"elements\", {\n // Properties\n /**\n * Gets the `element`.\n * @private\n */\n get: function () {\n return this.layoutElement;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the `element`.\n * @private\n */\n ElementLayouter.prototype.getElement = function () {\n return this.layoutElement;\n };\n ElementLayouter.prototype.layout = function (param, isBoundsChanged) {\n if (typeof isBoundsChanged === 'boolean' && isBoundsChanged === true) {\n return this.layoutInternal(param, true);\n }\n else {\n return this.layoutInternal(param);\n }\n };\n /**\n * Returns the `next page`.\n * @private\n */\n ElementLayouter.prototype.getNextPage = function (currentPage) {\n var section = currentPage.section;\n var nextPage = section.add();\n return nextPage;\n };\n return ElementLayouter;\n}());\nexport { ElementLayouter };\nvar PdfLayoutFormat = /** @class */ (function () {\n function PdfLayoutFormat(baseFormat) {\n if (typeof baseFormat === 'undefined') {\n //\n }\n else {\n this.break = baseFormat.break;\n this.layout = baseFormat.layout;\n this.paginateBounds = baseFormat.paginateBounds;\n this.boundsSet = baseFormat.usePaginateBounds;\n }\n }\n Object.defineProperty(PdfLayoutFormat.prototype, \"layout\", {\n // Properties\n /**\n * Gets or sets `layout` type of the element.\n * @private\n */\n get: function () {\n if (typeof this.layoutType === 'undefined' || this.layoutType == null) {\n this.layoutType = PdfLayoutType.Paginate;\n }\n return this.layoutType;\n },\n set: function (value) {\n this.layoutType = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfLayoutFormat.prototype, \"break\", {\n /**\n * Gets or sets `break` type of the element.\n * @private\n */\n get: function () {\n if (typeof this.breakType === 'undefined' || this.boundsSet == null) {\n this.breakType = PdfLayoutBreakType.FitPage;\n }\n return this.breakType;\n },\n set: function (value) {\n this.breakType = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfLayoutFormat.prototype, \"paginateBounds\", {\n /**\n * Gets or sets the `bounds` on the next page.\n * @private\n */\n get: function () {\n if (typeof this.layoutPaginateBounds === 'undefined' && this.layoutPaginateBounds == null) {\n this.layoutPaginateBounds = new RectangleF(0, 0, 0, 0);\n }\n return this.layoutPaginateBounds;\n },\n set: function (value) {\n this.layoutPaginateBounds = value;\n this.boundsSet = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfLayoutFormat.prototype, \"usePaginateBounds\", {\n /**\n * Gets a value indicating whether [`use paginate bounds`].\n * @private\n */\n get: function () {\n if (typeof this.boundsSet === 'undefined' || this.boundsSet == null) {\n this.boundsSet = false;\n }\n return this.boundsSet;\n },\n enumerable: true,\n configurable: true\n });\n return PdfLayoutFormat;\n}());\nexport { PdfLayoutFormat };\nvar PdfLayoutParams = /** @class */ (function () {\n function PdfLayoutParams() {\n }\n Object.defineProperty(PdfLayoutParams.prototype, \"page\", {\n // Properties\n /**\n * Gets or sets the layout `page` for the element.\n * @private\n */\n get: function () {\n return this.pdfPage;\n },\n set: function (value) {\n this.pdfPage = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfLayoutParams.prototype, \"bounds\", {\n /**\n * Gets or sets layout `bounds` for the element.\n * @private\n */\n get: function () {\n return new RectangleF(this.layoutBounds.x, this.layoutBounds.y, this.layoutBounds.width, this.layoutBounds.height);\n },\n set: function (value) {\n this.layoutBounds = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfLayoutParams.prototype, \"format\", {\n /**\n * Gets or sets `layout settings` for the element.\n * @private\n */\n get: function () {\n return this.layoutFormat;\n },\n set: function (value) {\n this.layoutFormat = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfLayoutParams;\n}());\nexport { PdfLayoutParams };\nvar PdfLayoutResult = /** @class */ (function () {\n // Constructors\n /**\n * Initializes the new instance of `PdfLayoutResult` class.\n * @private\n */\n function PdfLayoutResult(page, bounds) {\n this.pdfPage = page;\n this.layoutBounds = bounds;\n }\n Object.defineProperty(PdfLayoutResult.prototype, \"page\", {\n // Properties\n /**\n * Gets the last `page` where the element was drawn.\n * @private\n */\n get: function () {\n return this.pdfPage;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfLayoutResult.prototype, \"bounds\", {\n /**\n * Gets the `bounds` of the element on the last page where it was drawn.\n * @private\n */\n get: function () {\n return this.layoutBounds;\n },\n enumerable: true,\n configurable: true\n });\n return PdfLayoutResult;\n}());\nexport { PdfLayoutResult };\n","/**\n * public Enum for `PdfDestinationMode`.\n * @private\n */\nexport var PdfDestinationMode;\n(function (PdfDestinationMode) {\n /**\n * Specifies the type of `Location`.\n * @private\n */\n PdfDestinationMode[PdfDestinationMode[\"Location\"] = 0] = \"Location\";\n /**\n * Specifies the type of `FitToPage`.\n * @private\n */\n PdfDestinationMode[PdfDestinationMode[\"FitToPage\"] = 1] = \"FitToPage\";\n /**\n * Specifies the type of `FitR`.\n * @private\n */\n PdfDestinationMode[PdfDestinationMode[\"FitR\"] = 2] = \"FitR\";\n})(PdfDestinationMode || (PdfDestinationMode = {}));\n","import { RectangleF, PointF } from './../../drawing/pdf-drawing';\nimport { PdfLayoutParams, PdfLayoutFormat } from './base/element-layouter';\n/**\n * `PdfLayoutElement` class represents the base class for all elements that can be layout on the pages.\n * @private\n */\nvar PdfLayoutElement = /** @class */ (function () {\n function PdfLayoutElement() {\n }\n PdfLayoutElement.prototype.drawHelper = function (arg2, arg3, arg4, arg5) {\n if (arg3 instanceof PointF && typeof arg3.width === 'undefined' && typeof arg3 === 'undefined') {\n return this.drawHelper(arg2, arg3.x, arg3.y);\n }\n else if (typeof arg3 === 'number' && typeof arg4 === 'number' && typeof arg5 === 'undefined') {\n return this.drawHelper(arg2, arg3, arg4, null);\n }\n else if (arg3 instanceof RectangleF && typeof arg3.width !== 'undefined' && typeof arg4 === 'undefined') {\n return this.drawHelper(arg2, arg3, null);\n }\n else if (arg3 instanceof PointF && typeof arg3.width === 'undefined' && arg4 instanceof PdfLayoutFormat) {\n return this.drawHelper(arg2, arg3.x, arg3.y, arg4);\n }\n else if (typeof arg3 === 'number' && typeof arg4 === 'number' && (arg5 instanceof PdfLayoutFormat || arg5 == null)) {\n var width = (arg2.graphics.clientSize.width - arg3);\n var layoutRectangle = new RectangleF(arg3, arg4, width, 0);\n return this.drawHelper(arg2, layoutRectangle, arg5);\n }\n else if (arg3 instanceof RectangleF && typeof arg3.width !== 'undefined' && typeof arg4 === 'boolean') {\n this.bEmbedFonts = arg4;\n return this.drawHelper(arg2, arg3, null);\n }\n else {\n var param = new PdfLayoutParams();\n var temparg3 = arg3;\n var temparg4 = arg4;\n param.page = arg2;\n param.bounds = temparg3;\n param.format = (temparg4 != null) ? temparg4 : new PdfLayoutFormat();\n var result = this.layout(param);\n return result;\n }\n };\n return PdfLayoutElement;\n}());\nexport { PdfLayoutElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * TextLayouter.ts class for EJ2-PDF\n */\nimport { ElementLayouter, PdfLayoutResult } from './element-layouter';\nimport { RectangleF, SizeF } from './../../../drawing/pdf-drawing';\nimport { PdfStringLayouter } from './../../fonts/string-layouter';\nimport { PdfLayoutBreakType } from './../../figures/enum';\nimport { PdfColor } from './../../pdf-color';\nimport { PdfTextWebLink } from './../../../annotations/pdf-text-web-link';\n/**\n * Class that `layouts the text`.\n * @private\n */\nvar TextLayouter = /** @class */ (function (_super) {\n __extends(TextLayouter, _super);\n // Constructors\n /**\n * Initializes a new instance of the `TextLayouter` class.\n * @private\n */\n function TextLayouter(element) {\n return _super.call(this, element) || this;\n }\n Object.defineProperty(TextLayouter.prototype, \"element\", {\n /**\n * Gets the layout `element`.\n * @private\n */\n get: function () {\n return _super.prototype.getElement.call(this);\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Layouts` the element.\n * @private\n */\n TextLayouter.prototype.layoutInternal = function (param) {\n /* tslint:disable */\n this.format = (this.element.stringFormat !== null && typeof this.element.stringFormat !== 'undefined') ? this.element.stringFormat : null;\n var currentPage = param.page;\n var currentBounds = param.bounds;\n var text = this.element.value;\n var result = null;\n var pageResult = new TextPageLayoutResult();\n pageResult.page = currentPage;\n pageResult.remainder = text;\n for (;;) {\n pageResult = this.layoutOnPage(text, currentPage, currentBounds, param);\n result = this.getLayoutResult(pageResult);\n break;\n }\n /* tslint:enable */\n return result;\n };\n /**\n * Raises `PageLayout` event if needed.\n * @private\n */\n TextLayouter.prototype.getLayoutResult = function (pageResult) {\n var result = new PdfTextLayoutResult(pageResult.page, pageResult.bounds, pageResult.remainder, pageResult.lastLineBounds);\n return result;\n };\n /* tslint:disable */\n /**\n * `Layouts` the text on the page.\n * @private\n */\n TextLayouter.prototype.layoutOnPage = function (text, currentPage, currentBounds, param) {\n var result = new TextPageLayoutResult();\n result.remainder = text;\n result.page = currentPage;\n currentBounds = this.checkCorrectBounds(currentPage, currentBounds);\n var layouter = new PdfStringLayouter();\n var stringResult = layouter.layout(text, this.element.font, this.format, currentBounds, currentPage.getClientSize().height, false, new SizeF(0, 0));\n var textFinished = (stringResult.remainder == null);\n var doesntFit = (param.format.break === PdfLayoutBreakType.FitElement);\n var canDraw = !(doesntFit || stringResult.empty);\n // Draw the text.\n var graphics = currentPage.graphics;\n var brush = this.element.getBrush();\n if (this.element instanceof PdfTextWebLink) {\n brush.color = new PdfColor(0, 0, 255);\n }\n graphics.drawStringLayoutResult(stringResult, this.element.font, this.element.pen, brush, currentBounds, this.format);\n var lineInfo = stringResult.lines[stringResult.lineCount - 1];\n result.lastLineBounds = graphics.getLineBounds(stringResult.lineCount - 1, stringResult, this.element.font, currentBounds, this.format);\n result.bounds = this.getTextPageBounds(currentPage, currentBounds, stringResult);\n result.remainder = stringResult.remainder;\n result.end = (textFinished);\n return result;\n };\n /* tslint:enable */\n /**\n * `Corrects current bounds` on the page.\n * @private\n */\n TextLayouter.prototype.checkCorrectBounds = function (currentPage, currentBounds) {\n var pageSize = currentPage.graphics.clientSize;\n currentBounds.height = (currentBounds.height > 0) ? currentBounds.height : pageSize.height - currentBounds.y;\n return currentBounds;\n };\n /**\n * Returns a `rectangle` where the text was printed on the page.\n * @private\n */\n /* tslint:disable */\n TextLayouter.prototype.getTextPageBounds = function (currentPage, currentBounds, stringResult) {\n var textSize = stringResult.actualSize;\n var x = currentBounds.x;\n var y = currentBounds.y;\n var width = (currentBounds.width > 0) ? currentBounds.width : textSize.width;\n var height = textSize.height;\n var shiftedRect = currentPage.graphics.checkCorrectLayoutRectangle(textSize, currentBounds.x, currentBounds.y, this.format);\n // if (currentBounds.width <= 0) {\n x = shiftedRect.x;\n // }\n var verticalShift = currentPage.graphics.getTextVerticalAlignShift(textSize.height, currentBounds.height, this.format);\n y += verticalShift;\n var bounds = new RectangleF(x, y, width, height);\n return bounds;\n };\n return TextLayouter;\n}(ElementLayouter));\nexport { TextLayouter };\nvar TextPageLayoutResult = /** @class */ (function () {\n function TextPageLayoutResult() {\n }\n return TextPageLayoutResult;\n}());\nexport { TextPageLayoutResult };\nvar PdfTextLayoutResult = /** @class */ (function (_super) {\n __extends(PdfTextLayoutResult, _super);\n // Constructors\n /**\n * Initializes the new instance of `PdfTextLayoutResult` class.\n * @private\n */\n function PdfTextLayoutResult(page, bounds, remainder, lastLineBounds) {\n var _this = _super.call(this, page, bounds) || this;\n _this.remainderText = remainder;\n _this.lastLineTextBounds = lastLineBounds;\n return _this;\n }\n Object.defineProperty(PdfTextLayoutResult.prototype, \"remainder\", {\n // Properties\n /**\n * Gets a value that contains the `text` that was not printed.\n * @private\n */\n get: function () {\n return this.remainderText;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTextLayoutResult.prototype, \"lastLineBounds\", {\n /**\n * Gets a value that indicates the `bounds` of the last line that was printed on the page.\n * @private\n */\n get: function () {\n return this.lastLineTextBounds;\n },\n enumerable: true,\n configurable: true\n });\n return PdfTextLayoutResult;\n}(PdfLayoutResult));\nexport { PdfTextLayoutResult };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfTextElement.ts class for EJ2-PDF\n */\nimport { PdfLayoutElement } from './../figures/layout-element';\nimport { PdfBrush } from './../brushes/pdf-brush';\nimport { PdfFont } from './../fonts/pdf-font';\nimport { PdfStandardFont } from './../fonts/pdf-standard-font';\nimport { PdfPen } from './../pdf-pen';\nimport { PdfLayoutParams } from './../figures/base/element-layouter';\nimport { TextLayouter } from './base/text-layouter';\nimport { PdfSolidBrush } from './../brushes/pdf-solid-brush';\nimport { PdfColor } from './../pdf-color';\nimport { RectangleF, SizeF, PointF } from './../../drawing/pdf-drawing';\nimport { PdfLayoutFormat } from './base/element-layouter';\nimport { PdfStringLayouter } from './../fonts/string-layouter';\nimport { PdfTextAlignment } from './../enum';\n/**\n * `PdfTextElement` class represents the text area with the ability to span several pages\n * and inherited from the 'PdfLayoutElement' class.\n * @private\n */\nvar PdfTextElement = /** @class */ (function (_super) {\n __extends(PdfTextElement, _super);\n function PdfTextElement(arg1, arg2, arg3, arg4, arg5) {\n var _this = _super.call(this) || this;\n // Fields\n /**\n * `Text` data.\n * @private\n */\n _this.content = '';\n /**\n * `Value` of text data.\n * @private\n */\n _this.elementValue = '';\n /**\n * indicate whether the drawText with PointF overload is called or not.\n * @default false\n * @private\n */\n _this.hasPointOverload = false;\n /**\n * indicate whether the PdfGridCell value is `PdfTextElement`\n * @default false\n * @private\n */\n _this.isPdfTextElement = false;\n if (typeof arg1 === 'undefined') {\n //\n }\n else if (typeof arg1 === 'string' && typeof arg2 === 'undefined') {\n _this = _super.call(this) || this;\n _this.content = arg1;\n _this.elementValue = arg1;\n }\n else if (typeof arg1 === 'string' && arg2 instanceof PdfFont && typeof arg3 === 'undefined') {\n _this = _super.call(this) || this;\n _this.content = arg1;\n _this.elementValue = arg1;\n _this.pdfFont = arg2;\n }\n else if (typeof arg1 === 'string' && arg2 instanceof PdfFont && arg3 instanceof PdfPen && typeof arg4 === 'undefined') {\n _this = _super.call(this) || this;\n _this.content = arg1;\n _this.elementValue = arg1;\n _this.pdfFont = arg2;\n _this.pdfPen = arg3;\n }\n else if (typeof arg1 === 'string' && arg2 instanceof PdfFont && arg3 instanceof PdfBrush && typeof arg4 === 'undefined') {\n _this = _super.call(this) || this;\n _this.content = arg1;\n _this.elementValue = arg1;\n _this.pdfFont = arg2;\n _this.pdfBrush = arg3;\n }\n else {\n _this = _super.call(this) || this;\n _this.content = arg1;\n _this.elementValue = arg1;\n _this.pdfFont = arg2;\n _this.pdfPen = arg3;\n _this.pdfBrush = arg4;\n _this.format = arg5;\n }\n return _this;\n }\n Object.defineProperty(PdfTextElement.prototype, \"text\", {\n // Properties\n /**\n * Gets or sets a value indicating the `text` that should be printed.\n * ```typescript\n * // create a new PDF document.\n * let document : PdfDocument = new PdfDocument();\n * // add a page to the document.\n * let page1 : PdfPage = document.pages.add();\n * // create the font\n * let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12);\n * // create the Text Web Link\n * let textLink : PdfTextWebLink = new PdfTextWebLink();\n * // set the hyperlink\n * textLink.url = 'http://www.google.com';\n * //\n * // set the link text\n * textLink.text = 'Google';\n * //\n * // set the font\n * textLink.font = font;\n * // draw the hyperlink in PDF page\n * textLink.draw(page1, new PointF(10, 40));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n return this.content;\n },\n set: function (value) {\n this.elementValue = value;\n this.content = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTextElement.prototype, \"value\", {\n //get value\n /**\n * Gets or sets a `value` indicating the text that should be printed.\n * @private\n */\n get: function () {\n return this.elementValue;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTextElement.prototype, \"pen\", {\n //get pen\n /**\n * Gets or sets a `PdfPen` that determines the color, width, and style of the text\n * @private\n */\n get: function () {\n return this.pdfPen;\n },\n //Set pen value\n set: function (value) {\n this.pdfPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTextElement.prototype, \"brush\", {\n //get brush\n /**\n * Gets or sets the `PdfBrush` that will be used to draw the text with color and texture.\n * @private\n */\n get: function () {\n return this.pdfBrush;\n },\n //Set brush value\n set: function (value) {\n this.pdfBrush = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTextElement.prototype, \"font\", {\n //get font\n /**\n * Gets or sets a `PdfFont` that defines the text format.\n * ```typescript\n * // create a new PDF document.\n * let document : PdfDocument = new PdfDocument();\n * // add a page to the document.\n * let page1 : PdfPage = document.pages.add();\n * // create the font\n * let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12);\n * // create the Text Web Link\n * let textLink : PdfTextWebLink = new PdfTextWebLink();\n * // set the hyperlink\n * textLink.url = 'http://www.google.com';\n * // set the link text\n * textLink.text = 'Google';\n * //\n * // set the font\n * textLink.font = font;\n * //\n * // draw the hyperlink in PDF page\n * textLink.draw(page1, new PointF(10, 40));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n return this.pdfFont;\n },\n set: function (value) {\n this.pdfFont = value;\n if (this.pdfFont instanceof PdfStandardFont && this.content != null) {\n this.elementValue = PdfStandardFont.convert(this.content);\n }\n else {\n this.elementValue = this.content;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTextElement.prototype, \"stringFormat\", {\n /**\n * Gets or sets the `PdfStringFormat` that will be used to set the string format\n * @private\n */\n get: function () {\n return this.format;\n },\n set: function (value) {\n this.format = value;\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * Gets a `brush` for drawing.\n * @private\n */\n PdfTextElement.prototype.getBrush = function () {\n return (this.pdfBrush == null || typeof this.pdfBrush === 'undefined') ? new PdfSolidBrush(new PdfColor(0, 0, 0)) : this.pdfBrush;\n };\n // /**\n // * `Draws` an element on the Graphics.\n // * @private\n // */\n // public drawInternal(graphics : PdfGraphics) : void {\n // graphics.drawString(this.elementValue, this.pdfFont, this.pdfPen, this.getBrush(), 0, 0, this.stringFormat);\n // }\n /**\n * `Layouts` the element.\n * @private\n */\n PdfTextElement.prototype.layout = function (param) {\n var layouter = new TextLayouter(this);\n var result = layouter.layout(param);\n return result;\n };\n PdfTextElement.prototype.drawText = function (arg2, arg3, arg4, arg5) {\n if (arg3 instanceof PointF && typeof arg3.width === 'undefined' && typeof arg4 === 'undefined') {\n this.hasPointOverload = true;\n return this.drawText(arg2, arg3.x, arg3.y);\n }\n else if (typeof arg3 === 'number' && typeof arg4 === 'number' && typeof arg5 === 'undefined') {\n this.hasPointOverload = true;\n return this.drawText(arg2, arg3, arg4, null);\n }\n else if (arg3 instanceof RectangleF && typeof arg3.width !== 'undefined' && typeof arg4 === 'undefined') {\n return this.drawText(arg2, arg3, null);\n }\n else if (arg3 instanceof PointF && typeof arg3.width === 'undefined' && arg4 instanceof PdfLayoutFormat) {\n this.hasPointOverload = true;\n return this.drawText(arg2, arg3.x, arg3.y, arg4);\n }\n else if (typeof arg3 === 'number' && typeof arg4 === 'number' && (arg5 instanceof PdfLayoutFormat || arg5 == null)) {\n this.hasPointOverload = true;\n var width = (arg2.graphics.clientSize.width - arg3);\n var layoutRectangle = new RectangleF(arg3, arg4, width, 0);\n return this.drawText(arg2, layoutRectangle, arg5);\n }\n else if (arg3 instanceof RectangleF && typeof arg3.width !== 'undefined' && typeof arg4 === 'boolean') {\n return this.drawText(arg2, arg3, null);\n }\n else {\n var layout = new PdfStringLayouter();\n if (this.hasPointOverload) {\n var stringLayoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF((arg2.graphics.clientSize.width - arg3.x), 0), true, arg2.graphics.clientSize);\n var layoutResult = void 0;\n var param = new PdfLayoutParams();\n var temparg3 = arg3;\n var temparg4 = arg4;\n param.page = arg2;\n var previousPage = arg2;\n param.bounds = temparg3;\n param.format = (temparg4 != null) ? temparg4 : new PdfLayoutFormat();\n if (stringLayoutResult.lines.length > 1) {\n this.text = stringLayoutResult.layoutLines[0].text;\n if (param.bounds.y <= param.page.graphics.clientSize.height) {\n var previousPosition = new PointF(param.bounds.x, param.bounds.y);\n layoutResult = this.layout(param);\n var bounds = new RectangleF(0, layoutResult.bounds.y + stringLayoutResult.lineHeight, arg2.graphics.clientSize.width, stringLayoutResult.lineHeight);\n var isPaginate = false;\n for (var i = 1; i < stringLayoutResult.lines.length; i++) {\n param.page = layoutResult.page;\n param.bounds = new RectangleF(new PointF(bounds.x, bounds.y), new SizeF(bounds.width, bounds.height));\n this.text = stringLayoutResult.layoutLines[i].text;\n if (bounds.y + stringLayoutResult.lineHeight > layoutResult.page.graphics.clientSize.height) {\n isPaginate = true;\n param.page = param.page.graphics.getNextPage();\n if (previousPosition.y > (layoutResult.page.graphics.clientSize.height - layoutResult.bounds.height)) {\n bounds = new RectangleF(0, layoutResult.bounds.height, layoutResult.page.graphics.clientSize.width, stringLayoutResult.lineHeight);\n }\n else {\n bounds = new RectangleF(0, 0, layoutResult.page.graphics.clientSize.width, stringLayoutResult.lineHeight);\n }\n param.bounds = bounds;\n }\n layoutResult = this.layout(param);\n if (i !== (stringLayoutResult.lines.length - 1)) {\n bounds = new RectangleF(0, layoutResult.bounds.y + stringLayoutResult.lineHeight, layoutResult.page.graphics.clientSize.width, stringLayoutResult.lineHeight);\n }\n else {\n var lineWidth = this.font.measureString(this.text, this.format).width;\n layoutResult = this.calculateResultBounds(layoutResult, lineWidth, layoutResult.page.graphics.clientSize.width, 0);\n }\n }\n }\n return layoutResult;\n }\n else {\n var lineSize = this.font.measureString(this.text, this.format);\n if (param.bounds.y <= param.page.graphics.clientSize.height) {\n layoutResult = this.layout(param);\n layoutResult = this.calculateResultBounds(layoutResult, lineSize.width, layoutResult.page.graphics.clientSize.width, 0);\n }\n return layoutResult;\n }\n }\n else {\n var layoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF(arg3.width, 0), false, arg2.graphics.clientSize);\n var result = void 0;\n var param = new PdfLayoutParams();\n var temparg3 = arg3;\n var temparg4 = arg4;\n param.page = arg2;\n param.bounds = temparg3;\n param.format = (temparg4 != null) ? temparg4 : new PdfLayoutFormat();\n if (layoutResult.lines.length > 1) {\n this.text = layoutResult.layoutLines[0].text;\n if (param.bounds.y <= param.page.graphics.clientSize.height) {\n var previousPosition = new PointF(param.bounds.x, param.bounds.y);\n result = this.layout(param);\n var bounds = new RectangleF(temparg3.x, result.bounds.y + layoutResult.lineHeight, temparg3.width, layoutResult.lineHeight);\n var isPaginate = false;\n for (var i = 1; i < layoutResult.lines.length; i++) {\n param.page = result.page;\n param.bounds = new RectangleF(bounds.x, bounds.y, bounds.width, bounds.height);\n this.text = layoutResult.layoutLines[i].text;\n if (bounds.y + layoutResult.lineHeight > result.page.graphics.clientSize.height) {\n isPaginate = true;\n param.page = param.page.graphics.getNextPage();\n if (previousPosition.y > (result.page.graphics.clientSize.height - result.bounds.height)) {\n bounds = new RectangleF(temparg3.x, layoutResult.lineHeight, temparg3.width, layoutResult.lineHeight);\n }\n else {\n bounds = new RectangleF(temparg3.x, 0, temparg3.width, layoutResult.lineHeight);\n }\n param.bounds = bounds;\n }\n result = this.layout(param);\n if (i !== (layoutResult.lines.length - 1)) {\n bounds = new RectangleF(temparg3.x, result.bounds.y + layoutResult.lineHeight, temparg3.width, layoutResult.lineHeight);\n }\n else {\n var lineWidth = this.font.measureString(this.text, this.format).width;\n result = this.calculateResultBounds(result, lineWidth, temparg3.width, temparg3.x);\n }\n }\n }\n return result;\n }\n else {\n var lineSize = this.font.measureString(this.text, this.format);\n if (param.bounds.y <= param.page.graphics.clientSize.height) {\n result = this.layout(param);\n result = this.calculateResultBounds(result, lineSize.width, temparg3.width, temparg3.x);\n }\n return result;\n }\n }\n }\n };\n PdfTextElement.prototype.calculateResultBounds = function (result, lineWidth, maximumWidth, startPosition) {\n var shift = 0;\n if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Center) {\n result.bounds.x = startPosition + (maximumWidth - lineWidth) / 2;\n result.bounds.width = lineWidth;\n }\n else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Right) {\n result.bounds.x = startPosition + (maximumWidth - lineWidth);\n result.bounds.width = lineWidth;\n }\n else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Justify) {\n result.bounds.x = startPosition;\n result.bounds.width = maximumWidth;\n }\n else {\n result.bounds.width = startPosition;\n result.bounds.width = lineWidth;\n }\n return result;\n };\n return PdfTextElement;\n}(PdfLayoutElement));\nexport { PdfTextElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfActionLinkAnnotation } from './action-link-annotation';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfUriAction } from './../actions/uri-action';\n/**\n * `PdfUriAnnotation` class represents the Uri annotation.\n * @private\n */\nvar PdfUriAnnotation = /** @class */ (function (_super) {\n __extends(PdfUriAnnotation, _super);\n function PdfUriAnnotation(rectangle, uri) {\n var _this = _super.call(this, rectangle) || this;\n if (typeof uri !== 'undefined') {\n _this.uri = uri;\n }\n return _this;\n }\n Object.defineProperty(PdfUriAnnotation.prototype, \"uriAction\", {\n /**\n * Get `action` of the annotation.\n * @private\n */\n get: function () {\n if (typeof this.pdfUriAction === 'undefined') {\n this.pdfUriAction = new PdfUriAction();\n }\n return this.pdfUriAction;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfUriAnnotation.prototype, \"uri\", {\n // Properties\n /**\n * Gets or sets the `Uri` address.\n * @private\n */\n get: function () {\n return this.uriAction.uri;\n },\n set: function (value) {\n if (this.uriAction.uri !== value) {\n this.uriAction.uri = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfUriAnnotation.prototype, \"action\", {\n /**\n * Gets or sets the `action`.\n * @private\n */\n get: function () {\n return this.getSetAction();\n },\n set: function (value) {\n this.getSetAction(value);\n this.uriAction.next = value;\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * `Initializes` annotation object.\n * @private\n */\n PdfUriAnnotation.prototype.initialize = function () {\n _super.prototype.initialize.call(this);\n this.dictionary.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.link));\n var tempPrimitive = this.uriAction.element;\n this.dictionary.items.setValue(this.dictionaryProperties.a, this.uriAction.element);\n };\n return PdfUriAnnotation;\n}(PdfActionLinkAnnotation));\nexport { PdfUriAnnotation };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfPage } from './../pages/pdf-page';\nimport { PointF, RectangleF, SizeF } from './../drawing/pdf-drawing';\nimport { PdfTextElement } from './../graphics/figures/text-element';\nimport { PdfUriAnnotation } from './uri-annotation';\nimport { PdfStringLayouter } from './../graphics/fonts/string-layouter';\nimport { PdfFontStyle } from './../graphics/fonts/enum';\nimport { PdfTextAlignment } from './../graphics/enum';\nimport { PdfArray } from './../primitives/pdf-array';\nimport { PdfNumber } from './../primitives/pdf-number';\n/**\n * `PdfTextWebLink` class represents the class for text web link annotation.\n * ```typescript\n * // create a new PDF document.\n * let document : PdfDocument = new PdfDocument();\n * // add a page to the document.\n * let page1 : PdfPage = document.pages.add();\n * // create the font\n * let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12);\n * //\n * // create the Text Web Link\n * let textLink : PdfTextWebLink = new PdfTextWebLink();\n * // set the hyperlink\n * textLink.url = 'http://www.google.com';\n * // set the link text\n * textLink.text = 'Google';\n * // set the font\n * textLink.font = font;\n * // draw the hyperlink in PDF page\n * textLink.draw(page1, new PointF(10, 40));\n * //\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\nvar PdfTextWebLink = /** @class */ (function (_super) {\n __extends(PdfTextWebLink, _super);\n // Constructors\n /**\n * Initializes a new instance of the `PdfTextWebLink` class.\n * @private\n */\n function PdfTextWebLink() {\n var _this = _super.call(this) || this;\n // Fields\n /**\n * Internal variable to store `Url`.\n * @default ''\n * @private\n */\n _this.uniformResourceLocator = '';\n /**\n * Internal variable to store `Uri Annotation` object.\n * @default null\n * @private\n */\n _this.uriAnnotation = null;\n /**\n * Checks whether the drawTextWebLink method with `PointF` overload is called or not.\n * If it set as true, then the start position of each lines excluding firest line is changed as (0, Y).\n * @private\n * @hidden\n */\n _this.recalculateBounds = false;\n _this.defaultBorder = new PdfArray();\n for (var i = 0; i < 3; i++) {\n _this.defaultBorder.add(new PdfNumber(0));\n }\n return _this;\n }\n Object.defineProperty(PdfTextWebLink.prototype, \"url\", {\n // Properties\n /**\n * Gets or sets the `Uri address`.\n * ```typescript\n * // create a new PDF document.\n * let document : PdfDocument = new PdfDocument();\n * // add a page to the document.\n * let page1 : PdfPage = document.pages.add();\n * // create the font\n * let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12);\n * // create the Text Web Link\n * let textLink : PdfTextWebLink = new PdfTextWebLink();\n * //\n * // set the hyperlink\n * textLink.url = 'http://www.google.com';\n * //\n * // set the link text\n * textLink.text = 'Google';\n * // set the font\n * textLink.font = font;\n * // draw the hyperlink in PDF page\n * textLink.draw(page1, new PointF(10, 40));\n * // save the document.\n * document.save('output.pdf');\n * // destroy the document\n * document.destroy();\n * ```\n */\n get: function () {\n return this.uniformResourceLocator;\n },\n set: function (value) {\n if (value.length === 0) {\n throw new Error('ArgumentException : Url - string can not be empty');\n }\n this.uniformResourceLocator = value;\n },\n enumerable: true,\n configurable: true\n });\n PdfTextWebLink.prototype.draw = function (arg1, arg2) {\n if (arg1 instanceof PdfPage) {\n var layout = new PdfStringLayouter();\n var previousFontStyle = this.font.style;\n if (arg2 instanceof PointF) {\n this.recalculateBounds = true;\n this.font.style = PdfFontStyle.Underline;\n var layoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF((arg1.graphics.clientSize.width - arg2.x), 0), true, arg1.graphics.clientSize);\n if (layoutResult.lines.length === 1) {\n var textSize = this.font.measureString(this.value);\n var rect = new RectangleF(arg2, textSize);\n rect = this.calculateBounds(rect, textSize.width, arg1.graphics.clientSize.width, arg2.x);\n this.uriAnnotation = new PdfUriAnnotation(rect, this.url);\n this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder);\n arg1.annotations.add(this.uriAnnotation);\n var result = this.drawText(arg1, arg2);\n this.font.style = previousFontStyle;\n return result;\n }\n else {\n var result = this.drawMultipleLineWithPoint(layoutResult, arg1, arg2);\n this.font.style = previousFontStyle;\n return result;\n }\n }\n else {\n var layoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF(arg2.width, 0), false, new SizeF(0, 0));\n this.font.style = PdfFontStyle.Underline;\n if (layoutResult.lines.length === 1) {\n var textSize = this.font.measureString(this.value);\n var rect = new RectangleF(new PointF(arg2.x, arg2.y), textSize);\n rect = this.calculateBounds(rect, textSize.width, arg2.width, arg2.x);\n this.uriAnnotation = new PdfUriAnnotation(rect, this.url);\n this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder);\n arg1.annotations.add(this.uriAnnotation);\n var returnValue = this.drawText(arg1, arg2);\n this.font.style = previousFontStyle;\n return returnValue;\n }\n else {\n var returnValue = this.drawMultipleLineWithBounds(layoutResult, arg1, arg2);\n this.font.style = previousFontStyle;\n return returnValue;\n }\n }\n }\n else {\n var page = new PdfPage();\n page = arg1.page;\n return this.draw(page, arg2);\n }\n };\n /* tslint:enable */\n //Private methods\n /**\n * Helper method `Draw` a Multiple Line Text Web Link on the Graphics with the specified location.\n * @private\n */\n PdfTextWebLink.prototype.drawMultipleLineWithPoint = function (result, page, location) {\n var layoutResult;\n for (var i = 0; i < result.layoutLines.length; i++) {\n var size = this.font.measureString(result.lines[i].text);\n var bounds = new RectangleF(location, size);\n if (i !== 0) {\n bounds.x = 0;\n }\n this.text = result.lines[i].text;\n if (bounds.y + size.height > page.graphics.clientSize.height) {\n if (i !== 0) {\n page = page.graphics.getNextPage();\n bounds = new RectangleF(0, 0, page.graphics.clientSize.width, size.height);\n location.y = 0;\n }\n else {\n break;\n }\n }\n bounds = this.calculateBounds(bounds, size.width, page.graphics.clientSize.width, bounds.x);\n this.uriAnnotation = new PdfUriAnnotation(bounds, this.url);\n this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder);\n page.annotations.add(this.uriAnnotation);\n if (i !== 0) {\n layoutResult = this.drawText(page, new PointF(0, bounds.y));\n }\n else {\n layoutResult = this.drawText(page, bounds.x, bounds.y);\n }\n location.y += size.height;\n }\n return layoutResult;\n };\n /**\n * Helper method `Draw` a Multiple Line Text Web Link on the Graphics with the specified bounds.\n * @private\n */\n PdfTextWebLink.prototype.drawMultipleLineWithBounds = function (result, page, bounds) {\n var layoutResult;\n for (var i = 0; i < result.layoutLines.length; i++) {\n var size = this.font.measureString(result.lines[i].text);\n var internalBounds = new RectangleF(new PointF(bounds.x, bounds.y), size);\n internalBounds = this.calculateBounds(internalBounds, size.width, bounds.width, bounds.x);\n this.text = result.lines[i].text;\n if (bounds.y + size.height > page.graphics.clientSize.height) {\n if (i !== 0) {\n page = page.graphics.getNextPage();\n bounds = new RectangleF(bounds.x, 0, bounds.width, size.height);\n internalBounds.y = 0;\n }\n else {\n break;\n }\n }\n this.uriAnnotation = new PdfUriAnnotation(internalBounds, this.url);\n this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder);\n page.annotations.add(this.uriAnnotation);\n layoutResult = this.drawText(page, bounds);\n bounds.y += size.height;\n }\n return layoutResult;\n };\n /* tslint:disable */\n PdfTextWebLink.prototype.calculateBounds = function (currentBounds, lineWidth, maximumWidth, startPosition) {\n var shift = 0;\n if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Center) {\n currentBounds.x = startPosition + (maximumWidth - lineWidth) / 2;\n currentBounds.width = lineWidth;\n }\n else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Right) {\n currentBounds.x = startPosition + (maximumWidth - lineWidth);\n currentBounds.width = lineWidth;\n }\n else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Justify) {\n currentBounds.x = startPosition;\n currentBounds.width = maximumWidth;\n }\n else {\n currentBounds.width = startPosition;\n currentBounds.width = lineWidth;\n }\n return currentBounds;\n };\n return PdfTextWebLink;\n}(PdfTextElement));\nexport { PdfTextWebLink };\n","/**\n * PdfNumbersConvertor.ts class for EJ2-PDF\n * @private\n */\nimport { PdfNumberStyle } from './../../pages/enum';\n/**\n * `PdfNumbersConvertor` for convert page number into numbers, roman letters, etc.,\n * @private\n */\nvar PdfNumbersConvertor = /** @class */ (function () {\n function PdfNumbersConvertor() {\n }\n // Static methods\n /**\n * Convert string value from page number with correct format.\n * @private\n */\n PdfNumbersConvertor.convert = function (intArabic, numberStyle) {\n var result = '';\n switch (numberStyle) {\n case PdfNumberStyle.None:\n result = '';\n break;\n case PdfNumberStyle.Numeric:\n result = intArabic.toString();\n break;\n case PdfNumberStyle.LowerLatin:\n result = this.arabicToLetter(intArabic).toLowerCase();\n break;\n case PdfNumberStyle.LowerRoman:\n result = this.arabicToRoman(intArabic).toLowerCase();\n break;\n case PdfNumberStyle.UpperLatin:\n result = this.arabicToLetter(intArabic);\n break;\n case PdfNumberStyle.UpperRoman:\n result = this.arabicToRoman(intArabic);\n break;\n }\n return result;\n };\n /**\n * Converts `arabic to roman` letters.\n * @private\n */\n PdfNumbersConvertor.arabicToRoman = function (intArabic) {\n var retval = '';\n retval += this.generateNumber(intArabic, 1000, 'M');\n retval += this.generateNumber(intArabic, 900, 'CM');\n retval += this.generateNumber(intArabic, 500, 'D');\n retval += this.generateNumber(intArabic, 400, 'CD');\n retval += this.generateNumber(intArabic, 100, 'C');\n retval += this.generateNumber(intArabic, 90, 'XC');\n retval += this.generateNumber(intArabic, 50, 'L');\n retval += this.generateNumber(intArabic, 40, 'XL');\n retval += this.generateNumber(intArabic, 10, 'X');\n retval += this.generateNumber(intArabic, 9, 'IX');\n retval += this.generateNumber(intArabic, 5, 'V');\n retval += this.generateNumber(intArabic, 4, 'IV');\n retval += this.generateNumber(intArabic, 1, 'I');\n return retval.toString();\n };\n /**\n * Converts `arabic to normal letters`.\n * @private\n */\n PdfNumbersConvertor.arabicToLetter = function (arabic) {\n var stack = this.convertToLetter(arabic);\n var result = '';\n while (stack.length > 0) {\n var num = stack.pop();\n result = this.appendChar(result, num);\n }\n return result.toString();\n };\n /**\n * Generate a string value of an input number.\n * @private\n */\n PdfNumbersConvertor.generateNumber = function (value, magnitude, letter) {\n var numberstring = '';\n while (value >= magnitude) {\n value -= magnitude;\n numberstring += letter;\n }\n return numberstring.toString();\n };\n /**\n * Convert a input number into letters.\n * @private\n */\n PdfNumbersConvertor.convertToLetter = function (arabic) {\n if (arabic <= 0) {\n throw Error('ArgumentOutOfRangeException-arabic, Value can not be less 0');\n }\n var stack = [];\n while (arabic > this.letterLimit) {\n var remainder = arabic % this.letterLimit;\n if (remainder === 0.0) {\n arabic = arabic / this.letterLimit - 1;\n remainder = this.letterLimit;\n }\n else {\n arabic /= this.letterLimit;\n }\n stack.push(remainder);\n }\n stack.push(arabic);\n return stack;\n };\n /**\n * Convert number to actual string value.\n * @private\n */\n PdfNumbersConvertor.appendChar = function (builder, value) {\n var letter = String.fromCharCode(PdfNumbersConvertor.acsiiStartIndex + value);\n builder += letter;\n return builder;\n };\n // Fields\n /**\n * numbers of letters in english [readonly].\n * @default = 26.0\n * @private\n */\n PdfNumbersConvertor.letterLimit = 26.0;\n /**\n * Resturns `acsii start index` value.\n * @default 64\n * @private\n */\n PdfNumbersConvertor.acsiiStartIndex = (65 - 1);\n return PdfNumbersConvertor;\n}());\nexport { PdfNumbersConvertor };\n","/**\n * Represent class to store information about `template and value pairs`.\n * @private\n */\nvar PdfTemplateValuePair = /** @class */ (function () {\n function PdfTemplateValuePair(template, value) {\n // Fields\n /**\n * Internal variable to store template.\n * @default null\n * @private\n */\n this.pdfTemplate = null;\n /**\n * Intenal variable to store value.\n * @private\n */\n this.content = '';\n if (typeof template === 'undefined') {\n //\n }\n else {\n this.template = template;\n this.value = value;\n }\n }\n Object.defineProperty(PdfTemplateValuePair.prototype, \"template\", {\n // Properties\n /**\n * Gets or sets the template.\n * @private\n */\n get: function () {\n return this.pdfTemplate;\n },\n set: function (value) {\n this.pdfTemplate = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfTemplateValuePair.prototype, \"value\", {\n /**\n * Gets or sets the value.\n * @private\n */\n get: function () {\n return this.content;\n },\n set: function (value) {\n this.content = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfTemplateValuePair;\n}());\nexport { PdfTemplateValuePair };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfAutomaticField.ts class for EJ2-PDF\n */\nimport { PdfAutomaticField } from './automatic-field';\nimport { TemporaryDictionary } from './../../collections/object-object-pair/dictionary';\nimport { PdfTemplateValuePair } from './pdf-template-value-pair';\nimport { SizeF, PointF } from './../../drawing/pdf-drawing';\nimport { PdfTemplate } from './../../graphics/figures/pdf-template';\n/**\n * Represents automatic field which has the same value within the `PdfGraphics`.\n */\nvar PdfMultipleValueField = /** @class */ (function (_super) {\n __extends(PdfMultipleValueField, _super);\n function PdfMultipleValueField() {\n var _this = _super.call(this) || this;\n // Fields\n /**\n * Stores the instance of dictionary values of `graphics and template value pair`.\n * @private\n */\n _this.list = new TemporaryDictionary();\n return _this;\n }\n // Implementation\n /* tslint:disable */\n PdfMultipleValueField.prototype.performDraw = function (graphics, location, scalingX, scalingY) {\n _super.prototype.performDrawHelper.call(this, graphics, location, scalingX, scalingY);\n var value = this.getValue(graphics);\n var template = new PdfTemplate(this.getSize());\n this.list.setValue(graphics, new PdfTemplateValuePair(template, value));\n var g = template.graphics;\n var size = this.getSize();\n template.graphics.drawString(value, this.getFont(), this.pen, this.getBrush(), 0, 0, size.width, size.height, this.stringFormat);\n var drawLocation = new PointF(location.x + this.location.x, location.y + this.location.y);\n graphics.drawPdfTemplate(template, drawLocation, new SizeF(template.width * scalingX, template.height * scalingY));\n };\n return PdfMultipleValueField;\n}(PdfAutomaticField));\nexport { PdfMultipleValueField };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfBrush } from './../../graphics/brushes/pdf-brush';\nimport { PdfNumberStyle } from './../../pages/enum';\nimport { PdfNumbersConvertor } from './pdf-numbers-convertor';\nimport { PdfMultipleValueField } from './multiple-value-field';\n/**\n * Represents PDF document `page number field`.\n * @public\n */\nvar PdfPageNumberField = /** @class */ (function (_super) {\n __extends(PdfPageNumberField, _super);\n function PdfPageNumberField(font, arg2) {\n var _this = _super.call(this) || this;\n // Fields\n /**\n * Stores the number style of the page number field.\n * @private\n */\n _this.internalNumberStyle = PdfNumberStyle.Numeric;\n if (typeof arg2 === 'undefined') {\n _this.font = font;\n }\n else if (arg2 instanceof PdfBrush) {\n _this.font = font;\n _this.brush = arg2;\n }\n else {\n _this.font = font;\n _this.bounds = arg2;\n }\n return _this;\n }\n Object.defineProperty(PdfPageNumberField.prototype, \"numberStyle\", {\n // Properties\n /**\n * Gets and sets the number style of the page number field.\n * @private\n */\n get: function () {\n return this.internalNumberStyle;\n },\n set: function (value) {\n this.internalNumberStyle = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Return the `string` value of page number field.\n * @public\n */\n PdfPageNumberField.prototype.getValue = function (graphics) {\n var result = null;\n var page = this.getPageFromGraphics(graphics);\n result = this.internalGetValue(page);\n return result;\n };\n /**\n * Internal method to `get actual value of page number`.\n * @private\n */\n PdfPageNumberField.prototype.internalGetValue = function (page) {\n var document = page.document;\n var pageIndex = document.pages.indexOf(page) + 1;\n return PdfNumbersConvertor.convert(pageIndex, this.numberStyle);\n };\n return PdfPageNumberField;\n}(PdfMultipleValueField));\nexport { PdfPageNumberField };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfCompositeField.ts class for EJ2-PDF\n */\nimport { PdfMultipleValueField } from './multiple-value-field';\n/**\n * Represents class which can concatenate multiple automatic fields into single string.\n */\nvar PdfCompositeField = /** @class */ (function (_super) {\n __extends(PdfCompositeField, _super);\n // Constructor\n /**\n * Initialize a new instance of `PdfCompositeField` class.\n * @param font Font of the field.\n * @param brush Color of the field.\n * @param text Content of the field.\n * @param list List of the automatic fields in specific order based on the text content.\n */\n function PdfCompositeField(font, brush, text) {\n var list = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n list[_i - 3] = arguments[_i];\n }\n var _this = _super.call(this) || this;\n // Fields\n /**\n * Stores the array of automatic fields.\n * @private\n */\n _this.internalAutomaticFields = null;\n /**\n * Stores the text value of the field.\n * @private\n */\n _this.internalText = '';\n _this.font = font;\n _this.brush = brush;\n _this.text = text;\n _this.automaticFields = list;\n return _this;\n }\n Object.defineProperty(PdfCompositeField.prototype, \"text\", {\n // Properties\n /**\n * Gets and sets the content of the field.\n * @public\n */\n get: function () {\n return this.internalText;\n },\n set: function (value) {\n this.internalText = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfCompositeField.prototype, \"automaticFields\", {\n /**\n * Gets and sets the list of the field to drawn.\n * @public\n */\n get: function () {\n return this.internalAutomaticFields;\n },\n set: function (value) {\n this.internalAutomaticFields = value;\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * Return the actual value generated from the list of automatic fields.\n * @public\n */\n PdfCompositeField.prototype.getValue = function (graphics) {\n var values = [];\n var text = this.text.toString();\n if (typeof this.automaticFields !== 'undefined' && this.automaticFields != null && this.automaticFields.length > 0) {\n for (var i = 0; i < this.automaticFields.length; i++) {\n var automaticField = this.automaticFields[i];\n text = text.replace('{' + i + '}', automaticField.getValue(graphics));\n }\n }\n return text;\n };\n return PdfCompositeField;\n}(PdfMultipleValueField));\nexport { PdfCompositeField };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfSingleValueField.ts class for EJ2-PDF\n */\nimport { PdfAutomaticField } from './automatic-field';\nimport { TemporaryDictionary } from './../../collections/object-object-pair/dictionary';\nimport { PdfTemplateValuePair } from './pdf-template-value-pair';\nimport { PointF, SizeF } from './../../drawing/pdf-drawing';\nimport { PdfTemplate } from './../../graphics/figures/pdf-template';\n/**\n * Represents automatic field which has the same value in the whole document.\n */\nvar PdfSingleValueField = /** @class */ (function (_super) {\n __extends(PdfSingleValueField, _super);\n // Constructors\n function PdfSingleValueField() {\n var _this = _super.call(this) || this;\n // Fields\n /* tslint:disable */\n _this.list = new TemporaryDictionary();\n /* tslint:enable */\n _this.painterGraphics = [];\n return _this;\n }\n PdfSingleValueField.prototype.performDraw = function (graphics, location, scalingX, scalingY) {\n _super.prototype.performDrawHelper.call(this, graphics, location, scalingX, scalingY);\n var page = this.getPageFromGraphics(graphics);\n var document = page.document;\n var textValue = this.getValue(graphics);\n /* tslint:disable */\n if (this.list.containsKey(document)) {\n var pair = this.list.getValue(document);\n var drawLocation = new PointF(location.x + this.location.x, location.y + this.location.y);\n graphics.drawPdfTemplate(pair.template, drawLocation, new SizeF(pair.template.width * scalingX, pair.template.height * scalingY));\n this.painterGraphics.push(graphics);\n }\n else {\n var size = this.getSize();\n var template = new PdfTemplate(size);\n this.list.setValue(document, new PdfTemplateValuePair(template, textValue));\n template.graphics.drawString(textValue, this.getFont(), this.pen, this.getBrush(), 0, 0, size.width, size.height, this.stringFormat);\n var drawLocation = new PointF(location.x + this.location.x, location.y + this.location.y);\n graphics.drawPdfTemplate(template, drawLocation, new SizeF(template.width * scalingX, template.height * scalingY));\n this.painterGraphics.push(graphics);\n }\n /* tslint:enable */\n };\n return PdfSingleValueField;\n}(PdfAutomaticField));\nexport { PdfSingleValueField };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfPageCountField.ts class for EJ2-PDF\n */\nimport { PdfSingleValueField } from './single-value-field';\nimport { PdfNumberStyle } from './../../pages/enum';\nimport { PdfBrush } from './../../graphics/brushes/pdf-brush';\nimport { PdfNumbersConvertor } from './pdf-numbers-convertor';\n/**\n * Represents total PDF document page count automatic field.\n */\nvar PdfPageCountField = /** @class */ (function (_super) {\n __extends(PdfPageCountField, _super);\n function PdfPageCountField(font, arg2) {\n var _this = _super.call(this) || this;\n // Fields\n /**\n * Stores the number style of the field.\n * @private\n */\n _this.internalNumberStyle = PdfNumberStyle.Numeric;\n if (typeof arg2 === 'undefined') {\n _this.font = font;\n }\n else if (arg2 instanceof PdfBrush) {\n _this.font = font;\n _this.brush = arg2;\n }\n else {\n _this.font = font;\n _this.bounds = arg2;\n }\n return _this;\n }\n Object.defineProperty(PdfPageCountField.prototype, \"numberStyle\", {\n // Properties\n /**\n * Gets and sets the number style of the field.\n * @public\n */\n get: function () {\n return this.internalNumberStyle;\n },\n set: function (value) {\n this.internalNumberStyle = value;\n },\n enumerable: true,\n configurable: true\n });\n // Implementation\n /**\n * Return the actual value of the content to drawn.\n * @public\n */\n PdfPageCountField.prototype.getValue = function (graphics) {\n var result = null;\n var page = this.getPageFromGraphics(graphics);\n var document = page.section.parent.document;\n var count = document.pages.count;\n result = PdfNumbersConvertor.convert(count, this.numberStyle);\n return result;\n };\n return PdfPageCountField;\n}(PdfSingleValueField));\nexport { PdfPageCountField };\n","import { PointF, RectangleF } from './../drawing/pdf-drawing';\nimport { PdfArray } from './../primitives/pdf-array';\nimport { PdfPageRotateAngle } from './../pages/enum';\nimport { PdfDestinationMode } from './../general/enum';\nimport { PdfReferenceHolder } from './../primitives/pdf-reference';\nimport { PdfName } from './../primitives/pdf-name';\nimport { PdfNumber } from './../primitives/pdf-number';\nimport { DictionaryProperties } from './../input-output/pdf-dictionary-properties';\n/**\n * `PdfDestination` class represents an anchor in the document\n * where bookmarks or annotations can direct when clicked.\n */\nvar PdfDestination = /** @class */ (function () {\n function PdfDestination(arg1, arg2) {\n // Fields\n /**\n * Internal variable for accessing fields from `DictionryProperties` class.\n * @private\n */\n this.dictionaryProperties = new DictionaryProperties();\n /**\n * Type of the `destination`.\n * @private\n */\n this.destinationMode = PdfDestinationMode.Location;\n /**\n * `Zoom` factor.\n * @private\n * @default 0\n */\n this.zoomFactor = 0;\n /**\n * `Location` of the destination.\n * @default new PointF() with 0 ,0 as co-ordinates\n * @private\n */\n this.destinationLocation = new PointF(0, 0);\n /**\n * `Bounds` of the destination as RectangleF.\n * @default RectangleF.Empty\n * @private\n */\n this.bounds = new RectangleF();\n /**\n * Pdf primitive representing `this` object.\n * @private\n */\n this.array = new PdfArray();\n if (typeof arg2 === 'undefined') {\n var angle = PdfPageRotateAngle.RotateAngle0;\n this.destinationLocation = new PointF(0, this.destinationLocation.y);\n this.pdfPage = arg1;\n }\n else if (arg2 instanceof PointF) {\n this.constructor(arg1);\n this.destinationLocation = arg2;\n }\n else {\n this.constructor(arg1);\n this.bounds = arg2;\n }\n }\n Object.defineProperty(PdfDestination.prototype, \"zoom\", {\n // Properties\n /**\n * Gets and Sets the `zoom` factor.\n * @private\n */\n get: function () {\n return this.zoomFactor;\n },\n set: function (value) {\n this.zoomFactor = value;\n this.initializePrimitive();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDestination.prototype, \"page\", {\n /**\n * Gets and Sets the `page` object.\n * @private\n */\n get: function () {\n return this.pdfPage;\n },\n set: function (value) {\n this.pdfPage = value;\n this.initializePrimitive();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDestination.prototype, \"mode\", {\n /**\n * Gets and Sets the destination `mode`.\n * @private\n */\n get: function () {\n return this.destinationMode;\n },\n set: function (value) {\n this.destinationMode = value;\n this.initializePrimitive();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfDestination.prototype, \"location\", {\n /**\n * Gets and Sets the `location`.\n * @private\n */\n get: function () {\n return this.destinationLocation;\n },\n set: function (value) {\n this.destinationLocation = value;\n this.initializePrimitive();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Translates` co-ordinates to PDF co-ordinate system (lower/left).\n * @private\n */\n PdfDestination.prototype.pointToNativePdf = function (page, point) {\n var section = page.section;\n return section.pointToNativePdf(page, point);\n };\n /**\n * `In fills` array by correct values.\n * @private\n */\n PdfDestination.prototype.initializePrimitive = function () {\n this.array.clear();\n this.array.add(new PdfReferenceHolder(this.pdfPage));\n switch (this.destinationMode) {\n case PdfDestinationMode.Location:\n var simplePage = this.pdfPage;\n var point = new PointF();\n point = this.pointToNativePdf(simplePage, this.destinationLocation);\n this.array.add(new PdfName(this.dictionaryProperties.xyz));\n this.array.add(new PdfNumber(point.x));\n this.array.add(new PdfNumber(point.y));\n this.array.add(new PdfNumber(this.zoomFactor));\n break;\n case PdfDestinationMode.FitToPage:\n this.array.add(new PdfName(this.dictionaryProperties.fit));\n break;\n }\n };\n Object.defineProperty(PdfDestination.prototype, \"element\", {\n /**\n * Gets the `element` representing this object.\n * @private\n */\n get: function () {\n this.initializePrimitive();\n return this.array;\n },\n enumerable: true,\n configurable: true\n });\n return PdfDestination;\n}());\nexport { PdfDestination };\n","/**\n * public Enum for `PdfBorderOverlapStyle`.\n * @private\n */\nexport var PdfBorderOverlapStyle;\n(function (PdfBorderOverlapStyle) {\n /**\n * Specifies the type of `Overlap`.\n * @private\n */\n PdfBorderOverlapStyle[PdfBorderOverlapStyle[\"Overlap\"] = 0] = \"Overlap\";\n /**\n * Specifies the type of `Inside`.\n * @private\n */\n PdfBorderOverlapStyle[PdfBorderOverlapStyle[\"Inside\"] = 1] = \"Inside\";\n})(PdfBorderOverlapStyle || (PdfBorderOverlapStyle = {}));\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfTrueTypeFont.ts class for EJ2-PDF\n */\nimport { UnicodeTrueTypeFont } from './unicode-true-type-font';\nimport { PdfFont } from './pdf-font';\nimport { PdfFontStyle } from './enum';\nimport { PdfDocument } from './../../document/pdf-document';\n//https://www.giftofspeed.com/base64-encoder/\nvar PdfTrueTypeFont = /** @class */ (function (_super) {\n __extends(PdfTrueTypeFont, _super);\n function PdfTrueTypeFont(base64String, size, style) {\n var _this = _super.call(this, size) || this;\n /**\n * Indicates whether the font is embedded or not.\n * @private\n */\n _this.isEmbedFont = false;\n /**\n * Indicates whether the font is unicoded or not.\n * @private\n */\n _this.isUnicode = true;\n if (style !== undefined) {\n _this.createFontInternal(base64String, style);\n }\n else {\n _this.createFontInternal(base64String, PdfFontStyle.Regular);\n }\n return _this;\n }\n PdfTrueTypeFont.prototype.equalsToFont = function (font) {\n var result = false;\n //let result : boolean = this.fontInternal.equalsToFont(font);\n return result;\n };\n PdfTrueTypeFont.prototype.getLineWidth = function (line, format) {\n var width = 0;\n // width = this.fontInternal.getLineWidth(line);\n // let size : number = metrics.getSize(format);\n // width *= (PdfFont.charSizeMultiplier * size);\n // width = this.applyFormatSettings(line, format, width);\n return width;\n };\n /**\n * Returns width of the char.\n */\n PdfTrueTypeFont.prototype.getCharWidth = function (charCode, format) {\n var codeWidth = this.fontInternal.getCharWidth(charCode);\n var size = this.metrics.getSize(format);\n codeWidth *= (0.001 * size);\n return codeWidth;\n };\n //Implementation\n PdfTrueTypeFont.prototype.createFontInternal = function (base64String, style) {\n this.fontInternal = new UnicodeTrueTypeFont(base64String, this.size);\n this.calculateStyle(style);\n this.initializeInternals();\n };\n PdfTrueTypeFont.prototype.calculateStyle = function (style) {\n var iStyle = this.fontInternal.ttfMetrics.macStyle;\n if ((style & PdfFontStyle.Underline) !== 0) {\n iStyle |= PdfFontStyle.Underline;\n }\n if ((style & PdfFontStyle.Strikeout) !== 0) {\n iStyle |= PdfFontStyle.Strikeout;\n }\n this.setStyle(iStyle);\n };\n PdfTrueTypeFont.prototype.initializeInternals = function () {\n var equalFont = null;\n if (PdfDocument.enableCache) {\n // Search for the similar fonts.\n equalFont = PdfDocument.cache.search(this);\n }\n var internals = null;\n // There is not equal font in the cache.\n if (equalFont !== null && equalFont !== undefined) {\n // Get the settings from the cached font.\n internals = equalFont.getInternals();\n var metrics = equalFont.metrics;\n metrics = metrics.clone();\n metrics.size = this.size;\n this.metrics = metrics;\n this.fontInternal = equalFont.fontInternal;\n }\n else {\n if (equalFont == null) {\n if (this.fontInternal instanceof UnicodeTrueTypeFont) {\n this.fontInternal.isEmbed = this.isEmbedFont;\n }\n this.fontInternal.createInternals();\n internals = this.fontInternal.getInternals();\n this.metrics = this.fontInternal.metrics;\n }\n }\n this.metrics.isUnicodeFont = true;\n this.setInternals(internals);\n //this.ttfReader = (this.fontInternal as UnicodeTrueTypeFont).ttfReader;\n };\n /**\n * Stores used symbols.\n */\n PdfTrueTypeFont.prototype.setSymbols = function (text) {\n var internalFont = this.fontInternal;\n if (internalFont != null) {\n internalFont.setSymbols(text);\n }\n };\n return PdfTrueTypeFont;\n}(PdfFont));\nexport { PdfTrueTypeFont };\n","/**\n * PdfPageTemplateElement.ts class for EJ2-Pdf\n */\nimport { PdfDockStyle, PdfAlignmentStyle, TemplateType } from './enum';\nimport { PointF, SizeF } from './../drawing/pdf-drawing';\nimport { PdfTemplate } from './../graphics/figures/pdf-template';\nimport { PdfPage } from './pdf-page';\nimport { RectangleF } from './../drawing/pdf-drawing';\n/**\n * Describes a `page template` object that can be used as header/footer, watermark or stamp.\n */\nvar PdfPageTemplateElement = /** @class */ (function () {\n /* tslint:disable */\n function PdfPageTemplateElement(arg1, arg2, arg3, arg4, arg5) {\n if (arg1 instanceof RectangleF && typeof arg2 === 'undefined') {\n this.constructor(arg1.x, arg1.y, arg1.width, arg1.height);\n }\n else if (arg1 instanceof RectangleF && arg2 instanceof PdfPage && typeof arg3 === 'undefined') {\n this.constructor(arg1.x, arg1.y, arg1.width, arg1.height, arg2);\n }\n else if (arg1 instanceof PointF && arg2 instanceof SizeF && typeof arg3 === 'undefined') {\n this.constructor(arg1.x, arg1.y, arg2.width, arg2.height);\n }\n else if (arg1 instanceof PointF && arg2 instanceof SizeF && arg3 instanceof PdfPage && typeof arg4 === 'undefined') {\n this.constructor(arg1.x, arg1.y, arg2.width, arg2.height, arg3);\n }\n else if (arg1 instanceof SizeF && typeof arg2 === 'undefined') {\n this.constructor(arg1.width, arg1.height);\n }\n else if (typeof arg1 === 'number' && typeof arg2 === 'number' && typeof arg3 === 'undefined') {\n this.constructor(0, 0, arg1, arg2);\n }\n else if (typeof arg1 === 'number' && typeof arg2 === 'number' && arg3 instanceof PdfPage && typeof arg4 === 'undefined') {\n this.constructor(0, 0, arg1, arg2, arg3);\n }\n else if (typeof arg1 === 'number' && typeof arg2 === 'number' && typeof arg3 === 'number' && typeof arg4 === 'number' && typeof arg5 === 'undefined') {\n this.x = arg1;\n this.y = arg2;\n this.pdfTemplate = new PdfTemplate(arg3, arg4);\n }\n else {\n this.x = arg1;\n this.y = arg2;\n this.pdfTemplate = new PdfTemplate(arg3, arg4);\n // this.graphics.colorSpace = this.page.document.colorSpace;\n }\n /* tslint:enable */\n }\n Object.defineProperty(PdfPageTemplateElement.prototype, \"dock\", {\n // Properties\n /**\n * Gets or sets the `dock style` of the page template element.\n * @private\n */\n get: function () {\n return this.dockStyle;\n },\n set: function (value) {\n // if (this.dockStyle !== value && this.Type === TemplateType.None) {\n this.dockStyle = value;\n // Reset alignment.\n this.resetAlignment();\n // }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"alignment\", {\n /**\n * Gets or sets `alignment` of the page template element.\n * @private\n */\n get: function () {\n return this.alignmentStyle;\n },\n set: function (value) {\n // if (this.alignmentStyle !== value) {\n this.setAlignment(value);\n // }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"foreground\", {\n /**\n * Indicates whether the page template is located `in front of the page layers or behind of it`.\n * @private\n */\n get: function () {\n return this.isForeground;\n },\n set: function (value) {\n // if (this.foreground !== value) {\n this.isForeground = value;\n // }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"background\", {\n /**\n * Indicates whether the page template is located `behind of the page layers or in front of it`.\n * @private\n */\n get: function () {\n return !this.isForeground;\n },\n set: function (value) {\n this.isForeground = !value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"location\", {\n /**\n * Gets or sets `location` of the page template element.\n * @private\n */\n get: function () {\n return this.currentLocation;\n },\n set: function (value) {\n if (this.type === TemplateType.None) {\n this.currentLocation = value;\n }\n else {\n //\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"x\", {\n /**\n * Gets or sets `X` co-ordinate of the template element on the page.\n * @private\n */\n get: function () {\n var value = (typeof this.currentLocation !== 'undefined') ? this.currentLocation.x : 0;\n return value;\n },\n set: function (value) {\n if (this.type === TemplateType.None) {\n this.currentLocation.x = value;\n }\n else {\n //\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"y\", {\n /**\n * Gets or sets `Y` co-ordinate of the template element on the page.\n * @private\n */\n get: function () {\n var value = (typeof this.currentLocation !== 'undefined') ? this.currentLocation.y : 0;\n return value;\n },\n set: function (value) {\n if (this.type === TemplateType.None) {\n this.currentLocation.y = value;\n }\n else {\n //\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"size\", {\n /**\n * Gets or sets `size` of the page template element.\n * @private\n */\n get: function () {\n return this.template.size;\n },\n set: function (value) {\n if (this.type === TemplateType.None) {\n this.template.reset(value);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"width\", {\n /**\n * Gets or sets `width` of the page template element.\n * @private\n */\n get: function () {\n return this.template.width;\n },\n set: function (value) {\n if (this.template.width !== value && this.type === TemplateType.None) {\n var size = this.template.size;\n size.width = value;\n this.template.reset(size);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"height\", {\n /**\n * Gets or sets `height` of the page template element.\n * @private\n */\n get: function () {\n return this.template.height;\n },\n set: function (value) {\n if (this.template.height !== value && this.type === TemplateType.None) {\n var size = this.template.size;\n size.height = value;\n this.template.reset(size);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"graphics\", {\n /**\n * Gets `graphics` context of the page template element.\n * @private\n */\n get: function () {\n return this.template.graphics;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"template\", {\n /**\n * Gets Pdf `template` object.\n * @private\n */\n get: function () {\n // if (typeof this.pdfTemplate === 'undefined' || this.pdfTemplate == null) {\n // this.pdfTemplate = new PdfTemplate(this.size);\n // }\n return this.pdfTemplate;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"type\", {\n /**\n * Gets or sets `type` of the usage of this page template.\n * @private\n */\n get: function () {\n return this.templateType;\n },\n set: function (value) {\n this.updateDocking(value);\n this.templateType = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPageTemplateElement.prototype, \"bounds\", {\n /**\n * Gets or sets `bounds` of the page template.\n * @public\n */\n get: function () {\n return new RectangleF(new PointF(this.x, this.y), this.size);\n },\n set: function (value) {\n if (this.type === TemplateType.None) {\n this.location = new PointF(value.x, value.y);\n this.size = new SizeF(value.width, value.height);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * `Updates Dock` property if template is used as header/footer.\n * @private\n */\n PdfPageTemplateElement.prototype.updateDocking = function (type) {\n if (type !== TemplateType.None) {\n switch (type) {\n case TemplateType.Top:\n this.dock = PdfDockStyle.Top;\n break;\n case TemplateType.Bottom:\n this.dock = PdfDockStyle.Bottom;\n break;\n case TemplateType.Left:\n this.dock = PdfDockStyle.Left;\n break;\n case TemplateType.Right:\n this.dock = PdfDockStyle.Right;\n break;\n }\n this.resetAlignment();\n }\n };\n /**\n * `Resets alignment` of the template.\n * @private\n */\n PdfPageTemplateElement.prototype.resetAlignment = function () {\n this.alignment = PdfAlignmentStyle.None;\n };\n /**\n * `Sets alignment` of the template.\n * @private\n */\n PdfPageTemplateElement.prototype.setAlignment = function (alignment) {\n if (this.dock === PdfDockStyle.None) {\n this.alignmentStyle = alignment;\n }\n else {\n // Template is docked and alignment has been changed.\n var canBeSet = false;\n switch (this.dock) {\n case PdfDockStyle.Left:\n canBeSet = (alignment === PdfAlignmentStyle.TopLeft || alignment === PdfAlignmentStyle.MiddleLeft ||\n alignment === PdfAlignmentStyle.BottomLeft || alignment === PdfAlignmentStyle.None);\n break;\n case PdfDockStyle.Top:\n canBeSet = (alignment === PdfAlignmentStyle.TopLeft || alignment === PdfAlignmentStyle.TopCenter ||\n alignment === PdfAlignmentStyle.TopRight || alignment === PdfAlignmentStyle.None);\n break;\n case PdfDockStyle.Right:\n canBeSet = (alignment === PdfAlignmentStyle.TopRight || alignment === PdfAlignmentStyle.MiddleRight ||\n alignment === PdfAlignmentStyle.BottomRight || alignment === PdfAlignmentStyle.None);\n break;\n case PdfDockStyle.Bottom:\n canBeSet = (alignment === PdfAlignmentStyle.BottomLeft || alignment === PdfAlignmentStyle.BottomCenter\n || alignment === PdfAlignmentStyle.BottomRight || alignment === PdfAlignmentStyle.None);\n break;\n case PdfDockStyle.Fill:\n canBeSet = (alignment === PdfAlignmentStyle.MiddleCenter || alignment === PdfAlignmentStyle.None);\n break;\n }\n if (canBeSet) {\n this.alignmentStyle = alignment;\n }\n }\n };\n /**\n * Draws the template.\n * @private\n */\n PdfPageTemplateElement.prototype.draw = function (layer, document) {\n var page = layer.page;\n var bounds = this.calculateBounds(page, document);\n if (bounds.x === -0) {\n bounds.x = 0;\n }\n layer.graphics.drawPdfTemplate(this.template, new PointF(bounds.x, bounds.y), new SizeF(bounds.width, bounds.height));\n };\n /**\n * Calculates bounds of the page template.\n * @private\n */\n PdfPageTemplateElement.prototype.calculateBounds = function (page, document) {\n var result = this.bounds;\n if (this.alignmentStyle !== PdfAlignmentStyle.None) {\n result = this.getAlignmentBounds(page, document);\n }\n else if (this.dockStyle !== PdfDockStyle.None) {\n result = this.getDockBounds(page, document);\n }\n return result;\n };\n /**\n * Calculates bounds according to the alignment.\n * @private\n */\n PdfPageTemplateElement.prototype.getAlignmentBounds = function (page, document) {\n var result = this.bounds;\n if (this.type === TemplateType.None) {\n result = this.getSimpleAlignmentBounds(page, document);\n }\n else {\n result = this.getTemplateAlignmentBounds(page, document);\n }\n return result;\n };\n /**\n * Calculates bounds according to the alignment.\n * @private\n */\n PdfPageTemplateElement.prototype.getSimpleAlignmentBounds = function (page, document) {\n var bounds = this.bounds;\n var pdfSection = page.section;\n var actualBounds = pdfSection.getActualBounds(document, page, false);\n var x = this.x;\n var y = this.y;\n switch (this.alignmentStyle) {\n case PdfAlignmentStyle.TopLeft:\n x = 0;\n y = 0;\n break;\n case PdfAlignmentStyle.TopCenter:\n x = (actualBounds.width - this.width) / 2;\n y = 0;\n break;\n case PdfAlignmentStyle.TopRight:\n x = actualBounds.width - this.width;\n y = 0;\n break;\n case PdfAlignmentStyle.MiddleLeft:\n x = 0;\n y = (actualBounds.height - this.height) / 2;\n break;\n case PdfAlignmentStyle.MiddleCenter:\n x = (actualBounds.width - this.width) / 2;\n y = (actualBounds.height - this.height) / 2;\n break;\n case PdfAlignmentStyle.MiddleRight:\n x = actualBounds.width - this.width;\n y = (actualBounds.height - this.height) / 2;\n break;\n case PdfAlignmentStyle.BottomLeft:\n x = 0;\n y = actualBounds.height - this.height;\n break;\n case PdfAlignmentStyle.BottomCenter:\n x = (actualBounds.width - this.width) / 2;\n y = actualBounds.height - this.height;\n break;\n case PdfAlignmentStyle.BottomRight:\n x = actualBounds.width - this.width;\n y = actualBounds.height - this.height;\n break;\n }\n bounds.x = x;\n bounds.y = y;\n return bounds;\n };\n /**\n * Calculates bounds according to the alignment.\n * @private\n */\n PdfPageTemplateElement.prototype.getTemplateAlignmentBounds = function (page, document) {\n var result = this.bounds;\n var section = page.section;\n var actualBounds = section.getActualBounds(document, page, false);\n var x = this.x;\n var y = this.y;\n switch (this.alignmentStyle) {\n case PdfAlignmentStyle.TopLeft:\n if (this.type === TemplateType.Left) {\n x = -actualBounds.x;\n y = 0;\n }\n else if (this.type === TemplateType.Top) {\n x = -actualBounds.x;\n y = -actualBounds.y;\n }\n break;\n case PdfAlignmentStyle.TopCenter:\n x = (actualBounds.width - this.width) / 2;\n y = -actualBounds.y;\n break;\n case PdfAlignmentStyle.TopRight:\n if (this.type === TemplateType.Right) {\n x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;\n y = 0;\n }\n else if (this.type === TemplateType.Top) {\n x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;\n y = -actualBounds.y;\n }\n break;\n case PdfAlignmentStyle.MiddleLeft:\n x = -actualBounds.x;\n y = (actualBounds.height - this.height) / 2;\n break;\n case PdfAlignmentStyle.MiddleCenter:\n x = (actualBounds.width - this.width) / 2;\n y = (actualBounds.height - this.height) / 2;\n break;\n case PdfAlignmentStyle.MiddleRight:\n x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;\n y = (actualBounds.height - this.height) / 2;\n break;\n case PdfAlignmentStyle.BottomLeft:\n if (this.type === TemplateType.Left) {\n x = -actualBounds.x;\n y = actualBounds.height - this.height;\n }\n else if (this.type === TemplateType.Bottom) {\n x = -actualBounds.x;\n y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;\n }\n break;\n case PdfAlignmentStyle.BottomCenter:\n x = (actualBounds.width - this.width) / 2;\n y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;\n break;\n case PdfAlignmentStyle.BottomRight:\n if (this.type === TemplateType.Right) {\n x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;\n y = actualBounds.height - this.height;\n }\n else if (this.type === TemplateType.Bottom) {\n x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;\n y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;\n }\n break;\n }\n result.x = x;\n result.y = y;\n return result;\n };\n /**\n * Calculates bounds according to the docking.\n * @private\n */\n PdfPageTemplateElement.prototype.getDockBounds = function (page, document) {\n var result = this.bounds;\n if (this.type === TemplateType.None) {\n result = this.getSimpleDockBounds(page, document);\n }\n else {\n result = this.getTemplateDockBounds(page, document);\n }\n return result;\n };\n /**\n * Calculates bounds according to the docking.\n * @private\n */\n PdfPageTemplateElement.prototype.getSimpleDockBounds = function (page, document) {\n var result = this.bounds;\n var section = page.section;\n var actualBounds = section.getActualBounds(document, page, false);\n var x = this.x;\n var y = this.y;\n var width = this.width;\n var height = this.height;\n switch (this.dockStyle) {\n case PdfDockStyle.Left:\n x = 0;\n y = 0;\n width = this.width;\n height = actualBounds.height;\n break;\n case PdfDockStyle.Top:\n x = 0;\n y = 0;\n width = actualBounds.width;\n height = this.height;\n break;\n case PdfDockStyle.Right:\n x = actualBounds.width - this.width;\n y = 0;\n width = this.width;\n height = actualBounds.height;\n break;\n case PdfDockStyle.Bottom:\n x = 0;\n y = actualBounds.height - this.height;\n width = actualBounds.width;\n height = this.height;\n break;\n case PdfDockStyle.Fill:\n x = 0;\n x = 0;\n width = actualBounds.width;\n height = actualBounds.height;\n break;\n }\n result = new RectangleF(x, y, width, height);\n return result;\n };\n /**\n * Calculates template bounds basing on docking if template is a page template.\n * @private\n */\n PdfPageTemplateElement.prototype.getTemplateDockBounds = function (page, document) {\n var result = this.bounds;\n var section = page.section;\n var actualBounds = section.getActualBounds(document, page, false);\n var actualSize = section.pageSettings.getActualSize();\n var x = this.x;\n var y = this.y;\n var width = this.width;\n var height = this.height;\n switch (this.dockStyle) {\n case PdfDockStyle.Left:\n x = -actualBounds.x;\n y = 0;\n width = this.width;\n height = actualBounds.height;\n break;\n case PdfDockStyle.Top:\n x = -actualBounds.x;\n y = -actualBounds.y;\n width = actualSize.width;\n height = this.height;\n if (actualBounds.height < 0) {\n y = -actualBounds.y + actualSize.height;\n }\n break;\n case PdfDockStyle.Right:\n x = actualBounds.width + section.getRightIndentWidth(document, page, false) - this.width;\n y = 0;\n width = this.width;\n height = actualBounds.height;\n break;\n case PdfDockStyle.Bottom:\n x = -actualBounds.x;\n y = actualBounds.height + section.getBottomIndentHeight(document, page, false) - this.height;\n width = actualSize.width;\n height = this.height;\n if (actualBounds.height < 0) {\n y -= actualSize.height;\n }\n break;\n case PdfDockStyle.Fill:\n x = 0;\n x = 0;\n width = actualBounds.width;\n height = actualBounds.height;\n break;\n }\n result = new RectangleF(x, y, width, height);\n return result;\n };\n return PdfPageTemplateElement;\n}());\nexport { PdfPageTemplateElement };\n","/**\n * PdfBorders.ts class for EJ2-PDF\n */\nimport { PdfPen } from './../../../graphics/pdf-pen';\nimport { PdfDashStyle } from './../../../graphics/enum';\nimport { PdfColor } from './../../../graphics/pdf-color';\n/**\n * `PdfBorders` class used represents the cell border of the PDF grid.\n */\nvar PdfBorders = /** @class */ (function () {\n // Constructor\n /**\n * Create a new instance for `PdfBorders` class.\n * @private\n */\n function PdfBorders() {\n var defaultBorderPenLeft = new PdfPen(new PdfColor(0, 0, 0));\n defaultBorderPenLeft.dashStyle = PdfDashStyle.Solid;\n var defaultBorderPenRight = new PdfPen(new PdfColor(0, 0, 0));\n defaultBorderPenRight.dashStyle = PdfDashStyle.Solid;\n var defaultBorderPenTop = new PdfPen(new PdfColor(0, 0, 0));\n defaultBorderPenTop.dashStyle = PdfDashStyle.Solid;\n var defaultBorderPenBottom = new PdfPen(new PdfColor(0, 0, 0));\n defaultBorderPenBottom.dashStyle = PdfDashStyle.Solid;\n this.leftPen = defaultBorderPenLeft;\n this.rightPen = defaultBorderPenRight;\n this.topPen = defaultBorderPenTop;\n this.bottomPen = defaultBorderPenBottom;\n }\n Object.defineProperty(PdfBorders.prototype, \"left\", {\n // Properties\n /**\n * Gets or sets the `Left`.\n * @private\n */\n get: function () {\n return this.leftPen;\n },\n set: function (value) {\n this.leftPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBorders.prototype, \"right\", {\n /**\n * Gets or sets the `Right`.\n * @private\n */\n get: function () {\n return this.rightPen;\n },\n set: function (value) {\n this.rightPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBorders.prototype, \"top\", {\n /**\n * Gets or sets the `Top`.\n * @private\n */\n get: function () {\n return this.topPen;\n },\n set: function (value) {\n this.topPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBorders.prototype, \"bottom\", {\n /**\n * Gets or sets the `Bottom`.\n * @private\n */\n get: function () {\n return this.bottomPen;\n },\n set: function (value) {\n this.bottomPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBorders.prototype, \"all\", {\n /**\n * sets the `All`.\n * @private\n */\n set: function (value) {\n this.leftPen = this.rightPen = this.topPen = this.bottomPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBorders.prototype, \"isAll\", {\n /**\n * Gets a value indicating whether this instance `is all`.\n * @private\n */\n get: function () {\n return ((this.leftPen === this.rightPen) && (this.leftPen === this.topPen) && (this.leftPen === this.bottomPen));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfBorders, \"default\", {\n /**\n * Gets the `default`.\n * @private\n */\n get: function () {\n return new PdfBorders();\n },\n enumerable: true,\n configurable: true\n });\n return PdfBorders;\n}());\nexport { PdfBorders };\nvar PdfPaddings = /** @class */ (function () {\n function PdfPaddings(left, right, top, bottom) {\n if (typeof left === 'undefined') {\n //5.76 and 0 are taken from ms-word default table margins.\n this.leftPad = this.rightPad = 5.76;\n //0.5 is set for top and bottom by default.\n this.bottom = this.topPad = 0.5;\n }\n else {\n this.leftPad = left;\n this.rightPad = right;\n this.topPad = top;\n this.bottomPad = bottom;\n }\n }\n Object.defineProperty(PdfPaddings.prototype, \"left\", {\n // Properties\n /**\n * Gets or sets the `left` value of the edge\n * @private\n */\n get: function () {\n return this.leftPad;\n },\n set: function (value) {\n this.leftPad = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPaddings.prototype, \"right\", {\n /**\n * Gets or sets the `right` value of the edge.\n * @private\n */\n get: function () {\n return this.rightPad;\n },\n set: function (value) {\n this.rightPad = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPaddings.prototype, \"top\", {\n /**\n * Gets or sets the `top` value of the edge\n * @private\n */\n get: function () {\n return this.topPad;\n },\n set: function (value) {\n this.topPad = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPaddings.prototype, \"bottom\", {\n /**\n * Gets or sets the `bottom` value of the edge.\n * @private\n */\n get: function () {\n return this.bottomPad;\n },\n set: function (value) {\n this.bottomPad = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfPaddings.prototype, \"all\", {\n /**\n * Sets value to all sides `left,right,top and bottom`.s\n * @private\n */\n set: function (value) {\n this.leftPad = this.rightPad = this.topPad = this.bottomPad = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfPaddings;\n}());\nexport { PdfPaddings };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PdfBorders, PdfPaddings } from './pdf-borders';\nimport { PdfBorderOverlapStyle } from './../../tables/light-tables/enum';\n/**\n * Base class for the `grid style`,\n */\nvar PdfGridStyleBase = /** @class */ (function () {\n function PdfGridStyleBase() {\n }\n Object.defineProperty(PdfGridStyleBase.prototype, \"backgroundBrush\", {\n // Properties\n /**\n * Gets or sets the `background brush`.\n * @private\n */\n get: function () {\n return this.gridBackgroundBrush;\n },\n set: function (value) {\n this.gridBackgroundBrush = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridStyleBase.prototype, \"textBrush\", {\n /**\n * Gets or sets the `text brush`.\n * @private\n */\n get: function () {\n return this.gridTextBrush;\n },\n set: function (value) {\n this.gridTextBrush = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridStyleBase.prototype, \"textPen\", {\n /**\n * Gets or sets the `text pen`.\n * @private\n */\n get: function () {\n return this.gridTextPen;\n },\n set: function (value) {\n this.gridTextPen = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridStyleBase.prototype, \"font\", {\n /**\n * Gets or sets the `font`.\n * @private\n */\n get: function () {\n return this.gridFont;\n },\n set: function (value) {\n this.gridFont = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGridStyleBase;\n}());\nexport { PdfGridStyleBase };\n/**\n * `PdfGridStyle` class provides customization of the appearance for the 'PdfGrid'.\n */\nvar PdfGridStyle = /** @class */ (function (_super) {\n __extends(PdfGridStyle, _super);\n //constructor\n /**\n * Initialize a new instance for `PdfGridStyle` class.\n * @private\n */\n function PdfGridStyle() {\n var _this = _super.call(this) || this;\n _this.gridBorderOverlapStyle = PdfBorderOverlapStyle.Overlap;\n _this.bAllowHorizontalOverflow = false;\n _this.gridHorizontalOverflowType = PdfHorizontalOverflowType.LastPage;\n return _this;\n }\n Object.defineProperty(PdfGridStyle.prototype, \"cellSpacing\", {\n //Properties\n /**\n * Gets or sets the `cell spacing` of the 'PdfGrid'.\n * @private\n */\n get: function () {\n if (typeof this.gridCellSpacing === 'undefined') {\n this.gridCellSpacing = 0;\n }\n return this.gridCellSpacing;\n },\n set: function (value) {\n this.gridCellSpacing = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridStyle.prototype, \"horizontalOverflowType\", {\n /**\n * Gets or sets the type of the `horizontal overflow` of the 'PdfGrid'.\n * @private\n */\n get: function () {\n return this.gridHorizontalOverflowType;\n },\n set: function (value) {\n this.gridHorizontalOverflowType = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridStyle.prototype, \"allowHorizontalOverflow\", {\n /**\n * Gets or sets a value indicating whether to `allow horizontal overflow`.\n * @private\n */\n get: function () {\n return this.bAllowHorizontalOverflow;\n },\n set: function (value) {\n this.bAllowHorizontalOverflow = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridStyle.prototype, \"cellPadding\", {\n /**\n * Gets or sets the `cell padding`.\n * @private\n */\n get: function () {\n if (typeof this.gridCellPadding === 'undefined') {\n this.gridCellPadding = new PdfPaddings();\n }\n return this.gridCellPadding;\n },\n set: function (value) {\n if (typeof this.gridCellPadding === 'undefined') {\n this.gridCellPadding = new PdfPaddings();\n this.gridCellPadding = value;\n }\n else {\n this.gridCellPadding = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridStyle.prototype, \"borderOverlapStyle\", {\n /**\n * Gets or sets the `border overlap style` of the 'PdfGrid'.\n * @private\n */\n get: function () {\n return this.gridBorderOverlapStyle;\n },\n set: function (value) {\n this.gridBorderOverlapStyle = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGridStyle;\n}(PdfGridStyleBase));\nexport { PdfGridStyle };\n/**\n * `PdfGridCellStyle` class provides customization of the appearance for the 'PdfGridCell'.\n */\nvar PdfGridCellStyle = /** @class */ (function (_super) {\n __extends(PdfGridCellStyle, _super);\n /**\n * Initializes a new instance of the `PdfGridCellStyle` class.\n * @private\n */\n function PdfGridCellStyle() {\n var _this = _super.call(this) || this;\n /**\n * @hidden\n * @private\n */\n _this.gridCellBorders = PdfBorders.default;\n return _this;\n }\n Object.defineProperty(PdfGridCellStyle.prototype, \"stringFormat\", {\n //Properties\n /**\n * Gets the `string format` of the 'PdfGridCell'.\n * @private\n */\n get: function () {\n return this.format;\n },\n set: function (value) {\n this.format = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCellStyle.prototype, \"borders\", {\n /**\n * Gets or sets the `border` of the 'PdfGridCell'.\n * @private\n */\n get: function () {\n return this.gridCellBorders;\n },\n set: function (value) {\n this.gridCellBorders = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCellStyle.prototype, \"cellPadding\", {\n /**\n * Gets or sets the `cell padding`.\n * @private\n */\n get: function () {\n return this.gridCellPadding;\n },\n set: function (value) {\n if (this.gridCellPadding == null || typeof this.gridCellPadding === 'undefined') {\n this.gridCellPadding = new PdfPaddings();\n }\n this.gridCellPadding = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGridCellStyle;\n}(PdfGridStyleBase));\nexport { PdfGridCellStyle };\n/**\n * `PdfGridRowStyle` class provides customization of the appearance for the `PdfGridRow`.\n */\nvar PdfGridRowStyle = /** @class */ (function () {\n // Constructor\n /**\n * Initializes a new instance of the `PdfGridRowStyle` class.\n * @private\n */\n function PdfGridRowStyle() {\n //\n }\n Object.defineProperty(PdfGridRowStyle.prototype, \"backgroundBrush\", {\n /**\n * Determine the value of the border is changed or not.\n * @private\n */\n // Properties\n /**\n * Gets or sets the `background brush`.\n * @private\n */\n get: function () {\n return this.gridRowBackgroundBrush;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridRowStyle.prototype.setBackgroundBrush = function (value) {\n this.gridRowBackgroundBrush = value;\n if (typeof this.parent !== 'undefined') {\n for (var i = 0; i < this.parent.cells.count; i++) {\n this.parent.cells.getCell(i).style.backgroundBrush = value;\n }\n }\n };\n Object.defineProperty(PdfGridRowStyle.prototype, \"textBrush\", {\n /**\n * Gets or sets the `text brush`.\n * @private\n */\n get: function () {\n return this.gridRowTextBrush;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridRowStyle.prototype.setTextBrush = function (value) {\n this.gridRowTextBrush = value;\n if (typeof this.parent !== 'undefined') {\n for (var i = 0; i < this.parent.cells.count; i++) {\n this.parent.cells.getCell(i).style.textBrush = value;\n }\n }\n };\n Object.defineProperty(PdfGridRowStyle.prototype, \"textPen\", {\n /**\n * Gets or sets the `text pen`.\n * @private\n */\n get: function () {\n return this.gridRowTextPen;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridRowStyle.prototype.setTextPen = function (value) {\n this.gridRowTextPen = value;\n if (typeof this.parent !== 'undefined') {\n for (var i = 0; i < this.parent.cells.count; i++) {\n this.parent.cells.getCell(i).style.textPen = value;\n }\n }\n };\n Object.defineProperty(PdfGridRowStyle.prototype, \"font\", {\n /**\n * Gets or sets the `font`.\n * @private\n */\n get: function () {\n return this.gridRowFont;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridRowStyle.prototype.setFont = function (value) {\n this.gridRowFont = value;\n if (typeof this.parent !== 'undefined') {\n for (var i = 0; i < this.parent.cells.count; i++) {\n this.parent.cells.getCell(i).style.font = value;\n }\n }\n };\n Object.defineProperty(PdfGridRowStyle.prototype, \"border\", {\n /**\n * Gets or sets the `border` of the current row.\n * @private\n */\n get: function () {\n if (typeof this.gridRowBorder === 'undefined') {\n this.setBorder(new PdfBorders());\n }\n return this.gridRowBorder;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridRowStyle.prototype.setBorder = function (value) {\n this.gridRowBorder = value;\n if (typeof this.parent !== 'undefined') {\n for (var i = 0; i < this.parent.cells.count; i++) {\n this.parent.cells.getCell(i).style.borders = value;\n }\n }\n };\n /**\n * sets the `parent row` of the current object.\n * @private\n */\n PdfGridRowStyle.prototype.setParent = function (parent) {\n this.parent = parent;\n };\n return PdfGridRowStyle;\n}());\nexport { PdfGridRowStyle };\n/**\n * public Enum for `PdfHorizontalOverflowType`.\n * @private\n */\nexport var PdfHorizontalOverflowType;\n(function (PdfHorizontalOverflowType) {\n /**\n * Specifies the type of `NextPage`.\n * @private\n */\n PdfHorizontalOverflowType[PdfHorizontalOverflowType[\"NextPage\"] = 0] = \"NextPage\";\n /**\n * Specifies the type of `LastPage`.\n * @private\n */\n PdfHorizontalOverflowType[PdfHorizontalOverflowType[\"LastPage\"] = 1] = \"LastPage\";\n})(PdfHorizontalOverflowType || (PdfHorizontalOverflowType = {}));\n","import { PdfGridCellStyle } from './styles/style';\nimport { PdfStringLayouter } from './../../graphics/fonts/string-layouter';\nimport { PdfDocument } from './../../document/pdf-document';\nimport { PdfStringFormat } from './../../graphics/fonts/pdf-string-format';\nimport { RectangleF, PointF, SizeF } from './../../drawing/pdf-drawing';\nimport { PdfDashStyle, PdfLineCap } from './../../graphics/enum';\nimport { PdfBorderOverlapStyle } from './../tables/light-tables/enum';\nimport { PdfSolidBrush } from './../../graphics/brushes/pdf-solid-brush';\nimport { PdfColor } from './../../graphics/pdf-color';\nimport { PdfImage } from './../../graphics/images/pdf-image';\nimport { PdfBitmap } from './../../graphics/images/pdf-bitmap';\nimport { PdfTextWebLink } from './../../annotations/pdf-text-web-link';\n/**\n * `PdfGridCell` class represents the schema of a cell in a 'PdfGrid'.\n */\nvar PdfGridCell = /** @class */ (function () {\n function PdfGridCell(row) {\n /**\n * `Width` of the cell.\n * @default 0\n * @private\n */\n this.cellWidth = 0;\n /**\n * `Height` of the cell.\n * @default 0\n * @private\n */\n this.cellHeight = 0;\n /**\n * Specifies weather the `cell is drawn`.\n * @default true\n * @private\n */\n this.finsh = true;\n /**\n * The `remaining height` of row span.\n * @default 0\n * @private\n */\n this.rowSpanRemainingHeight = 0;\n if (typeof row === 'undefined') {\n this.gridRowSpan = 1;\n this.colSpan = 1;\n }\n else {\n this.constructor();\n this.gridRow = row;\n }\n }\n Object.defineProperty(PdfGridCell.prototype, \"isCellMergeContinue\", {\n //Properties\n get: function () {\n return this.internalIsCellMergeContinue;\n },\n set: function (value) {\n this.internalIsCellMergeContinue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"isRowMergeContinue\", {\n get: function () {\n return this.internalIsRowMergeContinue;\n },\n set: function (value) {\n this.internalIsRowMergeContinue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"isCellMergeStart\", {\n get: function () {\n return this.internalIsCellMergeStart;\n },\n set: function (value) {\n this.internalIsCellMergeStart = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"isRowMergeStart\", {\n get: function () {\n return this.internalIsRowMergeStart;\n },\n set: function (value) {\n this.internalIsRowMergeStart = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"remainingString\", {\n /**\n * Gets or sets the `remaining string` after the row split between pages.\n * @private\n */\n get: function () {\n return this.remaining;\n },\n set: function (value) {\n this.remaining = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"stringFormat\", {\n /**\n * Gets or sets the `string format`.\n * @private\n */\n get: function () {\n if (this.format == null) {\n this.format = new PdfStringFormat();\n }\n return this.format;\n },\n set: function (value) {\n this.format = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"row\", {\n /**\n * Gets or sets the parent `row`.\n * @private\n */\n get: function () {\n return this.gridRow;\n },\n set: function (value) {\n this.gridRow = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"value\", {\n /**\n * Gets or sets the `value` of the cell.\n * @private\n */\n get: function () {\n return this.objectValue;\n },\n set: function (value) {\n this.objectValue = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"rowSpan\", {\n /**\n * Gets or sets a value that indicates the total number of rows that cell `spans` within a PdfGrid.\n * @private\n */\n get: function () {\n return this.gridRowSpan;\n },\n set: function (value) {\n if (value < 1) {\n throw new Error('ArgumentException : Invalid span specified, must be greater than or equal to 1');\n }\n else {\n this.gridRowSpan = value;\n this.row.rowSpanExists = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"style\", {\n /**\n * Gets or sets the cell `style`.\n * @private\n */\n get: function () {\n if (this.cellStyle == null) {\n this.cellStyle = new PdfGridCellStyle();\n }\n return this.cellStyle;\n },\n set: function (value) {\n this.cellStyle = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"height\", {\n /**\n * Gets the `height` of the PdfGrid cell.[Read-Only].\n * @private\n */\n get: function () {\n if (this.cellHeight === 0) {\n this.cellHeight = this.measureHeight();\n }\n return this.cellHeight;\n },\n set: function (value) {\n this.cellHeight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"columnSpan\", {\n /**\n * Gets or sets a value that indicates the total number of columns that cell `spans` within a PdfGrid.\n * @private\n */\n get: function () {\n return this.colSpan;\n },\n set: function (value) {\n if (value < 1) {\n throw Error('Invalid span specified, must be greater than or equal to 1');\n }\n else {\n this.colSpan = value;\n this.row.columnSpanExists = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridCell.prototype, \"width\", {\n /**\n * Gets the `width` of the PdfGrid cell.[Read-Only].\n * @private\n */\n get: function () {\n if (this.cellWidth === 0 || this.row.grid.isComplete) {\n this.cellWidth = this.measureWidth();\n }\n return this.cellWidth;\n },\n set: function (value) {\n this.cellWidth = value;\n },\n enumerable: true,\n configurable: true\n });\n //Implementation\n /**\n * `Calculates the width`.\n * @private\n */\n PdfGridCell.prototype.measureWidth = function () {\n // .. Calculate the cell text width.\n // .....Add border widths, cell spacings and paddings to the width.\n var width = 0;\n var layouter = new PdfStringLayouter();\n if (typeof this.objectValue === 'string') {\n /* tslint:disable */\n var slr = layouter.layout(this.objectValue, this.getTextFont(), this.stringFormat, new SizeF(0, 0), false, new SizeF(0, 0));\n width += slr.actualSize.width;\n width += (this.style.borders.left.width + this.style.borders.right.width) * 2;\n }\n else if (this.objectValue instanceof PdfImage || this.objectValue instanceof PdfBitmap) {\n width += this.objectValue.width;\n }\n else if (this.objectValue instanceof PdfTextWebLink) {\n var webLink = this.objectValue;\n var result = layouter.layout(webLink.text, webLink.font, webLink.stringFormat, new SizeF(0, 0), false, new SizeF(0, 0));\n /* tslint:enable */\n width += result.actualSize.width;\n width += (this.style.borders.left.width + this.style.borders.right.width) * 2;\n }\n width += (this.row.grid.style.cellPadding.left + this.row.grid.style.cellPadding.right);\n width += this.row.grid.style.cellSpacing;\n return width;\n };\n /**\n * Draw the `cell background`.\n * @private\n */\n PdfGridCell.prototype.drawCellBackground = function (graphics, bounds) {\n var backgroundBrush = this.getBackgroundBrush();\n if (backgroundBrush != null) {\n graphics.drawRectangle(backgroundBrush, bounds.x, bounds.y, bounds.width, bounds.height);\n }\n };\n /**\n * `Adjusts the text layout area`.\n * @private\n */\n /* tslint:disable */\n PdfGridCell.prototype.adjustContentLayoutArea = function (bounds) {\n //Add Padding value to its Cell Bounds\n var returnBounds = new RectangleF(bounds.x, bounds.y, bounds.width, bounds.height);\n if (typeof this.style.cellPadding === 'undefined' || this.style.cellPadding == null) {\n returnBounds.x += this.gridRow.grid.style.cellPadding.left + this.cellStyle.borders.left.width;\n returnBounds.y += this.gridRow.grid.style.cellPadding.top + this.cellStyle.borders.top.width;\n returnBounds.width -= (this.gridRow.grid.style.cellPadding.right + this.gridRow.grid.style.cellPadding.left);\n returnBounds.width -= (this.cellStyle.borders.left.width + this.cellStyle.borders.right.width);\n returnBounds.height -= (this.gridRow.grid.style.cellPadding.bottom + this.gridRow.grid.style.cellPadding.top);\n returnBounds.height -= (this.cellStyle.borders.top.width + this.cellStyle.borders.bottom.width);\n if (this.rowSpan === 1) {\n returnBounds.width -= (this.style.borders.left.width);\n }\n }\n else {\n returnBounds.x += this.style.cellPadding.left + this.cellStyle.borders.left.width;\n returnBounds.y += this.style.cellPadding.top + this.cellStyle.borders.top.width;\n returnBounds.width -= (this.style.cellPadding.right + this.style.cellPadding.left);\n returnBounds.width -= (this.cellStyle.borders.left.width + this.cellStyle.borders.right.width);\n returnBounds.height -= (this.style.cellPadding.bottom + this.style.cellPadding.top);\n returnBounds.height -= (this.cellStyle.borders.top.width + this.cellStyle.borders.bottom.width);\n if (this.rowSpan === 1) {\n returnBounds.width -= (this.style.borders.left.width);\n }\n }\n return returnBounds;\n };\n /**\n * `Draws` the specified graphics.\n * @private\n */\n PdfGridCell.prototype.draw = function (graphics, bounds, cancelSubsequentSpans) {\n var isrowbreak = false;\n var result = null;\n if (this.internalIsCellMergeContinue || this.internalIsRowMergeContinue) {\n if (this.internalIsCellMergeContinue && this.row.grid.style.allowHorizontalOverflow) {\n if ((this.row.rowOverflowIndex > 0 && (this.row.cells.indexOf(this) != this.row.rowOverflowIndex + 1)) || (this.row.rowOverflowIndex == 0 && this.internalIsCellMergeContinue)) {\n return result;\n }\n }\n else {\n return result;\n }\n }\n //Adjust bounds with Row and Column Spacing\n bounds = this.adjustOuterLayoutArea(bounds, graphics);\n var textPen = this.getTextPen();\n var textBrush = this.getTextBrush();\n if (typeof textPen === 'undefined' && typeof textBrush === 'undefined') {\n textBrush = new PdfSolidBrush(new PdfColor(0, 0, 0));\n }\n var font = this.getTextFont();\n var strFormat = this.getStringFormat();\n var innerLayoutArea = this.adjustContentLayoutArea(bounds);\n this.drawCellBackground(graphics, bounds);\n if (typeof this.objectValue === 'string' || typeof this.remaining === 'string') {\n var temp = void 0;\n temp = this.remaining === '' ? this.remaining : this.objectValue;\n graphics.drawString(temp, font, textPen, textBrush, innerLayoutArea.x, innerLayoutArea.y, innerLayoutArea.width, innerLayoutArea.height, strFormat);\n result = graphics.stringLayoutResult;\n }\n else if (this.objectValue instanceof PdfImage || this.objectValue instanceof PdfBitmap) {\n var imageBounds = void 0;\n if (this.objectValue.width <= innerLayoutArea.width) {\n imageBounds = new RectangleF(innerLayoutArea.x, innerLayoutArea.y, this.objectValue.width, innerLayoutArea.height);\n }\n else {\n imageBounds = innerLayoutArea;\n }\n graphics.drawImage(this.objectValue, imageBounds.x, imageBounds.y, imageBounds.width, imageBounds.height);\n }\n else if (this.objectValue instanceof PdfTextWebLink) {\n this.objectValue.draw(graphics.currentPage, innerLayoutArea);\n }\n if (this.style.borders != null) {\n this.drawCellBorders(graphics, bounds);\n }\n return result;\n };\n /* tslint:enable */\n /**\n * Draws the `cell border` constructed by drawing lines.\n * @private\n */\n PdfGridCell.prototype.drawCellBorders = function (graphics, bounds) {\n if (this.row.grid.style.borderOverlapStyle === PdfBorderOverlapStyle.Inside) {\n bounds.x += this.style.borders.left.width;\n bounds.y += this.style.borders.top.width;\n bounds.width -= this.style.borders.right.width;\n bounds.height -= this.style.borders.bottom.width;\n }\n var p1 = new PointF(bounds.x, bounds.y + bounds.height);\n var p2 = new PointF(bounds.x, bounds.y);\n var pen = this.cellStyle.borders.left;\n if (this.cellStyle.borders.left.dashStyle === PdfDashStyle.Solid) {\n pen.lineCap = PdfLineCap.Square;\n }\n // SetTransparency(ref graphics, pen);\n graphics.drawLine(pen, p1, p2);\n p1 = new PointF(bounds.x + bounds.width, bounds.y);\n p2 = new PointF(bounds.x + bounds.width, bounds.y + bounds.height);\n pen = this.cellStyle.borders.right;\n if ((bounds.x + bounds.width) > (graphics.clientSize.width - (pen.width / 2))) {\n p1 = new PointF(graphics.clientSize.width - (pen.width / 2), bounds.y);\n p2 = new PointF(graphics.clientSize.width - (pen.width / 2), bounds.y + bounds.height);\n }\n if (this.cellStyle.borders.right.dashStyle === PdfDashStyle.Solid) {\n pen.lineCap = PdfLineCap.Square;\n }\n graphics.drawLine(pen, p1, p2);\n p1 = new PointF(bounds.x, bounds.y);\n p2 = new PointF(bounds.x + bounds.width, bounds.y);\n pen = this.cellStyle.borders.top;\n if (this.cellStyle.borders.top.dashStyle === PdfDashStyle.Solid) {\n pen.lineCap = PdfLineCap.Square;\n }\n graphics.drawLine(pen, p1, p2);\n p1 = new PointF(bounds.x + bounds.width, bounds.y + bounds.height);\n p2 = new PointF(bounds.x, bounds.y + bounds.height);\n pen = this.cellStyle.borders.bottom;\n // if ((bounds.y + bounds.height) > (graphics.clientSize.height - (pen.width / 2))) {\n // p1 = new PointF((bounds.x + bounds.width), (graphics.clientSize.height - (pen.width / 2)));\n // p2 = new PointF(bounds.x, (graphics.clientSize.height - (pen.width / 2)));\n // }\n if (this.cellStyle.borders.bottom.dashStyle === PdfDashStyle.Solid) {\n pen.lineCap = PdfLineCap.Square;\n }\n graphics.drawLine(pen, p1, p2);\n };\n /**\n * `Adjusts the outer layout area`.\n * @private\n */\n /* tslint:disable */\n PdfGridCell.prototype.adjustOuterLayoutArea = function (bounds, g) {\n var isHeader = false;\n var cellSpacing = this.row.grid.style.cellSpacing;\n if (cellSpacing > 0) {\n bounds = new RectangleF(bounds.x + cellSpacing, bounds.y + cellSpacing, bounds.width - cellSpacing, bounds.height - cellSpacing);\n }\n var currentColIndex = this.row.cells.indexOf(this);\n if (this.columnSpan > 1) {\n var span = this.columnSpan;\n var totalWidth = 0;\n for (var i = currentColIndex; i < currentColIndex + span; i++) {\n if (this.row.grid.style.allowHorizontalOverflow) {\n var width = void 0;\n var compWidth = this.row.grid.size.width < g.clientSize.width ? this.row.grid.size.width : g.clientSize.width;\n if (this.row.grid.size.width > g.clientSize.width) {\n width = bounds.x + totalWidth + this.row.grid.columns.getColumn(i).width;\n }\n else {\n width = totalWidth + this.row.grid.columns.getColumn(i).width;\n }\n if (width > compWidth) {\n break;\n }\n }\n totalWidth += this.row.grid.columns.getColumn(i).width;\n }\n totalWidth -= this.row.grid.style.cellSpacing;\n bounds.width = totalWidth;\n }\n if (this.rowSpan > 1 || this.row.rowSpanExists) {\n var span = this.rowSpan;\n var currentRowIndex = this.row.grid.rows.rowCollection.indexOf(this.row);\n if (currentRowIndex == -1) {\n currentRowIndex = this.row.grid.headers.indexOf(this.row);\n if (currentRowIndex != -1) {\n isHeader = true;\n }\n }\n var totalHeight = 0;\n var max = 0;\n for (var i = currentRowIndex; i < currentRowIndex + span; i++) {\n totalHeight += (isHeader ? this.row.grid.headers.getHeader(i).height : this.row.grid.rows.getRow(i).height);\n var row = this.row.grid.rows.getRow(i);\n var rowIndex = this.row.grid.rows.rowCollection.indexOf(row);\n }\n var cellIndex = this.row.cells.indexOf(this);\n totalHeight -= this.row.grid.style.cellSpacing;\n // if (this.row.cells.getCell(cellIndex).height > totalHeight && (!this.row.grid.rows.getRow((currentRowIndex + span) - 1).isRowHeightSet)) {\n // this.row.grid.rows.getRow((currentRowIndex + span) - 1).cells.getCell(cellIndex).rowSpanRemainingHeight = this.row.cells.getCell(cellIndex).height - totalHeight;\n // totalHeight = this.row.cells.getCell(cellIndex).height;\n // bounds.height = totalHeight;\n // } else {\n bounds.height = totalHeight;\n // }\n if (!this.row.rowMergeComplete) {\n bounds.height = totalHeight;\n }\n }\n return bounds;\n };\n /* tslint:enable */\n /**\n * Gets the `text font`.\n * @private\n */\n PdfGridCell.prototype.getTextFont = function () {\n if (typeof this.style.font !== 'undefined' && this.style.font != null) {\n return this.style.font;\n }\n else if (typeof this.row.style.font !== 'undefined' && this.row.style.font != null) {\n return this.row.style.font;\n }\n else if (typeof this.row.grid.style.font !== 'undefined' && this.row.grid.style.font != null) {\n return this.row.grid.style.font;\n }\n else {\n return PdfDocument.defaultFont;\n }\n };\n /**\n * Gets the `text brush`.\n * @private\n */\n PdfGridCell.prototype.getTextBrush = function () {\n if (typeof this.style.textBrush !== 'undefined' && this.style.textBrush != null) {\n return this.style.textBrush;\n }\n else if (typeof this.row.style.textBrush !== 'undefined' && this.row.style.textBrush != null) {\n return this.row.style.textBrush;\n }\n else {\n return this.row.grid.style.textBrush;\n }\n };\n /**\n * Gets the `text pen`.\n * @private\n */\n PdfGridCell.prototype.getTextPen = function () {\n if (typeof this.style.textPen !== 'undefined' && this.style.textPen != null) {\n return this.style.textPen;\n }\n else if (typeof this.row.style.textPen !== 'undefined' && this.row.style.textPen != null) {\n return this.row.style.textPen;\n }\n else {\n return this.row.grid.style.textPen;\n }\n };\n /**\n * Gets the `background brush`.\n * @private\n */\n PdfGridCell.prototype.getBackgroundBrush = function () {\n if (typeof this.style.backgroundBrush !== 'undefined' && this.style.backgroundBrush != null) {\n return this.style.backgroundBrush;\n }\n else if (typeof this.row.style.backgroundBrush !== 'undefined' && this.row.style.backgroundBrush != null) {\n return this.row.style.backgroundBrush;\n }\n else {\n return this.row.grid.style.backgroundBrush;\n }\n };\n /**\n * Gets the current `StringFormat`.\n * @private\n */\n PdfGridCell.prototype.getStringFormat = function () {\n if (typeof this.style.stringFormat !== 'undefined' && this.style.stringFormat != null) {\n return this.style.stringFormat;\n }\n else {\n return this.stringFormat;\n }\n };\n /**\n * Calculates the `height`.\n * @private\n */\n PdfGridCell.prototype.measureHeight = function () {\n // .. Calculate the cell text height.\n // .....Add border widths, cell spacings and paddings to the height.\n var width = this.calculateWidth();\n // //check whether the Current PdfGridCell has padding\n if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') {\n width -= (this.gridRow.grid.style.cellPadding.right + this.gridRow.grid.style.cellPadding.left);\n width -= (this.style.borders.left.width + this.style.borders.right.width);\n }\n else {\n width -= (this.style.cellPadding.right + this.style.cellPadding.left);\n width -= (this.style.borders.left.width + this.style.borders.right.width);\n }\n var height = 0;\n var layouter = new PdfStringLayouter();\n if (typeof this.objectValue === 'string' || typeof this.remainingString === 'string') {\n var currentValue = this.objectValue;\n /* tslint:disable */\n var slr = layouter.layout(currentValue, this.getTextFont(), this.stringFormat, new SizeF(width, 0), false, new SizeF(0, 0));\n /* tslint:enable */\n height += slr.actualSize.height;\n }\n else if (this.objectValue instanceof PdfImage || this.objectValue instanceof PdfBitmap) {\n height += this.objectValue.height;\n }\n else if (this.objectValue instanceof PdfTextWebLink) {\n var webLink = this.objectValue;\n /* tslint:disable */\n var slr = layouter.layout(webLink.text, webLink.font, webLink.stringFormat, new SizeF(width, 0), false, new SizeF(0, 0));\n /* tslint:enable */\n height += slr.actualSize.height;\n }\n height += (this.style.borders.top.width + this.style.borders.bottom.width) * 2;\n //Add padding top and bottom value to height\n if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') {\n height += (this.row.grid.style.cellPadding.top + this.row.grid.style.cellPadding.bottom);\n }\n else {\n height += (this.style.cellPadding.top + this.style.cellPadding.bottom);\n }\n height += this.row.grid.style.cellSpacing;\n return height;\n };\n /**\n * return the calculated `width` of the cell.\n * @private\n */\n PdfGridCell.prototype.calculateWidth = function () {\n var cellIndex = this.row.cells.indexOf(this);\n var columnSpan = this.columnSpan;\n var width = 0;\n for (var i = 0; i < columnSpan; i++) {\n width += this.row.grid.columns.getColumn(cellIndex + i).width;\n }\n return width;\n };\n return PdfGridCell;\n}());\nexport { PdfGridCell };\n/**\n * `PdfGridCellCollection` class provides access to an ordered,\n * strongly typed collection of 'PdfGridCell' objects.\n * @private\n */\nvar PdfGridCellCollection = /** @class */ (function () {\n //Constructor\n /**\n * Initializes a new instance of the `PdfGridCellCollection` class with the row.\n * @private\n */\n function PdfGridCellCollection(row) {\n /**\n * @hidden\n * @private\n */\n this.cells = [];\n this.gridRow = row;\n }\n //Properties\n /**\n * Gets the current `cell`.\n * @private\n */\n PdfGridCellCollection.prototype.getCell = function (index) {\n if (index < 0 || index >= this.count) {\n throw new Error('IndexOutOfRangeException');\n }\n return this.cells[index];\n };\n Object.defineProperty(PdfGridCellCollection.prototype, \"count\", {\n /**\n * Gets the cells `count`.[Read-Only].\n * @private\n */\n get: function () {\n return this.cells.length;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridCellCollection.prototype.add = function (cell) {\n if (typeof cell === 'undefined') {\n var tempcell = new PdfGridCell();\n this.add(tempcell);\n return cell;\n }\n else {\n cell.row = this.gridRow;\n this.cells.push(cell);\n }\n };\n /**\n * Returns the `index of` a particular cell in the collection.\n * @private\n */\n PdfGridCellCollection.prototype.indexOf = function (cell) {\n return this.cells.indexOf(cell);\n };\n return PdfGridCellCollection;\n}());\nexport { PdfGridCellCollection };\n","import { PdfGridCell } from './pdf-grid-cell';\nimport { PdfStringFormat } from './../../graphics/fonts/pdf-string-format';\n/**\n * `PdfGridColumn` class represents the schema of a column in a 'PdfGrid'.\n */\nvar PdfGridColumn = /** @class */ (function () {\n //Constructors\n /**\n * Initializes a new instance of the `PdfGridColumn` class with the parent grid.\n * @private\n */\n function PdfGridColumn(grid) {\n /**\n * The `width` of the column.\n * @default 0\n * @private\n */\n this.columnWidth = 0;\n this.grid = grid;\n }\n Object.defineProperty(PdfGridColumn.prototype, \"width\", {\n /**\n * Gets or sets the `width` of the 'PdfGridColumn'.\n * @private\n */\n get: function () {\n return this.columnWidth;\n },\n set: function (value) {\n this.isCustomWidth = true;\n this.columnWidth = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridColumn.prototype, \"format\", {\n /**\n * Gets or sets the information about the text `formatting`.\n * @private\n */\n get: function () {\n if (this.stringFormat == null) {\n this.stringFormat = new PdfStringFormat(); //GetDefaultFormat();\n }\n return this.stringFormat;\n },\n set: function (value) {\n this.stringFormat = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGridColumn;\n}());\nexport { PdfGridColumn };\n/**\n * `PdfGridColumnCollection` class provides access to an ordered,\n * strongly typed collection of 'PdfGridColumn' objects.\n * @private\n */\nvar PdfGridColumnCollection = /** @class */ (function () {\n //properties\n //Constructors\n /**\n * Initializes a new instance of the `PdfGridColumnCollection` class with the parent grid.\n * @private\n */\n function PdfGridColumnCollection(grid) {\n /**\n * @hidden\n * @private\n */\n this.internalColumns = [];\n /**\n * @hidden\n * @private\n */\n this.columnWidth = 0;\n this.grid = grid;\n this.internalColumns = [];\n }\n //Iplementation\n /**\n * `Add` a new column to the 'PdfGrid'.\n * @private\n */\n PdfGridColumnCollection.prototype.add = function (count) {\n // public add(column : PdfGridColumn) : void\n // public add(arg : number|PdfGridColumn) : void {\n // if (typeof arg === 'number') {\n for (var i = 0; i < count; i++) {\n this.internalColumns.push(new PdfGridColumn(this.grid));\n for (var index = 0; index < this.grid.rows.count; index++) {\n var row = this.grid.rows.getRow(index);\n var cell = new PdfGridCell();\n cell.value = '';\n row.cells.add(cell);\n }\n }\n // } else {\n // let column : PdfGridColumn = new PdfGridColumn(this.grid);\n // this.columns.push(column);\n // return column;\n // }\n };\n Object.defineProperty(PdfGridColumnCollection.prototype, \"count\", {\n /**\n * Gets the `number of columns` in the 'PdfGrid'.[Read-Only].\n * @private\n */\n get: function () {\n return this.internalColumns.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridColumnCollection.prototype, \"width\", {\n /**\n * Gets the `widths`.\n * @private\n */\n get: function () {\n if (this.columnWidth === 0) {\n this.columnWidth = this.measureColumnsWidth();\n }\n if (this.grid.initialWidth !== 0 && this.columnWidth !== this.grid.initialWidth && !this.grid.style.allowHorizontalOverflow) {\n this.columnWidth = this.grid.initialWidth;\n this.grid.isPageWidth = true;\n }\n return this.columnWidth;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridColumnCollection.prototype, \"columns\", {\n /**\n * Gets the `array of PdfGridColumn`.[Read-Only]\n * @private\n */\n get: function () {\n return this.internalColumns;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the `PdfGridColumn` from the specified index.[Read-Only]\n * @private\n */\n PdfGridColumnCollection.prototype.getColumn = function (index) {\n if (index >= 0 && index <= this.columns.length) {\n return this.columns[index];\n }\n else {\n throw Error('can not get the column from the index: ' + index);\n }\n };\n //Implementation\n /**\n * `Calculates the column widths`.\n * @private\n */\n PdfGridColumnCollection.prototype.measureColumnsWidth = function () {\n var totalWidth = 0;\n // this.m_grid.measureColumnsWidth();\n for (var i = 0, count = this.internalColumns.length; i < count; i++) {\n totalWidth += this.internalColumns[i].width;\n }\n return totalWidth;\n };\n /**\n * Gets the `widths of the columns`.\n * @private\n */\n PdfGridColumnCollection.prototype.getDefaultWidths = function (totalWidth) {\n var widths = [];\n var summ = 0.0;\n var subFactor = this.count;\n for (var i = 0; i < this.count; i++) {\n if (this.grid.isPageWidth && totalWidth >= 0 && !this.internalColumns[i].isCustomWidth) {\n this.internalColumns[i].width = 0;\n }\n else {\n widths[i] = this.internalColumns[i].width;\n if (this.internalColumns[i].width > 0 && this.internalColumns[i].isCustomWidth) {\n totalWidth -= this.internalColumns[i].width;\n subFactor--;\n }\n else {\n widths[i] = 0;\n }\n }\n }\n for (var i = 0; i < this.count; i++) {\n var width = totalWidth / subFactor;\n if (widths[i] <= 0) {\n widths[i] = width;\n }\n }\n return widths;\n };\n return PdfGridColumnCollection;\n}());\nexport { PdfGridColumnCollection };\n","import { PdfGridCell, PdfGridCellCollection } from './pdf-grid-cell';\nimport { PdfGridRowStyle } from './styles/style';\n/**\n * `PdfGridRow` class provides customization of the settings for the particular row.\n */\nvar PdfGridRow = /** @class */ (function () {\n //Constructor\n /**\n * Initializes a new instance of the `PdfGridRow` class with the parent grid.\n * @private\n */\n function PdfGridRow(grid) {\n /**\n * Stores the index of the overflowing row.\n * @private\n */\n this.gridRowOverflowIndex = 0;\n /**\n * Check whether the row height `is set explicitly`.\n * @default false\n * @private\n */\n this.isRowHeightSet = false;\n /**\n * Check weather the row merge `is completed` or not.\n * @default true\n * @private\n */\n this.isRowMergeComplete = true;\n this.pdfGrid = grid;\n }\n Object.defineProperty(PdfGridRow.prototype, \"rowSpanExists\", {\n //Properties\n /**\n * Gets or sets a value indicating [`row span exists`].\n * @private\n */\n get: function () {\n return this.bRowSpanExists;\n },\n set: function (value) {\n this.bRowSpanExists = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"cells\", {\n /**\n * Gets the `cells` from the selected row.[Read-Only].\n * @private\n */\n get: function () {\n if (this.gridCells == null) {\n this.gridCells = new PdfGridCellCollection(this);\n }\n return this.gridCells;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"grid\", {\n /**\n * Gets or sets the parent `grid`.\n * @private\n */\n get: function () {\n return this.pdfGrid;\n },\n set: function (value) {\n this.pdfGrid = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"style\", {\n /**\n * Gets or sets the row `style`.\n * @private\n */\n get: function () {\n if (typeof this.rowStyle === 'undefined') {\n this.rowStyle = new PdfGridRowStyle();\n this.rowStyle.setParent(this);\n }\n return this.rowStyle;\n },\n set: function (value) {\n this.rowStyle = value;\n for (var i = 0; i < this.cells.count; i++) {\n this.cells.getCell(i).style.borders = value.border;\n if (typeof value.font !== 'undefined') {\n this.cells.getCell(i).style.font = value.font;\n }\n if (typeof value.backgroundBrush !== 'undefined') {\n this.cells.getCell(i).style.backgroundBrush = value.backgroundBrush;\n }\n if (typeof value.textBrush !== 'undefined') {\n this.cells.getCell(i).style.textBrush = value.textBrush;\n }\n if (typeof value.textPen !== 'undefined') {\n this.cells.getCell(i).style.textPen = value.textPen;\n }\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"rowBreakHeight\", {\n /**\n * `Height` of the row yet to be drawn after split.\n * @private\n */\n get: function () {\n if (typeof this.gridRowBreakHeight === 'undefined') {\n this.gridRowBreakHeight = 0;\n }\n return this.gridRowBreakHeight;\n },\n set: function (value) {\n this.gridRowBreakHeight = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"rowOverflowIndex\", {\n get: function () {\n return this.gridRowOverflowIndex;\n },\n set: function (value) {\n this.gridRowOverflowIndex = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"height\", {\n /**\n * Gets or sets the `height` of the row.\n * @private\n */\n get: function () {\n if (!this.isRowHeightSet) {\n this.rowHeight = this.measureHeight();\n }\n return this.rowHeight;\n },\n set: function (value) {\n this.rowHeight = value;\n this.isRowHeightSet = true;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"columnSpanExists\", {\n /**\n * Gets or sets a value indicating [`column span exists`].\n * @private\n */\n get: function () {\n return this.bColumnSpanExists;\n },\n set: function (value) {\n this.bColumnSpanExists = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"rowMergeComplete\", {\n /**\n * Check whether the Row `has row span or row merge continue`.\n * @private\n */\n get: function () {\n return this.isRowMergeComplete;\n },\n set: function (value) {\n this.isRowMergeComplete = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRow.prototype, \"rowIndex\", {\n /**\n * Returns `index` of the row.\n * @private\n */\n get: function () {\n return this.grid.rows.rowCollection.indexOf(this);\n },\n enumerable: true,\n configurable: true\n });\n //Implementation\n /**\n * `Calculates the height`.\n * @private\n */\n PdfGridRow.prototype.measureHeight = function () {\n var rowSpanRemainingHeight = 0;\n var rowHeight;\n var maxHeight = 0;\n // if(this.cells.getCell(0).RowSpan > 1) {\n // rowHeight=0;\n // } else {\n rowHeight = this.cells.getCell(0).height;\n // }\n for (var i = 0; i < this.cells.count; i++) {\n var cell = this.cells.getCell(i);\n //get the maximum rowspan remaining height.\n if (cell.rowSpanRemainingHeight > rowSpanRemainingHeight) {\n rowSpanRemainingHeight = cell.rowSpanRemainingHeight;\n }\n //skip the cell if row spanned.\n // if (cell.IsRowMergeContinue)\n // continue; \n // if (!cell.IsRowMergeContinue)\n this.rowMergeComplete = false;\n if (cell.rowSpan > 1) {\n if (maxHeight < cell.height) {\n maxHeight = cell.height;\n }\n continue;\n }\n rowHeight = Math.max(rowHeight, cell.height);\n }\n if (rowHeight === 0) {\n rowHeight = maxHeight;\n }\n else if (rowSpanRemainingHeight > 0) {\n rowHeight += rowSpanRemainingHeight;\n }\n return rowHeight;\n };\n return PdfGridRow;\n}());\nexport { PdfGridRow };\n/**\n * `PdfGridRowCollection` class provides access to an ordered, strongly typed collection of 'PdfGridRow' objects.\n * @private\n */\nvar PdfGridRowCollection = /** @class */ (function () {\n // Constructor\n /**\n * Initializes a new instance of the `PdfGridRowCollection` class with the parent grid.\n * @private\n */\n function PdfGridRowCollection(grid) {\n this.rows = [];\n this.grid = grid;\n }\n Object.defineProperty(PdfGridRowCollection.prototype, \"count\", {\n //Properties\n /**\n * Gets the number of header in the `PdfGrid`.[Read-Only].\n * @private\n */\n get: function () {\n return this.rows.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridRowCollection.prototype, \"rowCollection\", {\n //Implementation\n /**\n * Return the row collection of the `grid`.\n * @private\n */\n get: function () {\n return this.rows;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridRowCollection.prototype.addRow = function (arg) {\n if (typeof arg === 'undefined') {\n var temprow = new PdfGridRow(this.grid);\n this.addRow(temprow);\n return temprow;\n }\n else {\n arg.style.setBackgroundBrush(this.grid.style.backgroundBrush);\n arg.style.setFont(this.grid.style.font);\n arg.style.setTextBrush(this.grid.style.textBrush);\n arg.style.setTextPen(this.grid.style.textPen);\n if (arg.cells.count === 0) {\n for (var i = 0; i < this.grid.columns.count; i++) {\n arg.cells.add(new PdfGridCell());\n }\n }\n this.rows.push(arg);\n }\n };\n /**\n * Return the row by index.\n * @private\n */\n PdfGridRowCollection.prototype.getRow = function (index) {\n return this.rows[index];\n };\n return PdfGridRowCollection;\n}());\nexport { PdfGridRowCollection };\n/**\n * `PdfGridHeaderCollection` class provides customization of the settings for the header.\n * @private\n */\nvar PdfGridHeaderCollection = /** @class */ (function () {\n //constructor\n /**\n * Initializes a new instance of the `PdfGridHeaderCollection` class with the parent grid.\n * @private\n */\n function PdfGridHeaderCollection(grid) {\n /**\n * The array to store the `rows` of the grid header.\n * @private\n */\n this.rows = [];\n this.grid = grid;\n this.rows = [];\n }\n //Properties\n /**\n * Gets a 'PdfGridRow' object that represents the `header` row in a 'PdfGridHeaderCollection' control.[Read-Only].\n * @private\n */\n PdfGridHeaderCollection.prototype.getHeader = function (index) {\n // if (index < 0 || index >= Count) {\n // throw new IndexOutOfRangeException();\n // }\n return (this.rows[index]);\n };\n Object.defineProperty(PdfGridHeaderCollection.prototype, \"count\", {\n /**\n * Gets the `number of header` in the 'PdfGrid'.[Read-Only]\n * @private\n */\n get: function () {\n return this.rows.length;\n },\n enumerable: true,\n configurable: true\n });\n PdfGridHeaderCollection.prototype.add = function (arg) {\n if (typeof arg === 'number') {\n var row = void 0;\n for (var i = 0; i < arg; i++) {\n row = new PdfGridRow(this.grid);\n for (var j = 0; j < this.grid.columns.count; j++) {\n row.cells.add(new PdfGridCell());\n }\n this.rows.push(row);\n }\n return this.rows;\n }\n else {\n this.rows.push(arg);\n }\n };\n PdfGridHeaderCollection.prototype.indexOf = function (row) {\n return this.rows.indexOf(row);\n };\n return PdfGridHeaderCollection;\n}());\nexport { PdfGridHeaderCollection };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * PdfGrid.ts class for EJ2-PDF\n */\nimport { PdfGridColumnCollection } from './pdf-grid-column';\nimport { PdfGridRowCollection, PdfGridHeaderCollection } from './pdf-grid-row';\nimport { RectangleF, SizeF, PointF } from './../../drawing/pdf-drawing';\nimport { PdfLayoutElement } from './../../graphics/figures/layout-element';\nimport { PdfLayoutResult, PdfLayoutFormat } from './../../graphics/figures/base/element-layouter';\nimport { PdfBorders } from './styles/pdf-borders';\nimport { PdfGridStyle } from './styles/style';\nimport { PdfLayoutType } from './../../graphics/figures/enum';\nimport { PdfHorizontalOverflowType } from './styles/style';\nimport { TemporaryDictionary } from './../../collections/object-object-pair/dictionary';\nimport { PdfStringFormat } from './../../graphics/fonts/pdf-string-format';\n/**\n * `PdfGridLayoutFormat` class represents a flexible grid that consists of columns and rows.\n */\nvar PdfGridLayoutFormat = /** @class */ (function (_super) {\n __extends(PdfGridLayoutFormat, _super);\n /**\n * Initializes a new instance of the `PdfGridLayoutFormat` class.\n * @private\n */\n function PdfGridLayoutFormat(baseFormat) {\n var _this = this;\n if (typeof baseFormat === 'undefined') {\n _this = _super.call(this) || this;\n }\n else {\n _this = _super.call(this, baseFormat) || this;\n }\n return _this;\n }\n return PdfGridLayoutFormat;\n}(PdfLayoutFormat));\nexport { PdfGridLayoutFormat };\nvar PdfGrid = /** @class */ (function (_super) {\n __extends(PdfGrid, _super);\n //constructor\n /**\n * Initialize a new instance for `PdfGrid` class.\n * @private\n */\n function PdfGrid() {\n var _this = _super.call(this) || this;\n /**\n * @hidden\n * @private\n */\n _this.gridSize = new SizeF(0, 0);\n /**\n * @hidden\n * @private\n */\n _this.isRearranged = false;\n /**\n * @hidden\n * @private\n */\n _this.pageBounds = new RectangleF();\n /**\n * @hidden\n * @private\n */\n _this.listOfNavigatePages = [];\n /**\n * @hidden\n * @private\n */\n _this.flag = true;\n /**\n * @hidden\n * @private\n */\n _this.columnRanges = [];\n /**\n * @hidden\n * @private\n */\n _this.currentLocation = new PointF(0, 0);\n /**\n * @hidden\n * @private\n */\n _this.breakRow = true;\n return _this;\n }\n Object.defineProperty(PdfGrid.prototype, \"raiseBeginCellDraw\", {\n //Properties\n /**\n * Gets a value indicating whether the `start cell layout event` should be raised.\n * @private\n */\n get: function () {\n return (typeof this.beginCellDraw !== 'undefined' && typeof this.beginCellDraw !== null);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"raiseEndCellDraw\", {\n /**\n * Gets a value indicating whether the `end cell layout event` should be raised.\n * @private\n */\n get: function () {\n return (typeof this.endCellDraw !== 'undefined' && typeof this.endCellDraw !== null);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"raiseBeginPageLayout\", {\n /**\n * Gets a value indicating whether the `start page layout event` should be raised.\n * @private\n */\n get: function () {\n return (typeof this.beginPageLayout !== 'undefined');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"raiseEndPageLayout\", {\n /**\n * Gets a value indicating whether the `ending page layout event` should be raised.\n * @private\n */\n get: function () {\n return (typeof this.endPageLayout !== 'undefined');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"repeatHeader\", {\n /**\n * Gets or sets a value indicating whether to `repeat header`.\n * @private\n */\n get: function () {\n if (this.bRepeatHeader == null || typeof this.bRepeatHeader === 'undefined') {\n this.bRepeatHeader = false;\n }\n return this.bRepeatHeader;\n },\n set: function (value) {\n this.bRepeatHeader = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"allowRowBreakAcrossPages\", {\n /**\n * Gets or sets a value indicating whether to split or cut rows that `overflow a page`.\n * @private\n */\n get: function () {\n return this.breakRow;\n },\n set: function (value) {\n this.breakRow = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"columns\", {\n /**\n * Gets the `column` collection of the PdfGrid.[Read-Only]\n * @private\n */\n get: function () {\n if (this.gridColumns == null || typeof this.gridColumns === 'undefined') {\n this.gridColumns = new PdfGridColumnCollection(this);\n }\n return this.gridColumns;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"rows\", {\n /**\n * Gets the `row` collection from the PdfGrid.[Read-Only]\n * @private\n */\n get: function () {\n if (this.gridRows == null) {\n this.gridRows = new PdfGridRowCollection(this);\n }\n return this.gridRows;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"headers\", {\n /**\n * Gets the `headers` collection from the PdfGrid.[Read-Only]\n * @private\n */\n get: function () {\n if (this.gridHeaders == null || typeof this.gridHeaders === 'undefined') {\n this.gridHeaders = new PdfGridHeaderCollection(this);\n }\n return this.gridHeaders;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"initialWidth\", {\n /**\n * Indicating `initial width` of the page.\n * @private\n */\n get: function () {\n return this.gridInitialWidth;\n },\n set: function (value) {\n this.gridInitialWidth = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"style\", {\n /**\n * Gets or sets the `grid style`.\n * @private\n */\n get: function () {\n if (this.gridStyle == null) {\n this.gridStyle = new PdfGridStyle();\n }\n return this.gridStyle;\n },\n set: function (value) {\n if (this.gridStyle == null) {\n this.gridStyle = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"isPageWidth\", {\n /**\n * Gets a value indicating whether the grid column width is considered to be `page width`.\n * @private\n */\n get: function () {\n return this.pageWidth;\n },\n set: function (value) {\n this.pageWidth = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"isChildGrid\", {\n /**\n * Gets or set if grid `is nested grid`.\n * @private\n */\n get: function () {\n return this.childGrid;\n },\n set: function (value) {\n this.childGrid = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGrid.prototype, \"size\", {\n /**\n * Gets the `size`.\n * @private\n */\n get: function () {\n if (this.gridSize.width === 0 && this.gridSize.height === 0) {\n this.gridSize = this.measure();\n return this.gridSize;\n }\n else {\n return this.gridSize;\n }\n },\n set: function (value) {\n this.gridSize = value;\n },\n enumerable: true,\n configurable: true\n });\n PdfGrid.prototype.draw = function (arg1, arg2, arg3, arg4) {\n if (arg2 instanceof PointF && typeof arg2.width === 'undefined' && typeof arg3 === 'undefined') {\n return this.drawHelper(arg1, arg2.x, arg2.y);\n }\n else if (typeof arg2 === 'number' && typeof arg3 === 'number' && typeof arg4 === 'undefined') {\n return this.drawHelper(arg1, arg2, arg3, null);\n }\n else if (arg2 instanceof RectangleF && typeof arg2.width !== 'undefined' && typeof arg3 === 'undefined') {\n return this.drawHelper(arg1, arg2, null);\n }\n else if (arg2 instanceof PointF && typeof arg2.width === 'undefined' && arg3 instanceof PdfLayoutFormat) {\n return this.drawHelper(arg1, arg2.x, arg2.y, arg3);\n }\n else if (typeof arg2 === 'number' && typeof arg3 === 'number' && (arg4 instanceof PdfLayoutFormat || arg4 == null)) {\n var width = (arg1.graphics.clientSize.width - arg2);\n var layoutRectangle = new RectangleF(arg2, arg3, width, 0);\n return this.drawHelper(arg1, layoutRectangle, arg4);\n }\n else if (arg2 instanceof RectangleF && typeof arg2.width !== 'undefined' && typeof arg3 === 'boolean') {\n return this.drawHelper(arg1, arg2, null);\n }\n else {\n return this.drawHelper(arg1, arg2, arg3);\n }\n };\n /**\n * `measures` this instance.\n * @private\n */\n PdfGrid.prototype.measure = function () {\n var height = 0;\n var width = this.columns.width;\n for (var i = 0; i < this.headers.count; i++) {\n var row = this.headers.getHeader(i);\n height += row.height;\n }\n for (var i = 0; i < this.rows.count; i++) {\n var row = this.rows.getRow(i);\n height += row.height;\n }\n return new SizeF(width, height);\n };\n PdfGrid.prototype.layout = function (param, isGridLayouter) {\n if (typeof isGridLayouter === 'undefined') {\n this.setSpan();\n this.layoutFormat = param.format;\n this.gridLocation = param.bounds;\n var result = this.layout(param, true);\n return result;\n }\n else {\n return this.layoutInternal(param);\n }\n };\n PdfGrid.prototype.setSpan = function () {\n var colSpan;\n var rowSpan = 1;\n var currentCellIndex;\n var currentRowIndex = 0;\n var rowCount = this.headers.count;\n for (var i = 0; i < rowCount; i++) {\n var row = this.headers.getHeader(i);\n var colCount = row.cells.count;\n for (var j = 0; j < colCount; j++) {\n var cell = row.cells.getCell(j);\n //Skip setting span map for already coverted rows/columns.\n if (!cell.isCellMergeContinue && !cell.isRowMergeContinue && (cell.columnSpan > 1 || cell.rowSpan > 1)) {\n if (cell.columnSpan + j > row.cells.count) {\n throw new Error('Invalid span specified at row ' + j.toString() + ' column ' + i.toString());\n }\n if (cell.rowSpan + i > this.headers.count) {\n throw new Error('Invalid span specified at Header ' + j.toString() + ' column ' + i.toString());\n }\n // if (this.rows.count !== 0 && cell.rowSpan + i > this.rows.count) {\n // throw new Error('Invalid span specified at row ' + j.toString() + ' column ' + i.toString());\n // }\n if (cell.columnSpan > 1 && cell.rowSpan > 1) {\n colSpan = cell.columnSpan;\n rowSpan = cell.rowSpan;\n currentCellIndex = j;\n currentRowIndex = i;\n cell.isCellMergeStart = true;\n cell.isRowMergeStart = true;\n //Set Column merges for first row\n while (colSpan > 1) {\n currentCellIndex++;\n row.cells.getCell(currentCellIndex).isCellMergeContinue = true;\n row.cells.getCell(currentCellIndex).isRowMergeContinue = true;\n row.cells.getCell(currentCellIndex).rowSpan = rowSpan;\n colSpan--;\n }\n currentCellIndex = j;\n colSpan = cell.columnSpan;\n //Set Row Merges and column merges foreach subsequent rows.\n while (rowSpan > 1) {\n currentRowIndex++;\n this.headers.getHeader(currentRowIndex).cells.getCell(j).isRowMergeContinue = true;\n this.headers.getHeader(currentRowIndex).cells.getCell(currentCellIndex).isRowMergeContinue = true;\n rowSpan--;\n while (colSpan > 1) {\n currentCellIndex++;\n this.headers.getHeader(currentRowIndex).cells.getCell(currentCellIndex).isCellMergeContinue = true;\n this.headers.getHeader(currentRowIndex).cells.getCell(currentCellIndex).isRowMergeContinue = true;\n colSpan--;\n }\n colSpan = cell.columnSpan;\n currentCellIndex = j;\n }\n }\n else if (cell.columnSpan > 1 && cell.rowSpan === 1) {\n colSpan = cell.columnSpan;\n currentCellIndex = j;\n cell.isCellMergeStart = true;\n //Set Column merges.\n while (colSpan > 1) {\n currentCellIndex++;\n row.cells.getCell(currentCellIndex).isCellMergeContinue = true;\n colSpan--;\n }\n }\n else if (cell.columnSpan === 1 && cell.rowSpan > 1) {\n rowSpan = cell.rowSpan;\n currentRowIndex = i;\n //Set row Merges.\n while (rowSpan > 1) {\n currentRowIndex++;\n this.headers.getHeader(currentRowIndex).cells.getCell(j).isRowMergeContinue = true;\n rowSpan--;\n }\n }\n }\n }\n }\n };\n /**\n * Gets the `format`.\n * @private\n */\n PdfGrid.prototype.getFormat = function (format) {\n var f = format;\n return f;\n };\n /**\n * `Layouts` the element.\n * @private\n */\n PdfGrid.prototype.layoutInternal = function (param) {\n this.initialWidth = param.bounds.width;\n var format = this.getFormat(param.format);\n this.currentPage = param.page;\n if (this.currentPage !== null) {\n var pageHeight = this.currentPage.getClientSize().height;\n var pageWidth = this.currentPage.getClientSize().width;\n this.currentPageBounds = this.currentPage.getClientSize();\n }\n else {\n throw Error('Can not set page as null');\n }\n this.currentGraphics = this.currentPage.graphics;\n var index = 0;\n index = this.currentGraphics.page.section.indexOf(this.currentGraphics.page);\n this.listOfNavigatePages.push(index);\n this.currentBounds = new RectangleF(new PointF(param.bounds.x, param.bounds.y), this.currentGraphics.clientSize);\n if (this.rows.count !== 0) {\n this.currentBounds.width = (param.bounds.width > 0) ? param.bounds.width :\n (this.currentBounds.width - this.rows.getRow(0).cells.getCell(0).style.borders.left.width / 2);\n }\n else if (this.headers.count !== 0) {\n this.currentBounds.width = param.bounds.width;\n }\n else {\n throw Error('Please add row or header into grid');\n }\n this.startLocation = new PointF(param.bounds.x, param.bounds.y);\n if (param.bounds.height > 0 && !this.isChildGrid) {\n this.currentBounds.height = param.bounds.height;\n }\n this.hType = this.style.horizontalOverflowType;\n if (!this.style.allowHorizontalOverflow) {\n this.measureColumnsWidth(this.currentBounds);\n this.columnRanges.push([0, this.columns.count - 1]);\n }\n else {\n this.measureColumnsWidth();\n this.determineColumnDrawRanges();\n }\n var result = this.layoutOnPage(param);\n return result;\n };\n PdfGrid.prototype.measureColumnsWidth = function (bounds) {\n if (typeof bounds !== 'undefined') {\n var widths = this.columns.getDefaultWidths(bounds.width);\n var tempWidth = this.columns.getColumn(0).width;\n for (var i = 0, count = this.columns.count; i < count; i++) {\n this.columns.getColumn(i).width = widths[i];\n }\n }\n else {\n var widths = [];\n var cellWidth = 0;\n var cellWidths = 0;\n if (this.headers.count > 0) {\n var colCount = this.headers.getHeader(0).cells.count;\n var rowCount = this.headers.count;\n for (var i = 0; i < colCount; i++) {\n cellWidth = 0;\n for (var j = 0; j < rowCount; j++) {\n var rowWidth = Math.min(this.initialWidth, this.headers.getHeader(j).cells.getCell(i).width);\n cellWidth = Math.max(cellWidth, rowWidth);\n }\n widths[i] = cellWidth;\n }\n }\n else {\n var colCount = this.rows.getRow(0).cells.count;\n var rowCount = this.rows.count;\n for (var i = 0; i < colCount; i++) {\n cellWidth = 0;\n for (var j = 0; j < rowCount; j++) {\n var rowWidth = Math.min(this.initialWidth, this.rows.getRow(j).cells.getCell(i).width);\n cellWidth = Math.max(cellWidth, rowWidth);\n }\n widths[i] = cellWidth;\n }\n }\n cellWidth = 0;\n for (var i = 0, colCount = this.columns.count; i < colCount; i++) {\n for (var j = 0, rowCount = this.rows.count; j < rowCount; j++) {\n if (this.rows.getRow(j).cells.getCell(i).columnSpan == 1 || this.rows.getRow(j).cells.getCell(i).value !== null || this.rows.getRow(j).cells.getCell(i).rowSpan >= 1) {\n if (this.rows.getRow(j).cells.getCell(i).value !== null &&\n !this.rows.getRow(j).grid.style.allowHorizontalOverflow) {\n var value = this.rows.getRow(j).grid.style.cellPadding.right +\n this.rows.getRow(j).grid.style.cellPadding.left\n + this.rows.getRow(j).cells.getCell(i).style.borders.left.width / 2\n + this.gridLocation.x;\n this.rows.getRow(j).cells.getCell(i).value.initialWidth = this.initialWidth - value;\n }\n var rowWidth = 0;\n var internalWidth = this.rows.getRow(j).cells.getCell(i).width;\n internalWidth += this.rows.getRow(j).cells.getCell(i).style.borders.left.width;\n internalWidth += this.rows.getRow(j).cells.getCell(i).style.borders.right.width;\n var internalHeight = this.rows.getRow(j).cells.getCell(i).height;\n internalHeight += (this.rows.getRow(j).cells.getCell(i).style.borders.top.width);\n internalHeight += (this.rows.getRow(j).cells.getCell(i).style.borders.bottom.width);\n var isCorrectWidth = (internalWidth + this.gridLocation.x) > this.currentGraphics.clientSize.width;\n var isCorrectHeight = (internalHeight + this.gridLocation.y) > this.currentGraphics.clientSize.height;\n if (isCorrectWidth || isCorrectHeight) {\n throw Error('Image size exceeds client size of the page. Can not insert this image');\n }\n rowWidth = Math.min(this.initialWidth, this.rows.getRow(j).cells.getCell(i).width);\n cellWidth = Math.max(widths[i], Math.max(cellWidth, rowWidth));\n cellWidth = Math.max(this.columns.getColumn(i).width, cellWidth);\n }\n }\n widths[i] = cellWidth;\n cellWidth = 0;\n }\n for (var i = 0, count = this.columns.count; i < count; i++) {\n this.columns.getColumn(i).width = widths[i];\n }\n }\n };\n /* tslint:enable */\n /**\n * `Determines the column draw ranges`.\n * @private\n */\n PdfGrid.prototype.determineColumnDrawRanges = function () {\n var startColumn = 0;\n var endColumn = 0;\n var cellWidths = 0;\n var availableWidth = this.currentGraphics.clientSize.width - this.currentBounds.x;\n for (var i = 0; i < this.columns.count; i++) {\n cellWidths += this.columns.getColumn(i).width;\n if (cellWidths >= availableWidth) {\n var subWidths = 0;\n for (var j = startColumn; j <= i; j++) {\n subWidths += this.columns.getColumn(j).width;\n if (subWidths > availableWidth) {\n break;\n }\n endColumn = j;\n }\n this.columnRanges.push([startColumn, endColumn]);\n startColumn = endColumn + 1;\n endColumn = startColumn;\n cellWidths = (endColumn <= i) ? this.columns.getColumn(i).width : 0;\n }\n }\n // if (startColumn !== this.columns.Count) {\n this.columnRanges.push([startColumn, this.columns.count - 1]);\n // }\n };\n /**\n * `Layouts the on page`.\n * @private\n */\n PdfGrid.prototype.layoutOnPage = function (param) {\n /* tslint:disable */\n this.pageBounds.x = param.bounds.x;\n this.pageBounds.y = param.bounds.y;\n this.pageBounds.height = param.bounds.height;\n var format = this.getFormat(param.format);\n var endArgs = null;\n var result = null;\n var layoutedPages = new TemporaryDictionary();\n var startPage = param.page;\n var isParentCell = false;\n var cellBounds = [];\n for (var index = 0; index < this.columnRanges.length; index++) {\n var range = this.columnRanges[index];\n this.cellStartIndex = range[0];\n this.cellEndIndex = range[1];\n var returnObject = this.raiseBeforePageLayout(this.currentPage, this.currentBounds, this.currentRowIndex);\n this.currentBounds = returnObject.currentBounds;\n this.currentRowIndex = returnObject.currentRowIndex;\n // if (returnObject.returnValue) {\n // result = new PdfGridLayoutResult(this.currentPage, this.currentBounds);\n // break;\n // }\n //Draw Headers.\n var drawHeader = void 0;\n for (var i_1 = 0; i_1 < this.headers.count; i_1++) {\n var row = this.headers.getHeader(i_1);\n var headerHeight = this.currentBounds.y;\n // RowLayoutResult\n var headerResult = this.drawRow(row);\n // if (headerHeight === this.currentBounds.y) {\n // drawHeader = true;\n // if (PdfGrid.repeatRowIndex === -1) {\n // PdfGrid.repeatRowIndex = this.rows.getRow.indexOf(row);\n // }\n // } else {\n drawHeader = false;\n // }\n }\n var i = 0;\n var length_1 = this.rows.count;\n var repeatRow = void 0;\n var startingHeight = 0;\n var flag = true;\n //Here is to draw parent Grid and Cells\n cellBounds = [];\n //Draw row by row with the specified cell range.\n for (var j = 0; j < this.rows.count; j++) {\n var row = this.rows.getRow(j);\n i++;\n this.currentRowIndex = i - 1;\n var originalHeight = this.currentBounds.y;\n startPage = this.currentPage;\n PdfGrid.repeatRowIndex = -1;\n var rowResult = this.drawRow(row);\n cellBounds.push(rowResult.bounds.width);\n //if height remains same, it is understood that row is not drawn in the page\n if (originalHeight === this.currentBounds.y) {\n repeatRow = true;\n PdfGrid.repeatRowIndex = this.rows.rowCollection.indexOf(row);\n }\n else {\n repeatRow = false;\n PdfGrid.repeatRowIndex = -1;\n }\n if (!rowResult.isFinish && startPage !== null && format.layout !== PdfLayoutType.OnePage && repeatRow) {\n // During pagination, cell position is maintained here.\n this.startLocation.x = this.currentBounds.x;\n var isAddNextPage = false;\n this.currentPage = this.getNextPage(format);\n if ((param.format !== null) && !param.format.usePaginateBounds && param.bounds !== null &&\n param.bounds.height > 0 && !this.isChildGrid) {\n this.currentBounds.height = param.bounds.height;\n }\n if ((param.format !== null) && !param.format.usePaginateBounds && param.bounds !== null &&\n param.bounds.y > 0 && !this.isChildGrid) {\n this.currentBounds.y = param.bounds.y;\n }\n this.startLocation.y = this.currentBounds.y;\n if ((format.paginateBounds.x === format.paginateBounds.y) &&\n (format.paginateBounds.y === format.paginateBounds.height) &&\n (format.paginateBounds.height === format.paginateBounds.width) && (format.paginateBounds.width === 0)) {\n this.currentBounds.x += this.startLocation.x;\n }\n if (this.currentBounds.x === PdfBorders.default.left.width / 2) {\n this.currentBounds.y += this.startLocation.x;\n }\n if (this.repeatHeader) {\n for (var i_2 = 0; i_2 < this.headers.count; i_2++) {\n var header = this.headers.getHeader(i_2);\n this.drawRow(header);\n }\n }\n this.drawRow(row);\n if (this.currentPage !== null && !layoutedPages.containsKey(this.currentPage)) {\n layoutedPages.add(this.currentPage, range);\n }\n }\n }\n var isPdfGrid = false;\n var maximumCellBoundsWidth = 0;\n if (cellBounds.length > 0) {\n maximumCellBoundsWidth = cellBounds[0];\n }\n var largeNavigatePage = [[0, 0]];\n if (!isPdfGrid && cellBounds.length > 0) {\n for (var c = 0; c < i - 1; c++) {\n if (maximumCellBoundsWidth < cellBounds[c]) {\n maximumCellBoundsWidth = cellBounds[c];\n }\n }\n this.rowLayoutBoundsWidth = maximumCellBoundsWidth;\n }\n else {\n this.rowLayoutBoundsWidth = largeNavigatePage[0][1];\n }\n if (this.columnRanges.length - 1 !== index && this.columnRanges.length > 1 && format.layout !== PdfLayoutType.OnePage) {\n this.currentPage = this.getNextPage(format);\n if ((format.paginateBounds.x === format.paginateBounds.y) && (format.paginateBounds.y === format.paginateBounds.height)\n && (format.paginateBounds.height === format.paginateBounds.width) && (format.paginateBounds.width === 0)) {\n this.currentBounds.x += this.startLocation.x;\n this.currentBounds.y += this.startLocation.y;\n // this.currentBounds.height = this.pageBounds.height;\n }\n }\n }\n result = this.getLayoutResult();\n if (this.style.allowHorizontalOverflow && this.style.horizontalOverflowType == PdfHorizontalOverflowType.NextPage) {\n this.reArrangePages(layoutedPages);\n }\n this.raisePageLayouted(result);\n return result;\n }; /* tslint:enable */\n /**\n * Gets the `next page`.\n * @private\n */\n PdfGrid.prototype.getNextPage = function (format) {\n var section = this.currentPage.section;\n var nextPage = null;\n var index = section.indexOf(this.currentPage);\n this.flag = false;\n if (index === section.count - 1) {\n nextPage = section.add();\n }\n else {\n nextPage = section.getPages()[index + 1];\n }\n this.currentGraphics = nextPage.graphics;\n var pageindex = this.currentGraphics.page.section.indexOf(this.currentGraphics.page);\n if (!(this.listOfNavigatePages.indexOf(pageindex) !== -1)) {\n this.listOfNavigatePages.push(pageindex);\n }\n this.currentBounds = new RectangleF(new PointF(0, 0), nextPage.getClientSize());\n // if ((format.PaginateBounds.x !== format.PaginateBounds.y) && (format.PaginateBounds.y !== format.PaginateBounds.height)\n // && (format.PaginateBounds.height !== format.PaginateBounds.width) && (format.PaginateBounds.width !== 0)) {\n // this.currentBounds.x = format.PaginateBounds.x;\n // this.currentBounds.y = format.PaginateBounds.y;\n // this.currentBounds.height = format.PaginateBounds.height;\n // }\n return nextPage;\n };\n /**\n * Gets the `layout result`.\n * @private\n */\n PdfGrid.prototype.getLayoutResult = function () {\n var bounds;\n /* tslint:disable */\n bounds = new RectangleF(this.startLocation, new SizeF(this.currentBounds.width, this.currentBounds.y - this.startLocation.y));\n /* tslint:enable */\n return new PdfGridLayoutResult(this.currentPage, bounds);\n };\n /**\n * `Recalculate row height` for the split cell to be drawn.\n * @private\n */\n PdfGrid.prototype.ReCalculateHeight = function (row, height) {\n var newHeight = 0.0;\n // for (let i : number = this.cellStartIndex; i <= this.cellEndIndex; i++) {\n // if (!(row.cells.getCell(i).RemainingString === null || row.cells.getCell(i).RemainingString === '' ||\n // typeof row.cells.getCell(i).RemainingString === 'undefined')) {\n // newHeight = Math.max(newHeight, row.cells.getCell(i).MeasureHeight());\n // }\n // }\n return Math.max(height, newHeight);\n };\n /**\n * `Raises BeforePageLayout event`.\n * @private\n */\n PdfGrid.prototype.raiseBeforePageLayout = function (currentPage, currentBounds, currentRow) {\n var cancel = false;\n if (this.raiseBeginPageLayout) {\n var args = new PdfGridBeginPageLayoutEventArgs(currentBounds, currentPage, currentRow);\n this.beginPageLayout(this, args);\n // if (currentBounds !== args.Bounds) {\n // this.isChanged = true;\n // this.currentLocation = new PointF(args.Bounds.x, args.Bounds.y);\n // this.measureColumnsWidth(new RectangleF(new PointF(args.Bounds.x, args.Bounds.y) ,\n // new SizeF(args.Bounds.width + args.Bounds.x ,\n // args.Bounds.height)));\n // }\n cancel = args.cancel;\n currentBounds = args.bounds;\n currentRow = args.startRowIndex;\n }\n return { returnValue: cancel, currentBounds: currentBounds, currentRowIndex: currentRow };\n };\n /**\n * `Raises PageLayout event` if needed.\n * @private\n */\n PdfGrid.prototype.raisePageLayouted = function (result) {\n var args = new PdfGridEndPageLayoutEventArgs(result);\n if (this.raiseEndPageLayout) {\n this.endPageLayout(this, args);\n }\n return args;\n };\n PdfGrid.prototype.drawRow = function (row, result, height) {\n if (typeof result === 'undefined') {\n //.. Check if required space available.\n //.....If the row conains spans which falls through more than one page, then draw the row to next page.\n var result_1 = new RowLayoutResult();\n var rowHeightWithSpan = 0;\n var location_1 = new PointF(0, 0);\n var size = new SizeF(0, 0);\n var isHeader = false;\n if (row.rowSpanExists) {\n var maxSpan = 0;\n var currRowIndex = this.rows.rowCollection.indexOf(row);\n if (currRowIndex === -1) {\n currRowIndex = this.headers.indexOf(row);\n if (currRowIndex !== -1) {\n isHeader = true;\n }\n }\n for (var i = 0; i < row.cells.count; i++) {\n var cell = row.cells.getCell(i);\n maxSpan = Math.max(maxSpan, cell.rowSpan);\n }\n for (var i = currRowIndex; i < currRowIndex + maxSpan; i++) {\n rowHeightWithSpan += (isHeader ? this.headers.getHeader(i).height : this.rows.getRow(i).height);\n }\n var rowMaxHeight = rowHeightWithSpan;\n for (var i = 0; i < row.cells.count; i++) {\n rowMaxHeight = rowMaxHeight > row.cells.getCell(i).height ? rowMaxHeight : row.cells.getCell(i).height;\n }\n var nextRow = this.headers.getHeader(this.headers.indexOf(row) + 1);\n var flag = true;\n for (var i = 0; i < nextRow.cells.count; i++) {\n if (nextRow.cells.getCell(i).value !== '' && nextRow.cells.getCell(i).value !== undefined) {\n flag = false;\n break;\n }\n }\n if ((rowMaxHeight > rowHeightWithSpan) && flag) {\n row.height += (rowMaxHeight - rowHeightWithSpan);\n }\n }\n var calculatedHeight = row.rowBreakHeight > 0.0 ? row.rowBreakHeight : row.height;\n if (this.currentBounds.y + calculatedHeight > this.currentPageBounds.height ||\n this.currentBounds.y + calculatedHeight > (this.currentBounds.height + this.startLocation.y) ||\n this.currentBounds.y + rowHeightWithSpan > this.currentPageBounds.height) {\n // If a row is repeated and still cannot fit in page, proceed draw.\n // if (PdfGrid.repeatRowIndex > -1 && PdfGrid.repeatRowIndex === row.RowIndex) {\n // if (this.AllowRowBreakAcrossPages) {\n // result.IsFinish = true;\n // // this.DrawRowWithBreak(ref result, row, height);\n // } else {\n // result.IsFinish = false;\n // this.drawRow(row, result, height);\n // }\n // } else {\n result_1.isFinish = false;\n // }\n }\n else {\n result_1.isFinish = true;\n this.drawRow(row, result_1, calculatedHeight);\n }\n return result_1;\n }\n else {\n var skipcell = false;\n var location_2 = new PointF(this.currentBounds.x, this.currentBounds.y);\n result.bounds = new RectangleF(location_2, new SizeF(0, 0));\n height = this.ReCalculateHeight(row, height);\n for (var i = this.cellStartIndex; i <= this.cellEndIndex; i++) {\n var cancelSpans = ((i > this.cellEndIndex + 1) && (row.cells.getCell(i).columnSpan > 1));\n // let cancelSpans : boolean = false;\n if (!cancelSpans) {\n for (var j = 1; j < row.cells.getCell(i).columnSpan; j++) {\n row.cells.getCell(i + j).isCellMergeContinue = true;\n }\n }\n var size = new SizeF(this.columns.getColumn(i).width, height);\n // if (size.width > this.currentGraphics.ClientSize.width) {\n // size.width = this.currentGraphics.ClientSize.width;\n // }\n // if (this.IsChildGrid && this.style.AllowHorizontalOverflow) {\n // if (size.width >= this.currentGraphics.ClientSize.width) {\n // size.width -= 2 * this.currentBounds.x;\n // }\n // }\n /* tslint:disable */\n if (!this.CheckIfDefaultFormat(this.columns.getColumn(i).format) &&\n this.CheckIfDefaultFormat(row.cells.getCell(i).stringFormat)) {\n row.cells.getCell(i).stringFormat = this.columns.getColumn(i).format;\n }\n var cellstyle = row.cells.getCell(i).style;\n var tempValue = ((typeof row.cells.getCell(i).value === 'string' &&\n row.cells.getCell(i).value !== null) ? row.cells.getCell(i).value : '');\n row.cells.getCell(i).style = this.RaiseBeforeCellDraw(this.currentGraphics, this.currentRowIndex, i, new RectangleF(location_2, size), tempValue, cellstyle);\n // if (!skipcell) {\n // let stringResult : PdfStringLayoutResult = row.cells.getCell(i).draw(this.currentGraphics, new RectangleF(location, size), cancelSpans);\n var stringResult = row.cells.getCell(i).draw(this.currentGraphics, new RectangleF(location_2, size), cancelSpans);\n if (row.grid.style.allowHorizontalOverflow && (row.cells.getCell(i).columnSpan > this.cellEndIndex || i + row.cells.getCell(i).columnSpan > this.cellEndIndex + 1) && this.cellEndIndex < row.cells.count - 1) {\n row.rowOverflowIndex = this.cellEndIndex;\n }\n if (row.grid.style.allowHorizontalOverflow && (row.rowOverflowIndex > 0 && (row.cells.getCell(i).columnSpan > this.cellEndIndex || i + row.cells.getCell(i).columnSpan > this.cellEndIndex + 1)) && row.cells.getCell(i).columnSpan - this.cellEndIndex + i - 1 > 0) {\n row.cells.getCell(row.rowOverflowIndex + 1).value = stringResult !== null ? (stringResult.remainder !== undefined) ? stringResult.remainder : '' : '';\n row.cells.getCell(row.rowOverflowIndex + 1).stringFormat = row.cells.getCell(i).stringFormat;\n row.cells.getCell(row.rowOverflowIndex + 1).style = row.cells.getCell(i).style;\n row.cells.getCell(row.rowOverflowIndex + 1).columnSpan = row.cells.getCell(i).columnSpan - this.cellEndIndex + i - 1;\n }\n // }\n /* tslint:enable */\n tempValue = ((typeof row.cells.getCell(i).value === 'string' &&\n row.cells.getCell(i).value !== null) ? row.cells.getCell(i).value : '');\n this.RaiseAfterCellDraw(this.currentGraphics, this.currentRowIndex, i, new RectangleF(location_2, size), tempValue, row.cells.getCell(i).style);\n location_2.x += this.columns.getColumn(i).width;\n }\n // if (!row.RowMergeComplete || row.isRowHeightSet) {\n this.currentBounds.y += height;\n // }\n result.bounds = new RectangleF(new PointF(result.bounds.x, result.bounds.y), new SizeF(location_2.x, location_2.y));\n }\n };\n /**\n * Checks if the given format `is default format` or not.\n * @private\n */\n PdfGrid.prototype.CheckIfDefaultFormat = function (format) {\n var defaultFormat = new PdfStringFormat();\n return (format.alignment === defaultFormat.alignment && format.characterSpacing === defaultFormat.characterSpacing &&\n format.clipPath === defaultFormat.clipPath && format.firstLineIndent === defaultFormat.firstLineIndent &&\n format.horizontalScalingFactor === defaultFormat.horizontalScalingFactor &&\n format.lineAlignment === defaultFormat.lineAlignment\n && format.lineLimit === defaultFormat.lineLimit && format.lineSpacing === defaultFormat.lineSpacing &&\n format.measureTrailingSpaces === defaultFormat.measureTrailingSpaces && format.noClip === defaultFormat.noClip &&\n format.paragraphIndent === defaultFormat.paragraphIndent && format.rightToLeft === defaultFormat.rightToLeft &&\n format.subSuperScript === defaultFormat.subSuperScript && format.wordSpacing === defaultFormat.wordSpacing &&\n format.wordWrap === defaultFormat.wordWrap);\n };\n /**\n * `Raises BeforeCellDraw event`.\n * @private\n */\n PdfGrid.prototype.RaiseBeforeCellDraw = function (graphics, rowIndex, cellIndex, bounds, value, style) {\n var args = null;\n if (this.raiseBeginCellDraw) {\n args = new PdfGridBeginCellDrawEventArgs(graphics, rowIndex, cellIndex, bounds, value, style);\n this.beginCellDraw(this, args);\n style = args.style;\n }\n return style;\n };\n /**\n * `Raises AfterCellDraw event`.\n * @private\n */\n PdfGrid.prototype.RaiseAfterCellDraw = function (graphics, rowIndex, cellIndex, bounds, value, cellstyle) {\n var args = null;\n if (this.raiseEndCellDraw) {\n args = new PdfGridEndCellDrawEventArgs(graphics, rowIndex, cellIndex, bounds, value, cellstyle);\n this.endCellDraw(this, args);\n }\n };\n /**\n * `Rearranges the pages`.\n * @private\n */\n PdfGrid.prototype.reArrangePages = function (layoutedPages) {\n var document = this.currentPage.document;\n var pages = [];\n var keys = layoutedPages.keys();\n var values = layoutedPages.values();\n for (var i = 0; i < keys.length; i++) {\n var page = keys[i];\n page.section = null;\n pages.push(page);\n document.pages.remove(page);\n }\n /* tslint:disable */\n for (var i = 0; i < layoutedPages.size(); i++) {\n var count = 0;\n for (var j = i, count_1 = (layoutedPages.size() / this.columnRanges.length); j < layoutedPages.size(); j += count_1) {\n var page = pages[j];\n if (document.pages.indexOf(page) === -1) {\n document.pages.add(page);\n }\n }\n }\n /* tslint:enable */\n };\n /**\n * @hidden\n * @private\n */\n PdfGrid.repeatRowIndex = -1;\n return PdfGrid;\n}(PdfLayoutElement));\nexport { PdfGrid };\n/**\n * `GridCellEventArgs` class is alternate for grid events.\n */\nvar GridCellEventArgs = /** @class */ (function () {\n // Constructors\n /**\n * Initialize a new instance for `GridCellEventArgs` class.\n * @private\n */\n function GridCellEventArgs(graphics, rowIndex, cellIndex, bounds, value) {\n this.gridRowIndex = rowIndex;\n this.gridCellIndex = cellIndex;\n this.internalValue = value;\n this.gridBounds = bounds;\n this.pdfGraphics = graphics;\n }\n Object.defineProperty(GridCellEventArgs.prototype, \"rowIndex\", {\n // Properties\n /**\n * Gets the value of current `row index`.\n * @private\n */\n get: function () {\n return this.gridRowIndex;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GridCellEventArgs.prototype, \"cellIndex\", {\n /**\n * Gets the value of current `cell index`.\n * @private\n */\n get: function () {\n return this.gridCellIndex;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GridCellEventArgs.prototype, \"value\", {\n /**\n * Gets the actual `value` of current cell.\n * @private\n */\n get: function () {\n return this.internalValue;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GridCellEventArgs.prototype, \"bounds\", {\n /**\n * Gets the `bounds` of current cell.\n * @private\n */\n get: function () {\n return this.gridBounds;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GridCellEventArgs.prototype, \"graphics\", {\n /**\n * Gets the instance of `current graphics`.\n * @private\n */\n get: function () {\n return this.pdfGraphics;\n },\n enumerable: true,\n configurable: true\n });\n return GridCellEventArgs;\n}());\nexport { GridCellEventArgs };\n/**\n * `PdfGridBeginCellDrawEventArgs` class is alternate for begin cell draw events.\n */\nvar PdfGridBeginCellDrawEventArgs = /** @class */ (function (_super) {\n __extends(PdfGridBeginCellDrawEventArgs, _super);\n // Constructors\n /**\n * Initializes a new instance of the `StartCellLayoutEventArgs` class.\n * @private\n */\n function PdfGridBeginCellDrawEventArgs(graphics, rowIndex, cellIndex, bounds, value, style) {\n var _this = _super.call(this, graphics, rowIndex, cellIndex, bounds, value) || this;\n _this.style = style;\n return _this;\n }\n Object.defineProperty(PdfGridBeginCellDrawEventArgs.prototype, \"skip\", {\n // Properties\n /**\n * Gets or sets a value indicating whether the value of this cell should be `skipped`.\n * @private\n */\n get: function () {\n return this.bSkip;\n },\n set: function (value) {\n this.bSkip = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(PdfGridBeginCellDrawEventArgs.prototype, \"style\", {\n /**\n * Gets or sets a `style` value of the cell.\n * @private\n */\n get: function () {\n return this.cellStyle;\n },\n set: function (value) {\n this.cellStyle = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGridBeginCellDrawEventArgs;\n}(GridCellEventArgs));\nexport { PdfGridBeginCellDrawEventArgs };\n/**\n * `PdfGridEndCellDrawEventArgs` class is alternate for end cell draw events.\n */\nvar PdfGridEndCellDrawEventArgs = /** @class */ (function (_super) {\n __extends(PdfGridEndCellDrawEventArgs, _super);\n // Constructors\n /**\n * Initializes a new instance of the `PdfGridEndCellLayoutEventArgs` class.\n * @private\n */\n function PdfGridEndCellDrawEventArgs(graphics, rowIndex, cellIndex, bounds, value, style) {\n var _this = _super.call(this, graphics, rowIndex, cellIndex, bounds, value) || this;\n _this.cellStyle = style;\n return _this;\n }\n Object.defineProperty(PdfGridEndCellDrawEventArgs.prototype, \"style\", {\n // Propertise\n /**\n * Get the `PdfGridCellStyle`.\n * @private\n */\n get: function () {\n return this.cellStyle;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGridEndCellDrawEventArgs;\n}(GridCellEventArgs));\nexport { PdfGridEndCellDrawEventArgs };\n/**\n * `PdfGridCancelEventArgs` class is alternate for cancel events.\n */\nvar PdfCancelEventArgs = /** @class */ (function () {\n function PdfCancelEventArgs() {\n }\n Object.defineProperty(PdfCancelEventArgs.prototype, \"cancel\", {\n // Properties\n /**\n * Gets and Sets the value of `cancel`.\n * @private\n */\n get: function () {\n return this.isCancel;\n },\n set: function (value) {\n this.isCancel = value;\n },\n enumerable: true,\n configurable: true\n });\n return PdfCancelEventArgs;\n}());\nexport { PdfCancelEventArgs };\n/**\n * `BeginPageLayoutEventArgs` class is alternate for begin page layout events.\n */\nvar BeginPageLayoutEventArgs = /** @class */ (function (_super) {\n __extends(BeginPageLayoutEventArgs, _super);\n // Constructors\n /**\n * Initializes a new instance of the `BeginPageLayoutEventArgs` class with the specified rectangle and page.\n * @private\n */\n function BeginPageLayoutEventArgs(bounds, page) {\n var _this = _super.call(this) || this;\n _this.bounds = bounds;\n _this.pdfPage = page;\n return _this;\n }\n Object.defineProperty(BeginPageLayoutEventArgs.prototype, \"bounds\", {\n // Properties\n /**\n * Gets or sets value that indicates the lay outing `bounds` on the page.\n * @private\n */\n get: function () {\n return this.cellBounds;\n },\n set: function (value) {\n this.cellBounds = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BeginPageLayoutEventArgs.prototype, \"page\", {\n /**\n * Gets the `page` where the lay outing should start.\n * @private\n */\n get: function () {\n return this.pdfPage;\n },\n enumerable: true,\n configurable: true\n });\n return BeginPageLayoutEventArgs;\n}(PdfCancelEventArgs));\nexport { BeginPageLayoutEventArgs };\n/**\n * `EndPageLayoutEventArgs` class is alternate for end page layout events.\n */\nvar EndPageLayoutEventArgs = /** @class */ (function (_super) {\n __extends(EndPageLayoutEventArgs, _super);\n // Constructors\n /**\n * Initializes a new instance of the `EndPageLayoutEventArgs` class. with the specified 'PdfLayoutResult'.\n * @private\n */\n function EndPageLayoutEventArgs(result) {\n var _this = _super.call(this) || this;\n _this.layoutResult = result;\n return _this;\n }\n Object.defineProperty(EndPageLayoutEventArgs.prototype, \"result\", {\n // Properties\n /**\n * Gets the lay outing `result` of the page.\n * @private\n */\n get: function () {\n return this.layoutResult;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EndPageLayoutEventArgs.prototype, \"nextPage\", {\n /**\n * Gets or sets a value indicating the `next page` where the element should be layout.\n * @private\n */\n get: function () {\n return this.nextPdfPage;\n },\n set: function (value) {\n this.nextPdfPage = value;\n },\n enumerable: true,\n configurable: true\n });\n return EndPageLayoutEventArgs;\n}(PdfCancelEventArgs));\nexport { EndPageLayoutEventArgs };\n/**\n * `PdfGridBeginPageLayoutEventArgs` class is alternate for begin page layout events.\n */\nvar PdfGridBeginPageLayoutEventArgs = /** @class */ (function (_super) {\n __extends(PdfGridBeginPageLayoutEventArgs, _super);\n // Constructors\n /**\n * Initialize a new instance of `PdfGridBeginPageLayoutEventArgs` class.\n * @private\n */\n function PdfGridBeginPageLayoutEventArgs(bounds, page, startRow) {\n var _this = _super.call(this, bounds, page) || this;\n _this.startRow = startRow;\n return _this;\n }\n Object.defineProperty(PdfGridBeginPageLayoutEventArgs.prototype, \"startRowIndex\", {\n // Properties\n /**\n * Gets the `start row index`.\n * @private\n */\n get: function () {\n return this.startRow;\n },\n enumerable: true,\n configurable: true\n });\n return PdfGridBeginPageLayoutEventArgs;\n}(BeginPageLayoutEventArgs));\nexport { PdfGridBeginPageLayoutEventArgs };\n/**\n * `PdfGridEndPageLayoutEventArgs` class is alternate for begin page layout events.\n */\nvar PdfGridEndPageLayoutEventArgs = /** @class */ (function (_super) {\n __extends(PdfGridEndPageLayoutEventArgs, _super);\n // Constructors\n /**\n * Initialize a new instance of `PdfGridEndPageLayoutEventArgs` class.\n * @private\n */\n function PdfGridEndPageLayoutEventArgs(result) {\n return _super.call(this, result) || this;\n }\n return PdfGridEndPageLayoutEventArgs;\n}(EndPageLayoutEventArgs));\nexport { PdfGridEndPageLayoutEventArgs };\n/**\n * `RowLayoutResult` class to store layout result of rows.\n */\nvar RowLayoutResult = /** @class */ (function () {\n //Constructors\n /**\n * Initializes a new instance of the `RowLayoutResult` class.\n * @private\n */\n function RowLayoutResult() {\n this.layoutedBounds = new RectangleF(0, 0, 0, 0);\n }\n Object.defineProperty(RowLayoutResult.prototype, \"isFinish\", {\n /**\n * Gets or sets a value indicating whether this instance `is finish`.\n * @private\n */\n get: function () {\n return this.bIsFinished;\n },\n set: function (value) {\n this.bIsFinished = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(RowLayoutResult.prototype, \"bounds\", {\n /**\n * Gets or sets the `bounds`.\n * @private\n */\n get: function () {\n return this.layoutedBounds;\n },\n set: function (value) {\n this.layoutedBounds = value;\n },\n enumerable: true,\n configurable: true\n });\n return RowLayoutResult;\n}());\nexport { RowLayoutResult };\n/**\n * `PdfGridLayoutResult` class represents the results of the PdfGrid including bounds and resultant page.\n */\nvar PdfGridLayoutResult = /** @class */ (function (_super) {\n __extends(PdfGridLayoutResult, _super);\n // Constructor\n /**\n * Initializes a new instance of the `PdfGridLayoutResult` class with the current page and bounds.\n * @private\n */\n function PdfGridLayoutResult(page, bounds) {\n return _super.call(this, page, bounds) || this;\n }\n return PdfGridLayoutResult;\n}(PdfLayoutResult));\nexport { PdfGridLayoutResult };\n","import { print as printWindow, createElement, isNullOrUndefined, Browser, SvgRenderer } from '@syncfusion/ej2-base';\nimport { getElement } from '../utils/helper';\nimport { beforePrint } from '../model/constants';\nimport { PdfPageOrientation, PdfDocument, PdfBitmap } from '@syncfusion/ej2-pdf-export';\nvar ExportUtils = /** @class */ (function () {\n /**\n * Constructor for chart and accumulation annotation\n * @param control\n */\n function ExportUtils(control) {\n this.control = control;\n }\n /**\n * To print the accumulation and chart elements\n * @param elements\n */\n ExportUtils.prototype.print = function (elements) {\n this.printWindow = window.open('', 'print', 'height=' + window.outerHeight + ',width=' + window.outerWidth + ',tabbar=no');\n this.printWindow.moveTo(0, 0);\n this.printWindow.resizeTo(screen.availWidth, screen.availHeight);\n var argsData = {\n cancel: false, htmlContent: this.getHTMLContent(elements), name: beforePrint\n };\n this.control.trigger(beforePrint, argsData);\n if (!argsData.cancel) {\n printWindow(argsData.htmlContent, this.printWindow);\n }\n };\n /**\n * To get the html string of the chart and accumulation\n * @param elements\n * @private\n */\n ExportUtils.prototype.getHTMLContent = function (elements) {\n var div = createElement('div');\n if (elements) {\n if (elements instanceof Array) {\n elements.forEach(function (value) {\n div.appendChild(getElement(value).cloneNode(true));\n });\n }\n else if (elements instanceof Element) {\n div.appendChild(elements.cloneNode(true));\n }\n else {\n div.appendChild(getElement(elements).cloneNode(true));\n }\n }\n else {\n div.appendChild(this.control.element.cloneNode(true));\n }\n return div;\n };\n /**\n * To export the file as image/svg format\n * @param type\n * @param fileName\n */\n ExportUtils.prototype.export = function (type, fileName, orientation, controls, width, height) {\n var _this = this;\n var controlValue = this.getControlsValue(controls);\n width = width ? width : controlValue.width;\n height = height ? height : controlValue.height;\n var element = createElement('canvas', {\n id: 'ej2-canvas',\n attrs: {\n 'width': width.toString(),\n 'height': height.toString()\n }\n });\n var isDownload = !(Browser.userAgent.toString().indexOf('HeadlessChrome') > -1);\n orientation = isNullOrUndefined(orientation) ? PdfPageOrientation.Landscape : orientation;\n var svgData = '' +\n controlValue.svg.outerHTML +\n ' ';\n var url = window.URL.createObjectURL(new Blob(type === 'SVG' ? [svgData] :\n [(new XMLSerializer()).serializeToString(controlValue.svg)], { type: 'image/svg+xml' }));\n if (type === 'SVG') {\n this.triggerDownload(fileName, type, url, isDownload);\n }\n else {\n var image_1 = new Image();\n var ctx_1 = element.getContext('2d');\n image_1.onload = (function () {\n ctx_1.drawImage(image_1, 0, 0);\n window.URL.revokeObjectURL(url);\n if (type === 'PDF') {\n var document_1 = new PdfDocument();\n var imageString = element.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');\n document_1.pageSettings.orientation = orientation;\n imageString = imageString.slice(imageString.indexOf(',') + 1);\n document_1.pages.add().graphics.drawImage(new PdfBitmap(imageString), 0, 0, width, height);\n if (isDownload) {\n document_1.save(fileName + '.pdf');\n document_1.destroy();\n }\n }\n else {\n if (window.navigator.msSaveOrOpenBlob) {\n window.navigator.msSaveOrOpenBlob(element.msToBlob(), fileName + '.' + type.toLocaleLowerCase());\n }\n else {\n _this.triggerDownload(fileName, type, element.toDataURL('image/png').replace('image/png', 'image/octet-stream'), isDownload);\n }\n }\n });\n image_1.src = url;\n }\n };\n /**\n * To trigger the download element\n * @param fileName\n * @param type\n * @param url\n */\n ExportUtils.prototype.triggerDownload = function (fileName, type, url, isDownload) {\n createElement('a', {\n attrs: {\n 'download': fileName + '.' + type.toLocaleLowerCase(),\n 'href': url\n }\n }).dispatchEvent(new MouseEvent(isDownload ? 'click' : 'move', {\n view: window,\n bubbles: false,\n cancelable: true\n }));\n };\n /**\n * To get the maximum size value\n * @param controls\n * @param name\n */\n ExportUtils.prototype.getControlsValue = function (controls) {\n var width = 0;\n var height = 0;\n var content = '';\n var svgObject = new SvgRenderer('').createSvg({\n id: 'Svg_Export_Element',\n width: 200, height: 200\n });\n controls.map(function (control) {\n var svg = control.svgObject.cloneNode(true);\n var groupEle = control.renderer.createGroup({\n style: 'transform: translateY(' + height + 'px)'\n });\n groupEle.appendChild(svg);\n width = Math.max(control.availableSize.width, width);\n height += control.availableSize.height;\n content += control.svgObject.outerHTML;\n svgObject.appendChild(groupEle);\n });\n svgObject.setAttribute('width', width + '');\n svgObject.setAttribute('height', height + '');\n return {\n 'width': width,\n 'height': height,\n 'svg': svgObject\n };\n };\n return ExportUtils;\n}());\nexport { ExportUtils };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, NotifyPropertyChanges, Internationalization } from '@syncfusion/ej2-base';\nimport { L10n } from '@syncfusion/ej2-base';\nimport { ChildProperty } from '@syncfusion/ej2-base';\nimport { remove, extend } from '@syncfusion/ej2-base';\nimport { Browser, Touch } from '@syncfusion/ej2-base';\nimport { Event, EventHandler, Complex, Collection } from '@syncfusion/ej2-base';\nimport { findClipRect, measureText, TextOption, showTooltip, removeElement } from '../common/utils/helper';\nimport { textElement, RectOption, createSvg, firstToLowerCase, titlePositionX } from '../common/utils/helper';\nimport { getSeriesColor, Theme, getThemeColor } from '../common/model/theme';\nimport { Margin, Border, ChartArea, Font, Indexes, TooltipSettings } from '../common/model/base';\nimport { Row, Column, Axis } from './axis/axis';\nimport { CartesianAxisLayoutPanel } from './axis/cartesian-panel';\nimport { Size, Rect } from '../common/utils/helper';\nimport { ChartData } from './utils/get-data';\nimport { Series } from './series/chart-series';\nimport { Data } from '../common/model/data';\nimport { Marker } from './series/marker';\nimport { LegendSettings } from '../common/legend/legend';\nimport { TechnicalIndicator } from './technical-indicators/technical-indicator';\nimport { chartMouseClick, pointClick, pointMove, chartMouseLeave, resized } from '../common/model/constants';\nimport { chartMouseDown, chartMouseMove, chartMouseUp, load } from '../common/model/constants';\nimport { ExportUtils } from '../common/utils/export';\nimport { ChartAnnotationSettings } from './model/chart-base';\nimport { getElement, getTitle } from '../common/utils/helper';\n/**\n * Configures the crosshair in the chart.\n */\nvar CrosshairSettings = /** @class */ (function (_super) {\n __extends(CrosshairSettings, _super);\n function CrosshairSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], CrosshairSettings.prototype, \"enable\", void 0);\n __decorate([\n Complex({ color: null, width: 1 }, Border)\n ], CrosshairSettings.prototype, \"line\", void 0);\n __decorate([\n Property('Both')\n ], CrosshairSettings.prototype, \"lineType\", void 0);\n return CrosshairSettings;\n}(ChildProperty));\nexport { CrosshairSettings };\n/**\n * Configures the zooming behavior for the chart.\n */\nvar ZoomSettings = /** @class */ (function (_super) {\n __extends(ZoomSettings, _super);\n function ZoomSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], ZoomSettings.prototype, \"enableSelectionZooming\", void 0);\n __decorate([\n Property(false)\n ], ZoomSettings.prototype, \"enablePinchZooming\", void 0);\n __decorate([\n Property(false)\n ], ZoomSettings.prototype, \"enableMouseWheelZooming\", void 0);\n __decorate([\n Property(true)\n ], ZoomSettings.prototype, \"enableDeferredZooming\", void 0);\n __decorate([\n Property('XY')\n ], ZoomSettings.prototype, \"mode\", void 0);\n __decorate([\n Property(['Zoom', 'ZoomIn', 'ZoomOut', 'Pan', 'Reset'])\n ], ZoomSettings.prototype, \"toolbarItems\", void 0);\n __decorate([\n Property(false)\n ], ZoomSettings.prototype, \"enablePan\", void 0);\n __decorate([\n Property(false)\n ], ZoomSettings.prototype, \"enableScrollbar\", void 0);\n return ZoomSettings;\n}(ChildProperty));\nexport { ZoomSettings };\n/**\n * Represents the Chart control.\n * ```html\n * \n * \n * ```\n */\nvar Chart = /** @class */ (function (_super) {\n __extends(Chart, _super);\n /**\n * Constructor for creating the widget\n * @hidden\n */\n function Chart(options, element) {\n var _this = _super.call(this, options, element) || this;\n /** @private */\n _this.chartAreaType = 'Cartesian';\n _this.chartid = 57723;\n return _this;\n }\n /**\n * Initialize the event handler.\n */\n Chart.prototype.preRender = function () {\n this.unWireEvents();\n this.initPrivateVariable();\n this.setCulture();\n this.wireEvents();\n };\n Chart.prototype.initPrivateVariable = function () {\n this.animateSeries = true;\n this.delayRedraw = false;\n this.horizontalAxes = [];\n this.verticalAxes = [];\n this.refreshAxis();\n this.refreshDefinition(this.rows);\n this.refreshDefinition(this.columns);\n if (this.tooltipModule) {\n this.tooltipModule.previousPoints = [];\n }\n if (this.element.id === '') {\n var collection = document.getElementsByClassName('e-chart').length;\n this.element.id = 'chart_' + this.chartid + '_' + collection;\n }\n };\n /**\n * To Initialize the control rendering.\n */\n Chart.prototype.render = function () {\n this.trigger(load, { chart: this });\n this.createChartSvg();\n this.setTheme();\n this.markerRender = new Marker(this);\n this.calculateAreaType();\n this.calculateVisibleSeries();\n this.initTechnicalIndicators();\n this.initTrendLines();\n this.calculateVisibleAxis();\n this.processData();\n };\n /**\n * Gets the localized label by locale keyword.\n * @param {string} key\n * @return {string}\n */\n Chart.prototype.getLocalizedLabel = function (key) {\n return this.localeObject.getConstant(key);\n };\n /**\n * Refresh the chart bounds.\n * @private\n */\n Chart.prototype.refreshBound = function () {\n if (this.legendModule && this.legendSettings.visible) {\n this.legendModule.getLegendOptions(this.visibleSeries, this);\n }\n var isCalculateStacking = false;\n var series;\n for (var i = 0, len = this.visibleSeries.length; i < len; i++) {\n series = this.visibleSeries[i];\n series.position = series.rectCount = undefined;\n if (((series.type.indexOf('Stacking') !== -1) || (series.drawType.indexOf('Stacking') !== -1\n && this.chartAreaType === 'PolarRadar')) && !isCalculateStacking) {\n series.calculateStackedValue(series.type.indexOf('100') > -1, this);\n isCalculateStacking = true;\n }\n }\n this.calculateBounds();\n this.renderElements();\n var element = document.getElementById('chartmeasuretext');\n if (element) {\n element.remove();\n }\n };\n Chart.prototype.renderElements = function () {\n this.renderBorder();\n this.renderTitle();\n this.renderAreaBorder();\n var axisElement = this.renderAxes();\n this.renderSeriesElements(axisElement);\n this.renderLegend();\n this.applyZoomkit();\n this.performSelection();\n this.setSecondaryElementPosition();\n this.renderAnnotation();\n };\n /**\n * To render the legend\n */\n Chart.prototype.renderAxes = function () {\n this.yAxisElements = this.renderer.createGroup({ id: this.element.id + 'yAxisCollection' });\n var axisElement;\n if (this.rows.length > 0 && this.columns.length > 0) {\n axisElement = this.chartAxisLayoutPanel.renderAxes();\n }\n if (this.stripLineModule) {\n this.stripLineModule.renderStripLine(this, 'Behind', this.axisCollections);\n }\n return axisElement;\n };\n /**\n * To render the legend\n */\n Chart.prototype.renderLegend = function () {\n if (this.legendModule && this.legendModule.legendCollections.length) {\n this.legendModule.renderLegend(this, this.legendSettings, this.legendModule.legendBounds);\n }\n this.element.appendChild(this.svgObject);\n };\n /**\n * To set the left and top position for data label template for center aligned chart\n */\n Chart.prototype.setSecondaryElementPosition = function () {\n var element = getElement(this.element.id + '_Secondary_Element');\n if (!element) {\n return;\n }\n var rect = this.element.getBoundingClientRect();\n var svgRect = getElement(this.element.id + '_svg').getBoundingClientRect();\n element.style.left = Math.max(svgRect.left - rect.left, 0) + 'px';\n element.style.top = Math.max(svgRect.top - rect.top, 0) + 'px';\n };\n Chart.prototype.initializeModuleElements = function () {\n this.dataLabelCollections = [];\n this.seriesElements = this.renderer.createGroup({ id: this.element.id + 'SeriesCollection' });\n if (this.indicators.length) {\n this.indicatorElements = this.renderer.createGroup({ id: this.element.id + 'IndicatorCollection' });\n }\n if (this.hasTrendlines()) {\n this.trendLineElements = this.renderer.createGroup({ id: this.element.id + 'TrendLineCollection' });\n }\n this.dataLabelElements = this.renderer.createGroup({ id: this.element.id + 'DataLabelCollection' });\n };\n Chart.prototype.hasTrendlines = function () {\n var isTrendline;\n for (var _i = 0, _a = this.series; _i < _a.length; _i++) {\n var series = _a[_i];\n isTrendline = series.trendlines.length ? true : false;\n if (isTrendline) {\n break;\n }\n }\n return isTrendline;\n };\n Chart.prototype.renderSeriesElements = function (axisElement) {\n // Initialize the series elements values\n this.initializeModuleElements();\n var tooltipDiv = this.createElement('div');\n tooltipDiv.id = this.element.id + '_Secondary_Element';\n tooltipDiv.setAttribute('style', 'position: relative');\n this.element.appendChild(tooltipDiv);\n // For userInteraction\n if (this.tooltip.enable) {\n this.svgObject.appendChild(this.renderer.createGroup({ id: this.element.id + '_UserInteraction', style: 'pointer-events:none;' }));\n }\n if (this.rows.length > 0 && this.columns.length > 0) {\n this.initializeIndicator();\n this.initializeTrendLine();\n this.renderSeries();\n this.appendElementsAfterSeries(axisElement);\n }\n };\n Chart.prototype.renderSeries = function () {\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var item = _a[_i];\n if (item.visible) {\n findClipRect(item);\n item.renderSeries(this, item.index);\n }\n }\n var clipRect = this.renderer.drawClipPath({\n 'id': this.element.id + '_ChartAreaClipRect_',\n 'x': this.chartAxisLayoutPanel.seriesClipRect.x,\n 'y': this.chartAxisLayoutPanel.seriesClipRect.y,\n 'width': this.chartAxisLayoutPanel.seriesClipRect.width,\n 'height': this.chartAxisLayoutPanel.seriesClipRect.height,\n 'fill': 'transparent',\n 'stroke-width': 1,\n 'stroke': 'Gray'\n });\n this.seriesElements.appendChild(clipRect);\n this.svgObject.appendChild(this.seriesElements);\n };\n Chart.prototype.initializeIndicator = function () {\n for (var _i = 0, _a = this.indicators; _i < _a.length; _i++) {\n var indicator = _a[_i];\n if (this[firstToLowerCase(indicator.type) + 'IndicatorModule']) {\n this[firstToLowerCase(indicator.type) + 'IndicatorModule'].createIndicatorElements(this, indicator, indicator.index);\n }\n }\n if (this.indicatorElements) {\n this.svgObject.appendChild(this.indicatorElements);\n }\n };\n Chart.prototype.initializeTrendLine = function () {\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n if (series.trendlines.length) {\n this.trendLineModule.getTrendLineElements(series, this);\n }\n }\n if (this.trendLineElements) {\n this.svgObject.appendChild(this.trendLineElements);\n }\n };\n Chart.prototype.appendElementsAfterSeries = function (axisElement) {\n if (this.chartAreaType === 'PolarRadar') {\n this.svgObject.appendChild(this.yAxisElements);\n }\n this.svgObject.appendChild(axisElement);\n if (this.zoomModule && this.zoomSettings.enableScrollbar && this.scrollElement.childElementCount) {\n getElement(this.element.id + '_Secondary_Element').appendChild(this.scrollElement);\n }\n if (this.stripLineModule) {\n this.stripLineModule.renderStripLine(this, 'Over', this.axisCollections);\n }\n if (!this.tooltip.enable) {\n this.svgObject.appendChild(this.renderer.createGroup({ id: this.element.id + '_UserInteraction', style: 'pointer-events:none;' }));\n }\n };\n Chart.prototype.applyZoomkit = function () {\n if (this.zoomModule && this.zoomModule.isZoomed && (!this.zoomSettings.enablePan || this.zoomModule.performedUI)) {\n this.zoomModule.applyZoomToolkit(this, this.axisCollections);\n }\n };\n Chart.prototype.renderAnnotation = function () {\n if (this.annotationModule) {\n this.annotationModule.renderAnnotations(getElement(this.element.id + '_Secondary_Element'));\n }\n };\n Chart.prototype.performSelection = function () {\n var selectedDataIndexes = [];\n if (this.selectionModule) {\n selectedDataIndexes = extend([], this.selectionModule.selectedDataIndexes, null, true);\n this.selectionModule.invokeSelection(this);\n }\n if (selectedDataIndexes.length > 0) {\n this.selectionModule.selectedDataIndexes = selectedDataIndexes;\n this.selectionModule.redrawSelection(this, this.selectionMode);\n }\n };\n Chart.prototype.processData = function (render) {\n if (render === void 0) { render = true; }\n var series;\n this.visibleSeriesCount = 0;\n var check = true;\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var series_1 = _a[_i];\n if (!series_1.visible && !this.legendSettings.visible) {\n this.visibleSeriesCount++;\n continue;\n }\n if (series_1.category !== 'Indicator' && series_1.category !== 'TrendLine') {\n this.initializeDataModule(series_1);\n }\n }\n for (var _b = 0, _c = this.indicators; _b < _c.length; _b++) {\n var indicator = _c[_b];\n if (indicator.dataSource) {\n var techIndicator = indicator;\n this.initializeDataModule(techIndicator);\n check = false;\n }\n }\n if (render && (!this.visibleSeries.length || this.visibleSeriesCount === this.visibleSeries.length && check)) {\n this.refreshBound();\n this.trigger('loaded', { chart: this });\n }\n };\n Chart.prototype.initializeDataModule = function (series) {\n series.xData = [];\n series.yData = [];\n series.dataModule = new Data(series.dataSource || this.dataSource, series.query);\n series.points = [];\n series.refreshDataManager(this);\n };\n Chart.prototype.calculateBounds = function () {\n var margin = this.margin;\n // Title Height;\n var titleHeight = 0;\n var padding = 15;\n var left = margin.left;\n var width = this.availableSize.width - left - margin.right - this.border.width;\n this.titleCollection = [];\n if (this.title) {\n this.titleCollection = getTitle(this.title, this.titleStyle, width);\n titleHeight = (measureText(this.title, this.titleStyle).height * this.titleCollection.length) + padding;\n }\n var top = margin.top + titleHeight + this.chartArea.border.width / 2;\n var height = this.availableSize.height - top - this.border.width - margin.bottom;\n this.initialClipRect = new Rect(left, top, width, height);\n if (this.legendModule) {\n this.legendModule.calculateLegendBounds(this.initialClipRect, this.availableSize);\n }\n this.chartAxisLayoutPanel.measureAxis(this.initialClipRect);\n };\n /**\n * Handles the print method for chart control.\n */\n Chart.prototype.print = function (id) {\n var exportChart = new ExportUtils(this);\n exportChart.print(id);\n };\n /**\n * Handles the export method for chart control.\n * @param type\n * @param fileName\n */\n Chart.prototype.export = function (type, fileName, orientation, controls, width, height) {\n var exportChart = new ExportUtils(this);\n controls = controls ? controls : [this];\n exportChart.export(type, fileName, orientation, controls, width, height);\n };\n /**\n * Defines the trendline initialization\n */\n Chart.prototype.initTrendLines = function () {\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n var trendIndex = 0;\n for (var _b = 0, _c = series.trendlines; _b < _c.length; _b++) {\n var trendline = _c[_b];\n var trendLine = trendline;\n var type = firstToLowerCase(trendLine.type);\n if (this.trendLineModule) {\n trendLine.index = trendIndex;\n trendLine.sourceIndex = series.index;\n this.trendLineModule.initSeriesCollection(trendLine, this);\n if (trendLine.targetSeries) {\n trendLine.targetSeries.xAxisName = series.xAxisName;\n trendLine.targetSeries.yAxisName = series.yAxisName;\n this.visibleSeries.push(trendLine.targetSeries);\n }\n }\n trendIndex++;\n }\n }\n };\n Chart.prototype.calculateAreaType = function () {\n var series = this.series[0];\n if (series) {\n this.requireInvertedAxis = ((series.type.indexOf('Bar') !== -1) && !this.isTransposed) ||\n ((series.type.indexOf('Bar') === -1) && this.isTransposed && this.chartAreaType !== 'PolarRadar');\n }\n this.chartAxisLayoutPanel = this.chartAreaType === 'PolarRadar' ? (this.polarSeriesModule || this.radarSeriesModule)\n : new CartesianAxisLayoutPanel(this);\n };\n Chart.prototype.calculateVisibleAxis = function () {\n var axis;\n var series;\n var axes = [this.primaryXAxis, this.primaryYAxis];\n axes = this.chartAreaType === 'Cartesian' ? axes.concat(this.axes) : axes;\n this.axisCollections = [];\n if (this.zoomModule) {\n this.zoomModule.isPanning = this.zoomModule.isAxisZoomed(axes) && this.zoomSettings.enablePan;\n this.svgObject.setAttribute('cursor', this.zoomModule.isPanning ? 'pointer' : 'auto');\n if (this.scrollBarModule) {\n this.scrollBarModule.axes = axes;\n }\n }\n for (var i = 0, len = axes.length; i < len; i++) {\n axis = axes[i];\n axis.series = [];\n axis.labels = [];\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var series_2 = _a[_i];\n this.initAxis(series_2, axis, true);\n }\n for (var _b = 0, _c = this.indicators; _b < _c.length; _b++) {\n var indicator = _c[_b];\n this.initAxis(indicator, axis, false);\n }\n if (this.scrollBarModule) {\n this.scrollBarModule.injectTo(axis, this);\n }\n if (axis.orientation != null) {\n this.axisCollections.push(axis);\n }\n }\n if (this.rows.length > 0 && this.columns.length > 0) {\n this.chartAxisLayoutPanel.measure();\n }\n };\n Chart.prototype.initAxis = function (series, axis, isSeries) {\n if (series.xAxisName === axis.name || (series.xAxisName == null && axis.name === 'primaryXAxis')) {\n axis.orientation = this.requireInvertedAxis ? 'Vertical' : 'Horizontal';\n series.xAxis = axis;\n if (isSeries) {\n axis.series.push(series);\n }\n }\n else if (series.yAxisName === axis.name || (series.yAxisName == null && axis.name === 'primaryYAxis')) {\n axis.orientation = this.requireInvertedAxis ? 'Horizontal' : 'Vertical';\n series.yAxis = axis;\n if (isSeries) {\n axis.series.push(series);\n }\n }\n };\n Chart.prototype.initTechnicalIndicators = function () {\n var i = 0;\n for (var _i = 0, _a = this.indicators; _i < _a.length; _i++) {\n var indicator = _a[_i];\n var techIndicator = indicator;\n var type = firstToLowerCase(techIndicator.type);\n if (this[type + 'IndicatorModule']) {\n techIndicator.index = i;\n this[type + 'IndicatorModule'].initSeriesCollection(techIndicator, this);\n for (var _b = 0, _c = techIndicator.targetSeries; _b < _c.length; _b++) {\n var targetSeries = _c[_b];\n if (indicator.seriesName || indicator.dataSource) {\n this.visibleSeries.push(targetSeries);\n }\n }\n }\n i++;\n }\n };\n /** @private */\n Chart.prototype.refreshTechnicalIndicator = function (series) {\n if (this.indicators.length) {\n var targetIndicator = null;\n if (series instanceof Series && series.category !== 'Indicator') {\n for (var _i = 0, _a = this.indicators; _i < _a.length; _i++) {\n var indicator = _a[_i];\n if (indicator.seriesName === series.name && !indicator.dataSource) {\n targetIndicator = indicator;\n targetIndicator.setDataSource(series, this);\n }\n }\n }\n else if (series instanceof TechnicalIndicator) {\n targetIndicator = series;\n targetIndicator.setDataSource(series instanceof Series ? series : null, this);\n }\n }\n };\n Chart.prototype.calculateVisibleSeries = function () {\n var series;\n this.visibleSeries = [];\n var colors = this.palettes.length ? this.palettes : getSeriesColor(this.theme);\n var count = colors.length;\n for (var i = 0, len = this.series.length; i < len; i++) {\n series = this.series[i];\n series.index = i;\n series.interior = series.fill || colors[i % count];\n switch (series.type) {\n case 'Bar':\n case 'StackingBar':\n case 'StackingBar100':\n if (this.series[0].type.indexOf('Bar') === -1) {\n continue;\n }\n break;\n case 'Polar':\n case 'Radar':\n if (this.chartAreaType !== 'PolarRadar') {\n continue;\n }\n if (this.chartAreaType === 'PolarRadar' && ((series.xAxisName === null && series.yAxisName !== null) ||\n (series.xAxisName !== null && series.yAxisName === null) ||\n (series.xAxisName !== null && series.yAxisName !== null))) {\n continue;\n }\n break;\n default:\n if (this.chartAreaType === 'PolarRadar' || this.series[0].type.indexOf('Bar') > -1) {\n continue;\n }\n break;\n }\n this.visibleSeries.push(series);\n this.series[i] = series;\n }\n };\n Chart.prototype.renderTitle = function () {\n if (this.title) {\n var anchor = this.titleStyle.textAlignment === 'Near' ? 'start' :\n this.titleStyle.textAlignment === 'Far' ? 'end' : 'middle';\n this.elementSize = measureText(this.title, this.titleStyle);\n var options = new TextOption(this.element.id + '_ChartTitle', titlePositionX(this.availableSize, this.margin.left, this.margin.right, this.titleStyle), this.margin.top + ((this.elementSize.height) * 3 / 4), anchor, this.titleCollection, '', 'auto');\n var element = textElement(options, this.titleStyle, this.titleStyle.color || this.themeStyle.chartTitle, this.svgObject);\n element.setAttribute('aria-label', this.description || this.title);\n element.setAttribute('tabindex', this.tabIndex.toString());\n }\n };\n Chart.prototype.renderBorder = function () {\n var width = this.border.width;\n var rect = new RectOption(this.element.id + '_ChartBorder', this.background || this.themeStyle.background, this.border, 1, new Rect(width / 2, width / 2, this.availableSize.width - width, this.availableSize.height - width));\n this.htmlObject = this.renderer.drawRectangle(rect);\n this.svgObject.appendChild(this.htmlObject);\n };\n Chart.prototype.renderAreaBorder = function () {\n if (this.chartAreaType === 'PolarRadar') {\n return null;\n }\n else {\n var rect = new RectOption(this.element.id + '_ChartAreaBorder', this.chartArea.background, { width: this.chartArea.border.width, color: this.chartArea.border.color || this.themeStyle.areaBorder }, this.chartArea.opacity, this.chartAxisLayoutPanel.seriesClipRect);\n this.htmlObject = this.renderer.drawRectangle(rect);\n this.svgObject.appendChild(this.htmlObject);\n }\n };\n /**\n * To add series for the chart\n * @param {SeriesModel[]} seriesCollection - Defines the series collection to be added in chart.\n * @return {void}.\n */\n Chart.prototype.addSeries = function (seriesCollection) {\n for (var _i = 0, seriesCollection_1 = seriesCollection; _i < seriesCollection_1.length; _i++) {\n var series = seriesCollection_1[_i];\n series = new Series(this, 'series', series);\n this.series.push(series);\n }\n this.refresh();\n };\n /**\n * To Remove series for the chart\n * @param index - Defines the series index to be remove in chart series\n * @return {void}\n */\n Chart.prototype.removeSeries = function (index) {\n this.series.splice(index, 1);\n this.refresh();\n };\n /**\n * To destroy the widget\n * @method destroy\n * @return {void}.\n * @member of Chart\n */\n Chart.prototype.destroy = function () {\n if (this.scrollBarModule) {\n this.scrollBarModule.destroy();\n }\n this.unWireEvents();\n _super.prototype.destroy.call(this);\n this.element.classList.remove('e-chart');\n };\n /**\n * Get component name\n */\n Chart.prototype.getModuleName = function () {\n return 'chart';\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n Chart.prototype.getPersistData = function () {\n var keyEntity = ['loaded', 'animationComplete'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Method to create SVG element.\n */\n Chart.prototype.createChartSvg = function () {\n this.removeSvg();\n createSvg(this);\n };\n /**\n * Method to bind events for chart\n */\n Chart.prototype.unWireEvents = function () {\n /*! Find the Events type */\n var startEvent = Browser.touchStartEvent;\n var moveEvent = Browser.touchMoveEvent;\n var stopEvent = Browser.touchEndEvent;\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n /*! UnBind the Event handler */\n EventHandler.remove(this.element, startEvent, this.chartOnMouseDown);\n EventHandler.remove(this.element, moveEvent, this.mouseMove);\n EventHandler.remove(this.element, stopEvent, this.mouseEnd);\n EventHandler.remove(this.element, 'click', this.chartOnMouseClick);\n EventHandler.remove(this.element, 'contextmenu', this.chartRightClick);\n EventHandler.remove(this.element, cancelEvent, this.mouseLeave);\n window.removeEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.chartResize);\n };\n Chart.prototype.wireEvents = function () {\n /*! Find the Events type */\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n /*! Bind the Event handler */\n EventHandler.add(this.element, Browser.touchStartEvent, this.chartOnMouseDown, this);\n EventHandler.add(this.element, Browser.touchMoveEvent, this.mouseMove, this);\n EventHandler.add(this.element, Browser.touchEndEvent, this.mouseEnd, this);\n EventHandler.add(this.element, 'click', this.chartOnMouseClick, this);\n EventHandler.add(this.element, 'contextmenu', this.chartRightClick, this);\n EventHandler.add(this.element, cancelEvent, this.mouseLeave, this);\n window.addEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.chartResize.bind(this));\n this.longPress = this.longPress.bind(this);\n new Touch(this.element, { tapHold: this.longPress, tapHoldThreshold: 500 });\n /*! Apply the style for chart */\n this.setStyle(this.element);\n };\n Chart.prototype.chartRightClick = function (event) {\n if (this.crosshair.enable && this.crosshairModule &&\n (event.buttons === 2 || event.which === 0 || event.pointerType === 'touch')) {\n event.preventDefault();\n event.stopPropagation();\n return false;\n }\n return true;\n };\n Chart.prototype.setStyle = function (element) {\n var zooming = this.zoomSettings;\n var disableScroll = zooming.enableSelectionZooming || zooming.enablePinchZooming ||\n this.selectionMode !== 'None' || this.crosshair.enable;\n element.style.touchAction = disableScroll ? 'none' : 'element';\n element.style.msTouchAction = disableScroll ? 'none' : 'element';\n element.style.msContentZooming = 'none';\n element.style.msUserSelect = 'none';\n element.style.webkitUserSelect = 'none';\n element.style.position = 'relative';\n element.style.display = 'block';\n };\n /**\n * Finds the orientation.\n * @return {boolean}\n * @private\n */\n Chart.prototype.isOrientation = function () {\n return ('orientation' in window && 'onorientationchange' in window);\n };\n /**\n * Handles the long press on chart.\n * @return {boolean}\n * @private\n */\n Chart.prototype.longPress = function (e) {\n this.mouseX = (e && e.originalEvent.changedTouches) ? (e.originalEvent.changedTouches[0].clientX) : 0;\n this.mouseY = (e && e.originalEvent.changedTouches) ? (e.originalEvent.changedTouches[0].clientY) : 0;\n this.startMove = true;\n this.setMouseXY(this.mouseX, this.mouseY);\n this.notify('tapHold', e);\n return false;\n };\n /**\n * To find mouse x, y for aligned chart element svg position\n */\n Chart.prototype.setMouseXY = function (pageX, pageY) {\n var svgRect = getElement(this.element.id + '_svg').getBoundingClientRect();\n var rect = this.element.getBoundingClientRect();\n this.mouseY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0);\n this.mouseX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0);\n };\n /**\n * Handles the chart resize.\n * @return {boolean}\n * @private\n */\n Chart.prototype.chartResize = function (e) {\n var _this = this;\n this.animateSeries = false;\n var arg = {\n chart: this,\n name: resized,\n currentSize: new Size(0, 0),\n previousSize: new Size(this.availableSize.width, this.availableSize.height),\n };\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n this.resizeTo = setTimeout(function () {\n if (_this.isDestroyed) {\n clearTimeout(_this.resizeTo);\n return;\n }\n _this.createChartSvg();\n arg.currentSize = _this.availableSize;\n _this.trigger(resized, arg);\n _this.refreshAxis();\n _this.refreshBound();\n _this.trigger('loaded', { chart: _this });\n }, 500);\n return false;\n };\n /**\n * Handles the mouse move.\n * @return {boolean}\n * @private\n */\n Chart.prototype.mouseMove = function (e) {\n var pageX;\n var pageY;\n var touchArg;\n if (e.type === 'touchmove') {\n this.isTouch = true;\n touchArg = e;\n pageX = touchArg.changedTouches[0].clientX;\n pageY = touchArg.changedTouches[0].clientY;\n }\n else {\n this.isTouch = e.pointerType === 'touch' || e.pointerType === '2' || this.isTouch;\n pageX = e.clientX;\n pageY = e.clientY;\n }\n this.setMouseXY(pageX, pageY);\n this.chartOnMouseMove(e);\n return false;\n };\n /**\n * Handles the mouse leave.\n * @return {boolean}\n * @private\n */\n Chart.prototype.mouseLeave = function (e) {\n var pageX;\n var pageY;\n var touchArg;\n if (e.type === 'touchleave') {\n this.isTouch = true;\n touchArg = e;\n pageX = touchArg.changedTouches[0].clientX;\n pageY = touchArg.changedTouches[0].clientY;\n }\n else {\n this.isTouch = e.pointerType === 'touch' || e.pointerType === '2';\n pageX = e.clientX;\n pageY = e.clientY;\n }\n this.setMouseXY(pageX, pageY);\n this.chartOnMouseLeave(e);\n return false;\n };\n /**\n * Handles the mouse leave on chart.\n * @return {boolean}\n * @private\n */\n Chart.prototype.chartOnMouseLeave = function (e) {\n var element = e.target;\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n this.trigger(chartMouseLeave, { target: element.id, x: this.mouseX, y: this.mouseY });\n this.isChartDrag = false;\n this.notify(cancelEvent, e);\n return false;\n };\n /**\n * Handles the mouse click on chart.\n * @return {boolean}\n * @private\n */\n Chart.prototype.chartOnMouseClick = function (e) {\n var element = e.target;\n this.trigger(chartMouseClick, { target: element.id, x: this.mouseX, y: this.mouseY });\n if (this.pointClick) {\n this.triggerPointEvent(pointClick);\n }\n this.notify('click', e);\n return false;\n };\n Chart.prototype.triggerPointEvent = function (event) {\n var data = new ChartData(this);\n var pointData = data.getData();\n if (pointData.series && pointData.point) {\n this.trigger(event, {\n series: pointData.series,\n point: pointData.point,\n seriesIndex: pointData.series.index, pointIndex: pointData.point.index,\n x: this.mouseX, y: this.mouseY\n });\n }\n };\n /**\n * Handles the mouse move on chart.\n * @return {boolean}\n * @private\n */\n Chart.prototype.chartOnMouseMove = function (e) {\n var element = e.target;\n this.trigger(chartMouseMove, { target: element.id, x: this.mouseX, y: this.mouseY });\n if (this.pointMove) {\n this.triggerPointEvent(pointMove);\n }\n // Tooltip for chart series.\n if (!this.isTouch) {\n this.titleTooltip(e, this.mouseX, this.mouseY);\n this.axisTooltip(e, this.mouseX, this.mouseY);\n }\n this.notify(Browser.touchMoveEvent, e);\n this.isTouch = false;\n return false;\n };\n Chart.prototype.titleTooltip = function (event, x, y, isTouch) {\n var targetId = event.target.id;\n if ((targetId === (this.element.id + '_ChartTitle')) && (event.target.textContent.indexOf('...') > -1)) {\n showTooltip(this.title, x, y, this.element.offsetWidth, this.element.id + '_EJ2_Title_Tooltip', getElement(this.element.id + '_Secondary_Element'), isTouch);\n }\n else {\n removeElement(this.element.id + '_EJ2_Title_Tooltip');\n }\n };\n Chart.prototype.axisTooltip = function (event, x, y, isTouch) {\n var targetId = event.target.id;\n if (((targetId.indexOf('AxisLabel') > -1) || targetId.indexOf('Axis_MultiLevelLabel') > -1) &&\n (event.target.textContent.indexOf('...') > -1)) {\n showTooltip(this.findAxisLabel(targetId), x, y, this.element.offsetWidth, this.element.id + '_EJ2_AxisLabel_Tooltip', getElement(this.element.id + '_Secondary_Element'), isTouch);\n }\n else {\n removeElement(this.element.id + '_EJ2_AxisLabel_Tooltip');\n }\n };\n Chart.prototype.findAxisLabel = function (text) {\n var texts;\n if (text.indexOf('AxisLabel') > -1) {\n texts = ((text.replace(this.element.id, '')).replace('AxisLabel_', '')).split('_');\n return this.axisCollections[parseInt(texts[0], 10)].visibleLabels[parseInt(texts[1], 10)].originalText;\n }\n else {\n texts = ((text.replace(this.element.id, '')).replace('Axis_MultiLevelLabel_Level_', '').replace('Text_', '')).split('_');\n return (this.axisCollections[parseInt(texts[0], 10)].multiLevelLabels[parseInt(texts[1], 10)]\n .categories[parseInt(texts[2], 10)].text);\n }\n };\n /**\n * Handles the mouse down on chart.\n * @return {boolean}\n * @private\n */\n Chart.prototype.chartOnMouseDown = function (e) {\n var pageX;\n var pageY;\n var target;\n var touchArg;\n var offset = Browser.isDevice ? 20 : 30;\n var rect = this.element.getBoundingClientRect();\n var element = e.target;\n this.trigger(chartMouseDown, { target: element.id, x: this.mouseX, y: this.mouseY });\n if (e.type === 'touchstart') {\n this.isTouch = true;\n touchArg = e;\n pageX = touchArg.changedTouches[0].clientX;\n pageY = touchArg.changedTouches[0].clientY;\n target = touchArg.target;\n }\n else {\n this.isTouch = e.pointerType === 'touch';\n pageX = e.clientX;\n pageY = e.clientY;\n target = e.target;\n }\n var svgRect = getElement(this.element.id + '_svg').getBoundingClientRect();\n this.mouseDownX = this.previousMouseMoveX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0);\n this.mouseDownY = this.previousMouseMoveY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0);\n if (this.isTouch) {\n this.isDoubleTap = (new Date().getTime() < this.threshold && target.id.indexOf(this.element.id + '_Zooming_') === -1 &&\n (this.mouseDownX - offset >= this.mouseX || this.mouseDownX + offset >= this.mouseX) &&\n (this.mouseDownY - offset >= this.mouseY || this.mouseDownY + offset >= this.mouseY) &&\n (this.mouseX - offset >= this.mouseDownX || this.mouseX + offset >= this.mouseDownX) &&\n (this.mouseY - offset >= this.mouseDownY || this.mouseY + offset >= this.mouseDownY));\n }\n this.notify(Browser.touchStartEvent, e);\n return false;\n };\n /**\n * Handles the mouse up.\n * @return {boolean}\n * @private\n */\n Chart.prototype.mouseEnd = function (e) {\n var pageY;\n var pageX;\n var touchArg;\n if (e.type === 'touchend') {\n touchArg = e;\n pageX = touchArg.changedTouches[0].clientX;\n this.isTouch = true;\n pageY = touchArg.changedTouches[0].clientY;\n }\n else {\n pageY = e.clientY;\n pageX = e.clientX;\n this.isTouch = e.pointerType === 'touch' || e.pointerType === '2';\n }\n this.setMouseXY(pageX, pageY);\n this.chartOnMouseUp(e);\n return false;\n };\n /**\n * Handles the mouse up.\n * @return {boolean}\n * @private\n */\n Chart.prototype.chartOnMouseUp = function (e) {\n var element = e.target;\n this.trigger(chartMouseUp, { target: element.id, x: this.mouseX, y: this.mouseY });\n this.isChartDrag = false;\n if (this.isTouch) {\n this.titleTooltip(e, this.mouseX, this.mouseY, this.isTouch);\n this.axisTooltip(e, this.mouseX, this.mouseY, this.isTouch);\n this.threshold = new Date().getTime() + 300;\n }\n this.seriesElements.removeAttribute('clip-path');\n this.notify(Browser.touchEndEvent, e);\n return false;\n };\n /**\n * Method to set culture for chart\n */\n Chart.prototype.setCulture = function () {\n this.intl = new Internationalization();\n this.setLocaleConstants();\n this.localeObject = new L10n(this.getModuleName(), this.defaultLocalConstants, this.locale);\n };\n /**\n * Method to set the annotation content dynamically for chart.\n */\n Chart.prototype.setAnnotationValue = function (annotationIndex, content) {\n var parentNode = getElement(this.element.id + '_Annotation_Collections');\n var annotation = this.annotations[annotationIndex];\n var element;\n if (content !== null) {\n annotation.content = content;\n if (parentNode) {\n removeElement(this.element.id + '_Annotation_' + annotationIndex);\n element = this.createElement('div');\n this.annotationModule.processAnnotation(annotation, annotationIndex, element);\n parentNode.appendChild(element.children[0]);\n }\n else {\n this.annotationModule.renderAnnotations(getElement(this.element.id + '_Secondary_Element'));\n }\n }\n };\n /**\n * Method to set locale constants\n */\n Chart.prototype.setLocaleConstants = function () {\n this.defaultLocalConstants = {\n ZoomIn: 'ZoomIn',\n Zoom: 'Zoom',\n ZoomOut: 'ZoomOut',\n Pan: 'Pan',\n Reset: 'Reset',\n ResetZoom: 'Reset Zoom'\n };\n };\n /**\n * Theming for chart\n */\n Chart.prototype.setTheme = function () {\n /*! Set theme */\n this.themeStyle = getThemeColor(this.theme);\n };\n /**\n * To provide the array of modules needed for control rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n Chart.prototype.requiredModules = function () {\n var _this = this;\n var modules = [];\n var series = this.series;\n var enableAnnotation = false;\n var moduleName;\n var errorBarVisible = false;\n var dataLabelEnable = false;\n var zooming = this.zoomSettings;\n this.chartAreaType = (series.length > 0 && (series[0].type === 'Polar' || series[0].type === 'Radar')) ? 'PolarRadar' : 'Cartesian';\n if (this.tooltip.enable) {\n modules.push({\n member: 'Tooltip',\n args: [this]\n });\n }\n series.map(function (value) {\n _this.isLegend = (_this.legendSettings.visible && ((value.name !== '') || !!_this.isLegend));\n moduleName = value.type.indexOf('100') !== -1 ? value.type.replace('100', '') + 'Series' : value.type + 'Series';\n errorBarVisible = value.errorBar.visible || errorBarVisible;\n dataLabelEnable = value.marker.dataLabel.visible || dataLabelEnable;\n if (!modules.some(function (currentModule) {\n return currentModule.member === moduleName;\n })) {\n modules.push({\n member: moduleName,\n args: [_this, series]\n });\n }\n if (_this.chartAreaType === 'PolarRadar') {\n modules.push({\n member: value.drawType + 'Series',\n args: [_this, series]\n });\n }\n });\n this.findIndicatorModules(modules);\n this.findTrendLineModules(modules);\n modules = this.findAxisModule(modules);\n enableAnnotation = this.annotations.some(function (value) {\n return (value.content !== null);\n });\n if (errorBarVisible) {\n modules.push({\n member: 'ErrorBar',\n args: [this, series]\n });\n }\n if (this.isLegend) {\n modules.push({\n member: 'Legend',\n args: [this]\n });\n }\n if (this.chartAreaType !== 'PolarRadar' && (zooming.enableSelectionZooming\n || zooming.enableMouseWheelZooming || zooming.enablePinchZooming || zooming.enablePan)) {\n modules.push({\n member: 'Zoom',\n args: [this, this.zoomSettings]\n });\n if (zooming.enableScrollbar) {\n modules.push({\n member: 'ScrollBar',\n args: [this]\n });\n }\n }\n if (this.selectionMode !== 'None' && !(this.chartAreaType === 'PolarRadar' &&\n this.selectionMode.indexOf('Drag') > -1)) {\n modules.push({\n member: 'Selection',\n args: [this]\n });\n }\n if (dataLabelEnable) {\n modules.push({\n member: 'DataLabel',\n args: [this, series]\n });\n }\n if (enableAnnotation) {\n modules.push({\n member: 'Annotation',\n args: [this]\n });\n }\n if (this.chartAreaType !== 'PolarRadar' && this.crosshair.enable) {\n modules.push({\n member: 'Crosshair',\n args: [this]\n });\n }\n return modules;\n };\n Chart.prototype.findAxisModule = function (modules) {\n var axisCollections = [];\n axisCollections.push(this.primaryXAxis);\n axisCollections.push(this.primaryYAxis);\n axisCollections = axisCollections.concat(this.axes);\n var datetimeEnabled = false;\n var categoryEnabled = false;\n var logarithmicEnabled = false;\n var striplineEnabled = false;\n var dateTimeCategoryEnabled = false;\n var multiLevelEnabled = false;\n for (var _i = 0, axisCollections_1 = axisCollections; _i < axisCollections_1.length; _i++) {\n var axis = axisCollections_1[_i];\n datetimeEnabled = axis.valueType === 'DateTime' || datetimeEnabled;\n categoryEnabled = axis.valueType === 'Category' || categoryEnabled;\n logarithmicEnabled = axis.valueType === 'Logarithmic' || logarithmicEnabled;\n dateTimeCategoryEnabled = axis.valueType === 'DateTimeCategory' || dateTimeCategoryEnabled;\n striplineEnabled = this.findStriplineVisibility(axis.stripLines) || striplineEnabled;\n multiLevelEnabled = axis.multiLevelLabels.length > 0 || multiLevelEnabled;\n }\n if (datetimeEnabled) {\n modules.push({\n member: 'DateTime',\n args: [this]\n });\n }\n if (categoryEnabled) {\n modules.push({\n member: 'Category',\n args: [this]\n });\n }\n if (logarithmicEnabled) {\n modules.push({\n member: 'Logarithmic',\n args: [this]\n });\n }\n if (striplineEnabled) {\n modules.push({\n member: 'StripLine',\n args: [this]\n });\n }\n if (multiLevelEnabled) {\n modules.push({\n member: 'MultiLevelLabel',\n args: [this]\n });\n }\n if (dateTimeCategoryEnabled) {\n modules.push({\n member: 'DateTimeCategory',\n args: [this]\n });\n }\n return modules;\n };\n Chart.prototype.findIndicatorModules = function (modules) {\n var macdEnable;\n var bandEnable;\n var indicators = this.indicators;\n if (this.indicators.length) {\n modules.push({\n member: 'LineSeries',\n args: [this]\n });\n indicators.map(function (indicator) {\n macdEnable = macdEnable || indicator.type === 'Macd';\n bandEnable = bandEnable || indicator.type === 'BollingerBands';\n });\n if (macdEnable) {\n modules.push({\n member: 'ColumnSeries',\n args: [this]\n });\n }\n if (bandEnable) {\n modules.push({\n member: 'RangeAreaSeries',\n args: [this]\n });\n }\n for (var _i = 0, _a = this.indicators; _i < _a.length; _i++) {\n var indicator = _a[_i];\n modules.push({\n member: indicator.type + 'Indicator',\n args: [this]\n });\n }\n }\n };\n Chart.prototype.findTrendLineModules = function (modules) {\n var isLine;\n var isSpline;\n var _loop_1 = function (series) {\n var markerEnable;\n series.trendlines.map(function (trendline) {\n markerEnable = markerEnable || trendline.marker.visible;\n isLine = isLine || (trendline.type === 'Linear' || trendline.type === 'MovingAverage') ? true : false;\n isSpline = isSpline || !isLine ? true : false;\n });\n if (markerEnable) {\n modules.push({\n member: 'Marker',\n args: [this_1, series]\n });\n }\n };\n var this_1 = this;\n for (var _i = 0, _a = this.series; _i < _a.length; _i++) {\n var series = _a[_i];\n _loop_1(series);\n }\n if (isLine || isSpline) {\n modules.push({\n member: 'TrendLine',\n args: [this]\n });\n }\n if (isLine) {\n modules.push({\n member: 'LineSeries',\n args: [this]\n });\n }\n if (isSpline) {\n modules.push({\n member: 'SplineSeries',\n args: [this]\n });\n }\n };\n Chart.prototype.findStriplineVisibility = function (striplines) {\n var visible = false;\n for (var _i = 0, striplines_1 = striplines; _i < striplines_1.length; _i++) {\n var stripline = striplines_1[_i];\n if (stripline.visible) {\n visible = true;\n break;\n }\n }\n return visible;\n };\n /**\n * To Remove the SVG.\n * @return {boolean}\n * @private\n */\n Chart.prototype.removeSvg = function () {\n if (document.getElementById(this.element.id + '_Secondary_Element')) {\n remove(document.getElementById(this.element.id + '_Secondary_Element'));\n }\n var removeLength = 0;\n if (this.zoomModule && this.zoomModule.pinchTarget) {\n this.zoomModule.pinchTarget.id = '';\n this.zoomModule.pinchTarget.setAttribute('opacity', '0');\n this.svgObject.appendChild(this.zoomModule.pinchTarget);\n removeLength = 1;\n }\n if (this.svgObject) {\n while (this.svgObject.childNodes.length > removeLength) {\n this.svgObject.removeChild(this.svgObject.firstChild);\n }\n if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) {\n remove(this.svgObject);\n }\n }\n };\n Chart.prototype.refreshDefinition = function (definitions) {\n for (var _i = 0, definitions_1 = definitions; _i < definitions_1.length; _i++) {\n var item = definitions_1[_i];\n item.axes = [];\n }\n };\n /**\n * Refresh the axis default value.\n * @return {boolean}\n * @private\n */\n Chart.prototype.refreshAxis = function () {\n var axis = this.primaryXAxis;\n axis.rect = new Rect(undefined, undefined, 0, 0);\n axis = this.primaryYAxis;\n axis.isStack100 = false;\n axis.rect = new Rect(undefined, undefined, 0, 0);\n for (var _i = 0, _a = this.axes; _i < _a.length; _i++) {\n var item = _a[_i];\n axis = item;\n axis.rect = new Rect(undefined, undefined, 0, 0);\n axis.isStack100 = false;\n }\n };\n Chart.prototype.axisChange = function (axis) {\n if (!axis.name && !axis.valueType) {\n return false;\n }\n this.refreshDefinition(this.columns);\n this.refreshDefinition(this.rows);\n this.calculateVisibleAxis();\n this.processData();\n return true;\n };\n /**\n * Called internally if any of the property value changed.\n * @private\n */\n // tslint:disable-next-line:max-func-body-length\n Chart.prototype.onPropertyChanged = function (newProp, oldProp) {\n var renderer = false;\n var refreshBounds = false;\n if (Object.keys(newProp).length === 1 && Object.keys(newProp)[0] === 'indicators') {\n //add valid check,it should happen only when property change is triggered for target series\n return;\n }\n this.animateSeries = false;\n if (!this.delayRedraw) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'primaryXAxis':\n refreshBounds = this.axisChange(newProp.primaryXAxis);\n if (newProp.primaryXAxis.edgeLabelPlacement) {\n renderer = true;\n }\n if (!newProp.primaryXAxis.crosshairTooltip) {\n refreshBounds = true;\n }\n break;\n case 'primaryYAxis':\n refreshBounds = this.axisChange(newProp.primaryYAxis);\n if (newProp.primaryYAxis.edgeLabelPlacement) {\n renderer = true;\n }\n if (!newProp.primaryYAxis.crosshairTooltip) {\n refreshBounds = true;\n }\n break;\n case 'axes':\n for (var _b = 0, _c = Object.keys(newProp.axes); _b < _c.length; _b++) {\n var index = _c[_b];\n refreshBounds = refreshBounds || this.axisChange(newProp.axes[index]);\n if (!newProp.axes[index].crosshairTooltip) {\n refreshBounds = true;\n }\n }\n break;\n case 'height':\n case 'width':\n this.createChartSvg();\n refreshBounds = true;\n break;\n case 'title':\n refreshBounds = true;\n break;\n case 'titleStyle':\n if (newProp.titleStyle && (newProp.titleStyle.size || newProp.titleStyle.textOverflow)) {\n refreshBounds = true;\n }\n else {\n renderer = true;\n }\n break;\n case 'border':\n renderer = true;\n break;\n case 'dataSource':\n this.processData(false);\n refreshBounds = true;\n break;\n case 'series':\n var len = this.series.length;\n var seriesRefresh = false;\n var series = void 0;\n for (var i = 0; i < len; i++) {\n series = newProp.series[i];\n if (series && (series.dataSource || series.xName || series.yName || series.size ||\n series.high || series.low || series.open || series.close)) {\n seriesRefresh = true;\n }\n }\n if (seriesRefresh) {\n this.processData(false);\n refreshBounds = true;\n }\n break;\n case 'zoomSettings':\n if (newProp.zoomSettings.enableScrollbar || oldProp.zoomSettings.enableScrollbar) {\n refreshBounds = true;\n }\n renderer = true;\n break;\n case 'background':\n renderer = true;\n break;\n case 'chartArea':\n if (newProp.chartArea.border && newProp.chartArea.border.width) {\n refreshBounds = true;\n }\n renderer = true;\n break;\n case 'legendSettings':\n if (!newProp.legendSettings.background || !newProp.legendSettings.opacity) {\n refreshBounds = true;\n }\n renderer = true;\n break;\n case 'palettes':\n this.calculateVisibleSeries();\n renderer = true;\n break;\n case 'selectedDataIndexes':\n case 'selectionMode':\n if (this.selectionModule && newProp.selectionMode && newProp.selectionMode.indexOf('Drag') === -1) {\n this.selectionModule.redrawSelection(this, oldProp.selectionMode);\n }\n break;\n case 'isMultiSelect':\n if (this.selectionModule && !newProp.isMultiSelect && this.selectionModule.selectedDataIndexes.length > 1) {\n this.selectionModule.redrawSelection(this, oldProp.selectionMode);\n }\n break;\n case 'theme':\n this.animateSeries = true;\n break;\n case 'locale':\n case 'currencyCode':\n _super.prototype.refresh.call(this);\n break;\n case 'tooltip':\n this.tooltipModule.previousPoints = [];\n break;\n }\n }\n if (!refreshBounds && renderer) {\n this.removeSvg();\n this.renderElements();\n this.trigger('loaded', { chart: this });\n }\n if (refreshBounds) {\n this.removeSvg();\n this.refreshAxis();\n this.refreshBound();\n this.trigger('loaded', { chart: this });\n }\n }\n };\n __decorate([\n Property(null)\n ], Chart.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], Chart.prototype, \"height\", void 0);\n __decorate([\n Property('')\n ], Chart.prototype, \"title\", void 0);\n __decorate([\n Property('')\n ], Chart.prototype, \"dataSource\", void 0);\n __decorate([\n Complex(Theme.chartTitleFont, Font)\n ], Chart.prototype, \"titleStyle\", void 0);\n __decorate([\n Complex({}, Margin)\n ], Chart.prototype, \"margin\", void 0);\n __decorate([\n Complex({ color: '#DDDDDD', width: 0 }, Border)\n ], Chart.prototype, \"border\", void 0);\n __decorate([\n Property(null)\n ], Chart.prototype, \"background\", void 0);\n __decorate([\n Complex({ border: { color: null, width: 0.5 }, background: 'transparent' }, ChartArea)\n ], Chart.prototype, \"chartArea\", void 0);\n __decorate([\n Complex({ name: 'primaryXAxis' }, Axis)\n ], Chart.prototype, \"primaryXAxis\", void 0);\n __decorate([\n Complex({ name: 'primaryYAxis' }, Axis)\n ], Chart.prototype, \"primaryYAxis\", void 0);\n __decorate([\n Collection([{}], Row)\n ], Chart.prototype, \"rows\", void 0);\n __decorate([\n Collection([{}], Column)\n ], Chart.prototype, \"columns\", void 0);\n __decorate([\n Collection([{}], Axis)\n ], Chart.prototype, \"axes\", void 0);\n __decorate([\n Collection([{}], Series)\n ], Chart.prototype, \"series\", void 0);\n __decorate([\n Collection([{}], ChartAnnotationSettings)\n ], Chart.prototype, \"annotations\", void 0);\n __decorate([\n Property([])\n ], Chart.prototype, \"palettes\", void 0);\n __decorate([\n Property('Material')\n ], Chart.prototype, \"theme\", void 0);\n __decorate([\n Complex({}, TooltipSettings)\n ], Chart.prototype, \"tooltip\", void 0);\n __decorate([\n Complex({}, CrosshairSettings)\n ], Chart.prototype, \"crosshair\", void 0);\n __decorate([\n Complex({}, LegendSettings)\n ], Chart.prototype, \"legendSettings\", void 0);\n __decorate([\n Complex({}, ZoomSettings)\n ], Chart.prototype, \"zoomSettings\", void 0);\n __decorate([\n Property('None')\n ], Chart.prototype, \"selectionMode\", void 0);\n __decorate([\n Property(false)\n ], Chart.prototype, \"isMultiSelect\", void 0);\n __decorate([\n Collection([], Indexes)\n ], Chart.prototype, \"selectedDataIndexes\", void 0);\n __decorate([\n Property(false)\n ], Chart.prototype, \"useGroupingSeparator\", void 0);\n __decorate([\n Property(false)\n ], Chart.prototype, \"isTransposed\", void 0);\n __decorate([\n Collection([], TechnicalIndicator)\n ], Chart.prototype, \"indicators\", void 0);\n __decorate([\n Property(null)\n ], Chart.prototype, \"description\", void 0);\n __decorate([\n Property(1)\n ], Chart.prototype, \"tabIndex\", void 0);\n __decorate([\n Property(true)\n ], Chart.prototype, \"enableSideBySidePlacement\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"resized\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"annotationRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"beforePrint\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"loaded\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"load\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"animationComplete\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"legendRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"textRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"pointRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"seriesRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"axisLabelRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"axisRangeCalculated\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"axisMultiLabelRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"tooltipRender\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"chartMouseMove\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"chartMouseClick\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"pointClick\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"pointMove\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"chartMouseLeave\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"chartMouseDown\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"chartMouseUp\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"dragComplete\", void 0);\n __decorate([\n Event()\n ], Chart.prototype, \"zoomComplete\", void 0);\n __decorate([\n Property('USD')\n ], Chart.prototype, \"currencyCode\", void 0);\n Chart = __decorate([\n NotifyPropertyChanges\n ], Chart);\n return Chart;\n}(Component));\nexport { Chart };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Double } from '../axis/double-axis';\n/**\n * Common axis classes\n * @private\n */\nvar NiceInterval = /** @class */ (function (_super) {\n __extends(NiceInterval, _super);\n function NiceInterval() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Method to calculate numeric datetime interval\n */\n NiceInterval.prototype.calculateDateTimeNiceInterval = function (axis, size, start, end, isChart) {\n if (isChart === void 0) { isChart = true; }\n var oneDay = 24 * 60 * 60 * 1000;\n var startDate = new Date(start);\n var endDate = new Date(end);\n //var axisInterval ;\n var totalDays = (Math.abs((startDate.getTime() - endDate.getTime()) / (oneDay)));\n var interval;\n axis.actualIntervalType = axis.intervalType;\n var type = axis.intervalType;\n switch (type) {\n case 'Years':\n interval = this.calculateNumericNiceInterval(axis, totalDays / 365, size);\n break;\n case 'Quarter':\n interval = this.calculateNumericNiceInterval(axis, (totalDays / 365) * 4, size);\n break;\n case 'Months':\n interval = this.calculateNumericNiceInterval(axis, totalDays / 30, size);\n break;\n case 'Weeks':\n interval = this.calculateNumericNiceInterval(axis, totalDays / 7, size);\n break;\n case 'Days':\n interval = this.calculateNumericNiceInterval(axis, totalDays, size);\n break;\n case 'Hours':\n interval = this.calculateNumericNiceInterval(axis, totalDays * 24, size);\n break;\n case 'Minutes':\n interval = this.calculateNumericNiceInterval(axis, totalDays * 24 * 60, size);\n break;\n case 'Seconds':\n interval = this.calculateNumericNiceInterval(axis, totalDays * 24 * 60 * 60, size);\n break;\n case 'Auto':\n interval = this.calculateNumericNiceInterval(axis, totalDays / 365, size);\n if (interval >= 1) {\n axis.actualIntervalType = 'Years';\n return interval;\n }\n interval = this.calculateNumericNiceInterval(axis, (totalDays / 365) * 4, size);\n if (interval >= 1 && !isChart) {\n axis.actualIntervalType = 'Quarter';\n return interval;\n }\n interval = this.calculateNumericNiceInterval(axis, totalDays / 30, size);\n if (interval >= 1) {\n axis.actualIntervalType = 'Months';\n return interval;\n }\n interval = this.calculateNumericNiceInterval(axis, totalDays / 7, size);\n if (interval >= 1 && !isChart) {\n axis.actualIntervalType = 'Weeks';\n return interval;\n }\n interval = this.calculateNumericNiceInterval(axis, totalDays, size);\n if (interval >= 1) {\n axis.actualIntervalType = 'Days';\n return interval;\n }\n interval = this.calculateNumericNiceInterval(axis, totalDays * 24, size);\n if (interval >= 1) {\n axis.actualIntervalType = 'Hours';\n return interval;\n }\n interval = this.calculateNumericNiceInterval(axis, totalDays * 24 * 60, size);\n if (interval >= 1) {\n axis.actualIntervalType = 'Minutes';\n return interval;\n }\n interval = this.calculateNumericNiceInterval(axis, totalDays * 24 * 60 * 60, size);\n axis.actualIntervalType = 'Seconds';\n return interval;\n }\n return interval;\n };\n /**\n * To get the skeleton for the DateTime axis.\n * @return {string}\n * @private\n */\n NiceInterval.prototype.getSkeleton = function (axis) {\n var skeleton;\n var intervalType = axis.actualIntervalType;\n if (axis.skeleton) {\n return axis.skeleton;\n }\n if (intervalType === 'Years') {\n skeleton = axis.isChart ? 'yMMM' : 'y';\n }\n else if (intervalType === 'Quarter') {\n skeleton = 'yMMM';\n }\n else if (intervalType === 'Months') {\n skeleton = axis.isChart ? 'MMMd' : 'MMM';\n }\n else if (intervalType === 'Weeks') {\n skeleton = 'MEd';\n }\n else if (intervalType === 'Days') {\n skeleton = axis.isChart ? 'yMd' : 'MMMd';\n }\n else if (intervalType === 'Hours') {\n skeleton = axis.isChart ? 'EHm' : 'h';\n }\n else if (intervalType === 'Minutes') {\n skeleton = axis.isChart ? 'Hms' : 'hm';\n }\n else {\n skeleton = axis.isChart ? 'Hms' : 'hms';\n }\n return skeleton;\n };\n return NiceInterval;\n}(Double));\nexport { NiceInterval };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { setRange, triggerLabelRender } from '../../common/utils/helper';\nimport { DoubleRange } from '../utils/double-range';\nimport { withIn, firstToLowerCase } from '../../common/utils/helper';\nimport { extend, getValue } from '@syncfusion/ej2-base';\nimport { DataUtil } from '@syncfusion/ej2-data';\nimport { NiceInterval } from '../axis/axis-helper';\n/**\n * `DateTime` module is used to render datetime axis.\n */\nvar DateTime = /** @class */ (function (_super) {\n __extends(DateTime, _super);\n /**\n * Constructor for the dateTime module.\n * @private\n */\n function DateTime(chart) {\n return _super.call(this, chart) || this;\n }\n /**\n * The function to calculate the range and labels for the axis.\n * @return {void}\n */\n DateTime.prototype.calculateRangeAndInterval = function (size, axis) {\n this.calculateRange(axis, size);\n this.getActualRange(axis, size);\n this.applyRangePadding(axis, size);\n this.calculateVisibleLabels(axis, this.chart);\n };\n /**\n * Actual Range for the axis.\n * @private\n */\n DateTime.prototype.getActualRange = function (axis, size) {\n var option = {\n skeleton: 'full',\n type: 'dateTime'\n };\n var dateParser = this.chart.intl.getDateParser(option);\n var dateFormatter = this.chart.intl.getDateFormat(option);\n // Axis min\n if ((axis.minimum) !== null) {\n this.min = Date.parse(dateParser(dateFormatter(new Date(DataUtil.parse.parseJson({ val: axis.minimum }).val))));\n }\n else if (this.min === null || this.min === Number.POSITIVE_INFINITY) {\n this.min = Date.parse(dateParser(dateFormatter(new Date(1970, 1, 1))));\n }\n // Axis Max\n if ((axis.maximum) !== null) {\n this.max = Date.parse(dateParser(dateFormatter(new Date(DataUtil.parse.parseJson({ val: axis.maximum }).val))));\n }\n else if (this.max === null || this.max === Number.NEGATIVE_INFINITY) {\n this.max = Date.parse(dateParser(dateFormatter(new Date(1970, 5, 1))));\n }\n if (this.min === this.max) {\n this.max = this.max + 2592000000;\n this.min = this.min - 2592000000;\n }\n axis.actualRange = {};\n axis.doubleRange = new DoubleRange(this.min, this.max);\n var datetimeInterval = this.calculateDateTimeNiceInterval(axis, size, axis.doubleRange.start, axis.doubleRange.end);\n if (!axis.interval) {\n axis.actualRange.interval = datetimeInterval;\n }\n else {\n axis.actualRange.interval = axis.interval;\n }\n axis.actualRange.min = axis.doubleRange.start;\n axis.actualRange.max = axis.doubleRange.end;\n };\n /**\n * Apply padding for the range.\n * @private\n */\n DateTime.prototype.applyRangePadding = function (axis, size) {\n this.min = (axis.actualRange.min);\n this.max = (axis.actualRange.max);\n var minimum;\n var maximum;\n var interval = axis.actualRange.interval;\n if (!setRange(axis)) {\n var rangePadding = axis.getRangePadding(this.chart);\n minimum = new Date(this.min);\n maximum = new Date(this.max);\n var intervalType = axis.actualIntervalType;\n if (rangePadding === 'None') {\n this.min = minimum.getTime();\n this.max = maximum.getTime();\n }\n else if (rangePadding === 'Additional' || rangePadding === 'Round') {\n switch (intervalType) {\n case 'Years':\n this.getYear(minimum, maximum, rangePadding, interval);\n break;\n case 'Months':\n this.getMonth(minimum, maximum, rangePadding, interval);\n break;\n case 'Days':\n this.getDay(minimum, maximum, rangePadding, interval);\n break;\n case 'Hours':\n this.getHour(minimum, maximum, rangePadding, interval);\n break;\n case 'Minutes':\n var minute = (minimum.getMinutes() / interval) * interval;\n var endMinute = maximum.getMinutes() + (minimum.getMinutes() - minute);\n if (rangePadding === 'Round') {\n this.min = (new Date(minimum.getFullYear(), minimum.getMonth(), minimum.getDate(), minimum.getHours(), minute, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), maximum.getDate(), maximum.getHours(), endMinute, 59)).getTime();\n }\n else {\n this.min = (new Date(minimum.getFullYear(), maximum.getMonth(), minimum.getDate(), minimum.getHours(), minute + (-interval), 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), maximum.getDate(), maximum.getHours(), endMinute + (interval), 0)).getTime();\n }\n break;\n case 'Seconds':\n var second = (minimum.getSeconds() / interval) * interval;\n var endSecond = maximum.getSeconds() + (minimum.getSeconds() - second);\n if (rangePadding === 'Round') {\n this.min = (new Date(minimum.getFullYear(), minimum.getMonth(), minimum.getDate(), minimum.getHours(), minimum.getMinutes(), second, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), maximum.getDate(), maximum.getHours(), maximum.getMinutes(), endSecond, 0)).getTime();\n }\n else {\n this.min = (new Date(minimum.getFullYear(), minimum.getMonth(), minimum.getDate(), minimum.getHours(), minimum.getMinutes(), second + (-interval), 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), maximum.getDate(), maximum.getHours(), maximum.getMinutes(), endSecond + (interval), 0)).getTime();\n }\n break;\n }\n }\n }\n axis.actualRange.min = (axis.minimum != null) ? this.min : this.min;\n axis.actualRange.max = (axis.maximum != null) ? this.max : this.max;\n axis.actualRange.delta = (axis.actualRange.max - axis.actualRange.min);\n axis.doubleRange = new DoubleRange(axis.actualRange.min, axis.actualRange.max);\n this.calculateVisibleRange(size, axis);\n };\n DateTime.prototype.getYear = function (minimum, maximum, rangePadding, interval) {\n var startYear = minimum.getFullYear();\n var endYear = maximum.getFullYear();\n if (rangePadding === 'Additional') {\n this.min = (new Date(startYear - interval, 1, 1, 0, 0, 0)).getTime();\n this.max = (new Date(endYear + interval, 1, 1, 0, 0, 0)).getTime();\n }\n else {\n this.min = new Date(startYear, 0, 0, 0, 0, 0).getTime();\n this.max = new Date(endYear, 11, 30, 23, 59, 59).getTime();\n }\n };\n DateTime.prototype.getMonth = function (minimum, maximum, rangePadding, interval) {\n var month = minimum.getMonth();\n var endMonth = maximum.getMonth();\n if (rangePadding === 'Round') {\n this.min = (new Date(minimum.getFullYear(), month, 0, 0, 0, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), endMonth, new Date(maximum.getFullYear(), maximum.getMonth(), 0).getDate(), 23, 59, 59)).getTime();\n }\n else {\n this.min = (new Date(minimum.getFullYear(), month + (-interval), 1, 0, 0, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), endMonth + (interval), endMonth === 2 ? 28 : 30, 0, 0, 0)).getTime();\n }\n };\n DateTime.prototype.getDay = function (minimum, maximum, rangePadding, interval) {\n var day = minimum.getDate();\n var endDay = maximum.getDate();\n if (rangePadding === 'Round') {\n this.min = (new Date(minimum.getFullYear(), minimum.getMonth(), day, 0, 0, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), endDay, 23, 59, 59)).getTime();\n }\n else {\n this.min = (new Date(minimum.getFullYear(), minimum.getMonth(), day + (-interval), 0, 0, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), endDay + (interval), 0, 0, 0)).getTime();\n }\n };\n DateTime.prototype.getHour = function (minimum, maximum, rangePadding, interval) {\n var hour = (minimum.getHours() / interval) * interval;\n var endHour = maximum.getHours() + (minimum.getHours() - hour);\n if (rangePadding === 'Round') {\n this.min = (new Date(minimum.getFullYear(), minimum.getMonth(), minimum.getDate(), hour, 0, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), maximum.getDate(), endHour, 59, 59)).getTime();\n }\n else {\n this.min = (new Date(minimum.getFullYear(), minimum.getMonth(), minimum.getDate(), hour + (-interval), 0, 0)).getTime();\n this.max = (new Date(maximum.getFullYear(), maximum.getMonth(), maximum.getDate(), endHour + (interval), 0, 0)).getTime();\n }\n };\n /**\n * Calculate visible range for axis.\n * @private\n */\n DateTime.prototype.calculateVisibleRange = function (size, axis) {\n axis.visibleRange = {\n min: axis.actualRange.min,\n max: axis.actualRange.max,\n interval: axis.actualRange.interval,\n delta: axis.actualRange.delta,\n };\n if (axis.zoomFactor < 1 || axis.zoomPosition > 0) {\n axis.calculateVisibleRange(size);\n axis.visibleRange.interval = (axis.enableAutoIntervalOnZooming) ?\n this.calculateDateTimeNiceInterval(axis, size, axis.visibleRange.min, axis.visibleRange.max)\n : axis.visibleRange.interval;\n }\n axis.dateTimeInterval = this.increaseDateTimeInterval(axis, axis.visibleRange.min, axis.visibleRange.interval).getTime()\n - axis.visibleRange.min;\n axis.triggerRangeRender(this.chart, axis.visibleRange.min, axis.visibleRange.max, axis.visibleRange.interval);\n };\n /**\n * Calculate visible labels for the axis.\n * @private\n */\n DateTime.prototype.calculateVisibleLabels = function (axis, chart) {\n axis.visibleLabels = [];\n var tempInterval = axis.visibleRange.min;\n var labelStyle;\n if (!setRange(axis)) {\n tempInterval = this.alignRangeStart(axis, tempInterval, axis.visibleRange.interval, axis.actualIntervalType).getTime();\n }\n axis.format = chart.intl.getDateFormat({\n format: axis.labelFormat, type: firstToLowerCase(axis.skeletonType), skeleton: this.getSkeleton(axis)\n });\n axis.startLabel = axis.format(new Date(axis.visibleRange.min));\n axis.endLabel = axis.format(new Date(axis.visibleRange.max));\n while (tempInterval <= axis.visibleRange.max) {\n labelStyle = (extend({}, getValue('properties', axis.labelStyle), null, true));\n if (withIn(tempInterval, axis.visibleRange)) {\n triggerLabelRender(chart, tempInterval, axis.format(new Date(tempInterval)), labelStyle, axis);\n }\n tempInterval = this.increaseDateTimeInterval(axis, tempInterval, axis.visibleRange.interval).getTime();\n }\n if (axis.getMaxLabelWidth) {\n axis.getMaxLabelWidth(this.chart);\n }\n };\n /** @private */\n DateTime.prototype.increaseDateTimeInterval = function (axis, value, interval) {\n var result = new Date(value);\n interval = Math.ceil(interval);\n var intervalType = axis.actualIntervalType;\n switch (intervalType) {\n case 'Years':\n result.setFullYear(result.getFullYear() + interval);\n return result;\n case 'Quarter':\n result.setMonth(result.getMonth() + (3 * interval));\n return result;\n case 'Months':\n result.setMonth(result.getMonth() + interval);\n return result;\n case 'Weeks':\n result.setDate(result.getDate() + (interval * 7));\n return result;\n case 'Days':\n result.setDate(result.getDate() + interval);\n return result;\n case 'Hours':\n result.setHours(result.getHours() + interval);\n return result;\n case 'Minutes':\n result.setMinutes(result.getMinutes() + interval);\n return result;\n case 'Seconds':\n result.setSeconds(result.getSeconds() + interval);\n return result;\n }\n return result;\n };\n DateTime.prototype.alignRangeStart = function (axis, sDate, intervalSize, intervalType) {\n var sResult = new Date(sDate);\n switch (axis.actualIntervalType) {\n case 'Years':\n var year = Math.floor(Math.floor(sResult.getFullYear() / intervalSize) * intervalSize);\n sResult = new Date(year, sResult.getMonth(), sResult.getDate(), 0, 0, 0);\n return sResult;\n case 'Months':\n var month = Math.floor(Math.floor((sResult.getMonth()) / intervalSize) * intervalSize);\n sResult = new Date(sResult.getFullYear(), month, sResult.getDate(), 0, 0, 0);\n return sResult;\n case 'Days':\n var day = Math.floor(Math.floor((sResult.getDate()) / intervalSize) * intervalSize);\n sResult = new Date(sResult.getFullYear(), sResult.getMonth(), day, 0, 0, 0);\n return sResult;\n case 'Hours':\n var hour = Math.floor(Math.floor((sResult.getHours()) / intervalSize) * intervalSize);\n sResult = new Date(sResult.getFullYear(), sResult.getMonth(), sResult.getDate(), hour, 0, 0);\n return sResult;\n case 'Minutes':\n var minutes = Math.floor(Math.floor((sResult.getMinutes()) / intervalSize) * intervalSize);\n sResult = new Date(sResult.getFullYear(), sResult.getMonth(), sResult.getDate(), sResult.getHours(), minutes, 0, 0);\n return sResult;\n case 'Seconds':\n var seconds = Math.floor(Math.floor((sResult.getSeconds()) / intervalSize) * intervalSize);\n sResult = new Date(sResult.getFullYear(), sResult.getMonth(), sResult.getDate(), sResult.getHours(), sResult.getMinutes(), seconds, 0);\n return sResult;\n }\n return sResult;\n };\n /**\n * Get module name\n */\n DateTime.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'DateTime';\n };\n /**\n * To destroy the category axis.\n * @return {void}\n * @private\n */\n DateTime.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return DateTime;\n}(NiceInterval));\nexport { DateTime };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { getActualDesiredIntervalsCount, triggerLabelRender } from '../../common/utils/helper';\nimport { DoubleRange } from '../utils/double-range';\nimport { withIn } from '../../common/utils/helper';\nimport { extend, getValue } from '@syncfusion/ej2-base';\nimport { NiceInterval } from '../axis/axis-helper';\n/**\n * `Category` module is used to render category axis.\n */\nvar Category = /** @class */ (function (_super) {\n __extends(Category, _super);\n /**\n * Constructor for the category module.\n * @private\n */\n function Category(chart) {\n return _super.call(this, chart) || this;\n }\n /**\n * The function to calculate the range and labels for the axis.\n * @return {void}\n */\n Category.prototype.calculateRangeAndInterval = function (size, axis) {\n this.calculateRange(axis, size);\n this.getActualRange(axis, size);\n this.applyRangePadding(axis, size);\n this.calculateVisibleLabels(axis);\n };\n /**\n * Actual Range for the axis.\n * @private\n */\n Category.prototype.getActualRange = function (axis, size) {\n this.initializeDoubleRange(axis);\n // axis.doubleRange = new DoubleRange(
this.min, this.max);\n axis.actualRange = {};\n if (!axis.interval) {\n axis.actualRange.interval = Math.max(1, Math.floor(axis.doubleRange.delta / getActualDesiredIntervalsCount(size, axis)));\n }\n else {\n axis.actualRange.interval = Math.ceil(axis.interval);\n }\n axis.actualRange.min = axis.doubleRange.start;\n axis.actualRange.max = axis.doubleRange.end;\n axis.actualRange.delta = axis.doubleRange.delta;\n };\n /**\n * Padding for the axis.\n * @private\n */\n Category.prototype.applyRangePadding = function (axis, size) {\n var ticks = (axis.labelPlacement === 'BetweenTicks' && this.chart.chartAreaType !== 'PolarRadar') ? 0.5 : 0;\n if (ticks > 0) {\n axis.actualRange.min -= ticks;\n axis.actualRange.max += ticks;\n }\n else {\n axis.actualRange.max += axis.actualRange.max ? 0 : 0.5;\n }\n axis.doubleRange = new DoubleRange(axis.actualRange.min, axis.actualRange.max);\n axis.actualRange.delta = axis.doubleRange.delta;\n this.calculateVisibleRange(size, axis);\n };\n /**\n * Calculate label for the axis.\n * @private\n */\n Category.prototype.calculateVisibleLabels = function (axis) {\n /*! Generate axis labels */\n axis.visibleLabels = [];\n var tempInterval = Math.ceil(axis.visibleRange.min);\n var labelStyle;\n if (axis.zoomFactor < 1 || axis.zoomPosition > 0) {\n tempInterval = axis.visibleRange.min - (axis.visibleRange.min % axis.visibleRange.interval);\n }\n var position;\n axis.startLabel = axis.labels[Math.round(axis.visibleRange.min)];\n axis.endLabel = axis.labels[Math.floor(axis.visibleRange.max)];\n for (; tempInterval <= axis.visibleRange.max; tempInterval += axis.visibleRange.interval) {\n labelStyle = (extend({}, getValue('properties', axis.labelStyle), null, true));\n if (withIn(tempInterval, axis.visibleRange) && axis.labels.length > 0) {\n position = Math.round(tempInterval);\n triggerLabelRender(this.chart, position, axis.labels[position] ? axis.labels[position] : position.toString(), labelStyle, axis);\n }\n }\n if (axis.getMaxLabelWidth) {\n axis.getMaxLabelWidth(this.chart);\n }\n };\n /**\n * Get module name\n */\n Category.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'Category';\n };\n /**\n * To destroy the category axis.\n * @return {void}\n * @private\n */\n Category.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return Category;\n}(NiceInterval));\nexport { Category };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Double } from '../axis/double-axis';\nimport { getActualDesiredIntervalsCount, triggerLabelRender } from '../../common/utils/helper';\nimport { logBase, withIn } from '../../common/utils/helper';\nimport { extend, getValue } from '@syncfusion/ej2-base';\n/**\n * `Logarithmic` module is used to render log axis.\n */\nvar Logarithmic = /** @class */ (function (_super) {\n __extends(Logarithmic, _super);\n /**\n * Constructor for the logerithmic module.\n * @private\n */\n function Logarithmic(chart) {\n return _super.call(this, chart) || this;\n }\n /**\n * The method to calculate the range and labels for the axis.\n * @return {void}\n */\n Logarithmic.prototype.calculateRangeAndInterval = function (size, axis) {\n this.calculateRange(axis, size);\n this.getActualRange(axis, size);\n this.calculateVisibleRange(size, axis);\n this.calculateVisibleLabels(axis, this.chart);\n };\n /**\n * Calculates actual range for the axis.\n * @private\n */\n Logarithmic.prototype.getActualRange = function (axis, size) {\n this.initializeDoubleRange(axis);\n this.min = this.min < 0 ? 0 : this.min;\n var logStart = logBase(this.min, axis.logBase);\n logStart = isFinite(logStart) ? logStart : this.min;\n var logEnd = logBase(this.max, axis.logBase);\n logEnd = isFinite(logStart) ? logEnd : this.max;\n this.min = Math.floor(logStart / 1);\n this.max = Math.ceil(logEnd / 1);\n axis.actualRange.interval = axis.interval || this.calculateLogNiceInterval(this.max - this.min, size, axis);\n axis.actualRange.min = this.min;\n axis.actualRange.max = this.max;\n axis.actualRange.delta = this.max - this.min;\n };\n /**\n * Calculates visible range for the axis.\n * @private\n */\n Logarithmic.prototype.calculateVisibleRange = function (size, axis) {\n axis.visibleRange = {\n interval: axis.actualRange.interval, max: axis.actualRange.max,\n min: axis.actualRange.min, delta: axis.actualRange.delta\n };\n if (axis.zoomFactor < 1 || axis.zoomPosition > 0) {\n axis.calculateVisibleRange(size);\n axis.visibleRange.interval = (axis.enableAutoIntervalOnZooming) ?\n this.calculateLogNiceInterval(axis.doubleRange.delta, size, axis)\n : axis.visibleRange.interval;\n axis.visibleRange.interval = Math.floor(axis.visibleRange.interval) === 0 ? 1 : Math.floor(axis.visibleRange.interval);\n axis.triggerRangeRender(this.chart, axis.visibleRange.min, axis.visibleRange.max, axis.visibleRange.interval);\n }\n };\n /**\n * Calculates log iInteval for the axis.\n * @private\n */\n Logarithmic.prototype.calculateLogNiceInterval = function (delta, size, axis) {\n var actualDesiredIntervalsCount = getActualDesiredIntervalsCount(size, axis);\n var niceInterval = delta;\n var minInterval = Math.pow(10, Math.floor(logBase(niceInterval, 10)));\n for (var j = 0, len = axis.intervalDivs.length; j < len; j++) {\n var currentInterval = minInterval * axis.intervalDivs[j];\n if (actualDesiredIntervalsCount < (delta / currentInterval)) {\n break;\n }\n niceInterval = currentInterval;\n }\n return niceInterval;\n };\n /**\n * Calculates labels for the axis.\n * @private\n */\n Logarithmic.prototype.calculateVisibleLabels = function (axis, chart) {\n /*! Generate axis labels */\n var tempInterval = axis.visibleRange.min;\n axis.visibleLabels = [];\n var labelStyle;\n if (axis.zoomFactor < 1 || axis.zoomPosition > 0) {\n tempInterval = axis.visibleRange.min - (axis.visibleRange.min % axis.visibleRange.interval);\n }\n var axisFormat = this.getFormat(axis);\n var isCustomFormat = axisFormat.match('{value}') !== null;\n axis.format = chart.intl.getNumberFormat({\n format: isCustomFormat ? '' : axisFormat,\n useGrouping: chart.useGroupingSeparator\n });\n axis.startLabel = axis.format(Math.pow(axis.logBase, axis.visibleRange.min));\n axis.endLabel = axis.format(Math.pow(axis.logBase, axis.visibleRange.max));\n for (; tempInterval <= axis.visibleRange.max; tempInterval += axis.visibleRange.interval) {\n labelStyle = (extend({}, getValue('properties', axis.labelStyle), null, true));\n if (withIn(tempInterval, axis.visibleRange)) {\n triggerLabelRender(this.chart, tempInterval, this.formatValue(axis, isCustomFormat, axisFormat, Math.pow(axis.logBase, tempInterval)), labelStyle, axis);\n }\n }\n if (axis.getMaxLabelWidth) {\n axis.getMaxLabelWidth(this.chart);\n }\n };\n /**\n * Get module name\n */\n Logarithmic.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'Logarithmic';\n };\n /**\n * To destroy the category axis.\n * @return {void}\n * @private\n */\n Logarithmic.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return Logarithmic;\n}(Double));\nexport { Logarithmic };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Category } from '../axis/category-axis';\nimport { triggerLabelRender } from '../../common/utils/helper';\nimport { withIn, firstToLowerCase } from '../../common/utils/helper';\nimport { extend, getValue } from '@syncfusion/ej2-base';\n/**\n * Category module is used to render category axis.\n */\nvar DateTimeCategory = /** @class */ (function (_super) {\n __extends(DateTimeCategory, _super);\n /**\n * Constructor for the category module.\n * @private\n */\n function DateTimeCategory(chart) {\n return _super.call(this, chart) || this;\n }\n /**\n * The function to calculate the range and labels for the axis.\n * @return {void}\n * @private\n */\n DateTimeCategory.prototype.calculateRangeAndInterval = function (size, axis) {\n this.axisSize = size;\n this.calculateRange(axis, size);\n this.getActualRange(axis, size);\n this.applyRangePadding(axis, size);\n this.calculateVisibleLabels(axis);\n };\n /**\n * Calculate label for the axis.\n * @private\n */\n DateTimeCategory.prototype.calculateVisibleLabels = function (axis) {\n /*! Generate axis labels */\n axis.visibleLabels = [];\n var labelStyle;\n var padding = axis.labelPlacement === 'BetweenTicks' ? 0.5 : 0;\n if (axis.intervalType === 'Auto') {\n this.calculateDateTimeNiceInterval(axis, this.axisSize, parseInt(axis.labels[0], 10), parseInt(axis.labels[axis.labels.length - 1], 10));\n }\n else {\n axis.actualIntervalType = axis.intervalType;\n }\n axis.format = this.chart.intl.getDateFormat({\n format: axis.labelFormat, type: firstToLowerCase(axis.skeletonType), skeleton: this.getSkeleton(axis)\n });\n for (var i = 0; i < axis.labels.length; i++) {\n labelStyle = (extend({}, getValue('properties', axis.labelStyle), null, true));\n if (!this.sameInterval(axis.labels.map(Number)[i], axis.labels.map(Number)[i - 1], axis.actualIntervalType, i)) {\n if (withIn(i - padding, axis.visibleRange)) {\n triggerLabelRender(this.chart, i, axis.format(new Date(axis.labels.map(Number)[i])), labelStyle, axis);\n }\n }\n }\n if (axis.getMaxLabelWidth) {\n axis.getMaxLabelWidth(this.chart);\n }\n };\n /**\n * get same interval\n */\n DateTimeCategory.prototype.sameInterval = function (currentDate, previousDate, type, index) {\n var sameValue;\n if (index === 0) {\n sameValue = false;\n }\n else {\n switch (type) {\n case 'Years':\n sameValue = new Date(currentDate).getFullYear() === new Date(previousDate).getFullYear();\n break;\n case 'Months':\n sameValue = new Date(currentDate).getFullYear() === new Date(previousDate).getFullYear() &&\n new Date(currentDate).getMonth() === new Date(previousDate).getMonth();\n break;\n case 'Days':\n sameValue = (Math.abs(currentDate - previousDate) < 24 * 60 * 60 * 1000 &&\n new Date(currentDate).getDay() === new Date(previousDate).getDay());\n break;\n case 'Hours':\n sameValue = (Math.abs(currentDate - previousDate) < 60 * 60 * 1000 &&\n new Date(currentDate).getDay() === new Date(previousDate).getDay());\n break;\n case 'Minutes':\n sameValue = (Math.abs(currentDate - previousDate) < 60 * 1000 &&\n new Date(currentDate).getMinutes() === new Date(previousDate).getMinutes());\n break;\n case 'Seconds':\n sameValue = (Math.abs(currentDate - previousDate) < 1000 &&\n new Date(currentDate).getDay() === new Date(previousDate).getDay());\n break;\n }\n }\n return sameValue;\n };\n /**\n * Get module name\n */\n DateTimeCategory.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'DateTimeCategory';\n };\n /**\n * To destroy the category axis.\n * @return {void}\n * @private\n */\n DateTimeCategory.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return DateTimeCategory;\n}(Category));\nexport { DateTimeCategory };\n","/**\n * StripLine src\n */\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Rect, TextOption, measureText, valueToCoefficient, textElement, logBase, RectOption } from '../../common/utils/helper';\n/**\n * `StripLine` module is used to render the stripLine in chart.\n */\nvar StripLine = /** @class */ (function () {\n function StripLine() {\n }\n StripLine.prototype.measureStripLine = function (axis, stripline, seriesClipRect) {\n var actualStart;\n var actualEnd;\n if (axis.valueType === 'DateTimeCategory') {\n var start = stripline.start;\n var end = stripline.end;\n actualStart = start ? axis.labels.indexOf(start.getTime().toString()) : null;\n actualEnd = end ? axis.labels.indexOf(end.getTime().toString()) : null;\n }\n else {\n actualStart = stripline.start;\n actualEnd = stripline.end;\n }\n var rect = this.getFromTovalue(actualStart, actualEnd, stripline.size, stripline.startFromAxis, axis);\n var height = (axis.orientation === 'Vertical') ? (rect.to - rect.from) * axis.rect.height : seriesClipRect.height;\n var width = (axis.orientation === 'Horizontal') ? (rect.to - rect.from) * axis.rect.width : seriesClipRect.width;\n var x = (axis.orientation === 'Vertical') ? seriesClipRect.x : ((rect.from * axis.rect.width) + axis.rect.x);\n var y = (axis.orientation === 'Horizontal') ? seriesClipRect.y : (axis.rect.y + axis.rect.height -\n (rect.to * axis.rect.height));\n if (height !== 0 && width !== 0) {\n return new Rect(x, y, width, height);\n }\n return new Rect(0, 0, 0, 0);\n };\n /**\n * To get from to value from start, end, size, start from axis\n */\n StripLine.prototype.getFromTovalue = function (start, end, size, startFromAxis, axis) {\n var from = startFromAxis ? axis.visibleRange.min : this.findValue(Math.min(start, isNullOrUndefined(end) ? start : end), axis);\n var to = this.findValue(this.getToValue(Math.max(start, isNullOrUndefined(end) ? start : end), from, size, axis, end), axis);\n return { from: valueToCoefficient(axis.isInversed ? to : from, axis), to: valueToCoefficient(axis.isInversed ? from : to, axis) };\n };\n StripLine.prototype.getToValue = function (to, from, size, axis, end) {\n if (axis.valueType === 'DateTime') {\n return (isNullOrUndefined(end) ? new Date(new Date(from).getTime() + size) : to);\n }\n else {\n return isNullOrUndefined(end) ? (axis.valueType === 'Logarithmic' ? Math.pow(axis.logBase, from) : from) + size : to;\n }\n };\n StripLine.prototype.findValue = function (value, axis) {\n if (axis.valueType === 'Logarithmic') {\n value = logBase(value, axis.logBase);\n }\n if (value < axis.visibleRange.min) {\n value = axis.visibleRange.min;\n }\n else if (value > axis.visibleRange.max) {\n value = axis.visibleRange.max;\n }\n return value;\n };\n /**\n * To render striplines based start and end.\n * @private\n * @param chart\n * @param position\n * @param axes\n */\n StripLine.prototype.renderStripLine = function (chart, position, axes) {\n var id = chart.element.id + '_stripline_' + position + '_';\n var striplineGroup = chart.renderer.createGroup({ id: id + 'collections' });\n var seriesClipRect = chart.chartAxisLayoutPanel.seriesClipRect;\n var rect;\n var count = 0;\n for (var _i = 0, axes_1 = axes; _i < axes_1.length; _i++) {\n var axis = axes_1[_i];\n for (var _a = 0, _b = axis.stripLines; _a < _b.length; _a++) {\n var stripline = _b[_a];\n if (stripline.visible && stripline.zIndex === position) {\n rect = this.measureStripLine(axis, stripline, seriesClipRect);\n this.renderRectangle(stripline, rect, id + 'rect_' + count, striplineGroup, chart);\n this.renderText(stripline, rect, id + 'text_' + count, striplineGroup, chart, axis);\n count++;\n }\n }\n }\n chart.svgObject.appendChild(striplineGroup);\n };\n StripLine.prototype.renderRectangle = function (stripline, rect, id, parent, chart) {\n parent.appendChild(chart.renderer.drawRectangle(new RectOption(id, stripline.color, stripline.border, stripline.opacity, rect, 0, 0, '', '')));\n };\n StripLine.prototype.renderText = function (stripline, rect, id, parent, chart, axis) {\n var textSize = measureText(stripline.text, stripline.textStyle);\n var textMid = 3 * (textSize.height / 8);\n var ty = rect.y + (rect.height / 2) + textMid;\n var rotation = (stripline.rotation === null) ? ((axis.orientation === 'Vertical') ? 0 : -90) : stripline.rotation;\n var tx = rect.x + (rect.width / 2);\n var alignment;\n var anchor;\n var padding = 5;\n if (axis.orientation === 'Horizontal') {\n tx = this.getTextStart(tx + (textMid * this.factor(stripline.horizontalAlignment)), rect.width, stripline.horizontalAlignment);\n ty = this.getTextStart(ty - textMid, rect.height, stripline.verticalAlignment);\n alignment = this.invertAlignment(stripline.horizontalAlignment);\n }\n else {\n tx = this.getTextStart(tx, rect.width, stripline.horizontalAlignment);\n ty = this.getTextStart(ty + (textMid * this.factor(stripline.verticalAlignment)) - padding, rect.height, stripline.verticalAlignment);\n alignment = stripline.verticalAlignment;\n }\n anchor = alignment;\n textElement(new TextOption(id, tx, ty, anchor, stripline.text, 'rotate(' + rotation + ' ' + tx + ',' + ty + ')', 'middle'), stripline.textStyle, stripline.textStyle.color, parent);\n };\n StripLine.prototype.invertAlignment = function (anchor) {\n switch (anchor) {\n case 'Start':\n anchor = 'Start';\n break;\n case 'End':\n anchor = 'End';\n break;\n }\n return anchor;\n };\n StripLine.prototype.factor = function (anchor) {\n var factor = 0;\n switch (anchor) {\n case 'Start':\n factor = 1;\n break;\n case 'End':\n factor = -1;\n break;\n }\n return factor;\n };\n StripLine.prototype.getTextStart = function (xy, size, textAlignment) {\n var padding = 5;\n switch (textAlignment) {\n case 'Start':\n xy = xy - (size / 2) + padding;\n break;\n case 'End':\n xy = xy + (size / 2) - padding;\n break;\n }\n return xy;\n };\n /**\n * To get the module name for `StripLine`.\n * @private\n */\n StripLine.prototype.getModuleName = function () {\n return 'StripLine';\n };\n /**\n * To destroy the `StripLine` module.\n * @private\n */\n StripLine.prototype.destroy = function () {\n // destroy peform here\n };\n return StripLine;\n}());\nexport { StripLine };\n","import { Rect, getAnimationFunction } from '../../common/utils/helper';\nimport { Animation } from '@syncfusion/ej2-base';\n/**\n * Base for line type series.\n */\nvar LineBase = /** @class */ (function () {\n /** @private */\n function LineBase(chartModule) {\n this.chart = chartModule;\n this.padding = 5;\n }\n /**\n * To improve the chart performance.\n * @return {void}\n * @private\n */\n LineBase.prototype.improveChartPerformance = function (series) {\n var tempPoints = [];\n var xVisibleRange = series.xAxis.visibleRange;\n var yVisibleRange = series.yAxis.visibleRange;\n var seriesPoints = series.points;\n var areaBounds = series.clipRect;\n var xTolerance = Math.abs(xVisibleRange.delta / areaBounds.width);\n var yTolerance = Math.abs(yVisibleRange.delta / areaBounds.height);\n var prevXValue = (seriesPoints[0] && seriesPoints[0].x > xTolerance) ? 0 : xTolerance;\n var prevYValue = (seriesPoints[0] && seriesPoints[0].y > yTolerance) ? 0 : yTolerance;\n var xVal = 0;\n var yVal = 0;\n var currentPoint;\n for (var _i = 0, seriesPoints_1 = seriesPoints; _i < seriesPoints_1.length; _i++) {\n var currentPoint_1 = seriesPoints_1[_i];\n currentPoint_1.symbolLocations = [];\n xVal = currentPoint_1.xValue ? currentPoint_1.xValue : xVisibleRange.min;\n yVal = currentPoint_1.yValue ? currentPoint_1.yValue : yVisibleRange.min;\n if (Math.abs(prevXValue - xVal) >= xTolerance || Math.abs(prevYValue - yVal) >= yTolerance) {\n tempPoints.push(currentPoint_1);\n prevXValue = xVal;\n prevYValue = yVal;\n }\n }\n return tempPoints;\n };\n /**\n * To generate the line path direction\n * @param firstPoint\n * @param secondPoint\n * @param series\n * @param isInverted\n * @param getPointLocation\n * @param startPoint\n */\n LineBase.prototype.getLineDirection = function (firstPoint, secondPoint, series, isInverted, getPointLocation, startPoint) {\n var direction = '';\n if (firstPoint != null) {\n var point1 = getPointLocation(firstPoint.xValue, firstPoint.yValue, series.xAxis, series.yAxis, isInverted, series);\n var point2 = getPointLocation(secondPoint.xValue, secondPoint.yValue, series.xAxis, series.yAxis, isInverted, series);\n direction = startPoint + ' ' + (point1.x) + ' ' + (point1.y) + ' ' +\n 'L' + ' ' + (point2.x) + ' ' + (point2.y) + ' ';\n }\n return direction;\n };\n /**\n * To append the line path.\n * @return {void}\n * @private\n */\n LineBase.prototype.appendLinePath = function (options, series, clipRect) {\n var htmlObject = series.chart.renderer.drawPath(options);\n htmlObject.setAttribute('clip-path', clipRect);\n series.pathElement = htmlObject;\n series.seriesElement.appendChild(htmlObject);\n series.isRectSeries = false;\n };\n /**\n * To render the marker for the series.\n * @return {void}\n * @private\n */\n LineBase.prototype.renderMarker = function (series) {\n if (series.marker && series.marker.visible) {\n series.chart.markerRender.render(series);\n }\n };\n /**\n * To do the progressive animation.\n * @return {void}\n * @private\n */\n LineBase.prototype.doProgressiveAnimation = function (series, option) {\n var animation = new Animation({});\n var path = series.pathElement;\n var strokeDashArray = path.getAttribute('stroke-dasharray');\n var pathLength = series.pathElement.getTotalLength();\n var currentTime;\n path.style.visibility = 'hidden';\n animation.animate(path, {\n duration: option.duration,\n delay: option.delay,\n progress: function (args) {\n if (args.timeStamp >= args.delay) {\n path.style.visibility = 'visible';\n currentTime = Math.abs(Math.round(((args.timeStamp - args.delay) * pathLength) / args.duration));\n path.setAttribute('stroke-dasharray', currentTime + ',' + pathLength);\n }\n },\n end: function (model) {\n path.setAttribute('stroke-dasharray', strokeDashArray);\n series.chart.trigger('animationComplete', { series: series });\n }\n });\n };\n /**\n * To store the symbol location and region\n * @param point\n * @param series\n * @param isInverted\n * @param getLocation\n */\n LineBase.prototype.storePointLocation = function (point, series, isInverted, getLocation) {\n var markerWidth = (series.marker && series.marker.width) ? series.marker.width : 0;\n var markerHeight = (series.marker && series.marker.height) ? series.marker.height : 0;\n point.symbolLocations.push(getLocation(point.xValue, point.yValue, series.xAxis, series.yAxis, isInverted, series));\n point.regions.push(new Rect(point.symbolLocations[0].x - markerWidth, point.symbolLocations[0].y - markerHeight, 2 * markerWidth, 2 * markerHeight));\n };\n /**\n * To do the linear animation.\n * @return {void}\n * @private\n */\n LineBase.prototype.doLinearAnimation = function (series, animation) {\n var clipRect = series.clipRectElement.childNodes[0].childNodes[0];\n var effect = getAnimationFunction('Linear');\n var elementHeight = +clipRect.getAttribute('height');\n var elementWidth = +clipRect.getAttribute('width');\n var xCenter = +clipRect.getAttribute('x');\n var yCenter = series.chart.requireInvertedAxis ? +clipRect.getAttribute('height') + +clipRect.getAttribute('y') :\n +clipRect.getAttribute('y');\n var value;\n clipRect.style.visibility = 'hidden';\n new Animation({}).animate(clipRect, {\n duration: animation.duration,\n delay: animation.delay,\n progress: function (args) {\n if (args.timeStamp >= args.delay) {\n clipRect.style.visibility = 'visible';\n if (series.chart.requireInvertedAxis) {\n value = effect(args.timeStamp - args.delay, 0, elementHeight, args.duration);\n clipRect.setAttribute('transform', 'translate(' + xCenter + ' ' + yCenter +\n ') scale(1,' + (value / elementHeight) + ') translate(' + (-xCenter) + ' ' + (-yCenter) + ')');\n }\n else {\n value = effect(args.timeStamp - args.delay, 0, elementWidth, args.duration);\n clipRect.setAttribute('transform', 'translate(' + xCenter + ' ' + yCenter +\n ') scale(' + (value / elementWidth) + ', 1) translate(' + (-xCenter) + ' ' + (-yCenter) + ')');\n }\n }\n },\n end: function (model) {\n clipRect.setAttribute('transform', 'translate(0,0)');\n series.chart.trigger('animationComplete', { series: series });\n }\n });\n };\n return LineBase;\n}());\nexport { LineBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange, getPoint, PathOption, TransformToVisible } from '../../common/utils/helper';\nimport { LineBase } from './line-base';\n/**\n * `LineSeries` module used to render the line series.\n */\nvar LineSeries = /** @class */ (function (_super) {\n __extends(LineSeries, _super);\n function LineSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Line Series.\n * @return {void}.\n * @private\n */\n LineSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var point1;\n var point2;\n var direction = '';\n var prevPoint = null;\n var startPoint = 'M';\n var options;\n var isPolar = (series.chart && series.chart.chartAreaType === 'PolarRadar');\n var isDrop = (series.emptyPointSettings && series.emptyPointSettings.mode === 'Drop');\n var getCoordinate = isPolar ? TransformToVisible : getPoint;\n var visiblePoints = this.improveChartPerformance(series);\n for (var _i = 0, visiblePoints_1 = visiblePoints; _i < visiblePoints_1.length; _i++) {\n var point = visiblePoints_1[_i];\n point.regions = [];\n if (point.visible && withInRange(visiblePoints[point.index - 1], point, visiblePoints[point.index + 1], series)) {\n direction += this.getLineDirection(prevPoint, point, series, isInverted, getCoordinate, startPoint);\n startPoint = prevPoint ? 'L' : startPoint;\n prevPoint = point;\n this.storePointLocation(point, series, isInverted, getCoordinate);\n }\n else {\n prevPoint = isDrop ? prevPoint : null;\n startPoint = isDrop ? startPoint : 'M';\n point.symbolLocations = [];\n }\n }\n if (isPolar) {\n if (series.isClosed) {\n point2 = getCoordinate(visiblePoints[visiblePoints.length - 1].xValue, visiblePoints[visiblePoints.length - 1].yValue, xAxis, yAxis, isInverted, series);\n point1 = getCoordinate(visiblePoints[0].xValue, visiblePoints[0].yValue, xAxis, yAxis, isInverted, series);\n direction = direction.concat(startPoint + ' ' + point2.x + ' ' + point2.y + ' ' + 'L' + ' ' + point1.x + ' ' + point1.y);\n }\n }\n var name = series.category === 'Indicator' ? series.chart.element.id + '_Indicator_' + series.index + '_' + series.name :\n series.category === 'TrendLine' ? series.chart.element.id + '_Series_' + series.sourceIndex + '_TrendLine_' + series.index :\n series.chart.element.id + '_Series_' + series.index;\n options = new PathOption(name, 'none', series.width, series.interior, series.opacity, series.dashArray, direction);\n this.appendLinePath(options, series, '');\n this.renderMarker(series);\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n LineSeries.prototype.doAnimation = function (series) {\n var option = series.animation;\n this.doProgressiveAnimation(series, option);\n };\n /**\n * Get module name.\n */\n LineSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'LineSeries';\n };\n /**\n * To destroy the line series.\n * @return {void}\n * @private\n */\n LineSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return LineSeries;\n}(LineBase));\nexport { LineSeries };\n","import { Animation } from '@syncfusion/ej2-base';\nimport { DoubleRange } from '../utils/double-range';\nimport { Rect, valueToCoefficient, getMinPointsDelta, PathOption } from '../../common/utils/helper';\nimport { getAnimationFunction, getPoint } from '../../common/utils/helper';\nimport { pointRender } from '../../common/model/constants';\n/**\n * Column Series Base\n */\nvar ColumnBase = /** @class */ (function () {\n function ColumnBase() {\n }\n /**\n * To get the position of the column series.\n * @return {DoubleRange}\n * @private\n */\n ColumnBase.prototype.getSideBySideInfo = function (series) {\n if (series.chart.enableSideBySidePlacement && !series.position) {\n this.getSideBySidePositions(series);\n }\n var position = !series.chart.enableSideBySidePlacement ? 0 : series.position;\n var rectCount = !series.chart.enableSideBySidePlacement ? 1 : series.rectCount;\n series.isRectSeries = true;\n var visibleSeries = series.chart.visibleSeries;\n var seriesSpacing = series.chart.enableSideBySidePlacement ? series.columnSpacing : 0; // Column Spacing\n var pointSpacing = (series.columnWidth === null) ? ((series.type === 'Histogram') ? 1 : 0.7) :\n series.columnWidth; // Column width\n var minimumPointDelta = getMinPointsDelta(series.xAxis, visibleSeries);\n var width = minimumPointDelta * pointSpacing;\n var radius;\n var location = (position) / rectCount - 0.5;\n var doubleRange = new DoubleRange(location, location + (1 / rectCount));\n if (!(isNaN(doubleRange.start) || isNaN(doubleRange.end))) {\n doubleRange = new DoubleRange(doubleRange.start * width, doubleRange.end * width);\n radius = seriesSpacing * doubleRange.delta;\n doubleRange = new DoubleRange(doubleRange.start + radius / 2, doubleRange.end - radius / 2);\n }\n return doubleRange;\n };\n /**\n * To get the rect values.\n * @return {Rect}\n * @private\n */\n ColumnBase.prototype.getRectangle = function (x1, y1, x2, y2, series) {\n var point1 = getPoint(x1, y1, series.xAxis, series.yAxis, series.chart.requireInvertedAxis);\n var point2 = getPoint(x2, y2, series.xAxis, series.yAxis, series.chart.requireInvertedAxis);\n return new Rect(Math.min(point1.x, point2.x), Math.min(point1.y, point2.y), Math.abs(point2.x - point1.x), Math.abs(point2.y - point1.y));\n };\n /**\n * To get the position of each series.\n * @return {void}\n * @private\n */\n ColumnBase.prototype.getSideBySidePositions = function (series) {\n var chart = series.chart;\n var seriesCollection = [];\n for (var _i = 0, _a = chart.columns; _i < _a.length; _i++) {\n var columnItem = _a[_i];\n for (var _b = 0, _c = chart.rows; _b < _c.length; _b++) {\n var item = _c[_b];\n this.findRectPosition(series.findSeriesCollection(columnItem, item, false));\n }\n }\n };\n ColumnBase.prototype.findRectPosition = function (seriesCollection) {\n var stackingGroup = [];\n var vSeries = { rectCount: 0, position: null };\n seriesCollection.forEach(function (value) {\n if (value.type.indexOf('Stacking') !== -1) {\n if (value.stackingGroup) {\n if (stackingGroup[value.stackingGroup] === undefined) {\n value.position = vSeries.rectCount;\n stackingGroup[value.stackingGroup] = vSeries.rectCount++;\n }\n else {\n value.position = stackingGroup[value.stackingGroup];\n }\n }\n else {\n if (vSeries.position === null) {\n value.position = vSeries.rectCount;\n vSeries.position = vSeries.rectCount++;\n }\n else {\n value.position = vSeries.position;\n }\n }\n }\n else {\n value.position = vSeries.rectCount++;\n }\n });\n seriesCollection.forEach(function (value) {\n value.rectCount = vSeries.rectCount;\n });\n };\n /**\n * Updates the symbollocation for points\n * @return void\n * @private\n */\n ColumnBase.prototype.updateSymbolLocation = function (point, rect, series) {\n if (!series.chart.requireInvertedAxis) {\n this.updateXRegion(point, rect, series);\n }\n else {\n this.updateYRegion(point, rect, series);\n }\n if (series.type === 'Histogram') {\n point.minimum = +point.x - series.histogramValues.binWidth / 2;\n point.maximum = +point.x + series.histogramValues.binWidth / 2;\n }\n };\n /**\n * Update the region for the point.\n * @return {void}\n * @private\n */\n ColumnBase.prototype.updateXRegion = function (point, rect, series) {\n point.regions.push(rect);\n point.symbolLocations.push({\n x: rect.x + (rect.width) / 2,\n y: (series.seriesType === 'BoxPlot' || series.seriesType.indexOf('HighLow') !== -1 ||\n (point.yValue >= 0 === !series.yAxis.isInversed)) ? rect.y : (rect.y + rect.height)\n });\n };\n /**\n * Update the region for the point in bar series.\n * @return {void}\n * @private\n */\n ColumnBase.prototype.updateYRegion = function (point, rect, series) {\n point.regions.push(rect);\n point.symbolLocations.push({\n x: (series.seriesType === 'BoxPlot' || series.seriesType.indexOf('HighLow') !== -1 ||\n (point.yValue >= 0 === !series.yAxis.isInversed)) ? rect.x + rect.width : rect.x,\n y: rect.y + rect.height / 2\n });\n };\n /**\n * To trigger the point rendering event.\n * @return {void}\n * @private\n */\n ColumnBase.prototype.triggerEvent = function (series, point, fill, border) {\n var argsData = {\n cancel: false, name: pointRender, series: series, point: point,\n fill: series.setPointColor(point, fill),\n border: series.setBorderColor(point, border)\n };\n series.chart.trigger(pointRender, argsData);\n point.color = argsData.fill;\n return argsData;\n };\n /**\n * To draw the rectangle for points.\n * @return {void}\n * @private\n */\n ColumnBase.prototype.drawRectangle = function (series, point, rect, argsData) {\n var check = series.chart.requireInvertedAxis ? rect.height : rect.width;\n if (check <= 0) {\n return null;\n }\n var direction = this.calculateRoundedRectPath(rect, series.cornerRadius.topLeft, series.cornerRadius.topRight, series.cornerRadius.bottomLeft, series.cornerRadius.bottomRight);\n var name = series.category === 'Indicator' ? series.chart.element.id + '_Indicator_' + series.index + '_' + series.name +\n '_Point_' + point.index : series.chart.element.id + '_Series_' + series.index + '_Point_' + point.index;\n var options = new PathOption(name, argsData.fill, argsData.border.width, argsData.border.color, series.opacity, series.dashArray, direction);\n var element = series.chart.renderer.drawPath(options);\n switch (series.seriesType) {\n case 'XY':\n element.setAttribute('aria-label', point.x.toString() + ':' + point.yValue.toString());\n break;\n case 'HighLow':\n element.setAttribute('aria-label', point.x.toString() + ':' + point.high.toString() + ':' + point.low.toString());\n break;\n }\n series.seriesElement.appendChild(element);\n };\n /**\n * To animate the series.\n * @return {void}\n * @private\n */\n ColumnBase.prototype.animate = function (series) {\n var rectElements = series.seriesElement.childNodes;\n var count = series.category === 'Indicator' ? 0 : 1;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n if (!point.symbolLocations.length && !(series.type === 'BoxAndWhisker' && point.regions.length)) {\n continue;\n }\n this.animateRect(rectElements[count], series, point);\n count++;\n }\n };\n /**\n * To animate the series.\n * @return {void}\n * @private\n */\n ColumnBase.prototype.animateRect = function (element, series, point) {\n var option = series.animation;\n var effect = getAnimationFunction('Linear');\n var isPlot = point.yValue < 0;\n var x;\n var y;\n var elementHeight = +point.regions[0].height;\n var elementWidth = +point.regions[0].width;\n var centerX;\n var centerY;\n if (!series.chart.requireInvertedAxis) {\n x = +point.regions[0].x;\n if (series.type.indexOf('Stacking') > -1) {\n y = (1 - valueToCoefficient(0, series.yAxis)) * (series.yAxis.rect.height);\n centerX = x;\n centerY = y;\n }\n else {\n y = +point.regions[0].y;\n centerY = (series.seriesType.indexOf('HighLow') !== -1 || series.type.indexOf('Waterfall') !== -1) ? y + elementHeight / 2 :\n (isPlot !== series.yAxis.isInversed) ? y : y + elementHeight;\n centerX = isPlot ? x : x + elementWidth;\n }\n }\n else {\n y = +point.regions[0].y;\n if (series.type.indexOf('Stacking') > -1) {\n x = (valueToCoefficient(0, series.yAxis)) * series.yAxis.rect.width;\n centerX = x;\n centerY = y;\n }\n else {\n x = +point.regions[0].x;\n centerY = isPlot ? y : y + elementHeight;\n centerX = (series.seriesType.indexOf('HighLow') !== -1 || series.type.indexOf('Waterfall') !== -1) ? x + elementWidth / 2 :\n (isPlot !== series.yAxis.isInversed) ? x + elementWidth : x;\n }\n }\n var value;\n element.style.visibility = 'hidden';\n new Animation({}).animate(element, {\n duration: option.duration,\n delay: option.delay,\n progress: function (args) {\n if (args.timeStamp >= args.delay) {\n element.style.visibility = 'visible';\n if (!series.chart.requireInvertedAxis) {\n elementHeight = elementHeight ? elementHeight : 1;\n value = effect(args.timeStamp - args.delay, 0, elementHeight, args.duration);\n element.setAttribute('transform', 'translate(' + centerX + ' ' + centerY +\n ') scale(1,' + (value / elementHeight) + ') translate(' + (-centerX) + ' ' + (-centerY) + ')');\n }\n else {\n elementWidth = elementWidth ? elementWidth : 1;\n value = effect(args.timeStamp - args.delay, 0, elementWidth, args.duration);\n element.setAttribute('transform', 'translate(' + centerX + ' ' + centerY +\n ') scale(' + (value / elementWidth) + ', 1) translate(' + (-centerX) + ' ' + (-centerY) + ')');\n }\n }\n },\n end: function (model) {\n element.setAttribute('transform', 'translate(0,0)');\n var seriesElement = series.seriesElement;\n if (element === seriesElement.lastElementChild || point.index === series.points.length - 1 ||\n (series.type === 'Waterfall' && element === seriesElement.children[seriesElement.childElementCount - 2])) {\n series.chart.trigger('animationComplete', { series: series });\n if (series.type === 'Waterfall') {\n var rectElements = seriesElement.childNodes;\n for (var i = 0; i < rectElements.length; i++) {\n if (rectElements[i].id.indexOf('Connector') !== -1) {\n rectElements[i].style.visibility = 'visible';\n rectElements[i].setAttribute('transform', 'translate(0,0)');\n }\n }\n }\n }\n }\n });\n };\n /**\n * To get rounded rect path direction\n */\n ColumnBase.prototype.calculateRoundedRectPath = function (rect, topLeft, topRight, bottomLeft, bottomRight) {\n return 'M' + ' ' + rect.x + ' ' + (topLeft + rect.y) +\n ' Q ' + rect.x + ' ' + rect.y + ' ' + (rect.x + topLeft) + ' ' +\n rect.y + ' ' + 'L' + ' ' + (rect.x + rect.width - topRight) + ' ' + rect.y +\n ' Q ' + (rect.x + rect.width) + ' ' + rect.y + ' ' +\n (rect.x + rect.width) + ' ' + (rect.y + topRight) + ' ' + 'L ' +\n (rect.x + rect.width) + ' ' + (rect.y + rect.height - bottomRight)\n + ' Q ' + (rect.x + rect.width) + ' ' + (rect.y + rect.height) + ' ' + (rect.x + rect.width - bottomRight) + ' ' +\n (rect.y + rect.height) + ' ' + 'L ' + (rect.x + bottomLeft) + ' ' + (rect.y + rect.height) + ' Q ' + rect.x + ' ' +\n (rect.y + rect.height) + ' ' + rect.x + ' ' + (rect.y + rect.height - bottomLeft) + ' ' + 'L' + ' ' + rect.x + ' ' +\n (topLeft + rect.y) + ' ' + 'Z';\n };\n return ColumnBase;\n}());\nexport { ColumnBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `ColumnSeries` Module used to render the column series.\n */\nvar ColumnSeries = /** @class */ (function (_super) {\n __extends(ColumnSeries, _super);\n function ColumnSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Column series.\n * @return {void}\n * @private\n */\n ColumnSeries.prototype.render = function (series) {\n var rect;\n var sideBySideInfo = this.getSideBySideInfo(series);\n var origin = Math.max(series.yAxis.visibleRange.min, 0);\n var argsData;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var pointColumn = _a[_i];\n pointColumn.symbolLocations = [];\n pointColumn.regions = [];\n if (pointColumn.visible && withInRange(series.points[pointColumn.index - 1], pointColumn, series.points[pointColumn.index + 1], series)) {\n rect = this.getRectangle(pointColumn.xValue + sideBySideInfo.start, pointColumn.yValue, pointColumn.xValue + sideBySideInfo.end, origin, series);\n var color = series.category === 'Indicator' ? pointColumn.color : series.interior;\n argsData = this.triggerEvent(series, pointColumn, color, { width: series.border.width, color: series.border.color });\n if (!argsData.cancel) {\n this.updateSymbolLocation(pointColumn, rect, series);\n this.drawRectangle(series, pointColumn, rect, argsData);\n }\n }\n }\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n ColumnSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * Get module name.\n */\n ColumnSeries.prototype.getModuleName = function () {\n return 'ColumnSeries';\n /**\n * return the module name\n */\n };\n /**\n * To destroy the column series.\n * @return {void}\n * @private\n */\n ColumnSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return ColumnSeries;\n}(ColumnBase));\nexport { ColumnSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { getPoint } from '../../common/utils/helper';\nimport { LineBase } from './line-base';\nimport { RectOption } from '../../common/utils/helper';\nimport { DataUtil } from '@syncfusion/ej2-data';\n/**\n * Base class for multi colored series\n */\nvar MultiColoredSeries = /** @class */ (function (_super) {\n __extends(MultiColoredSeries, _super);\n function MultiColoredSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * To Generate the area path direction\n * @param xValue\n * @param yValue\n * @param series\n * @param isInverted\n * @param getPointLocation\n * @param startPoint\n * @param startPath\n */\n MultiColoredSeries.prototype.getAreaPathDirection = function (xValue, yValue, series, isInverted, getPointLocation, startPoint, startPath) {\n var direction = '';\n var firstPoint;\n if (startPoint === null) {\n firstPoint = getPointLocation(xValue, yValue, series.xAxis, series.yAxis, isInverted, series);\n direction += (startPath + ' ' + (firstPoint.x) + ' ' + (firstPoint.y) + ' ');\n }\n return direction;\n };\n /**\n * To Generate the empty point direction\n * @param firstPoint\n * @param secondPoint\n * @param series\n * @param isInverted\n * @param getPointLocation\n */\n MultiColoredSeries.prototype.getAreaEmptyDirection = function (firstPoint, secondPoint, series, isInverted, getPointLocation) {\n var direction = '';\n direction += this.getAreaPathDirection(firstPoint.x, firstPoint.y, series, isInverted, getPointLocation, null, 'L');\n direction += this.getAreaPathDirection(secondPoint.x, secondPoint.y, series, isInverted, getPointLocation, null, 'L');\n return direction;\n };\n /**\n * To set point color\n * @param points\n */\n MultiColoredSeries.prototype.setPointColor = function (currentPoint, previous, series, isXSegment, segments) {\n if (series.pointColorMapping === '') {\n var segment = void 0;\n var value = void 0;\n for (var i = 0; i < segments.length; i++) {\n segment = segments[i];\n value = isXSegment ? currentPoint.xValue : currentPoint.yValue;\n if (value <= this.getAxisValue(segment.value, isXSegment ? series.xAxis : series.yAxis, series.chart) || !segment.value) {\n currentPoint.interior = segment.color;\n break;\n }\n }\n if (currentPoint.interior == null) {\n currentPoint.interior = series.interior;\n }\n return false;\n }\n else {\n if (previous) {\n return series.setPointColor(currentPoint, series.interior) !== series.setPointColor(previous, series.interior);\n }\n else {\n return false;\n }\n }\n };\n MultiColoredSeries.prototype.sortSegments = function (series, chartSegments) {\n var axis = series.segmentAxis === 'X' ? series.xAxis : series.yAxis;\n var segments = [].concat(chartSegments);\n var access = this;\n return segments.sort(function (a, b) {\n return access.getAxisValue(a.value, axis, series.chart) - access.getAxisValue(b.value, axis, series.chart);\n });\n };\n /**\n * Segment calculation performed here\n * @param series\n * @param options\n * @param chartSegments\n */\n MultiColoredSeries.prototype.applySegmentAxis = function (series, options, segments) {\n var _this = this;\n if (series.pointColorMapping !== '') {\n options.map(function (option) {\n _this.appendLinePath(option, series, '');\n });\n return null;\n }\n var isXSegment = series.segmentAxis === 'X';\n var axis = isXSegment ? series.xAxis : series.yAxis;\n var chart = series.chart;\n var segment;\n this.includeSegment(segments, axis, series, segments.length);\n var length = segments.length;\n var value;\n var clipPath;\n var _loop_1 = function (index) {\n segment = segments[index];\n value = this_1.getAxisValue(segment.value, axis, series.chart);\n clipPath = this_1.createClipRect(index ? this_1.getAxisValue(segments[index - 1].value, axis, series.chart)\n : axis.visibleRange.min, value, series, index, isXSegment);\n if (clipPath) {\n options.map(function (option) {\n series.seriesElement.appendChild(chart.renderer.drawPath({\n 'clip-path': clipPath,\n 'stroke-dasharray': segment.dashArray,\n 'opacity': option.opacity,\n 'stroke': series.type.indexOf('Line') > -1 ? segment.color || series.interior : series.border.color,\n 'stroke-width': option['stroke-width'],\n 'fill': series.type.indexOf('Line') > -1 ? 'none' : segment.color || series.interior,\n 'id': option.id + '_Segment_' + index,\n 'd': option.d\n }));\n });\n }\n };\n var this_1 = this;\n for (var index = 0; index < length; index++) {\n _loop_1(index);\n }\n };\n MultiColoredSeries.prototype.includeSegment = function (segments, axis, series, length) {\n if (length <= 0) {\n segments.push({ value: axis.visibleRange.max, color: series.interior });\n return null;\n }\n if (this.getAxisValue(segments[length - 1].value, axis, series.chart) < axis.visibleRange.max) {\n segments.push({ value: axis.visibleRange.max, color: series.interior });\n }\n };\n /**\n * To create clip rect for segment axis\n * @param startValue\n * @param endValue\n * @param series\n * @param index\n * @param isX\n * @param chart\n */\n MultiColoredSeries.prototype.createClipRect = function (startValue, endValue, series, index, isX) {\n var isRequired = series.chart.requireInvertedAxis;\n var startPointLocation = getPoint(isX ? startValue : series.xAxis.visibleRange.min, isX ? series.yAxis.visibleRange.max : endValue, series.xAxis, series.yAxis, isRequired);\n var endPointLocation = getPoint(isX ? endValue : series.xAxis.visibleRange.max, isX ? series.yAxis.visibleRange.min : startValue, series.xAxis, series.yAxis, isRequired);\n endPointLocation = isRequired ?\n [startPointLocation, startPointLocation = endPointLocation][0] : endPointLocation;\n if ((endPointLocation.x - startPointLocation.x > 0) && (endPointLocation.y - startPointLocation.y > 0)) {\n series.seriesElement.appendChild(series.chart.renderer.drawClipPath(new RectOption(series.chart.element.id + '_ChartSegmentClipRect_' + index, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: startPointLocation.x,\n y: startPointLocation.y,\n width: endPointLocation.x - startPointLocation.x,\n height: endPointLocation.y - startPointLocation.y\n })));\n return 'url(#' + series.chart.element.id + '_ChartSegmentClipRect_' + index + ')';\n }\n return null;\n };\n /**\n * To get exact value from segment value\n * @param segmentValue\n * @param axis\n * @param chart\n */\n MultiColoredSeries.prototype.getAxisValue = function (segmentValue, axis, chart) {\n if (segmentValue === null) {\n segmentValue = axis.visibleRange.max;\n }\n if (axis.valueType === 'DateTime') {\n var option = { skeleton: 'full', type: 'dateTime' };\n return Date.parse(chart.intl.getDateParser(option)(chart.intl.getDateFormat(option)(new Date(DataUtil.parse.parseJson({ val: segmentValue }).val))));\n }\n else if (axis.valueType.indexOf('Category') > -1) {\n var xValue = axis.valueType === 'DateTimeCategory' ?\n (segmentValue.getTime()).toString() :\n segmentValue;\n return (axis.labels.indexOf(xValue) < 0) ? +segmentValue : axis.labels.indexOf(xValue);\n }\n else {\n return +segmentValue;\n }\n };\n return MultiColoredSeries;\n}(LineBase));\nexport { MultiColoredSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { getPoint, withInRange, ChartLocation, PathOption, TransformToVisible } from '../../common/utils/helper';\nimport { MultiColoredSeries } from './multi-colored-base';\n/**\n * `AreaSeries` module is used to render the area series.\n */\nvar AreaSeries = /** @class */ (function (_super) {\n __extends(AreaSeries, _super);\n function AreaSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Area series.\n * @return {void}\n * @private\n */\n AreaSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var _this = this;\n var startPoint = null;\n var direction = '';\n var origin = series.chart.chartAreaType === 'PolarRadar' ? series.points[0].yValue :\n Math.max(series.yAxis.visibleRange.min, 0);\n var currentXValue;\n var isDropMode = (series.emptyPointSettings && series.emptyPointSettings.mode === 'Drop');\n var borderWidth = series.border ? series.border.width : 0;\n var borderColor = series.border ? series.border.color : 'transparent';\n var getCoordinate = series.chart.chartAreaType === 'PolarRadar' ? TransformToVisible : getPoint;\n series.points.map(function (point, i, seriesPoints) {\n currentXValue = point.xValue;\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(seriesPoints[i - 1], point, seriesPoints[i + 1], series)) {\n direction += _this.getAreaPathDirection(currentXValue, origin, series, isInverted, getCoordinate, startPoint, 'M');\n startPoint = startPoint || new ChartLocation(currentXValue, origin);\n // First Point to draw the area path\n direction += _this.getAreaPathDirection(currentXValue, point.yValue, series, isInverted, getCoordinate, null, 'L');\n if (seriesPoints[i + 1] && !seriesPoints[i + 1].visible && !isDropMode) {\n direction += _this.getAreaEmptyDirection({ 'x': currentXValue, 'y': origin }, startPoint, series, isInverted, getCoordinate);\n startPoint = null;\n }\n _this.storePointLocation(point, series, isInverted, getCoordinate);\n }\n });\n this.appendLinePath(new PathOption(series.chart.element.id + '_Series_' + series.index, series.interior, borderWidth, borderColor, series.opacity, series.dashArray, (series.points.length > 1 ? (direction + this.getAreaPathDirection(series.points[series.points.length - 1].xValue, series.chart.chartAreaType === 'PolarRadar' ?\n series.points[series.points.length - 1].yValue : origin, series, isInverted, getCoordinate, null, 'L')) : '')), series, '');\n this.renderMarker(series);\n };\n /**\n * To destroy the area series.\n * @return {void}\n * @private\n */\n AreaSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n /**\n * Get module name\n */\n AreaSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'AreaSeries';\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n AreaSeries.prototype.doAnimation = function (series) {\n var option = series.animation;\n this.doLinearAnimation(series, option);\n };\n return AreaSeries;\n}(MultiColoredSeries));\nexport { AreaSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `BarSeries` module is used to render the bar series.\n */\nvar BarSeries = /** @class */ (function (_super) {\n __extends(BarSeries, _super);\n function BarSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Bar series.\n * @return {void}\n * @private\n */\n BarSeries.prototype.render = function (series) {\n var origin = Math.max(series.yAxis.visibleRange.min, 0);\n var sideBySideInfo = this.getSideBySideInfo(series);\n var rect;\n var argsData;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var pointBar = _a[_i];\n pointBar.symbolLocations = [];\n pointBar.regions = [];\n if (pointBar.visible && withInRange(series.points[pointBar.index - 1], pointBar, series.points[pointBar.index + 1], series)) {\n rect = this.getRectangle(pointBar.xValue + sideBySideInfo.start, pointBar.yValue, pointBar.xValue + sideBySideInfo.end, origin, series);\n argsData = this.triggerEvent(series, pointBar, series.interior, { width: series.border.width, color: series.border.color });\n if (!argsData.cancel) {\n this.updateSymbolLocation(pointBar, rect, series);\n this.drawRectangle(series, pointBar, rect, argsData);\n }\n }\n }\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n BarSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * To destroy the bar series.\n * @return {void}\n * @private\n */\n BarSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name\n */\n BarSeries.prototype.getModuleName = function () {\n return 'BarSeries';\n };\n return BarSeries;\n}(ColumnBase));\nexport { BarSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { valueToCoefficient, TextOption, inside, measureText } from '../../common/utils/helper';\nimport { Size, Rect, PathOption, CircleOption } from '../../common/utils/helper';\nimport { LineBase } from '../series/line-base';\nimport { textElement, valueToPolarCoefficient, CoefficientToVector } from '../../common/utils/helper';\n/**\n * Specifies the Polar Axis Layout.\n */\nvar axisPadding = 10;\nvar PolarRadarPanel = /** @class */ (function (_super) {\n __extends(PolarRadarPanel, _super);\n function PolarRadarPanel() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Measure the polar radar axis size.\n * @return {void}\n * @private\n */\n PolarRadarPanel.prototype.measureAxis = function (rect) {\n var chart = this.chart;\n this.initialClipRect = rect;\n this.seriesClipRect = new Rect(rect.x, rect.y, rect.width, rect.height);\n //Measure axis size calculation\n this.measureRowAxis(chart, this.initialClipRect);\n this.measureColumnAxis(chart, this.initialClipRect);\n this.calculateAxisSize();\n };\n PolarRadarPanel.prototype.measureRowAxis = function (chart, rect) {\n this.calculateRowSize(rect);\n var row = chart.rows[0];\n this.measureDefinition(row, chart, new Size(chart.availableSize.width, row.computedHeight), rect);\n };\n PolarRadarPanel.prototype.measureColumnAxis = function (chart, rect) {\n this.calculateColumnSize(rect);\n var column = chart.columns[0];\n this.measureDefinition(column, chart, new Size(column.computedWidth, chart.availableSize.height), rect);\n };\n /**\n * Measure the column and row in chart.\n * @return {void}\n * @private\n */\n PolarRadarPanel.prototype.measureDefinition = function (definition, chart, size, clipRect) {\n for (var _i = 0, _a = definition.axes; _i < _a.length; _i++) {\n var axis = _a[_i];\n axis.getModule(chart);\n axis.baseModule.calculateRangeAndInterval(size, axis);\n }\n };\n /**\n * Measure the axis.\n * @return {void}\n * @private\n */\n PolarRadarPanel.prototype.calculateAxisSize = function () {\n var chart = this.chart;\n var axis;\n var padding = 5;\n this.centerX = this.initialClipRect.width * 0.5 + this.initialClipRect.x;\n this.centerY = this.initialClipRect.height * 0.5 + this.initialClipRect.y;\n chart.radius = Math.min(this.initialClipRect.width, this.initialClipRect.height) / 2 - padding -\n chart.primaryXAxis.majorTickLines.height - chart.primaryXAxis.maxLabelSize.height;\n chart.radius = (chart.primaryXAxis.coefficient * chart.radius) / 100;\n this.seriesClipRect.y = this.centerY - chart.radius;\n this.seriesClipRect.x = this.centerX - chart.radius;\n this.seriesClipRect.height = 2 * chart.radius;\n this.seriesClipRect.width = 2 * chart.radius;\n this.calculateRowSize(this.seriesClipRect);\n axis = chart.primaryYAxis;\n axis.rect = this.seriesClipRect;\n this.calculateColumnSize(this.seriesClipRect);\n axis = chart.primaryXAxis;\n axis.rect = this.seriesClipRect;\n };\n /**\n * Measure the axis.\n * @return {void}\n * @private\n */\n PolarRadarPanel.prototype.measure = function () {\n var chart = this.chart;\n chart.verticalAxes.push(chart.primaryYAxis);\n var row = chart.rows[0];\n row.axes[0] = chart.primaryYAxis;\n chart.rows[0] = row;\n chart.horizontalAxes.push(chart.primaryXAxis);\n var column = chart.columns[0];\n column.axes[0] = chart.primaryXAxis;\n chart.columns[0] = column;\n };\n /**\n * Measure the row size.\n * @return {void}\n */\n PolarRadarPanel.prototype.calculateRowSize = function (rect) {\n /*! Calculate row size */\n var chart = this.chart;\n var row = chart.rows[0];\n row.computedHeight = rect.height / 2;\n row.computedTop = rect.y;\n chart.rows[0] = row;\n };\n /**\n * Measure the row size.\n * @return {void}\n */\n PolarRadarPanel.prototype.calculateColumnSize = function (rect) {\n /*! Calculate column size */\n var chart = this.chart;\n var column = chart.columns[0];\n column.computedLeft = rect.x;\n column.computedWidth = rect.width;\n chart.columns[0] = column;\n };\n /**\n * To render the axis element.\n * @return {void}\n * @private\n */\n PolarRadarPanel.prototype.renderAxes = function () {\n var axis;\n var chart = this.chart;\n this.startAngle = chart.primaryXAxis.startAngle;\n var axisElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisCollection' });\n var axisLineElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisOutsideCollection' });\n for (var i = 0, len = chart.axisCollections.length; i < len; i++) {\n this.element = chart.renderer.createGroup({ id: chart.element.id + 'AxisGroup' + i });\n axis = chart.axisCollections[i];\n if (axis.orientation === 'Horizontal') {\n if (axis.majorGridLines.width > 0 || axis.majorTickLines.width > 0) {\n this.drawXAxisGridLine(axis, i);\n }\n if (axis.visible) {\n this.drawXAxisLabels(axis, i);\n }\n }\n else {\n this.drawYAxisGridLine(axis, i);\n if (axis.lineStyle.width > 0) {\n this.drawYAxisLine(axis, i, axis.plotOffset, 0);\n }\n if (axis.visible) {\n this.drawYAxisLabels(axis, i);\n }\n }\n axisElement.appendChild(this.element);\n }\n axisElement.appendChild(this.element);\n chart.svgObject.appendChild(axisElement);\n return axisLineElement;\n };\n PolarRadarPanel.prototype.drawYAxisLine = function (axis, index, plotX, plotY) {\n var chart = this.chart;\n var optionsLine = {};\n var vector = CoefficientToVector(valueToPolarCoefficient(axis.visibleLabels[0].value, axis), this.startAngle);\n var axisLine = 'M ' + this.centerX + ' ' + this.centerY + 'L ' +\n (this.centerX + chart.radius * vector.x) + ' ' + (this.centerY + chart.radius * vector.y);\n optionsLine = {\n 'id': chart.element.id + 'AxisLine_' + index,\n 'd': axisLine,\n 'stroke-dasharray': axis.lineStyle.dashArray,\n 'stroke-width': axis.lineStyle.width,\n 'stroke': axis.lineStyle.color || chart.themeStyle.axisLine\n };\n chart.yAxisElements.appendChild(chart.renderer.drawPath(optionsLine));\n };\n PolarRadarPanel.prototype.drawYAxisLabels = function (axis, index) {\n var chart = this.chart;\n var elementSize;\n var options;\n var pointX = 0;\n var pointY = 0;\n var vector;\n var angle = this.startAngle < 0 ? this.startAngle + 360 : this.startAngle;\n var anchor = 'middle';\n var radius;\n var padding = 5;\n var labelElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisLabels' + index });\n vector = CoefficientToVector(valueToPolarCoefficient(axis.visibleLabels[0].value, axis), this.startAngle);\n for (var i = 0, len = axis.visibleLabels.length; i < len; i++) {\n radius = chart.radius * valueToCoefficient(axis.visibleLabels[i].value, axis);\n elementSize = axis.visibleLabels[i].size;\n radius = chart.radius * valueToCoefficient(axis.visibleLabels[i].value, axis);\n pointX = (this.centerX + radius * vector.x) + ((axis.majorTickLines.height + elementSize.width / 2 + padding / 2)\n * (Math.cos(angle * Math.PI / 180)) * (axis.labelPosition === 'Inside' ? 1 : -1));\n pointY = (this.centerY + radius * vector.y) + ((axis.majorTickLines.height + elementSize.height / 2)\n * (Math.sin(angle * Math.PI / 180)) * (axis.labelPosition === 'Inside' ? 1 : -1));\n options = new TextOption(chart.element.id + index + '_AxisLabel_' + i, pointX, pointY + (elementSize.height / 4), anchor, axis.visibleLabels[i].text);\n textElement(options, axis.labelStyle, axis.labelStyle.color || chart.themeStyle.axisLabel, labelElement);\n }\n chart.yAxisElements.appendChild(labelElement);\n };\n PolarRadarPanel.prototype.drawYAxisGridLine = function (axis, index) {\n var chart = this.chart;\n var options;\n var radius;\n var majorTick = '';\n var majorGrid = '';\n var vector;\n var vector2;\n var angle = this.startAngle < 0 ? this.startAngle + 360 : this.startAngle;\n var rect = axis.rect;\n var x1;\n var y1;\n var x2;\n var y2;\n var border = {\n color: axis.majorGridLines.color || chart.themeStyle.majorGridLine,\n width: axis.majorGridLines.width\n };\n if (axis.majorGridLines.width > 0) {\n if (chart.visibleSeries[0].type === 'Polar') {\n for (var j = 0; j < axis.visibleLabels.length; j++) {\n radius = chart.radius * valueToCoefficient(axis.visibleLabels[j].value, axis);\n options = new CircleOption(chart.element.id + '_MajorGridLine_' + index, 'transparent', border, axis.majorGridLines.width, this.centerX, this.centerY, radius);\n this.element.appendChild(chart.renderer.drawCircle(options));\n }\n }\n else {\n for (var j = 0; j < axis.visibleLabels.length; j++) {\n radius = chart.radius * valueToCoefficient(axis.visibleLabels[j].value, axis);\n for (var i = 0, len = chart.primaryXAxis.visibleLabels.length; i < len; i++) {\n vector = CoefficientToVector(valueToPolarCoefficient(chart.primaryXAxis.visibleLabels[i].value, chart.primaryXAxis), this.startAngle);\n if (i + 1 < len) {\n vector2 = CoefficientToVector(valueToPolarCoefficient(chart.primaryXAxis.visibleLabels[i + 1].value, chart.primaryXAxis), this.startAngle);\n }\n else {\n vector2 = CoefficientToVector(valueToPolarCoefficient(chart.primaryXAxis.visibleLabels[0].value, chart.primaryXAxis), this.startAngle);\n }\n x1 = this.centerX + radius * vector.x;\n y1 = this.centerY + radius * vector.y;\n x2 = this.centerX + radius * vector2.x;\n y2 = this.centerY + radius * vector2.y;\n majorGrid = majorGrid.concat('M' + ' ' + x1 + ' ' + y1 + ' ' + 'L' + ' ' + x2 + ' ' + y2 + ' ');\n }\n }\n options = new PathOption(chart.element.id + '_MajorGridLine_' + index, 'transparent', axis.majorGridLines.width, axis.majorGridLines.color || chart.themeStyle.majorGridLine, null, null, majorGrid);\n this.element.appendChild(chart.renderer.drawPath(options));\n }\n }\n if (axis.majorTickLines.width > 0) {\n vector = CoefficientToVector(valueToPolarCoefficient(axis.visibleLabels[0].value, axis), this.startAngle);\n for (var i = 0; i < axis.visibleLabels.length; i++) {\n radius = chart.radius * valueToCoefficient(axis.visibleLabels[i].value, axis);\n x1 = this.centerX + radius * vector.x;\n y1 = this.centerY + radius * vector.y;\n x2 = x1 + (axis.majorTickLines.height * (Math.cos(angle * Math.PI / 180)) * (axis.tickPosition === 'Inside' ? 1 : -1));\n y2 = y1 + (axis.majorTickLines.height * (Math.sin(angle * Math.PI / 180)) * (axis.tickPosition === 'Inside' ? 1 : -1));\n majorTick = majorTick.concat('M ' + x1 + ' ' + y1 +\n ' L ' + x2 + ' ' + y2 + ' ');\n }\n }\n this.renderTickLine(axis, index, majorTick, '');\n };\n PolarRadarPanel.prototype.drawXAxisGridLine = function (axis, index) {\n var chart = this.chart;\n var tempInterval;\n var vector;\n var majorGrid = '';\n var majorTick = '';\n var minorGirdLine = '';\n var minorTickLine = '';\n var x1 = this.centerX;\n var x2;\n var y1 = this.centerY;\n var y2;\n var minorDirection;\n var tickSize = axis.majorTickLines.height;\n var rect = axis.rect;\n var length = axis.visibleLabels.length;\n //Gridlines\n for (var i = 0; i < length; i++) {\n tempInterval = axis.visibleLabels[i].value;\n vector = CoefficientToVector(valueToPolarCoefficient(axis.visibleLabels[i].value, axis), this.startAngle);\n x2 = this.centerX + chart.radius * vector.x;\n y2 = this.centerY + chart.radius * vector.y;\n var xLoc = x2 + (axis.majorTickLines.height * vector.x * (axis.tickPosition === 'Inside' ? -1 : 1));\n var yLoc = y2 + (axis.majorTickLines.height * vector.y * (axis.tickPosition === 'Inside' ? -1 : 1));\n majorGrid = majorGrid.concat('M ' + x1 + ' ' + y1 + ' ' + 'L' + x2 + ' ' + y2);\n majorTick = majorTick.concat('M ' + x2 + ' ' + y2 +\n ' L ' + xLoc + ' ' + yLoc + ' ');\n if (axis.minorTicksPerInterval > 0 && (axis.minorGridLines.width > 0 || axis.minorTickLines.width > 0)\n && axis.valueType !== 'Category' && chart.visibleSeries[0].type !== 'Radar') {\n minorDirection = this.drawAxisMinorLine(axis, tempInterval, minorGirdLine, minorTickLine);\n minorGirdLine = minorDirection[0];\n minorTickLine = minorDirection[1];\n }\n }\n this.renderTickLine(axis, index, majorTick, minorTickLine);\n this.renderGridLine(axis, index, majorGrid, minorGirdLine);\n };\n PolarRadarPanel.prototype.drawAxisMinorLine = function (axis, tempInterval, minorGird, minorTick) {\n var value = tempInterval;\n var x;\n var y;\n var vector;\n var range = axis.visibleRange;\n var direction = [];\n var tickSize = axis.minorTickLines.height;\n var rect = axis.rect;\n for (var j = 0; j < axis.minorTicksPerInterval; j++) {\n value += (axis.valueType === 'DateTime' ? axis.dateTimeInterval : axis.visibleRange.interval) /\n (axis.minorTicksPerInterval + 1);\n if (inside(value, range)) {\n vector = CoefficientToVector(valueToPolarCoefficient(value, axis), this.startAngle);\n x = this.centerX + this.chart.radius * vector.x;\n y = this.centerY + this.chart.radius * vector.y;\n var tickXSize = x + (axis.minorTickLines.height * vector.x * (axis.tickPosition === 'Inside' ? -1 : 1));\n var tickYSize = y + (axis.minorTickLines.height * vector.y * (axis.tickPosition === 'Inside' ? -1 : 1));\n minorGird = minorGird.concat('M' + ' ' + this.centerX + ' ' + this.centerY\n + 'L ' + x + ' ' + y);\n minorTick = minorTick.concat('M' + ' ' + x + ' ' + y + 'L' + ' ' + (tickXSize) + ' ' +\n (tickYSize));\n }\n }\n direction.push(minorGird);\n direction.push(minorTick);\n return direction;\n };\n /**\n * To render the axis label.\n * @return {void}\n * @private\n */\n PolarRadarPanel.prototype.drawXAxisLabels = function (axis, index) {\n var chart = this.chart;\n var pointX = 0;\n var elementSize;\n var pointY = 0;\n var labelElement = chart.renderer.createGroup({ id: chart.element.id + 'AxisLabels' + index });\n var options;\n var vector;\n var labelText;\n var firstLabelX;\n var islabelInside = axis.labelPosition === 'Inside';\n var padding = 5;\n var lastLabelX;\n var textAnchor = '';\n var ticksbwtLabel = axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks'\n && chart.visibleSeries[0].type !== 'Radar' ? 0.5 : 0;\n var radius = chart.radius + axis.majorTickLines.height;\n radius = (islabelInside) ? -radius : radius;\n for (var i = 0, len = axis.visibleLabels.length; i < len; i++) {\n vector = CoefficientToVector(valueToPolarCoefficient(axis.visibleLabels[i].value + ticksbwtLabel, axis), this.startAngle);\n if (!isNaN(vector.x) && !isNaN(vector.y)) {\n pointX = this.centerX + (radius + axis.majorTickLines.height + padding) * vector.x;\n pointY = this.centerY + (radius + axis.majorTickLines.height + padding) * vector.y;\n textAnchor = parseFloat(pointX.toFixed(1)) === parseFloat(this.centerX.toFixed(1)) ? 'middle' :\n ((pointX < this.centerX && !islabelInside) || (pointX > this.centerX && islabelInside)) ? 'end' : 'start';\n }\n labelText = axis.visibleLabels[i].text;\n if (i === 0) {\n firstLabelX = pointX;\n }\n else if (i === axis.visibleLabels.length - 1 && axis.valueType !== 'Category') {\n lastLabelX = measureText(labelText, axis.labelStyle).height;\n lastLabelX += pointX;\n labelText = (lastLabelX > firstLabelX) ? '' : labelText;\n }\n options = new TextOption(chart.element.id + index + '_AxisLabel_' + i, pointX, pointY, textAnchor, labelText, '', 'central');\n textElement(options, axis.labelStyle, axis.labelStyle.color || chart.themeStyle.axisLabel, labelElement);\n }\n this.element.appendChild(labelElement);\n };\n PolarRadarPanel.prototype.renderTickLine = function (axis, index, majorTickLine, minorTickLine) {\n var tickOptions;\n var chart = this.chart;\n if (axis.majorTickLines.width > 0) {\n tickOptions = new PathOption(chart.element.id + '_MajorTickLine_' + index, 'transparent', axis.majorTickLines.width, axis.majorTickLines.color || chart.themeStyle.majorTickLine, null, null, majorTickLine);\n chart.yAxisElements.appendChild(chart.renderer.drawPath(tickOptions));\n }\n if (axis.minorTickLines.width > 0) {\n tickOptions = new PathOption(chart.element.id + '_MinorTickLine_' + index, 'transparent', axis.minorTickLines.width, axis.minorTickLines.color || chart.themeStyle.minorTickLine, null, null, minorTickLine);\n chart.yAxisElements.appendChild(chart.renderer.drawPath(tickOptions));\n }\n };\n PolarRadarPanel.prototype.renderGridLine = function (axis, index, majorGrid, minorGird) {\n var chart = this.chart;\n var gridOptions;\n if (axis.majorGridLines.width > 0) {\n gridOptions = new PathOption(chart.element.id + '_MajorGridLine_' + index, 'transparent', axis.majorGridLines.width, axis.majorGridLines.color || chart.themeStyle.majorGridLine, null, axis.majorGridLines.dashArray, majorGrid);\n this.element.appendChild(chart.renderer.drawPath(gridOptions));\n }\n if (axis.minorGridLines.width > 0) {\n gridOptions = new PathOption(chart.element.id + '_MinorGridLine_' + index, 'transparent', axis.minorGridLines.width, axis.minorGridLines.color || chart.themeStyle.minorGridLine, null, axis.minorGridLines.dashArray, minorGird);\n this.element.appendChild(chart.renderer.drawPath(gridOptions));\n }\n };\n return PolarRadarPanel;\n}(LineBase));\nexport { PolarRadarPanel };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange, PathOption, logBase, markerAnimate, PolarArc, valueToCoefficient, firstToLowerCase } from '../../common/utils/helper';\nimport { PolarRadarPanel } from '../axis/polar-radar-panel';\nimport { pointRender } from '../../common/model/constants';\nimport { Animation } from '@syncfusion/ej2-base';\n/**\n * `PolarSeries` module is used to render the polar series.\n */\nvar PolarSeries = /** @class */ (function (_super) {\n __extends(PolarSeries, _super);\n function PolarSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Polar Series.\n * @return {void}.\n * @private\n */\n PolarSeries.prototype.render = function (series) {\n var seriesType = firstToLowerCase(series.drawType);\n if (series.drawType.indexOf('Column') > -1) {\n this.columnDrawTypeRender(series);\n }\n else {\n series.chart[seriesType + 'SeriesModule'].render(series, series.xAxis, series.yAxis, series.chart.requireInvertedAxis);\n }\n };\n /**\n * Render Column DrawType.\n * @return {void}.\n * @private\n */\n PolarSeries.prototype.columnDrawTypeRender = function (series) {\n var visiblePoints = series.points;\n var rect;\n var options;\n var argsData;\n var startAngle;\n var endAngle;\n var itemCurrentXPos;\n var radius;\n var pointStartAngle;\n var pointEndAngle;\n var x1;\n var x2;\n var y1;\n var y2;\n var startValue;\n var endValue;\n var innerRadius;\n var centerX = (series.clipRect.width / 2) + series.clipRect.x;\n var dStartX;\n var dStartY;\n var centerY = (series.clipRect.height / 2) + series.clipRect.y;\n var dEndX;\n var dEndY;\n var axisInversed = series.xAxis.isInversed ? 1 : 0;\n var direction = '';\n var sumofYValues = 0;\n var interval = (series.points[1] ? series.points[1].xValue : 2 * series.points[0].xValue) - series.points[0].xValue;\n var ticks = series.xAxis.valueType === 'Category' && series.xAxis.labelPlacement === 'BetweenTicks' ? 0 : interval / 2;\n var rangeInterval = series.xAxis.valueType === 'DateTime' ? series.xAxis.dateTimeInterval : 1;\n var min = series.xAxis.actualRange.min;\n var inversedValue;\n this.getSeriesPosition(series);\n var position = series.xAxis.isInversed ? (series.rectCount - 1 - series.position) : series.position;\n var ticksbwtLabel = series.xAxis.valueType === 'Category' && series.xAxis.labelPlacement === 'BetweenTicks' ? 0.5\n : 0.5 - (series.rectCount / 2);\n do {\n sumofYValues += rangeInterval;\n min += rangeInterval;\n } while (min <= series.xAxis.actualRange.max - (series.xAxis.valueType === 'Category' ? 0 : 1));\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(series.points[point.index - 1], point, series.points[point.index + 1], series)) {\n inversedValue = series.xAxis.isInversed ? (series.xAxis.visibleRange.max - point.xValue) :\n point.xValue - series.xAxis.visibleRange.min;\n itemCurrentXPos = (inversedValue) +\n ((interval / series.rectCount) * position - ticks) + (sumofYValues / 360 * series.xAxis.startAngle);\n itemCurrentXPos = (((itemCurrentXPos) / (sumofYValues)));\n startAngle = 2 * Math.PI * (itemCurrentXPos + series.xAxis.startAngle);\n endAngle = 2 * Math.PI * ((itemCurrentXPos + series.xAxis.startAngle) + (interval / series.rectCount) / (sumofYValues));\n pointStartAngle = startAngle;\n pointEndAngle = endAngle;\n startAngle = (startAngle - 0.5 * Math.PI);\n endAngle = (endAngle - 0.5 * Math.PI) - 0.000001;\n if (series.drawType === 'StackingColumn' || series.drawType === 'RangeColumn') {\n startValue = series.drawType === 'RangeColumn' ? point.low : series.stackedValues.startValues[point.index];\n endValue = series.drawType === 'RangeColumn' ? point.high : series.stackedValues.endValues[point.index];\n endValue = (series.yAxis.valueType === 'Logarithmic' ?\n logBase(endValue === 0 ? 1 : endValue, series.yAxis.logBase) : endValue);\n endValue = endValue > series.yAxis.actualRange.max ? series.yAxis.actualRange.max : endValue;\n radius = startValue === endValue ? 0 : series.chart.radius * valueToCoefficient(endValue, series.yAxis);\n x1 = centerX + radius * Math.cos(startAngle);\n x2 = centerX + radius * Math.cos(endAngle);\n y1 = centerY + radius * Math.sin(startAngle);\n y2 = centerY + radius * Math.sin(endAngle);\n innerRadius = series.chart.radius * valueToCoefficient((startValue === 0 && series.yAxis.visibleRange.min !== 0) ? series.yAxis.visibleRange.min : startValue, series.yAxis);\n dStartX = centerX + innerRadius * Math.cos(startAngle);\n dStartY = centerY + innerRadius * Math.sin(startAngle);\n dEndX = centerX + innerRadius * Math.cos(endAngle);\n dEndY = centerY + innerRadius * Math.sin(endAngle);\n if (series.type === 'Polar') {\n direction = ('M' + ' ' + x1 + ' ' + y1 + ' ' + 'A' + ' ' + radius + ' ' + radius + ' ' + '0' + ' '\n + '0' + ' ' + 1 + ' ' + x2 + ' ' + y2 + ' ' + 'L' + ' ' + dEndX + ' ' + dEndY + ' ' +\n 'A' + ' ' + innerRadius + ' ' + innerRadius + ' ' + '1' + ' ' + '0' + ' ' + '0' + ' '\n + dStartX + ' ' + dStartY + ' ' + 'z');\n }\n else {\n direction = ('M' + ' ' + x1 + ' ' + y1 + ' ' + 'L' + ' ' + x2 + ' ' + y2 + ' ' + 'L'\n + dEndX + ' ' + dEndY + ' ' + 'L' + ' ' + dStartX + ' ' + dStartY + ' ' + 'z');\n }\n point.regionData = new PolarArc(pointStartAngle, pointEndAngle, innerRadius, radius, itemCurrentXPos);\n }\n else {\n endValue = point.yValue > series.yAxis.actualRange.max ? series.yAxis.actualRange.max : point.yValue;\n radius = series.chart.radius * valueToCoefficient((series.yAxis.valueType === 'Logarithmic' ? logBase(endValue, series.yAxis.logBase) : endValue), series.yAxis);\n x1 = centerX + radius * Math.cos(startAngle);\n x2 = centerX + radius * Math.cos(endAngle);\n y1 = centerY + radius * Math.sin(startAngle);\n y2 = centerY + radius * Math.sin(endAngle);\n if (series.type === 'Polar') {\n direction = ('M' + ' ' + x1 + ' ' + y1 + ' ' + 'A' + ' ' + radius + ' ' + radius + ' ' + '0' + ' ' +\n '0' + ' ' + 1 + ' ' + x2 + ' ' + y2 + ' ' + 'L' + ' ' + centerX + ' ' +\n centerY + ' ' + 'z');\n }\n else {\n direction = ('M' + ' ' + x1 + ' ' + y1 + ' ' + 'L' + ' ' + x2 + ' ' + y2 + ' ' + 'L' + ' '\n + centerX + ' ' + centerY + ' ' + 'z');\n }\n point.regionData = new PolarArc(pointStartAngle, pointEndAngle, 0, radius, itemCurrentXPos);\n }\n argsData = this.triggerEvent(series.chart, series, point);\n options = new PathOption(series.chart.element.id + '_Series_' + series.index + '_Point_' + point.index, argsData.fill, argsData.border.width, argsData.border.color, series.opacity, series.dashArray, direction);\n if (!argsData.cancel) {\n this.appendLinePath(options, series, '');\n if (series.type === 'Polar') {\n point.symbolLocations.push({\n x: centerX + radius * Math.cos((startAngle + (endAngle - startAngle) / 2)),\n y: centerY + radius * Math.sin((startAngle + (endAngle - startAngle) / 2))\n });\n }\n else {\n point.symbolLocations.push({ x: (x1 + x2) / 2, y: (y1 + y2) / 2 });\n }\n }\n }\n }\n series.isRectSeries = true;\n };\n /**\n * To trigger the point rendering event.\n * @return {void}\n * @private\n */\n PolarSeries.prototype.triggerEvent = function (chart, series, point) {\n var argsData = {\n cancel: false, name: pointRender, series: series, point: point,\n fill: series.setPointColor(point, series.interior),\n border: series.setBorderColor(point, { width: series.border.width, color: series.border.color })\n };\n chart.trigger(pointRender, argsData);\n point.color = argsData.fill;\n return argsData;\n };\n /** get position for column drawtypes\n * @return {void}.\n * @private\n */\n PolarSeries.prototype.getSeriesPosition = function (series) {\n var chart = series.chart;\n var seriesCollection = [];\n var stackingGroup = [];\n var vSeries = { rectCount: 0, position: null };\n for (var _i = 0, _a = chart.visibleSeries; _i < _a.length; _i++) {\n var series_1 = _a[_i];\n if (series_1.visible && (series_1.type === 'Polar' || series_1.type === 'Radar') && series_1.drawType.indexOf('Column') !== -1) {\n seriesCollection.push(series_1);\n }\n }\n seriesCollection.forEach(function (series) {\n if (series.drawType.indexOf('Stacking') !== -1) {\n if (series.stackingGroup) {\n if (stackingGroup[series.stackingGroup] === undefined) {\n series.position = vSeries.rectCount;\n stackingGroup[series.stackingGroup] = vSeries.rectCount++;\n }\n else {\n series.position = stackingGroup[series.stackingGroup];\n }\n }\n else {\n if (vSeries.position === null) {\n series.position = vSeries.rectCount;\n vSeries.position = vSeries.rectCount++;\n }\n else {\n series.position = vSeries.position;\n }\n }\n }\n else {\n series.position = vSeries.rectCount++;\n }\n });\n seriesCollection.forEach(function (value) {\n value.rectCount = vSeries.rectCount;\n });\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n PolarSeries.prototype.doAnimation = function (series) {\n var option = series.animation;\n var duration = series.animation.duration;\n var delay = series.animation.delay;\n var rectElements = series.seriesElement.childNodes;\n var count = 1;\n if (series.drawType === 'Scatter') {\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n if (!point.symbolLocations.length || !rectElements[count]) {\n continue;\n }\n markerAnimate(rectElements[count], delay, duration, series, point.index, point.symbolLocations[0], false);\n count++;\n }\n }\n else {\n for (count = 1; count < rectElements.length; count++) {\n this.doPolarRadarAnimation(rectElements[count], delay, duration, series);\n }\n }\n };\n /**\n * To do the Polar Radar draw type column animation.\n * @return {void}\n * @private\n */\n PolarSeries.prototype.doPolarRadarAnimation = function (animateElement, delay, duration, series) {\n var chartcenterX = series.clipRect.width / 2 + series.clipRect.x;\n var chartcenterY = series.clipRect.height / 2 + series.clipRect.y;\n var elementHeight = 0;\n animateElement.style.visibility = 'hidden';\n new Animation({}).animate(animateElement, {\n duration: duration,\n delay: delay,\n progress: function (args) {\n if (args.timeStamp > args.delay) {\n args.element.style.visibility = 'visible';\n elementHeight = ((args.timeStamp - args.delay) / args.duration);\n animateElement.setAttribute('transform', 'translate(' + chartcenterX\n + ' ' + chartcenterY + ') scale(' + elementHeight + ') translate(' + (-chartcenterX) + ' ' + (-chartcenterY) + ')');\n }\n },\n end: function (model) {\n animateElement.style.visibility = 'visible';\n animateElement.removeAttribute('transform');\n series.chart.trigger('animationComplete', { series: series });\n }\n });\n };\n /**\n * Get module name.\n */\n PolarSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'PolarSeries';\n };\n /**\n * To destroy the polar series.\n * @return {void}\n * @private\n */\n PolarSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return PolarSeries;\n}(PolarRadarPanel));\nexport { PolarSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { firstToLowerCase } from '../../common/utils/helper';\nimport { PolarSeries } from '../series/polar-series';\n/**\n * `RadarSeries` module is used to render the radar series.\n */\nvar RadarSeries = /** @class */ (function (_super) {\n __extends(RadarSeries, _super);\n function RadarSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render radar Series.\n * @return {void}.\n * @private\n */\n RadarSeries.prototype.render = function (series) {\n var seriesType = firstToLowerCase(series.drawType);\n if (series.drawType.indexOf('Column') === -1) {\n series.chart[seriesType + 'SeriesModule'].render(series, series.xAxis, series.yAxis, series.chart.requireInvertedAxis);\n }\n else {\n this.columnDrawTypeRender(series);\n }\n };\n /**\n * Get module name.\n */\n RadarSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'RadarSeries';\n };\n /**\n * To destroy the radar series.\n * @return {void}\n * @private\n */\n RadarSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return RadarSeries;\n}(PolarSeries));\nexport { RadarSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `StackingBarSeries` module is used to render the stacking bar series.\n */\nvar StackingBarSeries = /** @class */ (function (_super) {\n __extends(StackingBarSeries, _super);\n function StackingBarSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render the Stacking bar series.\n * @return {void}\n * @private\n */\n StackingBarSeries.prototype.render = function (series) {\n var origin = Math.max(series.yAxis.visibleRange.min, 0);\n var sideBySideInfo = this.getSideBySideInfo(series);\n var stackedValue = series.stackedValues;\n var rect;\n var argsData;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var pointStack = _a[_i];\n pointStack.symbolLocations = [];\n pointStack.regions = [];\n if (pointStack.visible && withInRange(series.points[pointStack.index - 1], pointStack, series.points[pointStack.index + 1], series)) {\n rect = this.getRectangle(pointStack.xValue + sideBySideInfo.start, stackedValue.endValues[pointStack.index], pointStack.xValue + sideBySideInfo.end, stackedValue.startValues[pointStack.index], series);\n argsData = this.triggerEvent(series, pointStack, series.interior, { width: series.border.width, color: series.border.color });\n if (!argsData.cancel) {\n this.drawRectangle(series, pointStack, rect, argsData);\n this.updateSymbolLocation(pointStack, rect, series);\n }\n }\n }\n };\n /**\n * To destroy the stacking bar.\n * @return {void}\n * @private\n */\n StackingBarSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name.\n */\n StackingBarSeries.prototype.getModuleName = function () {\n return 'StackingBarSeries';\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n StackingBarSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n return StackingBarSeries;\n}(ColumnBase));\nexport { StackingBarSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange, PathOption } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `CandleSeries` module is used to render the candle series.\n */\nvar CandleSeries = /** @class */ (function (_super) {\n __extends(CandleSeries, _super);\n function CandleSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Candle series.\n * @return {void}\n * @private\n */\n CandleSeries.prototype.render = function (series) {\n var sideBySideInfo = this.getSideBySideInfo(series);\n var argsData;\n var borderWidth = Math.max(series.border.width, 1);\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n var direction = '';\n var centerRegion = void 0;\n var tickRegion = void 0;\n var midPoint = void 0;\n midPoint = (sideBySideInfo.start + sideBySideInfo.end) / 2;\n //initializing after zooming and also normal initialization\n point.regions = [];\n point.symbolLocations = [];\n if (point.visible && withInRange(series.points[point.index - 1], point, series.points[point.index + 1], series)) {\n //region to cover the top and bottom ticks\n tickRegion = this.getRectangle((point.xValue + sideBySideInfo.median), Math.max(point.high, point.low), (point.xValue + sideBySideInfo.median), Math.min(point.high, point.low), series);\n if (!series.chart.requireInvertedAxis) {\n tickRegion.x -= borderWidth / 2;\n tickRegion.width = borderWidth;\n }\n else {\n tickRegion.y -= borderWidth / 2;\n tickRegion.height = borderWidth;\n }\n //get middleRect\n centerRegion = this.getRectangle((point.xValue + sideBySideInfo.start), Math.max(point.open, point.close), (point.xValue + sideBySideInfo.end), Math.min(point.open, point.close), series);\n direction = this.getPathString(tickRegion, centerRegion, series);\n argsData = this.triggerPointRenderEvent(series, point);\n if (!argsData.cancel) {\n this.drawCandle(series, point, centerRegion, argsData, direction);\n this.updateSymbolLocation(point, tickRegion, series);\n this.updateSymbolLocation(point, centerRegion, series);\n }\n }\n }\n };\n /**\n * Trigger point rendering event\n */\n CandleSeries.prototype.triggerPointRenderEvent = function (series, point) {\n var fill;\n fill = this.getCandleColor(point, series);\n var border = { color: series.border.color, width: Math.max(series.border.width, 1) };\n return this.triggerEvent(series, point, fill, border);\n };\n /**\n * Find the color of the candle\n * @param series\n * @private\n */\n CandleSeries.prototype.getCandleColor = function (point, series) {\n var currentPoint = point;\n var previousPoint = series.points[point.index - 1];\n if (series.enableSolidCandles === false) {\n if (!previousPoint) {\n return series.bearFillColor;\n }\n else {\n return previousPoint.close > point.close ? series.bullFillColor :\n series.bearFillColor;\n }\n }\n else {\n return point.open > point.close ? series.bullFillColor :\n series.bearFillColor;\n }\n };\n /**\n * Finds the path of the candle shape\n * @param Series\n * @private\n */\n CandleSeries.prototype.getPathString = function (topRect, midRect, series) {\n var direction = '';\n var width = series.chart.requireInvertedAxis ? topRect.height : topRect.width;\n var center = series.chart.requireInvertedAxis ? topRect.y + topRect.height / 2 :\n topRect.x + topRect.width / 2;\n //tick 1 segment\n direction += !series.chart.requireInvertedAxis ?\n 'M' + ' ' + (center) + ' ' + (topRect.y) + ' ' + 'L' + ' ' + (center) + ' ' + midRect.y :\n 'M' + ' ' + (topRect.x) + ' ' + (center) + ' ' + 'L' + ' ' + (midRect.x) + ' ' + center;\n direction = direction.concat(' M' + ' ' + (midRect.x) + ' ' + (midRect.y) + ' ' +\n 'L' + ' ' + (midRect.x + midRect.width) + ' ' + (midRect.y) + ' ' +\n 'L' + ' ' + (midRect.x + midRect.width) + ' ' +\n (midRect.y + midRect.height) + ' ' +\n 'L' + ' ' + (midRect.x) + ' ' + (midRect.y + midRect.height) +\n ' ' + 'Z');\n direction += !series.chart.requireInvertedAxis ?\n ' M' + ' ' + (center) + ' ' + (midRect.y + midRect.height) + ' ' + 'L' + ' ' + (center) + ' ' + (topRect.y +\n topRect.height) :\n ' M' + ' ' + (midRect.x + midRect.width) + ' ' + (center) + ' ' + 'L' + ' ' +\n (topRect.x + topRect.width) + ' ' + center;\n return direction;\n };\n /**\n * Draws the candle shape\n * @param series\n * @private\n */\n CandleSeries.prototype.drawCandle = function (series, point, rect, argsData, direction) {\n var check = series.chart.requireInvertedAxis ? rect.height : rect.width;\n if (check <= 0) {\n return null;\n }\n var fill = !series.enableSolidCandles ?\n (point.open > point.close ? argsData.fill : 'transparent') : argsData.fill;\n argsData.border.color = argsData.fill;\n var options = new PathOption(series.chart.element.id + '_Series_' + series.index + '_Point_' + point.index, fill, argsData.border.width, argsData.border.color, series.opacity, series.dashArray, direction);\n var candleElement = series.chart.renderer.drawPath(options);\n candleElement.setAttribute('aria-label', point.x.toString() + ':' + point.high.toString()\n + ':' + point.low.toString() + ':' + point.close.toString() + ':' + point.open.toString());\n series.seriesElement.appendChild(candleElement);\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n CandleSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * Get module name.\n */\n CandleSeries.prototype.getModuleName = function () {\n return 'CandleSeries';\n /**\n * return the module name\n */\n };\n /**\n * To destroy the candle series.\n * @return {void}\n * @private\n */\n CandleSeries.prototype.destroy = function (chart) {\n /**\n * Destroys the candle series.\n */\n };\n return CandleSeries;\n}(ColumnBase));\nexport { CandleSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `StackingColumnSeries` module used to render the stacking column series.\n */\nvar StackingColumnSeries = /** @class */ (function (_super) {\n __extends(StackingColumnSeries, _super);\n function StackingColumnSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render the Stacking column series.\n * @return {void}\n * @private\n */\n StackingColumnSeries.prototype.render = function (series) {\n series.isRectSeries = true;\n var origin = Math.max(series.yAxis.visibleRange.min, 0);\n var sideBySideInfo = this.getSideBySideInfo(series);\n var rect;\n var argsData;\n var stackedValue = series.stackedValues;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(series.points[point.index - 1], point, series.points[point.index + 1], series)) {\n rect = this.getRectangle(point.xValue + sideBySideInfo.start, stackedValue.endValues[point.index], point.xValue + sideBySideInfo.end, stackedValue.startValues[point.index], series);\n argsData = this.triggerEvent(series, point, series.interior, { width: series.border.width, color: series.border.color });\n if (!argsData.cancel) {\n this.drawRectangle(series, point, rect, argsData);\n this.updateSymbolLocation(point, rect, series);\n }\n }\n }\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n StackingColumnSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * To destroy the stacking column.\n * @return {void}\n * @private\n */\n StackingColumnSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name.\n */\n StackingColumnSeries.prototype.getModuleName = function () {\n return 'StackingColumnSeries';\n };\n return StackingColumnSeries;\n}(ColumnBase));\nexport { StackingColumnSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PathOption, getPoint, withInRange } from '../../common/utils/helper';\nimport { LineBase } from './line-base';\n/**\n * `StepLineSeries` module is used to render the step line series.\n */\nvar StepLineSeries = /** @class */ (function (_super) {\n __extends(StepLineSeries, _super);\n function StepLineSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render the Step line series.\n * @return {void}\n * @private\n */\n StepLineSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var direction = '';\n var startPoint = 'M';\n var prevPoint = null;\n var pathOptions;\n var lineLength;\n var point1;\n var point2;\n var visiblePoints = this.improveChartPerformance(series);\n if (xAxis.valueType === 'Category' && xAxis.labelPlacement === 'BetweenTicks') {\n lineLength = 0.5;\n }\n else {\n lineLength = 0;\n }\n for (var _i = 0, visiblePoints_1 = visiblePoints; _i < visiblePoints_1.length; _i++) {\n var point = visiblePoints_1[_i];\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(visiblePoints[point.index - 1], point, visiblePoints[point.index + 1], series)) {\n if (prevPoint != null) {\n point2 = getPoint(point.xValue, point.yValue, xAxis, yAxis, isInverted);\n point1 = getPoint(prevPoint.xValue, prevPoint.yValue, xAxis, yAxis, isInverted);\n direction = direction.concat(startPoint + ' ' + (point1.x) + ' ' + (point1.y) + ' ' + 'L' + ' ' +\n (point2.x) + ' ' + (point1.y) + 'L' + ' ' + (point2.x) + ' ' + (point2.y) + ' ');\n startPoint = 'L';\n }\n else {\n point1 = getPoint(point.xValue - lineLength, point.yValue, xAxis, yAxis, isInverted);\n direction = direction.concat(startPoint + ' ' + (point1.x) + ' ' + (point1.y) + ' ');\n startPoint = 'L';\n }\n this.storePointLocation(point, series, isInverted, getPoint);\n prevPoint = point;\n }\n else {\n prevPoint = series.emptyPointSettings.mode === 'Drop' ? prevPoint : null;\n startPoint = series.emptyPointSettings.mode === 'Drop' ? startPoint : 'M';\n }\n }\n point1 = getPoint(visiblePoints[visiblePoints.length - 1].xValue + lineLength, visiblePoints[visiblePoints.length - 1].yValue, xAxis, yAxis, isInverted);\n direction = direction.concat(startPoint + ' ' + (point1.x) + ' ' + (point1.y) + ' ');\n pathOptions = new PathOption(series.chart.element.id + '_Series_' + series.index, 'transparent', series.width, series.interior, series.opacity, series.dashArray, direction);\n this.appendLinePath(pathOptions, series, '');\n this.renderMarker(series);\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n StepLineSeries.prototype.doAnimation = function (series) {\n var option = series.animation;\n this.doLinearAnimation(series, option);\n };\n /**\n * To destroy the step line series.\n * @return {void}\n * @private\n */\n StepLineSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n /**\n * Get module name.\n */\n StepLineSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'StepLineSeries';\n };\n return StepLineSeries;\n}(LineBase));\nexport { StepLineSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { getPoint, withInRange, ChartLocation, PathOption } from '../../common/utils/helper';\nimport { LineBase } from './line-base';\n/**\n * `StepAreaSeries` Module used to render the step area series.\n */\nvar StepAreaSeries = /** @class */ (function (_super) {\n __extends(StepAreaSeries, _super);\n function StepAreaSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render StepArea series.\n * @return {void}\n * @private\n */\n StepAreaSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var currentPoint;\n var secondPoint;\n var start = null;\n var direction = '';\n var pointsLength = series.points.length;\n var origin = Math.max(series.yAxis.visibleRange.min, 0);\n var options;\n var point;\n var xValue;\n var lineLength;\n var prevPoint = null;\n if (xAxis.valueType === 'Category' && xAxis.labelPlacement === 'BetweenTicks') {\n lineLength = 0.5;\n }\n else {\n lineLength = 0;\n }\n for (var i = 0; i < pointsLength; i++) {\n point = series.points[i];\n xValue = point.xValue;\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(series.points[i - 1], point, series.points[i + 1], series)) {\n if (start === null) {\n start = new ChartLocation(xValue, 0);\n // Start point for the current path\n currentPoint = getPoint(xValue - lineLength, origin, xAxis, yAxis, isInverted);\n direction += ('M' + ' ' + (currentPoint.x) + ' ' + (currentPoint.y) + ' ');\n currentPoint = getPoint(xValue - lineLength, point.yValue, xAxis, yAxis, isInverted);\n direction += ('L' + ' ' + (currentPoint.x) + ' ' + (currentPoint.y) + ' ');\n }\n // First Point to draw the Steparea path\n if (prevPoint != null) {\n currentPoint = getPoint(point.xValue, point.yValue, xAxis, yAxis, isInverted);\n secondPoint = getPoint(prevPoint.xValue, prevPoint.yValue, xAxis, yAxis, isInverted);\n direction += ('L' + ' ' +\n (currentPoint.x) + ' ' + (secondPoint.y) + 'L' + ' ' + (currentPoint.x) + ' ' + (currentPoint.y) + ' ');\n }\n else if (series.emptyPointSettings.mode === 'Gap') {\n currentPoint = getPoint(point.xValue, point.yValue, xAxis, yAxis, isInverted);\n direction += 'L' + ' ' + (currentPoint.x) + ' ' + (currentPoint.y) + ' ';\n }\n this.storePointLocation(point, series, isInverted, getPoint);\n prevPoint = point;\n }\n if (series.points[i + 1] && !series.points[i + 1].visible && series.emptyPointSettings.mode !== 'Drop') {\n // current start point\n currentPoint = getPoint(xValue + lineLength, origin, xAxis, yAxis, isInverted);\n direction += ('L' + ' ' + (currentPoint.x) + ' ' + (currentPoint.y));\n start = null;\n prevPoint = null;\n }\n }\n if (pointsLength > 1) {\n start = { 'x': series.points[pointsLength - 1].xValue + lineLength, 'y': series.points[pointsLength - 1].yValue };\n secondPoint = getPoint(start.x, start.y, xAxis, yAxis, isInverted);\n direction += ('L' + ' ' + (secondPoint.x) + ' ' + (secondPoint.y) + ' ');\n start = { 'x': series.points[pointsLength - 1].xValue + lineLength, 'y': origin };\n secondPoint = getPoint(start.x, start.y, xAxis, yAxis, isInverted);\n direction += ('L' + ' ' + (secondPoint.x) + ' ' + (secondPoint.y) + ' ');\n }\n options = new PathOption(series.chart.element.id + '_Series_' + series.index, series.interior, series.border.width, series.border.color, series.opacity, series.dashArray, direction);\n this.appendLinePath(options, series, '');\n this.renderMarker(series);\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n StepAreaSeries.prototype.doAnimation = function (series) {\n var option = series.animation;\n this.doLinearAnimation(series, option);\n };\n /**\n * To destroy the step Area series.\n * @return {void}\n * @private\n */\n StepAreaSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n /**\n * Get module name.\n */\n StepAreaSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'StepAreaSeries';\n };\n return StepAreaSeries;\n}(LineBase));\nexport { StepAreaSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PathOption, getPoint, withInRange, Rect, TransformToVisible } from '../../common/utils/helper';\nimport { LineBase } from './line-base';\n/**\n * `StackingAreaSeries` module used to render the Stacking Area series.\n */\nvar StackingAreaSeries = /** @class */ (function (_super) {\n __extends(StackingAreaSeries, _super);\n function StackingAreaSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render the Stacking area series.\n * @return {void}\n * @private\n */\n StackingAreaSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var polarAreaType = series.chart.chartAreaType === 'PolarRadar';\n var getCoordinate = polarAreaType ? TransformToVisible : getPoint;\n var lineDirection = '';\n var visiblePoints = series.points;\n var pointsLength = visiblePoints.length;\n var stackedvalue = series.stackedValues;\n var origin = polarAreaType ?\n Math.max(series.yAxis.visibleRange.min, stackedvalue.endValues[0]) :\n Math.max(series.yAxis.visibleRange.min, stackedvalue.startValues[0]);\n var border = series.border;\n var options;\n var startPoint = 0;\n var point1 = getCoordinate(visiblePoints[0].xValue, origin, xAxis, yAxis, isInverted, series);\n var point2;\n lineDirection = lineDirection.concat('M' + ' ' + (point1.x) + ' ' + (point1.y) + ' ');\n for (var i = 0; i < pointsLength; i++) {\n visiblePoints[i].symbolLocations = [];\n visiblePoints[i].regions = [];\n if (visiblePoints[i].visible && withInRange(visiblePoints[i - 1], visiblePoints[i], visiblePoints[i + 1], series)) {\n point1 = getCoordinate(visiblePoints[i].xValue, stackedvalue.endValues[i], xAxis, yAxis, isInverted, series);\n lineDirection = lineDirection.concat('L' + ' ' + (point1.x) + ' ' + (point1.y) + ' ');\n visiblePoints[i].symbolLocations.push(getCoordinate(visiblePoints[i].xValue, stackedvalue.endValues[i], xAxis, yAxis, isInverted, series));\n visiblePoints[i].regions.push(new Rect(visiblePoints[i].symbolLocations[0].x - series.marker.width, visiblePoints[i].symbolLocations[0].y - series.marker.height, 2 * series.marker.width, 2 * series.marker.height));\n }\n else {\n if (series.emptyPointSettings.mode !== 'Drop') {\n for (var j = i - 1; j >= startPoint; j--) {\n point2 = getCoordinate(visiblePoints[j].xValue, stackedvalue.startValues[j], xAxis, yAxis, isInverted, series);\n lineDirection = lineDirection.concat('L' + ' ' + (point2.x) + ' ' + (point2.y) + ' ');\n }\n if (visiblePoints[i + 1] && visiblePoints[i + 1].visible) {\n point1 = getCoordinate(visiblePoints[i + 1].xValue, stackedvalue.startValues[i + 1], xAxis, yAxis, isInverted, series);\n lineDirection = lineDirection.concat('M' + ' ' + (point1.x) + ' ' + (point1.y) + ' ');\n }\n startPoint = i + 1;\n }\n }\n }\n if (series.chart.chartAreaType === 'PolarRadar' && visiblePoints.length > 1) {\n point1 = { 'x': series.points[0].xValue, 'y': stackedvalue.endValues[0] };\n point2 = getCoordinate(point1.x, point1.y, xAxis, yAxis, isInverted, series);\n lineDirection += ('L' + ' ' + (point2.x) + ' ' + (point2.y) + ' ');\n }\n for (var j = pointsLength - 1; j >= startPoint; j--) {\n var previousSeries = this.getPreviousSeries(series);\n if (previousSeries.emptyPointSettings.mode !== 'Drop' || !previousSeries.points[j].isEmpty) {\n point2 = getCoordinate(visiblePoints[j].xValue, stackedvalue.startValues[j], xAxis, yAxis, isInverted, series);\n lineDirection = lineDirection.concat(((j === (pointsLength - 1) && polarAreaType) ? 'M' : 'L')\n + ' ' + (point2.x) + ' ' + (point2.y) + ' ');\n }\n }\n options = new PathOption(series.chart.element.id + '_Series_' + series.index, series.interior, series.border.width, series.border.color, series.opacity, series.dashArray, lineDirection);\n this.appendLinePath(options, series, '');\n this.renderMarker(series);\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n StackingAreaSeries.prototype.doAnimation = function (series) {\n var option = series.animation;\n this.doLinearAnimation(series, option);\n };\n /**\n * To destroy the stacking area.\n * @return {void}\n * @private\n */\n StackingAreaSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n /**\n * Get module name.\n */\n StackingAreaSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'StackingAreaSeries';\n };\n /**\n * To find previous visible series\n */\n StackingAreaSeries.prototype.getPreviousSeries = function (series) {\n var seriesCollection = series.chart.visibleSeries;\n for (var i = 0, length_1 = seriesCollection.length; i < length_1; i++) {\n if (series.index === seriesCollection[i].index && i !== 0) {\n return seriesCollection[i - 1];\n }\n }\n return seriesCollection[0];\n };\n return StackingAreaSeries;\n}(LineBase));\nexport { StackingAreaSeries };\n","import { withInRange, getPoint, PathOption, drawSymbol, Size, Rect, markerAnimate, TransformToVisible } from '../../common/utils/helper';\nimport { pointRender } from '../../common/model/constants';\n/**\n * `ScatterSeries` module is used to render the scatter series.\n */\nvar ScatterSeries = /** @class */ (function () {\n function ScatterSeries() {\n }\n /**\n * Render the scatter series.\n * @return {void}\n * @private\n */\n ScatterSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var seriesIndex = series.index;\n var marker = series.marker;\n var border = series.border;\n var visiblePoints = series.points;\n var pointIndex;\n var symbolId;\n var shapeOption;\n var argsData;\n var getCoordinate = series.chart.chartAreaType === 'PolarRadar' ? TransformToVisible : getPoint;\n for (var _i = 0, visiblePoints_1 = visiblePoints; _i < visiblePoints_1.length; _i++) {\n var point = visiblePoints_1[_i];\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(visiblePoints[point.index - 1], point, visiblePoints[point.index + 1], series)) {\n symbolId = series.chart.element.id + '_Series_' + seriesIndex + '_Point_' + point.index;\n argsData = {\n cancel: false, name: pointRender, series: series, point: point,\n fill: series.setPointColor(point, series.interior),\n border: series.setBorderColor(point, { width: series.border.width, color: series.border.color }),\n height: marker.height, width: marker.width, shape: marker.shape\n };\n series.chart.trigger(pointRender, argsData);\n if (!argsData.cancel) {\n point.symbolLocations.push(getCoordinate(point.xValue, point.yValue, xAxis, yAxis, isInverted, series));\n point.color = argsData.fill;\n shapeOption = new PathOption(symbolId, argsData.fill, argsData.border.width, argsData.border.color, series.opacity, null);\n series.seriesElement.appendChild(drawSymbol(point.symbolLocations[0], argsData.shape, new Size(argsData.width, argsData.height), marker.imageUrl, shapeOption, point.x.toString() + ':' + point.yValue.toString()));\n point.regions.push(new Rect(point.symbolLocations[0].x - marker.width, point.symbolLocations[0].y - marker.height, 2 * marker.width, 2 * marker.height));\n point.marker = {\n border: argsData.border, fill: argsData.fill,\n height: argsData.height, visible: true,\n width: argsData.width, shape: argsData.shape\n };\n }\n else {\n point.marker = { visible: true };\n }\n }\n }\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n ScatterSeries.prototype.doAnimation = function (series) {\n var duration = series.animation.duration;\n var delay = series.animation.delay;\n var rectElements = series.seriesElement.childNodes;\n var count = 1;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n if (!point.symbolLocations.length || !rectElements[count]) {\n continue;\n }\n markerAnimate(rectElements[count], delay, duration, series, point.index, point.symbolLocations[0], false);\n count++;\n }\n };\n /**\n * Get module name.\n */\n ScatterSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'ScatterSeries';\n };\n /**\n * To destroy the scatter.\n * @return {void}\n */\n ScatterSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n return ScatterSeries;\n}());\nexport { ScatterSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `RangeColumnSeries` module is used to render the range column series.\n */\nvar RangeColumnSeries = /** @class */ (function (_super) {\n __extends(RangeColumnSeries, _super);\n function RangeColumnSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Range Column series.\n * @return {void}\n * @private\n */\n RangeColumnSeries.prototype.render = function (series) {\n var rect;\n var sideBySideInfo = this.getSideBySideInfo(series);\n //let origin: number = Math.max(series.yAxis.visibleRange.min, 0);\n var argsData;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var rangePoint = _a[_i];\n rangePoint.symbolLocations = [];\n rangePoint.regions = [];\n if (rangePoint.visible && withInRange(series.points[rangePoint.index - 1], rangePoint, series.points[rangePoint.index + 1], series)) {\n rect = this.getRectangle(rangePoint.xValue + sideBySideInfo.start, rangePoint.high, rangePoint.xValue + sideBySideInfo.end, rangePoint.low, series);\n argsData = this.triggerEvent(series, rangePoint, series.interior, { width: series.border.width, color: series.border.color });\n if (!argsData.cancel) {\n this.updateSymbolLocation(rangePoint, rect, series);\n this.drawRectangle(series, rangePoint, rect, argsData);\n }\n }\n }\n };\n /**\n * Get module name.\n */\n RangeColumnSeries.prototype.getModuleName = function () {\n return 'RangeColumnSeries';\n /**\n * return the module name\n */\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n RangeColumnSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * To destroy the range column series.\n * @return {void}\n * @private\n */\n RangeColumnSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return RangeColumnSeries;\n}(ColumnBase));\nexport { RangeColumnSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PathOption, withInRange, subArraySum } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `WaterfallSeries` module is used to render the waterfall series.\n */\nvar WaterfallSeries = /** @class */ (function (_super) {\n __extends(WaterfallSeries, _super);\n function WaterfallSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render waterfall series.\n * @return {void}\n * @private\n */\n WaterfallSeries.prototype.render = function (series) {\n var rect;\n var sideBySideInfo = this.getSideBySideInfo(series);\n var origin = Math.max(series.yAxis.visibleRange.min, 0);\n var argsData;\n var prevEndValue = 0;\n var direction = '';\n var currentEndValue = 0;\n var originValue;\n var prevRegion = null;\n var y;\n var isInversed = series.chart.requireInvertedAxis;\n var intermediateOrigin = 0;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(series.points[point.index - 1], point, series.points[point.index + 1], series)) {\n //Calcute the current point value to render waterfall series.\n var isSum = this.isIntermediateSum(series, point.index);\n var totalSum = this.isSumIndex(series, point.index);\n currentEndValue += isSum || totalSum === true ? 0 : point.yValue;\n //Calcute the origin value for points\n originValue = (isSum === true ? intermediateOrigin : ((prevEndValue !== null && !totalSum) ? prevEndValue : origin));\n rect = this.getRectangle(point.xValue + sideBySideInfo.start, currentEndValue, point.xValue + sideBySideInfo.end, originValue, series);\n argsData = this.triggerPointRenderEvent(series, point);\n //intermediateOrigin is used only for imtermediate data \n if (isSum) {\n intermediateOrigin = currentEndValue;\n }\n prevEndValue = currentEndValue;\n if (!argsData.cancel) {\n this.updateSymbolLocation(point, rect, series);\n this.drawRectangle(series, point, rect, argsData);\n }\n var currentRegion = point.regions[0];\n if (prevRegion !== null) {\n var prevLeft = isInversed ? prevRegion.x : prevRegion.y;\n var currentLeft = isInversed ? currentRegion.x : currentRegion.y;\n var prevBottom = isInversed ? prevRegion.x + prevRegion.width : prevRegion.y + prevRegion.height;\n var currentBottom = isInversed ?\n currentRegion.x + currentRegion.width : currentRegion.y + currentRegion.height;\n if (Math.round(prevLeft) === Math.round(currentLeft) ||\n Math.round(prevBottom) === Math.round(currentLeft)) {\n y = isInversed ? currentRegion.x : currentRegion.y;\n }\n else {\n y = currentBottom;\n }\n if (isInversed) {\n direction = direction.concat('M' + ' ' + y + ' ' + (prevRegion.y + prevRegion.height) + ' ' +\n 'L' + ' ' + y + ' ' + currentRegion.y + ' ');\n }\n else {\n direction = direction.concat('M' + ' ' + prevRegion.x + ' ' + y + ' ' +\n 'L' + ' ' + (currentRegion.x + currentRegion.width) + ' ' + y + ' ');\n }\n }\n prevRegion = point.regions[0];\n }\n }\n var options = new PathOption(series.chart.element.id + '_Series_' + series.index + '_Connector_', 'none', series.connector.width, series.connector.color, series.opacity, series.connector.dashArray, direction);\n var element = series.chart.renderer.drawPath(options);\n if (series.chart.animateSeries) {\n element.style.visibility = 'hidden';\n }\n series.seriesElement.appendChild(element);\n };\n /**\n * To check intermediateSumIndex in waterfall series.\n * @return boolean\n * @private\n */\n WaterfallSeries.prototype.isIntermediateSum = function (series, index) {\n if (series.intermediateSumIndexes !== undefined && series.intermediateSumIndexes.indexOf(index) !== -1) {\n return true;\n }\n return false;\n };\n /**\n * To check sumIndex in waterfall series.\n * @return boolean\n * @private\n */\n WaterfallSeries.prototype.isSumIndex = function (series, index) {\n if (series.sumIndexes !== undefined && series.sumIndexes.indexOf(index) !== -1) {\n return true;\n }\n return false;\n };\n /**\n * To trigger the point rendering event for waterfall series.\n * @return IPointRenderEventArgs\n * @private\n */\n WaterfallSeries.prototype.triggerPointRenderEvent = function (series, point) {\n var color;\n var isSum = this.isIntermediateSum(series, point.index);\n var totalSum = this.isSumIndex(series, point.index);\n if (isSum || totalSum) {\n color = series.summaryFillColor;\n }\n else if (point.y < 0) {\n color = series.negativeFillColor;\n }\n else {\n color = series.interior;\n }\n return this.triggerEvent(series, point, color, { color: series.border.color, width: series.border.width });\n };\n /**\n * Add sumIndex and intermediateSumIndex data.\n * @return {object[]}\n * @private\n */\n WaterfallSeries.prototype.processInternalData = function (json, series) {\n var data = json;\n var length = json.length;\n var index;\n var intermediateSum = series.intermediateSumIndexes;\n var sumIndex = series.sumIndexes;\n if (intermediateSum !== undefined && intermediateSum.length > 0) {\n for (var i = 0; i < intermediateSum.length; i++) {\n for (var j = 0; j < data.length; j++) {\n if (j === intermediateSum[i]) {\n if (i === 0) {\n index = subArraySum(data, -1, intermediateSum[i], null, series);\n }\n else {\n index = subArraySum(data, intermediateSum[i - 1], intermediateSum[i], null, series);\n }\n data[j][series.yName] = index;\n }\n }\n }\n }\n if (sumIndex !== undefined && sumIndex.length > 0) {\n for (var k = 0; k < sumIndex.length; k++) {\n for (var j = 0; j < data.length; j++) {\n if (j === sumIndex[k]) {\n if (intermediateSum !== undefined) {\n index = subArraySum(data, -1, sumIndex[k], sumIndex, series);\n }\n else {\n index = subArraySum(data, -1, sumIndex[k], null, series);\n }\n data[j][series.yName] = index;\n }\n }\n }\n }\n return data;\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n WaterfallSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * Get module name.\n */\n WaterfallSeries.prototype.getModuleName = function () {\n return 'WaterfallSeries';\n /**\n * return the module name\n */\n };\n /**\n * To destroy the waterfall series.\n * @return {void}\n * @private\n */\n WaterfallSeries.prototype.destroy = function (chart) {\n /**\n * Destroys the waterfall series.\n */\n };\n return WaterfallSeries;\n}(ColumnBase));\nexport { WaterfallSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `HiloSeries` module is used to render the hilo series.\n */\nvar HiloSeries = /** @class */ (function (_super) {\n __extends(HiloSeries, _super);\n function HiloSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Hiloseries.\n * @return {void}\n * @private\n */\n HiloSeries.prototype.render = function (series) {\n var region;\n var sideBySideInfo = this.getSideBySideInfo(series);\n var argsData;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible &&\n withInRange(series.points[point.index - 1], point, series.points[point.index + 1], series)) {\n region = this.getRectangle(point.xValue + sideBySideInfo.median, point.high, point.xValue + sideBySideInfo.median, point.low, series);\n argsData = this.triggerPointRenderEvent(series, point);\n if (!argsData.cancel) {\n if (!series.chart.requireInvertedAxis) {\n region.width = argsData.border.width;\n region.x = region.x - (region.width / 2);\n }\n else {\n region.height = argsData.border.width;\n region.y = region.y - (region.height / 2);\n }\n argsData.border.width = 0;\n this.updateSymbolLocation(point, region, series);\n this.drawRectangle(series, point, region, argsData);\n }\n }\n }\n };\n /**\n * To trigger the point rendering event.\n * @return {void}\n * @private\n */\n HiloSeries.prototype.triggerPointRenderEvent = function (series, point) {\n var border = { color: series.fill, width: Math.max(series.border.width, 2) };\n return _super.prototype.triggerEvent.call(this, series, point, series.interior, border);\n };\n /**\n * Get module name.\n */\n HiloSeries.prototype.getModuleName = function () {\n return 'HiloSeries';\n /**\n * return the module name\n */\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n HiloSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * To destroy the Hilo series.\n * @return {void}\n * @private\n */\n HiloSeries.prototype.destroy = function (chart) {\n /**\n * Destroys the Hilo Series\n */\n };\n return HiloSeries;\n}(ColumnBase));\nexport { HiloSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange, PathOption } from '../../common/utils/helper';\nimport { ColumnBase } from './column-base';\n/**\n * `HiloOpenCloseSeries` module is used to render the hiloOpenClose series.\n */\nvar HiloOpenCloseSeries = /** @class */ (function (_super) {\n __extends(HiloOpenCloseSeries, _super);\n function HiloOpenCloseSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render HiloOpenCloseSeries series.\n * @return {void}\n * @private\n */\n HiloOpenCloseSeries.prototype.render = function (series) {\n var highLowRect;\n var open;\n var close;\n var sideBySideInfo = this.getSideBySideInfo(series);\n var argsData;\n var borderWidth = Math.max(series.border.width, 2);\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible &&\n withInRange(series.points[point.index - 1], point, series.points[point.index + 1], series)) {\n //highlow\n highLowRect = this.getRectangle(point.xValue + sideBySideInfo.start, Math.max(point.high, point.low), point.xValue + sideBySideInfo.end, Math.min(point.high, point.low), series);\n point.regions.push(this.getRectangle(point.xValue + sideBySideInfo.median, Math.max(point.high, point.low), point.xValue + sideBySideInfo.median, Math.min(point.high, point.low), series));\n this.updateTickRegion(!series.chart.requireInvertedAxis, point.regions[0], borderWidth);\n //open\n point.regions.push(this.getRectangle(point.xValue + sideBySideInfo.start, Math.max(point.open, point.close), point.xValue + sideBySideInfo.median, Math.max(point.open, point.close), series));\n //close\n point.regions.push(this.getRectangle(point.xValue + sideBySideInfo.median, Math.min(point.open, point.close), point.xValue + sideBySideInfo.end, Math.min(point.open, point.close), series));\n argsData = this.triggerPointRenderEvent(series, point);\n if (!argsData.cancel) {\n this.updateSymbolLocation(point, point.regions[0], series);\n var open_1 = { x: point.regions[1].x, y: point.regions[1].y };\n var close_1 = { x: point.regions[2].x, y: point.regions[2].y };\n this.drawHiloOpenClosePath(series, point, open_1, close_1, highLowRect, argsData);\n }\n this.updateTickRegion(series.chart.requireInvertedAxis, point.regions[1], borderWidth);\n this.updateTickRegion(series.chart.requireInvertedAxis, point.regions[2], borderWidth);\n }\n }\n };\n /**\n * Updates the tick region\n */\n HiloOpenCloseSeries.prototype.updateTickRegion = function (horizontal, region, borderWidth) {\n if (horizontal) {\n region.x -= borderWidth / 2;\n region.width = borderWidth;\n }\n else {\n region.y -= borderWidth / 2;\n region.height = borderWidth;\n }\n };\n /**\n * Trigger point rendering event\n */\n HiloOpenCloseSeries.prototype.triggerPointRenderEvent = function (series, point) {\n var fill = (point.open <= point.close) ? series.bearFillColor : series.bullFillColor;\n var border = { color: series.border.color, width: Math.max(series.border.width, 1) };\n return this.triggerEvent(series, point, fill, border);\n };\n /**\n * To draw the rectangle for points.\n * @return {void}\n * @private\n */\n HiloOpenCloseSeries.prototype.drawHiloOpenClosePath = function (series, point, open, close, rect, argsData) {\n // region highlow\n var direction;\n var options;\n if (series.chart.requireInvertedAxis) {\n direction = ('M' + ' ' + (rect.x) + ' ' + (rect.y + rect.height / 2) + ' ' +\n 'L' + ' ' + (rect.x + rect.width) + ' ' + (rect.y + rect.height / 2) + ' ');\n direction += ('M' + ' ' + (open.x) + ' ' + (rect.y + rect.height / 2) + ' ' +\n 'L' + ' ' + (open.x) + ' ' + (rect.y + rect.height) + ' ');\n direction += ('M' + ' ' + (close.x) + ' ' + (rect.y + rect.height / 2) + ' ' +\n 'L' + ' ' + (close.x) + ' ' + (rect.y) + ' ');\n }\n else {\n direction = ('M' + ' ' + (rect.x + rect.width / 2) + ' ' + (rect.y + rect.height) + ' ' +\n 'L' + ' ' + (rect.x + rect.width / 2) + ' ' + (rect.y) + ' ');\n //region opentick\n direction += ('M' + ' ' + (rect.x) + ' ' + (open.y) + ' ' +\n 'L' + ' ' + (rect.x + rect.width / 2) + ' ' + (open.y) + ' ');\n //region closetick\n direction += ('M' + ' ' + (rect.x + rect.width / 2) + ' ' + (close.y) + ' ' +\n 'L' + ' ' + (rect.x + rect.width) + ' ' + (close.y) + ' ');\n }\n options = new PathOption(series.chart.element.id + '_Series_' + series.index + '_Point_' + point.index, argsData.fill, argsData.border.width, argsData.fill, series.opacity, series.dashArray, direction);\n var element = series.chart.renderer.drawPath(options);\n element.setAttribute('aria-label', point.x.toString() + ':' + point.high.toString()\n + ':' + point.low.toString() + ':' + point.close.toString() + ':' + point.open.toString());\n series.seriesElement.appendChild(element);\n };\n /**\n * Get module name.\n */\n HiloOpenCloseSeries.prototype.getModuleName = function () {\n return 'HiloOpenCloseSeries';\n /**\n * return the module name\n */\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n HiloOpenCloseSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * To destroy the column series.\n * @return {void}\n * @private\n */\n HiloOpenCloseSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return HiloOpenCloseSeries;\n}(ColumnBase));\nexport { HiloOpenCloseSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange, getPoint, PathOption, Rect } from '../../common/utils/helper';\nimport { LineBase } from './line-base';\n/**\n * `RangeAreaSeries` module is used to render the range area series.\n */\nvar RangeAreaSeries = /** @class */ (function (_super) {\n __extends(RangeAreaSeries, _super);\n function RangeAreaSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render RangeArea Series.\n * @return {void}.\n * @private\n */\n RangeAreaSeries.prototype.render = function (series) {\n var point;\n var direction = '';\n var command = 'M';\n var closed = undefined;\n var visiblePoints = this.improveChartPerformance(series);\n for (var i = 0, length_1 = visiblePoints.length; i < length_1; i++) {\n point = visiblePoints[i];\n point.symbolLocations = [];\n point.regions = [];\n var low = Math.min(point.low, point.high);\n var high = Math.max(point.low, point.high);\n if (series.yAxis.isInversed) {\n var temp = low;\n low = high;\n high = temp;\n }\n var lowPoint = getPoint(point.xValue, low, series.xAxis, series.yAxis, series.chart.requireInvertedAxis);\n var highPoint = getPoint(point.xValue, high, series.xAxis, series.yAxis, series.chart.requireInvertedAxis);\n point.symbolLocations.push(highPoint);\n point.symbolLocations.push(lowPoint);\n var rect = new Rect(Math.min(lowPoint.x, highPoint.x), Math.min(lowPoint.y, highPoint.y), Math.max(Math.abs(highPoint.x - lowPoint.x), series.marker.width), Math.max(Math.abs(highPoint.y - lowPoint.y), series.marker.width));\n if (!series.chart.requireInvertedAxis) {\n rect.x -= series.marker.width / 2;\n }\n else {\n rect.y -= series.marker.width / 2;\n }\n point.regions.push(rect);\n //Path to connect the high points\n if (point.visible && withInRange(visiblePoints[point.index - 1], point, visiblePoints[point.index + 1], series)) {\n direction = direction.concat(command + ' ' + (lowPoint.x) + ' ' + (lowPoint.y) + ' ');\n closed = false;\n if ((i + 1 < visiblePoints.length && !visiblePoints[i + 1].visible)\n || i === visiblePoints.length - 1) {\n // Path to connect the low points\n direction = this.closeRangeAreaPath(visiblePoints, point, series, direction, i);\n command = 'M';\n direction = direction.concat(' ' + 'Z');\n closed = true;\n }\n command = 'L';\n }\n else {\n if (closed === false && i !== 0) {\n direction = this.closeRangeAreaPath(visiblePoints, point, series, direction, i);\n closed = true;\n }\n command = 'M';\n point.symbolLocations = [];\n }\n }\n var name = series.category === 'Indicator' ? series.chart.element.id + '_Indicator_' + series.index + '_' + series.name :\n series.chart.element.id + '_Series_' + series.index;\n var options = new PathOption(name, series.interior, series.border.width, series.border.color, series.opacity, series.dashArray, direction);\n this.appendLinePath(options, series, '');\n this.renderMarker(series);\n };\n /**\n * path for rendering the low points\n * @return {void}.\n * @private\n */\n RangeAreaSeries.prototype.closeRangeAreaPath = function (visiblePoints, point, series, direction, i) {\n for (var j = i; j >= 0; j--) {\n if (visiblePoints[j].visible && visiblePoints[j].symbolLocations[0]) {\n point = visiblePoints[j];\n direction += 'L' + ' ' + (point.symbolLocations[0].x) + ' ' + ((point.symbolLocations[0].y)) + ' ';\n }\n else {\n break;\n }\n }\n return direction;\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n RangeAreaSeries.prototype.doAnimation = function (series) {\n var option = series.animation;\n this.doLinearAnimation(series, option);\n };\n /**\n * Get module name.\n */\n RangeAreaSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'RangeAreaSeries';\n };\n /**\n * To destroy the line series.\n * @return {void}\n * @private\n */\n RangeAreaSeries.prototype.destroy = function (chart) {\n /**\n * Destroys range area series\n */\n };\n return RangeAreaSeries;\n}(LineBase));\nexport { RangeAreaSeries };\n","import { withInRange, getPoint, PathOption, drawSymbol, Size, Rect, markerAnimate } from '../../common/utils/helper';\nimport { pointRender } from '../../common/model/constants';\n/**\n * `BubbleSeries` module is used to render the bubble series.\n */\nvar BubbleSeries = /** @class */ (function () {\n function BubbleSeries() {\n }\n /**\n * Render the Bubble series.\n * @return {void}\n * @private\n */\n BubbleSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var marker = series.marker;\n var visiblePoints = series.points;\n var shapeOption;\n var argsData;\n //let bubbleMode: RadiusMode = bubbleOptions.radiusMode;\n var segmentRadius;\n var radius;\n var value = Math.max(series.chart.initialClipRect.height, series.chart.initialClipRect.width);\n var percentChange = value / 100;\n var maxRadius = series.maxRadius * percentChange;\n var minRadius = series.minRadius * percentChange;\n var maximumSize = null;\n var maxValue = null;\n if ((series.maxRadius === null || series.minRadius === null)) {\n for (var _i = 0, _a = series.chart.visibleSeries; _i < _a.length; _i++) {\n var value_1 = _a[_i];\n if (value_1.type === 'Bubble' && value_1.visible === true && (value_1.maxRadius === null || value_1.minRadius === null)) {\n maximumSize = value_1.sizeMax > maximumSize ? value_1.sizeMax : maximumSize;\n }\n }\n maxValue = (value / 5) / 2;\n minRadius = maxRadius = 1;\n radius = maxValue * maxRadius;\n }\n else {\n maximumSize = series.sizeMax;\n radius = maxRadius - minRadius;\n }\n for (var _b = 0, visiblePoints_1 = visiblePoints; _b < visiblePoints_1.length; _b++) {\n var bubblePoint = visiblePoints_1[_b];\n bubblePoint.symbolLocations = [];\n bubblePoint.regions = [];\n if (bubblePoint.visible &&\n withInRange(visiblePoints[bubblePoint.index - 1], bubblePoint, visiblePoints[bubblePoint.index + 1], series)) {\n if ((series.maxRadius === null || series.minRadius === null)) {\n segmentRadius = radius * Math.abs(+bubblePoint.size / maximumSize);\n }\n else {\n segmentRadius = minRadius + radius * Math.abs(+bubblePoint.size / maximumSize);\n }\n segmentRadius = segmentRadius || minRadius;\n argsData = {\n cancel: false, name: pointRender, series: series, point: bubblePoint,\n fill: series.setPointColor(bubblePoint, series.interior),\n border: series.setBorderColor(bubblePoint, { width: series.border.width, color: series.border.color }),\n height: 2 * segmentRadius, width: 2 * segmentRadius\n };\n series.chart.trigger(pointRender, argsData);\n if (!argsData.cancel) {\n bubblePoint.symbolLocations.push(getPoint(bubblePoint.xValue, bubblePoint.yValue, xAxis, yAxis, isInverted));\n bubblePoint.color = argsData.fill;\n shapeOption = new PathOption(series.chart.element.id + '_Series_' + series.index + '_Point_' + bubblePoint.index, argsData.fill, argsData.border.width, argsData.border.color, series.opacity, null);\n series.seriesElement.appendChild(drawSymbol(bubblePoint.symbolLocations[0], 'Circle', new Size(argsData.width, argsData.height), marker.imageUrl, shapeOption, bubblePoint.x.toString() + ':' + bubblePoint.yValue.toString()));\n bubblePoint.regions.push(new Rect(bubblePoint.symbolLocations[0].x - segmentRadius, bubblePoint.symbolLocations[0].y - segmentRadius, 2 * segmentRadius, 2 * segmentRadius));\n bubblePoint.marker = {\n border: argsData.border, fill: argsData.fill,\n height: argsData.height, visible: true,\n shape: 'Circle', width: argsData.width\n };\n }\n else {\n bubblePoint.marker = { visible: false };\n }\n }\n }\n };\n /**\n * To destroy the Bubble.\n * @return {void}\n * @private\n */\n BubbleSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n /**\n * Get module name.\n */\n BubbleSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'BubbleSeries';\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n BubbleSeries.prototype.doAnimation = function (series) {\n var duration = series.animation.duration;\n var delay = series.animation.delay;\n var rectElements = series.seriesElement.childNodes;\n var count = 1;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var bubblePoint = _a[_i];\n if (!bubblePoint.symbolLocations.length) {\n continue;\n }\n markerAnimate(rectElements[count], delay, duration, series, bubblePoint.index, bubblePoint.symbolLocations[0], false);\n count++;\n }\n };\n return BubbleSeries;\n}());\nexport { BubbleSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { ChartLocation, ControlPoints } from '../../common/utils/helper';\nimport { extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { LineBase } from './line-base';\n/**\n * render Line series\n */\nvar SplineBase = /** @class */ (function (_super) {\n __extends(SplineBase, _super);\n /** @private */\n function SplineBase(chartModule) {\n var _this = _super.call(this, chartModule) || this;\n _this.splinePoints = [];\n return _this;\n }\n /**\n * To find the control points for spline.\n * @return {void}\n * @private\n */\n SplineBase.prototype.findSplinePoint = function (series) {\n var value;\n var points = this.filterEmptyPoints(series);\n this.splinePoints = this.findSplineCoefficients(points, series);\n if (points.length > 1) {\n series.drawPoints = [];\n for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {\n var point = points_1[_i];\n if (point.index !== 0) {\n var previous = this.getPreviousIndex(points, point.index - 1, series);\n value = this.getControlPoints(points[previous], point, this.splinePoints[previous], this.splinePoints[point.index], series);\n series.drawPoints.push(value);\n if (point.yValue && value.controlPoint1.y && value.controlPoint2.y) {\n series.yMin = Math.floor(Math.min(series.yMin, point.yValue, value.controlPoint1.y, value.controlPoint2.y));\n series.yMax = Math.ceil(Math.max(series.yMax, point.yValue, value.controlPoint1.y, value.controlPoint2.y));\n }\n }\n }\n }\n };\n SplineBase.prototype.getPreviousIndex = function (points, i, series) {\n if (series.emptyPointSettings.mode !== 'Drop') {\n return i;\n }\n while (isNullOrUndefined(points[i]) && i > -1) {\n i = i - 1;\n }\n return i;\n };\n SplineBase.prototype.getNextIndex = function (points, i, series) {\n if (series.emptyPointSettings.mode !== 'Drop') {\n return i;\n }\n while (isNullOrUndefined(points[i]) && i < points.length) {\n i = i + 1;\n }\n return i;\n };\n SplineBase.prototype.filterEmptyPoints = function (series) {\n if (series.emptyPointSettings.mode !== 'Drop') {\n return series.points;\n }\n var points = extend([], series.points, null, true);\n for (var i = 0; i < points.length; i++) {\n points[i].index = i;\n if (points[i].isEmpty) {\n points[i].symbolLocations = [];\n points[i].regions = [];\n points.splice(i, 1);\n i--;\n }\n }\n return points;\n };\n /**\n * To find the natural spline.\n * @return {void}\n * @private\n */\n SplineBase.prototype.findSplineCoefficients = function (points, series) {\n var count = points.length;\n var ySpline = [];\n var ySplineDuplicate = [];\n var coefficient1;\n var coefficient2;\n var coefficient3;\n var dy1;\n var dy2;\n var dx = [];\n var dy = [];\n var slope = [];\n var interPoint;\n var slopeLength;\n var cardinalSplineTension = series.cardinalSplineTension ? series.cardinalSplineTension : 0.5;\n cardinalSplineTension = cardinalSplineTension < 0 ? 0 : cardinalSplineTension > 1 ? 1 : cardinalSplineTension;\n switch (series.splineType) {\n case 'Monotonic':\n for (var i = 0; i < count - 1; i++) {\n dx[i] = points[i + 1].xValue - points[i].xValue;\n dy[i] = points[i + 1].yValue - points[i].yValue;\n slope[i] = dy[i] / dx[i];\n }\n //interpolant points\n slopeLength = slope.length;\n // to find the first and last co-efficient value\n ySpline[0] = slope[0];\n ySpline[count - 1] = slope[slopeLength - 1];\n //to find the other co-efficient values\n for (var j = 0; j < dx.length; j++) {\n if (slopeLength > j + 1) {\n if (slope[j] * slope[j + 1] <= 0) {\n ySpline[j + 1] = 0;\n }\n else {\n interPoint = dx[j] + dx[j + 1];\n ySpline[j + 1] = 3 * interPoint / ((interPoint + dx[j + 1]) / slope[j] + (interPoint + dx[j]) / slope[j + 1]);\n }\n }\n }\n break;\n case 'Cardinal':\n for (var i = 0; i < count; i++) {\n if (i === 0) {\n ySpline[i] = (count > 2) ? (cardinalSplineTension * (points[i + 2].xValue - points[i].xValue)) : 0;\n }\n else if (i === (count - 1)) {\n ySpline[i] = (count > 2) ? (cardinalSplineTension * (points[count - 1].xValue - points[count - 3].xValue)) : 0;\n }\n else {\n ySpline[i] = (cardinalSplineTension * (points[i + 1].xValue - points[i - 1].xValue));\n }\n }\n break;\n default:\n if (series.splineType === 'Clamped') {\n var firstIndex = (points[1].yValue - points[0].yValue) / (points[1].xValue - points[0].xValue);\n var lastIndex = (points[count - 1].xValue - points[count - 2].xValue) /\n (points[count - 1].yValue - points[count - 2].yValue);\n ySpline[0] = (3 * (points[1].yValue - points[0].yValue)) / (points[1].xValue - points[0].xValue) - 3;\n ySplineDuplicate[0] = 0.5;\n ySpline[points.length - 1] = (3 * (points[points.length - 1].yValue - points[points.length - 2].yValue)) /\n (points[points.length - 1].xValue - points[points.length - 2].xValue);\n ySpline[0] = ySplineDuplicate[0] = Math.abs(ySpline[0]) === Infinity ? 0 : ySpline[0];\n ySpline[points.length - 1] = ySplineDuplicate[points.length - 1] = Math.abs(ySpline[points.length - 1]) === Infinity ?\n 0 : ySpline[points.length - 1];\n }\n else {\n // assigning the first and last value as zero\n ySpline[0] = ySplineDuplicate[0] = 0;\n ySpline[points.length - 1] = 0;\n }\n for (var i = 1; i < count - 1; i++) {\n coefficient1 = points[i].xValue - points[i - 1].xValue;\n coefficient2 = points[i + 1].xValue - points[i - 1].xValue;\n coefficient3 = points[i + 1].xValue - points[i].xValue;\n dy1 = points[i + 1].yValue - points[i].yValue || null;\n dy2 = points[i].yValue - points[i - 1].yValue || null;\n if (coefficient1 === 0 || coefficient2 === 0 || coefficient3 === 0) {\n ySpline[i] = 0;\n ySplineDuplicate[i] = 0;\n }\n else {\n var p = 1 / (coefficient1 * ySpline[i - 1] + 2 * coefficient2);\n ySpline[i] = -p * coefficient3;\n ySplineDuplicate[i] = p * (6 * (dy1 / coefficient3 - dy2 / coefficient1) - coefficient1 * ySplineDuplicate[i - 1]);\n }\n }\n for (var k = count - 2; k >= 0; k--) {\n ySpline[k] = ySpline[k] * ySpline[k + 1] + ySplineDuplicate[k];\n }\n break;\n }\n return ySpline;\n };\n /**\n * To find the control points for spline.\n * @return {void}\n * @private\n */\n SplineBase.prototype.getControlPoints = function (point1, point2, ySpline1, ySpline2, series) {\n var controlPoint1;\n var controlPoint2;\n var point;\n var ySplineDuplicate1 = ySpline1;\n var ySplineDuplicate2 = ySpline2;\n switch (series.splineType) {\n case 'Cardinal':\n if (series.xAxis.valueType === 'DateTime') {\n ySplineDuplicate1 = ySpline1 / this.dateTimeInterval(series);\n ySplineDuplicate2 = ySpline2 / this.dateTimeInterval(series);\n }\n controlPoint1 = new ChartLocation(point1.xValue + ySpline1 / 3, point1.yValue + ySplineDuplicate1 / 3);\n controlPoint2 = new ChartLocation(point2.xValue - ySpline2 / 3, point2.yValue - ySplineDuplicate2 / 3);\n point = new ControlPoints(controlPoint1, controlPoint2);\n break;\n case 'Monotonic':\n var value = (point2.xValue - point1.xValue) / 3;\n controlPoint1 = new ChartLocation(point1.xValue + value, point1.yValue + ySpline1 * value);\n controlPoint2 = new ChartLocation(point2.xValue - value, point2.yValue - ySpline2 * value);\n point = new ControlPoints(controlPoint1, controlPoint2);\n break;\n default:\n var one3 = 1 / 3.0;\n var deltaX2 = (point2.xValue - point1.xValue);\n deltaX2 = deltaX2 * deltaX2;\n var y1 = one3 * (((2 * point1.yValue) + point2.yValue) - one3 * deltaX2 * (ySpline1 + 0.5 * ySpline2));\n var y2 = one3 * ((point1.yValue + (2 * point2.yValue)) - one3 * deltaX2 * (0.5 * ySpline1 + ySpline2));\n controlPoint1 = new ChartLocation((2 * (point1.xValue) + (point2.xValue)) * one3, y1);\n controlPoint2 = new ChartLocation(((point1.xValue) + 2 * (point2.xValue)) * one3, y2);\n point = new ControlPoints(controlPoint1, controlPoint2);\n break;\n }\n return point;\n };\n /**\n * calculate datetime interval in hours\n *\n */\n SplineBase.prototype.dateTimeInterval = function (series) {\n var interval = series.xAxis.actualIntervalType;\n var intervalInMilliseconds;\n if (interval === 'Years') {\n intervalInMilliseconds = 365 * 24 * 60 * 60 * 1000;\n }\n else if (interval === 'Months') {\n intervalInMilliseconds = 30 * 24 * 60 * 60 * 1000;\n }\n else if (interval === 'Days') {\n intervalInMilliseconds = 24 * 60 * 60 * 1000;\n }\n else if (interval === 'Hours') {\n intervalInMilliseconds = 60 * 60 * 1000;\n }\n else if (interval === 'Minutes') {\n intervalInMilliseconds = 60 * 1000;\n }\n else if (interval === 'Seconds') {\n intervalInMilliseconds = 1000;\n }\n else {\n intervalInMilliseconds = 30 * 24 * 60 * 60 * 1000;\n }\n return intervalInMilliseconds;\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n SplineBase.prototype.doAnimation = function (series) {\n var option = series.animation;\n this.doLinearAnimation(series, option);\n };\n return SplineBase;\n}(LineBase));\nexport { SplineBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PathOption, getPoint, withInRange, TransformToVisible } from '../../common/utils/helper';\nimport { SplineBase } from './spline-base';\n/**\n * `SplineSeries` module is used to render the spline series.\n */\nvar SplineSeries = /** @class */ (function (_super) {\n __extends(SplineSeries, _super);\n function SplineSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render the spline series.\n * @return {void}\n * @private\n */\n SplineSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var chart = series.chart;\n var marker = series.marker;\n var ySpline;\n var options;\n var firstPoint = null;\n var secondPoint = null;\n var direction = '';\n var pt1;\n var pt2;\n var bpt1;\n var bpt2;\n var data;\n var controlPointCount = 0;\n var controlPoint1;\n var controlPoint2;\n var startPoint = 'M';\n var points = this.filterEmptyPoints(series);\n var previous;\n var getCoordinate = series.chart.chartAreaType === 'PolarRadar' ? TransformToVisible : getPoint;\n for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {\n var point = points_1[_i];\n previous = this.getPreviousIndex(points, point.index - 1, series);\n point.symbolLocations = [];\n point.regions = [];\n if (point.visible && withInRange(points[previous], point, points[this.getNextIndex(points, point.index - 1, series)], series)) {\n if (firstPoint !== null) {\n data = series.drawPoints[previous];\n controlPoint1 = data.controlPoint1;\n controlPoint2 = data.controlPoint2;\n pt1 = getCoordinate(firstPoint.xValue, firstPoint.yValue, xAxis, yAxis, isInverted, series);\n pt2 = getCoordinate(point.xValue, point.yValue, xAxis, yAxis, isInverted, series);\n bpt1 = getCoordinate(controlPoint1.x, controlPoint1.y, xAxis, yAxis, isInverted, series);\n bpt2 = getCoordinate(controlPoint2.x, controlPoint2.y, xAxis, yAxis, isInverted, series);\n direction = direction.concat((startPoint + ' ' + (pt1.x) + ' ' + (pt1.y) + ' ' + 'C' + ' ' + (bpt1.x) + ' '\n + (bpt1.y) + ' ' + (bpt2.x) + ' ' + (bpt2.y) + ' ' + (pt2.x) + ' ' + (pt2.y) + ' '));\n startPoint = 'L';\n }\n firstPoint = point;\n this.storePointLocation(point, series, isInverted, getCoordinate);\n }\n else {\n startPoint = 'M';\n firstPoint = null;\n point.symbolLocations = [];\n }\n }\n var name = series.category === 'TrendLine' ? series.chart.element.id + '_Series_' + series.sourceIndex + '_TrendLine_' + series.index :\n series.chart.element.id + '_Series_' + series.index;\n options = new PathOption(name, 'transparent', series.width, series.interior, series.opacity, series.dashArray, direction);\n this.appendLinePath(options, series, '');\n this.renderMarker(series);\n };\n /**\n * Get module name.\n */\n SplineSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'SplineSeries';\n };\n /**\n * To destroy the spline.\n * @return {void}\n * @private\n */\n SplineSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n return SplineSeries;\n}(SplineBase));\nexport { SplineSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { sum, PathOption, getPoint, templateAnimate } from '../../common/utils/helper';\nimport { ColumnSeries } from './column-series';\n/**\n * `HistogramSeries` Module used to render the histogram series.\n */\nvar HistogramSeries = /** @class */ (function (_super) {\n __extends(HistogramSeries, _super);\n function HistogramSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Histogram series.\n * @return {void}\n * @private\n */\n HistogramSeries.prototype.render = function (series) {\n _super.prototype.render.call(this, series);\n if (series.showNormalDistribution) {\n this.renderNormalDistribution(series);\n }\n };\n /**\n * To calculate bin interval for Histogram series.\n * @return number\n * @private\n */\n HistogramSeries.prototype.calculateBinInterval = function (yValues, series) {\n var mean = sum(yValues) / yValues.length;\n var sumValue = 0;\n for (var _i = 0, yValues_1 = yValues; _i < yValues_1.length; _i++) {\n var value = yValues_1[_i];\n sumValue += (value - mean) * (value - mean);\n }\n series.histogramValues.mean = mean;\n series.histogramValues.sDValue = Math.round(Math.sqrt(sumValue / yValues.length - 1));\n series.histogramValues.binWidth = series.binInterval ||\n Math.round((3.5 * series.histogramValues.sDValue) / Math.pow(yValues.length, 1 / 3));\n };\n /**\n * Add data points for Histogram series.\n * @return {object[]}\n * @private\n */\n HistogramSeries.prototype.processInternalData = function (data, series) {\n var updatedData = [];\n var yValues = [];\n var binWidth;\n Object.keys(data).forEach(function (key) {\n yValues.push(data[key][series.yName]);\n });\n series.histogramValues = {\n yValues: yValues\n };\n var min = Math.min.apply(Math, series.histogramValues.yValues);\n this.calculateBinInterval(series.histogramValues.yValues, series);\n binWidth = series.histogramValues.binWidth;\n var yCount;\n for (var j = 0; j < data.length;) {\n yCount = yValues.filter(function (y) { return y >= min && y < (min + (binWidth)); }).length;\n updatedData.push((_a = {\n 'x': min + binWidth / 2\n },\n _a[series.yName] = yCount,\n _a));\n min = min + binWidth;\n j += yCount;\n }\n return updatedData;\n var _a;\n };\n /**\n * Render Normal Distribution for Histogram series.\n * @return {void}\n * @private\n */\n HistogramSeries.prototype.renderNormalDistribution = function (series) {\n var min = series.xAxis.actualRange.min;\n var max = series.xAxis.actualRange.max;\n var xValue;\n var pointLocation;\n var yValue;\n var direction = '';\n var startPoint = 'M';\n var yValuesCount = series.histogramValues.yValues.length;\n var binWidth = series.histogramValues.binWidth;\n var mean = series.histogramValues.mean;\n var sDValue = series.histogramValues.sDValue;\n var pointsCount = 500;\n var del = (max - min) / (pointsCount - 1);\n var distributionLine;\n for (var i = 0; i < pointsCount; i++) {\n xValue = min + i * del;\n yValue = Math.exp(-(xValue - mean) * (xValue - mean) / (2 * sDValue * sDValue)) /\n (sDValue * Math.sqrt(2 * Math.PI));\n pointLocation = getPoint(xValue, yValue * binWidth * yValuesCount, series.xAxis, series.yAxis, series.chart.requireInvertedAxis, series);\n direction += startPoint + ' ' + (pointLocation.x) + ' ' + (pointLocation.y) + ' ';\n startPoint = 'L';\n }\n distributionLine = series.chart.renderer.drawPath(new PathOption(series.chart.element.id + '_Series_' + series.index + '_NDLine', 'transparent', 2, series.chart.themeStyle.errorBar, series.opacity, series.dashArray, direction));\n distributionLine.style.visibility = (series.animation.enable && series.chart.animateSeries) ?\n 'hidden' : 'visible';\n series.seriesElement.appendChild(distributionLine);\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n HistogramSeries.prototype.doAnimation = function (series) {\n _super.prototype.doAnimation.call(this, series);\n if (series.showNormalDistribution) {\n templateAnimate(series.seriesElement.lastElementChild, series.animation.duration, 500, 'FadeIn');\n }\n };\n /**\n * Get module name.\n */\n HistogramSeries.prototype.getModuleName = function () {\n return 'HistogramSeries';\n /**\n * return the module name\n */\n };\n /**\n * To destroy the histogram series.\n * @return {void}\n * @private\n */\n HistogramSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return HistogramSeries;\n}(ColumnSeries));\nexport { HistogramSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PathOption, getPoint, withInRange, TransformToVisible } from '../../common/utils/helper';\nimport { SplineBase } from './spline-base';\n/**\n * `SplineAreaSeries` module used to render the spline area series.\n */\nvar SplineAreaSeries = /** @class */ (function (_super) {\n __extends(SplineAreaSeries, _super);\n function SplineAreaSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render the splineArea series.\n * @return {void}\n * @private\n */\n SplineAreaSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var firstPoint = null;\n var direction = '';\n var startPoint = null;\n var startPoint1 = null;\n var pt1;\n var pt2;\n var bpt1;\n var bpt2;\n var controlPt1;\n var controlPt2;\n var points = this.filterEmptyPoints(series);\n var pointsLength = series.points.length;\n var point;\n var previous;\n var getCoordinate = series.chart.chartAreaType === 'PolarRadar' ? TransformToVisible : getPoint;\n var origin = series.chart.chartAreaType === 'PolarRadar' ? series.points[0].yValue :\n Math.max(series.yAxis.visibleRange.min, 0);\n for (var i = 0; i < pointsLength; i++) {\n point = series.points[i];\n point.symbolLocations = [];\n point.regions = [];\n previous = this.getPreviousIndex(points, point.index - 1, series);\n if (point.visible &&\n withInRange(points[previous], point, points[this.getNextIndex(points, point.index - 1, series)], series)) {\n if (firstPoint) {\n controlPt1 = series.drawPoints[previous].controlPoint1;\n controlPt2 = series.drawPoints[previous].controlPoint2;\n pt1 = getCoordinate(firstPoint.xValue, firstPoint.yValue, xAxis, yAxis, isInverted, series);\n pt2 = getCoordinate(point.xValue, point.yValue, xAxis, yAxis, isInverted, series);\n bpt1 = getCoordinate(controlPt1.x, controlPt1.y, xAxis, yAxis, isInverted, series);\n bpt2 = getCoordinate(controlPt2.x, controlPt2.y, xAxis, yAxis, isInverted, series);\n direction = direction.concat(' C' + bpt1.x + ' '\n + bpt1.y + ' ' + bpt2.x + ' ' + bpt2.y + ' ' + pt2.x + ' ' + pt2.y + ' ');\n }\n else {\n // Start point for the current path\n startPoint = getCoordinate(point.xValue, origin, xAxis, yAxis, isInverted, series);\n direction += ('M ' + startPoint.x + ' ' + startPoint.y + ' ');\n // First Point to draw the area path\n startPoint1 = getCoordinate(point.xValue, point.yValue, xAxis, yAxis, isInverted, series);\n direction += ('L ' + startPoint1.x + ' ' + startPoint1.y + ' ');\n }\n this.storePointLocation(point, series, isInverted, getCoordinate);\n firstPoint = point;\n }\n else {\n firstPoint = null;\n point.symbolLocations = [];\n }\n if (((i + 1 < pointsLength && !series.points[i + 1].visible) || i === pointsLength - 1)\n && pt2 && startPoint) {\n startPoint = getCoordinate(point.xValue, origin, xAxis, yAxis, isInverted, series);\n direction = direction.concat('L ' + (startPoint.x) + ' ' + (startPoint.y));\n }\n }\n this.appendLinePath(new PathOption(series.chart.element.id + '_Series_' + series.index, series.interior, series.border.width, series.border.color, series.opacity, series.dashArray, direction), series, '');\n this.renderMarker(series);\n };\n /**\n * Get module name.\n */\n SplineAreaSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'SplineAreaSeries';\n };\n /**\n * To destroy the spline.\n * @return {void}\n * @private\n */\n SplineAreaSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n return SplineAreaSeries;\n}(SplineBase));\nexport { SplineAreaSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { LineBase } from '../series/line-base';\nimport { Series, Points } from '../series/chart-series';\nimport { RectOption, Rect } from '../../common/utils/helper';\nimport { findClipRect } from '../../common/utils/helper';\n/**\n * Technical Analysis module helps to predict the market trend\n */\nvar TechnicalAnalysis = /** @class */ (function (_super) {\n __extends(TechnicalAnalysis, _super);\n function TechnicalAnalysis() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the collection of series, that are used to represent the given technical indicator\n * @private\n */\n TechnicalAnalysis.prototype.initSeriesCollection = function (indicator, chart) {\n indicator.targetSeries = [];\n var signalLine = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(signalLine, indicator, 'SignalLine', indicator.fill, indicator.width, chart);\n };\n /**\n * Initializes the properties of the given series\n * @private\n */\n TechnicalAnalysis.prototype.setSeriesProperties = function (series, indicator, name, fill, width, chart) {\n series.name = name;\n series.xName = 'x';\n series.yName = 'y';\n series.fill = fill || '#606eff';\n series.dashArray = indicator.dashArray;\n series.width = width;\n series.xAxisName = indicator.xAxisName;\n series.animation = indicator.animation;\n series.yAxisName = indicator.yAxisName;\n series.clipRectElement = indicator.clipRectElement;\n series.points = [];\n series.enableTooltip = true;\n series.interior = series.fill;\n series.category = 'Indicator';\n series.index = indicator.index;\n series.chart = chart;\n series.xMin = Infinity;\n series.xMax = -Infinity;\n series.yMin = Infinity;\n series.yMax = -Infinity;\n series.xData = [];\n series.yData = [];\n series.marker.visible = false;\n indicator.targetSeries.push(series);\n };\n /**\n * Creates the elements of a technical indicator\n * @private\n */\n TechnicalAnalysis.prototype.createIndicatorElements = function (chart, indicator, index) {\n if (indicator.seriesName || indicator.dataSource) {\n findClipRect(indicator.targetSeries[0]);\n }\n var clipRect = new Rect(0, 0, 0, 0);\n if (indicator.seriesName || indicator.dataSource) {\n clipRect = indicator.targetSeries[0].clipRect;\n }\n //defines the clip rect element\n var clipRectElement = chart.renderer.drawClipPath(new RectOption(chart.element.id + '_ChartIndicatorClipRect_' + index, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: 0, y: 0, width: clipRect.width,\n height: clipRect.height,\n }));\n //creates the group for an indicator\n indicator.indicatorElement = chart.renderer.createGroup({\n 'id': chart.element.id + 'IndicatorGroup' + index,\n 'transform': 'translate(' + clipRect.x + ',' + clipRect.y + ')',\n 'clip-path': 'url(#' + chart.element.id + '_ChartIndicatorClipRect_' + index + ')'\n });\n indicator.indicatorElement.appendChild(clipRectElement);\n //Defines a group for each series in a technical indicator\n for (var _i = 0, _a = indicator.targetSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n series.clipRectElement = clipRectElement;\n var element = series.chart.renderer.createGroup({\n 'id': series.chart.element.id + '_Indicator_' +\n indicator.index + '_' + series.name + '_Group'\n });\n indicator.indicatorElement.appendChild(element);\n series.seriesElement = element;\n }\n chart.indicatorElements.appendChild(indicator.indicatorElement);\n };\n TechnicalAnalysis.prototype.getDataPoint = function (x, y, sourcePoint, series, index, indicator) {\n if (indicator === void 0) { indicator = null; }\n var point = new Points();\n point.x = x;\n point.y = y;\n point.xValue = sourcePoint.xValue;\n point.color = series.fill;\n point.index = index;\n point.yValue = y;\n point.visible = true;\n series.xMin = Math.min(series.xMin, point.xValue);\n series.yMin = Math.min(series.yMin, point.yValue);\n series.xMax = Math.max(series.xMax, point.xValue);\n series.yMax = Math.max(series.yMax, point.yValue);\n series.xData.push(point.xValue);\n if (indicator && indicator.type === 'Macd' && series.type === 'Column') {\n if (point.y >= 0) {\n point.color = indicator.macdPositiveColor;\n }\n else {\n point.color = indicator.macdNegativeColor;\n }\n }\n return point;\n };\n TechnicalAnalysis.prototype.getRangePoint = function (x, high, low, sourcePoint, series, index, indicator) {\n if (indicator === void 0) { indicator = null; }\n var point = new Points();\n point.x = x;\n point.high = high;\n point.low = low;\n point.xValue = sourcePoint.xValue;\n point.color = series.fill;\n point.index = index;\n point.visible = true;\n series.xData.push(point.xValue);\n return point;\n };\n TechnicalAnalysis.prototype.setSeriesRange = function (points, indicator, series) {\n if (series === void 0) { series = null; }\n if (!series) {\n indicator.targetSeries[0].points = points;\n }\n else {\n series.points = points;\n }\n };\n return TechnicalAnalysis;\n}(LineBase));\nexport { TechnicalAnalysis };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { firstToLowerCase } from '../../common/utils/helper';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `SmaIndicator` module is used to render SMA indicator.\n */\nvar SmaIndicator = /** @class */ (function (_super) {\n __extends(SmaIndicator, _super);\n function SmaIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the predictions based on SMA approach\n * @private\n */\n SmaIndicator.prototype.initDataSource = function (indicator, chart) {\n var smaPoints = [];\n var points = indicator.points;\n if (points && points.length) {\n //prepare data\n var validData = points;\n var field = firstToLowerCase(indicator.field);\n var xField = 'x';\n var signalSeries = indicator.targetSeries[0];\n if (validData && validData.length && validData.length >= indicator.period) {\n //find initial average\n var average = 0;\n var sum = 0;\n for (var i = 0; i < indicator.period; i++) {\n sum += validData[i][field];\n }\n average = sum / indicator.period;\n smaPoints.push(this.getDataPoint(validData[indicator.period - 1][xField], average, validData[indicator.period - 1], signalSeries, smaPoints.length));\n var index = indicator.period;\n while (index < validData.length) {\n sum -= validData[index - indicator.period][field];\n sum += validData[index][field];\n average = sum / indicator.period;\n smaPoints.push(this.getDataPoint(validData[index][xField], average, validData[index], signalSeries, smaPoints.length));\n index++;\n }\n }\n this.setSeriesRange(smaPoints, indicator);\n }\n };\n /**\n * To destroy the SMA indicator\n * @return {void}\n * @private\n */\n SmaIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the SMA indicator\n */\n };\n /**\n * Get module name.\n */\n SmaIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'SmaIndicator';\n };\n return SmaIndicator;\n}(TechnicalAnalysis));\nexport { SmaIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { firstToLowerCase } from '../../common/utils/helper';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `EmaIndicator` module is used to render EMA indicator.\n */\nvar EmaIndicator = /** @class */ (function (_super) {\n __extends(EmaIndicator, _super);\n function EmaIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the predictions based on EMA approach\n * @private\n */\n EmaIndicator.prototype.initDataSource = function (indicator, chart) {\n var field = firstToLowerCase(indicator.field);\n var xField = 'x';\n var emaPoints = [];\n var signalSeries = indicator.targetSeries[0];\n //prepare data\n var validData = indicator.points;\n if (validData && validData.length && validData.length >= indicator.period) {\n //find initial average\n var sum = 0;\n var average = 0;\n //smoothing factor\n var k = (2 / (indicator.period + 1));\n for (var i = 0; i < indicator.period; i++) {\n sum += validData[i][field];\n }\n average = sum / indicator.period;\n emaPoints.push(this.getDataPoint(validData[indicator.period - 1][xField], average, validData[indicator.period - 1], signalSeries, emaPoints.length));\n var index = indicator.period;\n while (index < validData.length) {\n //previous average\n var prevAverage = emaPoints[index - indicator.period][signalSeries.yName];\n var yValue = (validData[index][field] - prevAverage) * k + prevAverage;\n emaPoints.push(this.getDataPoint(validData[index][xField], yValue, validData[index], signalSeries, emaPoints.length));\n index++;\n }\n }\n this.setSeriesRange(emaPoints, indicator);\n };\n /**\n * To destroy the EMA Indicator\n * @return {void}\n * @private\n */\n EmaIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the EMA Indicator\n */\n };\n /**\n * Get module name.\n */\n EmaIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'EmaIndicator';\n };\n return EmaIndicator;\n}(TechnicalAnalysis));\nexport { EmaIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { firstToLowerCase } from '../../common/utils/helper';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `TmaIndicator` module is used to render TMA indicator.\n */\nvar TmaIndicator = /** @class */ (function (_super) {\n __extends(TmaIndicator, _super);\n function TmaIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the predictions based on TMA approach\n * @private\n */\n TmaIndicator.prototype.initDataSource = function (indicator, chart) {\n var tmaPoints = [];\n var field = firstToLowerCase(indicator.field);\n var xField = 'x';\n var signalSeries = indicator.targetSeries[0];\n //prepare data\n var validData = indicator.points;\n if (validData && validData.length && validData.length >= indicator.period) {\n var signalSeries_1 = indicator.targetSeries[0];\n //prepare data\n var validData_1 = indicator.points;\n if (validData_1.length && validData_1.length >= indicator.period) {\n //smoothing factor\n var k = (2 / (indicator.period + 1));\n //find initial average\n var average = 0;\n var sum = 0;\n var sumOfSMA = 0;\n var averageSMA = 0;\n var smaValues = [];\n //sma values\n var index = 0;\n var length_1 = validData_1.length;\n var period = indicator.period;\n while (length_1 >= period) {\n sum = 0;\n index = validData_1.length - length_1;\n for (var j = index; j < index + period; j++) {\n sum = sum + validData_1[j][field];\n }\n sum = sum / period;\n smaValues.push(sum);\n length_1--;\n }\n //initial values\n for (var k_1 = 0; k_1 < period - 1; k_1++) {\n sum = 0;\n for (var j = 0; j < k_1 + 1; j++) {\n sum = sum + validData_1[j][field];\n }\n sum = sum / (k_1 + 1);\n smaValues.splice(k_1, 0, sum);\n }\n index = indicator.period;\n while (index <= smaValues.length) {\n sum = 0;\n for (var j = index - indicator.period; j < index; j++) {\n sum = sum + smaValues[j];\n }\n sum = sum / indicator.period;\n tmaPoints.push(this.getDataPoint(validData_1[index - 1][xField], sum, validData_1[index - 1], signalSeries_1, tmaPoints.length));\n index++;\n }\n }\n }\n this.setSeriesRange(tmaPoints, indicator);\n };\n /**\n * To destroy the TMA indicator.\n * @return {void}\n * @private\n */\n TmaIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the TMA Indicator\n */\n };\n /**\n * Get module name.\n */\n TmaIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'TmaIndicator';\n };\n return TmaIndicator;\n}(TechnicalAnalysis));\nexport { TmaIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `AccumulationDistributionIndicator` module is used to render accumulation distribution indicator.\n */\nvar AccumulationDistributionIndicator = /** @class */ (function (_super) {\n __extends(AccumulationDistributionIndicator, _super);\n function AccumulationDistributionIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the predictions using accumulation distribution approach\n * @private\n */\n AccumulationDistributionIndicator.prototype.initDataSource = function (indicator, chart) {\n var sourceSeries = indicator.sourceSeries;\n var adPoints = [];\n var validData = indicator.points;\n if (validData.length > 0 && validData.length > indicator.period) {\n adPoints = this.calculateADPoints(indicator, validData);\n }\n this.setSeriesRange(adPoints, indicator);\n };\n /**\n * Calculates the Accumulation Distribution values\n * @private\n */\n AccumulationDistributionIndicator.prototype.calculateADPoints = function (indicator, validData) {\n var temp = [];\n var sum = 0;\n var i = 0;\n var value = 0;\n var high = 0;\n var low = 0;\n var close = 0;\n var signalSeries = indicator.targetSeries[0];\n for (i = 0; i < validData.length; i++) {\n high = Number(validData[i].high);\n low = Number(validData[i].low);\n close = Number(validData[i].close);\n /**\n * Money Flow Multiplier = [(Close - Low) - (High - Close)] /(High - Low)\n * Money Flow Volume = Money Flow Multiplier x Volume for the Period\n * ADL = Previous ADL + Current Period's Money Flow Volume\n */\n value = ((close - low) - (high - close)) / (high - low);\n /**\n * Sum is to calculate the Y values of the Accumulation distribution indicator\n */\n sum = sum + value * Number(validData[i].volume);\n /**\n * To calculate the x and y values for the Accumulation distribution indicator\n */\n temp[i] = this.getDataPoint(validData[i].x, sum, validData[i], signalSeries, temp.length);\n }\n return temp;\n };\n /**\n * To destroy the Accumulation Distribution Technical Indicator.\n * @return {void}\n * @private\n */\n AccumulationDistributionIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the Accumulation Distribution Technical indicator\n */\n };\n /**\n * Get module name.\n */\n AccumulationDistributionIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the Indicator\n */\n return 'AccumulationDistributionIndicator';\n };\n return AccumulationDistributionIndicator;\n}(TechnicalAnalysis));\nexport { AccumulationDistributionIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `AtrIndicator` module is used to render ATR indicator.\n */\nvar AtrIndicator = /** @class */ (function (_super) {\n __extends(AtrIndicator, _super);\n function AtrIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the predictions using Average True Range approach\n * @private\n */\n AtrIndicator.prototype.initDataSource = function (indicator, chart) {\n var sourceSeries = indicator.sourceSeries;\n var atrPoints = [];\n var validData = indicator.points;\n if (validData.length > 0 && validData.length > indicator.period) {\n this.calculateATRPoints(indicator, validData);\n }\n };\n /**\n * To calculate Average True Range indicator points\n * @private\n */\n AtrIndicator.prototype.calculateATRPoints = function (indicator, validData) {\n var average = 0;\n var highLow = 0;\n var highClose = 0;\n var lowClose = 0;\n var trueRange = 0;\n var points = [];\n var temp = [];\n var period = indicator.period;\n var sum = 0;\n var y = 'y';\n var signalSeries = indicator.targetSeries[0];\n for (var i = 0; i < validData.length; i++) {\n /**\n * Current High less the current Low\n * Current High less the previous Close (absolute value)\n * Current Low less the previous Close (absolute value)\n */\n highLow = Number(validData[i].high) - Number(validData[i].low);\n if (i > 0) {\n //\n highClose = Math.abs(Number(validData[i].high) - Number(validData[i - 1].close));\n lowClose = Math.abs(Number(validData[i].low) - Number(validData[i - 1].close));\n }\n /**\n * To find the maximum of highLow, highClose, lowClose\n */\n trueRange = Math.max(highLow, highClose, lowClose);\n sum = sum + trueRange;\n /**\n * Push the x and y values for the Average true range indicator\n */\n if (i >= period) {\n average = (Number(temp[i - 1][y]) * (period - 1) + trueRange) / period;\n points.push(this.getDataPoint(validData[i].x, average, validData[i], signalSeries, points.length));\n }\n else {\n average = sum / period;\n if (i === period - 1) {\n points.push(this.getDataPoint(validData[i].x, average, validData[i], signalSeries, points.length));\n }\n }\n temp[i] = { x: validData[i].x, y: average };\n }\n this.setSeriesRange(points, indicator);\n };\n /**\n * To destroy the Average true range indicator.\n * @return {void}\n * @private\n */\n AtrIndicator.prototype.destroy = function (chart) {\n /**\n * Destroy the Average true range indicator\n */\n };\n /**\n * Get module name.\n */\n AtrIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the Indicator\n */\n return 'AtrIndicator';\n };\n return AtrIndicator;\n}(TechnicalAnalysis));\nexport { AtrIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Series } from '../series/chart-series';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `MomentumIndicator` module is used to render Momentum indicator.\n */\nvar MomentumIndicator = /** @class */ (function (_super) {\n __extends(MomentumIndicator, _super);\n function MomentumIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the collection of series to represent a momentum indicator\n * @private\n */\n MomentumIndicator.prototype.initSeriesCollection = function (indicator, chart) {\n _super.prototype.initSeriesCollection.call(this, indicator, chart);\n var upperLine = new Series(indicator, 'targetSeries', {}, true);\n _super.prototype.setSeriesProperties.call(this, upperLine, indicator, 'UpperLine', indicator.upperLine.color, indicator.upperLine.width, chart);\n };\n /**\n * Defines the predictions using momentum approach\n * @private\n */\n MomentumIndicator.prototype.initDataSource = function (indicator, chart) {\n var upperCollection = [];\n var signalCollection = [];\n var validData = indicator.points;\n if (validData && validData.length) {\n var upperSeries = indicator.targetSeries[1];\n var signalSeries = indicator.targetSeries[0];\n var length_1 = indicator.period;\n if (validData.length >= indicator.period) {\n for (var i = 0; i < validData.length; i++) {\n upperCollection.push(this.getDataPoint(validData[i].x, 100, validData[i], upperSeries, upperCollection.length));\n if (!(i < length_1)) {\n signalCollection.push(this.getDataPoint(validData[i].x, (Number(validData[i].close) / Number(validData[i - length_1].close) * 100), validData[i], signalSeries, signalCollection.length));\n }\n }\n }\n this.setSeriesRange(signalCollection, indicator, indicator.targetSeries[0]);\n this.setSeriesRange(upperCollection, indicator, indicator.targetSeries[1]);\n }\n };\n /**\n * To destroy the momentum indicator\n * @return {void}\n * @private\n */\n MomentumIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the momentum indicator\n */\n };\n /**\n * Get module name.\n */\n MomentumIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'MomentumIndicator';\n };\n return MomentumIndicator;\n}(TechnicalAnalysis));\nexport { MomentumIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Series } from '../series/chart-series';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `RsiIndicator` module is used to render RSI indicator.\n */\nvar RsiIndicator = /** @class */ (function (_super) {\n __extends(RsiIndicator, _super);\n function RsiIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Initializes the series collection to represent the RSI Indicator\n * @private\n */\n RsiIndicator.prototype.initSeriesCollection = function (indicator, chart) {\n _super.prototype.initSeriesCollection.call(this, indicator, chart);\n if (indicator.showZones) {\n var lowerLine = new Series(indicator, 'targetSeries', {}, true);\n _super.prototype.setSeriesProperties.call(this, lowerLine, indicator, 'LowerLine', indicator.lowerLine.color, indicator.lowerLine.width, chart);\n var upperLine = new Series(indicator, 'targetSeries', {}, true);\n _super.prototype.setSeriesProperties.call(this, upperLine, indicator, 'UpperLine', indicator.upperLine.color, indicator.upperLine.width, chart);\n }\n };\n /**\n * Defines the predictions using RSI approach\n * @private\n */\n RsiIndicator.prototype.initDataSource = function (indicator, chart) {\n var signalCollection = [];\n var lowerCollection = [];\n var upperCollection = [];\n var signalSeries = indicator.targetSeries[0];\n //prepare data\n var validData = indicator.points;\n if (validData.length && validData.length >= indicator.period) {\n //Find upper band and lower band values\n if (indicator.showZones) {\n for (var i = 0; i < validData.length; i++) {\n upperCollection.push(this.getDataPoint(validData[i].x, indicator.overBought, validData[i], indicator.targetSeries[1], upperCollection.length));\n lowerCollection.push(this.getDataPoint(validData[i].x, indicator.overSold, validData[i], indicator.targetSeries[2], lowerCollection.length));\n }\n }\n //Find signal line value\n var prevClose = Number(validData[0].close);\n var gain = 0;\n var loss = 0;\n for (var i = 1; i <= indicator.period; i++) {\n var close_1 = Number(validData[i].close);\n if (close_1 > prevClose) {\n gain += close_1 - prevClose;\n }\n else {\n loss += prevClose - close_1;\n }\n prevClose = close_1;\n }\n gain = gain / indicator.period;\n loss = loss / indicator.period;\n signalCollection.push(this.getDataPoint(validData[indicator.period].x, 100 - (100 / (1 + gain / loss)), validData[indicator.period], signalSeries, signalCollection.length));\n for (var j = indicator.period + 1; j < validData.length; j++) {\n var close_2 = Number(validData[j].close);\n if (close_2 > prevClose) {\n gain = (gain * (indicator.period - 1) + (close_2 - prevClose)) / indicator.period;\n loss = (loss * (indicator.period - 1)) / indicator.period;\n }\n else if (close_2 < prevClose) {\n loss = (loss * (indicator.period - 1) + (prevClose - close_2)) / indicator.period;\n gain = (gain * (indicator.period - 1)) / indicator.period;\n }\n prevClose = close_2;\n signalCollection.push(this.getDataPoint(validData[j].x, 100 - (100 / (1 + gain / loss)), validData[j], signalSeries, signalCollection.length));\n }\n }\n this.setSeriesRange(signalCollection, indicator, indicator.targetSeries[0]);\n if (indicator.showZones) {\n this.setSeriesRange(upperCollection, indicator, indicator.targetSeries[1]);\n this.setSeriesRange(lowerCollection, indicator, indicator.targetSeries[2]);\n }\n };\n /**\n * To destroy the RSI Indicator.\n * @return {void}\n * @private\n */\n RsiIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the RSI Indicator\n */\n };\n /**\n * Get module name.\n */\n RsiIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the indicator.\n */\n return 'RsiIndicator';\n };\n return RsiIndicator;\n}(TechnicalAnalysis));\nexport { RsiIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Series } from '../series/chart-series';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `StochasticIndicator` module is used to render stochastic indicator.\n */\nvar StochasticIndicator = /** @class */ (function (_super) {\n __extends(StochasticIndicator, _super);\n function StochasticIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the collection of series that represents the stochastic indicator\n * @private\n */\n StochasticIndicator.prototype.initSeriesCollection = function (indicator, chart) {\n _super.prototype.initSeriesCollection.call(this, indicator, chart);\n var periodLine = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(periodLine, indicator, 'PeriodLine', indicator.periodLine.color, indicator.periodLine.width, chart);\n if (indicator.showZones) {\n var upperSeries = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(upperSeries, indicator, 'UpperLine', indicator.upperLine.color, indicator.upperLine.width, chart);\n var lowerSeries = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(lowerSeries, indicator, 'LowerLine', indicator.lowerLine.color, indicator.lowerLine.width, chart);\n }\n };\n /**\n * Defines the predictions based on stochastic approach\n * @private\n */\n StochasticIndicator.prototype.initDataSource = function (indicator, chart) {\n var signalCollection = [];\n var upperCollection = [];\n var lowerCollection = [];\n var periodCollection = [];\n var source = [];\n var sourceSeries = indicator.sourceSeries;\n var point = {};\n //prepare data\n var validData = indicator.points;\n if (validData.length && validData.length >= indicator.period) {\n if (indicator.showZones) {\n for (var i = 0; i < validData.length; i++) {\n upperCollection.push(this.getDataPoint(validData[i].x, indicator.overBought, validData[i], indicator.targetSeries[2], upperCollection.length));\n lowerCollection.push(this.getDataPoint(validData[i].x, indicator.overSold, validData[i], indicator.targetSeries[3], lowerCollection.length));\n }\n }\n source = this.calculatePeriod(indicator.period, indicator.kPeriod, validData, indicator.targetSeries[1]);\n periodCollection = this.smaCalculation(indicator.period, indicator.kPeriod, source, indicator.targetSeries[1]);\n signalCollection = this.smaCalculation(indicator.period + indicator.kPeriod - 1, indicator.dPeriod, source, indicator.targetSeries[0]);\n }\n this.setSeriesRange(signalCollection, indicator, indicator.targetSeries[0]);\n this.setSeriesRange(periodCollection, indicator, indicator.targetSeries[1]);\n if (indicator.showZones) {\n this.setSeriesRange(upperCollection, indicator, indicator.targetSeries[2]);\n this.setSeriesRange(lowerCollection, indicator, indicator.targetSeries[3]);\n }\n };\n /**\n * Calculates the SMA Values\n * @private\n */\n StochasticIndicator.prototype.smaCalculation = function (period, kPeriod, data, sourceSeries) {\n var pointCollection = [];\n if (data.length >= period + kPeriod) {\n var count = period + (kPeriod - 1);\n var temp = [];\n var values = [];\n for (var i = 0; i < data.length; i++) {\n var value = Number(data[i].y);\n temp.push(value);\n }\n var length_1 = temp.length;\n while (length_1 >= count) {\n var sum = 0;\n for (var i = period - 1; i < (period + kPeriod - 1); i++) {\n sum = sum + temp[i];\n }\n sum = sum / kPeriod;\n values.push(sum.toFixed(2));\n temp.splice(0, 1);\n length_1 = temp.length;\n }\n var len = count - 1;\n for (var i = 0; i < data.length; i++) {\n if (!(i < len)) {\n pointCollection.push(this.getDataPoint(data[i].x, Number(values[i - len]), data[i], sourceSeries, pointCollection.length));\n data[i].y = Number((values[i - len]));\n }\n }\n }\n return pointCollection;\n };\n /**\n * Calculates the period line values.\n * @private\n */\n StochasticIndicator.prototype.calculatePeriod = function (period, kPeriod, data, series) {\n var lowValues = [];\n var highValues = [];\n var closeValues = [];\n var modifiedSource = [];\n for (var j = 0; j < data.length; j++) {\n lowValues[j] = data[j].low;\n highValues[j] = data[j].high;\n closeValues[j] = data[j].close;\n }\n if (data.length > period) {\n var totalPeriod = period + kPeriod;\n var mins = [];\n var maxs = [];\n for (var i = 0; i < period - 1; ++i) {\n maxs.push(0);\n mins.push(0);\n modifiedSource.push(this.getDataPoint(data[i].x, data[i].close, data[i], series, modifiedSource.length));\n }\n for (var i = period - 1; i < data.length; ++i) {\n var min = Number.MAX_VALUE;\n var max = Number.MIN_VALUE;\n for (var j = 0; j < period; ++j) {\n min = Math.min(min, lowValues[i - j]);\n max = Math.max(max, highValues[i - j]);\n }\n maxs.push(max);\n mins.push(min);\n }\n for (var i = period - 1; i < data.length; ++i) {\n var top_1 = 0;\n var bottom = 0;\n top_1 += closeValues[i] - mins[i];\n bottom += maxs[i] - mins[i];\n modifiedSource.push(this.getDataPoint(data[i].x, (top_1 / bottom) * 100, data[i], series, modifiedSource.length));\n }\n }\n return modifiedSource;\n };\n /**\n * To destroy the Stocastic Indicator.\n * @return {void}\n * @private\n */\n StochasticIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the stochastic indicator\n */\n };\n /**\n * Get module name.\n */\n StochasticIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the indicator.\n */\n return 'StochasticIndicator';\n };\n return StochasticIndicator;\n}(TechnicalAnalysis));\nexport { StochasticIndicator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Series } from '../series/chart-series';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `BollingerBands` module is used to render bollinger band indicator.\n */\nvar BollingerBands = /** @class */ (function (_super) {\n __extends(BollingerBands, _super);\n function BollingerBands() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Initializes the series collection to represent bollinger band\n */\n BollingerBands.prototype.initSeriesCollection = function (indicator, chart) {\n indicator.targetSeries = [];\n var rangeArea = new Series(indicator, 'targetSeries', {}, true);\n rangeArea.type = 'RangeArea';\n if (indicator.bandColor !== 'transparent' && indicator.bandColor !== 'none') {\n this.setSeriesProperties(rangeArea, indicator, 'BollingerBand', indicator.bandColor, 0, chart);\n }\n var signalLine = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(signalLine, indicator, 'SignalLine', indicator.fill, indicator.width, chart);\n var upperLine = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(upperLine, indicator, 'UpperLine', indicator.upperLine.color, indicator.upperLine.width, chart);\n var lowerLine = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(lowerLine, indicator, 'LowerLine', indicator.lowerLine.color, indicator.lowerLine.width, chart);\n };\n /**\n * Defines the predictions using Bollinger Band Approach\n * @private\n */\n BollingerBands.prototype.initDataSource = function (indicator, chart) {\n var enableBand = indicator.bandColor !== 'transparent' && indicator.bandColor !== 'none';\n var start = enableBand ? 1 : 0;\n var signalCollection = [];\n var upperCollection = [];\n var lowerCollection = [];\n var bandCollection = [];\n var upperSeries = indicator.targetSeries[start + 1];\n var lowerSeries = indicator.targetSeries[start + 2];\n var signalSeries = indicator.targetSeries[start];\n var rangeAreaSeries = enableBand ? indicator.targetSeries[0] : null;\n //prepare data\n var validData = indicator.points;\n if (validData.length && validData.length >= indicator.period) {\n var sum = 0;\n var deviationSum = 0;\n var multiplier = indicator.standardDeviation;\n var limit = validData.length;\n var length_1 = Math.round(indicator.period);\n var smaPoints = [];\n var deviations = [];\n var bollingerPoints = [];\n for (var i_1 = 0; i_1 < length_1; i_1++) {\n sum += Number(validData[i_1].close);\n }\n var sma = sum / indicator.period;\n for (var i_2 = 0; i_2 < limit; i_2++) {\n var y = Number(validData[i_2].close);\n if (i_2 >= length_1 - 1 && i_2 < limit) {\n if (i_2 - indicator.period >= 0) {\n var diff = y - Number(validData[i_2 - length_1].close);\n sum = sum + diff;\n sma = sum / (indicator.period);\n smaPoints[i_2] = sma;\n deviations[i_2] = Math.pow(y - sma, 2);\n deviationSum += deviations[i_2] - deviations[i_2 - length_1];\n }\n else {\n smaPoints[i_2] = sma;\n deviations[i_2] = Math.pow(y - sma, 2);\n deviationSum += deviations[i_2];\n }\n var range = Math.sqrt(deviationSum / (indicator.period));\n var lowerBand = smaPoints[i_2] - (multiplier * range);\n var upperBand = smaPoints[i_2] + (multiplier * range);\n if (i_2 + 1 === length_1) {\n for (var j_1 = 0; j_1 < length_1 - 1; j_1++) {\n bollingerPoints[j_1] = {\n 'X': validData[j_1].x, 'mb': smaPoints[i_2],\n 'lb': lowerBand, 'ub': upperBand, visible: true\n };\n }\n }\n bollingerPoints[i_2] = {\n 'X': validData[i_2].x, 'mb': smaPoints[i_2],\n 'lb': lowerBand, 'ub': upperBand, visible: true\n };\n }\n else {\n if (i_2 < indicator.period - 1) {\n smaPoints[i_2] = sma;\n deviations[i_2] = Math.pow(y - sma, 2);\n deviationSum += deviations[i_2];\n }\n }\n }\n var i = -1;\n var j = -1;\n for (var k = 0; k < limit; k++) {\n if (k >= (length_1 - 1)) {\n var ub = 'ub';\n var lb = 'lb';\n var mb = 'mb';\n upperCollection.push(this.getDataPoint(validData[k].x, bollingerPoints[k][ub], validData[k], upperSeries, upperCollection.length));\n lowerCollection.push(this.getDataPoint(validData[k].x, bollingerPoints[k][lb], validData[k], lowerSeries, lowerCollection.length));\n signalCollection.push(this.getDataPoint(validData[k].x, bollingerPoints[k][mb], validData[k], signalSeries, signalCollection.length));\n if (enableBand) {\n bandCollection.push(this.getRangePoint(validData[k].x, upperCollection[++i].y, lowerCollection[++j].y, validData[k], rangeAreaSeries, bandCollection.length));\n }\n }\n }\n }\n if (enableBand) {\n this.setSeriesRange(bandCollection, indicator, indicator.targetSeries[0]);\n }\n this.setSeriesRange(signalCollection, indicator, indicator.targetSeries[start]);\n this.setSeriesRange(upperCollection, indicator, indicator.targetSeries[start + 1]);\n this.setSeriesRange(lowerCollection, indicator, indicator.targetSeries[start + 2]);\n };\n /**\n * To destroy the Bollinger Band.\n * @return {void}\n * @private\n */\n BollingerBands.prototype.destroy = function (chart) {\n /**\n * Destroys the bollinger band\n */\n };\n /**\n * Get module name.\n */\n BollingerBands.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'BollingerBandsIndicator';\n };\n return BollingerBands;\n}(TechnicalAnalysis));\nexport { BollingerBands };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Series } from '../series/chart-series';\nimport { TechnicalAnalysis } from './indicator-base';\n/**\n * `MacdIndicator` module is used to render MACD indicator.\n */\nvar MacdIndicator = /** @class */ (function (_super) {\n __extends(MacdIndicator, _super);\n function MacdIndicator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the collection of series to represent the MACD indicator\n * @private\n */\n MacdIndicator.prototype.initSeriesCollection = function (indicator, chart) {\n _super.prototype.initSeriesCollection.call(this, indicator, chart);\n if (indicator.macdType === 'Line' || indicator.macdType === 'Both') {\n var macdSeries = new Series(indicator, 'targetSeries', {}, true);\n this.setSeriesProperties(macdSeries, indicator, 'MacdLine', indicator.macdLine.color, indicator.macdLine.width, chart);\n }\n if (indicator.macdType === 'Histogram' || indicator.macdType === 'Both') {\n var histogramSeries = new Series(indicator, 'targetSeries', {}, true);\n histogramSeries.type = 'Column';\n this.setSeriesProperties(histogramSeries, indicator, 'Histogram', indicator.macdPositiveColor, indicator.width, chart);\n }\n };\n /**\n * Defines the predictions using MACD approach\n * @private\n */\n MacdIndicator.prototype.initDataSource = function (indicator, chart) {\n var signalCollection = [];\n var fastPeriod = indicator.fastPeriod;\n var slowPeriod = indicator.slowPeriod;\n var trigger = indicator.period;\n var length = fastPeriod + trigger;\n var macdCollection = [];\n var histogramCollection = [];\n var validData = indicator.points;\n var signalSeries = indicator.targetSeries[0];\n var histogramSeries;\n var macdLineSeries;\n if (indicator.macdType === 'Histogram') {\n histogramSeries = indicator.targetSeries[1];\n }\n else {\n macdLineSeries = indicator.targetSeries[1];\n if (indicator.macdType === 'Both') {\n histogramSeries = indicator.targetSeries[2];\n }\n }\n if (validData && length < validData.length && slowPeriod <= fastPeriod &&\n slowPeriod > 0 && (length - 2) >= 0) {\n var shortEMA = this.calculateEMAValues(slowPeriod, validData, 'close');\n var longEMA = this.calculateEMAValues(fastPeriod, validData, 'close');\n var macdValues = this.getMACDVales(indicator, shortEMA, longEMA);\n macdCollection = this.getMACDPoints(indicator, macdValues, validData, macdLineSeries || signalSeries);\n var signalEMA = this.calculateEMAValues(trigger, macdCollection, 'y');\n signalCollection = this.getSignalPoints(indicator, signalEMA, validData, signalSeries);\n if (histogramSeries) {\n histogramCollection = this.getHistogramPoints(indicator, macdValues, signalEMA, validData, histogramSeries);\n }\n }\n this.setSeriesRange(signalCollection, indicator, indicator.targetSeries[0]);\n if (histogramSeries) {\n this.setSeriesRange(histogramCollection, indicator, histogramSeries);\n }\n if (macdLineSeries) {\n this.setSeriesRange(macdCollection, indicator, macdLineSeries);\n }\n };\n /**\n * Calculates the EMA values for the given period\n */\n MacdIndicator.prototype.calculateEMAValues = function (period, validData, field) {\n var sum = 0;\n var initialEMA = 0;\n var emaValues = [];\n var emaPercent = (2 / (period + 1));\n for (var i = 0; i < period; i++) {\n sum += Number(validData[i][field]);\n }\n initialEMA = (sum / period);\n emaValues.push(initialEMA);\n var emaAvg = initialEMA;\n for (var j = period; j < validData.length; j++) {\n emaAvg = (Number(validData[j][field]) - emaAvg) * emaPercent + emaAvg;\n emaValues.push(emaAvg);\n }\n return emaValues;\n };\n /**\n * Defines the MACD Points\n */\n MacdIndicator.prototype.getMACDPoints = function (indicator, macdPoints, validData, series) {\n var macdCollection = [];\n var dataMACDIndex = indicator.fastPeriod - 1;\n var macdIndex = 0;\n while (dataMACDIndex < validData.length) {\n macdCollection.push(this.getDataPoint(validData[dataMACDIndex].x, macdPoints[macdIndex], validData[dataMACDIndex], series, macdCollection.length));\n dataMACDIndex++;\n macdIndex++;\n }\n return macdCollection;\n };\n /**\n * Calculates the signal points\n */\n MacdIndicator.prototype.getSignalPoints = function (indicator, signalEma, validData, series) {\n var dataSignalIndex = indicator.fastPeriod + indicator.period - 2;\n var signalIndex = 0;\n var signalCollection = [];\n while (dataSignalIndex < validData.length) {\n signalCollection.push(this.getDataPoint(validData[dataSignalIndex].x, signalEma[signalIndex], validData[dataSignalIndex], series, signalCollection.length));\n dataSignalIndex++;\n signalIndex++;\n }\n return signalCollection;\n };\n /**\n * Calculates the MACD values\n */\n MacdIndicator.prototype.getMACDVales = function (indicator, shortEma, longEma) {\n var macdPoints = [];\n var diff = indicator.fastPeriod - indicator.slowPeriod;\n for (var i = 0; i < longEma.length; i++) {\n macdPoints.push((shortEma[i + diff] - longEma[i]));\n }\n return macdPoints;\n };\n /**\n * Calculates the Histogram Points\n */\n MacdIndicator.prototype.getHistogramPoints = function (indicator, macdPoints, signalEma, validData, series) {\n var dataHistogramIndex = indicator.fastPeriod + indicator.period - 2;\n var histogramIndex = 0;\n var histogramCollection = [];\n while (dataHistogramIndex < validData.length) {\n histogramCollection.push(this.getDataPoint(validData[dataHistogramIndex].x, macdPoints[histogramIndex + (indicator.period - 1)] - signalEma[histogramIndex], validData[dataHistogramIndex], series, histogramCollection.length, indicator));\n dataHistogramIndex++;\n histogramIndex++;\n }\n return histogramCollection;\n };\n /**\n * To destroy the MACD Indicator.\n * @return {void}\n * @private\n */\n MacdIndicator.prototype.destroy = function (chart) {\n /**\n * Destroys the MACD indicator\n */\n };\n /**\n * Get module name.\n */\n MacdIndicator.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'MacdIndicator';\n };\n return MacdIndicator;\n}(TechnicalAnalysis));\nexport { MacdIndicator };\n","import { Series, Points } from '../series/chart-series';\nimport { findClipRect, RectOption } from '../../common/utils/helper';\n/**\n * `Trendline` module is used to render 6 types of trendlines in chart.\n */\nvar Trendlines = /** @class */ (function () {\n function Trendlines() {\n }\n /**\n * Defines the collection of series, that are used to represent a trendline\n * @private\n */\n Trendlines.prototype.initSeriesCollection = function (trendline, chart) {\n var trendLineSeries = new Series(trendline, 'targetSeries', {}, true);\n if (trendline.type === 'Linear' || trendline.type === 'MovingAverage') {\n trendLineSeries.type = 'Line';\n }\n else {\n trendLineSeries.type = 'Spline';\n }\n this.setSeriesProperties(trendLineSeries, trendline, trendline.type, trendline.fill, trendline.width, chart);\n };\n /**\n * Initializes the properties of the trendline series\n */\n Trendlines.prototype.setSeriesProperties = function (series, trendline, name, fill, width, chart) {\n series.name = trendline.name;\n series.xName = 'x';\n series.yName = 'y';\n series.fill = fill || 'blue';\n series.width = width;\n series.clipRectElement = trendline.clipRectElement;\n series.points = [];\n series.enableTooltip = trendline.enableTooltip;\n series.index = trendline.index;\n series.sourceIndex = trendline.sourceIndex;\n series.interior = series.fill;\n series.animation = trendline.animation;\n series.legendShape = 'HorizontalLine';\n series.marker = trendline.marker;\n series.category = 'TrendLine';\n series.chart = chart;\n series.xMin = Infinity;\n series.xMax = -Infinity;\n series.yMin = Infinity;\n series.yMax = -Infinity;\n series.xData = [];\n series.yData = [];\n trendline.targetSeries = series;\n };\n /**\n * Creates the elements of a trendline\n */\n Trendlines.prototype.createTrendLineElements = function (chart, trendline, index, element, clipRectElement) {\n trendline.trendLineElement = element;\n trendline.targetSeries.clipRectElement = clipRectElement;\n trendline.targetSeries.seriesElement = element;\n chart.trendLineElements.appendChild(trendline.trendLineElement);\n };\n /**\n * Defines the data point of trendline\n */\n Trendlines.prototype.getDataPoint = function (x, y, sourcePoint, series, index) {\n var trendPoint = new Points();\n trendPoint.x = x;\n trendPoint.y = y;\n trendPoint.xValue = Number(x);\n trendPoint.color = series.fill;\n trendPoint.index = index;\n trendPoint.yValue = Number(y);\n trendPoint.visible = true;\n series.xMin = Math.min(series.xMin, trendPoint.xValue);\n series.yMin = Math.min(series.yMin, trendPoint.yValue);\n series.xMax = Math.max(series.xMax, trendPoint.xValue);\n series.yMax = Math.max(series.yMax, trendPoint.yValue);\n series.xData.push(trendPoint.xValue);\n return trendPoint;\n };\n /**\n * Finds the slope and intercept of trendline\n */\n Trendlines.prototype.findSlopeIntercept = function (xValues, yValues, trendline, points) {\n var xAvg = 0;\n var yAvg = 0;\n var xyAvg = 0;\n var xxAvg = 0;\n var yyAvg = 0;\n var index = 0;\n var slope = 0;\n var intercept = 0;\n while (index < points.length) {\n xAvg += xValues[index];\n yAvg += yValues[index];\n xyAvg += xValues[index] * yValues[index];\n xxAvg += xValues[index] * xValues[index];\n yyAvg += yValues[index] * yValues[index];\n index++;\n }\n var type = trendline.type;\n if (trendline.intercept && (type === 'Linear' || type === 'Exponential')) {\n intercept = trendline.intercept;\n switch (type) {\n case 'Linear':\n slope = ((xyAvg) - (trendline.intercept * xAvg)) / xxAvg;\n break;\n case 'Exponential':\n slope = ((xyAvg) - (Math.log(Math.abs(trendline.intercept)) * xAvg)) / xxAvg;\n break;\n }\n }\n else {\n slope = ((points.length * xyAvg) - (xAvg * yAvg)) / ((points.length * xxAvg) - (xAvg * xAvg));\n if (type === 'Exponential' || type === 'Power') {\n intercept = Math.exp((yAvg - (slope * xAvg)) / points.length);\n }\n else {\n intercept = (yAvg - (slope * xAvg)) / points.length;\n }\n }\n return { slope: slope, intercept: intercept };\n };\n /**\n * Defines the points to draw the trendlines\n */\n Trendlines.prototype.initDataSource = function (trendline, chart) {\n var points = trendline.points;\n if (points && points.length) {\n //prepare data\n var trendlineSeries = trendline.targetSeries;\n switch (trendline.type) {\n case 'Linear':\n this.setLinearRange(points, trendline, trendlineSeries);\n break;\n case 'Exponential':\n this.setExponentialRange(points, trendline, trendlineSeries);\n break;\n case 'MovingAverage':\n this.setMovingAverageRange(points, trendline, trendlineSeries);\n break;\n case 'Polynomial':\n this.setPolynomialRange(points, trendline, trendlineSeries);\n break;\n case 'Power':\n this.setPowerRange(points, trendline, trendlineSeries);\n break;\n case 'Logarithmic':\n this.setLogarithmicRange(points, trendline, trendlineSeries);\n break;\n }\n if (trendline.type !== 'Linear' && trendline.type !== 'MovingAverage') {\n trendlineSeries.chart.splineSeriesModule.findSplinePoint(trendlineSeries);\n }\n }\n };\n /**\n * Calculation of exponential points\n */\n Trendlines.prototype.setExponentialRange = function (points, trendline, series) {\n var xValue = [];\n var yValue = [];\n var index = 0;\n var slopeIntercept;\n while (index < points.length) {\n var point = points[index];\n xValue.push(point.xValue);\n yValue.push(Math.log(point.yValue));\n index++;\n }\n slopeIntercept = this.findSlopeIntercept(xValue, yValue, trendline, points);\n series.points = this.getExponentialPoints(trendline, points, xValue, yValue, series, slopeIntercept);\n };\n /**\n * Calculation of logarithmic points\n */\n Trendlines.prototype.setLogarithmicRange = function (points, trendline, series) {\n var xLogValue = [];\n var yLogValue = [];\n var xPointsLgr = [];\n var slopeIntercept;\n var index = 0;\n while (index < points.length) {\n var point = points[index];\n xPointsLgr.push(point.xValue);\n xLogValue.push(Math.log(point.xValue));\n yLogValue.push(point.yValue);\n index++;\n }\n slopeIntercept = this.findSlopeIntercept(xLogValue, yLogValue, trendline, points);\n series.points = this.getLogarithmicPoints(trendline, points, xPointsLgr, yLogValue, series, slopeIntercept);\n };\n /**\n * Calculation of polynomial points\n */\n Trendlines.prototype.setPolynomialRange = function (points, trendline, series) {\n var xPolyValues = [];\n var yPolyValues = [];\n var index = 0;\n while (index < points.length) {\n var point = points[index];\n xPolyValues.push(point.xValue);\n yPolyValues.push(point.yValue);\n index++;\n }\n series.points = this.getPolynomialPoints(trendline, points, xPolyValues, yPolyValues, series);\n };\n /**\n * Calculation of power points\n */\n Trendlines.prototype.setPowerRange = function (points, trendline, series) {\n var xValues = [];\n var yValues = [];\n var powerPoints = [];\n var slopeIntercept;\n var index = 0;\n while (index < points.length) {\n var point = points[index];\n powerPoints.push(point.xValue);\n xValues.push(Math.log(point.xValue));\n yValues.push(Math.log(point.yValue));\n index++;\n }\n slopeIntercept = this.findSlopeIntercept(xValues, yValues, trendline, points);\n series.points = this.getPowerPoints(trendline, points, powerPoints, yValues, series, slopeIntercept);\n };\n /**\n * Calculation of linear points\n */\n Trendlines.prototype.setLinearRange = function (points, trendline, series) {\n var xValues = [];\n var yValues = [];\n var slopeIntercept;\n var index = 0;\n while (index < points.length) {\n var point = points[index];\n xValues.push(point.xValue);\n yValues.push(point.yValue);\n index++;\n }\n slopeIntercept = this.findSlopeIntercept(xValues, yValues, trendline, points);\n series.points = this.getLinearPoints(trendline, points, xValues, yValues, series, slopeIntercept);\n };\n /**\n * Calculation of moving average points\n */\n Trendlines.prototype.setMovingAverageRange = function (points, trendline, series) {\n var xValues = [];\n var yValues = [];\n var xAvgValues = [];\n var index = 0;\n while (index < points.length) {\n var point = points[index];\n xAvgValues.push(point.xValue);\n xValues.push(index + 1);\n yValues.push(point.yValue);\n index++;\n }\n series.points = this.getMovingAveragePoints(trendline, points, xAvgValues, yValues, series);\n };\n /**\n * Calculation of logarithmic points\n */\n Trendlines.prototype.getLogarithmicPoints = function (trendline, points, xValues, yValues, series, slopeInterceptLog) {\n var midPoint = Math.round((points.length / 2));\n var pts = [];\n var x1Log = xValues[0] - trendline.backwardForecast;\n var y1Log = slopeInterceptLog.intercept + (slopeInterceptLog.slope * Math.log(x1Log));\n var x2Log = xValues[midPoint - 1];\n var y2Log = slopeInterceptLog.intercept + (slopeInterceptLog.slope * Math.log(x2Log));\n var x3Log = xValues[xValues.length - 1] + trendline.forwardForecast;\n var y3Log = slopeInterceptLog.intercept + (slopeInterceptLog.slope * Math.log(x3Log));\n pts.push(this.getDataPoint(x1Log, y1Log, points[0], series, pts.length));\n pts.push(this.getDataPoint(x2Log, y2Log, points[midPoint - 1], series, pts.length));\n pts.push(this.getDataPoint(x3Log, y3Log, points[points.length - 1], series, pts.length));\n return pts;\n };\n /**\n * Defines the points based on data point\n */\n Trendlines.prototype.getPowerPoints = function (trendline, points, xValues, yValues, series, slopeInterceptPower) {\n var midPoint = Math.round((points.length / 2));\n var pts = [];\n var x1 = xValues[0] - trendline.backwardForecast;\n x1 = x1 > -1 ? x1 : 0;\n var y1 = slopeInterceptPower.intercept * Math.pow(x1, slopeInterceptPower.slope);\n var x2 = xValues[midPoint - 1];\n var y2 = slopeInterceptPower.intercept * Math.pow(x2, slopeInterceptPower.slope);\n var x3 = xValues[xValues.length - 1] + trendline.forwardForecast;\n var y3 = slopeInterceptPower.intercept * Math.pow(x3, slopeInterceptPower.slope);\n pts.push(this.getDataPoint(x1, y1, points[0], series, pts.length));\n pts.push(this.getDataPoint(x2, y2, points[midPoint - 1], series, pts.length));\n pts.push(this.getDataPoint(x3, y3, points[points.length - 1], series, pts.length));\n return pts;\n };\n /**\n * Get the polynomial points based on polynomial slopes\n */\n Trendlines.prototype.getPolynomialPoints = function (trendline, points, xValues, yValues, series) {\n var midPoint = Math.round((points.length / 2));\n var pts = [];\n var polynomialOrder = points.length <= trendline.polynomialOrder ? points.length : trendline.polynomialOrder;\n polynomialOrder = Math.max(2, polynomialOrder);\n polynomialOrder = Math.min(6, polynomialOrder);\n trendline.polynomialOrder = polynomialOrder;\n trendline.polynomialSlopes = [];\n trendline.polynomialSlopes.length = trendline.polynomialOrder + 1;\n var index = 0;\n while (index < xValues.length) {\n var xVal = xValues[index];\n var yVal = yValues[index];\n var subIndex = 0;\n while (subIndex <= trendline.polynomialOrder) {\n if (!trendline.polynomialSlopes[subIndex]) {\n trendline.polynomialSlopes[subIndex] = 0;\n }\n trendline.polynomialSlopes[subIndex] += Math.pow(xVal, subIndex) * yVal;\n ++subIndex;\n }\n index++;\n }\n var numArray = [];\n numArray.length = 1 + 2 * trendline.polynomialOrder;\n var matrix = [];\n matrix.length = trendline.polynomialOrder + 1;\n var newIndex = 0;\n while (newIndex < (trendline.polynomialOrder + 1)) {\n matrix[newIndex] = [];\n matrix[newIndex].length = 3;\n newIndex++;\n }\n var nIndex = 0;\n var num1 = 0;\n while (nIndex < xValues.length) {\n var d = xValues[nIndex];\n var num2 = 1.0;\n var nIndex2 = 0;\n while (nIndex2 < numArray.length) {\n if (!numArray[nIndex2]) {\n numArray[nIndex2] = 0;\n }\n numArray[nIndex2] += num2;\n num2 *= d;\n ++num1;\n ++nIndex2;\n }\n ++nIndex;\n }\n var nnIndex = 0;\n while (nnIndex <= trendline.polynomialOrder) {\n var nnIndex2 = 0;\n while (nnIndex2 <= trendline.polynomialOrder) {\n matrix[nnIndex][nnIndex2] = numArray[nnIndex + nnIndex2];\n ++nnIndex2;\n }\n ++nnIndex;\n }\n if (!this.gaussJordanElimination(matrix, trendline.polynomialSlopes)) {\n trendline.polynomialSlopes = null;\n }\n pts = this.getPoints(trendline, points, xValues, yValues, series);\n return pts;\n };\n /**\n * Defines the moving average points\n */\n Trendlines.prototype.getMovingAveragePoints = function (trendline, points, xValues, yValues, series) {\n var pts = [];\n var period = trendline.period >= points.length ? points.length - 1 : trendline.period;\n period = Math.max(2, period);\n var index = 0;\n var y;\n var x;\n var count;\n var nullCount;\n while (index < points.length - 1) {\n y = count = nullCount = 0;\n for (var j = index; count < period; j++) {\n count++;\n if (!yValues[j]) {\n nullCount++;\n }\n y += yValues[j];\n }\n y = period - nullCount <= 0 ? null : y / (period - nullCount);\n if (y && !isNaN(y)) {\n x = xValues[period - 1 + index];\n pts.push(this.getDataPoint(x, y, points[period - 1 + index], series, pts.length));\n }\n index++;\n }\n return pts;\n };\n /**\n * Defines the linear points\n */\n Trendlines.prototype.getLinearPoints = function (trendline, points, xValues, yValues, series, slopeInterceptLinear) {\n var pts = [];\n var x1Linear = xValues[0] - trendline.backwardForecast;\n var y1Linear = slopeInterceptLinear.slope * x1Linear + slopeInterceptLinear.intercept;\n var x2Linear = xValues[xValues.length - 1] + trendline.forwardForecast;\n var y2Linear = slopeInterceptLinear.slope * x2Linear + slopeInterceptLinear.intercept;\n pts.push(this.getDataPoint(x1Linear, y1Linear, points[0], series, pts.length));\n pts.push(this.getDataPoint(x2Linear, y2Linear, points[points.length - 1], series, pts.length));\n return pts;\n };\n /**\n * Defines the exponential points\n */\n Trendlines.prototype.getExponentialPoints = function (trendline, points, xValues, yValues, series, slopeInterceptExp) {\n var midPoint = Math.round((points.length / 2));\n var ptsExp = [];\n var x1 = xValues[0] - trendline.backwardForecast;\n var y1 = slopeInterceptExp.intercept * Math.exp(slopeInterceptExp.slope * x1);\n var x2 = xValues[midPoint - 1];\n var y2 = slopeInterceptExp.intercept * Math.exp(slopeInterceptExp.slope * x2);\n var x3 = xValues[xValues.length - 1] + trendline.forwardForecast;\n var y3 = slopeInterceptExp.intercept * Math.exp(slopeInterceptExp.slope * x3);\n ptsExp.push(this.getDataPoint(x1, y1, points[0], series, ptsExp.length));\n ptsExp.push(this.getDataPoint(x2, y2, points[midPoint - 1], series, ptsExp.length));\n ptsExp.push(this.getDataPoint(x3, y3, points[points.length - 1], series, ptsExp.length));\n return ptsExp;\n };\n /**\n * Defines the points based on data point\n */\n Trendlines.prototype.getPoints = function (trendline, points, xValues, yValues, series) {\n var midPoint = Math.round((points.length / 2));\n var polynomialSlopes = trendline.polynomialSlopes;\n var pts = [];\n var x1 = 1;\n var index = 1;\n var xValue;\n var yValue;\n while (index <= polynomialSlopes.length) {\n if (index === 1) {\n xValue = xValues[0] - trendline.backwardForecast;\n yValue = this.getPolynomialYValue(polynomialSlopes, xValue);\n pts.push(this.getDataPoint(xValue, yValue, points[0], series, pts.length));\n }\n else if (index === polynomialSlopes.length) {\n xValue = xValues[points.length - 1] + trendline.forwardForecast;\n yValue = this.getPolynomialYValue(polynomialSlopes, xValue);\n pts.push(this.getDataPoint(xValue, yValue, points[points.length - 1], series, pts.length));\n }\n else {\n x1 += (points.length + trendline.forwardForecast) / polynomialSlopes.length;\n xValue = xValues[parseInt(x1.toString(), 10) - 1];\n yValue = this.getPolynomialYValue(polynomialSlopes, xValue);\n pts.push(this.getDataPoint(xValue, yValue, points[parseInt(x1.toString(), 10) - 1], series, pts.length));\n }\n index++;\n }\n return pts;\n };\n /**\n * Defines the polynomial value of y\n */\n Trendlines.prototype.getPolynomialYValue = function (slopes, x) {\n var sum = 0;\n var index = 0;\n while (index < slopes.length) {\n sum += slopes[index] * Math.pow(x, index);\n index++;\n }\n return sum;\n };\n /**\n * Defines the gauss jordan elimination\n */\n Trendlines.prototype.gaussJordanElimination = function (matrix, polynomialSlopes) {\n var length = matrix.length;\n var numArray1 = [];\n var numArray2 = [];\n var numArray3 = [];\n numArray1.length = length;\n numArray2.length = length;\n numArray3.length = length;\n var index = 0;\n while (index < length) {\n numArray3[index] = 0;\n ++index;\n }\n var index1 = 0;\n while (index1 < length) {\n var num1 = 0;\n var index2 = 0;\n var index3 = 0;\n var index4 = 0;\n while (index4 < length) {\n if (numArray3[index4] !== 1) {\n var index5 = 0;\n while (index5 < length) {\n if (numArray3[index5] === 0 && Math.abs(matrix[index4][index5]) >= num1) {\n num1 = Math.abs(matrix[index4][index5]);\n index2 = index4;\n index3 = index5;\n }\n ++index5;\n }\n }\n ++index4;\n }\n ++numArray3[index3];\n if (index2 !== index3) {\n var index4_1 = 0;\n while (index4_1 < length) {\n var num2 = matrix[index2][index4_1];\n matrix[index2][index4_1] = matrix[index3][index4_1];\n matrix[index3][index4_1] = num2;\n ++index4_1;\n }\n var num3 = polynomialSlopes[index2];\n polynomialSlopes[index2] = polynomialSlopes[index3];\n polynomialSlopes[index3] = num3;\n }\n numArray2[index1] = index2;\n numArray1[index1] = index3;\n if (matrix[index3][index3] === 0.0) {\n return false;\n }\n var num4 = 1.0 / matrix[index3][index3];\n matrix[index3][index3] = 1.0;\n var iindex4 = 0;\n while (iindex4 < length) {\n matrix[index3][iindex4] *= num4;\n ++iindex4;\n }\n polynomialSlopes[index3] *= num4;\n var iandex4 = 0;\n while (iandex4 < length) {\n if (iandex4 !== index3) {\n var num2 = matrix[iandex4][index3];\n matrix[iandex4][index3] = 0.0;\n var index5 = 0;\n while (index5 < length) {\n matrix[iandex4][index5] -= matrix[index3][index5] * num2;\n ++index5;\n }\n polynomialSlopes[iandex4] -= polynomialSlopes[index3] * num2;\n }\n ++iandex4;\n }\n ++index1;\n }\n var iindex1 = length - 1;\n while (iindex1 >= 0) {\n if (numArray2[iindex1] !== numArray1[iindex1]) {\n var iindex2 = 0;\n while (iindex2 < length) {\n var num = matrix[iindex2][numArray2[iindex1]];\n matrix[iindex2][numArray2[iindex1]] = matrix[iindex2][numArray1[iindex1]];\n matrix[iindex2][numArray1[iindex1]] = num;\n ++iindex2;\n }\n }\n --iindex1;\n }\n return true;\n };\n /**\n * Defines the trendline elements\n */\n Trendlines.prototype.getTrendLineElements = function (series, chart) {\n findClipRect(series);\n var clipRect = series.clipRect;\n var clipRectElement = chart.renderer.drawClipPath(new RectOption(chart.element.id + '_ChartTrendlineClipRect_' + series.index, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: 0, y: 0, width: clipRect.width,\n height: clipRect.height,\n }));\n var element;\n element = chart.renderer.createGroup({\n 'id': chart.element.id + 'TrendlineSeriesGroup' + series.index,\n 'transform': 'translate(' + clipRect.x + ',' + clipRect.y + ')',\n 'clip-path': 'url(#' + chart.element.id + '_ChartTrendlineClipRect_' + series.index + ')'\n });\n //defines the clip rect element\n element.appendChild(clipRectElement);\n for (var _i = 0, _a = series.trendlines; _i < _a.length; _i++) {\n var trendline = _a[_i];\n this.createTrendLineElements(chart, trendline, trendline.index, element, clipRectElement);\n }\n };\n /**\n * To destroy the trendline\n */\n Trendlines.prototype.destroy = function (chart) {\n /**\n * Destroys the Linear Trendline\n */\n };\n /**\n * Get module name\n */\n Trendlines.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'TrendLine';\n };\n return Trendlines;\n}());\nexport { Trendlines };\n","import { Animation, Browser } from '@syncfusion/ej2-base';\nimport { measureText, findDirection, textElement, getValueXByPoint, stopTimer, getValueYByPoint, TextOption, Rect, ChartLocation, PathOption, withInBounds, removeElement } from '../../common/utils/helper';\n/**\n * `Crosshair` module is used to render the crosshair for chart.\n */\nvar Crosshair = /** @class */ (function () {\n /**\n * Constructor for crosshair module.\n * @private\n */\n function Crosshair(chart) {\n this.arrowLocation = new ChartLocation(0, 0);\n this.rx = 2;\n this.ry = 2;\n this.chart = chart;\n this.elementID = this.chart.element.id;\n this.addEventListener();\n }\n /**\n * @hidden\n */\n Crosshair.prototype.addEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n this.chart.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);\n this.chart.on(Browser.touchEndEvent, this.mouseUpHandler, this);\n this.chart.on(cancelEvent, this.mouseLeaveHandler, this);\n this.chart.on('tapHold', this.longPress, this);\n };\n Crosshair.prototype.mouseUpHandler = function () {\n if (this.chart.startMove) {\n this.removeCrosshair(2000);\n }\n };\n Crosshair.prototype.mouseLeaveHandler = function () {\n this.removeCrosshair(1000);\n };\n Crosshair.prototype.mouseMoveHandler = function (event) {\n var chart = this.chart;\n if (event.type === 'touchmove' && (Browser.isIos || Browser.isIos7) && chart.startMove && event.preventDefault) {\n event.preventDefault();\n }\n // Tooltip for chart series.\n if (!chart.disableTrackTooltip) {\n if (withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {\n if (chart.startMove || !chart.isTouch) {\n this.crosshair();\n }\n }\n else {\n this.removeCrosshair(1000);\n }\n }\n };\n /**\n * Handles the long press on chart.\n * @return {boolean}\n * @private\n */\n Crosshair.prototype.longPress = function () {\n var chart = this.chart;\n if (withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {\n this.crosshair();\n }\n return false;\n };\n /**\n * Renders the crosshair.\n * @return {void}\n */\n Crosshair.prototype.crosshair = function () {\n var chart = this.chart;\n var horizontalCross = '';\n var verticalCross = '';\n var options;\n var crosshair = chart.crosshair;\n var chartRect = chart.chartAxisLayoutPanel.seriesClipRect;\n var crossGroup = document.getElementById(this.elementID + '_UserInteraction');\n this.stopAnimation();\n if (chart.tooltip.enable && !withInBounds(chart.tooltipModule.valueX, chart.tooltipModule.valueY, chartRect)) {\n return null;\n }\n this.valueX = chart.tooltip.enable ? chart.tooltipModule.valueX : chart.mouseX;\n this.valueY = chart.tooltip.enable ? chart.tooltipModule.valueY : chart.mouseY;\n crossGroup.setAttribute('opacity', '1');\n if (crosshair.lineType === 'Both' || crosshair.lineType === 'Horizontal') {\n horizontalCross += 'M ' + chartRect.x + ' ' + this.valueY +\n ' L ' + (chartRect.x + chartRect.width) + ' ' + this.valueY;\n }\n if (crosshair.lineType === 'Both' || crosshair.lineType === 'Vertical') {\n verticalCross += 'M ' + this.valueX + ' ' + chartRect.y +\n ' L ' + this.valueX + ' ' + (chartRect.y + chartRect.height);\n }\n if (crossGroup.childNodes.length === 0) {\n var axisTooltipGroup = chart.renderer.createGroup({ 'id': this.elementID + '_crosshair_axis' });\n options = new PathOption(this.elementID + '_HorizontalLine', 'none', crosshair.line.width, crosshair.line.color || chart.themeStyle.crosshairLine, 1, null, horizontalCross);\n this.renderCrosshairLine(options, crossGroup);\n options.d = verticalCross;\n options.id = this.elementID + '_VerticalLine';\n this.renderCrosshairLine(options, crossGroup);\n crossGroup.appendChild(axisTooltipGroup);\n this.renderAxisTooltip(chart, chartRect, crossGroup.lastChild);\n }\n else {\n document.getElementById(this.elementID + '_HorizontalLine').setAttribute('d', horizontalCross);\n document.getElementById(this.elementID + '_VerticalLine').setAttribute('d', verticalCross);\n this.renderAxisTooltip(chart, chartRect, crossGroup.lastChild);\n }\n };\n Crosshair.prototype.renderCrosshairLine = function (options, crossGroup) {\n var htmlObject = this.chart.renderer.drawPath(options);\n crossGroup.appendChild(htmlObject);\n };\n Crosshair.prototype.renderAxisTooltip = function (chart, chartRect, axisGroup) {\n var axis;\n var text;\n var rect;\n var pathElement;\n var textElem;\n var options;\n var padding = 5;\n var direction;\n var axisRect;\n for (var k = 0, length_1 = chart.axisCollections.length; k < length_1; k++) {\n axis = chart.axisCollections[k];\n axisRect = !axis.placeNextToAxisLine ? axis.rect : axis.updatedRect;\n if (axis.crosshairTooltip.enable) {\n if ((this.valueX <= (axisRect.x + axisRect.width) && axisRect.x <= this.valueX) ||\n (this.valueY <= (axisRect.y + axisRect.height) && axisRect.y <= this.valueY)) {\n pathElement = document.getElementById(this.elementID + '_axis_tooltip_' + k);\n textElem = document.getElementById(this.elementID + '_axis_tooltip_text_' + k);\n text = this.getAxisText(axis);\n if (!text) {\n continue;\n }\n rect = this.tooltipLocation(text, axis, chartRect, axisRect);\n if (pathElement === null) {\n pathElement = chart.renderer.drawPath({\n 'id': this.elementID + '_axis_tooltip_' + k,\n 'fill': axis.crosshairTooltip.fill || chart.themeStyle.crosshairFill\n });\n axisGroup.appendChild(pathElement);\n options = new TextOption(this.elementID + '_axis_tooltip_text_' + k, 0, 0, 'start', text);\n textElem = textElement(options, axis.crosshairTooltip.textStyle, axis.crosshairTooltip.textStyle.color || chart.themeStyle.crosshairLabel, axisGroup);\n }\n direction = findDirection(this.rx, this.ry, rect, this.arrowLocation, 10, this.isTop, this.isBottom, this.isLeft, this.valueX, this.valueY);\n pathElement.setAttribute('d', direction);\n textElem.textContent = text;\n textElem.setAttribute('x', (rect.x + padding).toString());\n textElem.setAttribute('y', (rect.y + padding + 3 * this.elementSize.height / 4).toString());\n }\n else {\n removeElement(this.elementID + '_axis_tooltip_' + k);\n removeElement(this.elementID + '_axis_tooltip_text_' + k);\n }\n }\n }\n };\n Crosshair.prototype.getAxisText = function (axis) {\n var value;\n this.isBottom = false;\n this.isTop = false;\n this.isLeft = false;\n this.isRight = false;\n var labelValue = (axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks')\n ? 0.5 : 0;\n if (axis.orientation === 'Horizontal') {\n value = getValueXByPoint(Math.abs(this.valueX - axis.rect.x), axis.rect.width, axis) + labelValue;\n this.isBottom = !axis.opposedPosition;\n this.isTop = axis.opposedPosition;\n }\n else {\n value = getValueYByPoint(Math.abs(this.valueY - axis.rect.y), axis.rect.height, axis) + labelValue;\n this.isRight = axis.opposedPosition;\n this.isLeft = !axis.opposedPosition;\n }\n if (axis.valueType === 'DateTime') {\n return axis.format(new Date(value));\n }\n else if (axis.valueType === 'Category') {\n return axis.labels[Math.floor(value)];\n }\n else if (axis.valueType === 'Logarithmic') {\n return value = axis.format(Math.pow(axis.logBase, value));\n }\n else {\n var customLabelFormat = axis.labelFormat && axis.labelFormat.match('{value}') !== null;\n return customLabelFormat ? axis.labelFormat.replace('{value}', axis.format(value)) : axis.format(value);\n }\n };\n Crosshair.prototype.tooltipLocation = function (text, axis, bounds, axisRect) {\n var isBottom = false;\n var isLeft = false;\n var padding = 5;\n var arrowPadding = 10;\n var tooltipRect;\n var boundsX = bounds.x;\n var boundsY = bounds.y;\n var islabelInside = axis.labelPosition === 'Inside';\n var scrollBarHeight = axis.zoomingScrollBar && axis.zoomingScrollBar.svgObject ? axis.scrollBarHeight : 0;\n this.elementSize = measureText(text, axis.crosshairTooltip.textStyle);\n if (axis.orientation === 'Horizontal') {\n var yLocation = islabelInside ? axisRect.y - this.elementSize.height - (padding * 2 + arrowPadding) :\n axisRect.y + scrollBarHeight;\n var height = islabelInside ? axisRect.y - this.elementSize.height - arrowPadding : axisRect.y + arrowPadding;\n this.arrowLocation = new ChartLocation(this.valueX, yLocation);\n tooltipRect = new Rect((this.valueX - (this.elementSize.width / 2) - padding), height + (!islabelInside ? scrollBarHeight : 0), this.elementSize.width + padding * 2, this.elementSize.height + padding * 2);\n if (axis.opposedPosition) {\n tooltipRect.y = islabelInside ? axisRect.y : axisRect.y -\n (this.elementSize.height + padding * 2 + arrowPadding) - scrollBarHeight;\n }\n if (tooltipRect.x < boundsX) {\n tooltipRect.x = boundsX;\n }\n if (tooltipRect.x + tooltipRect.width > boundsX + bounds.width) {\n tooltipRect.x -= ((tooltipRect.x + tooltipRect.width) - (boundsX + bounds.width));\n }\n if (this.arrowLocation.x + arrowPadding / 2 > tooltipRect.x + tooltipRect.width - this.rx) {\n this.arrowLocation.x = tooltipRect.x + tooltipRect.width - this.rx - arrowPadding / 2;\n }\n if (this.arrowLocation.x - arrowPadding / 2 < tooltipRect.x + this.rx) {\n this.arrowLocation.x = tooltipRect.x + this.rx + arrowPadding / 2;\n }\n }\n else {\n scrollBarHeight = scrollBarHeight * (axis.opposedPosition ? 1 : -1);\n this.arrowLocation = new ChartLocation(axisRect.x, this.valueY);\n var width = islabelInside ? axisRect.x - scrollBarHeight :\n axisRect.x - (this.elementSize.width) - (padding * 2 + arrowPadding);\n tooltipRect = new Rect(width + scrollBarHeight, this.valueY - (this.elementSize.height / 2) - padding, this.elementSize.width + (padding * 2), this.elementSize.height + padding * 2);\n if (axis.opposedPosition) {\n tooltipRect.x = islabelInside ? axisRect.x - this.elementSize.width - arrowPadding :\n axisRect.x + arrowPadding + scrollBarHeight;\n if ((tooltipRect.x + tooltipRect.width) > this.chart.availableSize.width) {\n this.arrowLocation.x -= ((tooltipRect.x + tooltipRect.width) - this.chart.availableSize.width);\n tooltipRect.x -= ((tooltipRect.x + tooltipRect.width) - this.chart.availableSize.width);\n }\n }\n else {\n if (tooltipRect.x < 0) {\n this.arrowLocation.x -= tooltipRect.x;\n tooltipRect.x = 0;\n }\n }\n if (tooltipRect.y < boundsY) {\n tooltipRect.y = boundsY;\n }\n if (tooltipRect.y + tooltipRect.height >= boundsY + bounds.height) {\n tooltipRect.y -= ((tooltipRect.y + tooltipRect.height) - (boundsY + bounds.height));\n }\n if (this.arrowLocation.y + arrowPadding / 2 > tooltipRect.y + tooltipRect.height - this.ry) {\n this.arrowLocation.y = tooltipRect.y + tooltipRect.height - this.ry - arrowPadding / 2;\n }\n if (this.arrowLocation.y - arrowPadding / 2 < tooltipRect.y + this.ry) {\n this.arrowLocation.y = tooltipRect.y + this.ry + arrowPadding / 2;\n }\n }\n return tooltipRect;\n };\n Crosshair.prototype.stopAnimation = function () {\n stopTimer(this.crosshairInterval);\n };\n /**\n * Removes the crosshair on mouse leave.\n * @return {void}\n * @private\n */\n Crosshair.prototype.removeCrosshair = function (duration) {\n var chart = this.chart;\n var crosshair = document.getElementById(this.elementID + '_UserInteraction');\n this.stopAnimation();\n if (crosshair && crosshair.getAttribute('opacity') !== '0') {\n this.crosshairInterval = setTimeout(function () {\n new Animation({}).animate(crosshair, {\n duration: 200,\n progress: function (args) {\n // crosshair.removeAttribute('e-animate');\n crosshair.style.animation = '';\n crosshair.setAttribute('opacity', (1 - (args.timeStamp / args.duration)).toString());\n },\n end: function (model) {\n crosshair.setAttribute('opacity', '0');\n chart.startMove = false;\n if (chart.tooltipModule) {\n chart.tooltipModule.valueX = null;\n chart.tooltipModule.valueY = null;\n }\n }\n });\n }, duration);\n }\n };\n /**\n * Get module name.\n */\n Crosshair.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'Crosshair';\n };\n /**\n * To destroy the crosshair.\n * @return {void}\n * @private\n */\n Crosshair.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return Crosshair;\n}());\nexport { Crosshair };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { NotifyPropertyChanges, Property, Event, Complex } from '@syncfusion/ej2-base';\nimport { SvgRenderer, extend, compile as templateComplier, Component } from '@syncfusion/ej2-base';\nimport { ChildProperty, remove, Browser, Animation } from '@syncfusion/ej2-base';\nimport { getTooltipThemeColor } from './interface';\nimport { Size, Rect, Side, measureText, getElement, findDirection, drawSymbol, textElement } from './helper';\nimport { removeElement, TextOption, TooltipLocation, PathOption } from './helper';\n/**\n * Configures the fonts in charts.\n * @private\n */\nvar TextStyle = /** @class */ (function (_super) {\n __extends(TextStyle, _super);\n function TextStyle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], TextStyle.prototype, \"size\", void 0);\n __decorate([\n Property('')\n ], TextStyle.prototype, \"color\", void 0);\n __decorate([\n Property('Segoe UI')\n ], TextStyle.prototype, \"fontFamily\", void 0);\n __decorate([\n Property('Normal')\n ], TextStyle.prototype, \"fontWeight\", void 0);\n __decorate([\n Property('Normal')\n ], TextStyle.prototype, \"fontStyle\", void 0);\n __decorate([\n Property(1)\n ], TextStyle.prototype, \"opacity\", void 0);\n return TextStyle;\n}(ChildProperty));\nexport { TextStyle };\n/**\n * Configures the borders in the chart.\n * @private\n */\nvar TooltipBorder = /** @class */ (function (_super) {\n __extends(TooltipBorder, _super);\n function TooltipBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], TooltipBorder.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], TooltipBorder.prototype, \"width\", void 0);\n return TooltipBorder;\n}(ChildProperty));\nexport { TooltipBorder };\n/**\n * Configures the borders in the chart.\n * @private\n */\nvar AreaBounds = /** @class */ (function (_super) {\n __extends(AreaBounds, _super);\n function AreaBounds() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], AreaBounds.prototype, \"x\", void 0);\n __decorate([\n Property(0)\n ], AreaBounds.prototype, \"y\", void 0);\n __decorate([\n Property(0)\n ], AreaBounds.prototype, \"width\", void 0);\n __decorate([\n Property(0)\n ], AreaBounds.prototype, \"height\", void 0);\n return AreaBounds;\n}(ChildProperty));\nexport { AreaBounds };\n/**\n * Configures the borders in the chart.\n * @private\n */\nvar ToolLocation = /** @class */ (function (_super) {\n __extends(ToolLocation, _super);\n function ToolLocation() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], ToolLocation.prototype, \"x\", void 0);\n __decorate([\n Property(0)\n ], ToolLocation.prototype, \"y\", void 0);\n return ToolLocation;\n}(ChildProperty));\nexport { ToolLocation };\n/**\n * Represents the Tooltip control.\n * ```html\n * \n * \n * ```\n * @private\n */\nvar Tooltip = /** @class */ (function (_super) {\n __extends(Tooltip, _super);\n /**\n * Constructor for creating the widget\n * @hidden\n */\n function Tooltip(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * Initialize the event handler.\n * @private.\n */\n Tooltip.prototype.preRender = function () {\n this.initPrivateVariable();\n this.removeSVG();\n this.createTooltipElement();\n };\n Tooltip.prototype.initPrivateVariable = function () {\n this.renderer = new SvgRenderer(this.element.id);\n this.themeStyle = getTooltipThemeColor(this.theme);\n this.formattedText = [];\n this.padding = 5;\n this.isFirst = true;\n this.markerPoint = [];\n };\n Tooltip.prototype.removeSVG = function () {\n var svgObject = document.getElementById(this.element.id + '_svg');\n var templateObject = document.getElementById(this.element.id + 'parent_template');\n if (svgObject && svgObject.parentNode) {\n remove(svgObject);\n }\n if (templateObject && templateObject.parentNode) {\n remove(templateObject);\n }\n };\n /**\n * To Initialize the control rendering.\n */\n Tooltip.prototype.render = function () {\n this.fadeOuted = false;\n if (!this.template) {\n this.renderText(this.isFirst);\n var argsData = {\n cancel: false, name: 'tooltipRender', tooltip: this\n };\n this.trigger('tooltipRender', argsData);\n var markerSide = this.renderTooltipElement(this.areaBounds, this.location);\n this.drawMarker(markerSide.isBottom, markerSide.isRight, this.markerSize);\n }\n else {\n this.updateTemplateFn();\n this.createTemplate(this.areaBounds, this.location);\n }\n this.trigger('loaded', { tooltip: this });\n var element = document.getElementById('chartmeasuretext');\n if (element) {\n element.remove();\n }\n };\n Tooltip.prototype.createTooltipElement = function () {\n this.textElements = [];\n if (!this.template || this.shared) {\n // SVG element for tooltip\n var svgObject = this.renderer.createSvg({ id: this.element.id + '_svg' });\n this.element.appendChild(svgObject);\n // Group to hold text and path.\n var groupElement = this.renderer.createGroup({ id: this.element.id + '_group' });\n svgObject.appendChild(groupElement);\n var pathElement = this.renderer.drawPath({\n 'id': this.element.id + '_path', 'stroke-width': this.border.width,\n 'fill': this.fill || this.themeStyle.tooltipFill, 'opacity': this.opacity,\n 'stroke': this.border.color\n });\n groupElement.appendChild(pathElement);\n }\n };\n Tooltip.prototype.drawMarker = function (isBottom, isRight, size) {\n if (this.shapes.length <= 0) {\n return null;\n }\n var shapeOption;\n var count = 0;\n var markerGroup = this.renderer.createGroup({ id: this.element.id + '_trackball_group' });\n var groupElement = getElement(this.element.id + '_group');\n var x = (this.marginX * 2) + (size / 2) + (isRight ? this.arrowPadding : 0);\n for (var _i = 0, _a = this.shapes; _i < _a.length; _i++) {\n var shape = _a[_i];\n shapeOption = new PathOption(this.element.id + '_Trackball_' + count, this.palette[count], 1, '#cccccc', 1, null);\n markerGroup.appendChild(drawSymbol(new TooltipLocation(x, this.markerPoint[count] - this.padding + (isBottom ? this.arrowPadding : 0)), shape, new Size(size, size), '', shapeOption, null));\n count++;\n }\n groupElement.appendChild(markerGroup);\n };\n Tooltip.prototype.renderTooltipElement = function (areaBounds, location) {\n var tooltipDiv = getElement(this.element.id);\n var arrowLocation = new TooltipLocation(0, 0);\n var tipLocation = new TooltipLocation(0, 0);\n var textHeights;\n var svgObject = getElement(this.element.id + '_svg');\n var groupElement = getElement(this.element.id + '_group');\n var pathElement = getElement(this.element.id + '_path');\n var rect;\n var isTop = false;\n var isLeft = false;\n var isBottom = false;\n var x = 0;\n var y = 0;\n this.tipRadius = 1;\n if (this.header !== '') {\n this.elementSize.height += this.marginY;\n }\n if (this.content.length > 1) {\n rect = this.sharedTooltipLocation(areaBounds, this.location.x, this.location.y);\n isTop = true;\n }\n else {\n rect = this.tooltipLocation(areaBounds, location, arrowLocation, tipLocation);\n if (!this.inverted) {\n isTop = (rect.y < (location.y + this.clipBounds.y));\n isBottom = !isTop;\n y = (isTop ? 0 : this.arrowPadding);\n }\n else {\n isLeft = (rect.x < (location.x + this.clipBounds.x));\n x = (isLeft ? 0 : this.arrowPadding);\n }\n }\n if (this.header !== '') {\n var headerSize = measureText(this.header, this.textStyle).height + (this.marginY * 2) +\n (isBottom ? this.arrowPadding : 0); //header padding;\n var xLength = (this.marginX * 3) + (!isLeft && !isTop && !isBottom ? this.arrowPadding : 0);\n var direction = 'M ' + xLength + ' ' + headerSize +\n 'L ' + (rect.width + (!isLeft && !isTop && !isBottom ? this.arrowPadding : 0) - (this.marginX * 2)) +\n ' ' + headerSize;\n var pathElement_1 = this.renderer.drawPath({\n 'id': this.element.id + '_header_path', 'stroke-width': 1,\n 'fill': null, 'opacity': 0.8, 'stroke': this.themeStyle.tooltipHeaderLine, 'd': direction\n });\n groupElement.appendChild(pathElement_1);\n }\n var start = this.border.width / 2;\n var pointRect = new Rect(start + x, start + y, rect.width - start, rect.height - start);\n groupElement.setAttribute('opacity', '1');\n if (this.enableAnimation && !this.shared && !this.isFirst) {\n this.animateTooltipDiv(tooltipDiv, rect);\n }\n else {\n this.updateDiv(tooltipDiv, rect.x, rect.y);\n }\n svgObject.setAttribute('height', (rect.height + this.border.width + (!((!this.inverted)) ? 0 : this.arrowPadding)).toString());\n svgObject.setAttribute('width', (rect.width + this.border.width + (((!this.inverted)) ? 0 : this.arrowPadding)).toString());\n svgObject.setAttribute('opacity', '1');\n pathElement.setAttribute('d', findDirection(this.rx, this.ry, pointRect, arrowLocation, this.arrowPadding, isTop, isBottom, isLeft, tipLocation.x, tipLocation.y, this.tipRadius));\n if (this.enableShadow) {\n pathElement.setAttribute('filter', Browser.isIE ? '' : 'url(#chart_shadow_tooltip)');\n var shadow = '
';\n shadow += '';\n shadow += ' ';\n var defElement = this.renderer.createDefs();\n defElement.setAttribute('id', 'SVG_tooltip_definition');\n groupElement.appendChild(defElement);\n defElement.innerHTML = shadow;\n }\n pathElement.setAttribute('stroke', this.border.color);\n this.changeText(new TooltipLocation(x, y), isBottom, !isLeft && !isTop && !isBottom, rect);\n return new Side(isBottom, !isLeft && !isTop && !isBottom);\n };\n Tooltip.prototype.changeText = function (point, isBottom, isRight, rect) {\n var element = document.getElementById(this.element.id + '_text');\n if (isBottom) {\n element.setAttribute('transform', 'translate(0,' + this.arrowPadding + ')');\n }\n if (isRight) {\n element.setAttribute('transform', 'translate(' + this.arrowPadding + ' 0)');\n }\n };\n Tooltip.prototype.findFormattedText = function () {\n this.formattedText = [];\n if (this.header.replace(/
/g, '').replace(/<\\/b>/g, '').trim() !== '') {\n this.formattedText = this.formattedText.concat(this.header);\n }\n this.formattedText = this.formattedText.concat(this.content);\n };\n Tooltip.prototype.renderText = function (isRender) {\n var height = 0;\n var width = 0; // Padding for text;\n var subWidth = 0;\n var size;\n var lines;\n var key = 'properties';\n var font = extend({}, this.textStyle, null, true)[key];\n var groupElement = getElement(this.element.id + '_group');\n var tspanElement;\n var tspanStyle = '';\n var line;\n var tspanOption;\n this.findFormattedText();\n var headerContent = this.header.replace(//g, '').replace(/<\\/b>/g, '').trim();\n var headerSpace = (headerContent !== '') ? this.marginY : 0;\n var isRow = true;\n var isColumn = true;\n this.markerPoint = [];\n var markerSize = (this.shapes.length > 0) ? 10 : 0;\n var markerPadding = (this.shapes.length > 0) ? 5 : 0;\n var spaceWidth = 4;\n var fontSize = '13px';\n var dy = (22 / parseFloat(fontSize)) * (parseFloat(font.size));\n if (!isRender) {\n removeElement(this.element.id + '_text');\n removeElement(this.element.id + '_header_path');\n removeElement(this.element.id + '_trackball_group');\n removeElement('SVG_tooltip_definition');\n }\n var options = new TextOption(this.element.id + '_text', this.marginX * 2, (this.marginY * 2 + this.padding * 2 + (this.marginY === 2 ? 3 : 0)), 'start', '');\n var parentElement = textElement(options, font, null, groupElement);\n for (var k = 0, pointsLength = this.formattedText.length; k < pointsLength; k++) {\n var textCollection = this.formattedText[k].replace(/<(b|strong)>/g, '')\n .replace(/<\\/(b|strong)>/g, ' ')\n .split(//g);\n size = measureText(this.formattedText[k], font);\n if ((k !== 0) || (headerContent === '')) {\n this.markerPoint.push((headerContent !== '' ? (this.marginY) : 0) + options.y + height);\n }\n for (var i = 0, len = textCollection.length; i < len; i++) {\n lines = textCollection[i].replace(//g, '').replace(/<\\/b>/g, ' ').split(' ');\n subWidth = 0;\n isColumn = true;\n height += dy;\n for (var k_1 = 0, len_1 = lines.length; k_1 < len_1; k_1++) {\n line = lines[k_1];\n if (line.replace(//g, '').replace(/<\\/b>/g, '').trim() !== '') {\n subWidth += spaceWidth;\n if (isColumn && !isRow) {\n tspanOption = { x: (this.marginX * 2) + (markerSize + markerPadding),\n dy: dy + ((isColumn) ? headerSpace : 0), fill: '' };\n headerSpace = null;\n }\n else {\n if (isRow && isColumn) {\n tspanOption = { x: (headerContent === '') ? ((this.marginX * 2) + (markerSize + markerPadding))\n : (this.marginX * 2) };\n }\n else {\n tspanOption = {};\n }\n }\n isColumn = false;\n tspanElement = this.renderer.createTSpan(tspanOption, '');\n parentElement.appendChild(tspanElement);\n if (line.indexOf('') > -1) {\n tspanStyle = 'font-weight:bold';\n font.fontWeight = 'bold';\n (tspanElement).setAttribute('fill', this.textStyle.color || this.themeStyle.tooltipBoldLabel);\n }\n else {\n tspanStyle = '';\n font.fontWeight = 'Normal';\n (tspanElement).setAttribute('fill', this.textStyle.color || this.themeStyle.tooltipLightLabel);\n }\n (tspanElement).textContent = line = line.replace(/<[a-zA-Z\\/](.|\\n)*?>/g, '');\n subWidth += measureText(line, font).width;\n if (tspanStyle !== '') {\n tspanElement.setAttribute('style', tspanStyle);\n }\n isRow = false;\n }\n }\n subWidth -= spaceWidth;\n width = Math.max(width, subWidth);\n }\n }\n this.elementSize = new Size(width + (width > 0 ? (2 * this.marginX) : 0), height);\n this.elementSize.width += (markerSize + markerPadding); // marker size + marker Spacing\n var element = (parentElement.childNodes[0]);\n if (headerContent !== '' && element) {\n font.fontWeight = 'bold';\n var width_1 = (this.elementSize.width + (2 * this.padding)) / 2 - measureText(headerContent, font).width / 2;\n element.setAttribute('x', width_1.toString());\n }\n };\n Tooltip.prototype.createTemplate = function (areaBounds, location) {\n var argsData = { cancel: false, name: 'tooltipRender', tooltip: this };\n this.trigger('tooltipRender', argsData);\n var parent = document.getElementById(this.element.id);\n var firstElement = parent.firstElementChild;\n if (firstElement) {\n firstElement.remove();\n }\n if (!argsData.cancel) {\n var templateElement = this.templateFn(this.data);\n var elem = this.createElement('div', { id: this.element.id + 'parent_template' });\n while (templateElement && templateElement.length > 0) {\n elem.appendChild(templateElement[0]);\n }\n parent.appendChild(elem);\n var rect = this.element.getBoundingClientRect();\n this.padding = 0;\n this.elementSize = new Size(rect.width, rect.height);\n var tooltipRect = this.tooltipLocation(areaBounds, location, new TooltipLocation(0, 0), new TooltipLocation(0, 0));\n if (this.enableAnimation && !this.shared && !this.isFirst) {\n this.animateTooltipDiv(this.element, tooltipRect);\n }\n else {\n this.updateDiv(this.element, tooltipRect.x, tooltipRect.y);\n }\n }\n else {\n getElement(this.element.id + '_tooltip').remove();\n }\n };\n Tooltip.prototype.sharedTooltipLocation = function (bounds, x, y) {\n var width = this.elementSize.width + (2 * this.marginX);\n var height = this.elementSize.height + (2 * this.marginY);\n var tooltipRect = new Rect(x + 2 * this.padding, y - height - this.padding, width, height);\n if (tooltipRect.y < bounds.y) {\n tooltipRect.y += (tooltipRect.height + 2 * this.padding);\n }\n if (tooltipRect.x + tooltipRect.width > bounds.x + bounds.width) {\n tooltipRect.x -= (tooltipRect.width + 4 * this.padding);\n }\n return tooltipRect;\n };\n Tooltip.prototype.tooltipLocation = function (bounds, symbolLocation, arrowLocation, tipLocation) {\n var location = new TooltipLocation(symbolLocation.x, symbolLocation.y);\n var width = this.elementSize.width + (2 * this.marginX);\n var height = this.elementSize.height + (2 * this.marginY);\n var markerHeight = this.offset;\n var clipX = this.clipBounds.x;\n var clipY = this.clipBounds.y;\n var boundsX = bounds.x;\n var boundsY = bounds.y;\n if (!this.inverted) {\n location = new TooltipLocation(location.x + clipX - this.elementSize.width / 2 - this.padding, location.y + clipY - this.elementSize.height - (2 * this.padding) - this.arrowPadding - markerHeight);\n arrowLocation.x = tipLocation.x = width / 2;\n if (location.y < boundsY || (this.isNegative)) {\n location.y = (symbolLocation.y < 0 ? 0 : symbolLocation.y) + clipY + markerHeight;\n }\n if (location.y + height + this.arrowPadding > boundsY + bounds.height) {\n location.y = (symbolLocation.y > bounds.height ? bounds.height : symbolLocation.y)\n + clipY - this.elementSize.height - (2 * this.padding) - this.arrowPadding - markerHeight;\n }\n tipLocation.x = width / 2;\n if (location.x < boundsX) {\n arrowLocation.x -= (boundsX - location.x);\n tipLocation.x -= (boundsX - location.x);\n location.x = boundsX;\n }\n if (location.x + width > boundsX + bounds.width) {\n arrowLocation.x += ((location.x + width) - (boundsX + bounds.width));\n tipLocation.x += ((location.x + width) - (boundsX + bounds.width));\n location.x -= ((location.x + width) - (boundsX + bounds.width));\n }\n if (arrowLocation.x + this.arrowPadding / 2 > width - this.rx) {\n arrowLocation.x = width - this.rx - this.arrowPadding / 2;\n tipLocation.x = width;\n this.tipRadius = 0;\n }\n if (arrowLocation.x - this.arrowPadding / 2 < this.rx) {\n arrowLocation.x = this.rx + this.arrowPadding / 2;\n tipLocation.x = 0;\n this.tipRadius = 0;\n }\n }\n else {\n location = new TooltipLocation(location.x + clipX + markerHeight, location.y + clipY - this.elementSize.height / 2 - (this.padding));\n arrowLocation.y = tipLocation.y = height / 2;\n if ((location.x + width + this.arrowPadding > boundsX + bounds.width) || (this.isNegative)) {\n location.x = (symbolLocation.x > bounds.width ? bounds.width : symbolLocation.x)\n + clipX - markerHeight - (width + this.arrowPadding);\n }\n if (location.x < boundsX) {\n location.x = (symbolLocation.x < 0 ? 0 : symbolLocation.x) + clipX + markerHeight;\n }\n if (location.y <= boundsY) {\n arrowLocation.y -= (boundsY - location.y);\n tipLocation.y -= (boundsY - location.y);\n location.y = boundsY;\n }\n if (location.y + height >= boundsY + bounds.height) {\n arrowLocation.y += ((location.y + height) - (boundsY + bounds.height));\n tipLocation.y += ((location.y + height) - (boundsY + bounds.height));\n location.y -= ((location.y + height) - (boundsY + bounds.height));\n }\n if (arrowLocation.y + this.arrowPadding / 2 > height - this.ry) {\n arrowLocation.y = height - this.ry - this.arrowPadding / 2;\n tipLocation.y = height;\n this.tipRadius = 0;\n }\n if (arrowLocation.y - this.arrowPadding / 2 < this.ry) {\n arrowLocation.y = this.ry + this.arrowPadding / 2;\n tipLocation.y = 0;\n this.tipRadius = 0;\n }\n }\n return new Rect(location.x, location.y, width, height);\n };\n Tooltip.prototype.animateTooltipDiv = function (tooltipDiv, rect) {\n var _this = this;\n var x = parseFloat(tooltipDiv.style.left);\n var y = parseFloat(tooltipDiv.style.top);\n var currenDiff;\n new Animation({}).animate(tooltipDiv, {\n duration: 300,\n progress: function (args) {\n currenDiff = (args.timeStamp / args.duration);\n tooltipDiv.style.animation = null;\n tooltipDiv.style.left = (x + currenDiff * (rect.x - x)) + 'px';\n tooltipDiv.style.top = (y + currenDiff * (rect.y - y)) + 'px';\n },\n end: function (model) {\n _this.updateDiv(tooltipDiv, rect.x, rect.y);\n _this.trigger('animationComplete', { tooltip: _this });\n }\n });\n };\n Tooltip.prototype.updateDiv = function (tooltipDiv, x, y) {\n tooltipDiv.style.left = x + 'px';\n tooltipDiv.style.top = y + 'px';\n };\n Tooltip.prototype.updateTemplateFn = function () {\n if (this.template) {\n var e = void 0;\n try {\n if (document.querySelectorAll(this.template).length) {\n this.templateFn = templateComplier(document.querySelector(this.template).innerHTML.trim());\n }\n }\n catch (e) {\n this.templateFn = templateComplier(this.template);\n }\n }\n };\n /** @private */\n Tooltip.prototype.fadeOut = function () {\n var _this = this;\n var tooltipElement = getElement(this.element.id);\n if (tooltipElement) {\n var tooltipGroup_1 = tooltipElement.firstChild;\n var opacity_1 = parseFloat(tooltipGroup_1.getAttribute('opacity')) || 1;\n new Animation({}).animate(tooltipGroup_1, {\n duration: 200,\n progress: function (args) {\n // tooltipGroup.removeAttribute('e-animate');\n _this.progressAnimation(tooltipGroup_1, opacity_1, (args.timeStamp / args.duration));\n },\n end: function (model) {\n _this.fadeOuted = true;\n _this.endAnimation(tooltipGroup_1);\n }\n });\n }\n };\n Tooltip.prototype.progressAnimation = function (tooltipGroup, opacity, timeStamp) {\n tooltipGroup.style.animation = '';\n tooltipGroup.setAttribute('opacity', (opacity - timeStamp).toString());\n };\n /*\n * @hidden\n */\n Tooltip.prototype.endAnimation = function (tooltipGroup) {\n tooltipGroup.setAttribute('opacity', '0');\n if (this.template && !this.shared) {\n tooltipGroup.style.display = 'none';\n }\n this.trigger('animationComplete', { tooltip: this });\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n Tooltip.prototype.getPersistData = function () {\n var keyEntity = [];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Get component name\n * @private\n */\n Tooltip.prototype.getModuleName = function () {\n return 'tooltip';\n };\n /**\n * To destroy the accumulationcharts\n * @private\n */\n Tooltip.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n this.element.classList.remove('e-tooltip');\n };\n /**\n * Called internally if any of the property value changed.\n * @return {void}\n * @private\n */\n Tooltip.prototype.onPropertyChanged = function (newProp, oldProp) {\n this.isFirst = false;\n this.render();\n };\n __decorate([\n Property(false)\n ], Tooltip.prototype, \"enable\", void 0);\n __decorate([\n Property(false)\n ], Tooltip.prototype, \"shared\", void 0);\n __decorate([\n Property(true)\n ], Tooltip.prototype, \"enableShadow\", void 0);\n __decorate([\n Property(null)\n ], Tooltip.prototype, \"fill\", void 0);\n __decorate([\n Property('')\n ], Tooltip.prototype, \"header\", void 0);\n __decorate([\n Property(0.75)\n ], Tooltip.prototype, \"opacity\", void 0);\n __decorate([\n Complex({ size: '13px', fontWeight: 'Normal', color: null, fontStyle: 'Normal', fontFamily: 'Segoe UI' }, TextStyle)\n ], Tooltip.prototype, \"textStyle\", void 0);\n __decorate([\n Property(null)\n ], Tooltip.prototype, \"template\", void 0);\n __decorate([\n Property(true)\n ], Tooltip.prototype, \"enableAnimation\", void 0);\n __decorate([\n Property(false)\n ], Tooltip.prototype, \"inverted\", void 0);\n __decorate([\n Property(false)\n ], Tooltip.prototype, \"isNegative\", void 0);\n __decorate([\n Complex({ color: '#cccccc', width: 0.5 }, TooltipBorder)\n ], Tooltip.prototype, \"border\", void 0);\n __decorate([\n Property([])\n ], Tooltip.prototype, \"content\", void 0);\n __decorate([\n Property(10)\n ], Tooltip.prototype, \"markerSize\", void 0);\n __decorate([\n Complex({ x: 0, y: 0 }, ToolLocation)\n ], Tooltip.prototype, \"clipBounds\", void 0);\n __decorate([\n Property([])\n ], Tooltip.prototype, \"palette\", void 0);\n __decorate([\n Property([])\n ], Tooltip.prototype, \"shapes\", void 0);\n __decorate([\n Complex({ x: 0, y: 0 }, ToolLocation)\n ], Tooltip.prototype, \"location\", void 0);\n __decorate([\n Property(0)\n ], Tooltip.prototype, \"offset\", void 0);\n __decorate([\n Property(2)\n ], Tooltip.prototype, \"rx\", void 0);\n __decorate([\n Property(2)\n ], Tooltip.prototype, \"ry\", void 0);\n __decorate([\n Property(5)\n ], Tooltip.prototype, \"marginX\", void 0);\n __decorate([\n Property(5)\n ], Tooltip.prototype, \"marginY\", void 0);\n __decorate([\n Property(12)\n ], Tooltip.prototype, \"arrowPadding\", void 0);\n __decorate([\n Property(null)\n ], Tooltip.prototype, \"data\", void 0);\n __decorate([\n Property('Material')\n ], Tooltip.prototype, \"theme\", void 0);\n __decorate([\n Complex({ x: 0, y: 0, width: 0, height: 0 }, AreaBounds)\n ], Tooltip.prototype, \"areaBounds\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"tooltipRender\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"loaded\", void 0);\n __decorate([\n Event()\n ], Tooltip.prototype, \"animationComplete\", void 0);\n Tooltip = __decorate([\n NotifyPropertyChanges\n ], Tooltip);\n return Tooltip;\n}(Component));\nexport { Tooltip };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { extend } from '@syncfusion/ej2-base';\nimport { ChartLocation } from '../../common/utils/helper';\nimport { stopTimer, removeElement } from '../../common/utils/helper';\nimport { ChartData } from '../../chart/utils/get-data';\nimport { tooltipRender } from '../../common/model/constants';\nimport { Tooltip as SVGTooltip } from '@syncfusion/ej2-svg-base';\n/**\n * Tooltip Module used to render the tooltip for series.\n */\nvar BaseTooltip = /** @class */ (function (_super) {\n __extends(BaseTooltip, _super);\n /**\n * Constructor for tooltip module.\n * @private.\n */\n function BaseTooltip(chart) {\n var _this = _super.call(this, chart) || this;\n _this.element = _this.chart.element;\n _this.textStyle = chart.tooltip.textStyle;\n _this.control = chart;\n return _this;\n }\n BaseTooltip.prototype.getElement = function (id) {\n return document.getElementById(id);\n };\n /**\n * Renders the tooltip.\n * @return {void}\n * @private\n */\n BaseTooltip.prototype.getTooltipElement = function (isTooltip) {\n this.inverted = this.chart.requireInvertedAxis;\n this.header = (this.control.tooltip.header === null) ?\n ((this.control.tooltip.shared) ? '${point.x} ' : '${series.name} ')\n : (this.control.tooltip.header);\n this.formattedText = [];\n if (!isTooltip) {\n return this.createElement();\n }\n return null;\n };\n BaseTooltip.prototype.createElement = function () {\n var tooltipDiv = document.createElement('div');\n tooltipDiv.id = this.element.id + '_tooltip';\n tooltipDiv.className = 'ejSVGTooltip';\n tooltipDiv.setAttribute('style', 'pointer-events:none; position:absolute;z-index: 1');\n return tooltipDiv;\n };\n BaseTooltip.prototype.pushData = function (data, isFirst, tooltipDiv, isChart) {\n if (data.series.enableTooltip) {\n if (isChart) {\n this.currentPoints.push(data);\n }\n else {\n this.currentPoints.push(data);\n }\n this.stopAnimation();\n if (tooltipDiv && !document.getElementById(tooltipDiv.id)) {\n document.getElementById(this.element.id + '_Secondary_Element').appendChild(tooltipDiv);\n }\n return true;\n }\n return false;\n };\n BaseTooltip.prototype.removeHighlight = function (chart) {\n var item;\n var series;\n for (var i = 0, len = this.previousPoints.length; i < len; i++) {\n item = this.previousPoints[i];\n if (item.series.isRectSeries) {\n if (item.series.visible) {\n this.highlightPoint(item.series, item.point.index, false);\n }\n continue;\n }\n series = item.series;\n if (!series.marker.visible && item.series.type !== 'Scatter' && item.series.type !== 'Bubble') {\n this.previousPoints.shift();\n len -= 1;\n }\n }\n };\n BaseTooltip.prototype.highlightPoint = function (series, pointIndex, highlight) {\n var element = this.getElement(this.element.id + '_Series_' + series.index + '_Point_' + pointIndex);\n if (element) {\n element.setAttribute('opacity', (highlight ? series.opacity / 2 : series.opacity).toString());\n }\n };\n BaseTooltip.prototype.highlightPoints = function () {\n for (var _i = 0, _a = this.currentPoints; _i < _a.length; _i++) {\n var item = _a[_i];\n if (item.series.isRectSeries && item.series.category === 'Series') {\n this.highlightPoint(item.series, item.point.index, true);\n }\n }\n };\n BaseTooltip.prototype.createTooltip = function (chart, isFirst, header, location, clipLocation, point, shapes, offset, bounds, extraPoints, templatePoint) {\n if (extraPoints === void 0) { extraPoints = null; }\n if (templatePoint === void 0) { templatePoint = null; }\n var series = this.currentPoints[0].series;\n var module = chart.tooltipModule || chart.accumulationTooltipModule;\n if (isFirst) {\n this.svgTooltip = new SVGTooltip({\n opacity: chart.tooltip.opacity,\n header: header, content: this.text, fill: chart.tooltip.fill, border: chart.tooltip.border,\n enableAnimation: chart.tooltip.enableAnimation, location: location, shared: chart.tooltip.shared,\n shapes: shapes, clipBounds: this.chart.chartAreaType === 'PolarRadar' ? new ChartLocation(0, 0) : clipLocation,\n areaBounds: bounds, palette: this.findPalette(), template: chart.tooltip.template, data: templatePoint,\n theme: chart.theme, offset: offset, textStyle: chart.tooltip.textStyle,\n isNegative: (series.isRectSeries && series.type !== 'Waterfall' && point && point.y < 0),\n inverted: this.chart.requireInvertedAxis && series.isRectSeries,\n arrowPadding: this.text.length > 1 ? 0 : 12,\n tooltipRender: function () {\n module.removeHighlight(module.control);\n module.highlightPoints();\n module.updatePreviousPoint(extraPoints);\n },\n animationComplete: function (args) {\n if (args.tooltip.fadeOuted) {\n module.fadeOut(module.previousPoints, chart);\n }\n }\n }, '#' + this.element.id + '_tooltip');\n }\n else {\n this.svgTooltip.location = location;\n this.svgTooltip.content = this.text;\n this.svgTooltip.header = header;\n this.svgTooltip.offset = offset;\n this.svgTooltip.palette = this.findPalette();\n this.svgTooltip.shapes = shapes;\n this.svgTooltip.data = templatePoint;\n this.svgTooltip.template = chart.tooltip.template;\n this.svgTooltip.textStyle = chart.tooltip.textStyle;\n this.svgTooltip.isNegative = (series.isRectSeries && series.type !== 'Waterfall' && point && point.y < 0);\n this.svgTooltip.clipBounds = this.chart.chartAreaType === 'PolarRadar' ? new ChartLocation(0, 0) : clipLocation;\n this.svgTooltip.arrowPadding = this.text.length > 1 ? 0 : 12;\n this.svgTooltip.dataBind();\n }\n };\n BaseTooltip.prototype.findPalette = function () {\n var colors = [];\n for (var _i = 0, _a = this.currentPoints; _i < _a.length; _i++) {\n var data = _a[_i];\n colors.push(this.findColor(data, data.series));\n }\n return colors;\n };\n BaseTooltip.prototype.findColor = function (data, series) {\n if (series.isRectSeries) {\n return data.point.color;\n }\n else {\n return (data.point.color && data.point.color !== '#ffffff' ? data.point.color\n : data.point.interior) ||\n series.marker.fill || series.interior;\n }\n };\n BaseTooltip.prototype.updatePreviousPoint = function (extraPoints) {\n if (extraPoints) {\n this.currentPoints = this.currentPoints.concat(extraPoints);\n }\n this.previousPoints = extend([], this.currentPoints, null, true);\n };\n BaseTooltip.prototype.fadeOut = function (data, chart) {\n var svgElement = this.getElement(this.element.id + '_tooltip_svg');\n var isTooltip = (svgElement && parseInt(svgElement.getAttribute('opacity'), 10) > 0);\n if (!isTooltip) {\n this.valueX = null;\n this.valueY = null;\n this.currentPoints = [];\n this.removeHighlight(chart);\n this.removeHighlightedMarker(data);\n this.svgTooltip = null;\n this.control.trigger('animationComplete', {});\n }\n };\n /*\n * @hidden\n */\n BaseTooltip.prototype.removeHighlightedMarker = function (data) {\n if (this.chart.markerRender) {\n for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {\n var item = data_1[_i];\n removeElement(this.element.id + '_Series_' + item.series.index +\n '_Point_' + item.point.index + '_Trackball');\n }\n this.chart.markerRender.removeHighlightedMarker();\n }\n this.previousPoints = [];\n };\n BaseTooltip.prototype.triggerEvent = function (point, isFirst, textCollection, firstText) {\n if (firstText === void 0) { firstText = true; }\n var argsData = {\n cancel: false, name: tooltipRender, text: textCollection,\n point: point.point, series: point.series, textStyle: this.textStyle\n };\n this.chart.trigger(tooltipRender, argsData);\n if (!argsData.cancel) {\n if (point.series.type === 'BoxAndWhisker') {\n this.removeText();\n isFirst = true;\n }\n this.formattedText = this.formattedText.concat(argsData.text);\n this.text = this.formattedText;\n }\n return !argsData.cancel;\n };\n BaseTooltip.prototype.removeText = function () {\n this.textElements = [];\n var element = this.getElement(this.element.id + '_tooltip_group');\n if (element && element.childNodes.length > 0) {\n while (element.lastChild && element.childNodes.length !== 1) {\n element.removeChild(element.lastChild);\n }\n }\n };\n BaseTooltip.prototype.stopAnimation = function () {\n stopTimer(this.toolTipInterval);\n };\n /**\n * Removes the tooltip on mouse leave.\n * @return {void}\n * @private\n */\n BaseTooltip.prototype.removeTooltip = function (duration) {\n var _this = this;\n var tooltipElement = this.getElement(this.element.id + '_tooltip');\n this.stopAnimation();\n if (tooltipElement && this.previousPoints.length > 0) {\n this.toolTipInterval = setTimeout(function () {\n if (_this.svgTooltip) {\n _this.svgTooltip.fadeOut();\n }\n }, duration);\n }\n };\n return BaseTooltip;\n}(ChartData));\nexport { BaseTooltip };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { extend, Browser } from '@syncfusion/ej2-base';\nimport { PointData, ChartLocation } from '../../common/utils/helper';\nimport { valueToCoefficient, removeElement, valueToPolarCoefficient, withInBounds } from '../../common/utils/helper';\nimport { BaseTooltip } from '../../common/user-interaction/tooltip';\n/**\n * `Tooltip` module is used to render the tooltip for chart series.\n */\nvar Tooltip = /** @class */ (function (_super) {\n __extends(Tooltip, _super);\n /**\n * Constructor for tooltip module.\n * @private.\n */\n function Tooltip(chart) {\n var _this = _super.call(this, chart) || this;\n _this.addEventListener();\n return _this;\n }\n /**\n * @hidden\n */\n Tooltip.prototype.addEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n this.chart.on(cancelEvent, this.mouseLeaveHandler, this);\n this.chart.on('tapHold', this.longPress, this);\n this.chart.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);\n this.chart.on(Browser.touchEndEvent, this.mouseUpHandler, this);\n };\n Tooltip.prototype.mouseUpHandler = function () {\n var chart = this.control;\n if (chart.isTouch && !this.isSelected(chart) &&\n ((withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect) && chart.tooltip.shared)\n || !chart.tooltip.shared)) {\n if (!chart.crosshair.enable) {\n this.tooltip();\n this.removeTooltip(2000);\n }\n else if (chart.startMove) {\n this.removeTooltip(2000);\n }\n }\n };\n Tooltip.prototype.mouseLeaveHandler = function () {\n this.removeTooltip(1000);\n };\n Tooltip.prototype.mouseMoveHandler = function () {\n var chart = this.chart;\n // Tooltip for chart series.\n if (!chart.disableTrackTooltip && !this.isSelected(chart)) {\n if (!chart.tooltip.shared && (!chart.isTouch || (chart.startMove))) {\n this.tooltip();\n }\n if (withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {\n if (chart.tooltip.shared && (!chart.isTouch || (chart.startMove))) {\n this.tooltip();\n }\n }\n else {\n if (chart.tooltip.shared) {\n this.removeTooltip(1000);\n }\n }\n }\n };\n /**\n * Handles the long press on chart.\n * @return {boolean}\n * @private\n */\n Tooltip.prototype.longPress = function () {\n var chart = this.chart;\n if (chart.crosshair.enable && withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {\n this.tooltip();\n }\n return false;\n };\n /**\n * Renders the tooltip.\n * @return {void}\n */\n Tooltip.prototype.tooltip = function () {\n var svgElement = this.getElement(this.element.id + '_tooltip_svg');\n var isTooltip = (svgElement && parseInt(svgElement.getAttribute('opacity'), 10) > 0);\n var tooltipDiv = this.getTooltipElement(isTooltip);\n if (!this.chart.tooltip.shared) {\n this.renderSeriesTooltip(this.chart, !isTooltip, tooltipDiv);\n }\n else {\n this.renderGroupedTooltip(this.chart, !isTooltip, tooltipDiv);\n }\n };\n Tooltip.prototype.findHeader = function (data) {\n if (this.header === '') {\n return '';\n }\n this.header = this.parseTemplate(data.point, data.series, this.header, data.series.xAxis, data.series.yAxis);\n if (this.header.replace(//g, '').replace(/<\\/b>/g, '').trim() !== '') {\n return this.header;\n }\n return '';\n };\n Tooltip.prototype.findShapes = function () {\n var marker = [];\n for (var _i = 0, _a = this.currentPoints; _i < _a.length; _i++) {\n var data = _a[_i];\n marker.push(data.point.marker.shape || data.series.marker.shape);\n }\n return marker;\n };\n Tooltip.prototype.renderSeriesTooltip = function (chart, isFirst, tooltipDiv) {\n var data = this.getData();\n data.lierIndex = this.lierIndex;\n var rect = chart.chartAxisLayoutPanel.seriesClipRect;\n this.currentPoints = [];\n var tool;\n if (this.findData(data, this.previousPoints[0])) {\n if (this.pushData(data, isFirst, tooltipDiv, true)) {\n if (this.triggerEvent(data, isFirst, this.getTooltipText(data))) {\n this.createTooltip(chart, isFirst, this.findHeader(data), this.getSymbolLocation(data), data.series.clipRect, data.point, this.findShapes(), this.findMarkerHeight(this.currentPoints[0]), chart.chartAxisLayoutPanel.seriesClipRect, null, this.getTemplateText(data));\n }\n else {\n this.removeHighlight(this.control);\n this.getElement(this.element.id + '_tooltip').remove();\n }\n this.isRemove = true;\n }\n }\n else {\n if (!data.point && this.isRemove) {\n this.removeTooltip(1000);\n this.isRemove = false;\n }\n else {\n for (var _i = 0, _a = chart.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n if (series.visible) {\n data = this.getClosestX(chart, series) || data;\n }\n }\n }\n }\n if (data && data.point) {\n this.findMouseValue(data, chart);\n }\n };\n Tooltip.prototype.findMarkerHeight = function (pointData) {\n var markerHeight = 0;\n var series = pointData.series;\n if (!series.isRectSeries) {\n markerHeight = (this.chart.tooltip.shared || series.marker.visible || series.type === 'Scatter'\n || series.drawType === 'Scatter') ? ((series.marker.height + 2) / 2 + (2 * series.marker.border.width)) : 0;\n }\n return markerHeight;\n };\n Tooltip.prototype.findData = function (data, previous) {\n return data.point && ((!previous || (previous.point !== data.point)) ||\n (previous && previous.lierIndex > 3 && previous.lierIndex !== this.lierIndex));\n };\n Tooltip.prototype.getSymbolLocation = function (data) {\n var location;\n if (data.series.type !== 'BoxAndWhisker') {\n if (!data.point.symbolLocations[0]) {\n return null;\n }\n location = new ChartLocation(data.point.symbolLocations[0].x, data.point.symbolLocations[0].y);\n }\n switch (data.series.type) {\n case 'BoxAndWhisker':\n return this.getBoxLocation(data);\n case 'Waterfall':\n return this.getWaterfallRegion(data, location);\n case 'RangeArea':\n return this.getRangeArea(data, location);\n default:\n return location;\n }\n };\n Tooltip.prototype.getRangeArea = function (data, location) {\n if (data.point.regions[0]) {\n if (!this.inverted) {\n location.y = data.point.regions[0].y + data.point.regions[0].height / 2;\n }\n else {\n location.x = data.point.regions[0].x + data.point.regions[0].width / 2;\n }\n }\n return location;\n };\n Tooltip.prototype.getWaterfallRegion = function (data, location) {\n if (!this.inverted) {\n location.y = (data.point.y < 0) ?\n location.y - data.point.regions[0].height : location.y;\n }\n else {\n location.x = (data.point.y < 0) ?\n location.x + data.point.regions[0].width : location.x;\n }\n return location;\n };\n Tooltip.prototype.getTooltipText = function (pointData) {\n var series = pointData.series;\n return this.parseTemplate(pointData.point, series, this.getFormat(this.chart, series), series.xAxis, series.yAxis);\n };\n Tooltip.prototype.getTemplateText = function (data) {\n if (this.chart.tooltip.template) {\n var point = extend({}, data.point);\n point.x = this.formatPointValue(data.point, data.series.xAxis, 'x', true, false);\n if ((data.series.seriesType === 'XY')) {\n point.y = this.formatPointValue(data.point, data.series.yAxis, 'y', false, true);\n }\n else {\n point.low = this.formatPointValue(data.point, data.series.yAxis, 'low', false, true);\n point.high = this.formatPointValue(data.point, data.series.yAxis, 'high', false, true);\n }\n return point;\n }\n else {\n return data.point;\n }\n };\n Tooltip.prototype.findMouseValue = function (data, chart) {\n if (!chart.requireInvertedAxis) {\n if (chart.chartAreaType === 'PolarRadar') {\n this.valueX = valueToPolarCoefficient(data.point.xValue, data.series.xAxis) * data.series.xAxis.rect.width\n + data.series.xAxis.rect.x;\n }\n else {\n this.valueX = valueToCoefficient(data.point.xValue, data.series.xAxis) * data.series.xAxis.rect.width\n + data.series.xAxis.rect.x;\n }\n this.valueY = chart.mouseY;\n }\n else {\n this.valueY = (1 - valueToCoefficient(data.point.xValue, data.series.xAxis)) * data.series.xAxis.rect.height\n + data.series.xAxis.rect.y;\n this.valueX = chart.mouseX;\n }\n };\n Tooltip.prototype.renderGroupedTooltip = function (chart, isFirst, tooltipDiv) {\n var data;\n var height = 0;\n var width = 0;\n var pointData = chart.chartAreaType === 'PolarRadar' ? this.getData() : null;\n this.stopAnimation();\n this.removeHighlight(chart);\n this.currentPoints = [];\n var extraPoints = [];\n var headerContent = '';\n if (isFirst) {\n document.getElementById(this.element.id + '_Secondary_Element').appendChild(tooltipDiv);\n }\n this.removeText();\n for (var _i = 0, _a = chart.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n if (!series.enableTooltip) {\n continue;\n }\n if (chart.chartAreaType === 'Cartesian' && series.visible) {\n data = this.getClosestX(chart, series);\n }\n else if (chart.chartAreaType === 'PolarRadar' && series.visible && pointData.point !== null) {\n data = new PointData(series.points[pointData.point.index], series);\n }\n if (data && this.header !== '' && this.currentPoints.length === 0) {\n headerContent = this.findHeader(data);\n }\n if (data && this.triggerEvent(data, isFirst, this.getTooltipText(data))) {\n this.findMouseValue(data, chart);\n this.currentPoints.push(data);\n data = null;\n }\n else if (data) {\n extraPoints.push(data);\n }\n }\n if (this.currentPoints.length > 0) {\n this.createTooltip(chart, isFirst, headerContent, this.findSharedLocation(), this.currentPoints.length === 1 ? this.currentPoints[0].series.clipRect : null, null, this.findShapes(), this.findMarkerHeight(this.currentPoints[0]), chart.chartAxisLayoutPanel.seriesClipRect, extraPoints);\n }\n else if (this.getElement(this.element.id + '_tooltip_path')) {\n this.getElement(this.element.id + '_tooltip_path').setAttribute('d', '');\n }\n };\n Tooltip.prototype.findSharedLocation = function () {\n if (this.currentPoints.length > 1) {\n return new ChartLocation(this.valueX, this.valueY);\n }\n else {\n return this.getSymbolLocation(this.currentPoints[0]);\n }\n };\n Tooltip.prototype.getBoxLocation = function (data) {\n var location;\n location = this.lierIndex > 3 ? data.point.symbolLocations[this.lierIndex - 4] :\n {\n x: data.point.regions[0].x + (data.point.regions[0].width / 2),\n y: data.point.regions[0].y + (data.point.regions[0].height / 2)\n };\n return location;\n };\n Tooltip.prototype.parseTemplate = function (point, series, format, xAxis, yAxis) {\n var val;\n var textValue;\n var xFormat;\n var customLabelFormat;\n var chart = this.chart;\n for (var _i = 0, _a = Object.keys(point); _i < _a.length; _i++) {\n var dataValue = _a[_i];\n val = new RegExp('${point' + '.' + dataValue + '}', 'gm');\n format = format.replace(val.source, this.formatPointValue(point, val.source === '${point.x}' ? xAxis : yAxis, dataValue, val.source === '${point.x}', (val.source === '${point.high}' ||\n val.source === '${point.open}' ||\n val.source === '${point.close}' ||\n val.source === '${point.low}' ||\n val.source === '${point.y}' ||\n val.source === '${point.minimum}' ||\n val.source === '${point.maximum}' ||\n val.source === '${point.outliers}' ||\n val.source === '${point.upperQuartile}' ||\n val.source === '${point.lowerQuartile}' ||\n val.source === '${point.median}')));\n }\n for (var _b = 0, _c = Object.keys(Object.getPrototypeOf(series)); _b < _c.length; _b++) {\n var dataValue = _c[_b];\n val = new RegExp('${series' + '.' + dataValue + '}', 'gm');\n textValue = series[dataValue];\n format = format.replace(val.source, textValue);\n }\n return format;\n };\n Tooltip.prototype.formatPointValue = function (point, axis, dataValue, isXPoint, isYPoint) {\n var textValue;\n var customLabelFormat;\n var value;\n if (axis.valueType !== 'Category' && isXPoint) {\n customLabelFormat = axis.labelFormat && axis.labelFormat.match('{value}') !== null;\n textValue = customLabelFormat ? axis.labelFormat.replace('{value}', axis.format(point[dataValue])) :\n axis.format(point[dataValue]);\n }\n else if (isYPoint) {\n customLabelFormat = axis.labelFormat && axis.labelFormat.match('{value}') !== null;\n value = dataValue === 'outliers' ? axis.format(point[dataValue][this.lierIndex - 4]) :\n axis.format(point[dataValue]);\n textValue = customLabelFormat ? axis.labelFormat.replace('{value}', value) : value;\n }\n else {\n textValue = point[dataValue];\n }\n return textValue;\n };\n Tooltip.prototype.getFormat = function (chart, series) {\n if (chart.tooltip.format) {\n if (series.seriesType === 'XY' && series.category === 'Indicator') {\n return this.getIndicatorTooltipFormat(series, chart, chart.tooltip.format);\n }\n return chart.tooltip.format;\n }\n var textX = (series.type === 'Histogram') ? '${point.minimum}' + '-' + '${point.maximum}' : '${point.x}';\n var format = !chart.tooltip.shared ? textX : '${series.name}';\n switch (series.seriesType) {\n case 'XY':\n if (series.category === 'Indicator') {\n this.getIndicatorTooltipFormat(series, chart, chart.tooltip.format);\n }\n return format + ' : ' + ((series.type === 'Bubble') ? '${point.y} Size : ${point.size} '\n : '${point.y} ');\n case 'HighLow':\n return format + (' High : ${point.high} Low : ${point.low} ');\n case 'HighLowOpenClose':\n return format + (' High : ${point.high} Low : ${point.low} ' +\n 'Open : ${point.open} Close : ${point.close} ');\n case 'BoxPlot': {\n return format + ' ' + (this.lierIndex > 3 ? 'Outliers : ${point.outliers} ' :\n 'Maximum : ${point.maximum} Q1 : ${point.upperQuartile} ' +\n 'Median : ${point.median} Q3 : ${point.lowerQuartile} Minimum : ${point.minimum} ');\n }\n }\n return '';\n };\n Tooltip.prototype.getIndicatorTooltipFormat = function (series, chart, format) {\n var toolTip;\n var points = [];\n if (series.seriesType === 'XY') {\n toolTip = series.name + ' : ${point.y}';\n }\n else {\n toolTip = format;\n }\n return toolTip;\n };\n /*\n * @hidden\n */\n Tooltip.prototype.removeHighlightedMarker = function (data) {\n for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {\n var item = data_1[_i];\n removeElement(this.element.id + '_Series_' + item.series.index +\n '_Point_' + item.point.index + '_Trackball');\n }\n if (this.chart.markerRender) {\n this.chart.markerRender.removeHighlightedMarker();\n }\n this.previousPoints = [];\n };\n /**\n * Get module name.\n */\n Tooltip.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'Tooltip';\n };\n /**\n * To destroy the tooltip.\n * @return {void}\n * @private\n */\n Tooltip.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return Tooltip;\n}(BaseTooltip));\nexport { Tooltip };\n","import { EventHandler } from '@syncfusion/ej2-base';\nimport { remove } from '@syncfusion/ej2-base';\nimport { removeElement, measureText, RectOption, Rect, PolygonOption, PathOption, createTooltip, minMax } from '../../common/utils/helper';\nimport { textElement, TextOption } from '../../common/utils/helper';\n/**\n * Zooming Toolkit created here\n * @private\n */\nvar Toolkit = /** @class */ (function () {\n /** @private */\n function Toolkit(chart) {\n this.chart = chart;\n this.elementId = chart.element.id;\n this.selectionColor = '#ff4081';\n this.fillColor = '#737373';\n }\n /**\n * To create the pan button.\n * @return {void}\n * @private\n */\n Toolkit.prototype.createPanButton = function (childElement, parentElement, chart) {\n var render = this.chart.renderer;\n var fillColor = this.chart.zoomModule.isPanning ? this.selectionColor : this.fillColor;\n var direction = 'M5,3h2.3L7.275,5.875h1.4L8.65,3H11L8,0L5,3z M3,11V8.7l2.875,0.025v-1.4L3,7.35V5L0,8L3,';\n direction += '11z M11,13H8.7l0.025-2.875h-1.4L7.35,13H5l3,3L11,13z M13,5v2.3l-2.875-0.025v1.4L13,8.65V11l3-3L13,5z';\n childElement.id = this.elementId + '_Zooming_Pan';\n childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('Pan'));\n this.panElements = childElement;\n childElement.appendChild(render.drawRectangle(new RectOption(this.elementId + '_Zooming_Pan_1', 'transparent', {}, 1, new Rect(0, 0, 16, 16))));\n childElement.appendChild(render.drawPath(new PathOption(this.elementId + '_Zooming_Pan_2', fillColor, null, null, 1, null, direction)));\n parentElement.appendChild(childElement);\n this.wireEvents(childElement, this.pan);\n };\n /**\n * To create the zoom button.\n * @return {void}\n * @private\n */\n Toolkit.prototype.createZoomButton = function (childElement, parentElement, chart) {\n var render = this.chart.renderer;\n var fillColor = this.chart.zoomModule.isPanning ? this.fillColor : this.selectionColor;\n var direction = 'M0.001,14.629L1.372,16l4.571-4.571v-0.685l0.228-0.274c1.051,0.868,2.423,1.417,3.885,1.417c3.291,0,';\n direction += '5.943-2.651,5.943-5.943S13.395,0,10.103,0S4.16,2.651,4.16,5.943c0,1.508,0.503,2.834,1.417,3.885l-0.274,0.228H4.571';\n direction = direction + 'L0.001,14.629L0.001,14.629z M5.943,5.943c0-2.285,1.828-4.114,4.114-4.114s4.114,1.828,4.114,';\n childElement.id = this.elementId + '_Zooming_Zoom';\n childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('Zoom'));\n this.zoomElements = childElement;\n childElement.appendChild(render.drawRectangle(new RectOption(this.elementId + '_Zooming_Zoom_1', 'transparent', {}, 1, new Rect(0, 0, 16, 16))));\n childElement.appendChild(render.drawPath(new PathOption(this.elementId + '_Zooming_Zoom_3', fillColor, null, null, 1, null, direction + '4.114s-1.828,4.114-4.114,4.114S5.943,8.229,5.943,5.943z')));\n parentElement.appendChild(childElement);\n this.wireEvents(childElement, this.zoom);\n };\n /**\n * To create the ZoomIn button.\n * @return {void}\n * @private\n */\n Toolkit.prototype.createZoomInButton = function (childElement, parentElement, chart) {\n var render = this.chart.renderer;\n var fillColor = this.fillColor;\n var direction = 'M10.103,0C6.812,0,4.16,2.651,4.16,5.943c0,1.509,0.503,2.834,1.417,3.885l-0.274,0.229H4.571L0,';\n direction += '14.628l0,0L1.372,16l4.571-4.572v-0.685l0.228-0.275c1.052,0.868,2.423,1.417,3.885,1.417c3.291,0,5.943-2.651,';\n direction += '5.943-5.943C16,2.651,13.395,0,10.103,0z M10.058,10.058c-2.286,0-4.114-1.828-4.114-4.114c0-2.286,1.828-4.114,';\n childElement.id = this.elementId + '_Zooming_ZoomIn';\n childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('ZoomIn'));\n var polygonDirection = '12.749,5.466 10.749,5.466 10.749,3.466 9.749,3.466 9.749,5.466 7.749,5.466 7.749,6.466';\n childElement.appendChild(render.drawRectangle(new RectOption(this.elementId + '_Zooming_ZoomIn_1', 'transparent', {}, 1, new Rect(0, 0, 16, 16))));\n childElement.appendChild(render.drawPath(new PathOption(this.elementId + '_Zooming_ZoomIn_2', fillColor, null, null, 1, null, direction + '4.114-4.114c2.286,0,4.114,1.828,4.114,4.114C14.172,8.229,12.344,10.058,10.058,10.058z')));\n childElement.appendChild(render.drawPolygon(new PolygonOption(this.elementId + '_Zooming_ZoomIn_3', polygonDirection + ' 9.749,6.466 9.749,8.466 10.749,8.466 10.749,6.466 12.749,6.466', fillColor)));\n this.zoomInElements = childElement;\n this.elementOpacity = chart.zoomModule.isPanning ? '0.2' : '1';\n childElement.setAttribute('opacity', this.elementOpacity);\n parentElement.appendChild(childElement);\n this.wireEvents(childElement, this.zoomIn);\n };\n /**\n * To create the ZoomOut button.\n * @return {void}\n * @private\n */\n Toolkit.prototype.createZoomOutButton = function (childElement, parentElement, chart) {\n var render = this.chart.renderer;\n var fillColor = this.fillColor;\n var direction = 'M0,14.622L1.378,16l4.533-4.533v-0.711l0.266-0.266c1.022,0.889,2.4,1.422,3.866,';\n direction += '1.422c3.289,0,5.955-2.666,5.955-5.955S13.333,0,10.044,0S4.089,2.667,4.134,5.911c0,1.466,0.533,2.844,';\n direction += '1.422,3.866l-0.266,0.266H4.578L0,14.622L0,14.622z M5.911,5.911c0-2.311,1.822-4.133,4.133-4.133s4.133,1.822,4.133,';\n childElement.id = this.elementId + '_Zooming_ZoomOut';\n childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('ZoomOut'));\n childElement.appendChild(render.drawRectangle(new RectOption(this.elementId + '_Zooming_ZoomOut_1', 'transparent', {}, 1, new Rect(0, 0, 16, 16))));\n childElement.appendChild(render.drawPath(new PathOption(this.elementId + '_Zooming_ZoomOut_2', fillColor, null, null, 1, null, direction + '4.133s-1.866,4.133-4.133,4.133S5.911,8.222,5.911,5.911z M12.567,6.466h-5v-1h5V6.466z')));\n this.zoomOutElements = childElement;\n this.elementOpacity = chart.zoomModule.isPanning ? '0.2' : '1';\n childElement.setAttribute('opacity', this.elementOpacity);\n parentElement.appendChild(childElement);\n this.wireEvents(childElement, this.zoomOut);\n };\n /**\n * To create the Reset button.\n * @return {void}\n * @private\n */\n Toolkit.prototype.createResetButton = function (childElement, parentElement, chart, isDevice) {\n var render = this.chart.renderer;\n var fillColor = this.fillColor;\n var size;\n var direction = 'M12.364,8h-2.182l2.909,3.25L16,8h-2.182c0-3.575-2.618-6.5-5.818-6.5c-1.128,0-2.218,0.366-3.091,';\n direction += '1.016l1.055,1.178C6.581,3.328,7.272,3.125,8,3.125C10.4,3.125,12.363,5.319,12.364,8L12.364,8z M11.091,';\n direction += '13.484l-1.055-1.178C9.419,12.672,8.728,12.875,8,12.875c-2.4,0-4.364-2.194-4.364-4.875h2.182L2.909,4.75L0,8h2.182c0,';\n childElement.id = this.elementId + '_Zooming_Reset';\n childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('Reset'));\n if (!isDevice) {\n childElement.appendChild(render.drawRectangle(new RectOption(this.elementId + '_Zooming_Reset_1', 'transparent', {}, 1, new Rect(0, 0, 16, 16))));\n childElement.appendChild(render.drawPath(new PathOption(this.elementId + '_Zooming_Reset_2', fillColor, null, null, 1, null, direction + '3.575,2.618,6.5,5.818,6.5C9.128,14.5,10.219,14.134,11.091,13.484L11.091,13.484z')));\n }\n else {\n size = measureText(this.chart.getLocalizedLabel('ResetZoom'), { size: '12px' });\n childElement.appendChild(render.drawRectangle(new RectOption(this.elementId + '_Zooming_Reset_1', 'transparent', {}, 1, new Rect(0, 0, size.width, size.height))));\n textElement(new TextOption(this.elementId + '_Zooming_Reset_2', 0 + size.width / 2, 0 + size.height * 3 / 4, 'middle', this.chart.getLocalizedLabel('ResetZoom'), 'rotate(0,' + (0) + ',' + (0) + ')', 'auto'), { size: '12px' }, 'black', childElement);\n }\n parentElement.appendChild(childElement);\n this.wireEvents(childElement, this.reset);\n };\n /**\n * To bind events.\n * @return {void}\n * @private\n */\n Toolkit.prototype.wireEvents = function (element, process) {\n EventHandler.add(element, 'mousedown touchstart', process, this);\n EventHandler.add(element, 'mouseover', this.showTooltip, this);\n EventHandler.add(element, 'mouseout', this.removeTooltip, this);\n };\n /**\n * To show tooltip.\n * @return {void}\n * @private\n */\n Toolkit.prototype.showTooltip = function (event) {\n var text = event.currentTarget.id.split('_Zooming_')[1];\n var left = (event.pageX - (measureText(text, { size: '10px' }).width + 5));\n if (!this.chart.isTouch) {\n createTooltip('EJ2_Chart_ZoomTip', this.chart.getLocalizedLabel(text), (event.pageY + 10), left, '10px');\n }\n };\n /** @private */\n Toolkit.prototype.removeTooltip = function () {\n removeElement('EJ2_Chart_ZoomTip');\n };\n // Toolkit events function calculation here.\n /** @private */\n Toolkit.prototype.reset = function () {\n var chart = this.chart;\n if (!chart.zoomModule.isDevice) {\n remove(chart.zoomModule.toolkitElements);\n }\n this.removeTooltip();\n chart.svgObject.setAttribute('cursor', 'auto');\n chart.axisCollections.forEach(function (axis) {\n axis.zoomFactor = 1;\n axis.zoomPosition = 0;\n if (axis.zoomingScrollBar) {\n axis.zoomingScrollBar.isScrollUI = false;\n }\n });\n chart.disableTrackTooltip = false;\n chart.zoomModule.isZoomed = chart.zoomModule.isPanning = chart.isChartDrag = chart.delayRedraw = false;\n chart.zoomModule.touchMoveList = chart.zoomModule.touchStartList = [];\n chart.zoomModule.pinchTarget = null;\n chart.removeSvg();\n chart.refreshAxis();\n chart.refreshBound();\n this.elementOpacity = '1';\n return false;\n };\n Toolkit.prototype.zoomIn = function (e) {\n this.zoomInOutCalculation(1, this.chart, this.chart.axisCollections, this.chart.zoomSettings.mode);\n return false;\n };\n Toolkit.prototype.zoomOut = function (e) {\n this.zoomInOutCalculation(-1, this.chart, this.chart.axisCollections, this.chart.zoomSettings.mode);\n return false;\n };\n Toolkit.prototype.zoom = function (e) {\n this.chart.zoomModule.isPanning = false;\n var zoomModule = this.chart.zoomModule;\n this.elementOpacity = '1';\n this.chart.svgObject.setAttribute('cursor', 'auto');\n this.zoomInElements.setAttribute('opacity', this.elementOpacity);\n this.zoomOutElements.setAttribute('opacity', this.elementOpacity);\n this.applySelection(this.zoomElements.childNodes, this.selectionColor);\n this.applySelection(this.panElements.childNodes, '#737373');\n return false;\n };\n /** @private */\n Toolkit.prototype.pan = function () {\n var zoomModule = this.chart.zoomModule;\n var element;\n this.chart.zoomModule.isPanning = true;\n this.chart.svgObject.setAttribute('cursor', 'pointer');\n this.elementOpacity = '0.2';\n element = this.zoomInElements ? this.zoomInElements.setAttribute('opacity', this.elementOpacity) : null;\n element = this.zoomOutElements ? this.zoomOutElements.setAttribute('opacity', this.elementOpacity) : null;\n element = this.panElements ? this.applySelection(this.panElements.childNodes, this.selectionColor) : null;\n element = this.zoomElements ? this.applySelection(this.zoomElements.childNodes, '#737373') : null;\n return false;\n };\n Toolkit.prototype.zoomInOutCalculation = function (scale, chart, axes, mode) {\n if (!chart.zoomModule.isPanning && this.elementOpacity !== '0.2') {\n var zoomFactor_1;\n var zoomPosition_1;\n var cumulative_1;\n chart.disableTrackTooltip = true;\n chart.delayRedraw = true;\n axes.forEach(function (axis) {\n if ((axis.orientation === 'Horizontal' && mode !== 'Y') ||\n (axis.orientation === 'Vertical' && mode !== 'X')) {\n cumulative_1 = Math.max(Math.max(1 / minMax(axis.zoomFactor, 0, 1), 1) + (0.25 * scale), 1);\n zoomFactor_1 = (cumulative_1 === 1) ? 1 : minMax(1 / cumulative_1, 0, 1);\n zoomPosition_1 = (cumulative_1 === 1) ? 0 : axis.zoomPosition + ((axis.zoomFactor - zoomFactor_1) * 0.5);\n if (axis.zoomPosition !== zoomPosition_1 || axis.zoomFactor !== zoomFactor_1) {\n zoomFactor_1 = (zoomPosition_1 + zoomFactor_1) > 1 ? (1 - zoomPosition_1) : zoomFactor_1;\n }\n axis.zoomFactor = zoomFactor_1;\n axis.zoomPosition = zoomPosition_1;\n }\n });\n }\n };\n Toolkit.prototype.applySelection = function (elements, color) {\n for (var i = 1, length_1 = elements.length; i < length_1; i++) {\n elements[i].setAttribute('fill', color);\n }\n };\n return Toolkit;\n}());\nexport { Toolkit };\n","import { EventHandler, Browser, createElement } from '@syncfusion/ej2-base';\nimport { getRectLocation, minMax, getElement, ChartLocation, Rect, RectOption, measureText } from '../../common/utils/helper';\nimport { Toolkit } from './zooming-toolkit';\nimport { zoomComplete } from '../../common/model/constants';\nimport { withInBounds } from '../../common/utils/helper';\n/**\n * `Zooming` module handles the zooming for chart.\n */\nvar Zoom = /** @class */ (function () {\n /**\n * Constructor for Zooming module.\n * @private.\n */\n function Zoom(chart) {\n this.chart = chart;\n this.isPointer = Browser.isPointer;\n this.browserName = Browser.info.name;\n this.wheelEvent = this.browserName === 'mozilla' ? (this.isPointer ? 'mousewheel' : 'DOMMouseScroll') : 'mousewheel';\n this.cancelEvent = this.isPointer ? 'pointerleave' : 'mouseleave';\n this.addEventListener();\n this.isDevice = Browser.isDevice;\n var zooming = chart.zoomSettings;\n this.toolkit = new Toolkit(chart);\n this.zooming = zooming;\n this.elementId = chart.element.id;\n this.zoomingRect = new Rect(0, 0, 0, 0);\n this.zoomAxes = [];\n this.zoomkitOpacity = 0.3;\n this.isIOS = Browser.isIos || Browser.isIos7;\n this.isZoomed = this.performedUI = this.zooming.enablePan && this.zooming.enableSelectionZooming;\n if (zooming.enableScrollbar) {\n chart.scrollElement = createElement('div', { id: chart.element.id + '_scrollElement' });\n }\n }\n /**\n * Function that handles the Rectangular zooming.\n * @return {void}\n */\n Zoom.prototype.renderZooming = function (e, chart, isTouch) {\n this.calculateZoomAxesRange(chart, chart.axisCollections);\n if (this.zooming.enableSelectionZooming && (!isTouch\n || (chart.isDoubleTap && this.touchStartList.length === 1)) && (!this.isPanning || chart.isDoubleTap)) {\n this.isPanning = this.isDevice ? true : this.isPanning;\n this.performedUI = true;\n this.drawZoomingRectangle(chart);\n }\n else if (this.isPanning && chart.isChartDrag) {\n if (!isTouch || (isTouch && this.touchStartList.length === 1)) {\n this.pinchTarget = isTouch ? e.target : null;\n this.doPan(chart, chart.axisCollections);\n }\n }\n };\n // Zooming rectangle drawn here\n Zoom.prototype.drawZoomingRectangle = function (chart) {\n var areaBounds = chart.chartAxisLayoutPanel.seriesClipRect;\n var startLocation = new ChartLocation(chart.previousMouseMoveX, chart.previousMouseMoveY);\n var endLocation = new ChartLocation(chart.mouseX, chart.mouseY);\n var rect = this.zoomingRect = getRectLocation(startLocation, endLocation, areaBounds);\n if (rect.width > 0 && rect.height > 0) {\n this.isZoomed = true;\n chart.disableTrackTooltip = true;\n chart.svgObject.setAttribute('cursor', 'crosshair');\n if (this.zooming.mode === 'X') {\n rect.height = areaBounds.height;\n rect.y = areaBounds.y;\n }\n else if (this.zooming.mode === 'Y') {\n rect.width = areaBounds.width;\n rect.x = areaBounds.x;\n }\n chart.svgObject.appendChild(chart.renderer.drawRectangle(new RectOption(this.elementId + '_ZoomArea', chart.themeStyle.selectionRectFill, { color: chart.themeStyle.selectionRectStroke, width: 1 }, 1, rect, 0, 0, '', '3')));\n }\n };\n // Panning performed here\n Zoom.prototype.doPan = function (chart, axes) {\n if (chart.startMove && chart.crosshair.enable) {\n return null;\n }\n var currentScale;\n var offset;\n this.isZoomed = true;\n var translateX;\n var translateY;\n this.offset = !chart.delayRedraw ? chart.chartAxisLayoutPanel.seriesClipRect : this.offset;\n chart.delayRedraw = true;\n chart.disableTrackTooltip = true;\n axes.forEach(function (axis) {\n currentScale = Math.max(1 / minMax(axis.zoomFactor, 0, 1), 1);\n if (axis.orientation === 'Horizontal') {\n offset = (chart.previousMouseMoveX - chart.mouseX) / axis.rect.width / currentScale;\n axis.zoomPosition = minMax(axis.zoomPosition + offset, 0, (1 - axis.zoomFactor));\n }\n else {\n offset = (chart.previousMouseMoveY - chart.mouseY) / axis.rect.height / currentScale;\n axis.zoomPosition = minMax(axis.zoomPosition - offset, 0, (1 - axis.zoomFactor));\n }\n });\n if (this.zooming.enableDeferredZooming) {\n translateX = chart.mouseX - chart.mouseDownX;\n translateY = chart.mouseY - chart.mouseDownY;\n switch (this.zooming.mode) {\n case 'X':\n translateY = 0;\n break;\n case 'Y':\n translateX = 0;\n break;\n }\n this.setTransform(translateX, translateY, null, null, chart, false);\n this.refreshAxis(chart.chartAxisLayoutPanel, chart, chart.axisCollections);\n }\n else {\n this.performZoomRedraw(chart);\n }\n chart.previousMouseMoveX = chart.mouseX;\n chart.previousMouseMoveY = chart.mouseY;\n };\n /**\n * Redraw the chart on zooming.\n * @return {void}\n * @private\n */\n Zoom.prototype.performZoomRedraw = function (chart) {\n var rect = this.zoomingRect;\n chart.animateSeries = false;\n if (this.isZoomed) {\n if (rect.width > 0 && rect.height > 0) {\n this.performedUI = true;\n chart.svgObject.setAttribute('cursor', 'auto');\n this.doZoom(chart, chart.axisCollections, chart.chartAxisLayoutPanel.seriesClipRect);\n chart.isDoubleTap = false;\n }\n else if (chart.disableTrackTooltip) {\n chart.disableTrackTooltip = false;\n chart.delayRedraw = false;\n chart.removeSvg();\n chart.refreshAxis();\n chart.refreshBound();\n }\n }\n };\n Zoom.prototype.refreshAxis = function (layout, chart, axes) {\n var mode = chart.zoomSettings.mode;\n layout.measureAxis(new Rect(chart.initialClipRect.x, chart.initialClipRect.y, chart.initialClipRect.width, chart.initialClipRect.height));\n axes.map(function (axis, index) {\n if (axis.orientation === 'Horizontal' && mode !== 'Y') {\n layout.drawXAxisLabels(axis, index, null, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n }\n if (axis.orientation === 'Vertical' && mode !== 'X') {\n layout.drawYAxisLabels(axis, index, null, (axis.placeNextToAxisLine ? axis.updatedRect : axis.rect));\n }\n });\n };\n // Rectangular zoom calculated here performed here\n Zoom.prototype.doZoom = function (chart, axes, bounds) {\n var zoomRect = this.zoomingRect;\n var mode = this.zooming.mode;\n var argsData;\n var previousZF;\n var previousZP;\n var currentZF;\n var currentZP;\n this.isPanning = chart.zoomSettings.enablePan || this.isPanning;\n axes.forEach(function (axis) {\n previousZF = currentZF = axis.zoomFactor;\n previousZP = currentZP = axis.zoomPosition;\n argsData = {\n cancel: false, name: zoomComplete, axis: axis, previousZoomFactor: previousZF, previousZoomPosition: previousZP,\n currentZoomFactor: currentZF, currentZoomPosition: currentZP\n };\n if (axis.orientation === 'Horizontal') {\n if (mode !== 'Y') {\n currentZP += Math.abs((zoomRect.x - bounds.x) / (bounds.width)) * axis.zoomFactor;\n currentZF *= (zoomRect.width / bounds.width);\n argsData.currentZoomPosition = currentZP;\n argsData.currentZoomFactor = currentZF;\n chart.trigger(zoomComplete, argsData);\n }\n }\n else {\n if (mode !== 'X') {\n currentZP += (1 - Math.abs((zoomRect.height + (zoomRect.y - bounds.y)) / (bounds.height))) * axis.zoomFactor;\n currentZF *= (zoomRect.height / bounds.height);\n argsData.currentZoomFactor = currentZF;\n argsData.currentZoomPosition = currentZP;\n chart.trigger(zoomComplete, argsData);\n }\n }\n if (!argsData.cancel) {\n axis.zoomFactor = argsData.currentZoomFactor;\n axis.zoomPosition = argsData.currentZoomPosition;\n }\n });\n this.zoomingRect = new Rect(0, 0, 0, 0);\n this.performZoomRedraw(chart);\n };\n /**\n * Function that handles the Mouse wheel zooming.\n * @return {void}\n * @private\n */\n Zoom.prototype.performMouseWheelZooming = function (e, mouseX, mouseY, chart, axes) {\n var direction = (this.browserName === 'mozilla' && !this.isPointer) ?\n -(e.detail) / 3 > 0 ? 1 : -1 : (e.wheelDelta / 120) > 0 ? 1 : -1;\n var mode = this.zooming.mode;\n var origin = 0.5;\n var cumulative;\n var zoomFactor;\n var zoomPosition;\n this.isZoomed = true;\n this.calculateZoomAxesRange(chart, chart.axisCollections);\n chart.disableTrackTooltip = true;\n this.performedUI = true;\n this.isPanning = chart.zoomSettings.enablePan || this.isPanning;\n axes.forEach(function (axis) {\n if ((axis.orientation === 'Vertical' && mode !== 'X') ||\n (axis.orientation === 'Horizontal' && mode !== 'Y')) {\n cumulative = Math.max(Math.max(1 / minMax(axis.zoomFactor, 0, 1), 1) + (0.25 * direction), 1);\n if (cumulative >= 1) {\n origin = axis.orientation === 'Horizontal' ? mouseX / axis.rect.width : 1 - (mouseY / axis.rect.height);\n origin = origin > 1 ? 1 : origin < 0 ? 0 : origin;\n zoomFactor = (cumulative === 1) ? 1 : minMax(1 / cumulative, 0, 1);\n zoomPosition = (cumulative === 1) ? 0 : axis.zoomPosition + ((axis.zoomFactor - zoomFactor) * origin);\n if (axis.zoomPosition !== zoomPosition || axis.zoomFactor !== zoomFactor) {\n zoomFactor = (zoomPosition + zoomFactor) > 1 ? (1 - zoomPosition) : zoomFactor;\n }\n }\n axis.zoomFactor = zoomFactor;\n axis.zoomPosition = zoomPosition;\n }\n });\n this.performZoomRedraw(chart);\n };\n /**\n * Function that handles the Pinch zooming.\n * @return {void}\n * @private\n */\n Zoom.prototype.performPinchZooming = function (e, chart) {\n if ((this.zoomingRect.width > 0 && this.zoomingRect.height > 0) || (chart.startMove && chart.crosshair.enable)) {\n return false;\n }\n this.calculateZoomAxesRange(chart, chart.axisCollections);\n this.isZoomed = true;\n this.isPanning = true;\n this.performedUI = true;\n this.offset = !chart.delayRedraw ? chart.chartAxisLayoutPanel.seriesClipRect : this.offset;\n chart.delayRedraw = true;\n chart.disableTrackTooltip = true;\n var elementOffset = chart.element.getBoundingClientRect();\n var touchDown = this.touchStartList;\n var touchMove = this.touchMoveList;\n var touch0StartX = touchDown[0].pageX - elementOffset.left;\n var touch0StartY = touchDown[0].pageY - elementOffset.top;\n var touch0EndX = touchMove[0].pageX - elementOffset.left;\n var touch0EndY = touchMove[0].pageY - elementOffset.top;\n var touch1StartX = touchDown[1].pageX - elementOffset.left;\n var touch1StartY = touchDown[1].pageY - elementOffset.top;\n var touch1EndX = touchMove[1].pageX - elementOffset.left;\n var touch1EndY = touchMove[1].pageY - elementOffset.top;\n var scaleX;\n var scaleY;\n var translateXValue;\n var translateYValue;\n var pinchRect;\n var clipX;\n var clipY;\n scaleX = Math.abs(touch0EndX - touch1EndX) / Math.abs(touch0StartX - touch1StartX);\n scaleY = Math.abs(touch0EndY - touch1EndY) / Math.abs(touch0StartY - touch1StartY);\n clipX = ((this.offset.x - touch0EndX) / scaleX) + touch0StartX;\n clipY = ((this.offset.y - touch0EndY) / scaleY) + touch0StartY;\n pinchRect = new Rect(clipX, clipY, this.offset.width / scaleX, this.offset.height / scaleY);\n translateXValue = (touch0EndX - (scaleX * touch0StartX));\n translateYValue = (touch0EndY - (scaleY * touch0StartY));\n if (!isNaN(scaleX - scaleX) && !isNaN(scaleY - scaleY)) {\n switch (this.zooming.mode) {\n case 'XY':\n this.setTransform(translateXValue, translateYValue, scaleX, scaleY, chart, true);\n break;\n case 'X':\n this.setTransform(translateXValue, 0, scaleX, 1, chart, true);\n break;\n case 'Y':\n this.setTransform(0, translateYValue, 1, scaleY, chart, true);\n break;\n }\n }\n this.calculatePinchZoomFactor(chart, pinchRect);\n this.refreshAxis(chart.chartAxisLayoutPanel, chart, chart.axisCollections);\n return true;\n };\n Zoom.prototype.calculatePinchZoomFactor = function (chart, pinchRect) {\n var _this = this;\n var mode = this.zooming.mode;\n var selectionMin;\n var selectionMax;\n var rangeMin;\n var rangeMax;\n var value;\n var axisTrans;\n chart.axisCollections.forEach(function (axis, index) {\n if ((axis.orientation === 'Horizontal' && mode !== 'Y') ||\n (axis.orientation === 'Vertical' && mode !== 'X')) {\n if (axis.orientation === 'Horizontal') {\n value = pinchRect.x - _this.offset.x;\n axisTrans = axis.rect.width / _this.zoomAxes[index].delta;\n rangeMin = value / axisTrans + _this.zoomAxes[index].min;\n value = pinchRect.x + pinchRect.width - _this.offset.x;\n rangeMax = value / axisTrans + _this.zoomAxes[index].min;\n }\n else {\n value = pinchRect.y - _this.offset.y;\n axisTrans = axis.rect.height / _this.zoomAxes[index].delta;\n rangeMin = (value * -1 + axis.rect.height) / axisTrans + _this.zoomAxes[index].min;\n value = pinchRect.y + pinchRect.height - _this.offset.y;\n rangeMax = (value * -1 + axis.rect.height) / axisTrans + _this.zoomAxes[index].min;\n }\n selectionMin = Math.min(rangeMin, rangeMax);\n selectionMax = Math.max(rangeMin, rangeMax);\n axis.zoomPosition = (selectionMin - _this.zoomAxes[index].actualMin) / _this.zoomAxes[index].actualDelta;\n axis.zoomFactor = (selectionMax - selectionMin) / _this.zoomAxes[index].actualDelta;\n axis.zoomPosition = axis.zoomPosition < 0 ? 0 : axis.zoomPosition;\n axis.zoomFactor = axis.zoomFactor > 1 ? 1 : axis.zoomFactor;\n }\n });\n };\n // Series transformation style applied here.\n Zoom.prototype.setTransform = function (transX, transY, scaleX, scaleY, chart, isPinch) {\n chart.seriesElements.setAttribute('clip-path', 'url(#' + this.elementId + '_ChartAreaClipRect_)');\n if (chart.indicatorElements) {\n chart.indicatorElements.setAttribute('clip-path', 'url(#' + this.elementId + '_ChartAreaClipRect_)');\n }\n var translate;\n var xAxisLoc;\n var yAxisLoc;\n var element;\n if (transX !== null && transY !== null) {\n chart.visibleSeries.forEach(function (value) {\n xAxisLoc = chart.requireInvertedAxis ? value.yAxis.rect.x : value.xAxis.rect.x;\n yAxisLoc = chart.requireInvertedAxis ? value.xAxis.rect.y : value.yAxis.rect.y;\n translate = 'translate(' + (transX + (isPinch ? (scaleX * xAxisLoc) : xAxisLoc)) +\n ',' + (transY + (isPinch ? (scaleY * yAxisLoc) : yAxisLoc)) + ')';\n translate = (scaleX || scaleY) ? translate + ' scale(' + scaleX + ' ' + scaleY + ')' : translate;\n if (value.category === 'Indicator') {\n value.seriesElement.parentNode.setAttribute('transform', translate);\n }\n else {\n value.seriesElement.setAttribute('transform', translate);\n }\n element = getElement(chart.element.id + '_Series_' + value.index + '_DataLabelCollections');\n if (value.errorBarElement) {\n value.errorBarElement.setAttribute('transform', translate);\n }\n if (value.symbolElement) {\n value.symbolElement.setAttribute('transform', translate);\n }\n if (value.textElement) {\n value.textElement.setAttribute('visibility', 'hidden');\n value.shapeElement.setAttribute('visibility', 'hidden');\n }\n if (element) {\n element.style.visibility = 'hidden';\n }\n });\n }\n };\n Zoom.prototype.calculateZoomAxesRange = function (chart, axes) {\n var _this = this;\n var range;\n var axisRange;\n chart.axisCollections.forEach(function (axis, index) {\n axisRange = axis.visibleRange;\n if (_this.zoomAxes[index]) {\n if (!chart.delayRedraw) {\n _this.zoomAxes[index].min = axisRange.min;\n _this.zoomAxes[index].delta = axisRange.delta;\n }\n }\n else {\n range = {\n actualMin: axis.actualRange.min,\n actualDelta: axis.actualRange.delta,\n min: axisRange.min,\n delta: axisRange.delta\n };\n _this.zoomAxes[index] = range;\n }\n });\n };\n // Zooming Toolkit created here\n Zoom.prototype.showZoomingToolkit = function (chart) {\n var toolboxItems = this.zooming.toolbarItems;\n var areaBounds = chart.chartAxisLayoutPanel.seriesClipRect;\n var spacing = 5;\n var render = chart.renderer;\n var length = this.isDevice ? 1 : toolboxItems.length;\n var iconSize = this.isDevice ? measureText('Reset Zoom', { size: '12px' }).width : 16;\n var height = this.isDevice ? measureText('Reset Zoom', { size: '12px' }).height : 22;\n var width = (length * iconSize) + ((length + 1) * spacing) + ((length - 1) * spacing);\n var transX = areaBounds.x + areaBounds.width - width - spacing;\n var transY = (areaBounds.y + spacing);\n var xPosition = spacing;\n var outerElement;\n var toolkit = this.toolkit;\n var element;\n var shadowElement = '';\n shadowElement += '';\n shadowElement += ' ';\n if (length === 0 || getElement(this.elementId + '_Zooming_KitCollection')) {\n return false;\n }\n var defElement = render.createDefs();\n toolboxItems = this.isDevice ? ['Reset'] : toolboxItems;\n defElement.innerHTML = shadowElement;\n this.toolkitElements = render.createGroup({\n id: this.elementId + '_Zooming_KitCollection',\n transform: 'translate(' + transX + ',' + transY + ')'\n });\n this.toolkitElements.appendChild(defElement);\n this.toolkitElements.appendChild(render.drawRectangle(new RectOption(this.elementId + '_Zooming_Rect', '#fafafa', { color: 'transparent', width: 1 }, 1, new Rect(0, 0, width, (height + (spacing * 2))), 0, 0)));\n outerElement = render.drawRectangle(new RectOption(this.elementId + '_Zooming_Rect', '#fafafa', { color: 'transparent', width: 1 }, 0.1, new Rect(0, 0, width, (height + (spacing * 2))), 0, 0));\n outerElement.setAttribute('filter', 'url(#chart_shadow)');\n this.toolkitElements.appendChild(outerElement);\n var currentItem;\n for (var i = 1; i <= length; i++) {\n currentItem = toolboxItems[i - 1];\n element = render.createGroup({\n transform: 'translate(' + xPosition + ',' + (this.isDevice ? spacing : (spacing + 3)) + ')'\n });\n // for desktop toolkit hight is 32 and top padding is 8 icon size 16\n switch (currentItem) {\n case 'Pan':\n toolkit.createPanButton(element, this.toolkitElements, chart);\n break;\n case 'Zoom':\n toolkit.createZoomButton(element, this.toolkitElements, chart);\n break;\n case 'ZoomIn':\n toolkit.createZoomInButton(element, this.toolkitElements, chart);\n break;\n case 'ZoomOut':\n toolkit.createZoomOutButton(element, this.toolkitElements, chart);\n break;\n case 'Reset':\n toolkit.createResetButton(element, this.toolkitElements, chart, this.isDevice);\n break;\n }\n xPosition += iconSize + (spacing * 2);\n }\n this.toolkitElements.setAttribute('opacity', this.isDevice ? '1' : '' + this.zoomkitOpacity);\n this.toolkitElements.setAttribute('cursor', 'auto');\n chart.svgObject.appendChild(this.toolkitElements);\n if (!this.isDevice) {\n EventHandler.add(this.toolkitElements, 'mousemove touchstart', this.zoomToolkitMove, this);\n EventHandler.add(this.toolkitElements, 'mouseleave touchend', this.zoomToolkitLeave, this);\n if (this.isPanning) {\n toolkit.pan();\n }\n }\n return true;\n };\n /**\n * To the show the zooming toolkit.\n * @return {void}\n * @private\n */\n Zoom.prototype.applyZoomToolkit = function (chart, axes) {\n var showToolkit = this.isAxisZoomed(axes);\n if (showToolkit) {\n this.showZoomingToolkit(chart);\n this.isZoomed = true;\n }\n else {\n this.toolkit.removeTooltip();\n this.isPanning = false;\n this.isZoomed = false;\n chart.svgObject.setAttribute('cursor', 'auto');\n }\n };\n /**\n * Return boolean property to show zooming toolkit.\n * @return {void}\n * @private\n */\n Zoom.prototype.isAxisZoomed = function (axes) {\n var showToolkit = false;\n axes.forEach(function (axis) {\n showToolkit = (showToolkit || (axis.zoomFactor !== 1 || axis.zoomPosition !== 0));\n });\n return showToolkit;\n };\n Zoom.prototype.zoomToolkitMove = function (e) {\n var element = this.toolkitElements;\n var opacity = +element.getAttribute('opacity');\n this.zoomkitOpacity = 1;\n element.setAttribute('opacity', '' + this.zoomkitOpacity);\n return false;\n };\n Zoom.prototype.zoomToolkitLeave = function (e) {\n var element = this.toolkitElements;\n this.zoomkitOpacity = 0.3;\n element.setAttribute('opacity', '' + this.zoomkitOpacity);\n return false;\n };\n /**\n * @hidden\n */\n Zoom.prototype.addEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n EventHandler.add(this.chart.element, this.wheelEvent, this.chartMouseWheel, this);\n this.chart.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);\n this.chart.on(Browser.touchStartEvent, this.mouseDownHandler, this);\n this.chart.on(Browser.touchEndEvent, this.mouseUpHandler, this);\n this.chart.on(this.cancelEvent, this.mouseCancelHandler, this);\n };\n /**\n * @hidden\n */\n Zoom.prototype.removeEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n EventHandler.remove(this.chart.element, this.wheelEvent, this.chartMouseWheel);\n this.chart.off(Browser.touchMoveEvent, this.mouseMoveHandler);\n this.chart.off(Browser.touchStartEvent, this.mouseDownHandler);\n this.chart.off(Browser.touchEndEvent, this.mouseUpHandler);\n this.chart.off(this.cancelEvent, this.mouseCancelHandler);\n };\n /**\n * Handles the mouse wheel on chart.\n * @return {boolean}\n * @private\n */\n Zoom.prototype.chartMouseWheel = function (e) {\n var chart = this.chart;\n var offset = chart.element.getBoundingClientRect();\n var svgRect = getElement(chart.element.id + '_svg').getBoundingClientRect();\n var mouseX = (e.clientX - offset.left) - Math.max(svgRect.left - offset.left, 0);\n var mouseY = (e.clientY - offset.top) - Math.max(svgRect.top - offset.top, 0);\n if (this.zooming.enableMouseWheelZooming &&\n withInBounds(mouseX, mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {\n e.preventDefault();\n this.performMouseWheelZooming(e, mouseX, mouseY, chart, chart.axisCollections);\n }\n return false;\n };\n /**\n * @hidden\n */\n Zoom.prototype.mouseMoveHandler = function (e) {\n //Zooming for chart\n var chart = this.chart;\n var touches = null;\n if (e.type === 'touchmove') {\n if (e.preventDefault && this.isIOS &&\n (this.isPanning || (chart.isDoubleTap)\n || (this.zooming.enablePinchZooming && this.touchStartList.length > 1))) {\n e.preventDefault();\n }\n touches = e.touches;\n }\n if (chart.isChartDrag) {\n if (chart.isTouch) {\n this.touchMoveList = this.addTouchPointer(this.touchMoveList, e, touches);\n if (this.zooming.enablePinchZooming && this.touchMoveList.length > 1\n && this.touchStartList.length > 1) {\n this.performPinchZooming(e, chart);\n }\n }\n this.renderZooming(e, chart, chart.isTouch);\n }\n };\n /**\n * @hidden\n */\n Zoom.prototype.mouseDownHandler = function (e) {\n //Zooming for chart\n var chart = this.chart;\n var touches = null;\n var target;\n if (e.type === 'touchstart') {\n touches = e.touches;\n target = e.target;\n }\n else {\n target = e.target;\n }\n if (target.id.indexOf(chart.element.id + '_Zooming_') === -1 &&\n withInBounds(chart.previousMouseMoveX, chart.previousMouseMoveY, chart.chartAxisLayoutPanel.seriesClipRect)) {\n chart.isChartDrag = true;\n }\n if (chart.isTouch) {\n this.touchStartList = this.addTouchPointer(this.touchStartList, e, touches);\n }\n };\n /**\n * @hidden\n */\n Zoom.prototype.mouseUpHandler = function (e) {\n var chart = this.chart;\n var performZoomRedraw = e.target.id.indexOf(chart.element.id + '_ZoomOut_') === -1 ||\n e.target.id.indexOf(chart.element.id + '_ZoomIn_') === -1;\n if (chart.isChartDrag || performZoomRedraw) {\n this.performZoomRedraw(chart);\n }\n if (chart.isTouch) {\n if (chart.isDoubleTap && withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)\n && this.touchStartList.length === 1 && this.isZoomed) {\n this.toolkit.reset();\n }\n this.touchStartList = [];\n chart.isDoubleTap = false;\n }\n };\n /**\n * @hidden\n */\n Zoom.prototype.mouseCancelHandler = function (e) {\n if (this.isZoomed) {\n this.performZoomRedraw(this.chart);\n }\n this.pinchTarget = null;\n this.touchStartList = [];\n this.touchMoveList = [];\n };\n /**\n * Handles the touch pointer.\n * @return {boolean}\n * @private\n */\n Zoom.prototype.addTouchPointer = function (touchList, e, touches) {\n if (touches) {\n touchList = [];\n for (var i = 0, length_1 = touches.length; i < length_1; i++) {\n touchList.push({ pageX: touches[i].clientX, pageY: touches[i].clientY, pointerId: null });\n }\n }\n else {\n touchList = touchList ? touchList : [];\n if (touchList.length === 0) {\n touchList.push({ pageX: e.clientX, pageY: e.clientY, pointerId: e.pointerId });\n }\n else {\n for (var i = 0, length_2 = touchList.length; i < length_2; i++) {\n if (touchList[i].pointerId === e.pointerId) {\n touchList[i] = { pageX: e.clientX, pageY: e.clientY, pointerId: e.pointerId };\n }\n else {\n touchList.push({ pageX: e.clientX, pageY: e.clientY, pointerId: e.pointerId });\n }\n }\n }\n }\n return touchList;\n };\n /**\n * Get module name.\n */\n Zoom.prototype.getModuleName = function () {\n // Returns te module name\n return 'Zoom';\n };\n /**\n * To destroy the zooming.\n * @return {void}\n * @private\n */\n Zoom.prototype.destroy = function (chart) {\n // Destroy method performed here\n this.removeEventListener();\n };\n return Zoom;\n}());\nexport { Zoom };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * Selection Module handles the selection for chart.\n * @private\n */\nvar BaseSelection = /** @class */ (function () {\n function BaseSelection(control) {\n this.control = control;\n }\n /**\n * To create selection styles for series\n */\n BaseSelection.prototype.seriesStyles = function () {\n var seriesclass;\n var style = document.getElementById(this.styleId);\n if (isNullOrUndefined(style)) {\n style = document.createElement('style');\n style.setAttribute('id', this.styleId);\n for (var _i = 0, _a = this.control.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n seriesclass = series.selectionStyle || this.styleId + '_series_' + series.index;\n style.innerHTML += series.selectionStyle ? '' : '.' + seriesclass + ' { } ';\n }\n style.innerHTML += '.' + this.unselected + ' { opacity:' + (0.3) + ';} ';\n document.body.appendChild(style);\n }\n };\n /**\n * To concat indexes\n */\n BaseSelection.prototype.concatIndexes = function (userIndexes, localIndexes) {\n return userIndexes.concat(localIndexes);\n };\n /**\n * Selected points series visibility checking on legend click\n */\n BaseSelection.prototype.checkVisibility = function (selectedIndexes) {\n var visible = false;\n var uniqueSeries = [];\n for (var _i = 0, selectedIndexes_1 = selectedIndexes; _i < selectedIndexes_1.length; _i++) {\n var index = selectedIndexes_1[_i];\n if (uniqueSeries.indexOf(index.series) === -1) {\n uniqueSeries.push(index.series);\n }\n }\n for (var _a = 0, uniqueSeries_1 = uniqueSeries; _a < uniqueSeries_1.length; _a++) {\n var index = uniqueSeries_1[_a];\n if (this.control.series[index].visible) {\n visible = true;\n break;\n }\n }\n return visible;\n };\n /**\n * To add svg element style class\n * @private\n */\n BaseSelection.prototype.addSvgClass = function (element, className) {\n var elementClassName = element.getAttribute('class') || '';\n elementClassName += ((elementClassName !== '') ? ' ' : '');\n if (elementClassName.indexOf(className) === -1) {\n element.setAttribute('class', elementClassName + className);\n }\n };\n /**\n * To remove svg element style class\n * @private\n */\n BaseSelection.prototype.removeSvgClass = function (element, className) {\n var elementClassName = element.getAttribute('class') || '';\n if (elementClassName.indexOf(className) > -1) {\n element.setAttribute('class', elementClassName.replace(className, ''));\n }\n };\n /**\n * To get children from parent element\n */\n BaseSelection.prototype.getChildren = function (parent) {\n var children = [];\n for (var i = 0; i < parent.childNodes.length; i++) {\n if (parent.childNodes[i].tagName !== 'defs') {\n children.push(parent.childNodes[i]);\n }\n }\n return children;\n };\n return BaseSelection;\n}());\nexport { BaseSelection };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * Selection src file\n */\nimport { Browser } from '@syncfusion/ej2-base';\nimport { remove } from '@syncfusion/ej2-base';\nimport { extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { ChartLocation, Rect, RectOption, CircleOption, withInBounds, getDraggedRectLocation, removeElement, getElement } from '../../common/utils/helper';\nimport { Index } from '../../common/model/base';\nimport { dragComplete } from '../../common/model/constants';\nimport { BaseSelection } from '../../common/user-interaction/selection';\n/**\n * `Selection` module handles the selection for chart.\n * @private\n */\nvar Selection = /** @class */ (function (_super) {\n __extends(Selection, _super);\n /**\n * Constructor for selection module.\n * @private.\n */\n function Selection(chart) {\n var _this = _super.call(this, chart) || this;\n _this.chart = chart;\n _this.renderer = chart.renderer;\n _this.addEventListener();\n return _this;\n }\n /**\n * Binding events for selection module.\n */\n Selection.prototype.addEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n this.chart.on(Browser.touchMoveEvent, this.mouseMove, this);\n this.chart.on(cancelEvent, this.completeSelection, this);\n this.chart.on('click', this.calculateSelectedElements, this);\n this.chart.on(Browser.touchStartEvent, this.mousedown, this);\n this.chart.on(Browser.touchEndEvent, this.completeSelection, this);\n };\n /**\n * Chart mouse down\n */\n Selection.prototype.mousedown = function (e) {\n var chart = this.chart;\n if (chart.selectionMode === 'None' || chart.isChartDrag) {\n return;\n }\n if (chart.isDoubleTap || !chart.isTouch || this.rectPoints) {\n this.dragStart(chart, chart.chartAxisLayoutPanel.seriesClipRect, chart.mouseDownX, chart.mouseDownY, e);\n }\n };\n /**\n * UnBinding events for selection module.\n */\n Selection.prototype.removeEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n this.chart.off(Browser.touchMoveEvent, this.mouseMove);\n this.chart.off('pointerleave' || 'mouseleave', this.completeSelection);\n this.chart.off('click', this.calculateSelectedElements);\n this.chart.off(Browser.touchStartEvent, this.mousedown);\n this.chart.off(Browser.touchEndEvent, this.completeSelection);\n };\n /**\n * To find private variable values\n */\n Selection.prototype.initPrivateVariables = function (chart) {\n this.styleId = chart.element.id + '_ej2_chart_selection';\n this.unselected = chart.element.id + '_ej2_deselected';\n this.closeIconId = chart.element.id + '_ej2_drag_close';\n this.draggedRectGroup = chart.element.id + '_ej2_drag_group';\n this.draggedRect = chart.element.id + '_ej2_drag_rect';\n this.selectedDataIndexes = [];\n this.rectPoints = null;\n this.isSeriesMode = chart.selectionMode === 'Series';\n };\n /**\n * Method to select the point and series.\n * @return {void}\n */\n Selection.prototype.invokeSelection = function (chart) {\n this.initPrivateVariables(chart);\n this.series = extend({}, chart.visibleSeries, null, true);\n this.seriesStyles();\n if (!(chart.selectionMode.indexOf('Drag') > -1)) {\n this.selectDataIndex(chart, this.concatIndexes(chart.selectedDataIndexes, this.selectedDataIndexes));\n }\n };\n Selection.prototype.generateStyle = function (series) {\n if (series) {\n return (series.selectionStyle || this.styleId + '_series_' + series.index);\n }\n return 'undefined';\n };\n Selection.prototype.selectDataIndex = function (chart, indexes) {\n for (var _i = 0, indexes_1 = indexes; _i < indexes_1.length; _i++) {\n var index = indexes_1[_i];\n this.performSelection(index, chart, this.getElementByIndex(chart, index)[0]);\n }\n };\n Selection.prototype.getElementByIndex = function (chart, index, suffix) {\n if (suffix === void 0) { suffix = ''; }\n var elementId = chart.element.id + '_Series_' + index.series + '_Point' + '_' + index.point;\n var series = chart.series[index.series];\n elementId = (!series.isRectSeries && series.type !== 'Scatter' && series.type !== 'Bubble' &&\n series.marker.visible) ? (elementId + '_Symbol' + suffix) : elementId;\n return [getElement(elementId), (series.type === 'RangeArea' && series.marker.visible) ? getElement(elementId + '1') : null];\n };\n Selection.prototype.getClusterElements = function (chart, index) {\n var clusters = [];\n for (var _i = 0, _a = chart.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n index = new Index(series.index, index.point);\n clusters.push(this.getElementByIndex(chart, index)[0]);\n }\n return clusters;\n };\n Selection.prototype.findElements = function (chart, series, index, suffix) {\n if (suffix === void 0) { suffix = ''; }\n if (this.isSeriesMode) {\n return this.getSeriesElements(series);\n }\n else if (chart.selectionMode === 'Cluster') {\n return this.getClusterElements(chart, index);\n }\n else {\n return this.getElementByIndex(chart, index, suffix);\n }\n };\n /**\n * To find the selected element.\n * @return {void}\n * @private\n */\n Selection.prototype.calculateSelectedElements = function (event) {\n if (this.chart.selectionMode === 'None' || event.target.id.indexOf(this.chart.element.id + '_') === -1) {\n return;\n }\n if (event.target.id.indexOf('_Series_') > -1) {\n this.performSelection(this.indexFinder(event.target.id), this.chart, event.target);\n }\n };\n Selection.prototype.performSelection = function (index, chart, element) {\n this.isSeriesMode = chart.selectionMode === 'Series';\n if (chart.series[index.series].type === 'BoxAndWhisker' &&\n element.id === chart.element.id + '_Series_' + index.series + '_Point_' + index.point + '_BoxPath') {\n element = element.parentElement;\n }\n switch (chart.selectionMode) {\n case 'Series':\n this.selection(chart, index, this.getSeriesElements(chart.series[index.series]));\n this.blurEffect(chart.element.id, chart.visibleSeries);\n break;\n case 'Point':\n if (!isNaN(index.point)) {\n this.selection(chart, index, [element]);\n this.blurEffect(chart.element.id, chart.visibleSeries);\n }\n break;\n case 'Cluster':\n if (!isNaN(index.point)) {\n this.clusterSelection(chart, chart.series, index);\n this.blurEffect(chart.element.id, chart.visibleSeries);\n }\n break;\n }\n };\n Selection.prototype.selection = function (chart, index, selectedElements) {\n if (!chart.isMultiSelect && (chart.selectionMode.indexOf('Drag') === -1)) {\n this.removeMultiSelectEelments(chart, this.selectedDataIndexes, index, chart.series);\n }\n var className = selectedElements[0] && (selectedElements[0].getAttribute('class') || '');\n if (selectedElements[0] && className.indexOf(this.getSelectionClass(selectedElements[0].id)) > -1) {\n this.removeStyles(selectedElements);\n this.addOrRemoveIndex(this.selectedDataIndexes, index);\n }\n else {\n this.applyStyles(selectedElements);\n this.addOrRemoveIndex(this.selectedDataIndexes, index, true);\n }\n };\n Selection.prototype.clusterSelection = function (chart, series, index) {\n this.selection(chart, index, this.getClusterElements(chart, new Index(index.series, index.point)));\n };\n Selection.prototype.removeMultiSelectEelments = function (chart, index, currentIndex, seriesCollection) {\n var series;\n for (var i = 0; i < index.length; i++) {\n series = seriesCollection[index[i].series];\n if ((this.isSeriesMode && !this.toEquals(index[i], currentIndex, this.isSeriesMode)) ||\n (this.control.selectionMode === 'Cluster' && !this.toEquals(index[i], currentIndex, false)) ||\n (!this.isSeriesMode && this.toEquals(index[i], currentIndex, true) && !this.toEquals(index[i], currentIndex, false))) {\n this.removeStyles(this.findElements(chart, series, index[i]));\n index.splice(i, 1);\n i--;\n }\n }\n };\n Selection.prototype.blurEffect = function (chartId, visibleSeries) {\n var visibility = this.checkVisibility(this.selectedDataIndexes); // legend click scenario\n for (var _i = 0, visibleSeries_1 = visibleSeries; _i < visibleSeries_1.length; _i++) {\n var series = visibleSeries_1[_i];\n if (series.visible) {\n this.checkSelectionElements(getElement(chartId + 'SeriesGroup' + series.index), this.generateStyle(series), visibility);\n if (!isNullOrUndefined(getElement(chartId + 'SymbolGroup' + series.index))) {\n this.checkSelectionElements(getElement(chartId + 'SymbolGroup' + series.index), this.generateStyle(series), visibility);\n }\n }\n }\n };\n Selection.prototype.checkSelectionElements = function (element, className, visibility) {\n var children = (this.isSeriesMode ? [element] : element.childNodes);\n var elementClassName;\n var parentClassName;\n var legendShape;\n var selectElement = element;\n for (var i = 0; i < children.length; i++) {\n elementClassName = children[i].getAttribute('class') || '';\n parentClassName = children[i].parentNode.getAttribute('class') || '';\n if (elementClassName.indexOf(className) === -1 &&\n parentClassName.indexOf(className) === -1 && visibility) {\n this.addSvgClass(children[i], this.unselected);\n }\n else {\n selectElement = children[i];\n this.removeSvgClass(children[i], this.unselected);\n }\n }\n if (this.control.legendModule && this.control.legendSettings.visible) {\n legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + className.split('_series_')[1]);\n if (legendShape) {\n elementClassName = selectElement.getAttribute('class') || '';\n parentClassName = selectElement.parentNode.getAttribute('class') || '';\n if (elementClassName.indexOf(className) === -1 && parentClassName.indexOf(className) === -1 && visibility) {\n this.addSvgClass(legendShape, this.unselected);\n }\n else {\n this.removeSvgClass(legendShape, this.unselected);\n }\n }\n }\n };\n Selection.prototype.applyStyles = function (elements) {\n for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {\n var element = elements_1[_i];\n if (element) {\n this.removeSvgClass(element.parentNode, this.unselected);\n this.removeSvgClass(element, this.unselected);\n this.addSvgClass(element, this.getSelectionClass(element.id));\n }\n }\n };\n Selection.prototype.getSelectionClass = function (id) {\n return this.generateStyle(this.control.series[this.indexFinder(id).series]);\n };\n Selection.prototype.removeStyles = function (elements) {\n for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {\n var element = elements_2[_i];\n if (element) {\n this.removeSvgClass(element, this.getSelectionClass(element.id));\n }\n }\n };\n Selection.prototype.addOrRemoveIndex = function (indexes, index, add) {\n for (var i = 0; i < indexes.length; i++) {\n if (this.toEquals(indexes[i], index, this.isSeriesMode)) {\n indexes.splice(i, 1);\n i--;\n }\n }\n if (add) {\n indexes.push(index);\n }\n };\n Selection.prototype.toEquals = function (first, second, checkSeriesOnly) {\n return ((first.series === second.series || (this.control.selectionMode === 'Cluster' && !checkSeriesOnly))\n && (checkSeriesOnly || (first.point === second.point)));\n };\n /**\n * To redraw the selected points.\n * @return {void}\n * @private\n */\n Selection.prototype.redrawSelection = function (chart, oldMode) {\n this.isSeriesMode = oldMode === 'Series';\n var selectedDataIndexes = extend([], this.selectedDataIndexes, null, true);\n this.removeSelectedElements(chart, this.selectedDataIndexes, chart.series);\n this.blurEffect(chart.element.id, chart.visibleSeries);\n this.selectDataIndex(chart, selectedDataIndexes);\n };\n /** @private */\n Selection.prototype.legendSelection = function (chart, series) {\n var seriesStyle = this.generateStyle(chart.visibleSeries[series]);\n var selectedElements = document.getElementsByClassName(seriesStyle);\n this.isSeriesMode = chart.selectionMode === 'Series';\n var isBlurEffectNeeded = true;\n if (selectedElements.length > 0) {\n var elements = [];\n for (var i = 0; i < selectedElements.length; i++) {\n elements.push(selectedElements[i]);\n }\n this.removeStyles(elements);\n this.isSeriesMode = true;\n this.addOrRemoveIndex(this.selectedDataIndexes, new Index(series, NaN));\n for (var _i = 0, _a = chart.visibleSeries; _i < _a.length; _i++) {\n var series_1 = _a[_i];\n seriesStyle = this.generateStyle(series_1);\n if (document.getElementsByClassName(seriesStyle).length > 0) {\n for (var _b = 0, elements_3 = elements; _b < elements_3.length; _b++) {\n var element = elements_3[_b];\n this.checkSelectionElements(element, seriesStyle, true);\n }\n isBlurEffectNeeded = false;\n break;\n }\n }\n if (isBlurEffectNeeded) {\n this.isSeriesMode = chart.selectionMode === 'Series';\n this.blurEffect(chart.element.id, chart.visibleSeries);\n }\n }\n else {\n var seriesElements = this.getSeriesElements(chart.visibleSeries[series]);\n for (var _c = 0, seriesElements_1 = seriesElements; _c < seriesElements_1.length; _c++) {\n var seriesElement = seriesElements_1[_c];\n this.checkSelectionElements(seriesElement, seriesStyle, false);\n }\n this.isSeriesMode = true;\n this.selection(chart, new Index(series, NaN), seriesElements);\n this.isSeriesMode = chart.selectionMode === 'Series';\n this.blurEffect(chart.element.id, chart.visibleSeries);\n }\n };\n Selection.prototype.getSeriesElements = function (series) {\n var seriesElements = [series.seriesElement];\n if (series.marker.visible && series.type !== 'Scatter' && series.type !== 'Bubble' && !series.isRectSeries) {\n seriesElements.push(series.symbolElement);\n }\n return seriesElements;\n };\n Selection.prototype.indexFinder = function (id) {\n var ids = ['NaN', 'NaN'];\n if (id.indexOf('SeriesGroup') > -1) {\n ids = id.split('SeriesGroup');\n ids[0] = ids[1];\n }\n else if (id.indexOf('SymbolGroup') > -1) {\n ids = id.split('SymbolGroup');\n ids[0] = ids[1];\n }\n else if (id.indexOf('_Point_') > -1) {\n ids = id.split('_Series_')[1].split('_Point_');\n }\n else if (id.indexOf('_Series_') > -1) {\n ids[0] = id.split('_Series_')[1];\n }\n return new Index(parseInt(ids[0], 10), parseInt(ids[1], 10));\n };\n /**\n * Drag selection that returns the selected data.\n * @return {void}\n * @private\n */\n Selection.prototype.calculateDragSelectedElements = function (chart, dragRect) {\n this.removeSelectedElements(chart, this.selectedDataIndexes, chart.series);\n var rect = new Rect(dragRect.x, dragRect.y, dragRect.width, dragRect.height);\n var axisOffset = new ChartLocation(chart.chartAxisLayoutPanel.seriesClipRect.x, chart.chartAxisLayoutPanel.seriesClipRect.y);\n this.removeOffset(rect, axisOffset);\n var points;\n var index;\n var selectedPointValues = [];\n var selectedSeriesValues = [];\n this.isSeriesMode = false;\n var symbolLocation;\n var _loop_1 = function (series) {\n if (series.visible) {\n points = series.points;\n selectedPointValues = [];\n var xAxisOffset_1;\n var yAxisOffset_1;\n if ((chart.isTransposed || series.type.indexOf('Bar') !== -1) &&\n !(chart.isTransposed && series.type.indexOf('Bar') !== -1)) {\n xAxisOffset_1 = series.xAxis.rect.y - axisOffset.y;\n yAxisOffset_1 = series.yAxis.rect.x - axisOffset.x;\n }\n else {\n xAxisOffset_1 = series.xAxis.rect.x - axisOffset.x;\n yAxisOffset_1 = series.yAxis.rect.y - axisOffset.y;\n }\n for (var j = 0; j < points.length; j++) {\n var yValue = series.type !== 'RangeArea' ? points[j].yValue :\n points[j].regions[0].y;\n var isCurrentPoint = void 0;\n if (series.type === 'BoxAndWhisker') {\n isCurrentPoint = points[j].regions.some(function (region) {\n return withInBounds(region.x + xAxisOffset_1, region.y + yAxisOffset_1, rect);\n });\n }\n else {\n isCurrentPoint = points[j].symbolLocations.some(function (location) {\n return location && withInBounds(location.x + xAxisOffset_1, location.y + yAxisOffset_1, rect);\n });\n }\n if (isCurrentPoint && series.category !== 'Indicator') {\n index = new Index(series.index, points[j].index);\n this_1.selection(chart, index, this_1.findElements(chart, series, index));\n selectedPointValues.push({ x: points[j].xValue.toString(), y: yValue });\n }\n if (isCurrentPoint && series.type === 'RangeArea') {\n selectedPointValues.push({ x: points[j].xValue.toString(), y: points[j].regions[0].y });\n }\n }\n selectedSeriesValues.push(selectedPointValues);\n }\n };\n var this_1 = this;\n for (var _i = 0, _a = chart.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n _loop_1(series);\n }\n this.blurEffect(chart.element.id, chart.visibleSeries);\n this.rectPoints = new Rect(dragRect.x, dragRect.y, dragRect.width, dragRect.height);\n this.createCloseButton((dragRect.x + dragRect.width), dragRect.y);\n var args = {\n name: dragComplete,\n selectedDataValues: selectedSeriesValues,\n cancel: false\n };\n chart.trigger(dragComplete, args);\n };\n Selection.prototype.removeOffset = function (rect, clip) {\n rect.x -= clip.x;\n rect.y -= clip.y;\n };\n /**\n * Method to draw dragging rect.\n * @return {void}\n * @private\n */\n Selection.prototype.drawDraggingRect = function (chart, dragRect) {\n var cartesianLayout = chart.chartAxisLayoutPanel.seriesClipRect;\n switch (chart.selectionMode) {\n case 'DragX':\n dragRect.y = cartesianLayout.y;\n dragRect.height = cartesianLayout.height;\n break;\n case 'DragY':\n dragRect.x = cartesianLayout.x;\n dragRect.width = cartesianLayout.width;\n break;\n }\n if (dragRect.width < 5 || dragRect.height < 5) {\n return null;\n }\n var element = getElement(this.draggedRect);\n if (this.closeIcon) {\n removeElement(this.closeIconId);\n }\n if (element) {\n this.setAttributes(element, dragRect);\n }\n else {\n var dragGroup = chart.renderer.createGroup({ id: this.draggedRectGroup });\n chart.svgObject.appendChild(dragGroup);\n element = chart.renderer.drawRectangle(new RectOption(this.draggedRect, chart.themeStyle.selectionRectFill, { color: chart.themeStyle.selectionRectStroke, width: 1 }, 1, dragRect));\n element.setAttribute('style', 'cursor:move;');\n dragGroup.appendChild(element);\n }\n };\n Selection.prototype.createCloseButton = function (x, y) {\n var closeIcon = this.chart.renderer.createGroup({\n id: this.closeIconId,\n style: 'cursor:pointer; visibility: visible;'\n });\n closeIcon.appendChild(this.chart.renderer.drawCircle(new CircleOption(this.closeIconId + '_circle', '#FFFFFF', { color: this.chart.themeStyle.selectionCircleStroke, width: 1 }, 1, x, y, 10)));\n var direction = 'M ' + (x - 4) + ' ' + (y - 4) + ' L ' + (x + 4) + ' ' + (y + 4) + ' M ' + (x - 4) + ' ' + (y + 4) +\n ' L ' + (x + 4) + ' ' + (y - 4);\n closeIcon.appendChild(this.chart.renderer.drawPath({\n id: this.closeIconId + '_cross', d: direction,\n stroke: this.chart.themeStyle.selectionCircleStroke,\n 'stroke-width': 2, fill: this.chart.themeStyle.selectionCircleStroke\n }));\n this.closeIcon = closeIcon;\n getElement(this.draggedRectGroup).appendChild(closeIcon);\n };\n /**\n * Method to remove dragged element.\n * @return {void}\n * @private\n */\n Selection.prototype.removeDraggedElements = function (chart, event) {\n if ((event.target.id.indexOf(this.closeIconId) > -1) && (event.type.indexOf('move') === -1)) {\n this.removeSelectedElements(chart, this.selectedDataIndexes, chart.series);\n this.blurEffect(chart.element.id, chart.visibleSeries);\n remove(getElement(this.draggedRectGroup));\n this.changeCursorStyle(false, chart.svgObject, 'auto');\n this.rectPoints = null;\n }\n };\n /**\n * Method to resize the drag rect.\n * @return {void}\n * @private\n */\n Selection.prototype.resizingSelectionRect = function (chart, location, tapped) {\n var rect = new Rect(this.rectPoints.x, this.rectPoints.y, this.rectPoints.width, this.rectPoints.height);\n var resize = this.findResizeMode(chart.svgObject, rect, location);\n if (this.resizing) {\n rect = getDraggedRectLocation(rect.x, rect.y, (rect.x + rect.width), (rect.y + rect.height), chart.chartAxisLayoutPanel.seriesClipRect);\n this.drawDraggingRect(chart, rect);\n this.dragRect = rect;\n }\n if (tapped) {\n this.resizing = resize;\n }\n };\n Selection.prototype.findResizeMode = function (chartSvgObject, rect, location) {\n var cursorStyle = 'se-resize';\n var resize = false;\n if (!this.resizing) {\n var resizeEdges = [new Rect(rect.x, (rect.y - 10), rect.width - 5, 20),\n new Rect((rect.x - 10), rect.y, 20, rect.height),\n new Rect(rect.x, (rect.y + rect.height - 10), rect.width - 10, 20),\n new Rect((rect.x + rect.width - 10), rect.y + 5, 20, rect.height - 15),\n new Rect((rect.x + rect.width - 10), (rect.y + rect.height - 10), 20, 20)]; //corner\n for (var i = 0; i < resizeEdges.length; i++) {\n if (withInBounds(location.x, location.y, resizeEdges[i])) {\n cursorStyle = (i === 4) ? cursorStyle : (i % 2 === 0) ? 'ns-resize' : 'ew-resize';\n resize = true;\n this.resizeMode = i;\n break;\n }\n }\n }\n else {\n var x = rect.x;\n var y = rect.y;\n var width = (location.x - x);\n var height = (location.y - y);\n switch (this.resizeMode) {\n case 0:\n height = Math.abs((rect.height + rect.y) - location.y);\n rect.y = Math.min((rect.height + rect.y), location.y);\n rect.height = height;\n break;\n case 1:\n width = Math.abs((rect.width + rect.x) - location.x);\n rect.x = Math.min((rect.width + rect.x), location.x);\n rect.width = width;\n break;\n case 2:\n rect.height = Math.abs(height);\n rect.y = Math.min(location.y, y);\n break;\n case 3:\n rect.width = Math.abs(width);\n rect.x = Math.min(location.x, x);\n break;\n case 4:\n rect.width = Math.abs(width);\n rect.height = Math.abs(height);\n rect.x = Math.min(location.x, x);\n rect.y = Math.min(location.y, y);\n break;\n }\n }\n this.changeCursorStyle(resize, getElement(this.draggedRect), cursorStyle);\n this.changeCursorStyle(resize, chartSvgObject, cursorStyle);\n return resize;\n };\n Selection.prototype.changeCursorStyle = function (isResize, rectelement, cursorStyle) {\n cursorStyle = isResize ? cursorStyle : (this.control.svgObject === rectelement) ? 'auto' : 'move';\n rectelement.setAttribute('style', 'cursor:' + cursorStyle + ';');\n };\n Selection.prototype.removeSelectedElements = function (chart, index, seriesCollection) {\n index.splice(0, index.length);\n var seriesElements;\n for (var _i = 0, seriesCollection_1 = seriesCollection; _i < seriesCollection_1.length; _i++) {\n var series = seriesCollection_1[_i];\n seriesElements = this.getSeriesElements(series);\n this.removeStyles(seriesElements);\n for (var _a = 0, seriesElements_2 = seriesElements; _a < seriesElements_2.length; _a++) {\n var seriesElement = seriesElements_2[_a];\n this.removeStyles(this.getChildren(seriesElement));\n }\n }\n };\n Selection.prototype.setAttributes = function (ele, object) {\n var keys = Object.keys(object);\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var key = keys_1[_i];\n ele.setAttribute(key, object[key]);\n }\n };\n /**\n * Method to move the dragged rect.\n * @return {void}\n * @private\n */\n Selection.prototype.draggedRectMoved = function (chart, grabbedPoint, doDrawing) {\n var rect = new Rect(this.rectPoints.x, this.rectPoints.y, this.rectPoints.width, this.rectPoints.height);\n rect.x -= (grabbedPoint.x - chart.mouseX);\n rect.y -= (grabbedPoint.y - chart.mouseY);\n rect = getDraggedRectLocation(rect.x, rect.y, rect.x + rect.width, rect.height + rect.y, chart.chartAxisLayoutPanel.seriesClipRect);\n if (doDrawing) {\n this.drawDraggingRect(chart, rect);\n }\n else {\n this.calculateDragSelectedElements(chart, rect);\n }\n };\n /**\n * To complete the selection.\n * @return {void}\n * @private\n */\n Selection.prototype.completeSelection = function (e) {\n var chart = this.chart;\n if (chart.selectionMode === 'None') {\n return;\n }\n if ((this.dragging || this.resizing) && this.dragRect.width > 5 && this.dragRect.height > 5) {\n this.calculateDragSelectedElements(chart, this.dragRect);\n }\n else if (this.rectGrabbing && this.rectPoints.width && this.rectPoints.height) {\n this.draggedRectMoved(chart, this.dragRect);\n }\n this.dragging = false;\n this.rectGrabbing = false;\n this.resizing = false;\n this.removeDraggedElements(chart, e);\n };\n Selection.prototype.getDragRect = function (chart, seriesClipRect) {\n return getDraggedRectLocation(chart.mouseDownX, chart.mouseDownY, chart.mouseX, chart.mouseY, seriesClipRect);\n };\n /** @private */\n Selection.prototype.dragStart = function (chart, seriesClipRect, mouseDownX, mouseDownY, event) {\n this.dragging = (chart.selectionMode.indexOf('Drag') > -1) && (chart.isDoubleTap || !chart.isTouch) &&\n chart.chartAreaType !== 'PolarRadar';\n if (this.dragging) {\n this.dragRect = new Rect(chart.mouseDownX, chart.mouseDownY, 0, 0);\n if (chart.mouseDownX < seriesClipRect.x || chart.mouseDownX > (seriesClipRect.x + seriesClipRect.width) ||\n chart.mouseDownY < seriesClipRect.y || chart.mouseDownY > (seriesClipRect.y + seriesClipRect.height)) {\n this.dragging = false;\n }\n }\n if (this.rectPoints) {\n this.dragRect = new Rect(chart.mouseDownX, chart.mouseDownY, 0, 0);\n this.resizingSelectionRect(chart, new ChartLocation(mouseDownX, mouseDownY), true);\n this.rectGrabbing = withInBounds(mouseDownX, mouseDownY, this.rectPoints);\n }\n };\n /** @private */\n Selection.prototype.mouseMove = function (event) {\n var chart = this.chart;\n if (chart.selectionMode === 'None') {\n return;\n }\n if (event.type === 'touchmove' && (Browser.isIos || Browser.isIos7) && this.dragging && event.preventDefault) {\n event.preventDefault();\n }\n var insideMoving = withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect);\n if (insideMoving) {\n if (this.rectGrabbing && !this.resizing) {\n this.draggedRectMoved(chart, this.dragRect, true);\n }\n else if (this.dragging && !this.resizing) {\n this.dragRect = this.getDragRect(chart, chart.chartAxisLayoutPanel.seriesClipRect);\n this.drawDraggingRect(chart, this.dragRect);\n }\n if (this.rectPoints) {\n this.resizingSelectionRect(chart, new ChartLocation(chart.mouseX, chart.mouseY));\n }\n }\n else {\n this.completeSelection(event);\n }\n };\n /**\n * Get module name.\n * @private\n */\n Selection.prototype.getModuleName = function () {\n return 'Selection';\n };\n /**\n * To destroy the selection.\n * @return {void}\n * @private\n */\n Selection.prototype.destroy = function (chart) {\n this.removeEventListener();\n // Destroy method performed here\n };\n return Selection;\n}(BaseSelection));\nexport { Selection };\n","import { ChartLocation, Rect, TextOption, RectOption, isCollide, markerAnimate } from '../../common/utils/helper';\nimport { getLabelText, measureText, convertHexToColor, calculateRect, textElement, colorNameToHex } from '../../common/utils/helper';\nimport { getValue, extend } from '@syncfusion/ej2-base';\nimport { textRender } from '../../common/model/constants';\nimport { createTemplate, getFontStyle, getElement, measureElementRect, templateAnimate, withIn } from '../../common/utils/helper';\nimport { createElement } from '@syncfusion/ej2-base';\nimport { getPoint } from '../../common/utils/helper';\n/**\n * `DataLabel` module is used to render data label for the data point.\n */\nvar DataLabel = /** @class */ (function () {\n /**\n * Constructor for the data label module.\n * @private\n */\n function DataLabel(chart) {\n this.errorHeight = 0;\n this.chart = chart;\n }\n DataLabel.prototype.initPrivateVariables = function (series, marker) {\n var transform;\n var render = series.chart.renderer;\n transform = series.chart.chartAreaType === 'Cartesian' ? 'translate(' + series.clipRect.x + ',' + (series.clipRect.y) + ')' : '';\n if (marker.dataLabel.visible) {\n series.shapeElement = render.createGroup({\n 'id': this.chart.element.id + 'ShapeGroup' + series.index,\n 'transform': transform,\n 'clip-path': 'url(#' + this.chart.element.id + '_ChartSeriesClipRect_' + series.index + ')'\n });\n series.textElement = render.createGroup({\n 'id': this.chart.element.id + 'TextGroup' + series.index,\n 'transform': transform,\n 'clip-path': 'url(#' + this.chart.element.id + '_ChartSeriesClipRect_' + series.index + ')'\n });\n }\n this.markerHeight = ((series.type === 'Scatter' || marker.visible) && !this.isRectSeries(series)) ? (marker.height / 2) : 0;\n this.commonId = this.chart.element.id + '_Series_' + series.index + '_Point_';\n this.calculateErrorHeight(series, series.marker.dataLabel.position);\n this.chartBackground = this.chart.chartArea.background === 'trasparent' ?\n this.chart.background || this.chart.themeStyle.background : this.chart.chartArea.background;\n };\n DataLabel.prototype.calculateErrorHeight = function (series, position) {\n if (!series.errorBar.visible) {\n return null;\n }\n else if (series.errorBar.visible && this.chart.chartAreaType !== 'PolarRadar') {\n var direction = series.errorBar.direction;\n var positiveHeight = this.chart.errorBarModule.positiveHeight;\n var negativeHeight = this.chart.errorBarModule.negativeHeight;\n if (this.isRectSeries(series)) {\n if (position === 'Top' || position === 'Auto') {\n if (direction === 'Both' || direction === 'Minus') {\n this.errorHeight = negativeHeight;\n }\n else {\n this.errorHeight = 0;\n }\n }\n if (position === 'Outer' || position === 'Auto') {\n if (direction === 'Both' || direction === 'Plus') {\n this.errorHeight = positiveHeight;\n }\n else {\n this.errorHeight = 0;\n }\n }\n }\n else {\n if (position === 'Top' || position === 'Outer' || position === 'Auto') {\n if ((direction === 'Both' || direction === 'Plus') && (!series.chart.isTransposed)) {\n this.errorHeight = positiveHeight;\n }\n else {\n this.errorHeight = 0;\n }\n }\n if (position === 'Bottom' || position === 'Auto') {\n if (direction === 'Both' || direction === 'Minus') {\n this.errorHeight = negativeHeight;\n }\n else {\n this.errorHeight = 0;\n }\n }\n }\n }\n else {\n this.errorHeight = 0;\n }\n };\n DataLabel.prototype.isRectSeries = function (series) {\n return series.isRectSeries || series.type === 'RangeArea';\n };\n /**\n * Render the data label for series.\n * @return {void}\n */\n DataLabel.prototype.render = function (series, chart, dataLabel) {\n var _this = this;\n // initialize the private variable\n this.initPrivateVariables(series, series.marker);\n var rect;\n var rgbValue;\n var contrast;\n var argsData;\n var border;\n var textSize;\n this.inverted = chart.requireInvertedAxis;\n this.yAxisInversed = series.yAxis.isInversed;\n var element = createElement('div', {\n id: chart.element.id + '_Series_' + series.index + '_DataLabelCollections'\n });\n // Data label point iteration started\n series.points.map(function (point, index) {\n _this.margin = dataLabel.margin;\n var labelText = [];\n var labelLength;\n var clip = series.clipRect;\n border = { width: dataLabel.border.width, color: dataLabel.border.color };\n var argsFont = (extend({}, getValue('properties', dataLabel.font), null, true));\n if ((point.symbolLocations.length && point.symbolLocations[0]) ||\n (series.type === 'BoxAndWhisker' && point.regions.length)) {\n labelText = getLabelText(point, series, chart);\n labelLength = labelText.length;\n for (var i = 0; i < labelLength; i++) {\n argsData = {\n cancel: false, name: textRender, series: series,\n point: point, text: labelText[i], border: border,\n color: dataLabel.fill, template: dataLabel.template, font: argsFont\n };\n chart.trigger(textRender, argsData);\n if (!argsData.cancel) {\n _this.fontBackground = argsData.color;\n _this.isDataLabelShape(argsData);\n _this.markerHeight = series.type === 'Bubble' ? (point.regions[0].height / 2) : _this.markerHeight;\n if (argsData.template !== null) {\n _this.createDataLabelTemplate(element, series, dataLabel, point, argsData, i);\n }\n else {\n textSize = measureText(argsData.text, dataLabel.font);\n rect = _this.calculateTextPosition(point, series, textSize, dataLabel, i);\n if (!isCollide(rect, chart.dataLabelCollections, clip)) {\n chart.dataLabelCollections.push(new Rect(rect.x + clip.x, rect.y + clip.y, rect.width, rect.height));\n if (_this.isShape) {\n series.shapeElement.appendChild(chart.renderer.drawRectangle(new RectOption(_this.commonId + index + '_TextShape_' + i, argsData.color, argsData.border, dataLabel.opacity, rect, dataLabel.rx, dataLabel.ry)));\n }\n // Checking the font color\n rgbValue = convertHexToColor(colorNameToHex(_this.fontBackground));\n contrast = Math.round((rgbValue.r * 299 + rgbValue.g * 587 + rgbValue.b * 114) / 1000);\n textElement(new TextOption(_this.commonId + index + '_Text_' + i, rect.x + _this.margin.left + textSize.width / 2, rect.y + _this.margin.top + textSize.height * 3 / 4, 'middle', argsData.text, 'rotate(0,' + (rect.x) + ',' + (rect.y) + ')', 'auto'), argsData.font, argsData.font.color ||\n ((contrast >= 128 || series.type === 'Hilo') ? 'black' : 'white'), series.textElement);\n }\n }\n }\n }\n }\n });\n if (element.childElementCount) {\n getElement(chart.element.id + '_Secondary_Element').appendChild(element);\n }\n };\n /**\n * Render the data label template.\n * @return {void}\n * @private\n */\n DataLabel.prototype.createDataLabelTemplate = function (parentElement, series, dataLabel, point, data, labelIndex) {\n this.margin = { left: 0, right: 0, bottom: 0, top: 0 };\n var clip = series.clipRect;\n var childElement = createTemplate(createElement('div', {\n id: this.chart.element.id + '_Series_' + series.index + '_DataLabel_'\n + point.index + (labelIndex ? ('_' + labelIndex) : ''),\n styles: 'position: absolute;background-color:' + data.color + ';' +\n getFontStyle(dataLabel.font) + ';border:' + data.border.width + 'px solid ' + data.border.color + ';'\n }), point.index, data.template, this.chart, point, series);\n var elementRect = measureElementRect(childElement);\n var rect = this.calculateTextPosition(point, series, { width: elementRect.width, height: elementRect.height }, dataLabel, labelIndex);\n childElement.style.left = ((this.chart.chartAreaType === 'PolarRadar' ? 0 : series.clipRect.x) + rect.x) + 'px';\n childElement.style.top = ((this.chart.chartAreaType === 'PolarRadar' ? 0 : series.clipRect.y) + rect.y) + 'px';\n var rgbValue = convertHexToColor(colorNameToHex(this.fontBackground));\n var vAxis = series.chart.requireInvertedAxis ? series.xAxis : series.yAxis;\n var hAxis = series.chart.requireInvertedAxis ? series.yAxis : series.xAxis;\n childElement.style.color = dataLabel.font.color ||\n ((Math.round((rgbValue.r * 299 + rgbValue.g * 587 + rgbValue.b * 114) / 1000)) >= 128 ? 'black' : 'white');\n if (childElement.childElementCount && !isCollide(rect, this.chart.dataLabelCollections, clip)\n && (series.seriesType !== 'XY' || point.yValue === undefined || withIn(point.yValue, series.yAxis.visibleRange) ||\n (series.type.indexOf('100') > -1 && withIn(series.stackedValues.endValues[point.index], series.yAxis.visibleRange)))\n && withIn(point.xValue, series.xAxis.visibleRange) && parseFloat(childElement.style.top) >= vAxis.rect.y &&\n parseFloat(childElement.style.left) >= hAxis.rect.x && parseFloat(childElement.style.top) <= vAxis.rect.y + vAxis.rect.height &&\n parseFloat(childElement.style.left) <= hAxis.rect.x + hAxis.rect.width) {\n this.chart.dataLabelCollections.push(new Rect(rect.x + clip.x, rect.y + clip.y, rect.width, rect.height));\n parentElement.appendChild(childElement);\n if (series.animation.enable && this.chart.animateSeries) {\n this.doDataLabelAnimation(series, childElement);\n }\n }\n };\n DataLabel.prototype.calculateTextPosition = function (point, series, textSize, dataLabel, labelIndex) {\n var labelRegion = labelIndex > 1 ? (series.type === 'Candle') ? point.regions[1] : point.regions[0] : point.regions[0];\n if (labelIndex > 1 && series.type === 'HiloOpenClose') {\n labelRegion = (labelIndex === 2) ? point.regions[1] : point.regions[2];\n }\n var location;\n location = this.getLabelLocation(point, series, textSize, labelIndex);\n var padding = 5;\n var clipRect = series.clipRect;\n var rect;\n // calculating alignment\n if (!this.chart.requireInvertedAxis || !this.isRectSeries(series) || series.type === 'BoxAndWhisker') {\n this.locationX = location.x;\n var alignmentValue = textSize.height + (this.borderWidth * 2) + this.markerHeight +\n this.margin.bottom + this.margin.top + padding;\n location.y = (dataLabel.position === 'Auto') ? location.y :\n this.calculateAlignment(alignmentValue, location.y, dataLabel.alignment, this.isRectSeries(series) ? point.yValue < 0 : false);\n // calculating position\n location.y = (!this.isRectSeries(series) || series.type === 'BoxAndWhisker') ?\n this.calculatePathPosition(location.y, dataLabel.position, series, point, textSize, labelIndex) :\n this.calculateRectPosition(location.y, labelRegion, point.yValue < 0 !== this.yAxisInversed, dataLabel.position, series, textSize, labelIndex, point);\n if (this.isRectSeries(series) && this.chart.chartAreaType === 'PolarRadar') {\n location = this.calculatePolarRectPosition(location, dataLabel.position, series, point, textSize, labelIndex);\n }\n }\n else {\n this.locationY = location.y;\n var alignmentValue = textSize.width + this.borderWidth + this.margin.left + this.margin.right - padding;\n location.x = dataLabel.position === 'Auto' ? location.x :\n this.calculateAlignment(alignmentValue, location.x, dataLabel.alignment, point.yValue < 0);\n location.x = this.calculateRectPosition(location.x, labelRegion, point.yValue < 0 !== this.yAxisInversed, dataLabel.position, series, textSize, labelIndex, point);\n }\n rect = calculateRect(location, textSize, this.margin);\n // Checking the condition whether data Label has been exist the clip rect\n if (!((rect.y > clipRect.height) || (rect.x > clipRect.width) ||\n (rect.x + rect.width < 0) || (rect.y + rect.height < 0))) {\n rect.x = rect.x < 0 ? padding : rect.x;\n rect.y = rect.y < 0 ? padding : rect.y;\n rect.x -= (rect.x + rect.width) > clipRect.width ? (rect.x + rect.width) - clipRect.width + padding : 0;\n rect.y -= (rect.y + rect.height) > clipRect.height ? (rect.y + rect.height) - clipRect.height + padding : 0;\n this.fontBackground = this.fontBackground === 'transparent' ? this.chartBackground : this.fontBackground;\n }\n return rect;\n };\n // Calculation label location for polar column draw types\n DataLabel.prototype.calculatePolarRectPosition = function (location, position, series, point, size, labelIndex) {\n var padding = 5;\n var columnRadius;\n var angle = (point.regionData.startAngle - 0.5 * Math.PI) + (point.regionData.endAngle - point.regionData.startAngle) / 2;\n if (labelIndex === 0) {\n columnRadius = point.regionData.radius < point.regionData.innerRadius ? point.regionData.innerRadius\n : point.regionData.radius;\n }\n else {\n columnRadius = point.regionData.radius > point.regionData.innerRadius ? point.regionData.innerRadius\n : point.regionData.radius;\n }\n this.fontBackground = this.fontBackground === 'transparent' ? this.chartBackground : this.fontBackground;\n if (series.drawType.indexOf('Stacking') > -1) {\n position = position === 'Outer' ? 'Top' : position;\n }\n else if (series.drawType.indexOf('Range') > -1) {\n position = (position === 'Outer' || position === 'Top') ? position : 'Auto';\n }\n if (position === 'Outer') {\n columnRadius = labelIndex === 0 ? columnRadius + 2 * padding : columnRadius - 2 * padding;\n }\n else if (position === 'Middle') {\n columnRadius = columnRadius / 2 + padding;\n }\n else if (position === 'Top') {\n columnRadius = labelIndex === 0 ? columnRadius - 2 * padding : columnRadius + 2 * padding;\n }\n else if (position === 'Bottom') {\n columnRadius = padding;\n }\n else {\n if (labelIndex === 0) {\n columnRadius = columnRadius >= series.chart.radius ? columnRadius - padding :\n series.drawType === 'StackingColumn' ? columnRadius - 2 * padding : columnRadius + 2 * padding;\n }\n else {\n columnRadius = columnRadius >= series.chart.radius ? columnRadius + padding : columnRadius - 2 * padding;\n }\n }\n location.x = series.clipRect.width / 2 + series.clipRect.x + columnRadius * Math.cos(angle);\n location.y = series.clipRect.height / 2 + series.clipRect.y + columnRadius * Math.sin(angle);\n return location;\n };\n /**\n * Get the label location\n */\n DataLabel.prototype.getLabelLocation = function (point, series, textSize, labelIndex) {\n var location = new ChartLocation(0, 0);\n var labelRegion = (series.type === 'Candle' && labelIndex > 1) ? point.regions[1] : point.regions[0];\n if (series.type === 'HiloOpenClose') {\n labelRegion = (labelIndex === 2) ? point.regions[1] : point.regions[2];\n }\n var xAxis = series.xAxis;\n var yAxis = series.yAxis;\n var isInverted = series.chart.requireInvertedAxis;\n if (series.type === 'BoxAndWhisker') {\n this.markerHeight = 0;\n switch (labelIndex) {\n case 0:\n location = getPoint(point.xValue, point.median, xAxis, yAxis, isInverted);\n break;\n case 1:\n location = getPoint(point.xValue, point.maximum, xAxis, yAxis, isInverted);\n break;\n case 2:\n location = getPoint(point.xValue, point.minimum, xAxis, yAxis, isInverted);\n break;\n case 3:\n location = getPoint(point.xValue, point.upperQuartile, xAxis, yAxis, isInverted);\n break;\n case 4:\n location = getPoint(point.xValue, point.lowerQuartile, xAxis, yAxis, isInverted);\n break;\n default: {\n location = getPoint(point.xValue, point.outliers[labelIndex - 5], xAxis, yAxis, isInverted);\n this.markerHeight = series.marker.height / 2;\n break;\n }\n }\n location.x = point.regions[0].x + (point.regions[0].width / 2);\n }\n else if (labelIndex === 0 || labelIndex === 1) {\n location = new ChartLocation(point.symbolLocations[0].x, point.symbolLocations[0].y);\n }\n else if ((labelIndex === 2 || labelIndex === 3) && series.type === 'Candle') {\n location = new ChartLocation(point.symbolLocations[1].x, point.symbolLocations[1].y);\n }\n else if (isInverted) {\n location = { x: labelRegion.x + (labelRegion.width) / 2, y: labelRegion.y };\n }\n else {\n location = { x: labelRegion.x + labelRegion.width, y: labelRegion.y + (labelRegion.height) / 2 };\n }\n //Aligning the label at the beginning of the tick, when tick size is less than text size\n if (labelIndex > 1 && series.type === 'HiloOpenClose') {\n if (series.chart.requireInvertedAxis) {\n var height = labelRegion.height;\n location.y = labelRegion.y + height / 2 + 2 * (labelIndex === 2 ? 1 : -1);\n }\n else {\n var width = labelRegion.width;\n location.x = labelRegion.x + width / 2 + 2 * (labelIndex === 2 ? 1 : -1);\n }\n }\n return location;\n };\n DataLabel.prototype.calculateRectPosition = function (labelLocation, rect, isMinus, position, series, textSize, labelIndex, point) {\n if (series.chart.chartAreaType === 'PolarRadar') {\n return null;\n }\n var padding = 5;\n var margin = this.margin;\n var textLength = !this.inverted ? textSize.height : textSize.width;\n var extraSpace = this.borderWidth + textLength / 2 + padding;\n if (series.type.indexOf('Stacking') > -1) {\n position = position === 'Outer' ? 'Top' : position;\n }\n else if (series.type.indexOf('Range') > -1) {\n position = (position === 'Outer' || position === 'Top') ? position : 'Auto';\n }\n else if (series.type === 'Waterfall') {\n position = position === 'Auto' ? 'Middle' : position;\n }\n switch (position) {\n case 'Bottom':\n labelLocation = !this.inverted ?\n isMinus ? (labelLocation - rect.height + extraSpace + margin.top) :\n (labelLocation + rect.height - extraSpace - margin.bottom) :\n isMinus ? (labelLocation + rect.width - extraSpace - margin.left) :\n (labelLocation - rect.width + extraSpace + margin.right);\n break;\n case 'Middle':\n labelLocation = labelLocation = !this.inverted ?\n (isMinus ? labelLocation - (rect.height / 2) : labelLocation + (rect.height / 2)) :\n (isMinus ? labelLocation + (rect.width / 2) : labelLocation - (rect.width / 2));\n break;\n case 'Auto':\n labelLocation = this.calculateRectActualPosition(labelLocation, rect, isMinus, series, textSize, labelIndex, point);\n break;\n default:\n extraSpace += this.errorHeight;\n labelLocation = this.calculateTopAndOuterPosition(labelLocation, rect, position, series, labelIndex, extraSpace, isMinus);\n break;\n }\n var check = !this.inverted ? (labelLocation < rect.y || labelLocation > rect.y + rect.height) :\n (labelLocation < rect.x || labelLocation > rect.x + rect.width);\n this.fontBackground = check ?\n (this.fontBackground === 'transparent' ? this.chartBackground : this.fontBackground)\n : this.fontBackground === 'transparent' ? (point.color || series.interior) : this.fontBackground;\n return labelLocation;\n };\n DataLabel.prototype.calculatePathPosition = function (labelLocation, position, series, point, size, labelIndex) {\n var padding = 5;\n if ((series.type.indexOf('Area') > -1 && series.type !== 'RangeArea')\n && this.yAxisInversed && series.marker.dataLabel.position !== 'Auto') {\n position = position === 'Top' ? 'Bottom' : position === 'Bottom' ? 'Top' : position;\n }\n this.fontBackground = this.fontBackground === 'transparent' ? this.chartBackground : this.fontBackground;\n switch (position) {\n case 'Top':\n case 'Outer':\n labelLocation = labelLocation - this.markerHeight - this.borderWidth - size.height / 2 - this.margin.bottom - padding -\n this.errorHeight;\n break;\n case 'Bottom':\n labelLocation = labelLocation + this.markerHeight + this.borderWidth + size.height / 2 + this.margin.top + padding +\n this.errorHeight;\n break;\n case 'Auto':\n labelLocation = this.calculatePathActualPosition(labelLocation, this.markerHeight, series, point, size, labelIndex);\n break;\n }\n return labelLocation;\n };\n DataLabel.prototype.isDataLabelShape = function (style) {\n this.isShape = (style.color !== 'transparent' || style.border.width > 0);\n this.borderWidth = style.border.width;\n if (!this.isShape) {\n this.margin = { left: 0, right: 0, bottom: 0, top: 0 };\n }\n };\n DataLabel.prototype.calculateRectActualPosition = function (labelLocation, rect, isMinus, series, size, labelIndex, point) {\n var location;\n var labelRect;\n var isOverLap = true;\n var position = 0;\n var collection = this.chart.dataLabelCollections;\n var finalPosition = series.type.indexOf('Range') !== -1 || series.type === 'Hilo' ? 2 : 4;\n while (isOverLap && position < finalPosition) {\n location = this.calculateRectPosition(labelLocation, rect, isMinus, this.getPosition(position), series, size, labelIndex, point);\n if (!this.inverted) {\n labelRect = calculateRect(new ChartLocation(this.locationX, location), size, this.margin);\n isOverLap = labelRect.y < 0 || isCollide(labelRect, collection, series.clipRect) || labelRect.y > series.clipRect.height;\n }\n else {\n labelRect = calculateRect(new ChartLocation(location, this.locationY), size, this.margin);\n isOverLap = labelRect.x < 0 || isCollide(labelRect, collection, series.clipRect) ||\n labelRect.x + labelRect.width > series.clipRect.width;\n }\n position++;\n }\n return location;\n };\n // alignment calculation assigned here\n DataLabel.prototype.calculateAlignment = function (value, labelLocation, alignment, isMinus) {\n switch (alignment) {\n case 'Far':\n labelLocation = !this.inverted ? (isMinus ? labelLocation + value : labelLocation - value) :\n (isMinus ? labelLocation - value : labelLocation + value);\n break;\n case 'Near':\n labelLocation = !this.inverted ? (isMinus ? labelLocation - value : labelLocation + value) :\n (isMinus ? labelLocation + value : labelLocation - value);\n break;\n case 'Center':\n labelLocation = labelLocation;\n break;\n }\n return labelLocation;\n };\n //calculation for top and outer position of datalabel for rect series\n DataLabel.prototype.calculateTopAndOuterPosition = function (location, rect, position, series, index, extraSpace, isMinus) {\n var margin = this.margin;\n var top;\n switch (series.type) {\n case 'RangeColumn':\n case 'RangeArea':\n case 'Hilo':\n top = (index === 0 && !this.yAxisInversed) || (index === 1 && this.yAxisInversed);\n location = this.updateLabelLocation(position, location, extraSpace, margin, rect, top);\n break;\n case 'Candle':\n top = (index === 0 || index === 2) && !this.yAxisInversed\n || (index === 1 || index === 3) && this.yAxisInversed;\n location = this.updateLabelLocation(position, location, extraSpace, margin, rect, top, index > 1);\n break;\n case 'HiloOpenClose':\n if (index <= 1) {\n top = (index === 0 && !this.yAxisInversed) || (index === 1 && this.yAxisInversed);\n location = this.updateLabelLocation(position, location, extraSpace, margin, rect, top);\n }\n else {\n if (this.yAxisInversed) {\n location = !this.inverted ? location + extraSpace + margin.top : location - extraSpace - margin.right;\n }\n else {\n location = !this.inverted ? location - extraSpace - margin.bottom : location + extraSpace + margin.left;\n }\n }\n break;\n default:\n if ((isMinus && position === 'Top') || (!isMinus && position === 'Outer')) {\n location = !this.inverted ? location - extraSpace - margin.bottom : location + extraSpace + margin.left;\n }\n else {\n location = !this.inverted ? location + extraSpace + margin.top : location - extraSpace - margin.right;\n }\n break;\n }\n return location;\n };\n /**\n * Updates the label location\n */\n DataLabel.prototype.updateLabelLocation = function (position, location, extraSpace, margin, rect, top, inside) {\n if (inside === void 0) { inside = false; }\n if (!this.inverted) {\n if (top) {\n location = (position === 'Outer' && !inside) ? location - extraSpace - margin.bottom : location + extraSpace + margin.top;\n }\n else {\n location = (position === 'Outer' && !inside) ? location + rect.height + extraSpace + margin.top :\n location + rect.height - extraSpace - margin.bottom;\n }\n }\n else {\n if (top) {\n location = (position === 'Outer' && !inside) ? location + extraSpace + margin.left : location - extraSpace - margin.right;\n }\n else {\n location = (position === 'Outer' && !inside) ? location - rect.width - extraSpace - margin.right :\n location - rect.width + extraSpace + margin.left;\n }\n }\n return location;\n };\n DataLabel.prototype.calculatePathActualPosition = function (y, markerSize, series, point, size, labelIndex) {\n var points = series.points;\n var index = point.index;\n var yValue = points[index].yValue;\n var position;\n var nextPoint = points.length - 1 > index ? points[index + 1] : null;\n var previousPoint = index > 0 ? points[index - 1] : null;\n var yLocation;\n var isOverLap = true;\n var labelRect;\n var isBottom;\n var positionIndex;\n var collection = this.chart.dataLabelCollections;\n if (series.type === 'Bubble') {\n position = 'Top';\n }\n else if (series.type.indexOf('Step') > -1) {\n position = 'Top';\n if (index) {\n position = (!previousPoint || !previousPoint.visible || (yValue > previousPoint.yValue !== this.yAxisInversed)\n || yValue === previousPoint.yValue) ? 'Top' : 'Bottom';\n }\n }\n else if (series.type === 'BoxAndWhisker') {\n if (labelIndex === 1 || labelIndex === 3 || labelIndex > 4) {\n position = series.yAxis.isInversed ? 'Bottom' : 'Top';\n }\n else if (labelIndex === 2 || labelIndex === 4) {\n position = series.yAxis.isInversed ? 'Top' : 'Bottom';\n }\n else {\n isOverLap = false;\n position = 'Middle';\n yLocation = this.calculatePathPosition(y, position, series, point, size, labelIndex);\n }\n }\n else {\n if (index === 0) {\n position = (!nextPoint || !nextPoint.visible || yValue > nextPoint.yValue ||\n (yValue < nextPoint.yValue && this.yAxisInversed)) ? 'Top' : 'Bottom';\n }\n else if (index === points.length - 1) {\n position = (!previousPoint || !previousPoint.visible || yValue > previousPoint.yValue ||\n (yValue < previousPoint.yValue && this.yAxisInversed)) ? 'Top' : 'Bottom';\n }\n else {\n if (!nextPoint.visible && !(previousPoint && previousPoint.visible)) {\n position = 'Top';\n }\n else if (!nextPoint.visible || !previousPoint) {\n position = (nextPoint.yValue > yValue || (previousPoint && previousPoint.yValue > yValue)) ?\n 'Bottom' : 'Top';\n }\n else {\n var slope = (nextPoint.yValue - previousPoint.yValue) / 2;\n var intersectY = (slope * index) + (nextPoint.yValue - (slope * (index + 1)));\n position = !this.yAxisInversed ? intersectY < yValue ? 'Top' : 'Bottom' :\n intersectY < yValue ? 'Bottom' : 'Top';\n }\n }\n }\n isBottom = position === 'Bottom';\n positionIndex = ['Outer', 'Top', 'Bottom', 'Middle', 'Auto'].indexOf(position);\n while (isOverLap && positionIndex < 4) {\n yLocation = this.calculatePathPosition(y, this.getPosition(positionIndex), series, point, size, labelIndex);\n labelRect = calculateRect(new ChartLocation(this.locationX, yLocation), size, this.margin);\n isOverLap = labelRect.y < 0 || isCollide(labelRect, collection, series.clipRect)\n || (labelRect.y + labelRect.height) > series.clipRect.height;\n positionIndex = isBottom ? positionIndex - 1 : positionIndex + 1;\n isBottom = false;\n }\n return yLocation;\n };\n /**\n * Animates the data label.\n * @param {Series} series - Data label of the series gets animated.\n * @return {void}\n */\n DataLabel.prototype.doDataLabelAnimation = function (series, element) {\n var shapeElements = series.shapeElement.childNodes;\n var textNode = series.textElement.childNodes;\n var delay = series.animation.delay + series.animation.duration;\n var location;\n var length = element ? 1 : textNode.length;\n for (var i = 0; i < length; i++) {\n if (element) {\n element.style.visibility = 'hidden';\n templateAnimate(element, delay, 200, 'ZoomIn');\n }\n else {\n location = new ChartLocation((+textNode[i].getAttribute('x')) + ((+textNode[i].getAttribute('width')) / 2), (+textNode[i].getAttribute('y')) + ((+textNode[i].getAttribute('height')) / 2));\n markerAnimate(textNode[i], delay, 200, series, null, location, true);\n if (shapeElements[i]) {\n location = new ChartLocation((+shapeElements[i].getAttribute('x')) + ((+shapeElements[i].getAttribute('width')) / 2), (+shapeElements[i].getAttribute('y')) + ((+shapeElements[i].getAttribute('height')) / 2));\n markerAnimate(shapeElements[i], delay, 200, series, null, location, true);\n }\n }\n }\n };\n DataLabel.prototype.getPosition = function (index) {\n return (['Outer', 'Top', 'Bottom', 'Middle', 'Auto'][index]);\n };\n /**\n * Get module name.\n */\n DataLabel.prototype.getModuleName = function () {\n // Returns the module name\n return 'DataLabel';\n };\n /**\n * To destroy the dataLabel for series.\n * @return {void}\n * @private\n */\n DataLabel.prototype.destroy = function (chart) {\n // Destroy method performed here\n };\n return DataLabel;\n}());\nexport { DataLabel };\n","import { Mean, RectOption } from '../../common/utils/helper';\nimport { getPoint, PathOption, sum, templateAnimate } from '../../common/utils/helper';\n/**\n * `ErrorBar` module is used to render the error bar for series.\n */\nvar ErrorBar = /** @class */ (function () {\n /**\n * Constructor for the error bar module.\n * @private\n */\n function ErrorBar(chart) {\n this.chart = chart;\n }\n /**\n * Render the error bar for series.\n * @return {void}\n */\n ErrorBar.prototype.render = function (series) {\n if (this.chart.chartAreaType === 'PolarRadar') {\n return null;\n }\n this.createElement(series);\n this.renderErrorBar(series);\n };\n ErrorBar.prototype.renderErrorBar = function (series) {\n var seriesIndex = series.index;\n var point;\n var symbolId;\n var capId;\n var errorbar = series.errorBar;\n var errorBarCap = series.errorBar.errorBarCap;\n var border = series.border;\n var start;\n var mid;\n var end;\n var isInverted;\n var isVert;\n var errorDirection = ['', ''];\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point_1 = _a[_i];\n if (point_1.visible && point_1.symbolLocations[0]) {\n var errorX = 0;\n var errorY = 0;\n switch (errorbar.mode) {\n case 'Vertical':\n errorY = errorbar.verticalError;\n break;\n case 'Horizontal':\n errorX = errorbar.horizontalError;\n break;\n case 'Both':\n errorX = errorbar.horizontalError;\n errorY = errorbar.verticalError;\n break;\n }\n errorDirection = this['calculate' + errorbar.type + 'Value'](point_1, series, this.chart.requireInvertedAxis, errorX, errorY);\n symbolId = this.chart.element.id + '_Series_' + '_ErrorBarGroup_' + seriesIndex + '_Point_' + point_1.index;\n capId = this.chart.element.id + '_Series_' + '_ErrorBarCap_' + seriesIndex + '_Point_' + point_1.index;\n var shapeOption = new PathOption(symbolId, '', errorbar.width, errorbar.color || this.chart.themeStyle.errorBar, null, '', errorDirection[0]);\n var path = this.chart.renderer.drawPath(shapeOption);\n series.errorBarElement.appendChild(path);\n var capOption = new PathOption(capId, '', errorBarCap.width, errorBarCap.color || this.chart.themeStyle.errorBar, null, '', errorDirection[1]);\n var capPath = this.chart.renderer.drawPath(capOption);\n series.errorBarElement.appendChild(capPath);\n }\n }\n };\n // path calculation for error bar\n ErrorBar.prototype.findLocation = function (point, series, isInverted, x1, y1) {\n var errorbar = series.errorBar;\n var direction = errorbar.direction;\n var location = [];\n var stackedValue = series.stackedValues;\n var yValue = series.type.indexOf('Stacking') > -1 ? series.stackedValues.endValues[point.index] :\n (series.seriesType === 'HighLow' || series.seriesType === 'HighLowOpenClose') ? (series.points[point.index].high) :\n point.yValue;\n var startPoint = getPoint(point.xValue + ((direction === 'Plus' || direction === 'Both') ? (errorbar.type === 'Custom' &&\n (errorbar.mode === 'Horizontal' || errorbar.mode === 'Both')) ? x1 = errorbar.horizontalPositiveError : x1 : 0), yValue + ((direction === 'Plus' || direction === 'Both') ? (errorbar.type === 'Custom' &&\n (errorbar.mode === 'Vertical' || errorbar.mode === 'Both')) ? y1 = errorbar.verticalPositiveError : y1 : 0), series.xAxis, series.yAxis, isInverted);\n location.push(startPoint);\n if (series.isRectSeries) {\n var midPoint = point.symbolLocations[0];\n location.push(midPoint);\n }\n else {\n var midPoint = getPoint(point.xValue, point.yValue, series.xAxis, series.yAxis, isInverted);\n location.push(midPoint);\n }\n var endPoint = getPoint(point.xValue - ((direction === 'Minus' || direction === 'Both') ? (errorbar.type === 'Custom' &&\n (errorbar.mode === 'Horizontal' || errorbar.mode === 'Both')) ? x1 = errorbar.horizontalNegativeError : x1 : 0), yValue - ((direction === 'Minus' || direction === 'Both') ? (errorbar.type === 'Custom' &&\n (errorbar.mode === 'Vertical' || errorbar.mode === 'Both')) ? y1 = errorbar.verticalNegativeError : y1 : 0), series.xAxis, series.yAxis, isInverted);\n location.push(endPoint);\n // calculate error height for datalabel position alignment\n point.error = (errorbar.mode === 'Vertical') ? errorbar.verticalError : errorbar.horizontalError;\n this.negativeHeight = (errorbar.mode === 'Vertical' || errorbar.mode === 'Both') ? (isInverted ? (location[1].x - location[2].x) :\n (location[2].y - location[1].y)) : 0;\n this.positiveHeight = (errorbar.mode === 'Vertical' || errorbar.mode === 'Both') ? (isInverted ? (location[0].x - location[1].x) :\n (location[1].y - location[0].y)) : 0;\n return this.getErrorDirection(location[0], location[1], location[2], series, isInverted);\n };\n // calculations for eror bar types\n ErrorBar.prototype.calculateFixedValue = function (point, series, isInverted, errorX, errorY, xAxis, yAxis) {\n var errorbar = series.errorBar;\n return this.findLocation(point, series, isInverted, errorX, errorY);\n };\n ErrorBar.prototype.calculatePercentageValue = function (point, series, isInverted, errorX, errorY, xAxis, yAxis) {\n errorX = (errorX / 100) * point.xValue;\n errorY = (errorY / 100) * point.yValue;\n return this.findLocation(point, series, isInverted, errorX, errorY);\n };\n ErrorBar.prototype.calculateStandardDeviationValue = function (point, series, isInverted, errorX, errorY, xAxis, yAxis) {\n var getMean = this.meanCalculation(series, series.errorBar.mode);\n errorX = errorX * (getMean.horizontalSquareRoot + getMean.horizontalMean);\n errorY = errorY * (getMean.verticalSquareRoot + getMean.verticalMean);\n return this.findLocation(point, series, isInverted, errorX, errorY);\n };\n ErrorBar.prototype.calculateStandardErrorValue = function (point, series, isInverted, errorX, errorY, xAxis, yAxis) {\n var length = series.points.length;\n var getMean = this.meanCalculation(series, series.errorBar.mode);\n errorX = ((errorX * getMean.horizontalSquareRoot) / Math.sqrt(length));\n errorY = ((errorY * getMean.verticalSquareRoot) / Math.sqrt(length));\n return this.findLocation(point, series, isInverted, errorX, errorY);\n };\n ErrorBar.prototype.calculateCustomValue = function (point, series, isInverted, errorX, errorY, xAxis, yAxis) {\n var errorbar = series.errorBar;\n return this.findLocation(point, series, isInverted, errorX, errorY);\n };\n ErrorBar.prototype.getHorizontalDirection = function (start, mid, end, direction, errorMode, capLength) {\n var path = '';\n var capDirection = '';\n path += ' M ' + start.x + ' ' + mid.y + ' L ' + end.x + ' ' + mid.y;\n capDirection += (direction === 'Plus' || direction === 'Both') ? ' M ' + (start.x) + ' ' + (mid.y - capLength) + ' L '\n + (start.x) + ' ' + (mid.y + capLength) : '';\n capDirection += (direction === 'Minus' || direction === 'Both') ? ' M ' + (end.x) + ' ' + (mid.y - capLength) + ' L '\n + (end.x) + ' ' + (mid.y + capLength) : ' ';\n return [path, capDirection];\n };\n ErrorBar.prototype.getVerticalDirection = function (start, mid, end, direction, errorMode, capLength) {\n var path = '';\n var capDirection = '';\n path += ' M ' + mid.x + ' ' + start.y + ' L ' + mid.x + ' ' + end.y;\n capDirection += (direction === 'Plus' || direction === 'Both') ? ' M ' + (mid.x - capLength) + ' ' + start.y + ' L '\n + (mid.x + capLength) + ' ' + start.y : '';\n capDirection += (direction === 'Minus' || direction === 'Both') ? ' M ' + (mid.x - capLength) + ' ' + end.y + ' L '\n + (mid.x + capLength) + ' ' + end.y : '';\n return [path, capDirection];\n };\n ErrorBar.prototype.getBothDirection = function (start, mid, end, direction, errorMode, capLength) {\n var capDirection = '';\n var path = '';\n var pathH = this.getHorizontalDirection(start, mid, end, direction, errorMode, capLength);\n var pathV = this.getVerticalDirection(start, mid, end, direction, errorMode, capLength);\n path = pathH[0].concat(pathV[0]);\n capDirection = pathH[1].concat(pathV[1]);\n return [path, capDirection];\n };\n ErrorBar.prototype.getErrorDirection = function (start, mid, end, series, isInverted) {\n var direction = series.errorBar.direction;\n var mode = series.errorBar.mode;\n var capLength = series.errorBar.errorBarCap.length;\n var path = '';\n var paths;\n var capDirection = '';\n var errorMode = mode;\n switch (mode) {\n case 'Both':\n errorMode = mode;\n break;\n case 'Horizontal':\n errorMode = (isInverted) ? 'Vertical' : mode;\n break;\n case 'Vertical':\n errorMode = (isInverted) ? 'Horizontal' : mode;\n break;\n }\n switch (errorMode) {\n case 'Horizontal':\n paths = this.getHorizontalDirection(start, mid, end, direction, errorMode, capLength);\n break;\n case 'Vertical':\n paths = this.getVerticalDirection(start, mid, end, direction, errorMode, capLength);\n break;\n case 'Both':\n paths = this.getBothDirection(start, mid, end, direction, errorMode, capLength);\n break;\n }\n return [paths[0], paths[1]];\n };\n // mean calculation for standard deviation and standard error\n ErrorBar.prototype.meanCalculation = function (series, mode) {\n var sumOfX = 0;\n var sumOfY = 0;\n var verticalMean = 0;\n var horizontalMean = 0;\n var horSquareDev;\n var verStandardMean;\n var horStandardMean;\n var verSquareTotal;\n var horSquareTotal;\n var verSquareRoot;\n var horSquareRoot;\n var length = series.points.length;\n switch (mode) {\n case 'Vertical':\n sumOfY = sum(series.yData);\n verticalMean = sumOfY / length;\n break;\n case 'Horizontal':\n sumOfX = sum(series.xData);\n horizontalMean = sumOfX / length;\n break;\n case 'Both':\n sumOfY = sum(series.yData);\n verticalMean = sumOfY / length;\n sumOfX = sum(series.xData);\n horizontalMean = sumOfX / length;\n }\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n if (mode === 'Vertical') {\n sumOfY = sumOfY + Math.pow((point.yValue - verticalMean), 2);\n }\n else if (mode === 'Horizontal') {\n sumOfX = sumOfX + Math.pow((point.xValue - horizontalMean), 2);\n }\n else {\n sumOfY = sumOfY + Math.pow((point.yValue - verticalMean), 2);\n sumOfX = sumOfX + Math.pow((point.xValue - horizontalMean), 2);\n }\n }\n verStandardMean = sumOfY / (length - 1);\n verSquareRoot = Math.sqrt(sumOfY / (length - 1));\n horStandardMean = sumOfX / (length - 1);\n horSquareRoot = Math.sqrt(sumOfX / (length - 1));\n return new Mean(verStandardMean, verSquareRoot, horStandardMean, horSquareRoot, verticalMean, horizontalMean);\n };\n ErrorBar.prototype.createElement = function (series) {\n var explodeValue = 5;\n var render = series.chart.renderer;\n var transform;\n transform = series.chart.chartAreaType === 'Cartesian' ? 'translate(' + series.clipRect.x + ',' + (series.clipRect.y) + ')' : '';\n var markerHeight = (series.marker.height + explodeValue) / 2;\n var markerWidth = (series.marker.width + explodeValue) / 2;\n if (series.chart.chartAreaType === 'Cartesian') {\n var errorBarClipRect = render.drawClipPath(new RectOption(this.chart.element.id + '_ChartErrorBarClipRect_' + series.index, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: -markerWidth, y: -markerHeight,\n width: series.clipRect.width + markerWidth * 2, height: series.clipRect.height + markerHeight * 2\n }));\n series.errorBarElement = render.createGroup({\n 'id': this.chart.element.id + 'ErrorBarGroup' + series.index,\n 'transform': transform,\n 'clip-path': 'url(#' + this.chart.element.id + '_ChartErrorBarClipRect_' + series.index + ')'\n });\n series.errorBarElement.appendChild(errorBarClipRect);\n }\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n ErrorBar.prototype.doErrorBarAnimation = function (series) {\n var errorBarElements = series.errorBarElement.childNodes;\n if (!errorBarElements) {\n return null;\n }\n var delay = series.animation.delay + series.animation.duration;\n var j = 1;\n while (j < errorBarElements.length) {\n for (var i = 0; i < series.points.length; i++) {\n if (!series.points[i].symbolLocations[0]) {\n continue;\n }\n errorBarElements[j].style.visibility = 'hidden';\n templateAnimate(errorBarElements[j], delay, 350, series.chart.requireInvertedAxis ? 'SlideLeftIn' : 'SlideBottomIn', false);\n }\n j++;\n }\n };\n /**\n * Get module name.\n */\n ErrorBar.prototype.getModuleName = function () {\n // Returns the module name\n return 'ErrorBar';\n };\n /**\n * To destroy the errorBar for series.\n * @return {void}\n * @private\n */\n ErrorBar.prototype.destroy = function (chart) {\n // Destroy method performed here\n };\n return ErrorBar;\n}());\nexport { ErrorBar };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * Chart legend\n */\nimport { remove, Browser } from '@syncfusion/ej2-base';\nimport { extend } from '@syncfusion/ej2-base';\nimport { LegendOptions, BaseLegend } from '../../common/legend/legend';\nimport { measureText, textTrim } from '../../common/utils/helper';\nimport { legendRender } from '../../common/model/constants';\n/**\n * `Legend` module is used to render legend for the chart.\n */\nvar Legend = /** @class */ (function (_super) {\n __extends(Legend, _super);\n function Legend(chart) {\n var _this = _super.call(this, chart) || this;\n _this.library = _this;\n _this.addEventListener();\n return _this;\n }\n /**\n * Binding events for legend module.\n */\n Legend.prototype.addEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n this.chart.on(Browser.touchMoveEvent, this.mouseMove, this);\n this.chart.on('click', this.click, this);\n this.chart.on(Browser.touchEndEvent, this.mouseEnd, this);\n };\n /**\n * UnBinding events for legend module.\n */\n Legend.prototype.removeEventListener = function () {\n if (this.chart.isDestroyed) {\n return;\n }\n this.chart.off(Browser.touchMoveEvent, this.mouseMove);\n this.chart.off('click', this.click);\n this.chart.off(Browser.touchEndEvent, this.mouseEnd);\n };\n /**\n * To handle mosue move for legend module\n */\n Legend.prototype.mouseMove = function (e) {\n if (this.chart.legendSettings.visible && !this.chart.isTouch) {\n this.move(e);\n }\n };\n /**\n * To handle mosue end for legend module\n */\n Legend.prototype.mouseEnd = function (e) {\n if (this.chart.legendSettings.visible && this.chart.isTouch) {\n this.move(e);\n }\n };\n /**\n * Get the legend options.\n * @return {void}\n * @private\n */\n Legend.prototype.getLegendOptions = function (visibleSeriesCollection, chart) {\n this.legendCollections = [];\n var seriesType;\n for (var _i = 0, visibleSeriesCollection_1 = visibleSeriesCollection; _i < visibleSeriesCollection_1.length; _i++) {\n var series = visibleSeriesCollection_1[_i];\n if (series.category !== 'Indicator') {\n seriesType = (chart.chartAreaType === 'PolarRadar') ? series.drawType :\n series.type;\n this.legendCollections.push(new LegendOptions(series.name, series.interior, series.legendShape, series.visible, seriesType, series.marker.shape, series.marker.visible));\n }\n }\n };\n /** @private */\n Legend.prototype.getLegendBounds = function (availableSize, legendBounds, legend) {\n var padding = legend.padding;\n var extraHeight = 0;\n var extraWidth = 0;\n if (!this.isVertical) {\n extraHeight = !legend.height ? ((availableSize.height / 100) * 5) : 0;\n }\n else {\n extraWidth = !legend.width ? ((availableSize.width / 100) * 5) : 0;\n }\n legendBounds.height += extraHeight;\n legendBounds.width += extraWidth;\n var shapeHeight = legend.shapeHeight;\n var shapeWidth = legend.shapeWidth;\n var shapePadding = legend.shapePadding;\n var maximumWidth = 0;\n var rowWidth = 0;\n var legendWidth = 0;\n var columnHeight = 0;\n var rowCount = 0;\n var legendEventArgs;\n this.maxItemHeight = Math.max(measureText('MeasureText', legend.textStyle).height, legend.shapeHeight);\n var render = false;\n for (var _i = 0, _a = this.legendCollections; _i < _a.length; _i++) {\n var legendOption = _a[_i];\n legendEventArgs = {\n fill: legendOption.fill, text: legendOption.text, shape: legendOption.shape,\n markerShape: legendOption.markerShape, name: legendRender, cancel: false\n };\n this.chart.trigger(legendRender, legendEventArgs);\n legendOption.render = !legendEventArgs.cancel;\n legendOption.text = legendEventArgs.text;\n legendOption.fill = legendEventArgs.fill;\n legendOption.shape = legendEventArgs.shape;\n legendOption.markerShape = legendEventArgs.markerShape;\n legendOption.textSize = measureText(legendOption.text, legend.textStyle);\n if (legendOption.render && legendOption.text !== '') {\n render = true;\n legendWidth = shapeWidth + shapePadding + legendOption.textSize.width + padding;\n rowWidth = rowWidth + legendWidth;\n if (legendBounds.width < (padding + rowWidth) || this.isVertical) {\n maximumWidth = Math.max(maximumWidth, (rowWidth + padding - (this.isVertical ? 0 : legendWidth)));\n if (rowCount === 0 && (legendWidth !== rowWidth)) {\n rowCount = 1;\n }\n rowWidth = this.isVertical ? 0 : legendWidth;\n rowCount++;\n columnHeight = (rowCount * (this.maxItemHeight + padding)) + padding;\n }\n }\n }\n columnHeight = Math.max(columnHeight, (this.maxItemHeight + padding) + padding);\n this.isPaging = legendBounds.height < columnHeight;\n this.totalPages = rowCount;\n if (render) {\n this.setBounds(Math.max((rowWidth + padding), maximumWidth), columnHeight, legend, legendBounds);\n }\n else {\n this.setBounds(0, 0, legend, legendBounds);\n }\n };\n /** @private */\n Legend.prototype.getRenderPoint = function (legendOption, start, textPadding, prevLegend, rect, count, firstLegend) {\n var padding = this.legend.padding;\n var previousBound = (prevLegend.location.x + textPadding + prevLegend.textSize.width);\n if ((previousBound + (legendOption.textSize.width + textPadding)) > (rect.x + rect.width + this.legend.shapeWidth / 2) ||\n this.isVertical) {\n legendOption.location.x = start.x;\n legendOption.location.y = (count === firstLegend) ? prevLegend.location.y :\n prevLegend.location.y + this.maxItemHeight + padding;\n }\n else {\n legendOption.location.x = (count === firstLegend) ? prevLegend.location.x : previousBound;\n legendOption.location.y = prevLegend.location.y;\n }\n var availwidth = (this.legendBounds.x + this.legendBounds.width) - (legendOption.location.x +\n textPadding - this.legend.shapeWidth / 2);\n legendOption.text = textTrim(+availwidth.toFixed(4), legendOption.text, this.legend.textStyle);\n };\n /** @private */\n Legend.prototype.LegendClick = function (seriesIndex) {\n var chart = this.chart;\n var series = chart.visibleSeries[seriesIndex];\n var legend = this.legendCollections[seriesIndex];\n var selectedDataIndexes = [];\n if (chart.selectionModule) {\n selectedDataIndexes = extend([], chart.selectionModule.selectedDataIndexes, null, true);\n }\n if (chart.legendSettings.toggleVisibility) {\n if (!series.visible) {\n series.visible = true;\n }\n else {\n series.visible = false;\n }\n legend.visible = (series.visible);\n if (chart.svgObject.childNodes.length > 0) {\n while (chart.svgObject.lastChild) {\n chart.svgObject.removeChild(chart.svgObject.lastChild);\n }\n remove(chart.svgObject);\n }\n chart.animateSeries = false;\n chart.removeSvg();\n chart.refreshAxis();\n series.refreshAxisLabel();\n this.refreshSeries(chart.visibleSeries);\n chart.refreshBound();\n chart.trigger('loaded', { chart: chart });\n if (selectedDataIndexes.length > 0) {\n chart.selectionModule.selectedDataIndexes = selectedDataIndexes;\n chart.selectionModule.redrawSelection(chart, chart.selectionMode);\n }\n }\n else if (chart.selectionModule) {\n chart.selectionModule.legendSelection(chart, seriesIndex);\n }\n };\n Legend.prototype.refreshSeries = function (seriesCollection) {\n for (var _i = 0, seriesCollection_1 = seriesCollection; _i < seriesCollection_1.length; _i++) {\n var series = seriesCollection_1[_i];\n series.position = undefined;\n }\n };\n /**\n * To show the tooltip for the trimmed text in legend.\n * @return {void}\n */\n Legend.prototype.click = function (event) {\n if (!this.chart.legendSettings.visible) {\n return;\n }\n var targetId = event.target.id;\n var legendItemsId = [this.legendID + '_text_', this.legendID + '_shape_marker_',\n this.legendID + '_shape_'];\n var seriesIndex;\n for (var _i = 0, legendItemsId_1 = legendItemsId; _i < legendItemsId_1.length; _i++) {\n var id = legendItemsId_1[_i];\n if (targetId.indexOf(id) > -1) {\n seriesIndex = parseInt(targetId.split(id)[1], 10);\n this.LegendClick(seriesIndex);\n }\n }\n if (targetId.indexOf(this.legendID + '_pageup') > -1) {\n this.changePage(event, true);\n }\n else if (targetId.indexOf(this.legendID + '_pagedown') > -1) {\n this.changePage(event, false);\n }\n };\n /**\n * Get module name\n */\n Legend.prototype.getModuleName = function () {\n return 'Legend';\n };\n /**\n * To destroy the Legend.\n * @return {void}\n * @private\n */\n Legend.prototype.destroy = function (chart) {\n this.removeEventListener();\n };\n return Legend;\n}(BaseLegend));\nexport { Legend };\n","import { createTemplate, measureElementRect, logBase } from '../utils/helper';\nimport { ChartLocation, stringToNumber, appendElement, withIn, Rect } from '../utils/helper';\nimport { getPoint } from '../utils/helper';\nimport { createElement } from '@syncfusion/ej2-base';\nimport { annotationRender } from '../model/constants';\nimport { DataUtil } from '@syncfusion/ej2-data';\n/**\n * Annotation Module handles the Annotation for chart and accumulation series.\n */\nvar AnnotationBase = /** @class */ (function () {\n /**\n * Constructor for chart and accumulation annotation\n * @param control\n */\n function AnnotationBase(control) {\n this.control = control;\n }\n /**\n * Method to render the annotation for chart and accumulation series.\n * @private\n * @param annotation\n * @param index\n */\n AnnotationBase.prototype.render = function (annotation, index) {\n this.isChart = this.control.getModuleName() === 'chart';\n this.annotation = annotation;\n var childElement = createTemplate(createElement('div', {\n id: this.control.element.id + '_Annotation_' + index,\n styles: 'position: absolute;'\n }), index, annotation.content, this.control);\n return childElement;\n };\n /**\n * Method to calculate the location for annotation - coordinate unit as pixel.\n * @private\n * @param location\n */\n AnnotationBase.prototype.setAnnotationPixelValue = function (location) {\n var rect;\n rect = this.annotation.region === 'Chart' ?\n new Rect(0, 0, this.control.availableSize.width, this.control.availableSize.height) :\n this.isChart ?\n this.control.chartAxisLayoutPanel.seriesClipRect :\n this.control.series[0].accumulationBound;\n location.x = ((typeof this.annotation.x !== 'string') ?\n ((typeof this.annotation.x === 'number') ? this.annotation.x : 0) :\n stringToNumber(this.annotation.x, rect.width)) + rect.x;\n location.y = ((typeof this.annotation.y === 'number') ? this.annotation.y :\n stringToNumber(this.annotation.y, rect.height)) + rect.y;\n return true;\n };\n /**\n * Method to calculate the location for annotation - coordinate unit as point.\n * @private\n * @param location\n */\n AnnotationBase.prototype.setAnnotationPointValue = function (location) {\n var symbolLocation = new ChartLocation(0, 0);\n if (this.isChart) {\n var xAxis = void 0;\n var yAxis = void 0;\n var chart = this.control;\n var annotation = this.annotation;\n var xValue = void 0;\n var isLog = false;\n var xAxisName = annotation.xAxisName;\n var yAxisName = annotation.yAxisName;\n var isInverted = chart.requireInvertedAxis;\n for (var _i = 0, _a = chart.axisCollections; _i < _a.length; _i++) {\n var axis = _a[_i];\n if (xAxisName === axis.name || (xAxisName == null && axis.name === 'primaryXAxis')) {\n xAxis = axis;\n if (xAxis.valueType.indexOf('Category') > -1) {\n var xAnnotation = xAxis.valueType === 'DateTimeCategory' ? (annotation.x.getTime()).toString() :\n annotation.x;\n if (xAxis.labels.indexOf(xAnnotation) < 0) {\n return false;\n }\n else {\n xValue = xAxis.labels.indexOf(xAnnotation);\n }\n }\n else if (xAxis.valueType === 'DateTime') {\n var option = { skeleton: 'full', type: 'dateTime' };\n xValue = (typeof this.annotation.x === 'object') ?\n Date.parse(chart.intl.getDateParser(option)(chart.intl.getDateFormat(option)(new Date(DataUtil.parse.parseJson({ val: annotation.x }).val)))) : 0;\n }\n else {\n xValue = +annotation.x;\n }\n }\n else if (yAxisName === axis.name || (yAxisName == null && axis.name === 'primaryYAxis')) {\n yAxis = axis;\n isLog = yAxis.valueType === 'Logarithmic';\n }\n }\n if (xAxis && yAxis && withIn(xAxis.valueType === 'Logarithmic' ? logBase(xValue, xAxis.logBase) : xValue, xAxis.visibleRange)) {\n symbolLocation = getPoint(xValue, withIn((isLog ? logBase(+this.annotation.y, yAxis.logBase) : +this.annotation.y), yAxis.visibleRange) ? +annotation.y :\n isLog ? Math.pow(yAxis.logBase, yAxis.visibleRange.max) :\n +annotation.y > yAxis.visibleRange.max ? yAxis.visibleRange.max : yAxis.visibleRange.min, xAxis, yAxis, isInverted);\n location.x = symbolLocation.x + (isInverted ? yAxis.rect.x : xAxis.rect.x);\n location.y = symbolLocation.y + (isInverted ? xAxis.rect.y : yAxis.rect.y);\n }\n else {\n return false;\n }\n return true;\n }\n else {\n return this.setAccumulationPointValue(location);\n }\n };\n /**\n * To process the annotation for accumulation chart\n * @param annotation\n * @param index\n * @param parentElement\n */\n AnnotationBase.prototype.processAnnotation = function (annotation, index, parentElement) {\n var annotationElement;\n var location;\n location = new ChartLocation(0, 0);\n annotationElement = this.render(annotation, index);\n if (this['setAnnotation' + annotation.coordinateUnits + 'Value'](location)) {\n this.setElementStyle(location, annotationElement, parentElement);\n }\n };\n /**\n * Method to calculate the location for annotation - coordinate unit as point in accumulation chart.\n * @private\n * @param location\n */\n AnnotationBase.prototype.setAccumulationPointValue = function (location) {\n var accumulation = this.control;\n var point;\n for (var _i = 0, _a = accumulation.visibleSeries[0].points; _i < _a.length; _i++) {\n var accPoint = _a[_i];\n if (typeof accPoint.x === 'object') {\n if (Date.parse(accPoint.x) === Date.parse(this.annotation.x) &&\n accPoint.y === this.annotation.y) {\n point = accPoint;\n break;\n }\n }\n else {\n if (accPoint.x === this.annotation.x && accPoint.y === this.annotation.y) {\n point = accPoint;\n break;\n }\n }\n }\n if (point && point.visible) {\n location.x = point.symbolLocation.x;\n location.y = point.symbolLocation.y;\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Method to set the element style for accumulation / chart annotation.\n * @private\n * @param location\n * @param element\n * @param parentElement\n */\n AnnotationBase.prototype.setElementStyle = function (location, element, parentElement) {\n var elementRect = measureElementRect(element);\n var argsData = {\n cancel: false, name: annotationRender, content: element,\n location: location\n };\n this.control.trigger(annotationRender, argsData);\n if (!argsData.cancel) {\n argsData.content.style.left = this.setAlignmentValue(this.annotation.horizontalAlignment, elementRect.width, argsData.location.x) + 'px';\n argsData.content.style.top = this.setAlignmentValue(this.annotation.verticalAlignment, elementRect.height, argsData.location.y) + 'px';\n argsData.content.setAttribute('aria-label', this.annotation.description || 'Annotation');\n appendElement(argsData.content, parentElement);\n }\n };\n /**\n * Method to calculate the alignment value for annotation.\n * @private\n * @param alignment\n * @param size\n * @param value\n */\n AnnotationBase.prototype.setAlignmentValue = function (alignment, size, value) {\n switch (alignment) {\n case 'Top':\n case 'Near':\n value -= size;\n break;\n case 'Bottom':\n case 'Far':\n value += 0;\n break;\n case 'Middle':\n case 'Center':\n value -= (size / 2);\n break;\n }\n return value;\n };\n return AnnotationBase;\n}());\nexport { AnnotationBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { AnnotationBase } from '../../common/annotation/annotation';\nimport { appendElement } from '../../common/utils/helper';\nimport { createElement } from '@syncfusion/ej2-base';\n/**\n * `ChartAnnotation` module handles the annotation for chart.\n */\nvar ChartAnnotation = /** @class */ (function (_super) {\n __extends(ChartAnnotation, _super);\n /**\n * Constructor for chart annotation.\n * @private.\n */\n function ChartAnnotation(control, annotations) {\n var _this = _super.call(this, control) || this;\n _this.chart = control;\n _this.annotations = annotations;\n return _this;\n }\n /**\n * Method to render the annotation for chart\n * @param element\n * @private\n */\n ChartAnnotation.prototype.renderAnnotations = function (element) {\n var _this = this;\n this.annotations = this.chart.annotations;\n this.parentElement = createElement('div', {\n id: this.chart.element.id + '_Annotation_Collections'\n });\n this.annotations.map(function (annotation, index) {\n _this.processAnnotation(annotation, index, _this.parentElement);\n });\n appendElement(this.parentElement, element);\n };\n /**\n * To destroy the annotation.\n * @return {void}\n * @private\n */\n ChartAnnotation.prototype.destroy = function (control) {\n // Destroy method performed here\n };\n /**\n * Get module name.\n */\n ChartAnnotation.prototype.getModuleName = function () {\n // Returns te module name\n return 'Annotation';\n };\n return ChartAnnotation;\n}(AnnotationBase));\nexport { ChartAnnotation };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange, PathOption, sum } from '../../common/utils/helper';\nimport { Size, getSaturationColor, getPoint } from '../../common/utils/helper';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { ColumnBase } from './column-base';\nimport { getMedian } from '../../common/utils/helper';\n/**\n * `BoxAndWhiskerSeries` module is used to render the box and whisker series.\n */\nvar BoxAndWhiskerSeries = /** @class */ (function (_super) {\n __extends(BoxAndWhiskerSeries, _super);\n function BoxAndWhiskerSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render BoxAndWhisker series.\n * @return {void}\n * @private\n */\n BoxAndWhiskerSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var sideBySideInfo = this.getSideBySideInfo(series);\n var argsData;\n var centerRegion;\n var borderWidth = series.border.width || 1;\n for (var _i = 0, _a = series.points; _i < _a.length; _i++) {\n var point = _a[_i];\n point.symbolLocations = [];\n point.regions = [];\n var centerRegion_1 = void 0;\n if (point.visible && withInRange(series.points[point.index - 1], point, series.points[point.index + 1], series)) {\n this.findBoxPlotValues(point.y, point, series.boxPlotMode);\n //region to cover the top and bottom ticks\n this.updateTipRegion(series, point, sideBySideInfo);\n //get middle rect\n centerRegion_1 = this.getRectangle((point.xValue + sideBySideInfo.start), point.upperQuartile, (point.xValue + sideBySideInfo.end), point.lowerQuartile, series);\n point.regions.push(centerRegion_1);\n argsData = this.triggerEvent(series, point, series.interior, {\n color: (!isNullOrUndefined(series.border.color) && series.border.color !== 'transparent') ? series.border.color :\n getSaturationColor(series.interior, -0.6),\n width: series.border.width ? series.border.width : 1\n });\n if (!argsData.cancel) {\n this.renderBoxAndWhisker(series, point, centerRegion_1, argsData, this.getPathString(point, series, getPoint(point.xValue, point.median, xAxis, yAxis, isInverted), getPoint(point.xValue + sideBySideInfo.median, point.average, xAxis, yAxis, isInverted)), sideBySideInfo.median);\n }\n }\n }\n if (series.marker.visible) {\n series.chart.markerRender.render(series);\n }\n };\n /**\n * update the tip region fo box plot\n * @param series\n * @param point\n * @param sideBySideInfo\n */\n BoxAndWhiskerSeries.prototype.updateTipRegion = function (series, point, sideBySideInfo) {\n var tipRegion = this.getRectangle((point.xValue + sideBySideInfo.median), point.maximum, (point.xValue + sideBySideInfo.median), point.minimum, series);\n this.updateTipSize(series, point, tipRegion, series.chart.requireInvertedAxis);\n };\n /**\n * Update tip size to tip regions\n * @param series\n * @param point\n * @param region\n * @param isInverted\n */\n BoxAndWhiskerSeries.prototype.updateTipSize = function (series, point, region, isInverted) {\n var borderWidth = series.border.width || 1;\n if (!isInverted) {\n region.x -= borderWidth / 2;\n region.width = region.width || borderWidth;\n }\n else {\n region.y -= borderWidth / 2;\n region.height = region.height || borderWidth;\n }\n point.regions.push(region);\n };\n /**\n * Calculation for path direction performed here\n * @param point\n * @param series\n * @param median\n * @param average\n */\n BoxAndWhiskerSeries.prototype.getPathString = function (point, series, median, average) {\n var topRect = point.regions[0];\n var midRect = point.regions[1];\n var direction = '';\n var width = series.chart.requireInvertedAxis ? topRect.height : topRect.width;\n var center = series.chart.requireInvertedAxis ? topRect.y + topRect.height / 2 :\n topRect.x + topRect.width / 2;\n var midWidth = midRect.x + midRect.width;\n var midHeight = midRect.y + midRect.height;\n var topWidth = topRect.x + topRect.width;\n var topHeight = topRect.y + topRect.height;\n if (!series.chart.requireInvertedAxis) {\n this.updateTipSize(series, point, { x: midRect.x, y: topRect.y, width: midWidth - midRect.x, height: 0 }, true);\n this.updateTipSize(series, point, { x: midRect.x, y: topHeight, width: midWidth - midRect.x, height: 0 }, true);\n direction += 'M ' + midRect.x + ' ' + topRect.y + ' ' + ' L ' + midWidth + ' ' + topRect.y;\n direction += ' M ' + center + ' ' + topRect.y + ' ' + ' L ' + center + ' ' + midRect.y;\n direction += ' M ' + midRect.x + ' ' + midRect.y + ' ' + ' L ' + midWidth + ' ' + midRect.y +\n ' L ' + midWidth + ' ' + midHeight + ' L ' + midRect.x + ' ' + midHeight + ' Z';\n direction += ' M ' + center + ' ' + midHeight + ' L ' + center + ' ' + topHeight;\n direction += ' M ' + midRect.x + ' ' + topHeight + ' L ' + midWidth + ' ' + topHeight;\n direction += ' M ' + midRect.x + ' ' + median.y + ' L ' + midWidth + ' ' + median.y;\n direction += series.showMean ?\n ' M ' + (average.x - 5) + ' ' + (average.y - 5) + ' L ' + (average.x + 5) + ' ' + (average.y + 5) +\n ' M ' + (average.x + 5) + ' ' + (average.y - 5) + ' L ' + (average.x - 5) + ' ' + (average.y + 5) : '';\n }\n else {\n this.updateTipSize(series, point, { x: topRect.x, y: midRect.y, width: 0, height: midHeight - midRect.y }, false);\n this.updateTipSize(series, point, { x: topWidth, y: midRect.y, width: 0, height: midHeight - midRect.y }, true);\n direction += 'M ' + topRect.x + ' ' + midRect.y + ' L ' + topRect.x + ' ' + midHeight;\n direction += 'M ' + topRect.x + ' ' + center + ' ' + ' L ' + midRect.x + ' ' + center;\n direction += ' M ' + midRect.x + ' ' + midRect.y + ' ' + ' L ' + midWidth + ' ' + midRect.y +\n ' L ' + midWidth + ' ' + midHeight + ' L ' + midRect.x + ' ' + midHeight + ' Z';\n direction += ' M ' + midWidth + ' ' + center + ' L ' + topWidth + ' ' + center;\n direction += ' M ' + topWidth + ' ' + midRect.y + ' L ' + topWidth + ' ' + midHeight;\n direction += ' M ' + median.x + ' ' + midRect.y + ' ' + ' L ' + median.x + ' ' + midHeight;\n direction += series.showMean ?\n 'M ' + (average.x + 5) + ' ' + (average.y - 5) + ' L ' + (average.x - 5) + ' ' + (average.y + 5) +\n 'M ' + (average.x - 5) + ' ' + (average.y - 5) + ' L ' + (average.x + 5) + ' ' + (average.y + 5) : '';\n }\n return direction;\n };\n /**\n * Rendering for box and whisker append here.\n * @param series\n * @param point\n * @param rect\n * @param argsData\n * @param direction\n */\n BoxAndWhiskerSeries.prototype.renderBoxAndWhisker = function (series, point, rect, argsData, direction, median) {\n var location;\n var size;\n var symbolId = series.chart.element.id + '_Series_' + series.index + '_Point_' + point.index;\n var element = series.chart.renderer.drawPath(new PathOption(symbolId + '_BoxPath', argsData.fill, argsData.border.width, argsData.border.color, series.opacity, series.dashArray, direction));\n element.setAttribute('aria-label', point.x.toString() + ':' + point.maximum.toString()\n + ':' + point.minimum.toString() + ':' + point.lowerQuartile.toString() + ':' + point.upperQuartile.toString());\n var parentElement = series.chart.renderer.createGroup({\n 'id': symbolId\n });\n parentElement.appendChild(element);\n for (var i = 0; i < point.outliers.length; i++) {\n location = getPoint((point.xValue + median), point.outliers[i], series.xAxis, series.yAxis, series.chart.requireInvertedAxis);\n size = new Size(series.marker.width, series.marker.height);\n point.symbolLocations.push(location);\n this.updateTipSize(series, point, {\n x: location.x - (size.width / 2), y: location.y - (size.height / 2),\n width: size.width, height: size.height\n }, true);\n }\n series.seriesElement.appendChild(parentElement);\n };\n /**\n * To find the box plot values\n * @param yValues\n * @param point\n * @param mode\n */\n BoxAndWhiskerSeries.prototype.findBoxPlotValues = function (yValues, point, mode) {\n var yCount = yValues.length;\n var quartile = {\n average: sum(yValues) / yCount,\n lowerQuartile: 0, upperQuartile: 0,\n maximum: 0, minimum: 0,\n median: 0, outliers: []\n };\n if (mode === 'Exclusive') {\n quartile.lowerQuartile = this.getExclusiveQuartileValue(yValues, yCount, 0.25);\n quartile.upperQuartile = this.getExclusiveQuartileValue(yValues, yCount, 0.75);\n quartile.median = this.getExclusiveQuartileValue(yValues, yCount, 0.5);\n }\n else if (mode === 'Inclusive') {\n quartile.lowerQuartile = this.getInclusiveQuartileValue(yValues, yCount, 0.25);\n quartile.upperQuartile = this.getInclusiveQuartileValue(yValues, yCount, 0.75);\n quartile.median = this.getInclusiveQuartileValue(yValues, yCount, 0.5);\n }\n else {\n quartile.median = getMedian(yValues);\n this.getQuartileValues(yValues, yCount, quartile);\n }\n this.getMinMaxOutlier(yValues, yCount, quartile);\n point.minimum = quartile.minimum;\n point.maximum = quartile.maximum;\n point.lowerQuartile = quartile.lowerQuartile;\n point.upperQuartile = quartile.upperQuartile;\n point.median = quartile.median;\n point.outliers = quartile.outliers;\n point.average = quartile.average;\n };\n /**\n * to find the exclusive quartile values\n * @param yValues\n * @param count\n * @param percentile\n */\n BoxAndWhiskerSeries.prototype.getExclusiveQuartileValue = function (yValues, count, percentile) {\n if (count === 0) {\n return 0;\n }\n else if (count === 1) {\n return yValues[0];\n }\n var value = 0;\n var rank = percentile * (count + 1);\n var integerRank = Math.floor(Math.abs(rank));\n var fractionRank = rank - integerRank;\n if (integerRank === 0) {\n value = yValues[0];\n }\n else if (integerRank > count - 1) {\n value = yValues[count - 1];\n }\n else {\n value = fractionRank * (yValues[integerRank] - yValues[integerRank - 1]) + yValues[integerRank - 1];\n }\n return value;\n };\n /**\n * to find the inclusive quartile values\n * @param yValues\n * @param count\n * @param percentile\n */\n BoxAndWhiskerSeries.prototype.getInclusiveQuartileValue = function (yValues, count, percentile) {\n if (count === 0) {\n return 0;\n }\n else if (count === 1) {\n return yValues[0];\n }\n var value = 0;\n var rank = percentile * (count - 1);\n var integerRank = Math.floor(Math.abs(rank));\n var fractionRank = rank - integerRank;\n value = fractionRank * (yValues[integerRank + 1] - yValues[integerRank]) + yValues[integerRank];\n return value;\n };\n /**\n * To find the quartile values\n * @param yValues\n * @param count\n * @param lowerQuartile\n * @param upperQuartile\n */\n BoxAndWhiskerSeries.prototype.getQuartileValues = function (yValues, count, quartile) {\n if (count === 1) {\n quartile.lowerQuartile = yValues[0];\n quartile.upperQuartile = yValues[0];\n return null;\n }\n var isEvenList = count % 2 === 0;\n var halfLength = count / 2;\n var lowerQuartileArray = yValues.slice(0, halfLength);\n var upperQuartileArray = yValues.slice(isEvenList ? halfLength : halfLength + 1, count);\n quartile.lowerQuartile = getMedian(lowerQuartileArray);\n quartile.upperQuartile = getMedian(upperQuartileArray);\n };\n /**\n * To find the min, max and outlier values\n * @param yValues\n * @param lowerQuartile\n * @param upperQuartile\n * @param minimum\n * @param maximum\n * @param outliers\n */\n BoxAndWhiskerSeries.prototype.getMinMaxOutlier = function (yValues, count, quartile) {\n var interquartile = quartile.upperQuartile - quartile.lowerQuartile;\n var rangeIQR = 1.5 * interquartile;\n for (var i = 0; i < count; i++) {\n if (yValues[i] < quartile.lowerQuartile - rangeIQR) {\n quartile.outliers.push(yValues[i]);\n }\n else {\n quartile.minimum = yValues[i];\n break;\n }\n }\n for (var i = count - 1; i >= 0; i--) {\n if (yValues[i] > quartile.upperQuartile + rangeIQR) {\n quartile.outliers.push(yValues[i]);\n }\n else {\n quartile.maximum = yValues[i];\n break;\n }\n }\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n BoxAndWhiskerSeries.prototype.doAnimation = function (series) {\n this.animate(series);\n };\n /**\n * Get module name.\n */\n BoxAndWhiskerSeries.prototype.getModuleName = function () {\n return 'BoxAndWhiskerSeries';\n /**\n * return the module name\n */\n };\n /**\n * To destroy the candle series.\n * @return {void}\n * @private\n */\n BoxAndWhiskerSeries.prototype.destroy = function (chart) {\n /**\n * Destroys the candle series.\n */\n };\n return BoxAndWhiskerSeries;\n}(ColumnBase));\nexport { BoxAndWhiskerSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { getPoint, withInRange, ChartLocation, PathOption } from '../../common/utils/helper';\nimport { MultiColoredSeries } from './multi-colored-base';\n/**\n * `MultiColoredAreaSeries` module used to render the area series with multi color.\n */\nvar MultiColoredAreaSeries = /** @class */ (function (_super) {\n __extends(MultiColoredAreaSeries, _super);\n function MultiColoredAreaSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Area series.\n * @return {void}\n * @private\n */\n MultiColoredAreaSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var _this = this;\n var firstPoint;\n var startPoint = null;\n var direction = '';\n var origin = Math.max(series.yAxis.visibleRange.min, 0);\n var options = [];\n var startRegion;\n var previous;\n var color;\n var rendered;\n var segments = this.sortSegments(series, series.segments);\n series.points.map(function (point, i, seriesPoints) {\n point.symbolLocations = [];\n point.regions = [];\n rendered = false;\n if (point.visible && withInRange(seriesPoints[i - 1], point, seriesPoints[i + 1], series)) {\n direction += _this.getAreaPathDirection(point.xValue, origin, series, isInverted, getPoint, startPoint, 'M');\n startPoint = startPoint || new ChartLocation(point.xValue, origin);\n firstPoint = getPoint(point.xValue, point.yValue, xAxis, yAxis, isInverted, series);\n if (previous && _this.setPointColor(point, previous, series, series.segmentAxis === 'X', segments)) {\n rendered = true;\n startRegion = getPoint(startPoint.x, origin, xAxis, yAxis, isInverted, series);\n direction += ('L' + ' ' + (firstPoint.x) + ' ' + (firstPoint.y) + ' ');\n direction += ('L' + ' ' + (firstPoint.x) + ' ' + (startRegion.y) + ' ');\n _this.generatePathOption(options, series, previous, direction, '_Point_' + previous.index);\n direction = 'M' + ' ' + (firstPoint.x) + ' ' + (startRegion.y) + ' ' + 'L' + ' ' +\n (firstPoint.x) + ' ' + (firstPoint.y) + ' ';\n }\n else {\n direction += ('L' + ' ' + (firstPoint.x) + ' ' + (firstPoint.y) + ' ');\n _this.setPointColor(point, null, series, series.segmentAxis === 'X', segments);\n }\n if (seriesPoints[i + 1] && !seriesPoints[i + 1].visible && series.emptyPointSettings.mode !== 'Drop') {\n direction += _this.getAreaEmptyDirection({ 'x': point.xValue, 'y': origin }, startPoint, series, isInverted, getPoint);\n startPoint = null;\n }\n previous = point;\n _this.storePointLocation(point, series, isInverted, getPoint);\n }\n });\n if (!rendered) {\n direction = series.points.length > 1 ?\n (direction + this.getAreaPathDirection(previous.xValue, origin, series, isInverted, getPoint, null, 'L')) : '';\n this.generatePathOption(options, series, previous, direction, '');\n }\n this.applySegmentAxis(series, options, segments);\n this.renderMarker(series);\n };\n /**\n * To Store the path directions of the area\n */\n MultiColoredAreaSeries.prototype.generatePathOption = function (options, series, point, direction, id) {\n options.push(new PathOption(series.chart.element.id + '_Series_' + series.index + id, series.setPointColor(point, series.interior), series.border.width, series.border.color, series.opacity, series.dashArray, direction));\n };\n /**\n * To destroy the area series.\n * @return {void}\n * @private\n */\n MultiColoredAreaSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n /**\n * Get module name\n */\n MultiColoredAreaSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'MultiColoredAreaSeries';\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n MultiColoredAreaSeries.prototype.doAnimation = function (series) {\n this.doLinearAnimation(series, series.animation);\n };\n return MultiColoredAreaSeries;\n}(MultiColoredSeries));\nexport { MultiColoredAreaSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { withInRange, getPoint, PathOption } from '../../common/utils/helper';\nimport { MultiColoredSeries } from './multi-colored-base';\n/**\n * `MultiColoredLineSeries` used to render the line series with multi color.\n */\nvar MultiColoredLineSeries = /** @class */ (function (_super) {\n __extends(MultiColoredLineSeries, _super);\n function MultiColoredLineSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Render Line Series.\n * @return {void}.\n * @private\n */\n MultiColoredLineSeries.prototype.render = function (series, xAxis, yAxis, isInverted) {\n var previous = null;\n var startPoint = 'M';\n var visiblePoints = this.improveChartPerformance(series);\n var options = [];\n var direction = '';\n var segments = this.sortSegments(series, series.segments);\n for (var _i = 0, visiblePoints_1 = visiblePoints; _i < visiblePoints_1.length; _i++) {\n var point = visiblePoints_1[_i];\n point.regions = [];\n if (point.visible && withInRange(visiblePoints[point.index - 1], point, visiblePoints[point.index + 1], series)) {\n direction += this.getLineDirection(previous, point, series, isInverted, getPoint, startPoint);\n if (previous != null) {\n if (this.setPointColor(point, previous, series, series.segmentAxis === 'X', segments)) {\n options.push(new PathOption(series.chart.element.id + '_Series_' + series.index + '_Point_' + previous.index, 'none', series.width, series.setPointColor(previous, series.interior), series.opacity, series.dashArray, direction));\n startPoint = 'M';\n direction = '';\n }\n else {\n startPoint = 'L';\n }\n }\n else {\n this.setPointColor(point, null, series, series.segmentAxis === 'X', segments);\n }\n previous = point;\n this.storePointLocation(point, series, isInverted, getPoint);\n }\n else {\n previous = (series.emptyPointSettings.mode === 'Drop') ? previous : null;\n startPoint = (series.emptyPointSettings.mode === 'Drop') ? startPoint : 'M';\n point.symbolLocations = [];\n }\n }\n if (direction !== '') {\n options.push(new PathOption(series.chart.element.id + '_Series_' + series.index, 'none', series.width, series.setPointColor(visiblePoints[visiblePoints.length - 1], series.interior), series.opacity, series.dashArray, direction));\n }\n this.applySegmentAxis(series, options, segments);\n this.renderMarker(series);\n };\n /**\n * Animates the series.\n * @param {Series} series - Defines the series to animate.\n * @return {void}\n */\n MultiColoredLineSeries.prototype.doAnimation = function (series) {\n this.doLinearAnimation(series, series.animation);\n };\n /**\n * Get module name.\n */\n MultiColoredLineSeries.prototype.getModuleName = function () {\n /**\n * Returns the module name of the series\n */\n return 'MultiColoredLineSeries';\n };\n /**\n * To destroy the line series.\n * @return {void}\n * @private\n */\n MultiColoredLineSeries.prototype.destroy = function (chart) {\n /**\n * Destroy method performed here\n */\n };\n return MultiColoredLineSeries;\n}(MultiColoredSeries));\nexport { MultiColoredLineSeries };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { textWrap, TextOption, PathOption } from '../../common/utils/helper';\nimport { valueToCoefficient, measureText, textTrim, textElement } from '../../common/utils/helper';\nimport { axisMultiLabelRender } from '../../common/model/constants';\n/**\n * `MultiLevelLabel` module is used to render the multi level label in chart.\n */\nvar MultiLevelLabel = /** @class */ (function () {\n /**\n * Constructor for the logerithmic module.\n * @private\n */\n function MultiLevelLabel(chart) {\n /** @private */\n this.xAxisPrevHeight = [];\n /** @private */\n this.xAxisMultiLabelHeight = [];\n /** @private */\n this.yAxisPrevHeight = [];\n /** @private */\n this.yAxisMultiLabelHeight = [];\n this.chart = chart;\n }\n /**\n * Finds multilevel label height\n * @return {void}\n */\n MultiLevelLabel.prototype.getMultilevelLabelsHeight = function (axis) {\n var value = 0;\n var multiLevelLabelsHeight = [];\n var prevHeight = [];\n var isVertical = axis.orientation === 'Vertical';\n var axisValue = isVertical ? axis.rect.height : axis.rect.width;\n var labelSize;\n var height;\n var padding = 10;\n var gap;\n axis.multiLevelLabels.map(function (multiLevel, index) {\n multiLevel.categories.map(function (categoryLabel) {\n if (categoryLabel.text !== '' && categoryLabel.start !== null && categoryLabel.end !== null) {\n labelSize = measureText(categoryLabel.text, multiLevel.textStyle);\n height = isVertical ? labelSize.width : labelSize.height;\n height += 2 * multiLevel.border.width +\n (multiLevel.border.type === 'CurlyBrace' ? padding : 0);\n gap = (categoryLabel.maximumTextWidth !== null) ? categoryLabel.maximumTextWidth :\n (valueToCoefficient(typeof categoryLabel.end === 'string' ? Number(new Date(categoryLabel.end)) :\n categoryLabel.end, axis) * axisValue) -\n (valueToCoefficient(typeof categoryLabel.start === 'string' ? Number(new Date(categoryLabel.start)) :\n categoryLabel.start, axis) * axisValue);\n if ((labelSize.width > gap - padding) && gap > 0 && (multiLevel.overflow === 'Wrap') && !isVertical) {\n height = (height * (textWrap(categoryLabel.text, gap - padding, multiLevel.textStyle).length));\n }\n multiLevelLabelsHeight[index] = !multiLevelLabelsHeight[index] ? height :\n ((multiLevelLabelsHeight[index] < height) ? height : multiLevelLabelsHeight[index]);\n }\n });\n prevHeight[index] = value;\n value += multiLevelLabelsHeight[index] ? (multiLevelLabelsHeight[index] + padding) : 0;\n });\n axis.multiLevelLabelHeight = value + ((axis.title !== '' || (this.chart.legendModule && this.chart.legendSettings.visible))\n ? padding / 2 : 0);\n if (isVertical) {\n this.yAxisMultiLabelHeight = multiLevelLabelsHeight;\n this.yAxisPrevHeight = prevHeight;\n }\n else {\n this.xAxisMultiLabelHeight = multiLevelLabelsHeight;\n this.xAxisPrevHeight = prevHeight;\n }\n };\n /**\n * render x axis multi level labels\n * @private\n * @return {void}\n */\n MultiLevelLabel.prototype.renderXAxisMultiLevelLabels = function (axis, index, parent, axisRect) {\n var _this = this;\n var x;\n var y;\n var padding = 10;\n var startX;\n var startY = (axis.labelPosition === axis.tickPosition ? axis.majorTickLines.height : 0) +\n (axis.maxLabelSize.height) + padding;\n var endX;\n var endY;\n var pathRect = '';\n var start;\n var end;\n var labelSize;\n var clipY;\n var isOutside = axis.labelPosition === 'Outside';\n var gap;\n var anchor;\n var isInversed = axis.isInversed;\n var argsData;\n var labelElement;\n var opposedPosition = axis.opposedPosition;\n var scrollBarHeight = isOutside && isNullOrUndefined(axis.crossesAt) ? axis.scrollBarHeight : 0;\n scrollBarHeight = scrollBarHeight * (opposedPosition ? -1 : 1);\n clipY = ((opposedPosition && !isOutside) || (!opposedPosition && isOutside)) ?\n (axisRect.y + startY - axis.majorTickLines.width) : (axisRect.y - startY - axis.multiLevelLabelHeight);\n this.createClipRect(axisRect.x - axis.majorTickLines.width, clipY + scrollBarHeight, axis.multiLevelLabelHeight + padding, axisRect.width + 2 * axis.majorTickLines.width, this.chart.element.id + '_XAxis_Clippath_' + index, this.chart.element.id + 'XAxisMultiLevelLabel' + index);\n axis.multiLevelLabels.map(function (multiLevel, level) {\n pathRect = '';\n multiLevel.categories.map(function (categoryLabel, i) {\n labelElement = _this.chart.renderer.createGroup({ id: _this.chart.element.id + index + '_MultiLevelLabel' + level });\n start = typeof categoryLabel.start === 'string' ? Number(new Date(categoryLabel.start)) : categoryLabel.start;\n end = typeof categoryLabel.end === 'string' ? Number(new Date(categoryLabel.end)) : categoryLabel.end;\n if (((start >= axis.visibleRange.min && start <= axis.visibleRange.max)\n || (end >= axis.visibleRange.min && end <= axis.visibleRange.max))) {\n argsData = _this.triggerMultiLabelRender(axis, categoryLabel.text, axis.multiLevelLabels[level].textStyle, axis.multiLevelLabels[level].alignment);\n if (!argsData.cancel) {\n startX = valueToCoefficient(start, axis) * axisRect.width;\n endX = valueToCoefficient(end, axis) * axisRect.width;\n endX = isInversed ? [startX, startX = endX][0] : endX;\n labelSize = measureText(argsData.text, argsData.textStyle);\n gap = ((categoryLabel.maximumTextWidth === null) ? endX - startX : categoryLabel.maximumTextWidth) - padding;\n x = startX + axisRect.x + padding;\n y = (((opposedPosition && !isOutside) || (!opposedPosition && isOutside)) ? (startY + axisRect.y +\n labelSize.height / 2 + padding + _this.xAxisPrevHeight[level]) : (axisRect.y - startY + labelSize.height / 2 -\n _this.xAxisMultiLabelHeight[level] - _this.xAxisPrevHeight[level])) + scrollBarHeight;\n if (argsData.alignment === 'Center') {\n x += (endX - startX - padding) / 2;\n anchor = 'middle';\n }\n else if (argsData.alignment === 'Far') {\n x = x + (endX - startX - padding) - multiLevel.border.width / 2;\n anchor = 'end';\n }\n else {\n anchor = 'start';\n x += multiLevel.border.width / 2;\n }\n y = multiLevel.border.type === 'CurlyBrace' ?\n (((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) ? y + padding : y - padding / 2) : y;\n var options = new TextOption(_this.chart.element.id + index + '_Axis_MultiLevelLabel_Level_' + level + '_Text_' + i, x, y, anchor, argsData.text);\n if (multiLevel.overflow !== 'None') {\n options.text = (multiLevel.overflow === 'Wrap') ?\n textWrap(argsData.text, gap, argsData.textStyle) : textTrim(gap, argsData.text, argsData.textStyle);\n options.x = options.x - padding / 2;\n }\n textElement(options, argsData.textStyle, argsData.textStyle.color || _this.chart.themeStyle.axisLabel, labelElement);\n if (multiLevel.border.width > 0 && multiLevel.border.type !== 'WithoutBorder') {\n pathRect = _this.renderXAxisLabelBorder(level, endX - startX - padding, axis, startX, startY, labelSize, options, axisRect, argsData.alignment, pathRect, isOutside, opposedPosition);\n }\n _this.multiElements.appendChild(labelElement);\n }\n }\n });\n if (pathRect !== '') {\n _this.createBorderElement(level, index, axis, pathRect);\n }\n });\n parent.appendChild(this.multiElements);\n };\n /**\n * render x axis multi level labels border\n * @private\n * @return {void}\n */\n MultiLevelLabel.prototype.renderXAxisLabelBorder = function (labelIndex, gap, axis, startX, startY, labelSize, textOptions, axisRect, alignment, path, isOutside, opposedPosition) {\n var padding = 10;\n var padding1;\n var padding2;\n var value;\n var value1;\n var groupLabel = axis.multiLevelLabels[labelIndex];\n var width = gap + padding;\n var height = this.xAxisMultiLabelHeight[labelIndex] + padding;\n var scrollBarHeight = axis.labelPosition === 'Outside' ? axis.scrollBarHeight : 0;\n var x = startX + axisRect.x;\n var y = ((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) ? (startY + axisRect.y +\n this.xAxisPrevHeight[labelIndex] + scrollBarHeight) : (axisRect.y - startY -\n this.xAxisPrevHeight[labelIndex] - scrollBarHeight);\n switch (groupLabel.border.type) {\n case 'WithoutTopandBottomBorder':\n case 'Rectangle':\n case 'WithoutTopBorder':\n height = ((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) ? height : -height;\n path += 'M' + x + ' ' + y + 'L' + x + ' ' + (y + height) +\n 'M' + (x + width) + ' ' + y + 'L' + (x + width) + ' ' + (y + height);\n path += (groupLabel.border.type !== 'WithoutTopandBottomBorder') ? ('L' + ' ' + (x) + ' ' + (y + height) + ' ') : ' ';\n path += groupLabel.border.type === 'Rectangle' ? ('M' + x + ' ' + y + 'L' + (x + width) + ' ' + y) : ' ';\n break;\n case 'Brace':\n if (alignment === 'Near') {\n value = textOptions.x;\n value1 = textOptions.x + labelSize.width + 2;\n }\n else if (alignment === 'Center') {\n value = textOptions.x - labelSize.width / 2 - 2;\n value1 = textOptions.x + labelSize.width / 2 + 2;\n }\n else {\n value = textOptions.x - labelSize.width - 2;\n value1 = textOptions.x;\n }\n height = ((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) ? height : -height;\n path += 'M' + x + ' ' + y + 'L' + x + ' ' + (y + height / 2) +\n 'M' + x + ' ' + (y + height / 2) + 'L' + (value - 2) + ' ' + (y + height / 2) +\n 'M' + (value1) + ' ' + (y + height / 2) + 'L' + (x + width) + ' ' + (y + height / 2) +\n 'M' + (x + width) + ' ' + (y + height / 2) + 'L' + (x + width) + ' ' + (y);\n break;\n case 'CurlyBrace':\n if ((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) {\n padding = 10;\n padding1 = 15;\n padding2 = 5;\n }\n else {\n padding = -10;\n padding1 = -15;\n padding2 = -5;\n }\n if (alignment === 'Center') {\n path += 'M' + x + ' ' + y + ' C ' + x + ' ' + y + ' ' + (x + 5) + ' ' + (y + padding) + ' ' + (x + 10) + ' ' +\n (y + padding) + 'L' + (x + width / 2 - 5) + ' ' + (y + padding) + 'L' + (x + width / 2) + ' ' + (y + padding1) +\n 'L' + (x + width / 2 + 5) + ' ' + (y + padding) + 'L' + (x + width - 10) + ' ' + (y + padding) + ' C ' +\n (x + width - 10) + ' ' + (y + padding) + ' ' + (x + width) + ' ' + (y + padding2) + ' ' + (x + width) + ' ' + (y);\n }\n else if (alignment === 'Near') {\n path += 'M' + x + ' ' + y + ' C ' + x + ' ' + y + ' ' + (x + 5) + ' ' + (y + padding) + ' ' + (x + 10) + ' ' +\n (y + padding) + 'L' + (x + 15) + ' ' + (y + padding1) + 'L' + (x + 20) + ' ' + (y + padding) + 'L' +\n (x + width - 10) + ' ' + (y + padding) + ' C ' + (x + width - 10) + ' ' + (y + padding) + ' ' + (x + width) + ' '\n + (y + padding2) + ' ' + (x + width) + ' ' + (y);\n }\n else {\n path += 'M' + x + ' ' + y + ' C ' + x + ' ' + y + ' ' + (x + 5) + ' ' + (y + padding) + ' ' + (x + 10) + ' ' +\n (y + padding) + 'L' + (x + width - 20) + ' ' + (y + padding) + 'L' + (x + width - 15) + ' ' + (y + padding1) +\n 'L' + (x + width - 10) + ' ' + (y + padding) + 'L' + (x + width - 10) + ' ' + (y + padding) + ' C '\n + (x + width - 10) + ' ' + (y + padding) + ' ' + (x + width) + ' ' + (y + padding2) + ' ' + (x + width) + ' ' + (y);\n }\n break;\n }\n return path;\n };\n /**\n * render y axis multi level labels\n * @private\n * @return {void}\n */\n MultiLevelLabel.prototype.renderYAxisMultiLevelLabels = function (axis, index, parent, rect) {\n var _this = this;\n var labelSize;\n var clipX;\n var isOutside = axis.labelPosition === 'Outside';\n var x;\n var y;\n var padding = 10;\n var startX = (axis.tickPosition === axis.labelPosition ? axis.majorTickLines.height : 0) +\n (axis.maxLabelSize.width) + padding;\n var startY;\n var path = '';\n var labelElement;\n var endY;\n var argsData;\n var isInversed = axis.isInversed;\n var start;\n var end;\n var gap;\n var anchor = 'middle';\n var opposedPosition = axis.opposedPosition;\n var scrollBarHeight = isOutside && isNullOrUndefined(axis.crossesAt) ? axis.scrollBarHeight : 0;\n scrollBarHeight = scrollBarHeight * (opposedPosition ? 1 : -1);\n clipX = ((opposedPosition && !isOutside) || (!opposedPosition && isOutside)) ?\n (rect.x - axis.multiLevelLabelHeight - startX - padding) : (rect.x + startX);\n this.createClipRect(clipX + scrollBarHeight, rect.y - axis.majorTickLines.width, rect.height + 2 * axis.majorTickLines.width, axis.multiLevelLabelHeight + padding, this.chart.element.id + '_YAxis_Clippath_' + index, this.chart.element.id\n + 'YAxisMultiLevelLabel' + index);\n axis.multiLevelLabels.map(function (multiLevel, level) {\n path = '';\n multiLevel.categories.map(function (categoryLabel, i) {\n labelElement = _this.chart.renderer.createGroup({ id: _this.chart.element.id + index + '_MultiLevelLabel' + level });\n end = typeof categoryLabel.end === 'string' ? Number(new Date(categoryLabel.end)) : categoryLabel.end;\n start = typeof categoryLabel.start === 'string' ? Number(new Date(categoryLabel.start)) : categoryLabel.start;\n if (((start >= axis.visibleRange.min && start <= axis.visibleRange.max)\n || (end >= axis.visibleRange.min && end <= axis.visibleRange.max))) {\n startY = valueToCoefficient((start), axis) * (rect.height);\n endY = valueToCoefficient((end), axis) * (rect.height);\n endY = isInversed ? [startY, startY = endY][0] : endY;\n argsData = _this.triggerMultiLabelRender(axis, categoryLabel.text, multiLevel.textStyle, multiLevel.alignment);\n if (!argsData.cancel) {\n labelSize = measureText(argsData.text, argsData.textStyle);\n gap = endY - startY;\n x = rect.x - startX - _this.yAxisPrevHeight[level] -\n (_this.yAxisMultiLabelHeight[level] / 2) - padding / 2;\n y = rect.height + rect.y - startY - (gap / 2);\n if (opposedPosition) {\n x = isOutside ? rect.x + startX + padding / 2 + (_this.yAxisMultiLabelHeight[level] / 2) +\n _this.yAxisPrevHeight[level] + scrollBarHeight : rect.x - startX - (_this.yAxisMultiLabelHeight[level] / 2) -\n _this.yAxisPrevHeight[level] - padding / 2;\n }\n else {\n x = isOutside ? x + scrollBarHeight : rect.x + startX + padding / 2 + (_this.yAxisMultiLabelHeight[level] / 2) +\n _this.yAxisPrevHeight[level];\n }\n if (argsData.alignment === 'Center') {\n y += labelSize.height / 4;\n }\n else if (argsData.alignment === 'Far') {\n y += gap / 2 - labelSize.height / 2;\n }\n else {\n y = y - gap / 2 + labelSize.height;\n }\n x = multiLevel.border.type === 'CurlyBrace' ? (((!opposedPosition && isOutside) ||\n (opposedPosition && !isOutside)) ? x - padding : x + padding) : x;\n var options = new TextOption(_this.chart.element.id + index + '_Axis_MultiLevelLabel_Level_' + level + '_Text_' + i, x, y, anchor, argsData.text);\n options.text = (multiLevel.overflow === 'Trim') ?\n textTrim((categoryLabel.maximumTextWidth === null ? _this.yAxisMultiLabelHeight[level] :\n categoryLabel.maximumTextWidth), argsData.text, argsData.textStyle) : options.text;\n textElement(options, argsData.textStyle, argsData.textStyle.color || _this.chart.themeStyle.axisLabel, labelElement);\n if (multiLevel.border.width > 0 && multiLevel.border.type !== 'WithoutBorder') {\n path = _this.renderYAxisLabelBorder(level, gap, axis, endY, startX, startY, labelSize, options, rect, argsData.alignment, path, isOutside, opposedPosition);\n }\n _this.multiElements.appendChild(labelElement);\n }\n }\n });\n if (path !== '') {\n _this.createBorderElement(level, index, axis, path);\n }\n });\n parent.appendChild(this.multiElements);\n };\n /**\n * render y axis multi level labels border\n * @private\n * @return {void}\n */\n MultiLevelLabel.prototype.renderYAxisLabelBorder = function (labelIndex, gap, axis, endY, startX, startY, labelSize, textOptions, rect, alignment, path, isOutside, opposedPosition) {\n var height = endY - startY;\n var padding = 10;\n var padding1;\n var padding2;\n var groupLabel = axis.multiLevelLabels[labelIndex];\n var y = rect.y + rect.height - endY;\n var scrollBarHeight = isOutside && isNullOrUndefined(axis.crossesAt) ? axis.scrollBarHeight : 0;\n scrollBarHeight = scrollBarHeight * (opposedPosition ? 1 : -1);\n var width = this.yAxisMultiLabelHeight[labelIndex] + padding;\n var x = (((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) ? rect.x - startX -\n this.yAxisPrevHeight[labelIndex] : rect.x + startX + this.yAxisPrevHeight[labelIndex]) + scrollBarHeight;\n switch (groupLabel.border.type) {\n case 'WithoutTopandBottomBorder':\n case 'Rectangle':\n case 'WithoutTopBorder':\n width = ((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) ? -width : width;\n path += 'M' + x + ' ' + y + 'L' + (x + width) + ' ' + y +\n 'M' + x + ' ' + (y + height) + 'L' + (x + width) + ' ' + (y + height);\n path += (groupLabel.border.type !== 'WithoutTopandBottomBorder') ? ('L' + ' ' + (x + width) + ' ' + y + ' ') : ' ';\n path += (groupLabel.border.type === 'Rectangle') ? ('M' + (x) + ' ' + (y + height) + 'L' + ' ' + (x) + ' ' + y + ' ') : ' ';\n break;\n case 'Brace':\n width = ((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) ? width : -width;\n path += 'M ' + (x) + ' ' + y + ' L ' + (x - width / 2) + ' ' + y + ' L ' + (x - width / 2) + ' ' +\n (textOptions.y - labelSize.height / 2 - 4) + ' M ' + (x - width / 2) + ' ' +\n (textOptions.y + labelSize.height / 4 + 2) +\n ' L ' + (x - width / 2) + ' ' + (y + height) + ' L ' + (x) + ' ' + (y + height);\n break;\n case 'CurlyBrace':\n if ((!opposedPosition && isOutside) || (opposedPosition && !isOutside)) {\n padding = -10;\n padding1 = -15;\n padding2 = -5;\n }\n else {\n padding = 10;\n padding1 = 15;\n padding2 = 5;\n }\n if (alignment === 'Center') {\n path += 'M ' + x + ' ' + y + ' C ' + x + ' ' + y + ' ' + (x + padding) + ' ' + y + ' ' + (x + padding) + ' ' + (y + 10)\n + ' L ' + (x + padding) + ' ' + (y + (height - 10) / 2) + ' L ' + (x + padding1) + ' ' + (y + (height - 10) / 2 + 5)\n + ' L ' + (x + padding) + ' ' + (y + (height - 10) / 2 + 10) + ' L ' + (x + padding) + ' ' + (y + (height - 10)) +\n ' C ' + (x + padding) + ' ' + (y + (height - 10)) + ' ' + (x + padding2) + ' ' + (y + height) + ' '\n + x + ' ' + (y + height);\n }\n else if (alignment === 'Far') {\n path += 'M ' + x + ' ' + y + ' C ' + x + ' ' + y + ' ' + (x + padding) + ' ' + y + ' ' + (x + padding) + ' ' + (y + 10)\n + ' L ' + (x + padding) + ' ' + (y + height - 20) + ' ' + ' L ' + (x + padding1) + ' ' + (y + (height - 15)) +\n ' L ' + (x + padding) + ' ' + (y + (height - 10)) + ' L ' + (x + padding) + ' ' + (y + (height - 10)) +\n ' C' + (x + padding) + ' ' + (y + (height - 10)) + ' ' + (x + padding) + ' ' + (y + height) + ' ' + x + ' '\n + (y + height);\n }\n else {\n path += 'M ' + x + ' ' + y + ' C ' + x + ' ' + y + ' ' + (x + padding) + ' ' + y + ' ' + (x + padding) + ' ' + (y + 10)\n + ' L ' + (x + padding1) + ' ' + (y + 15) +\n ' L ' + (x + padding) + ' ' + (y + 20) + ' L ' + (x + padding) + ' ' + (y + (height - 10)) +\n ' C' + (x + padding) + ' ' + (y + (height - 10)) + ' ' + (x + padding2) + ' ' + (y + height) + ' ' + x +\n ' ' + (y + height);\n }\n break;\n }\n return path;\n };\n /**\n * create cliprect\n * @return {void}\n * @private\n */\n MultiLevelLabel.prototype.createClipRect = function (x, y, height, width, clipId, axisId) {\n this.multiElements = this.chart.renderer.createGroup({\n 'id': axisId,\n 'clip-path': 'url(#' + clipId + ')'\n });\n this.multiElements.appendChild(this.chart.renderer.drawClipPath({\n 'id': clipId,\n 'x': x,\n 'y': y,\n 'width': width,\n 'height': height,\n 'fill': 'white',\n 'stroke-width': 1, 'stroke': 'Gray'\n }));\n };\n /**\n * create borer element\n * @return {void}\n * @private\n */\n MultiLevelLabel.prototype.createBorderElement = function (borderIndex, axisIndex, axis, path) {\n var borderElement = this.chart.renderer.drawPath(new PathOption(this.chart.element.id + axisIndex + '_Axis_MultiLevelLabel_Rect_' + borderIndex, 'Transparent', axis.multiLevelLabels[borderIndex].border.width, axis.multiLevelLabels[borderIndex].border.color || this.chart.themeStyle.axisLine, 1, '', path));\n borderElement.setAttribute('style', 'pointer-events: none');\n this.multiElements.appendChild(borderElement);\n };\n /**\n * Triggers the event.\n * @return {void}\n * @private\n */\n MultiLevelLabel.prototype.triggerMultiLabelRender = function (axis, text, textStyle, textAlignment) {\n var argsData;\n argsData = {\n cancel: false, name: axisMultiLabelRender, axis: axis,\n text: text, textStyle: textStyle, alignment: textAlignment\n };\n this.chart.trigger(axisMultiLabelRender, argsData);\n return argsData;\n };\n /**\n * To get the module name for `MultiLevelLabel`.\n * @private\n */\n MultiLevelLabel.prototype.getModuleName = function () {\n return 'MultiLevelLabel';\n };\n /**\n * To destroy the `MultiLevelLabel` module.\n * @private\n */\n MultiLevelLabel.prototype.destroy = function () {\n // destroy peform here\n };\n return MultiLevelLabel;\n}());\nexport { MultiLevelLabel };\n","import { Rect, PathOption, RectOption, CircleOption } from '../utils/helper';\n/**\n * Create scrollbar svg.\n * @return {void}\n */\nexport function createScrollSvg(scrollbar, renderer) {\n var rect = scrollbar.axis.rect;\n var isHorizontalAxis = scrollbar.axis.orientation === 'Horizontal';\n scrollbar.svgObject = renderer.createSvg({\n id: 'scrollBar_svg' + scrollbar.axis.name,\n width: scrollbar.isVertical ? scrollbar.height : scrollbar.width,\n height: scrollbar.isVertical ? scrollbar.width : scrollbar.height,\n style: 'position: absolute;top: ' + ((scrollbar.axis.opposedPosition && isHorizontalAxis ? -16 : 0) + rect.y) + 'px;left: ' +\n (((scrollbar.axis.opposedPosition && !isHorizontalAxis ? 16 : 0) + rect.x) - (scrollbar.isVertical ? scrollbar.height : 0))\n + 'px;cursor:auto;'\n });\n scrollbar.elements.push(scrollbar.svgObject);\n}\n/**\n * Scrollbar elements renderer\n */\nvar ScrollElements = /** @class */ (function () {\n /**\n * Constructor for scroll elements\n * @param scrollObj\n */\n function ScrollElements() {\n // Constructor Called here\n }\n /**\n * Render scrollbar elements.\n * @return {void}\n * @private\n */\n ScrollElements.prototype.renderElements = function (scroll, renderer) {\n var scrollGroup = renderer.createGroup({\n id: 'scrollBar_' + scroll.axis.name,\n transform: 'translate(' + (scroll.isVertical ? scroll.height : '0') +\n ',0) rotate(' + (scroll.isVertical ? '90' : '0') + ')'\n });\n var backRectGroup = renderer.createGroup({\n id: 'scrollBar_backRect_' + scroll.axis.name\n });\n var thumbGroup = renderer.createGroup({\n id: 'scrollBar_thumb_' + scroll.axis.name,\n transform: 'translate(0,0)'\n });\n this.backRect(scroll, renderer, backRectGroup);\n this.thumb(scroll, renderer, thumbGroup);\n this.renderCircle(scroll, renderer, thumbGroup);\n this.arrows(scroll, renderer, thumbGroup);\n this.thumbGrip(scroll, renderer, thumbGroup);\n scrollGroup.appendChild(backRectGroup);\n scrollGroup.appendChild(thumbGroup);\n return scrollGroup;\n };\n /**\n * Method to render back rectangle of scrollbar\n * @param scroll\n */\n ScrollElements.prototype.backRect = function (scroll, renderer, parent) {\n var style = scroll.scrollbarThemeStyle;\n var backRectEle = renderer.drawRectangle(new RectOption('scrollBarBackRect_' + scroll.axis.name, style.backRect, { width: 1, color: style.backRect }, 1, new Rect(0, 0, scroll.width, scroll.height), 0, 0));\n parent.appendChild(backRectEle);\n };\n /**\n * Method to render arrows\n * @param scroll\n */\n ScrollElements.prototype.arrows = function (scroll, renderer, parent) {\n var style = scroll.scrollbarThemeStyle;\n var option = new PathOption('scrollBar_leftArrow_' + scroll.axis.name, style.arrow, 1, style.arrow, 1, '', '');\n this.leftArrowEle = renderer.drawPath(option);\n option.id = 'scrollBar_rightArrow_' + scroll.axis.name;\n this.rightArrowEle = renderer.drawPath(option);\n this.setArrowDirection(this.thumbRectX, this.thumbRectWidth, scroll.height);\n parent.appendChild(this.leftArrowEle);\n parent.appendChild(this.rightArrowEle);\n };\n /**\n * Methods to set the arrow width\n * @param thumbRectX\n * @param thumbRectWidth\n * @param height\n */\n ScrollElements.prototype.setArrowDirection = function (thumbRectX, thumbRectWidth, height) {\n var circleRadius = 8;\n var leftDirection = 'M ' + ((thumbRectX - circleRadius / 2) + 1) + ' ' + (height / 2) + ' ' + 'L ' +\n (thumbRectX - circleRadius / 2 + 6) + ' ' + 11 + ' ' + 'L ' + (thumbRectX - circleRadius / 2 + 6) + ' ' + 5 + ' Z';\n var rightDirection = 'M ' + ((thumbRectX + thumbRectWidth + circleRadius / 2) - 0.5) + ' ' + (height / 2)\n + ' ' + 'L ' + (thumbRectX + thumbRectWidth + circleRadius / 2 - 6) + ' ' + 11.5 + ' ' + 'L ' + (thumbRectX +\n thumbRectWidth + circleRadius / 2 - 6) + ' ' + 4.5 + ' Z';\n this.leftArrowEle.setAttribute('d', leftDirection);\n this.rightArrowEle.setAttribute('d', rightDirection);\n };\n /**\n * Method to render thumb\n * @param scroll\n * @param renderer\n * @param parent\n */\n ScrollElements.prototype.thumb = function (scroll, renderer, parent) {\n scroll.startX = this.thumbRectX;\n var style = scroll.scrollbarThemeStyle;\n this.slider = renderer.drawRectangle(new RectOption('scrollBarThumb_' + scroll.axis.name, style.thumb, { width: 1, color: '' }, 1, new Rect(this.thumbRectX, 0, this.thumbRectWidth, scroll.height)));\n parent.appendChild(this.slider);\n };\n /**\n * Method to render circles\n * @param scroll\n * @param renderer\n * @param parent\n */\n ScrollElements.prototype.renderCircle = function (scroll, renderer, parent) {\n var style = scroll.scrollbarThemeStyle;\n var option = new CircleOption('scrollBar_leftCircle_' + scroll.axis.name, style.circle, { width: 1, color: style.circle }, 1, this.thumbRectX, scroll.height / 2, 8);\n var scrollShadowEle = ' ' +\n ' ' +\n ' ' +\n '' +\n ' ';\n var defElement = renderer.createDefs();\n defElement.innerHTML = scrollShadowEle;\n var shadowGroup = renderer.createGroup({\n id: scroll.axis.name + '_thumb_shadow'\n });\n shadowGroup.innerHTML = ' ';\n this.leftCircleEle = renderer.drawCircle(option);\n option.id = 'scrollBar_rightCircle_' + scroll.axis.name;\n option.cx = this.thumbRectX + this.thumbRectWidth;\n this.rightCircleEle = renderer.drawCircle(option);\n parent.appendChild(defElement);\n parent.appendChild(this.leftCircleEle);\n parent.appendChild(this.rightCircleEle);\n parent.appendChild(shadowGroup);\n };\n /**\n * Method to render grip elements\n * @param scroll\n * @param renderer\n * @param parent\n */\n ScrollElements.prototype.thumbGrip = function (scroll, renderer, parent) {\n var sidePadding = 0;\n var topPadding = 0;\n var gripWidth = 14;\n var gripCircleDiameter = 2;\n var padding = gripWidth / 2 - gripCircleDiameter;\n var style = scroll.scrollbarThemeStyle;\n var option = new CircleOption('scrollBar_gripCircle0' + '_' + scroll.axis.name, style.grip, { width: 1, color: style.grip }, 1, 0, 0, 1);\n this.gripCircle = renderer.createGroup({\n id: 'scrollBar_gripCircle_' + scroll.axis.name,\n transform: 'translate(' + ((this.thumbRectX + this.thumbRectWidth / 2) + ((scroll.isVertical ? 1 : -1) * padding)) +\n ',' + (scroll.isVertical ? '10' : '5') + ') rotate(' + (scroll.isVertical ? '180' : '0') + ')'\n });\n for (var i = 1; i <= 6; i++) {\n option.id = 'scrollBar_gripCircle' + i + '_' + scroll.axis.name;\n option.cx = sidePadding;\n option.cy = topPadding;\n this.gripCircle.appendChild(renderer.drawCircle(option));\n sidePadding = i === 3 ? 0 : (sidePadding + 5);\n topPadding = i >= 3 ? 5 : 0;\n }\n parent.appendChild(this.gripCircle);\n };\n return ScrollElements;\n}());\nexport { ScrollElements };\n","import { EventHandler, Browser, remove } from '@syncfusion/ej2-base';\nimport { Animation, createElement } from '@syncfusion/ej2-base';\nimport { ScrollElements, createScrollSvg } from './scrollbar-elements';\nimport { getElement, minMax } from '../utils/helper';\nimport { linear } from '../../chart/index';\nimport { getScrollbarThemeColor } from '../model/theme';\n/**\n * Scrollbar Base\n */\nvar ScrollBar = /** @class */ (function () {\n /**\n * Constructor for creating scrollbar\n * @param component\n * @param axis\n */\n function ScrollBar(component, axis) {\n this.component = component;\n this.elements = [];\n this.scrollElements = new ScrollElements();\n this.axis = axis;\n this.mouseMoveListener = this.scrollMouseMove.bind(this);\n this.mouseUpListener = this.scrollMouseUp.bind(this);\n this.animateDuration = 500;\n this.isPointer = Browser.isPointer;\n this.browserName = Browser.info.name;\n }\n /**\n * To Mouse x and y position\n * @param e\n */\n ScrollBar.prototype.getMouseXY = function (e) {\n var pageX;\n var pageY;\n var touchArg;\n if (e.type.indexOf('touch') > -1) {\n touchArg = e;\n pageX = touchArg.changedTouches[0].clientX;\n pageY = touchArg.changedTouches[0].clientY;\n }\n else {\n pageX = e.clientX;\n pageY = e.clientY;\n }\n var svgRect = getElement('scrollBar_svg' + this.axis.name).getBoundingClientRect();\n this.mouseX = pageX - Math.max(svgRect.left, 0);\n this.mouseY = pageY - Math.max(svgRect.top, 0);\n };\n /**\n * Method to bind events for scrollbar svg object\n * @param element\n */\n ScrollBar.prototype.wireEvents = function (element) {\n EventHandler.add(element, Browser.touchStartEvent, this.scrollMouseDown, this);\n EventHandler.add(element, Browser.touchMoveEvent, this.scrollMouseMove, this);\n EventHandler.add(element, Browser.touchEndEvent, this.scrollMouseUp, this);\n EventHandler.add(element, 'mousewheel', this.scrollMouseWheel, this);\n window.addEventListener('mousemove', this.mouseMoveListener, false);\n window.addEventListener('mouseup', this.mouseUpListener, false);\n };\n /**\n * Method to remove events for srcollbar svg object\n * @param element\n */\n ScrollBar.prototype.unWireEvents = function (element) {\n EventHandler.remove(element, Browser.touchStartEvent, this.scrollMouseDown);\n EventHandler.remove(element, Browser.touchMoveEvent, this.scrollMouseMove);\n EventHandler.remove(element, Browser.touchEndEvent, this.scrollMouseUp);\n EventHandler.remove(element, 'mousewheel', this.scrollMouseWheel);\n window.removeEventListener('mousemove', this.mouseMoveListener, false);\n window.removeEventListener('mouseup', this.mouseUpListener, false);\n };\n /**\n * Handles the mouse down on scrollbar\n * @param e\n */\n ScrollBar.prototype.scrollMouseDown = function (e) {\n var id = e.target.id;\n var elem = this.scrollElements;\n this.getMouseXY(e);\n this.isResizeLeft = this.isExist(id, '_leftCircle_') || this.isExist(id, '_leftArrow_');\n this.isResizeRight = this.isExist(id, '_rightCircle_') || this.isExist(id, '_rightArrow_');\n this.previousXY = this.isVertical ? this.mouseY : this.mouseX;\n this.previousWidth = elem.thumbRectWidth;\n this.previousRectX = elem.thumbRectX;\n if (this.isExist(id, 'scrollBarThumb_')) {\n this.isThumbDrag = true;\n this.svgObject.style.cursor = '-webkit-grabbing';\n }\n else if (this.isExist(id, 'scrollBarBackRect_')) {\n var currentX = this.moveLength(this.previousXY, this.previousRectX, 8);\n if (this.animateDuration) {\n currentX = this.isWithIn(currentX) ? currentX : elem.thumbRectX;\n this.performAnimation(elem.thumbRectX, currentX);\n }\n else {\n elem.thumbRectX = this.isWithIn(currentX) ? currentX : elem.thumbRectX;\n this.positionThumb(elem.thumbRectX, elem.thumbRectWidth);\n this.setZoomFactorPosition(elem.thumbRectX, elem.thumbRectWidth);\n }\n }\n };\n /**\n * To check the matched string\n * @param id\n * @param match\n */\n ScrollBar.prototype.isExist = function (id, match) {\n return id.indexOf(match) > -1;\n };\n /**\n * To check current poisition is within scrollbar region\n * @param currentX\n */\n ScrollBar.prototype.isWithIn = function (currentX) {\n var circleRadius = 8;\n return (currentX - circleRadius >= 0 &&\n currentX + this.scrollElements.thumbRectWidth + circleRadius <= this.width);\n };\n /**\n * Method to find move length of thumb\n * @param mouseXY\n * @param thumbX\n * @param circleRadius\n */\n ScrollBar.prototype.moveLength = function (mouseXY, thumbX, circleRadius) {\n var moveLength = (10 / 100) * (this.width - circleRadius * 2);\n if (mouseXY < thumbX) {\n moveLength = thumbX - (thumbX - moveLength > circleRadius ? moveLength : circleRadius);\n }\n else {\n moveLength = thumbX + (thumbX + this.scrollElements.thumbRectWidth + moveLength < this.width - circleRadius ?\n moveLength : circleRadius);\n }\n return moveLength;\n };\n /**\n * Method to calculate zoom factor and position\n * @param currentX\n * @param currentWidth\n */\n ScrollBar.prototype.setZoomFactorPosition = function (currentX, currentWidth) {\n var axis = this.axis;\n this.isScrollUI = true;\n var circleRadius = 8;\n var circleWidth = 1;\n var currentScrollWidth = currentX + currentWidth + circleRadius + circleWidth;\n var currentZPWidth = circleRadius + (circleWidth / 2);\n this.zoomPosition = (currentX - (currentX - currentZPWidth <= 0 ? currentZPWidth : 0)) / (this.isVertical\n ? axis.rect.height : this.width);\n this.zoomFactor = (currentWidth + (currentScrollWidth === this.width ? circleRadius + circleWidth : 0)) / (this.isVertical\n ? axis.rect.height : this.width);\n axis.zoomPosition = this.zoomPosition;\n axis.zoomFactor = this.zoomFactor;\n };\n /**\n * Handles the mouse move on scrollbar\n * @param e\n */\n ScrollBar.prototype.scrollMouseMove = function (e) {\n var target = e.target;\n var elem = this.scrollElements;\n this.getMouseXY(e);\n this.setCursor(target);\n this.setTheme(target);\n var style = this.scrollbarThemeStyle;\n var mouseXY = this.isVertical ? this.mouseY : this.mouseX;\n if (this.isThumbDrag) {\n this.svgObject.style.cursor = '-webkit-grabbing';\n var currentX = elem.thumbRectX + (mouseXY - this.previousXY);\n if (mouseXY >= 0 && mouseXY <= currentX + elem.thumbRectWidth) {\n elem.thumbRectX = this.isWithIn(currentX) ? currentX : elem.thumbRectX;\n this.positionThumb(elem.thumbRectX, elem.thumbRectWidth);\n this.previousXY = mouseXY;\n this.setZoomFactorPosition(currentX, elem.thumbRectWidth);\n }\n }\n else if (this.isResizeLeft || this.isResizeRight) {\n this.resizeThumb(e);\n }\n };\n /**\n * Handles the mouse wheel on scrollbar\n * @param e\n */\n ScrollBar.prototype.scrollMouseWheel = function (e) {\n var svgRect = getElement('scrollBar_svg' + this.axis.name).getBoundingClientRect();\n this.mouseX = e.clientX - Math.max(svgRect.left, 0);\n this.mouseY = e.clientY - Math.max(svgRect.top, 0);\n var origin = 0.5;\n var elem = this.scrollElements;\n var axis = this.axis;\n var direction = (this.browserName === 'mozilla' && !this.isPointer) ?\n -(e.detail) / 3 > 0 ? 1 : -1 : (e.wheelDelta / 120) > 0 ? 1 : -1;\n var cumulative;\n cumulative = Math.max(Math.max(1 / minMax(axis.zoomFactor, 0, 1), 1) + (0.25 * direction), 1);\n if (cumulative >= 1) {\n origin = axis.orientation === 'Horizontal' ? this.mouseX / axis.rect.width : 1 - (this.mouseY / axis.rect.height);\n origin = origin > 1 ? 1 : origin < 0 ? 0 : origin;\n this.zoomFactor = (cumulative === 1) ? 1 : minMax(1 / cumulative, 0, 1);\n this.zoomPosition = (cumulative === 1) ? 0 : axis.zoomPosition + ((axis.zoomFactor - this.zoomFactor) * origin);\n }\n elem.thumbRectX = this.isWithIn(this.zoomPosition * this.width) ? this.zoomPosition * this.width : elem.thumbRectX;\n this.isScrollUI = true;\n this.positionThumb(elem.thumbRectX, elem.thumbRectWidth);\n axis.zoomFactor = this.zoomFactor;\n axis.zoomPosition = this.zoomPosition;\n };\n /**\n * Handles the mouse up on scrollbar\n * @param e\n */\n ScrollBar.prototype.scrollMouseUp = function (e) {\n var circleRadius = 8;\n var circleWidth = 1;\n this.startX = this.scrollElements.thumbRectX;\n var currentScrollWidth = this.startX + this.scrollElements.thumbRectWidth + circleRadius + circleWidth;\n var currentZPWidth = circleRadius + (circleWidth / 2);\n if (this.isResizeLeft || this.isResizeRight) {\n this.axis.zoomFactor = (currentScrollWidth >= this.width - 1 && (this.startX - currentZPWidth) <= 0) ? 1 : this.zoomFactor;\n }\n this.isThumbDrag = false;\n this.isResizeLeft = false;\n this.isResizeRight = false;\n };\n /**\n * To render scroll bar\n * @private\n */\n ScrollBar.prototype.render = function () {\n this.getDefaults();\n this.getTheme();\n this.removeScrollSvg();\n createScrollSvg(this, this.component.renderer);\n this.wireEvents(this.svgObject);\n this.svgObject.appendChild(this.scrollElements.renderElements(this, this.component.renderer));\n return this.svgObject;\n };\n /**\n * Theming for scrollabr\n */\n ScrollBar.prototype.getTheme = function () {\n this.scrollbarThemeStyle = getScrollbarThemeColor(this.component.theme);\n };\n /**\n * Method to remove existing scrollbar\n */\n ScrollBar.prototype.removeScrollSvg = function () {\n if (document.getElementById('scrollBar_svg' + this.axis.name)) {\n remove(document.getElementById('scrollBar_svg' + this.axis.name));\n }\n };\n /**\n * Method to set cursor fpr scrollbar\n * @param target\n */\n ScrollBar.prototype.setCursor = function (target) {\n var id = target.id;\n this.svgObject.style.cursor = id.indexOf('scrollBarThumb_') > -1 || id.indexOf('_gripCircle') > -1 ?\n '-webkit-grab' : (id.indexOf('Circle_') > -1 || id.indexOf('Arrow_') > -1) ? this.isVertical ? 'ns-resize' :\n 'ew-resize' : 'auto';\n };\n /**\n * Method to set theme for sollbar\n * @param target\n */\n ScrollBar.prototype.setTheme = function (target) {\n var id = target.id;\n var isLeftHover = id.indexOf('_leftCircle_') > -1 || id.indexOf('_leftArrow_') > -1;\n var isRightHover = id.indexOf('_rightCircle_') > -1 || id.indexOf('_rightArrow_') > -1;\n var style = this.scrollbarThemeStyle;\n var leftArrowEle = this.scrollElements.leftArrowEle;\n var rightArrowEle = this.scrollElements.rightArrowEle;\n var leftCircleEle = this.scrollElements.leftCircleEle;\n var rightCircleEle = this.scrollElements.rightCircleEle;\n var isAxis = this.isCurrentAxis(target, leftArrowEle);\n leftCircleEle.style.fill = isLeftHover && isAxis ? style.circleHover : style.circle;\n rightCircleEle.style.fill = isRightHover && isAxis ? style.circleHover : style.circle;\n leftCircleEle.style.stroke = isLeftHover && isAxis ? style.circleHover : style.circle;\n rightCircleEle.style.stroke = isRightHover && isAxis ? style.circleHover : style.circle;\n if (this.component.theme === 'Highcontrast') {\n leftArrowEle.style.fill = isLeftHover && isAxis ? style.arrowHover : style.arrow;\n leftArrowEle.style.stroke = isLeftHover && isAxis ? style.arrowHover : style.arrow;\n rightArrowEle.style.fill = isRightHover && isAxis ? style.arrowHover : style.arrow;\n rightArrowEle.style.stroke = isRightHover && isAxis ? style.arrowHover : style.arrow;\n leftCircleEle.style.stroke = isLeftHover && isAxis ? style.circleHover : style.circle;\n rightCircleEle.style.stroke = isRightHover && isAxis ? style.circleHover : style.circle;\n }\n };\n /**\n * To check current axis\n * @param target\n * @param ele\n */\n ScrollBar.prototype.isCurrentAxis = function (target, ele) {\n return (target.id.split('_')[2] === ele.id.split('_')[2]);\n };\n /**\n * Method to resize thumb\n * @param e\n */\n ScrollBar.prototype.resizeThumb = function (e) {\n var currentWidth;\n var circleRadius = 8;\n var padding = 5;\n var gripWidth = 14;\n var elem = this.scrollElements;\n var minThumbWidth = circleRadius * 2 + padding * 2 + gripWidth;\n var thumbX = this.previousRectX;\n var mouseXY = this.isVertical ? this.mouseY : this.mouseX;\n var diff = Math.abs(this.previousXY - mouseXY);\n if (this.isResizeLeft && mouseXY >= 0) {\n var currentX = thumbX + (mouseXY > this.previousXY ? diff : -diff);\n currentWidth = currentX - circleRadius >= 0 ? this.previousWidth + (mouseXY > this.previousXY ? -diff : diff) :\n this.previousWidth;\n currentX = currentX - circleRadius >= 0 ? currentX : thumbX;\n if (currentWidth >= minThumbWidth && mouseXY < currentX + currentWidth) {\n this.scrollElements.thumbRectX = this.previousRectX = currentX;\n this.scrollElements.thumbRectWidth = this.previousWidth = currentWidth;\n this.previousXY = mouseXY;\n this.positionThumb(currentX, currentWidth);\n this.setZoomFactorPosition(currentX, currentWidth);\n }\n }\n else if (this.isResizeRight) {\n currentWidth = mouseXY >= minThumbWidth + this.scrollElements.thumbRectX && mouseXY <= this.width - circleRadius ?\n mouseXY - this.scrollElements.thumbRectX : this.previousWidth;\n this.scrollElements.thumbRectWidth = this.previousWidth = currentWidth;\n this.previousXY = mouseXY;\n this.positionThumb(this.startX, currentWidth);\n this.setZoomFactorPosition(this.startX, currentWidth);\n }\n };\n /**\n * Method to position the scrollbar thumb\n * @param currentX\n * @param currentWidth\n */\n ScrollBar.prototype.positionThumb = function (currentX, currentWidth) {\n var circlePadding = 3;\n var elem = this.scrollElements;\n var gripWidth = 14;\n var gripCircleDiameter = 2;\n var padding = gripWidth / 2 - gripCircleDiameter;\n elem.slider.setAttribute('x', currentX.toString());\n elem.slider.setAttribute('width', currentWidth.toString());\n elem.leftCircleEle.setAttribute('cx', currentX.toString());\n elem.rightCircleEle.setAttribute('cx', (currentX + currentWidth).toString());\n elem.setArrowDirection(currentX, currentWidth, this.height);\n elem.gripCircle.setAttribute('transform', 'translate(' + (currentX + currentWidth / 2 + ((this.isVertical ? 1 : -1) * padding)) +\n ',' + (this.isVertical ? '10' : '5') + ') rotate(' + (this.isVertical ? '180' : '0') + ')');\n };\n /**\n * Method to get default values\n */\n ScrollBar.prototype.getDefaults = function () {\n var circleRadius = 8;\n var padding = 5;\n var gripWidth = 14;\n var minThumbWidth = circleRadius * 2 + padding * 2 + gripWidth;\n var axis = this.axis;\n this.isVertical = axis.orientation === 'Vertical';\n var currentWidth = axis.zoomFactor * (this.isVertical ? axis.rect.height : axis.rect.width);\n currentWidth = currentWidth > minThumbWidth ? currentWidth : minThumbWidth;\n this.scrollX = axis.rect.x;\n this.scrollY = axis.rect.y;\n this.width = this.isVertical ? axis.rect.height : axis.rect.width;\n this.height = 16;\n var currentX = axis.zoomPosition * (this.isVertical ? axis.rect.height : this.width);\n this.scrollElements.thumbRectX = currentX > circleRadius ? currentX : circleRadius;\n this.scrollElements.thumbRectWidth = ((currentWidth + this.scrollElements.thumbRectX) < this.width - (circleRadius * 2))\n ? currentWidth : this.width - this.scrollElements.thumbRectX - circleRadius;\n };\n /**\n * Method for injecting scrollbar module\n * @param axis\n * @param component\n */\n ScrollBar.prototype.injectTo = function (axis, component) {\n axis.zoomingScrollBar = new ScrollBar(component, axis);\n };\n /**\n * Animation Calculation for scrollbar\n * @param previous\n * @param current\n */\n ScrollBar.prototype.performAnimation = function (previous, current) {\n var _this = this;\n var currentX;\n var width = this.scrollElements.thumbRectWidth;\n new Animation({}).animate(createElement('div'), {\n duration: this.animateDuration,\n progress: function (args) {\n currentX = linear(args.timeStamp, 0, current - previous, args.duration) + previous;\n _this.positionThumb(currentX, width);\n _this.setZoomFactorPosition(currentX, width);\n },\n end: function (model) {\n _this.scrollElements.thumbRectX = current;\n _this.startX = current;\n _this.positionThumb(current, width);\n _this.setZoomFactorPosition(current, width);\n }\n });\n };\n /**\n * Method to destroy scrollbar\n */\n ScrollBar.prototype.destroy = function () {\n var _this = this;\n if (this.axes) {\n this.axes.map(function (axis) {\n axis.zoomingScrollBar.destroy();\n });\n }\n else {\n this.elements.map(function (element) {\n _this.unWireEvents(element);\n remove(element.firstChild);\n });\n this.elements = [];\n }\n };\n /**\n * Method to get scrollbar module name\n */\n ScrollBar.prototype.getModuleName = function () {\n return 'ScrollBar';\n };\n return ScrollBar;\n}());\nexport { ScrollBar };\n","/**\n * Defines the common functionalities of accumulation series\n */\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { degreeToLocation, getElement, indexFinder } from '../../common/utils/helper';\nimport { pointByIndex } from '../model/acc-base';\n/**\n * Accumulation Base used to do some base calculation for accumulation chart.\n */\nvar AccumulationBase = /** @class */ (function () {\n /** @private */\n function AccumulationBase(accumulation) {\n this.accumulation = accumulation;\n }\n Object.defineProperty(AccumulationBase.prototype, \"center\", {\n /**\n * Gets the center of the pie\n * @private\n */\n get: function () {\n return this.pieCenter || (this.accumulation.visibleSeries[0].type === 'Pie' ?\n this.accumulation.pieSeriesModule.center : null);\n },\n /**\n * Sets the center of the pie\n * @private\n */\n set: function (value) {\n this.pieCenter = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AccumulationBase.prototype, \"radius\", {\n /**\n * Gets the radius of the pie\n * @private\n */\n get: function () {\n return this.pieRadius !== undefined ? this.pieRadius :\n this.accumulation.pieSeriesModule.radius;\n },\n /**\n * Sets the radius of the pie\n * @private\n */\n set: function (value) {\n this.pieRadius = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AccumulationBase.prototype, \"labelRadius\", {\n /**\n * Gets the label radius of the pie\n * @private\n */\n get: function () {\n return this.pieLabelRadius !== undefined ? this.pieLabelRadius :\n this.accumulation.pieSeriesModule.labelRadius;\n },\n /**\n * Sets the label radius of the pie\n * @private\n */\n set: function (value) {\n this.pieLabelRadius = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Checks whether the series is circular or not\n * @private\n */\n AccumulationBase.prototype.isCircular = function () {\n return this.accumulation.type === 'Pie';\n };\n /**\n * To process the explode on accumulation chart loading\n * @private\n */\n AccumulationBase.prototype.processExplode = function (event) {\n if (event.target.id.indexOf('_Series_') > -1 || event.target.id.indexOf('_datalabel_') > -1) {\n var pointIndex = indexFinder(event.target.id).point;\n if (isNaN(pointIndex) || (event.target.id.indexOf('_datalabel_') > -1 &&\n this.accumulation.visibleSeries[0].points[pointIndex].labelPosition === 'Outside')) {\n return null;\n }\n this.explodePoints(pointIndex, this.accumulation);\n this.deExplodeAll(pointIndex);\n }\n };\n /**\n * To invoke the explode on accumulation chart loading\n * @private\n */\n AccumulationBase.prototype.invokeExplode = function () {\n if (this.accumulation.visibleSeries[0].explodeAll) {\n for (var _i = 0, _a = this.accumulation.visibleSeries[0].points; _i < _a.length; _i++) {\n var point = _a[_i];\n this.explodePoints(point.index, this.accumulation);\n }\n }\n else if (!isNullOrUndefined(this.accumulation.visibleSeries[0].explodeIndex)) {\n this.explodePoints(this.accumulation.visibleSeries[0].explodeIndex, this.accumulation);\n }\n if (this.accumulation.accumulationSelectionModule && this.accumulation.selectionMode !== 'None' &&\n this.accumulation.accumulationSelectionModule.selectedDataIndexes.length) {\n for (var _b = 0, _c = this.accumulation.accumulationSelectionModule.selectedDataIndexes; _b < _c.length; _b++) {\n var index = _c[_b];\n this.explodePoints(index.point, this.accumulation, true);\n this.deExplodeAll(index.point);\n }\n }\n };\n /**\n * To deExplode all points in the series\n */\n AccumulationBase.prototype.deExplodeAll = function (index) {\n var pointId = this.accumulation.element.id + '_Series_0_Point_';\n var points = this.accumulation.visibleSeries[0].points;\n for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {\n var currentPoint = points_1[_i];\n if (index !== currentPoint.index) {\n this.deExplodeSlice(currentPoint.index, pointId, this.center);\n }\n }\n };\n /**\n * To explode point by index\n * @private\n */\n AccumulationBase.prototype.explodePoints = function (index, chart, explode) {\n if (explode === void 0) { explode = false; }\n var pointId = this.accumulation.element.id + '_Series_0_Point_';\n var translate;\n var points = this.accumulation.visibleSeries[0].points;\n var point = pointByIndex(index, this.accumulation.visibleSeries[0].points);\n if (isNullOrUndefined(point)) {\n return null;\n }\n if (!this.isCircular()) {\n translate = { x: chart.explodeDistance, y: 0 };\n }\n else {\n translate = degreeToLocation(point.midAngle, chart.explodeDistance, this.center);\n }\n if (this.isExplode(pointId + index) || explode) {\n this.explodeSlice(index, translate, pointId, this.center || { x: 0, y: 0 });\n }\n else {\n this.deExplodeSlice(index, pointId, this.center);\n }\n };\n /**\n * To check point is exploded by id\n */\n AccumulationBase.prototype.isExplode = function (id) {\n var element = getElement(id);\n if (element && (element.getAttribute('transform') === 'translate(0, 0)' || element.getAttribute('transform') === null ||\n element.getAttribute('transform') === 'translate(0)')) {\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * To deExplode the point by index\n */\n AccumulationBase.prototype.deExplodeSlice = function (index, sliceId, center) {\n var position = 'translate(0, 0)';\n this.setTranslate(index, sliceId, position);\n };\n /**\n * To translate the point elements by index and position\n */\n AccumulationBase.prototype.setTranslate = function (index, sliceId, position) {\n this.setElementTransform(sliceId + index, position);\n if (this.accumulation.visibleSeries[0].dataLabel.visible) {\n sliceId = this.accumulation.element.id + '_datalabel_Series_0_';\n this.setElementTransform(sliceId + 'shape_' + index, position);\n this.setElementTransform(sliceId + 'text_' + index, position);\n this.setElementTransform(sliceId + 'connector_' + index, position);\n }\n };\n /**\n * To translate the point element by id and position\n */\n AccumulationBase.prototype.setElementTransform = function (id, position) {\n var element = getElement(id);\n if (element) {\n element.setAttribute('transform', position);\n }\n };\n /**\n * To translate the point elements by index position\n */\n AccumulationBase.prototype.explodeSlice = function (index, translate, sliceId, center) {\n var position = 'translate(' + (translate.x - center.x) + ', ' + (translate.y - center.y) + ')';\n this.setTranslate(index, sliceId, position);\n };\n return AccumulationBase;\n}());\nexport { AccumulationBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * Accumulation charts base file\n */\nimport { Animation, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { stringToNumber, ChartLocation, degreeToLocation, Rect, getAnimationFunction, getElement } from '../../common/utils/helper';\nimport { animationComplete } from '../../common/model/constants';\nimport { AccumulationBase } from './accumulation-base';\n/**\n * PieBase class used to do pie base calculations.\n */\nvar PieBase = /** @class */ (function (_super) {\n __extends(PieBase, _super);\n function PieBase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * To initialize the property values.\n * @private\n */\n PieBase.prototype.initProperties = function (chart, series) {\n this.accumulation = chart;\n var size = Math.min(chart.initialClipRect.width, chart.initialClipRect.height);\n this.initAngles(series);\n this.radius = stringToNumber(series.radius, size / 2);\n this.innerRadius = stringToNumber(series.innerRadius, this.radius);\n this.labelRadius = series.dataLabel.position === 'Inside' ? (((this.radius - this.innerRadius) / 2) + this.innerRadius) :\n (this.radius + stringToNumber(series.dataLabel.connectorStyle.length || '4%', size / 2));\n chart.explodeDistance = series.explode ? stringToNumber(series.explodeOffset, this.radius) : 0;\n this.findCenter(chart, series);\n this.defaultLabelBound(series, series.dataLabel.visible, series.dataLabel.position);\n this.totalAngle -= 0.001;\n };\n /**\n * To find the center of the accumulation.\n * @private\n */\n PieBase.prototype.findCenter = function (accumulation, series) {\n this.accumulation = accumulation;\n this.center = {\n x: stringToNumber('50%', accumulation.initialClipRect.width) + (accumulation.initialClipRect.x),\n y: stringToNumber('50%', accumulation.initialClipRect.height) + (accumulation.initialClipRect.y)\n };\n var accumulationRect = this.getSeriesBound(series);\n var accumulationRectCenter = new ChartLocation(accumulationRect.x + accumulationRect.width / 2, accumulationRect.y + accumulationRect.height / 2);\n this.center.x += (this.center.x - accumulationRectCenter.x);\n this.center.y += (this.center.y - accumulationRectCenter.y);\n this.accumulation.center = this.center;\n };\n /**\n * To find angles from series.\n */\n PieBase.prototype.initAngles = function (series) {\n var endAngle = isNullOrUndefined(series.endAngle) ? series.startAngle : series.endAngle;\n this.totalAngle = (endAngle - series.startAngle) % 360;\n this.startAngle = series.startAngle - 90;\n this.totalAngle = this.totalAngle <= 0 ? (360 + this.totalAngle) : this.totalAngle;\n this.startAngle = (this.startAngle < 0 ? (this.startAngle + 360) : this.startAngle) % 360;\n };\n /**\n * To calculate data-label bound\n * @private\n */\n PieBase.prototype.defaultLabelBound = function (series, visible, position) {\n var accumulationBound = this.getSeriesBound(series);\n series.accumulationBound = accumulationBound;\n series.labelBound = new Rect(accumulationBound.x, accumulationBound.y, accumulationBound.width + accumulationBound.x, accumulationBound.height + accumulationBound.y);\n if (visible && position === 'Outside') {\n series.labelBound = new Rect(Infinity, Infinity, -Infinity, -Infinity);\n }\n };\n /**\n * To calculate series bound\n * @private\n */\n PieBase.prototype.getSeriesBound = function (series) {\n var rect = new Rect(Infinity, Infinity, -Infinity, -Infinity);\n this.initAngles(series);\n var start = this.startAngle;\n var total = this.totalAngle;\n var end = (this.startAngle + total) % 360;\n end = (end === 0) ? 360 : end;\n series.findMaxBounds(rect, this.getRectFromAngle(start));\n series.findMaxBounds(rect, this.getRectFromAngle(end));\n series.findMaxBounds(rect, new Rect(this.center.x, this.center.y, 0, 0));\n var nextQuandrant = (Math.floor(start / 90) * 90 + 90) % 360;\n var lastQuadrant = (Math.floor(end / 90) * 90) % 360;\n lastQuadrant = (lastQuadrant === 0) ? 360 : lastQuadrant;\n if (total >= 90 || lastQuadrant === nextQuandrant) {\n series.findMaxBounds(rect, this.getRectFromAngle(nextQuandrant));\n series.findMaxBounds(rect, this.getRectFromAngle(lastQuadrant));\n }\n if (start === 0 || (start + total >= 360)) {\n series.findMaxBounds(rect, this.getRectFromAngle(0));\n }\n var length = nextQuandrant === lastQuadrant ? 0 : Math.floor(total / 90);\n for (var i = 1; i < length; i++) {\n nextQuandrant = nextQuandrant + 90;\n if ((nextQuandrant < lastQuadrant || end < start) || total === 360) {\n series.findMaxBounds(rect, this.getRectFromAngle(nextQuandrant));\n }\n }\n rect.width -= rect.x;\n rect.height -= rect.y;\n return rect;\n };\n /**\n * To get rect location size from angle\n */\n PieBase.prototype.getRectFromAngle = function (angle) {\n var location = degreeToLocation(angle, this.radius, this.center);\n return new Rect(location.x, location.y, 0, 0);\n };\n /**\n * To get path arc direction\n */\n PieBase.prototype.getPathArc = function (center, start, end, radius, innerRadius) {\n var degree = end - start;\n degree = degree < 0 ? (degree + 360) : degree;\n var flag = (degree < 180) ? 0 : 1;\n if (!innerRadius && innerRadius === 0) {\n return this.getPiePath(center, degreeToLocation(start, radius, center), degreeToLocation(end, radius, center), radius, flag);\n }\n else {\n return this.getDoughnutPath(center, degreeToLocation(start, radius, center), degreeToLocation(end, radius, center), radius, degreeToLocation(start, innerRadius, center), degreeToLocation(end, innerRadius, center), innerRadius, flag);\n }\n };\n /**\n * To get pie direction\n */\n PieBase.prototype.getPiePath = function (center, start, end, radius, clockWise) {\n return 'M ' + center.x + ' ' + center.y + ' L ' + start.x + ' ' + start.y + ' A ' + radius + ' ' +\n radius + ' 0 ' + clockWise + ' 1 ' + end.x + ' ' + end.y + ' Z';\n };\n /**\n * To get doughnut direction\n */\n PieBase.prototype.getDoughnutPath = function (center, start, end, radius, innerStart, innerEnd, innerRadius, clockWise) {\n return 'M ' + start.x + ' ' + start.y + ' A ' + radius + ' ' + radius + ' 0 ' + clockWise +\n ' 1 ' + end.x + ' ' + end.y + ' L ' + innerEnd.x + ' ' + innerEnd.y + ' A ' + innerRadius +\n ' ' + innerRadius + ' 0 ' + clockWise + ',0 ' + innerStart.x + ' ' + innerStart.y + ' Z';\n };\n /**\n * Method to start animation for pie series.\n */\n PieBase.prototype.doAnimation = function (slice, series) {\n var _this = this;\n var startAngle = series.startAngle - 85;\n var value;\n var radius = Math.max(this.accumulation.availableSize.height, this.accumulation.availableSize.width) * 0.75;\n radius += radius * (0.414); // formula r + r / 2 * (1.414 -1)\n var effect = getAnimationFunction('Linear'); // need to check animation type\n new Animation({}).animate(slice, {\n duration: series.animation.duration,\n delay: series.animation.delay,\n progress: function (args) {\n value = effect(args.timeStamp, startAngle, _this.totalAngle, args.duration);\n slice.setAttribute('d', _this.getPathArc(_this.center, startAngle, value, radius, 0));\n },\n end: function (args) {\n slice.setAttribute('d', _this.getPathArc(_this.center, 0, 359.99999, radius, 0));\n _this.accumulation.trigger(animationComplete, { series: series, accumulation: _this.accumulation });\n var datalabelGroup = getElement(_this.accumulation.element.id + '_datalabel_Series_' + series.index);\n datalabelGroup.style.visibility = _this.accumulation.isDestroyed ? 'hidden' : 'visible';\n }\n });\n };\n return PieBase;\n}(AccumulationBase));\nexport { PieBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { PathOption, degreeToLocation } from '../../common/utils/helper';\nimport { PieBase } from '../renderer/pie-base';\n/**\n * PieSeries module used to render `Pie` Series.\n */\nvar PieSeries = /** @class */ (function (_super) {\n __extends(PieSeries, _super);\n function PieSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * To get path option, degree, symbolLocation from the point.\n * @private\n */\n PieSeries.prototype.renderPoint = function (point, series, chart, option) {\n var sum = series.sumOfPoints;\n var degree = (sum) ? ((Math.abs(point.y) / sum) * (this.totalAngle)) : null;\n option.d = this.getPathOption(point, degree);\n point.midAngle = (this.startAngle - (degree / 2)) % 360;\n point.endAngle = this.startAngle % 360;\n point.symbolLocation = degreeToLocation(point.midAngle, (this.radius + this.innerRadius) / 2, this.center);\n return option;\n };\n /**\n * To get path option from the point.\n */\n PieSeries.prototype.getPathOption = function (point, degree) {\n if (degree === null || !point.y) {\n return '';\n }\n var path = this.getPathArc(this.center, this.startAngle % 360, (this.startAngle + degree) % 360, this.radius, this.innerRadius);\n this.startAngle += degree;\n return path;\n };\n /**\n * To animate the pie series.\n * @private\n */\n PieSeries.prototype.animateSeries = function (accumulation, option, series, slice) {\n var groupId = accumulation.element.id + 'SeriesGroup' + series.index;\n if (series.animation.enable && accumulation.animateSeries) {\n var clippath = accumulation.renderer.createClipPath({ id: groupId + '_clipPath' });\n var path = new PathOption(groupId + '_slice', 'transparent', 1, 'transparent', 1, '', '');\n var clipslice = accumulation.renderer.drawPath(path);\n clippath.appendChild(clipslice);\n accumulation.svgObject.appendChild(clippath);\n slice.setAttribute('style', 'clip-path:url(#' + clippath.id + ')');\n this.doAnimation(clipslice, series);\n }\n };\n /**\n * To get the module name of the Pie series.\n */\n PieSeries.prototype.getModuleName = function () {\n return 'PieSeries';\n };\n /**\n * To destroy the pie series.\n * @return {void}\n * @private\n */\n PieSeries.prototype.destroy = function (accumulation) {\n /**\n * Destroy method calling here\n */\n };\n return PieSeries;\n}(PieBase));\nexport { PieSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n/**\n * AccumulationChart file\n */\nimport { Property, Component, Complex, Collection, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { Internationalization, Event, Browser, EventHandler, Touch } from '@syncfusion/ej2-base';\nimport { remove, extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Font, Margin, Border, TooltipSettings, Indexes } from '../common/model/base';\nimport { AccumulationSeries } from './model/acc-base';\nimport { Theme, getThemeColor } from '../common/model/theme';\nimport { load, pointClick } from '../common/model/constants';\nimport { pointMove, chartMouseClick, chartMouseDown } from '../common/model/constants';\nimport { chartMouseLeave, chartMouseMove, chartMouseUp, resized } from '../common/model/constants';\nimport { LegendSettings } from '../common/legend/legend';\nimport { Rect, Size, subtractRect, indexFinder } from '../common/utils/helper';\nimport { measureText, RectOption, showTooltip } from '../common/utils/helper';\nimport { textElement, TextOption, createSvg, calculateSize, removeElement, firstToLowerCase } from '../common/utils/helper';\nimport { getElement, titlePositionX } from '../common/utils/helper';\nimport { Data } from '../common/model/data';\nimport { AccumulationBase } from './renderer/accumulation-base';\nimport { PieSeries } from './renderer/pie-series';\nimport { AccumulationAnnotationSettings } from './model/acc-base';\nimport { ExportUtils } from '../common/utils/export';\nimport { getTitle } from '../common/utils/helper';\n/**\n * Represents the AccumulationChart control.\n * ```html\n * \n * \n * ```\n */\nvar AccumulationChart = /** @class */ (function (_super) {\n __extends(AccumulationChart, _super);\n /**\n * Constructor for creating the AccumulationChart widget\n * @private\n */\n function AccumulationChart(options, element) {\n var _this = _super.call(this, options, element) || this;\n /** @private explode radius internal property */\n _this.explodeDistance = 0;\n _this.chartid = 57724;\n return _this;\n }\n Object.defineProperty(AccumulationChart.prototype, \"type\", {\n /** @private */\n get: function () {\n if (this.series && this.series.length) {\n return this.series[0].type;\n }\n return 'Pie';\n },\n enumerable: true,\n configurable: true\n });\n // accumulation chart methods\n /**\n * To create svg object, renderer and binding events for the container.\n */\n AccumulationChart.prototype.preRender = function () {\n this.unWireEvents();\n this.setCulture();\n this.animateSeries = true;\n if (this.element.id === '') {\n var collection = document.getElementsByClassName('e-accumulationchart').length;\n this.element.id = 'acc_chart_' + this.chartid + '_' + collection;\n }\n calculateSize(this);\n this.wireEvents();\n };\n /**\n * Themeing for chart goes here\n */\n AccumulationChart.prototype.setTheme = function () {\n /*! Set theme for accumulation chart */\n this.themeStyle = getThemeColor(this.theme);\n };\n /**\n * To render the accumulation chart elements\n */\n AccumulationChart.prototype.render = function () {\n this.trigger(load, { accumulation: this });\n this.setTheme();\n this.accBaseModule = new AccumulationBase(this);\n this.pieSeriesModule = new PieSeries(this);\n this.calculateVisibleSeries();\n this.processData();\n };\n /**\n * Method to unbind events for accumulation chart\n */\n AccumulationChart.prototype.unWireEvents = function () {\n /*! Find the Events type */\n var isIE11Pointer = Browser.isPointer;\n var start = Browser.touchStartEvent;\n var move = Browser.touchMoveEvent;\n var stop = Browser.touchEndEvent;\n var cancel = isIE11Pointer ? 'pointerleave' : 'mouseleave';\n /*! UnBind the Event handler */\n EventHandler.remove(this.element, move, this.accumulationMouseMove);\n EventHandler.remove(this.element, stop, this.accumulationMouseEnd);\n EventHandler.remove(this.element, start, this.accumulationMouseStart);\n EventHandler.remove(this.element, 'click', this.accumulationOnMouseClick);\n EventHandler.remove(this.element, 'contextmenu', this.accumulationRightClick);\n EventHandler.remove(this.element, cancel, this.accumulationMouseLeave);\n window.removeEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.accumulationResize);\n };\n /**\n * Method to bind events for the accumulation chart\n */\n AccumulationChart.prototype.wireEvents = function () {\n /*! Find the Events type */\n var isIE11Pointer = Browser.isPointer;\n var start = Browser.touchStartEvent;\n var stop = Browser.touchEndEvent;\n var move = Browser.touchMoveEvent;\n var cancel = isIE11Pointer ? 'pointerleave' : 'mouseleave';\n /*! Bind the Event handler */\n EventHandler.add(this.element, move, this.accumulationMouseMove, this);\n EventHandler.add(this.element, stop, this.accumulationMouseEnd, this);\n EventHandler.add(this.element, start, this.accumulationMouseStart, this);\n EventHandler.add(this.element, 'click', this.accumulationOnMouseClick, this);\n EventHandler.add(this.element, 'contextmenu', this.accumulationRightClick, this);\n EventHandler.add(this.element, cancel, this.accumulationMouseLeave, this);\n window.addEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.accumulationResize.bind(this));\n new Touch(this.element); // To avoid geasture blocking for browser\n /*! Apply the style for chart */\n this.setStyle(this.element);\n };\n /**\n * Method to set mouse x, y from events\n */\n AccumulationChart.prototype.setMouseXY = function (e) {\n var pageX;\n var pageY;\n var svgRect = getElement(this.element.id + '_svg').getBoundingClientRect();\n var rect = this.element.getBoundingClientRect();\n if (e.type.indexOf('touch') > -1) {\n this.isTouch = true;\n var touchArg = e;\n pageY = touchArg.changedTouches[0].clientY;\n pageX = touchArg.changedTouches[0].clientX;\n }\n else {\n this.isTouch = e.pointerType === 'touch' || e.pointerType === '2';\n pageX = e.clientX;\n pageY = e.clientY;\n }\n this.mouseY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0);\n this.mouseX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0);\n };\n /**\n * Handles the mouse end.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.accumulationMouseEnd = function (e) {\n this.setMouseXY(e);\n this.trigger(chartMouseUp, { target: e.target.id, x: this.mouseX, y: this.mouseY });\n if (this.isTouch) {\n this.titleTooltip(e, this.mouseX, this.mouseY, this.isTouch);\n if (this.accumulationDataLabelModule && this.visibleSeries[0].dataLabel.visible) {\n this.accumulationDataLabelModule.move(e, this.mouseX, this.mouseY, this.isTouch);\n }\n if (this.accumulationLegendModule && this.legendSettings.visible) {\n this.accumulationLegendModule.move(e);\n }\n }\n this.notify(Browser.touchEndEvent, e);\n return false;\n };\n /*public removeSvgOffset(x: number, y: number): ChartLocation {\n let rect: ClientRect = this.element.getBoundingClientRect();\n let svgRect: ClientRect = getElement(this.element.id + '_svg').getBoundingClientRect();\n return { x: (x - rect.left) - Math.max(svgRect.left - rect.left, 0), y: (y - rect.top) - Math.max(svgRect.top - rect.top, 0)};\n }*/\n /**\n * Handles the mouse start.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.accumulationMouseStart = function (e) {\n this.setMouseXY(e);\n this.trigger(chartMouseDown, { target: e.target.id, x: this.mouseX, y: this.mouseY });\n return false;\n };\n /**\n * Handles the accumulation chart resize.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.accumulationResize = function (e) {\n var _this = this;\n this.animateSeries = false;\n var args = {\n accumulation: this,\n previousSize: new Size(this.availableSize.width, this.availableSize.height),\n name: resized,\n currentSize: new Size(0, 0)\n };\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n this.resizeTo = setTimeout(function () {\n if (_this.isDestroyed) {\n clearTimeout(_this.resizeTo);\n return;\n }\n calculateSize(_this);\n args.currentSize = _this.availableSize;\n _this.trigger(resized, args);\n _this.refreshSeries();\n _this.refreshChart();\n }, 500);\n return false;\n };\n /**\n * Handles the export method for accumulation control.\n */\n AccumulationChart.prototype.export = function (type, fileName, orientation, controls, width, height) {\n var exportChart = new ExportUtils(this);\n exportChart.export(type, fileName, orientation, (controls ? controls : [this]), width, height);\n };\n /**\n * Handles the print method for accumulation chart control.\n */\n AccumulationChart.prototype.print = function (id) {\n var exportChart = new ExportUtils(this);\n exportChart.print(id);\n };\n /**\n * Applying styles for accumulation chart element\n */\n AccumulationChart.prototype.setStyle = function (element) {\n element.style.touchAction = 'element';\n element.style.msTouchAction = 'element';\n element.style.msContentZooming = 'none';\n element.style.msUserSelect = 'none';\n element.style.webkitUserSelect = 'none';\n element.style.position = 'relative';\n };\n /**\n * Method to set the annotation content dynamically for accumulation.\n */\n AccumulationChart.prototype.setAnnotationValue = function (annotationIndex, content) {\n var annotation = this.annotations[annotationIndex];\n var element;\n var parentNode = getElement(this.element.id + '_Annotation_Collections');\n if (content) {\n annotation.content = content;\n if (parentNode) {\n element = this.createElement('div');\n removeElement(this.element.id + '_Annotation_' + annotationIndex);\n this.annotationModule.processAnnotation(annotation, annotationIndex, element);\n parentNode.appendChild(element.children[0]);\n }\n else {\n this.annotationModule.renderAnnotations(getElement(this.element.id + '_Secondary_Element'));\n }\n }\n };\n /**\n * Handles the mouse move on accumulation chart.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.accumulationMouseMove = function (e) {\n this.setMouseXY(e);\n this.trigger(chartMouseMove, { target: e.target.id, x: this.mouseX, y: this.mouseY });\n if (this.pointMove) {\n this.triggerPointEvent(pointMove, e.target);\n }\n if (this.accumulationLegendModule && this.legendSettings.visible) {\n this.accumulationLegendModule.move(e);\n }\n if (this.accumulationDataLabelModule && this.visibleSeries[0] && this.visibleSeries[0].dataLabel.visible) {\n this.accumulationDataLabelModule.move(e, this.mouseX, this.mouseY);\n }\n if (!this.isTouch) {\n this.titleTooltip(e, this.mouseX, this.mouseY);\n }\n this.notify(Browser.touchMoveEvent, e);\n return false;\n };\n AccumulationChart.prototype.titleTooltip = function (event, x, y, isTouch) {\n var targetId = event.target.id;\n if ((event.target.textContent.indexOf('...') > -1) && (targetId === (this.element.id + '_title'))) {\n showTooltip(this.title, x, y, this.element.offsetWidth, this.element.id + '_EJ2_Title_Tooltip', getElement(this.element.id + '_Secondary_Element'), isTouch);\n }\n else {\n removeElement(this.element.id + '_EJ2_Title_Tooltip');\n }\n };\n /**\n * Handles the mouse click on accumulation chart.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.accumulationOnMouseClick = function (e) {\n this.setMouseXY(e);\n if (this.accumulationLegendModule && this.legendSettings.visible) {\n this.accumulationLegendModule.click(e);\n }\n if (this.selectionMode !== 'None' && this.accumulationSelectionModule) {\n this.accumulationSelectionModule.calculateSelectedElements(this, e);\n }\n if (this.visibleSeries[0].explode) {\n this.accBaseModule.processExplode(e);\n }\n this.trigger(chartMouseClick, { target: e.target.id, x: this.mouseX, y: this.mouseY });\n if (this.pointClick) {\n this.triggerPointEvent(pointClick, e.target);\n }\n return false;\n };\n AccumulationChart.prototype.triggerPointEvent = function (event, element) {\n var indexes = indexFinder(element.id, true);\n if (indexes.series >= 0 && indexes.point >= 0) {\n this.trigger(event, { series: this.series[indexes.series],\n point: this.series[indexes.series].points[indexes.point],\n seriesIndex: indexes.series, pointIndex: indexes.point,\n x: this.mouseX, y: this.mouseY });\n }\n };\n /**\n * Handles the mouse right click on accumulation chart.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.accumulationRightClick = function (event) {\n if (event.buttons === 2 || event.pointerType === 'touch') {\n event.preventDefault();\n event.stopPropagation();\n return false;\n }\n return true;\n };\n /**\n * Handles the mouse leave on accumulation chart.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.accumulationMouseLeave = function (e) {\n this.setMouseXY(e);\n this.trigger(chartMouseLeave, { target: e.target.id, x: this.mouseX, y: this.mouseY });\n this.notify(Browser.isPointer ? 'pointerleave' : 'mouseleave', e);\n return false;\n };\n /**\n * Method to set culture for chart\n */\n AccumulationChart.prototype.setCulture = function () {\n this.intl = new Internationalization();\n };\n /**\n * Method to create SVG element for accumulation chart.\n */\n AccumulationChart.prototype.createPieSvg = function () {\n this.removeSvg();\n createSvg(this);\n };\n /**\n * To Remove the SVG from accumulation chart.\n * @return {boolean}\n * @private\n */\n AccumulationChart.prototype.removeSvg = function () {\n removeElement(this.element.id + '_Secondary_Element');\n if (this.svgObject) {\n while (this.svgObject.childNodes.length > 0) {\n this.svgObject.removeChild(this.svgObject.firstChild);\n }\n if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) {\n remove(this.svgObject);\n }\n }\n removeElement('EJ2_legend_tooltip');\n removeElement('EJ2_datalabel_tooltip');\n };\n /**\n * Method to create the secondary element for tooltip, datalabel and annotaitons.\n */\n AccumulationChart.prototype.createSecondaryElement = function () {\n this.element.appendChild(this.createElement('div', {\n id: this.element.id + '_Secondary_Element',\n styles: 'position: relative'\n }));\n };\n /**\n * Method to find visible series based on series types\n */\n AccumulationChart.prototype.calculateVisibleSeries = function () {\n this.visibleSeries = [];\n for (var i = 0, length_1 = this.series.length; i < length_1; i++) {\n this.series[i].index = i;\n if (this.series[i].type === this.type && this.visibleSeries.length === 0) {\n this.visibleSeries.push(this.series[i]);\n break;\n }\n }\n };\n /**\n * To find points from dataSource\n */\n AccumulationChart.prototype.processData = function (render) {\n if (render === void 0) { render = true; }\n this.seriesCounts = 0;\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n series.dataModule = new Data(series.dataSource || this.dataSource, series.query);\n series.refreshDataManager(this, render);\n }\n };\n /**\n * To refresh the accumulation chart\n * @private\n */\n AccumulationChart.prototype.refreshChart = function () {\n this.doGrouppingProcess();\n this.createPieSvg();\n this.calculateBounds();\n this.renderElements();\n var element = document.getElementById('chartmeasuretext');\n if (element) {\n element.remove();\n }\n };\n /**\n * Method to find groupped points\n */\n AccumulationChart.prototype.doGrouppingProcess = function () {\n var series = this.visibleSeries[0];\n if (!isNullOrUndefined(series.resultData) && ((!isNullOrUndefined(series.lastGroupTo) &&\n series.lastGroupTo !== series.groupTo))) {\n series.getPoints(series.resultData, this);\n }\n };\n /**\n * Method to calculate bounds for accumulation chart\n */\n AccumulationChart.prototype.calculateBounds = function () {\n this.initialClipRect = new Rect(this.margin.left, this.margin.top, this.availableSize.width, this.availableSize.height);\n this.titleCollection = [];\n this.titleCollection = getTitle(this.title, this.titleStyle, this.initialClipRect.width);\n subtractRect(this.initialClipRect, new Rect(0, (measureText(this.title, this.titleStyle).height * this.titleCollection.length), this.margin.right + this.margin.left, this.margin.bottom + this.margin.top));\n this.calculateLegendBounds();\n };\n /*\n * Method to calculate legend bounds for accumulation chart\n */\n AccumulationChart.prototype.calculateLegendBounds = function () {\n if (!this.accumulationLegendModule || !this.legendSettings.visible) {\n return null;\n }\n this.accumulationLegendModule.getLegendOptions(this, this.visibleSeries);\n this.accumulationLegendModule.calculateLegendBounds(this.initialClipRect, this.availableSize);\n };\n /**\n * To render elements for accumulation chart\n * @private\n */\n AccumulationChart.prototype.renderElements = function () {\n this.renderBorder();\n this.renderTitle();\n this.createSecondaryElement();\n this.renderSeries();\n this.renderLegend();\n this.element.appendChild(this.svgObject);\n this.processSelection();\n this.processExplode();\n this.renderAnnotation();\n this.setSecondaryElementPosition();\n this.trigger('loaded', { accumulation: this });\n this.animateSeries = false;\n };\n /**\n * To set the left and top position for data label template for center aligned chart\n */\n AccumulationChart.prototype.setSecondaryElementPosition = function () {\n var tooltipParent = getElement(this.element.id + '_Secondary_Element');\n if (!tooltipParent) {\n return;\n }\n var rect = this.element.getBoundingClientRect();\n var svgRect = getElement(this.element.id + '_svg').getBoundingClientRect();\n tooltipParent.style.left = Math.max(svgRect.left - rect.left, 0) + 'px';\n tooltipParent.style.top = Math.max(svgRect.top - rect.top, 0) + 'px';\n };\n /**\n * To render the annotaitions for accumulation series.\n */\n AccumulationChart.prototype.renderAnnotation = function () {\n if (this.annotationModule) {\n this.annotationModule.renderAnnotations(getElement(this.element.id + '_Secondary_Element'));\n }\n };\n /**\n * Method to process the explode in accumulation chart\n */\n AccumulationChart.prototype.processExplode = function () {\n if (!this.visibleSeries[0].explode) {\n return null;\n }\n this.accBaseModule.invokeExplode();\n };\n /**\n * Method to render series for accumulation chart\n */\n AccumulationChart.prototype.renderSeries = function () {\n this.svgObject.appendChild(this.renderer.createGroup({ id: this.element.id + '_SeriesCollection' }));\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n if (series.visible && this[(firstToLowerCase(series.type) + 'SeriesModule')]) {\n this[(firstToLowerCase(series.type) + 'SeriesModule')].initProperties(this, series);\n series.renderSeries(this);\n }\n }\n };\n /**\n * Method to render border for accumulation chart\n */\n AccumulationChart.prototype.renderBorder = function () {\n var padding = this.border.width;\n this.svgObject.appendChild(this.renderer.drawRectangle(new RectOption(this.element.id + '_border', this.background || this.themeStyle.background, this.border, 1, new Rect(padding / 2, padding / 2, this.availableSize.width - padding, this.availableSize.height - padding))));\n };\n /**\n * Method to render legend for accumulation chart\n */\n AccumulationChart.prototype.renderLegend = function () {\n if (!this.accumulationLegendModule || !this.legendSettings.visible) {\n return null;\n }\n if (this.accumulationLegendModule.legendCollections.length) {\n if (this.visibleSeries[0].type === 'Pie') {\n this.accumulationLegendModule.getSmartLegendLocation(this.visibleSeries[0].labelBound, this.accumulationLegendModule.legendBounds, this.margin);\n }\n this.accumulationLegendModule.renderLegend(this, this.legendSettings, this.accumulationLegendModule.legendBounds);\n }\n };\n /**\n * To process the selection in accumulation chart\n */\n AccumulationChart.prototype.processSelection = function () {\n if (!this.accumulationSelectionModule || this.selectionMode === 'None') {\n return null;\n }\n var selectedDataIndexes = extend([], this.accumulationSelectionModule.selectedDataIndexes, null, true);\n this.accumulationSelectionModule.invokeSelection(this);\n if (selectedDataIndexes.length > 0) {\n this.accumulationSelectionModule.selectedDataIndexes = selectedDataIndexes;\n this.accumulationSelectionModule.redrawSelection(this, this.selectionMode);\n }\n };\n /**\n * To render title for accumulation chart\n */\n AccumulationChart.prototype.renderTitle = function () {\n if (!this.title) {\n return null;\n }\n var titleSize = measureText(this.title, this.titleStyle);\n var anchor = this.titleStyle.textAlignment === 'Near' ? 'start' :\n this.titleStyle.textAlignment === 'Far' ? 'end' : 'middle';\n textElement(new TextOption(this.element.id + '_title', titlePositionX(this.availableSize, this.margin.left, this.margin.left, this.titleStyle), this.margin.top + (titleSize.height * 3 / 4), anchor, this.titleCollection, '', 'auto'), this.titleStyle, this.titleStyle.color || this.themeStyle.chartTitle, this.svgObject);\n };\n /**\n * To get the series parent element\n * @private\n */\n AccumulationChart.prototype.getSeriesElement = function () {\n return this.svgObject.getElementsByTagName('g')[0];\n };\n /**\n * To refresh the all visible series points\n * @private\n */\n AccumulationChart.prototype.refreshSeries = function () {\n for (var _i = 0, _a = this.visibleSeries; _i < _a.length; _i++) {\n var series = _a[_i];\n this.refreshPoints(series.points);\n }\n };\n /**\n * To refresh points label region and visible\n * @private\n */\n AccumulationChart.prototype.refreshPoints = function (points) {\n for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {\n var point = points_1[_i];\n point.labelPosition = null;\n point.labelRegion = null;\n point.labelVisible = true;\n }\n };\n /**\n * To get Module name\n * @private\n */\n AccumulationChart.prototype.getModuleName = function () {\n return 'accumulationchart';\n };\n /**\n * To destroy the accumulationcharts\n * @private\n */\n AccumulationChart.prototype.destroy = function () {\n this.unWireEvents();\n _super.prototype.destroy.call(this);\n this.element.classList.remove('e-accumulationchart');\n };\n /**\n * To provide the array of modules needed for control rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n AccumulationChart.prototype.requiredModules = function () {\n var modules = [];\n var enableAnnotation = false;\n modules.push({\n member: this.type + 'Series',\n args: [this]\n });\n if (this.legendSettings.visible) {\n modules.push({\n member: 'AccumulationLegend',\n args: [this]\n });\n }\n if (this.findDatalabelVisibility()) {\n modules.push({\n member: 'AccumulationDataLabel',\n args: [this]\n });\n }\n if (this.tooltip.enable) {\n modules.push({\n member: 'AccumulationTooltip',\n args: [this]\n });\n }\n if (this.selectionMode !== 'None') {\n modules.push({\n member: 'AccumulationSelection',\n args: [this]\n });\n }\n enableAnnotation = this.annotations.some(function (value) {\n return (value.content !== null);\n });\n if (enableAnnotation) {\n modules.push({\n member: 'Annotation',\n args: [this]\n });\n }\n return modules;\n };\n /**\n * To find datalabel visibility in series\n */\n AccumulationChart.prototype.findDatalabelVisibility = function () {\n for (var _i = 0, _a = this.series; _i < _a.length; _i++) {\n var series = _a[_i];\n if (series.dataLabel.visible) {\n return true;\n }\n }\n return false;\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n AccumulationChart.prototype.getPersistData = function () {\n return '';\n };\n /**\n * Called internally if any of the property value changed.\n * @private\n */\n AccumulationChart.prototype.onPropertyChanged = function (newProp, oldProp) {\n var update = {\n refreshElements: false, refreshBounds: false\n };\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'theme':\n this.animateSeries = true;\n break;\n case 'title':\n case 'height':\n case 'width':\n case 'margin':\n update.refreshBounds = true;\n break;\n case 'titleStyle':\n if (newProp.titleStyle && (newProp.titleStyle.size || newProp.titleStyle.textOverflow)) {\n update.refreshBounds = true;\n }\n else {\n update.refreshElements = true;\n }\n break;\n case 'legendSettings':\n update.refreshBounds = true;\n update.refreshElements = true;\n break;\n case 'dataSource':\n this.processData(false);\n update.refreshBounds = true;\n break;\n case 'series':\n var len = this.series.length;\n var seriesRefresh = false;\n for (var i = 0; i < len; i++) {\n if (newProp.series[i] && (newProp.series[i].dataSource || newProp.series[i].yName || newProp.series[i].xName)) {\n seriesRefresh = true;\n }\n }\n if (seriesRefresh) {\n this.processData(false);\n update.refreshBounds = true;\n }\n break;\n case 'locale':\n case 'currencyCode':\n _super.prototype.refresh.call(this);\n break;\n case 'background':\n case 'border':\n case 'annotations':\n case 'enableSmartLabels':\n update.refreshElements = true;\n break;\n case 'isMultiSelect':\n case 'selectedDataIndexes':\n case 'selectionMode':\n if (this.accumulationSelectionModule) {\n if (isNullOrUndefined(this.accumulationSelectionModule.selectedDataIndexes)) {\n this.accumulationSelectionModule.invokeSelection(this);\n }\n else {\n this.accumulationSelectionModule.redrawSelection(this, oldProp.selectionMode);\n }\n }\n break;\n }\n }\n if (!update.refreshBounds && update.refreshElements) {\n this.createPieSvg();\n this.renderElements();\n }\n else if (update.refreshBounds) {\n this.refreshSeries();\n this.createPieSvg();\n this.calculateBounds();\n this.renderElements();\n }\n };\n __decorate([\n Property(null)\n ], AccumulationChart.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], AccumulationChart.prototype, \"height\", void 0);\n __decorate([\n Property(null)\n ], AccumulationChart.prototype, \"title\", void 0);\n __decorate([\n Property('')\n ], AccumulationChart.prototype, \"dataSource\", void 0);\n __decorate([\n Complex(Theme.chartTitleFont, Font)\n ], AccumulationChart.prototype, \"titleStyle\", void 0);\n __decorate([\n Complex({}, LegendSettings)\n ], AccumulationChart.prototype, \"legendSettings\", void 0);\n __decorate([\n Complex({}, TooltipSettings)\n ], AccumulationChart.prototype, \"tooltip\", void 0);\n __decorate([\n Property('None')\n ], AccumulationChart.prototype, \"selectionMode\", void 0);\n __decorate([\n Property(false)\n ], AccumulationChart.prototype, \"isMultiSelect\", void 0);\n __decorate([\n Collection([], Indexes)\n ], AccumulationChart.prototype, \"selectedDataIndexes\", void 0);\n __decorate([\n Complex({}, Margin)\n ], AccumulationChart.prototype, \"margin\", void 0);\n __decorate([\n Property(true)\n ], AccumulationChart.prototype, \"enableSmartLabels\", void 0);\n __decorate([\n Complex({ color: '#DDDDDD', width: 0 }, Border)\n ], AccumulationChart.prototype, \"border\", void 0);\n __decorate([\n Property(null)\n ], AccumulationChart.prototype, \"background\", void 0);\n __decorate([\n Collection([{}], AccumulationSeries)\n ], AccumulationChart.prototype, \"series\", void 0);\n __decorate([\n Collection([{}], AccumulationAnnotationSettings)\n ], AccumulationChart.prototype, \"annotations\", void 0);\n __decorate([\n Property('Material')\n ], AccumulationChart.prototype, \"theme\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"loaded\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"load\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"seriesRender\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"legendRender\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"textRender\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"tooltipRender\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"pointRender\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"annotationRender\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"beforePrint\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"chartMouseMove\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"chartMouseClick\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"pointClick\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"pointMove\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"animationComplete\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"chartMouseDown\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"chartMouseLeave\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"chartMouseUp\", void 0);\n __decorate([\n Event()\n ], AccumulationChart.prototype, \"resized\", void 0);\n __decorate([\n Property('USD')\n ], AccumulationChart.prototype, \"currencyCode\", void 0);\n AccumulationChart = __decorate([\n NotifyPropertyChanges\n ], AccumulationChart);\n return AccumulationChart;\n}(Component));\nexport { AccumulationChart };\n","/**\n * Defines the common behavior of funnel and pyramid series\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Size, stringToNumber, Rect } from '../../common/utils/helper';\nimport { AccumulationBase } from './accumulation-base';\n/**\n * TriangularBase is used to calculate base functions for funnel/pyramid series.\n */\nvar TriangularBase = /** @class */ (function (_super) {\n __extends(TriangularBase, _super);\n function TriangularBase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Initializes the properties of funnel/pyramid series\n * @private\n */\n TriangularBase.prototype.initProperties = function (chart, series) {\n var actualChartArea = chart.initialClipRect;\n series.triangleSize = new Size(stringToNumber(series.width, actualChartArea.width), stringToNumber(series.height, actualChartArea.height));\n series.neckSize = new Size(stringToNumber(series.neckWidth, actualChartArea.width), stringToNumber(series.neckHeight, actualChartArea.height));\n this.defaultLabelBound(series, series.dataLabel.visible, series.dataLabel.position, chart);\n if (series.explodeOffset === '30%') {\n series.explodeOffset = '25px';\n }\n chart.explodeDistance = stringToNumber(series.explodeOffset, actualChartArea.width);\n var points = series.points;\n this.initializeSizeRatio(points, series);\n };\n /**\n * Initializes the size of the pyramid/funnel segments\n * @private\n */\n TriangularBase.prototype.initializeSizeRatio = function (points, series, reverse) {\n if (reverse === void 0) { reverse = false; }\n var sumOfPoints = series.sumOfPoints;\n //Limiting the ratio within the range of 0 to 1\n var gapRatio = Math.min(Math.max(series.gapRatio, 0), 1);\n //% equivalence of a value 1\n var coEff = 1 / (sumOfPoints * (1 + gapRatio / (1 - gapRatio)));\n var spacing = gapRatio / (points.length - 1);\n var y = 0;\n //starting from bottom\n for (var i = points.length - 1; i >= 0; i--) {\n var index = reverse ? points.length - 1 - i : i;\n if (points[index].visible) {\n var height = coEff * points[index].y;\n points[index].yRatio = y;\n points[index].heightRatio = height;\n y += height + spacing;\n }\n }\n };\n /**\n * Marks the label location from the set of points that forms a pyramid/funnel segment\n * @private\n */\n TriangularBase.prototype.setLabelLocation = function (series, point, points) {\n var last = points.length - 1;\n var bottom = series.type === 'Funnel' ? points.length - 2 : points.length - 1;\n var x = (points[0].x + points[bottom].x) / 2;\n var right = (points[1].x + points[bottom - 1].x) / 2;\n point.region = new Rect(x, points[0].y, right - x, points[bottom].y - points[0].y);\n point.symbolLocation = {\n x: point.region.x + point.region.width / 2,\n y: point.region.y + point.region.height / 2\n };\n point.labelOffset = {\n x: point.symbolLocation.x - (points[0].x + points[last].x) / 2,\n y: point.symbolLocation.y - (points[0].y + points[last].y) / 2\n };\n };\n /**\n * Finds the path to connect the list of points\n * @private\n */\n TriangularBase.prototype.findPath = function (locations) {\n var path = 'M';\n for (var i = 0; i < locations.length; i++) {\n path += locations[i].x + ' ' + locations[i].y;\n if (i !== locations.length - 1) {\n path += ' L';\n }\n }\n return path;\n };\n /**\n * To calculate data-label bounds\n * @private\n */\n TriangularBase.prototype.defaultLabelBound = function (series, visible, position, chart) {\n var x = (chart.initialClipRect.width - series.triangleSize.width) / 2;\n var y = (chart.initialClipRect.height - series.triangleSize.height) / 2;\n var accumulationBound = new Rect(x, y, series.triangleSize.width, series.triangleSize.height);\n series.labelBound = new Rect(accumulationBound.x, accumulationBound.y, accumulationBound.width + accumulationBound.x, accumulationBound.height + accumulationBound.y);\n series.accumulationBound = accumulationBound;\n if (visible && position === 'Outside') {\n series.labelBound = new Rect(Infinity, Infinity, -Infinity, -Infinity);\n }\n };\n return TriangularBase;\n}(AccumulationBase));\nexport { TriangularBase };\n","/**\n * Defines the behavior of a funnel series\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { TriangularBase } from './triangular-base';\n/**\n * FunnelSeries module used to render `Funnel` Series.\n */\nvar FunnelSeries = /** @class */ (function (_super) {\n __extends(FunnelSeries, _super);\n function FunnelSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the path of a funnel segment\n */\n FunnelSeries.prototype.getSegmentData = function (point, series, chart) {\n var lineWidth;\n var topRadius;\n var bottomRadius;\n var endTop;\n var endBottom;\n var minRadius;\n var endMin;\n var bottomY;\n var area = series.triangleSize;\n var offset = 0;\n var extraSpace = (chart.initialClipRect.width - series.triangleSize.width) / 2;\n var emptySpaceAtLeft = extraSpace + chart.initialClipRect.x;\n var seriesTop = chart.initialClipRect.y + (chart.initialClipRect.height - area.height) / 2;\n //defines the top and bottom of a segment\n var top = point.yRatio * area.height;\n var bottom = top + point.heightRatio * area.height;\n var neckSize = series.neckSize;\n lineWidth = neckSize.width + (area.width - neckSize.width) * ((area.height - neckSize.height - top) /\n (area.height - neckSize.height));\n topRadius = (area.width / 2) - lineWidth / 2;\n //Calculating the middle slope change and bottom\n endTop = topRadius + lineWidth;\n if (bottom > area.height - neckSize.height || area.height === neckSize.height) {\n lineWidth = neckSize.width;\n }\n else {\n lineWidth = neckSize.width + (area.width - neckSize.width) *\n ((area.height - neckSize.height - bottom) / (area.height - neckSize.height));\n }\n bottomRadius = (area.width / 2) - (lineWidth / 2);\n endBottom = bottomRadius + lineWidth;\n if (top >= area.height - neckSize.height) {\n topRadius = bottomRadius = minRadius = (area.width / 2) - neckSize.width / 2;\n endTop = endBottom = endMin = (area.width / 2) + neckSize.width / 2;\n }\n else if (bottom > (area.height - neckSize.height)) {\n minRadius = bottomRadius = (area.width / 2) - lineWidth / 2;\n endMin = endBottom = minRadius + lineWidth;\n bottomY = area.height - neckSize.height;\n }\n var points = [];\n top += seriesTop;\n bottom += seriesTop;\n bottomY += seriesTop;\n var line1 = { x: emptySpaceAtLeft + offset + topRadius, y: top };\n var line2 = { x: emptySpaceAtLeft + offset + endTop, y: top };\n var line4 = { x: emptySpaceAtLeft + offset + endBottom, y: bottom };\n var line5 = { x: emptySpaceAtLeft + offset + bottomRadius, y: bottom };\n var line3 = { x: emptySpaceAtLeft + offset + endBottom, y: bottom };\n var line6 = { x: emptySpaceAtLeft + offset + bottomRadius, y: bottom };\n if (bottomY) {\n line3 = { x: emptySpaceAtLeft + offset + endMin, y: bottomY };\n line6 = { x: emptySpaceAtLeft + offset + minRadius, y: bottomY };\n }\n var polygon = [line1, line2, line3, line4, line5, line6];\n this.setLabelLocation(series, point, polygon);\n var direction = this.findPath(polygon);\n return direction;\n };\n /**\n * Renders a funnel segment\n * @private\n */\n FunnelSeries.prototype.renderPoint = function (point, series, chart, options) {\n var direction = this.getSegmentData(point, series, chart);\n point.midAngle = 0;\n options.d = direction;\n };\n /**\n * To get the module name of the funnel series.\n */\n FunnelSeries.prototype.getModuleName = function () {\n return 'FunnelSeries';\n };\n /**\n * To destroy the funnel series.\n * @return {void}\n * @private\n */\n FunnelSeries.prototype.destroy = function (accumulation) {\n /**\n * Destroys the funnel series\n */\n };\n return FunnelSeries;\n}(TriangularBase));\nexport { FunnelSeries };\n","/**\n * Defines the behavior of a pyramid series\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { TriangularBase } from './triangular-base';\n/**\n * PyramidSeries module used to render `Pyramid` Series.\n */\nvar PyramidSeries = /** @class */ (function (_super) {\n __extends(PyramidSeries, _super);\n function PyramidSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Defines the path of a pyramid segment\n */\n PyramidSeries.prototype.getSegmentData = function (point, series, chart) {\n var area = series.triangleSize;\n //top of th series\n var seriesTop = chart.initialClipRect.y + (chart.initialClipRect.height - area.height) / 2;\n var points = [];\n //consider, if the point is exploded\n var offset = 0;\n var extraSpace = (chart.initialClipRect.width - series.triangleSize.width) / 2;\n var emptySpaceAtLeft = extraSpace + chart.initialClipRect.x;\n //top and bottom\n var top = point.yRatio;\n var bottom = point.yRatio + point.heightRatio;\n //width of the top and bottom edge\n var topRadius = 0.5 * (1 - point.yRatio);\n var bottomRadius = 0.5 * (1 - bottom);\n top += seriesTop / area.height;\n bottom += seriesTop / area.height;\n var line1 = {\n x: emptySpaceAtLeft + offset + topRadius * area.width,\n y: top * area.height\n };\n var line2 = {\n x: emptySpaceAtLeft + offset + (1 - topRadius) * area.width,\n y: top * area.height\n };\n var line3 = {\n x: emptySpaceAtLeft + offset + (1 - bottomRadius) * area.width,\n y: bottom * area.height\n };\n var line4 = {\n x: emptySpaceAtLeft + offset + bottomRadius * area.width,\n y: bottom * area.height\n };\n var polygon = [line1, line2, line3, line4];\n this.setLabelLocation(series, point, polygon);\n var direction = this.findPath(polygon);\n return direction;\n };\n /**\n * Initializes the size of the pyramid segments\n * @private\n */\n PyramidSeries.prototype.initializeSizeRatio = function (points, series) {\n if (series.pyramidMode === 'Linear') {\n _super.prototype.initializeSizeRatio.call(this, points, series, true);\n }\n else {\n this.calculateSurfaceSegments(series);\n }\n };\n /**\n * Defines the size of the pyramid segments, the surface of that will reflect the values\n */\n PyramidSeries.prototype.calculateSurfaceSegments = function (series) {\n var count = series.points.length;\n var sumOfValues = series.sumOfPoints;\n var yRatio = 0;\n var y = [];\n var height = [];\n var gapRatio = Math.min(0, Math.max(series.gapRatio, 1));\n var gapHeight = gapRatio / (count - 1);\n var preSum = this.getSurfaceHeight(0, sumOfValues);\n var currY = 0;\n for (var i = 0; i < count; i++) {\n if (series.points[i].visible) {\n y[i] = currY;\n height[i] = this.getSurfaceHeight(currY, Math.abs(series.points[i].y));\n currY += height[i] + gapHeight * preSum;\n }\n }\n var coef = 1 / (currY - gapHeight * preSum);\n for (var i = 0; i < count; i++) {\n if (series.points[i].visible) {\n series.points[i].yRatio = coef * y[i];\n series.points[i].heightRatio = coef * height[i];\n }\n }\n };\n /**\n * Finds the height of pyramid segment\n */\n PyramidSeries.prototype.getSurfaceHeight = function (y, surface) {\n var result = this.solveQuadraticEquation(1, 2 * y, -surface);\n return result;\n };\n /**\n * Solves quadratic equation\n */\n PyramidSeries.prototype.solveQuadraticEquation = function (a, b, c) {\n var root1;\n var root2;\n var d = b * b - 4 * a * c;\n if (d >= 0) {\n var sd = Math.sqrt(d);\n root1 = (-b - sd) / (2 * a);\n root2 = (-b + sd) / (2 * a);\n return Math.max(root1, root2);\n }\n return 0;\n };\n /**\n * Renders a pyramid segment\n */\n PyramidSeries.prototype.renderPoint = function (point, series, chart, options) {\n var direction = this.getSegmentData(point, series, chart);\n point.midAngle = 0;\n options.d = direction;\n };\n /**\n * To get the module name of the Pyramid series.\n */\n PyramidSeries.prototype.getModuleName = function () {\n return 'PyramidSeries';\n };\n /**\n * To destroy the pyramid series\n * @return {void}\n * @private\n */\n PyramidSeries.prototype.destroy = function (accumulation) {\n /**\n * Destroys the pyramid series\n */\n };\n return PyramidSeries;\n}(TriangularBase));\nexport { PyramidSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * AccumulationChart legend\n */\nimport { extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { pointByIndex } from '../model/acc-base';\nimport { BaseLegend, LegendOptions } from '../../common/legend/legend';\nimport { Rect, measureText, textTrim } from '../../common/utils/helper';\n/**\n * AccumulationLegend module used to render `Legend` for Accumulation chart.\n */\nvar AccumulationLegend = /** @class */ (function (_super) {\n __extends(AccumulationLegend, _super);\n /**\n * Constructor for Accumulation Legend.\n * @param chart\n */\n function AccumulationLegend(chart) {\n var _this = _super.call(this, chart) || this;\n _this.library = _this;\n _this.titleRect = new Rect(0, chart.margin.top, 0, 0);\n return _this;\n }\n /**\n * Get the legend options.\n * @return {void}\n * @private\n */\n AccumulationLegend.prototype.getLegendOptions = function (chart, series) {\n this.legendCollections = [];\n for (var i = 0; i < 1; i++) {\n var seriesType = series[i].type;\n if (seriesType === 'Pie' || seriesType === 'Doughnut') {\n seriesType = (series[i].innerRadius !== '0' && series[i].innerRadius !== '0%') ?\n 'Doughnut' : 'Pie';\n }\n for (var _i = 0, _a = series[i].points; _i < _a.length; _i++) {\n var point = _a[_i];\n if (!isNullOrUndefined(point.x) && !isNullOrUndefined(point.y)) {\n this.legendCollections.push(new LegendOptions(point.x.toString(), point.color, series[i].legendShape, point.visible, seriesType, null, null, point.index, series[i].index));\n }\n }\n }\n };\n /**\n * To find legend bounds for accumulation chart.\n * @private\n */\n AccumulationLegend.prototype.getLegendBounds = function (availableSize, legendBounds, legend) {\n var extraWidth = 0;\n var extraHeight = 0;\n var padding = legend.padding;\n if (!this.isVertical) {\n extraHeight = !legend.height ? ((availableSize.height / 100) * 5) : 0;\n }\n else {\n extraWidth = !legend.width ? ((availableSize.width / 100) * 5) : 0;\n }\n legendBounds.width += extraWidth;\n legendBounds.height += extraHeight;\n var shapePadding = legend.shapePadding;\n var maximumWidth = 0;\n var shapeWidth = legend.shapeWidth;\n var rowWidth = 0;\n var rowCount = 0;\n var columnWidth = [];\n var columnHeight = 0;\n var legendWidth = 0;\n this.maxItemHeight = Math.max(measureText('MeasureText', legend.textStyle).height, legend.shapeHeight);\n var legendEventArgs;\n var render = false;\n for (var _i = 0, _a = this.legendCollections; _i < _a.length; _i++) {\n var legendOption = _a[_i];\n legendEventArgs = { fill: legendOption.fill, text: legendOption.text, shape: legendOption.shape,\n name: 'legendRender', cancel: false };\n this.chart.trigger('legendRender', legendEventArgs);\n legendOption.render = !legendEventArgs.cancel;\n legendOption.text = legendEventArgs.text;\n legendOption.fill = legendEventArgs.fill;\n legendOption.shape = legendEventArgs.shape;\n legendOption.textSize = measureText(legendOption.text, legend.textStyle);\n if (legendOption.render && legendOption.text !== '') {\n render = true;\n legendWidth = shapeWidth + shapePadding + legendOption.textSize.width + padding;\n if (this.isVertical) {\n ++rowCount;\n columnHeight = (rowCount * (this.maxItemHeight + padding)) + padding;\n if ((rowCount * (this.maxItemHeight + padding)) + padding > legendBounds.height) {\n columnHeight = Math.max(columnHeight, (rowCount * (this.maxItemHeight + padding)) + padding);\n rowWidth = rowWidth + maximumWidth;\n columnWidth.push(maximumWidth);\n this.totalPages = Math.max(rowCount, this.totalPages || 1);\n maximumWidth = 0;\n rowCount = 1;\n }\n maximumWidth = Math.max(legendWidth, maximumWidth);\n }\n else {\n rowWidth = rowWidth + legendWidth;\n if (legendBounds.width < (padding + rowWidth)) {\n maximumWidth = Math.max(maximumWidth, (rowWidth + padding - legendWidth));\n if (rowCount === 0 && (legendWidth !== rowWidth)) {\n rowCount = 1;\n }\n rowWidth = legendWidth;\n rowCount++;\n columnHeight = (rowCount * (this.maxItemHeight + padding)) + padding;\n }\n }\n }\n }\n if (this.isVertical) {\n rowWidth = rowWidth + maximumWidth;\n this.isPaging = legendBounds.width < (rowWidth + padding);\n columnHeight = Math.max(columnHeight, ((this.totalPages || 1) * (this.maxItemHeight + padding)) + padding);\n this.isPaging = this.isPaging && (this.totalPages > 1);\n if (columnWidth[columnWidth.length - 1] !== maximumWidth) {\n columnWidth.push(maximumWidth);\n }\n }\n else {\n this.isPaging = legendBounds.height < columnHeight;\n this.totalPages = this.totalRowCount = rowCount;\n columnHeight = Math.max(columnHeight, (this.maxItemHeight + padding) + padding);\n }\n this.maxColumns = 0; // initialization for max columns\n var width = this.isVertical ? this.getMaxColumn(columnWidth, legendBounds.width, padding, rowWidth + padding) :\n Math.max(rowWidth + padding, maximumWidth);\n if (render) {\n this.setBounds(width, columnHeight, legend, legendBounds);\n }\n else {\n this.setBounds(0, 0, legend, legendBounds);\n }\n };\n /**\n * To find maximum column size for legend\n */\n AccumulationLegend.prototype.getMaxColumn = function (columns, width, padding, rowWidth) {\n var maxPageColumn = padding;\n this.maxColumnWidth = Math.max.apply(null, columns);\n for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {\n var column = columns_1[_i];\n maxPageColumn += this.maxColumnWidth;\n this.maxColumns++;\n if (maxPageColumn + padding > width) {\n maxPageColumn -= this.maxColumnWidth;\n this.maxColumns--;\n break;\n }\n }\n this.isPaging = (maxPageColumn < rowWidth) && (this.totalPages > 1);\n if (maxPageColumn === padding) {\n maxPageColumn = width;\n }\n this.maxColumns = Math.max(1, this.maxColumns);\n this.maxWidth = maxPageColumn;\n return maxPageColumn;\n };\n /**\n * To find available width from legend x position.\n */\n AccumulationLegend.prototype.getAvailWidth = function (tx, width, legendX) {\n if (this.isVertical) {\n width = this.maxWidth;\n }\n return width - ((this.legend.padding * 2) + this.legend.shapeWidth + this.legend.shapePadding);\n };\n /**\n * To find legend rendering locations from legend options.\n * @private\n */\n AccumulationLegend.prototype.getRenderPoint = function (legendOption, start, textPadding, prevLegend, rect, count, firstLegend) {\n var padding = this.legend.padding;\n if (this.isVertical) {\n if (count === firstLegend || (prevLegend.location.y + (this.maxItemHeight * 1.5) + (padding * 2) > rect.y + rect.height)) {\n legendOption.location.x = prevLegend.location.x + ((count === firstLegend) ? 0 : this.maxColumnWidth);\n legendOption.location.y = start.y;\n this.pageXCollections.push(legendOption.location.x - (this.legend.shapeWidth / 2) - padding);\n this.totalPages++;\n }\n else {\n legendOption.location.x = prevLegend.location.x;\n legendOption.location.y = prevLegend.location.y + this.maxItemHeight + padding;\n }\n }\n else {\n var previousBound = (prevLegend.location.x + textPadding + prevLegend.textSize.width);\n if ((previousBound + (legendOption.textSize.width + textPadding)) > (rect.x + rect.width + this.legend.shapeWidth / 2)) {\n legendOption.location.y = (count === firstLegend) ? prevLegend.location.y :\n prevLegend.location.y + this.maxItemHeight + padding;\n legendOption.location.x = start.x;\n }\n else {\n legendOption.location.y = prevLegend.location.y;\n legendOption.location.x = (count === firstLegend) ? prevLegend.location.x : previousBound;\n }\n this.totalPages = this.totalRowCount;\n }\n var availablewidth = this.getAvailWidth(legendOption.location.x, this.legendBounds.width, this.legendBounds.x);\n legendOption.text = textTrim(+availablewidth.toFixed(4), legendOption.text, this.legend.textStyle);\n };\n /**\n * finding the smart legend place according to positions.\n * @return {void}\n * @private\n */\n AccumulationLegend.prototype.getSmartLegendLocation = function (labelBound, legendBound, margin) {\n var space;\n switch (this.position) {\n case 'Left':\n space = ((labelBound.x - legendBound.width) - margin.left) / 2;\n legendBound.x = (labelBound.x - legendBound.width) < margin.left ? legendBound.x :\n (labelBound.x - legendBound.width) - space;\n break;\n case 'Right':\n space = ((this.chart.availableSize.width - margin.right) - (labelBound.x + labelBound.width + legendBound.width)) / 2;\n legendBound.x = (labelBound.x + labelBound.width + legendBound.width) > (this.chart.availableSize.width - margin.right) ?\n legendBound.x : (labelBound.x + labelBound.width + space);\n break;\n case 'Top':\n this.getTitleRect(this.chart);\n space = ((labelBound.y - legendBound.height) - (this.titleRect.y + this.titleRect.height)) / 2;\n legendBound.y = (labelBound.y - legendBound.height) < margin.top ? legendBound.y :\n (labelBound.y - legendBound.height) - space;\n break;\n case 'Bottom':\n space = ((this.chart.availableSize.height - margin.bottom) - (labelBound.y + labelBound.height + legendBound.height)) / 2;\n legendBound.y = labelBound.y + labelBound.height + legendBound.height > (this.chart.availableSize.height - margin.bottom) ?\n legendBound.y : (labelBound.y + labelBound.height) + space;\n break;\n }\n };\n /**\n * To get title rect.\n */\n AccumulationLegend.prototype.getTitleRect = function (accumulation) {\n if (!accumulation.title) {\n return null;\n }\n var titleSize = measureText(accumulation.title, accumulation.titleStyle);\n this.titleRect = new Rect(accumulation.availableSize.width / 2 - titleSize.width / 2, accumulation.margin.top, titleSize.width, titleSize.height);\n };\n /**\n * To get legend by index\n */\n AccumulationLegend.prototype.legendByIndex = function (index, legendCollections) {\n for (var _i = 0, legendCollections_1 = legendCollections; _i < legendCollections_1.length; _i++) {\n var legend = legendCollections_1[_i];\n if (legend.pointIndex === index) {\n return legend;\n }\n }\n return null;\n };\n /**\n * To show or hide the legend on clicking the legend.\n * @return {void}\n */\n AccumulationLegend.prototype.click = function (event) {\n var targetId = event.target.id;\n var legendItemsId = [this.legendID + '_text_', this.legendID + '_shape_',\n this.legendID + '_shape_marker_'];\n var selectedDataIndexes = [];\n if (this.chart.accumulationSelectionModule) {\n selectedDataIndexes = extend([], this.chart.accumulationSelectionModule.selectedDataIndexes, null, true);\n }\n for (var _i = 0, legendItemsId_1 = legendItemsId; _i < legendItemsId_1.length; _i++) {\n var id = legendItemsId_1[_i];\n if (targetId.indexOf(id) > -1) {\n var pointIndex = parseInt(targetId.split(id)[1], 10);\n var currentSeries = this.chart.visibleSeries[0];\n var point = pointByIndex(pointIndex, currentSeries.points);\n var legendOption = this.legendByIndex(pointIndex, this.legendCollections);\n if (this.chart.legendSettings.toggleVisibility) {\n point.visible = !point.visible;\n legendOption.visible = point.visible;\n this.chart.removeSvg();\n if (point.visible) {\n currentSeries.sumOfPoints += point.y;\n }\n else {\n currentSeries.sumOfPoints -= point.y;\n }\n this.chart.refreshPoints(currentSeries.points);\n this.chart.renderElements();\n }\n else if (this.chart.accumulationSelectionModule) {\n this.chart.accumulationSelectionModule.legendSelection(this.chart, 0, pointIndex);\n }\n }\n }\n if (targetId.indexOf(this.legendID + '_pageup') > -1) {\n this.changePage(event, true);\n }\n else if (targetId.indexOf(this.legendID + '_pagedown') > -1) {\n this.changePage(event, false);\n }\n };\n /**\n * Get module name\n */\n AccumulationLegend.prototype.getModuleName = function () {\n return 'AccumulationLegend';\n };\n /**\n * To destroy the Legend.\n * @return {void}\n * @private\n */\n AccumulationLegend.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n return AccumulationLegend;\n}(BaseLegend));\nexport { AccumulationLegend };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * AccumulationChart DataLabel module file\n */\nimport { extend, createElement, getValue } from '@syncfusion/ej2-base';\nimport { ChartLocation, degreeToLocation, Rect, isOverlap, stringToNumber, getAngle, TextOption } from '../../common/utils/helper';\nimport { textTrim, subtractThickness, Thickness, getElement } from '../../common/utils/helper';\nimport { removeElement, measureText, RectOption, textElement, showTooltip } from '../../common/utils/helper';\nimport { PathOption, colorNameToHex, convertHexToColor, containsRect } from '../../common/utils/helper';\nimport { getSeriesFromIndex } from '../model/acc-base';\nimport { textRender } from '../../common/model/constants';\nimport { getFontStyle, createTemplate, measureElementRect, templateAnimate } from '../../common/utils/helper';\nimport { AccumulationBase } from './accumulation-base';\n/**\n * AccumulationDataLabel module used to render `dataLabel`.\n */\nvar AccumulationDataLabel = /** @class */ (function (_super) {\n __extends(AccumulationDataLabel, _super);\n function AccumulationDataLabel(accumulation) {\n var _this = _super.call(this, accumulation) || this;\n _this.id = accumulation.element.id + '_datalabel_Series_';\n if (accumulation.title) {\n var titleSize = measureText(accumulation.title, accumulation.titleStyle);\n _this.titleRect = new Rect(accumulation.availableSize.width / 2 - titleSize.width / 2, accumulation.margin.top, titleSize.width, titleSize.height);\n }\n return _this;\n }\n /**\n * Method to get datalabel text location.\n * @private\n */\n AccumulationDataLabel.prototype.getDataLabelPosition = function (point, dataLabel, textSize, points, parent, id) {\n var radius = this.isCircular() ? this.labelRadius : this.getLabelDistance(point, dataLabel);\n this.getLabelRegion(point, dataLabel.position, textSize, radius, this.marginValue);\n point.labelAngle = point.midAngle;\n point.labelPosition = dataLabel.position;\n if (this.accumulation.enableSmartLabels) {\n this.getSmartLabel(point, dataLabel, textSize, points, parent, id);\n }\n };\n /**\n * Method to get datalabel bound.\n */\n AccumulationDataLabel.prototype.getLabelRegion = function (point, position, textSize, labelRadius, margin, endAngle) {\n if (endAngle === void 0) { endAngle = 0; }\n var labelAngle = endAngle || point.midAngle;\n var space = 10;\n var location = degreeToLocation(labelAngle, labelRadius, this.isCircular() ? this.center :\n this.getLabelLocation(point, position));\n location.y = (position === 'Inside') ? (location.y - textSize.height / 2) : location.y;\n location.x = (position === 'Inside') ? (location.x - textSize.width / 2) : location.x;\n point.labelRegion = new Rect(location.x, location.y, textSize.width + (margin * 2), textSize.height + (margin * 2));\n if (position === 'Outside') {\n point.labelRegion.y -= point.labelRegion.height / 2;\n if (labelAngle >= 90 && labelAngle <= 270) {\n point.labelRegion.x -= (point.labelRegion.width + space);\n }\n else {\n point.labelRegion.x += space;\n }\n }\n };\n /**\n * Method to get datalabel smart position.\n */\n AccumulationDataLabel.prototype.getSmartLabel = function (point, dataLabel, textSize, points, parent, id) {\n var circular = this.isCircular();\n var labelRadius = circular ? this.radius : this.getLabelDistance(point, dataLabel);\n var connectorLength = circular ? (dataLabel.connectorStyle.length || '4%') :\n '0px';\n labelRadius += stringToNumber(connectorLength, labelRadius);\n var previousPoint = this.findPreviousPoint(points, point.index, point.labelPosition);\n if (dataLabel.position === 'Inside') {\n if (previousPoint && previousPoint.labelRegion && (isOverlap(point.labelRegion, previousPoint.labelRegion)\n || this.isOverlapping(point, points)) || !circular && !containsRect(point.region, point.labelRegion)) {\n point.labelPosition = 'Outside';\n if (!circular) {\n labelRadius = this.getLabelDistance(point, dataLabel);\n }\n this.getLabelRegion(point, point.labelPosition, textSize, labelRadius, this.marginValue);\n previousPoint = this.findPreviousPoint(points, point.index, point.labelPosition);\n if (previousPoint && (isOverlap(point.labelRegion, previousPoint.labelRegion) ||\n this.isConnectorLineOverlapping(point, previousPoint))) {\n this.setOuterSmartLabel(previousPoint, point, dataLabel.border.width, labelRadius, textSize, this.marginValue);\n }\n }\n }\n else {\n if (previousPoint && previousPoint.labelRegion && (isOverlap(point.labelRegion, previousPoint.labelRegion)\n || this.isOverlapping(point, points) || this.isConnectorLineOverlapping(point, previousPoint))) {\n this.setOuterSmartLabel(previousPoint, point, dataLabel.border.width, labelRadius, textSize, this.marginValue);\n }\n }\n if (this.isOverlapping(point, points) || (this.titleRect && point.labelRegion && isOverlap(point.labelRegion, this.titleRect))) {\n this.setPointVisibileFalse(point);\n }\n if (this.accumulation.accumulationLegendModule && point.labelVisible && point.labelRegion) {\n var rect = this.accumulation.accumulationLegendModule.legendBounds;\n var padding = this.accumulation.legendSettings.border.width / 2;\n this.textTrimming(point, new Rect(rect.x - padding, rect.y - padding, rect.width + (2 * padding), rect.height + (2 * padding)), dataLabel.font, this.accumulation.accumulationLegendModule.position);\n }\n if (point.labelVisible && point.labelRegion) {\n var position = this.isCircular() ? (point.labelRegion.x >= this.center.x) ? 'InsideRight' : 'InsideLeft' :\n 'InsideRight';\n this.textTrimming(point, this.areaRect, dataLabel.font, position);\n }\n if (point.labelVisible && point.labelRegion && ((point.labelRegion.y + point.labelRegion.height >\n this.areaRect.y + this.areaRect.height || point.labelRegion.y < this.areaRect.y) || (point.labelRegion.x < this.areaRect.x ||\n point.labelRegion.x + point.labelRegion.width > this.areaRect.x + this.areaRect.width))) {\n this.setPointVisibileFalse(point);\n }\n };\n /**\n * To find trimmed datalabel tooltip needed.\n * @return {void}\n * @private\n */\n AccumulationDataLabel.prototype.move = function (e, x, y, isTouch) {\n var _this = this;\n if (e.target.textContent.indexOf('...') > -1) {\n var targetId = e.target.id.split(this.id);\n if (targetId.length === 2) {\n var seriesIndex = parseInt(targetId[1].split('_text_')[0], 10);\n var pointIndex = parseInt(targetId[1].split('_text_')[1], 10);\n if (!isNaN(seriesIndex) && !isNaN(pointIndex)) {\n if (isTouch) {\n removeElement(this.accumulation.element.id + '_EJ2_Datalabel_Tooltip');\n }\n var point = getSeriesFromIndex(seriesIndex, (this.accumulation).visibleSeries).points[pointIndex];\n showTooltip(point.text || point.y.toString(), x, y, this.areaRect.width, this.accumulation.element.id + '_EJ2_Datalabel_Tooltip', getElement(this.accumulation.element.id + '_Secondary_Element'));\n }\n }\n }\n else {\n removeElement(this.accumulation.element.id + '_EJ2_Datalabel_Tooltip');\n }\n if (isTouch) {\n clearTimeout(this.clearTooltip);\n this.clearTooltip = setTimeout(function () { removeElement(_this.accumulation.element.id + '_EJ2_Datalabel_Tooltip'); }, 1000);\n }\n };\n /**\n * To find previous valid label point\n */\n AccumulationDataLabel.prototype.findPreviousPoint = function (points, index, position) {\n var point = points[0];\n for (var i = index - 1; i >= 0; i--) {\n point = points[i];\n if (point.visible && point.labelVisible && point.labelRegion && point.labelPosition === position) {\n return point;\n }\n }\n return null;\n };\n /**\n * To find current point datalabel is overlapping with other points\n */\n AccumulationDataLabel.prototype.isOverlapping = function (currentPoint, points) {\n for (var i = currentPoint.index - 1; i >= 0; i--) {\n if (points[i].visible && points[i].labelVisible && points[i].labelRegion && currentPoint.labelRegion &&\n currentPoint.labelVisible && isOverlap(currentPoint.labelRegion, points[i].labelRegion)) {\n return true;\n }\n }\n return false;\n };\n /**\n * To get text trimmed while exceeds the accumulation chart area.\n */\n AccumulationDataLabel.prototype.textTrimming = function (point, rect, font, position) {\n if (isOverlap(point.labelRegion, rect)) {\n var size = point.labelRegion.width;\n if (position === 'Right') {\n size = rect.x - point.labelRegion.x;\n }\n else if (position === 'Left') {\n size = point.labelRegion.x - (rect.x + rect.width);\n if (size < 0) {\n size += point.labelRegion.width;\n point.labelRegion.x = rect.x + rect.width;\n }\n }\n else if (position === 'InsideRight') {\n size = (rect.x + rect.width) - point.labelRegion.x;\n }\n else if (position === 'InsideLeft') {\n size = (point.labelRegion.x + point.labelRegion.width) - rect.x;\n if (size < point.labelRegion.width) {\n point.labelRegion.x = rect.x;\n }\n }\n else {\n this.setPointVisibileFalse(point);\n }\n if (point.labelVisible && point.labelRegion) {\n if (size < point.labelRegion.width) {\n point.label = textTrim(size - (this.marginValue * 2), point.label, font);\n point.labelRegion.width = size;\n }\n if (point.label.length === 3 && point.label.indexOf('...') > -1) {\n this.setPointVisibileFalse(point);\n }\n }\n }\n };\n /**\n * To set point label visible and region to disable.\n */\n AccumulationDataLabel.prototype.setPointVisibileFalse = function (point) {\n point.labelVisible = false;\n point.labelRegion = null;\n };\n /**\n * To set datalabel angle position for outside labels\n */\n AccumulationDataLabel.prototype.setOuterSmartLabel = function (previousPoint, point, border, labelRadius, textsize, margin) {\n if (!this.isCircular()) {\n this.setSmartLabelForSegments(point, previousPoint, labelRadius, textsize, margin);\n }\n else {\n var labelAngle = this.getOverlappedAngle(previousPoint.labelRegion, point.labelRegion, point.midAngle, border * 2);\n this.getLabelRegion(point, 'Outside', textsize, labelRadius, margin, labelAngle);\n if (labelAngle > point.endAngle) {\n this.setPointVisibileFalse(point);\n }\n point.labelAngle = labelAngle;\n while (point.labelVisible && (isOverlap(previousPoint.labelRegion, point.labelRegion) || labelAngle <= previousPoint.labelAngle\n || this.isConnectorLineOverlapping(point, previousPoint))) {\n if (labelAngle > point.endAngle) {\n this.setPointVisibileFalse(point);\n break;\n }\n point.labelAngle = labelAngle;\n this.getLabelRegion(point, 'Outside', textsize, labelRadius, margin, labelAngle);\n labelAngle += 0.1;\n }\n }\n };\n /**\n * Sets smart label positions for funnel and pyramid series\n */\n AccumulationDataLabel.prototype.setSmartLabelForSegments = function (point, prevPoint, distance, textSize, margin) {\n var textRegion = point.labelRegion;\n //let overlapWidth: number = prevPoint.labelRegion.x + prevPoint.labelRegion.width - textRegion.x;\n var overlapHeight = this.accumulation.type === 'Funnel' ?\n prevPoint.labelRegion.y - (textRegion.y + textRegion.height) :\n point.labelRegion.y - (prevPoint.labelRegion.y + prevPoint.labelRegion.height);\n if (overlapHeight < 0) {\n point.labelRegion.y += this.accumulation.type === 'Funnel' ? overlapHeight : -overlapHeight;\n }\n };\n /**\n * To find connector line overlapping.\n */\n AccumulationDataLabel.prototype.isConnectorLineOverlapping = function (point, previous) {\n var start = this.getLabelLocation(point);\n var end = new ChartLocation(0, 0);\n this.getEdgeOfLabel(point.labelRegion, point.labelAngle, end);\n var previousstart = this.getLabelLocation(previous);\n var previousend = new ChartLocation(0, 0);\n this.getEdgeOfLabel(previous.labelRegion, previous.labelAngle, previousend);\n return this.isLineRectangleIntersect(start, end, point.labelRegion) ||\n this.isLineRectangleIntersect(start, end, previous.labelRegion) ||\n this.isLineRectangleIntersect(previousstart, previousend, point.labelRegion);\n };\n /**\n * To find two rectangle intersect\n */\n AccumulationDataLabel.prototype.isLineRectangleIntersect = function (line1, line2, rect) {\n var rectPoints = [\n new ChartLocation(Math.round(rect.x), Math.round(rect.y)),\n new ChartLocation(Math.round((rect.x + rect.width)), Math.round(rect.y)),\n new ChartLocation(Math.round((rect.x + rect.width)), Math.round((rect.y + rect.height))),\n new ChartLocation(Math.round(rect.x), Math.round((rect.y + rect.height)))\n ];\n line1.x = Math.round(line1.x);\n line1.y = Math.round(line1.y);\n line2.x = Math.round(line2.x);\n line2.y = Math.round(line2.y);\n for (var i = 0; i < rectPoints.length; i++) {\n if (this.isLinesIntersect(line1, line2, rectPoints[i], rectPoints[(i + 1) % rectPoints.length])) {\n return true;\n }\n }\n return false;\n };\n /**\n * To find two line intersect\n */\n AccumulationDataLabel.prototype.isLinesIntersect = function (point1, point2, point11, point12) {\n var a1 = point2.y - point1.y;\n var b1 = point1.x - point2.x;\n var c1 = a1 * point1.x + b1 * point1.y;\n var a2 = point12.y - point11.y;\n var b2 = point11.x - point12.x;\n var c2 = a2 * point11.x + b2 * point11.y;\n var delta = a1 * b2 - a2 * b1;\n if (delta !== 0) {\n var x = (b2 * c1 - b1 * c2) / delta;\n var y = (a1 * c2 - a2 * c1) / delta;\n var lies = Math.min(point1.x, point2.x) <= x && x <= Math.max(point1.x, point2.x);\n lies = lies && Math.min(point1.y, point2.y) <= y && y <= Math.max(point1.y, point2.y);\n lies = lies && Math.min(point11.x, point12.x) <= x && x <= Math.max(point11.x, point12.x);\n lies = lies && Math.min(point11.y, point12.y) <= y && y <= Math.max(point11.y, point12.y);\n return lies;\n }\n return false;\n };\n /**\n * To get two rectangle overlapping angles.\n */\n AccumulationDataLabel.prototype.getOverlappedAngle = function (first, second, angle, padding) {\n var x = first.x;\n if (angle >= 90 && angle <= 270) {\n second.y = first.y - (padding + second.height / 2);\n x = first.x + first.width;\n }\n else {\n second.y = first.y + first.height + padding;\n }\n return getAngle(this.center, new ChartLocation(x, second.y));\n };\n /**\n * To get connector line path\n */\n AccumulationDataLabel.prototype.getConnectorPath = function (label, point, dataLabel, end) {\n if (end === void 0) { end = 0; }\n var connector = dataLabel.connectorStyle;\n var labelRadius = this.isCircular() ? this.labelRadius : this.getLabelDistance(point, dataLabel);\n var start = this.getConnectorStartPoint(point, connector);\n var labelAngle = end || point.midAngle;\n var middle = new ChartLocation(0, 0);\n var endPoint = this.getEdgeOfLabel(label, labelAngle, middle, connector.width);\n if (connector.type === 'Curve') {\n if (this.isCircular()) {\n var r = labelRadius - this.radius;\n middle = degreeToLocation(labelAngle, labelRadius - (r / 2), this.center);\n return 'M ' + start.x + ' ' + start.y + ' Q' + middle.x + ',' + middle.y + ' ' + endPoint.x + ',' + endPoint.y;\n }\n else {\n return this.getPolyLinePath(start, endPoint);\n }\n }\n else {\n return 'M ' + start.x + ' ' + start.y + ' L ' + middle.x + ' ' + middle.y + ' L ' + endPoint.x + ' ' + endPoint.y;\n }\n };\n /**\n * Finds the curved path for funnel/pyramid data label connectors\n */\n AccumulationDataLabel.prototype.getPolyLinePath = function (start, end) {\n var controlPoints = [start, end];\n if (start.y === end.y) {\n return 'M ' + start.x + ' ' + start.y + ' L ' + end.x + ' ' + end.y;\n }\n var path = 'M';\n for (var i = 0; i <= 16; i++) {\n var t = i / 16;\n var points = this.getBezierPoint(t, controlPoints, 0, 2);\n path += points.x + ',' + points.y;\n if (i !== 16) {\n path += ' L';\n }\n }\n return path;\n };\n /**\n * Finds the bezier point for funnel/pyramid data label connectors\n */\n AccumulationDataLabel.prototype.getBezierPoint = function (t, controlPoints, index, count) {\n if (count === 1) {\n return controlPoints[index];\n }\n var p0 = this.getBezierPoint(t, controlPoints, index, count - 1);\n var p1 = this.getBezierPoint(t, controlPoints, index + 1, count - 1);\n var x = (p0.x) ? p0.x : p0.x;\n var y = (p0.y) ? p0.y : p0.y;\n var x1 = (p1.x) ? p1.x : p1.x;\n var y1 = (p1.y) ? p1.y : p1.y;\n var x2 = (1 - t) * x + t * x1;\n var y2 = (1 - t) * y + t * y1;\n if (p0.x) {\n return { x: x2, y: y2 };\n }\n else {\n return { x: x2, y: y2 };\n }\n };\n /**\n * To get label edges based on the center and label rect position.\n */\n AccumulationDataLabel.prototype.getEdgeOfLabel = function (labelshape, angle, middle, border) {\n if (border === void 0) { border = 1; }\n var edge = new ChartLocation(labelshape.x, labelshape.y);\n if (angle >= 90 && angle <= 270) {\n edge.x += labelshape.width + border / 2;\n edge.y += labelshape.height / 2;\n middle.x = edge.x + 10;\n middle.y = edge.y;\n }\n else {\n edge.x -= border / 2;\n edge.y += labelshape.height / 2;\n middle.x = edge.x - 10;\n middle.y = edge.y;\n }\n return edge;\n };\n /**\n * Finds the distance between the label position and the edge/center of the funnel/pyramid\n */\n AccumulationDataLabel.prototype.getLabelDistance = function (point, dataLabel) {\n if (point.labelPosition && dataLabel.position !== point.labelPosition || dataLabel.connectorStyle.length) {\n var length_1 = stringToNumber(dataLabel.connectorStyle.length || '70px', this.accumulation.initialClipRect.width);\n if (length_1 < this.accumulation.initialClipRect.width) {\n return length_1;\n }\n }\n var position = point.labelPosition || dataLabel.position;\n var series = this.accumulation.visibleSeries[0];\n var extraSpace = (this.accumulation.initialClipRect.width - series.triangleSize.width) / 2;\n var labelLocation;\n switch (position) {\n case 'Inside':\n return 0;\n case 'Outside':\n labelLocation = point.symbolLocation.x + point.labelOffset.x;\n return this.accumulation.initialClipRect.width - labelLocation - extraSpace;\n }\n };\n /**\n * Finds the label position / beginning of the connector(ouside funnel labels)\n */\n AccumulationDataLabel.prototype.getLabelLocation = function (point, position) {\n if (position === void 0) { position = 'Outside'; }\n if (this.accumulation.type !== 'Pie') {\n position = point.labelPosition || position;\n var location_1 = {\n x: point.symbolLocation.x,\n y: point.symbolLocation.y - point.labelOffset.y\n };\n switch (position) {\n case 'Inside':\n location_1.y = point.region.y + point.region.height / 2;\n break;\n case 'Outside':\n location_1.x += point.labelOffset.x;\n }\n return location_1;\n }\n else {\n return degreeToLocation(point.midAngle, this.radius, this.center);\n }\n };\n /**\n * Finds the beginning of connector line\n */\n AccumulationDataLabel.prototype.getConnectorStartPoint = function (point, connector) {\n return this.isCircular() ? degreeToLocation(point.midAngle, this.radius - connector.width, this.center) :\n this.getLabelLocation(point);\n };\n /**\n * To find area rect based on margin, available size.\n * @private\n */\n AccumulationDataLabel.prototype.findAreaRect = function () {\n this.areaRect = new Rect(0, 0, this.accumulation.availableSize.width, this.accumulation.availableSize.height);\n var margin = this.accumulation.margin;\n subtractThickness(this.areaRect, new Thickness(margin.left, margin.right, margin.top, margin.bottom));\n };\n /**\n * To render the data labels from series points.\n */\n AccumulationDataLabel.prototype.renderDataLabel = function (point, dataLabel, parent, points, series, templateElement) {\n var id = this.accumulation.element.id + '_datalabel_Series_' + series + '_';\n var datalabelGroup = this.accumulation.renderer.createGroup({ id: id + 'g_' + point.index });\n point.label = point.originalText || point.y.toString();\n var border = { width: dataLabel.border.width, color: dataLabel.border.color };\n var argsFont = (extend({}, getValue('properties', dataLabel.font), null, true));\n var argsData = {\n cancel: false, name: textRender, series: this.accumulation.visibleSeries[0], point: point,\n text: point.label, border: border, color: dataLabel.fill, template: dataLabel.template, font: argsFont\n };\n this.accumulation.trigger(textRender, argsData);\n var isTemplate = argsData.template !== null;\n point.labelVisible = !argsData.cancel;\n point.text = point.label = argsData.text;\n this.marginValue = argsData.border.width ? (5 + argsData.border.width) : 1;\n // Template element\n var childElement = createElement('div', {\n id: this.accumulation.element.id + '_Series_' + 0 + '_DataLabel_' + point.index,\n styles: 'position: absolute;background-color:' + argsData.color + ';' +\n getFontStyle(dataLabel.font) + ';border:' + argsData.border.width + 'px solid ' + argsData.border.color + ';'\n });\n var textSize = isTemplate ? this.getTemplateSize(childElement, point, argsData) :\n measureText(point.label, dataLabel.font);\n textSize.height += 4; // 4 for calculation with padding for smart label shape\n textSize.width += 4;\n this.getDataLabelPosition(point, dataLabel, textSize, points, datalabelGroup, id);\n if (point.labelVisible) {\n this.correctLabelRegion(point.labelRegion, textSize);\n if (isTemplate) {\n this.setTemplateStyle(childElement, point, templateElement, dataLabel.font.color, argsData.color);\n }\n else {\n datalabelGroup.appendChild(this.accumulation.renderer.drawRectangle(new RectOption(id + 'shape_' + point.index, argsData.color, argsData.border, 1, point.labelRegion, dataLabel.rx, dataLabel.ry)));\n textElement(new TextOption(id + 'text_' + point.index, point.labelRegion.x + this.marginValue, point.labelRegion.y + (textSize.height * 3 / 4) + this.marginValue, 'start', point.label, '', 'auto'), argsData.font, argsData.font.color || this.getSaturatedColor(point, argsData.color), datalabelGroup);\n }\n if (this.accumulation.accumulationLegendModule && (dataLabel.position === 'Outside' || this.accumulation.enableSmartLabels)) {\n this.accumulation.visibleSeries[0].findMaxBounds(this.accumulation.visibleSeries[0].labelBound, point.labelRegion);\n }\n if (point.labelPosition === 'Outside') {\n var path = this.getConnectorPath(extend({}, point.labelRegion, null, true), point, dataLabel, point.labelAngle);\n var pathElement = this.accumulation.renderer.drawPath(new PathOption(id + 'connector_' + point.index, 'transparent', dataLabel.connectorStyle.width, dataLabel.connectorStyle.color || point.color, 1, dataLabel.connectorStyle.dashArray, path));\n datalabelGroup.appendChild(pathElement);\n }\n parent.appendChild(datalabelGroup);\n }\n };\n /**\n * To find the template element size\n * @param element\n * @param point\n * @param argsData\n */\n AccumulationDataLabel.prototype.getTemplateSize = function (element, point, argsData) {\n var clientRect;\n element = createTemplate(element, point.index, argsData.template, this.accumulation, point, this.accumulation.visibleSeries[0]);\n clientRect = measureElementRect(element);\n return { width: clientRect.width, height: clientRect.height };\n };\n /**\n * To set the template element style\n * @param childElement\n * @param point\n * @param parent\n * @param labelColor\n * @param fill\n */\n AccumulationDataLabel.prototype.setTemplateStyle = function (childElement, point, parent, labelColor, fill) {\n childElement.style.left = (point.labelRegion.x) + 'px';\n childElement.style.top = (point.labelRegion.y) + 'px';\n childElement.style.color = labelColor ||\n this.getSaturatedColor(point, fill);\n if (childElement.childElementCount) {\n parent.appendChild(childElement);\n this.doTemplateAnimation(this.accumulation, childElement);\n }\n };\n /**\n * To find saturated color for datalabel\n */\n AccumulationDataLabel.prototype.getSaturatedColor = function (point, color) {\n var saturatedColor;\n if (this.marginValue >= 1) {\n saturatedColor = color === 'transparent' ? this.getLabelBackground(point) : color;\n }\n else {\n saturatedColor = this.getLabelBackground(point);\n }\n saturatedColor = (saturatedColor === 'transparent') ? window.getComputedStyle(document.body, null).backgroundColor : saturatedColor;\n var rgbValue = convertHexToColor(colorNameToHex(saturatedColor));\n var contrast = Math.round((rgbValue.r * 299 + rgbValue.g * 587 + rgbValue.b * 114) / 1000);\n return contrast >= 128 ? 'black' : 'white';\n };\n /**\n * Animates the data label template.\n * @return {void}.\n * @private\n */\n AccumulationDataLabel.prototype.doTemplateAnimation = function (accumulation, element) {\n var series = accumulation.visibleSeries[0];\n var delay = series.animation.delay + series.animation.duration;\n if (series.animation.enable && accumulation.animateSeries) {\n element.style.visibility = 'hidden';\n templateAnimate(element, delay, 200, 'ZoomIn');\n }\n };\n /**\n * To find background color for the datalabel\n */\n AccumulationDataLabel.prototype.getLabelBackground = function (point) {\n return point.labelPosition === 'Outside' ?\n this.accumulation.background || this.accumulation.themeStyle.background : point.color;\n };\n /**\n * To correct the padding between datalabel regions.\n */\n AccumulationDataLabel.prototype.correctLabelRegion = function (labelRegion, textSize, padding) {\n if (padding === void 0) { padding = 4; }\n labelRegion.height -= padding;\n labelRegion.width -= padding;\n labelRegion.x += padding / 2;\n labelRegion.y += padding / 2;\n textSize.height -= padding;\n textSize.width -= padding;\n };\n /**\n * To get the dataLabel module name\n */\n AccumulationDataLabel.prototype.getModuleName = function () {\n return 'AccumulationDataLabel';\n };\n /**\n * To destroy the data label.\n * @return {void}\n * @private\n */\n AccumulationDataLabel.prototype.destroy = function (accumulation) {\n /**\n * Destroy method performed here\n */\n };\n return AccumulationDataLabel;\n}(AccumulationBase));\nexport { AccumulationDataLabel };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * AccumulationChart Tooltip file\n */\nimport { Browser } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { AccPointData, withInBounds, indexFinder } from '../../common/utils/helper';\nimport { BaseTooltip } from '../../common/user-interaction/tooltip';\n/**\n * `AccumulationTooltip` module is used to render tooltip for accumulation chart.\n */\nvar AccumulationTooltip = /** @class */ (function (_super) {\n __extends(AccumulationTooltip, _super);\n function AccumulationTooltip(accumulation) {\n var _this = _super.call(this, accumulation) || this;\n _this.accumulation = accumulation;\n _this.addEventListener();\n return _this;\n }\n /**\n * @hidden\n */\n AccumulationTooltip.prototype.addEventListener = function () {\n if (this.accumulation.isDestroyed) {\n return;\n }\n this.accumulation.on(Browser.isPointer ? 'pointerleave' : 'mouseleave', this.mouseLeaveHandler, this);\n this.accumulation.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);\n this.accumulation.on(Browser.touchEndEvent, this.mouseUpHandler, this);\n };\n AccumulationTooltip.prototype.mouseLeaveHandler = function (e) {\n this.removeTooltip(1000);\n };\n AccumulationTooltip.prototype.mouseUpHandler = function (e) {\n var control = this.accumulation;\n if (control.tooltip.enable && control.isTouch && withInBounds(control.mouseX, control.mouseY, control.initialClipRect)) {\n this.tooltip(e);\n this.removeTooltip(2000);\n }\n };\n AccumulationTooltip.prototype.mouseMoveHandler = function (e) {\n var control = this.accumulation;\n // Tooltip for chart series. \n if (control.tooltip.enable && withInBounds(control.mouseX, control.mouseY, control.initialClipRect)) {\n this.tooltip(e);\n }\n };\n /**\n * Renders the tooltip.\n * @param {PointerEvent} event - Mouse move event.\n * @return {void}\n */\n AccumulationTooltip.prototype.tooltip = function (event) {\n var svgElement = this.getElement(this.element.id + '_tooltip_svg');\n var isTooltip = svgElement && parseInt(svgElement.getAttribute('opacity'), 10) > 0;\n var tooltipDiv = this.getTooltipElement(isTooltip);\n this.renderSeriesTooltip(event, this.accumulation, !isTooltip, tooltipDiv);\n };\n AccumulationTooltip.prototype.renderSeriesTooltip = function (e, chart, isFirst, tooltipDiv) {\n var data = this.getPieData(e, chart, chart.mouseX, chart.mouseY);\n var rect = chart.initialClipRect;\n this.currentPoints = [];\n if (data.point && (!this.previousPoints[0] || (this.previousPoints[0].point !== data.point))) {\n if (this.pushData(data, isFirst, tooltipDiv, false)) {\n if (this.triggerEvent(data, isFirst, this.getTooltipText(data, chart.tooltip))) {\n this.createTooltip(chart, isFirst, this.findHeader(data), data.point.symbolLocation, data.series.clipRect, data.point, ['Circle'], 0, rect, null, data.point);\n }\n else {\n this.removeHighlight(this.control);\n this.getElement(this.element.id + '_tooltip').remove();\n }\n this.isRemove = true;\n }\n }\n else {\n if (!data.point && this.isRemove) {\n this.removeTooltip(1000);\n this.isRemove = false;\n }\n }\n };\n AccumulationTooltip.prototype.getPieData = function (e, chart, x, y) {\n var target = e.target;\n var id = indexFinder(target.id, true);\n if (!isNaN(id.series)) {\n var seriesIndex = id.series;\n var pointIndex = id.point;\n if (!isNullOrUndefined(seriesIndex) && !isNaN(seriesIndex) && !isNullOrUndefined(pointIndex) && !isNaN(pointIndex)) {\n var series = this.getSeriesFromIndex(seriesIndex, chart.visibleSeries);\n if (series.enableTooltip) {\n return new AccPointData(series.points[pointIndex], series);\n }\n }\n }\n return new AccPointData(null, null);\n };\n /**\n * To get series from index\n */\n AccumulationTooltip.prototype.getSeriesFromIndex = function (index, visibleSeries) {\n return visibleSeries[0];\n };\n AccumulationTooltip.prototype.getTooltipText = function (data, tooltip) {\n var series = data.series;\n var format = tooltip.format ? tooltip.format : '${point.x} :
${point.y} ';\n return this.parseTemplate(data.point, series, format);\n };\n AccumulationTooltip.prototype.findHeader = function (data) {\n if (this.header === '') {\n return '';\n }\n this.header = this.parseTemplate(data.point, data.series, this.header);\n if (this.header.replace(/
/g, '').replace(/<\\/b>/g, '').trim() !== '') {\n return this.header;\n }\n return '';\n };\n AccumulationTooltip.prototype.parseTemplate = function (point, series, format) {\n var value;\n var textValue;\n for (var _i = 0, _a = Object.keys(point); _i < _a.length; _i++) {\n var dataValue = _a[_i];\n value = new RegExp('${point' + '.' + dataValue + '}', 'gm');\n format = format.replace(value.source, point[dataValue]);\n }\n for (var _b = 0, _c = Object.keys(Object.getPrototypeOf(series)); _b < _c.length; _b++) {\n var dataValue = _c[_b];\n value = new RegExp('${series' + '.' + dataValue + '}', 'gm');\n textValue = series[dataValue];\n format = format.replace(value.source, textValue);\n }\n return format;\n };\n /**\n * Get module name\n */\n AccumulationTooltip.prototype.getModuleName = function () {\n return 'AccumulationTooltip';\n };\n /**\n * To destroy the Tooltip.\n * @return {void}\n * @private\n */\n AccumulationTooltip.prototype.destroy = function (chart) {\n /**\n * Destroy method calling here\n */\n };\n return AccumulationTooltip;\n}(BaseTooltip));\nexport { AccumulationTooltip };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { extend } from '@syncfusion/ej2-base';\nimport { indexFinder } from '../../common/utils/helper';\nimport { pointByIndex } from '../model/acc-base';\nimport { Index } from '../../common/model/base';\nimport { BaseSelection } from '../../common/user-interaction/selection';\n/**\n * `AccumulationSelection` module handles the selection for accumulation chart.\n * @private\n */\nvar AccumulationSelection = /** @class */ (function (_super) {\n __extends(AccumulationSelection, _super);\n function AccumulationSelection(accumulation) {\n var _this = _super.call(this, accumulation) || this;\n _this.renderer = accumulation.renderer;\n return _this;\n }\n /**\n * To initialize the private variables\n */\n AccumulationSelection.prototype.initPrivateVariables = function (accumulation) {\n this.styleId = accumulation.element.id + '_ej2_chart_selection';\n this.unselected = accumulation.element.id + '_ej2_deselected';\n this.selectedDataIndexes = [];\n this.rectPoints = null;\n };\n /**\n * Invoke selection for rendered chart.\n * @param {AccumulationChart} chart - Define the chart to invoke the selection.\n * @return {void}\n */\n AccumulationSelection.prototype.invokeSelection = function (accumulation) {\n this.initPrivateVariables(accumulation);\n this.series = extend({}, accumulation.visibleSeries, null, true);\n this.seriesStyles();\n this.selectDataIndex(this.concatIndexes(accumulation.selectedDataIndexes, this.selectedDataIndexes), accumulation);\n };\n /**\n * To get series selection style by series.\n */\n AccumulationSelection.prototype.generateStyle = function (series) {\n return (series.selectionStyle || this.styleId + '_series_' + series.index);\n };\n /**\n * To get elements by index, series\n */\n AccumulationSelection.prototype.findElements = function (accumulation, series, index) {\n return [this.getElementByIndex(index)];\n };\n /**\n * To get series point element by index\n */\n AccumulationSelection.prototype.getElementByIndex = function (index) {\n var elementId = this.control.element.id + '_Series_' + index.series + '_Point_' + index.point;\n return document.getElementById(elementId);\n };\n /**\n * To calculate selected elements on mouse click or touch\n * @private\n */\n AccumulationSelection.prototype.calculateSelectedElements = function (accumulation, event) {\n if (event.target.id.indexOf(accumulation.element.id + '_') === -1) {\n return;\n }\n if (event.target.id.indexOf('_Series_') > -1 || event.target.id.indexOf('_datalabel_') > -1) {\n this.performSelection(indexFinder(event.target.id), accumulation, event.target);\n }\n };\n /**\n * To perform the selection process based on index and element.\n */\n AccumulationSelection.prototype.performSelection = function (index, accumulation, element) {\n element = element.id.indexOf('datalabel') > -1 ?\n accumulation.getSeriesElement().childNodes[index.series].childNodes[index.point]\n : element;\n switch (accumulation.selectionMode) {\n case 'Point':\n if (!isNaN(index.point)) {\n this.selection(accumulation, index, [element]);\n this.blurEffect(accumulation.element.id, accumulation.visibleSeries);\n }\n break;\n }\n };\n /**\n * To select the element by index. Adding or removing selection style class name.\n */\n AccumulationSelection.prototype.selection = function (accumulation, index, selectedElements) {\n if (!accumulation.isMultiSelect) {\n this.removeMultiSelectEelments(accumulation, this.selectedDataIndexes, index, accumulation.series);\n }\n var className = selectedElements[0] && (selectedElements[0].getAttribute('class') || '');\n if (selectedElements[0] && className.indexOf(this.getSelectionClass(selectedElements[0].id)) > -1) {\n this.removeStyles(selectedElements, index);\n this.addOrRemoveIndex(this.selectedDataIndexes, index);\n }\n else {\n this.applyStyles(selectedElements, index);\n this.addOrRemoveIndex(this.selectedDataIndexes, index, true);\n }\n };\n /**\n * To redraw the selection process on accumulation chart refresh.\n * @private\n */\n AccumulationSelection.prototype.redrawSelection = function (accumulation, oldMode) {\n var selectedDataIndexes = extend([], this.selectedDataIndexes, null, true);\n this.removeSelectedElements(accumulation, this.selectedDataIndexes);\n this.blurEffect(accumulation.element.id, accumulation.visibleSeries);\n this.selectDataIndex(selectedDataIndexes, accumulation);\n };\n /**\n * To remove the selected elements style classes by indexes.\n */\n AccumulationSelection.prototype.removeSelectedElements = function (accumulation, indexes) {\n var seriesgroup = accumulation.getSeriesElement();\n for (var _i = 0, indexes_1 = indexes; _i < indexes_1.length; _i++) {\n var index = indexes_1[_i];\n this.removeStyles([this.getElementByIndex(index)], index);\n }\n };\n /**\n * To perform the selection for legend elements.\n * @private\n */\n AccumulationSelection.prototype.legendSelection = function (accumulation, series, pointIndex) {\n var element = accumulation.getSeriesElement().childNodes[series].childNodes[pointIndex];\n var seriesStyle = this.generateStyle(accumulation.visibleSeries[series]);\n var seriesElements = accumulation.getSeriesElement().childNodes[series].childNodes[pointIndex];\n this.selection(accumulation, new Index(series, pointIndex), [seriesElements]);\n this.blurEffect(accumulation.element.id, accumulation.visibleSeries);\n };\n /**\n * To select the element by selected data indexes.\n */\n AccumulationSelection.prototype.selectDataIndex = function (indexes, accumulation) {\n var element;\n for (var _i = 0, indexes_2 = indexes; _i < indexes_2.length; _i++) {\n var index = indexes_2[_i];\n element = this.getElementByIndex(index);\n if (element) {\n this.performSelection(index, accumulation, element);\n }\n }\n };\n /**\n * To remove the selection styles for multi selection process.\n */\n AccumulationSelection.prototype.removeMultiSelectEelments = function (accumulation, index, currentIndex, seriesCollection) {\n var series;\n for (var i = 0; i < index.length; i++) {\n series = seriesCollection[index[i].series];\n if (!this.checkEquals(index[i], currentIndex)) {\n this.removeStyles(this.findElements(accumulation, series, index[i]), index[i]);\n index.splice(i, 1);\n i--;\n }\n }\n };\n /**\n * To apply the opacity effect for accumulation chart series elements.\n */\n AccumulationSelection.prototype.blurEffect = function (pieId, visibleSeries) {\n var visibility = this.checkPointVisibility(this.selectedDataIndexes); // legend click scenario\n for (var _i = 0, visibleSeries_1 = visibleSeries; _i < visibleSeries_1.length; _i++) {\n var series = visibleSeries_1[_i];\n if (series.visible) {\n this.checkSelectionElements(document.getElementById(pieId + '_SeriesCollection'), this.generateStyle(series), visibility);\n }\n }\n };\n /**\n * To check selection elements by style class name.\n */\n AccumulationSelection.prototype.checkSelectionElements = function (element, className, visibility) {\n var children = (element.childNodes[0].childNodes);\n var legendShape;\n var elementClass;\n var parentClass;\n for (var i = 0; i < children.length; i++) {\n elementClass = children[i].getAttribute('class') || '';\n parentClass = children[i].parentNode.getAttribute('class') || '';\n if (elementClass.indexOf(className) === -1 && parentClass.indexOf(className) === -1 && visibility) {\n this.addSvgClass(children[i], this.unselected);\n }\n else {\n this.removeSvgClass(children[i], this.unselected);\n }\n if (this.control.accumulationLegendModule && this.control.legendSettings.visible) {\n legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + i);\n if (legendShape) {\n if (elementClass.indexOf(className) === -1 && parentClass.indexOf(className) === -1 && visibility) {\n this.addSvgClass(legendShape, this.unselected);\n }\n else {\n this.removeSvgClass(legendShape, this.unselected);\n }\n }\n }\n }\n };\n /**\n * To apply selection style for elements.\n */\n AccumulationSelection.prototype.applyStyles = function (elements, index) {\n for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {\n var element = elements_1[_i];\n var legendShape = void 0;\n if (element) {\n if (this.control.accumulationLegendModule && this.control.legendSettings.visible) {\n legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + index.point);\n this.removeSvgClass(legendShape, this.unselected);\n this.addSvgClass(legendShape, this.getSelectionClass(legendShape.id));\n }\n this.removeSvgClass(element.parentNode, this.unselected);\n this.removeSvgClass(element, this.unselected);\n this.addSvgClass(element, this.getSelectionClass(element.id));\n }\n }\n };\n /**\n * To get selection style class name by id\n */\n AccumulationSelection.prototype.getSelectionClass = function (id) {\n return this.generateStyle(this.control.series[indexFinder(id).series]);\n };\n /**\n * To remove selection style for elements.\n */\n AccumulationSelection.prototype.removeStyles = function (elements, index) {\n var legendShape;\n for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {\n var element = elements_2[_i];\n if (element) {\n if (this.control.accumulationLegendModule && this.control.legendSettings.visible) {\n legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + index.point);\n this.removeSvgClass(legendShape, this.getSelectionClass(legendShape.id));\n }\n this.removeSvgClass(element, this.getSelectionClass(element.id));\n }\n }\n };\n /**\n * To apply or remove selected elements index.\n */\n AccumulationSelection.prototype.addOrRemoveIndex = function (indexes, index, add) {\n for (var i = 0; i < indexes.length; i++) {\n if (this.checkEquals(indexes[i], index)) {\n indexes.splice(i, 1);\n i--;\n }\n }\n if (add) {\n indexes.push(index);\n }\n };\n /**\n * To check two index, point and series are equal\n */\n AccumulationSelection.prototype.checkEquals = function (first, second) {\n return ((first.point === second.point) && (first.series === second.series));\n };\n /**\n * To check selected points are visibility\n */\n AccumulationSelection.prototype.checkPointVisibility = function (selectedDataIndexes) {\n var visible = false;\n for (var _i = 0, selectedDataIndexes_1 = selectedDataIndexes; _i < selectedDataIndexes_1.length; _i++) {\n var data = selectedDataIndexes_1[_i];\n if (pointByIndex(data.point, this.control.visibleSeries[0].points).visible) {\n visible = true;\n break;\n }\n }\n return visible;\n };\n /**\n * Get module name.\n */\n AccumulationSelection.prototype.getModuleName = function () {\n return 'AccumulationSelection';\n };\n /**\n * To destroy the selection.\n * @return {void}\n * @private\n */\n AccumulationSelection.prototype.destroy = function (accumulation) {\n // Destroy method performed here\n };\n return AccumulationSelection;\n}(BaseSelection));\nexport { AccumulationSelection };\n","/**\n * AccumulationChart annotation properties\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { AnnotationBase } from '../../common/annotation/annotation';\nimport { appendElement } from '../../common/utils/helper';\nimport { createElement } from '@syncfusion/ej2-base';\n/**\n * `AccumulationAnnotation` module handles the annotation for accumulation chart.\n */\nvar AccumulationAnnotation = /** @class */ (function (_super) {\n __extends(AccumulationAnnotation, _super);\n /**\n * Constructor for accumulation chart annotation.\n * @private.\n */\n function AccumulationAnnotation(control) {\n var _this = _super.call(this, control) || this;\n _this.pie = control;\n return _this;\n }\n /**\n * Method to render the annotation for accumulation chart\n * @param element\n */\n AccumulationAnnotation.prototype.renderAnnotations = function (element) {\n var _this = this;\n this.annotations = this.pie.annotations;\n this.parentElement = createElement('div', {\n id: this.pie.element.id + '_Annotation_Collections'\n });\n this.annotations.map(function (annotation, index) {\n _this.processAnnotation(annotation, index, _this.parentElement);\n });\n appendElement(this.parentElement, element);\n };\n /**\n * Get module name.\n */\n AccumulationAnnotation.prototype.getModuleName = function () {\n // Returns te module name\n return 'Annotation';\n };\n /**\n * To destroy the annotation.\n * @return {void}\n * @private\n */\n AccumulationAnnotation.prototype.destroy = function (control) {\n // Destroy method performed here\n };\n return AccumulationAnnotation;\n}(AnnotationBase));\nexport { AccumulationAnnotation };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { firstToLowerCase, RectOption, Rect, measureText } from '../../chart/index';\nimport { DataPoint } from '../utils/helper';\nimport { getValue, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { getSeriesColor } from '../../common/model/theme';\nimport { NiceInterval, Size, PathOption } from '../../chart/index';\nimport { Data } from '../../common/model/data';\n/**\n * To render Chart series\n */\nvar RangeSeries = /** @class */ (function (_super) {\n __extends(RangeSeries, _super);\n function RangeSeries(range) {\n var _this = _super.call(this) || this;\n _this.dataSource = range.dataSource;\n _this.xName = range.xName;\n _this.yName = range.yName;\n _this.query = range.query;\n _this.xMin = Infinity;\n _this.xMax = -Infinity;\n _this.yMin = Infinity;\n _this.yMax = -Infinity;\n return _this;\n }\n /**\n * To render light weight and data manager process\n * @param control\n */\n RangeSeries.prototype.renderChart = function (control) {\n var _this = this;\n var dataSource;\n var query;\n this.seriesLength = 0;\n control.rangeSlider.points = [];\n if (control.series.length) {\n control.series.map(function (series) {\n dataSource = series.dataSource || control.dataSource;\n query = series.query || control.query;\n series.points = [];\n _this.processDataSource(dataSource, query, control, series);\n });\n }\n else {\n this.processDataSource(control.dataSource, control.query, control);\n }\n };\n RangeSeries.prototype.processDataSource = function (dataSource, query, control, series) {\n var _this = this;\n if (isNullOrUndefined(query) && !isNullOrUndefined(dataSource)) {\n this.dataManagerSuccess({ result: dataSource, count: dataSource.length }, control, series);\n return;\n }\n control.dataModule = new Data(dataSource, query);\n var dataManager = control.dataModule.getData(control.dataModule.generateQuery().requiresCount());\n dataManager.then(function (e) { return _this.dataManagerSuccess(e, control, series); });\n };\n /**\n * data manager process calculated here\n * @param e\n */\n RangeSeries.prototype.dataManagerSuccess = function (e, control, series) {\n var viewData = e.result !== '' ? e.result : [];\n this.processJsonData(viewData, control, Object.keys(viewData).length, series);\n this.seriesLength += series ? 1 : this.seriesLength;\n if (!series || this.seriesLength === control.series.length) {\n this.processXAxis(control);\n this.calculateGroupingBounds(control);\n this.processYAxis(control);\n control.renderChart();\n }\n };\n /**\n * Process JSON data from data source\n * @param control\n * @param len\n */\n RangeSeries.prototype.processJsonData = function (viewData, control, len, series) {\n var i = 0;\n var point;\n var xName = (series && series.xName) || control.xName;\n var yName = (series && series.yName) || control.yName;\n while (i < len) {\n point = new DataPoint(getValue(xName, viewData[i]), getValue(yName, viewData[i]));\n point.xValue = +point.x;\n point.yValue = +point.y;\n if (series) {\n series.points.push(point);\n }\n this.xMin = Math.min(this.xMin, point.xValue);\n this.yMin = Math.min(this.yMin, point.yValue);\n this.xMax = Math.max(this.xMax, point.xValue);\n this.yMax = Math.max(this.yMax, point.yValue);\n control.rangeSlider.points.push(point);\n i++;\n }\n };\n RangeSeries.prototype.processXAxis = function (control) {\n var axisModule;\n var axis = {\n minimum: control.minimum, maximum: control.maximum,\n interval: control.interval, valueType: control.valueType,\n isInversed: control.enableRtl, labelFormat: control.labelFormat,\n logBase: control.logBase, skeleton: control.skeleton, skeletonType: control.skeletonType\n };\n this.xAxis = axis;\n this.xAxis.intervalType = control.intervalType;\n this.xAxis.maximumLabels = 3;\n this.xAxis.skeleton = control.skeleton;\n this.xAxis.intervalDivs = [10, 5, 2, 1];\n this.xAxis.rect = control.bounds;\n this.xAxis.visibleLabels = [];\n this.xAxis.orientation = 'Horizontal';\n axisModule = control[firstToLowerCase(control.valueType) + 'Module'];\n axisModule.min = this.xMin;\n axisModule.max = this.xMax;\n axisModule.getActualRange(this.xAxis, control.bounds);\n if (this.xAxis.valueType !== 'Logarithmic') {\n axisModule.updateActualRange(this.xAxis, this.xAxis.actualRange.min, this.xAxis.actualRange.max, this.xAxis.actualRange.interval);\n }\n this.xAxis.actualRange.delta = this.xAxis.actualRange.max - this.xAxis.actualRange.min;\n this.xAxis.visibleRange = this.xAxis.actualRange;\n axisModule.calculateVisibleLabels(this.xAxis, control);\n };\n /**\n * Process yAxis for range navigator\n * @param control\n */\n RangeSeries.prototype.processYAxis = function (control) {\n var axis = {\n majorGridLines: { width: 0 }, rangePadding: 'None',\n majorTickLines: { width: 0 }, labelStyle: { size: '0' },\n visible: false, valueType: 'Double', minimum: null, maximum: null,\n interval: null\n };\n this.yAxis = axis;\n this.yAxis.rect = control.bounds;\n this.yAxis.maximumLabels = 3;\n this.yAxis.intervalDivs = [10, 5, 2, 1];\n this.yAxis.orientation = 'Vertical';\n control.doubleModule.min = this.yMin;\n control.doubleModule.max = this.yMax;\n control.doubleModule.getActualRange(this.yAxis, control.bounds);\n control.doubleModule.updateActualRange(this.yAxis, this.yAxis.actualRange.min, this.yAxis.actualRange.max, this.yAxis.actualRange.interval);\n this.yAxis.actualRange.delta = this.yAxis.actualRange.max - this.yAxis.actualRange.min;\n this.yAxis.visibleRange = this.yAxis.actualRange;\n };\n /**\n * Process Light weight control\n * @param control\n * @private\n */\n RangeSeries.prototype.renderSeries = function (control) {\n var _this = this;\n var chartGroup = control.renderer.createGroup({ id: control.element.id + '_chart' });\n var colors = getSeriesColor(control.theme);\n control.series.map(function (series, index) {\n series.xAxis = _this.xAxis;\n series.yAxis = _this.yAxis;\n series.chart = control;\n series.index = index;\n series.xAxis.isInversed = control.enableRtl;\n series.interior = series.fill || colors[index % colors.length];\n _this.createSeriesElement(control, series, index);\n control[firstToLowerCase(series.type) + 'SeriesModule'].render(series, _this.xAxis, _this.yAxis, false);\n chartGroup.appendChild(series.seriesElement);\n if (series.animation.enable && control.animateSeries) {\n control[firstToLowerCase(series.type) + 'SeriesModule'].doAnimation(series);\n }\n });\n control.svgObject.appendChild(chartGroup);\n if (control.series.length) {\n this.drawSeriesBorder(control, chartGroup);\n }\n };\n RangeSeries.prototype.createSeriesElement = function (control, series, index) {\n var elementId = control.element.id;\n series.clipRect = new Rect(this.xAxis.rect.x, this.yAxis.rect.y, this.xAxis.rect.width, this.yAxis.rect.height);\n series.clipRectElement = control.renderer.drawClipPath(new RectOption(elementId + '_RangeSeriesClipRect_' + index, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: 0, y: 0,\n width: series.clipRect.width,\n height: series.clipRect.height\n }));\n series.seriesElement = control.renderer.createGroup({\n 'id': elementId + 'SeriesGroup' + index,\n 'transform': 'translate(' + series.clipRect.x + ',' + (series.clipRect.y) + ')',\n 'clip-path': 'url(#' + elementId + '_RangeSeriesClipRect_' + index + ')'\n });\n series.seriesElement.appendChild(series.clipRectElement);\n };\n RangeSeries.prototype.calculateGroupingBounds = function (control) {\n var padding = control.margin.bottom;\n var labelHeight = measureText('string', control.labelStyle).height;\n this.calculateDateTimeNiceInterval(this.xAxis, new Size(control.bounds.width, control.bounds.height), this.xMin, this.xMax, false);\n if (control.enableGrouping && control.valueType === 'DateTime'\n && (this.xAxis.actualIntervalType !== 'Years' || !control.series.length)) {\n control.bounds.height -= (control.labelPosition === 'Outside' || control.series.length === 0) ? padding + labelHeight :\n (labelHeight + 2 * padding);\n }\n if (!control.series.length) {\n control.bounds.y += control.bounds.height / 4;\n control.bounds.height = control.bounds.height / 2;\n }\n };\n RangeSeries.prototype.drawSeriesBorder = function (control, chartElement) {\n var options = new PathOption(control.element.id + '_SeriesBorder', 'transparent', control.navigatorBorder.width, control.navigatorBorder.color, 1, '', ('M ' + (control.bounds.x) + ' ' + (control.bounds.y) +\n ' L ' + (control.bounds.x + control.bounds.width) + ' ' + control.bounds.y +\n ' L ' + (control.bounds.x + control.bounds.width) + ' ' + (control.bounds.y + control.bounds.height) +\n ' L ' + (control.bounds.x) + ' ' + (control.bounds.y + control.bounds.height) + 'Z'));\n var htmlObject = control.renderer.drawPath(options);\n control.svgObject.appendChild(htmlObject);\n };\n return RangeSeries;\n}(NiceInterval));\nexport { RangeSeries };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { measureText, TextOption, Rect, valueToCoefficient, textElement, PathOption, firstToLowerCase, } from '../../common/utils/helper';\nimport { DateTime } from '../../chart/index';\nimport { VisibleLabels } from '../../chart/index';\n/**\n * class for axis\n */\nvar RangeNavigatorAxis = /** @class */ (function (_super) {\n __extends(RangeNavigatorAxis, _super);\n function RangeNavigatorAxis(range) {\n var _this = _super.call(this) || this;\n _this.firstLevelLabels = [];\n _this.secondLevelLabels = [];\n _this.rangeNavigator = range;\n return _this;\n }\n /**\n * To render grid lines of axis\n */\n RangeNavigatorAxis.prototype.renderGridLines = function () {\n var pointX = 0;\n var control = this.rangeNavigator;\n var majorGridLines = control.majorGridLines;\n var majorTickLines = control.majorTickLines;\n var majorGrid = '';\n var majorTick = '';\n var rect = control.bounds;\n var chartAxis = control.chartSeries.xAxis;\n var labelLength;\n var range = chartAxis.visibleRange;\n var disabledColor = (control.disableRangeSelector) ? 'transparent' : null;\n this.gridLines = control.renderer.createGroup({ id: control.element.id + '_GridLines' });\n var tick = (control.tickPosition === 'Outside' || control.series.length === 0) ?\n rect.y + rect.height + majorTickLines.height : rect.y + rect.height - majorTickLines.height;\n //Gridlines\n this.firstLevelLabels = [];\n chartAxis.labelStyle = control.labelStyle;\n chartAxis.skeleton = control.skeleton;\n chartAxis.skeletonType = control.skeletonType;\n chartAxis.isChart = false;\n if (control.valueType === 'DateTime') {\n this.calculateDateTimeNiceInterval(chartAxis, rect, chartAxis.doubleRange.start, chartAxis.doubleRange.end, chartAxis.isChart);\n this.actualIntervalType = chartAxis.actualIntervalType;\n this.findAxisLabels(chartAxis);\n }\n this.firstLevelLabels = chartAxis.visibleLabels;\n this.lowerValues = [];\n labelLength = chartAxis.visibleLabels.length;\n for (var i = 0; i < labelLength; i++) {\n this.lowerValues.push(this.firstLevelLabels[i].value);\n pointX = (valueToCoefficient(this.firstLevelLabels[i].value, chartAxis) * rect.width) + rect.x;\n if (pointX >= rect.x && (rect.x + rect.width) >= pointX) {\n majorGrid = majorGrid.concat('M ' + pointX + ' ' + (control.bounds.y + control.bounds.height) +\n ' L ' + pointX + ' ' + control.bounds.y + ' ');\n majorTick = majorTick.concat('M ' + (pointX) + ' ' + (rect.y + rect.height) +\n ' L ' + (pointX) + ' ' + tick + ' ');\n }\n }\n var options = new PathOption(control.element.id + '_MajorGridLine', 'transparent', majorGridLines.width, control.series.length ? disabledColor || majorGridLines.color || control.themeStyle.gridLineColor : 'transparent', 1, majorGridLines.dashArray, majorGrid);\n this.gridLines.appendChild(control.renderer.drawPath(options));\n options = new PathOption(control.element.id + '_MajorTickLine', 'transparent', majorTickLines.width, disabledColor || majorTickLines.color || control.themeStyle.gridLineColor, 1, majorGridLines.dashArray, majorTick);\n this.gridLines.appendChild(control.renderer.drawPath(options));\n };\n /**\n * To render of axis labels\n */\n RangeNavigatorAxis.prototype.renderAxisLabels = function () {\n var axis = this.rangeNavigator.chartSeries.xAxis;\n var control = this.rangeNavigator;\n var pointY;\n var rect = control.bounds;\n var labelElement = control.renderer.createGroup({ id: control.element.id + '_AxisLabels' });\n var firstLevelElement = control.renderer.createGroup({ id: control.element.id + '_FirstLevelAxisLabels' });\n var secondLevelElement = control.renderer.createGroup({ id: control.element.id + '_SecondLevelAxisLabels' });\n var secondaryAxis = axis;\n pointY = this.findLabelY(control, false);\n this.placeAxisLabels(axis, pointY, '_AxisLabel_', control, firstLevelElement);\n secondaryAxis.intervalType = secondaryAxis.actualIntervalType = (control.groupBy ||\n this.getSecondaryLabelType(axis.actualIntervalType));\n if (control.enableGrouping && control.valueType === 'DateTime' && this.actualIntervalType !== 'Years') {\n secondaryAxis.visibleRange.interval = 1;\n secondaryAxis.visibleLabels = [];\n this.findAxisLabels(secondaryAxis);\n this.secondLevelLabels = secondaryAxis.visibleLabels;\n pointY = this.findLabelY(control, true);\n var border = this.placeAxisLabels(secondaryAxis, pointY, '_SecondaryLabel_', control, secondLevelElement);\n var path = new PathOption(control.element.id + '_SecondaryMajorLines', 'transparent', control.majorTickLines.width, control.majorTickLines.color || control.themeStyle.gridLineColor, 1, control.majorGridLines.dashArray, border);\n this.gridLines.appendChild(control.renderer.drawPath(path));\n }\n control.chartSeries.xAxis.visibleLabels = control.chartSeries.xAxis.visibleLabels.concat(secondaryAxis.visibleLabels);\n labelElement.appendChild(firstLevelElement);\n labelElement.appendChild(secondLevelElement);\n //gridlines and axis label append to element\n control.svgObject.appendChild(this.gridLines);\n control.svgObject.appendChild(labelElement);\n };\n /**\n * To find secondary level label type\n * @param type\n */\n RangeNavigatorAxis.prototype.getSecondaryLabelType = function (type) {\n var types = ['Years', 'Quarter', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'];\n return (type === 'Years' ? 'Years' : types[types.indexOf(type) - 1]);\n };\n /**\n * To find labels for date time axis\n * @param axis\n */\n RangeNavigatorAxis.prototype.findAxisLabels = function (axis) {\n axis.visibleLabels = [];\n var start = new Date(axis.visibleRange.min);\n var nextInterval;\n var interval = this.rangeNavigator.interval ? this.rangeNavigator.interval : 1;\n switch (axis.actualIntervalType) {\n case 'Years':\n start = new Date(start.getFullYear().toString());\n break;\n case 'Quarter':\n if (start.getMonth() <= 2) {\n start = new Date(start.getFullYear(), 0, 1);\n }\n else if (start.getMonth() <= 5) {\n start = new Date(start.getFullYear(), 3, 1);\n }\n else if (start.getMonth() <= 8) {\n start = new Date(start.getFullYear(), 6, 1);\n }\n else {\n start = new Date(start.getFullYear(), 9, 1);\n }\n break;\n case 'Months':\n start = new Date(start.getFullYear(), start.getMonth());\n break;\n case 'Weeks':\n start = new Date(start.getFullYear(), start.getMonth(), start.getDate() - start.getDay());\n break;\n case 'Days':\n start = new Date(start.getFullYear(), start.getMonth(), start.getDate());\n break;\n case 'Hours':\n start = new Date(start.getFullYear(), start.getMonth(), start.getDate(), start.getHours());\n break;\n case 'Minutes':\n start = new Date(start.getFullYear(), start.getMonth(), start.getDate(), start.getHours(), start.getMinutes());\n break;\n case 'Seconds':\n start = new Date(start.getFullYear(), start.getMonth(), start.getDate(), start.getHours(), start.getMinutes(), start.getSeconds());\n break;\n }\n nextInterval = start.getTime();\n this.rangeNavigator.format = this.rangeNavigator.intl.getDateFormat({\n format: axis.labelFormat, type: firstToLowerCase(axis.skeletonType), skeleton: this.getSkeleton(axis)\n });\n while (nextInterval < axis.visibleRange.max) {\n axis.visibleLabels.push(new VisibleLabels(this.dateFormats(this.rangeNavigator.format(new Date(nextInterval)), axis, axis.visibleLabels.length), nextInterval, this.rangeNavigator.labelStyle));\n nextInterval = this.increaseDateTimeInterval(axis, nextInterval, interval).getTime();\n }\n };\n /**\n * To find date time formats for Quarter and week interval type\n * @param text\n * @param axis\n * @param index\n */\n RangeNavigatorAxis.prototype.dateFormats = function (text, axis, index) {\n var changedText = text;\n var isFirstLevel = this.rangeNavigator.enableGrouping && this.firstLevelLabels.length === 0;\n switch (axis.actualIntervalType) {\n case 'Quarter':\n if (text.indexOf('Jan') > -1) {\n changedText = !isFirstLevel ? text.replace('Jan', 'Quarter1') : 'Quarter1';\n }\n else if (text.indexOf('Apr') > -1) {\n changedText = !isFirstLevel ? text.replace('Apr', 'Quarter2') : 'Quarter2';\n }\n else if (text.indexOf('Jul') > -1) {\n changedText = !isFirstLevel ? text.replace('Jul', 'Quarter3') : 'Quarter3';\n }\n else if (text.indexOf('Oct') > -1) {\n changedText = !isFirstLevel ? text.replace('Oct', 'Quarter4') : 'Quarter4';\n }\n break;\n case 'Weeks':\n changedText = 'Week' + ++index;\n break;\n default:\n changedText = text;\n break;\n }\n return changedText;\n };\n /**\n * To find the y co-ordinate for axis labels\n * @param control - rangeNavigator\n * @param isSecondary sets true if the axis is secondary axis\n */\n RangeNavigatorAxis.prototype.findLabelY = function (control, isSecondary) {\n var pointY;\n var reference = control.bounds.y + control.bounds.height;\n var tickHeight = control.majorTickLines.height;\n var textHeight = measureText('Quarter1 2011', control.labelStyle).height;\n var padding = 8;\n if ((control.labelPosition === 'Outside' && control.tickPosition === 'Outside') || control.series.length === 0) {\n pointY = reference + tickHeight + padding + textHeight * 0.75;\n }\n else if (control.labelPosition === 'Inside' && control.tickPosition === 'Inside') {\n pointY = reference - tickHeight - padding;\n }\n else if (control.labelPosition === 'Inside' && control.tickPosition === 'Outside') {\n pointY = reference - padding;\n }\n else {\n pointY = reference + padding + (textHeight * 0.75);\n }\n if (isSecondary) {\n padding = 15;\n if (control.labelPosition === 'Outside' || control.series.length === 0) {\n pointY += padding + textHeight * 0.75;\n }\n else {\n pointY = (control.tickPosition === 'Outside' || control.series.length === 0) ?\n reference + tickHeight + padding + textHeight * 0.75 : reference + padding + textHeight * 0.75;\n }\n }\n return pointY;\n };\n /**\n * It places the axis labels and returns border for secondary axis labels\n * @param axis axis for the lables placed\n * @param pointY y co-ordinate for axis labels\n * @param id id for the axis elements\n * @param control range navigator\n * @param labelElement parent element in which axis labels appended\n */\n RangeNavigatorAxis.prototype.placeAxisLabels = function (axis, pointY, id, control, labelElement) {\n var maxLabels = axis.visibleLabels.length;\n var label;\n var prevLabel;\n var pointX;\n var rect = control.bounds;\n var border = '';\n var pointXGrid;\n var disabledColor = (control.disableRangeSelector) ? 'transparent' : null;\n var prevX = control.enableRtl ? (rect.x + rect.width) : rect.x;\n var intervalType = axis.actualIntervalType;\n var intervalInTime = control.valueType === 'DateTime' ?\n maxLabels > 1 ? (axis.visibleLabels[1].value - axis.visibleLabels[0].value) :\n (axis.visibleRange.max - axis.visibleLabels[0].value) / 2 : 0;\n if (control.valueType === 'DateTime' && (intervalType === 'Quarter' || intervalType === 'Weeks')) {\n this.findSuitableFormat(axis, control);\n }\n for (var i = 0, len = maxLabels; i < len; i++) {\n label = axis.visibleLabels[i];\n label.size = measureText(label.text, axis.labelStyle);\n if (control.secondaryLabelAlignment === 'Middle') {\n pointX = (valueToCoefficient((label.value + intervalInTime / 2), axis) * rect.width) + rect.x;\n }\n else if ((id.indexOf('Secondary') > -1)) {\n pointX = this.findAlignment(axis, i);\n }\n pointXGrid = (valueToCoefficient((label.value), axis) * rect.width) + rect.x;\n //edgelabelPlacements\n if ((i === 0 || (i === axis.visibleLabels.length - 1 && control.enableRtl)) && pointX < rect.x) {\n pointX = rect.x + label.size.width / 2;\n }\n if ((i === axis.visibleLabels.length - 1 || (i === 0 && control.enableRtl)) &&\n ((pointX + label.size.width) > (rect.x + rect.width))) {\n pointX = rect.x + rect.width - label.size.width / 2;\n }\n //secondary axis grid lines\n if (id.indexOf('_SecondaryLabel_') > -1) {\n if (pointX >= rect.x && (rect.x + rect.width) >= pointX) {\n border = border.concat('M ' + pointXGrid + ' ' + pointY +\n ' L ' + pointXGrid + ' ' + (pointY - label.size.height));\n }\n }\n //smart axis label position,\n if (control.labelIntersectAction === 'Hide' &&\n i !== 0 && this.isIntersect(axis, pointX, label.size.width, prevX, prevLabel.size.width)) {\n continue;\n }\n //labelrender event\n var argsData = void 0;\n var labelStyle = control.labelStyle;\n var style = {\n size: labelStyle.size, color: disabledColor || labelStyle.color || control.themeStyle.labelFontColor,\n fontFamily: labelStyle.fontFamily,\n fontStyle: labelStyle.fontStyle || control.labelStyle.fontStyle,\n fontWeight: labelStyle.fontWeight || control.labelStyle.fontWeight,\n opacity: labelStyle.opacity || control.labelStyle.opacity,\n textAlignment: labelStyle.textAlignment || control.labelStyle.textAlignment,\n textOverflow: labelStyle.textOverflow || control.labelStyle.textOverflow\n };\n argsData = {\n cancel: false, name: 'labelRender',\n text: label.text, value: label.value, labelStyle: style,\n region: new Rect(pointX, pointY, label.size.width, label.size.height)\n };\n control.trigger('labelRender', argsData);\n if (!argsData.cancel) {\n control.labels.push(argsData);\n }\n else {\n continue;\n }\n textElement(new TextOption(this.rangeNavigator.element.id + id + i, pointX, pointY, 'middle', argsData.text), argsData.labelStyle, argsData.labelStyle.color || control.themeStyle.labelFontColor, labelElement).setAttribute('style', axis.valueType === 'DateTime' ? 'cursor: pointer' : 'cursor: default');\n prevX = pointX;\n prevLabel = label;\n }\n return border;\n };\n /**\n * To check label is intersected with successive label or not\n */\n RangeNavigatorAxis.prototype.isIntersect = function (axis, currentX, currentWidth, prevX, prevWidth) {\n return (axis.isInversed) ? (currentX + currentWidth / 2 > prevX - prevWidth / 2) :\n (currentX - currentWidth / 2 < prevX + prevWidth / 2);\n };\n /**\n * To find suitable label format for Quarter and week Interval types\n * @param axis\n * @param control\n */\n RangeNavigatorAxis.prototype.findSuitableFormat = function (axis, control) {\n var labels = axis.visibleLabels;\n var labelLength = labels.length;\n var bounds = control.bounds;\n var prevX;\n var currentX;\n var interval = control.valueType === 'DateTime' ?\n labelLength > 1 ? (labels[1].value - labels[0].value) : axis.visibleRange.interval\n : 0;\n for (var i = 0; i < labelLength; i++) {\n currentX = (valueToCoefficient((labels[i].value + interval / 2), axis) * bounds.width) + bounds.x;\n labels[i].size = measureText(labels[i].text, axis.labelStyle);\n //edgelabelPlacements\n if (i === 0 && currentX < bounds.x) {\n currentX = bounds.x + labels[i].size.width / 2;\n }\n if (axis.actualIntervalType === 'Quarter') {\n if (i !== 0) {\n if ((labels[i].text.indexOf('Quarter') > -1) &&\n (this.isIntersect(axis, currentX, labels[i].size.width, prevX, labels[i - 1].size.width))) {\n labels.every(function (label) {\n label.text = label.text.toString().replace('Quarter', 'QTR');\n return true;\n });\n axis.visibleLabels = labels;\n this.findSuitableFormat(axis, control);\n }\n else {\n if (this.isIntersect(axis, currentX, labels[i].size.width, prevX, labels[i - 1].size.width)) {\n labels.every(function (label) {\n label.text = label.text.toString().replace('QTR', 'Q');\n return true;\n });\n axis.visibleLabels = labels;\n }\n }\n }\n }\n else if (axis.actualIntervalType === 'Weeks') {\n if ((i !== 0) && ((labels[i].text.indexOf('Week') > -1) &&\n (this.isIntersect(axis, currentX, labels[i].size.width, prevX, labels[i - 1].size.width)))) {\n labels.every(function (label) {\n label.text = label.text.toString().replace('Week', 'W');\n return true;\n });\n axis.visibleLabels = labels;\n }\n }\n prevX = currentX;\n }\n };\n /**\n * Alignment position for secondary level labels in date time axis\n * @param axis\n * @param index\n */\n RangeNavigatorAxis.prototype.findAlignment = function (axis, index) {\n var label = axis.visibleLabels[index];\n var nextLabel = axis.visibleLabels[index + 1];\n var bounds = this.rangeNavigator.bounds;\n return (this.rangeNavigator.secondaryLabelAlignment === 'Near' ?\n (valueToCoefficient((label.value), axis) * bounds.width) + bounds.x + label.size.width / 2 :\n (valueToCoefficient((nextLabel ? nextLabel.value : axis.visibleRange.max), axis) * bounds.width) + bounds.x - label.size.width);\n };\n return RangeNavigatorAxis;\n}(DateTime));\nexport { RangeNavigatorAxis };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { ChildProperty, Property, Complex, Collection } from '@syncfusion/ej2-base';\nimport { Border, Animation, Font } from '../../common/model/base';\nimport { Rect } from '../../index';\nimport { RangeNavigatorTheme } from '../utils/theme';\n/**\n * Series class for the range navigator\n */\nvar RangeNavigatorSeries = /** @class */ (function (_super) {\n __extends(RangeNavigatorSeries, _super);\n function RangeNavigatorSeries() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.clipRect = new Rect(0, 0, 0, 0);\n return _this;\n }\n __decorate([\n Property(null)\n ], RangeNavigatorSeries.prototype, \"dataSource\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigatorSeries.prototype, \"xName\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigatorSeries.prototype, \"yName\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigatorSeries.prototype, \"query\", void 0);\n __decorate([\n Property('Line')\n ], RangeNavigatorSeries.prototype, \"type\", void 0);\n __decorate([\n Complex({ enable: false }, Animation)\n ], RangeNavigatorSeries.prototype, \"animation\", void 0);\n __decorate([\n Complex({ color: 'transparent', width: 2 }, Border)\n ], RangeNavigatorSeries.prototype, \"border\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigatorSeries.prototype, \"fill\", void 0);\n __decorate([\n Property(1)\n ], RangeNavigatorSeries.prototype, \"width\", void 0);\n __decorate([\n Property('0')\n ], RangeNavigatorSeries.prototype, \"dashArray\", void 0);\n return RangeNavigatorSeries;\n}(ChildProperty));\nexport { RangeNavigatorSeries };\n/**\n * Thumb settings\n */\nvar ThumbSettings = /** @class */ (function (_super) {\n __extends(ThumbSettings, _super);\n function ThumbSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], ThumbSettings.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], ThumbSettings.prototype, \"height\", void 0);\n __decorate([\n Complex({ width: 1, color: null }, Border)\n ], ThumbSettings.prototype, \"border\", void 0);\n __decorate([\n Property(null)\n ], ThumbSettings.prototype, \"fill\", void 0);\n __decorate([\n Property('Circle')\n ], ThumbSettings.prototype, \"type\", void 0);\n return ThumbSettings;\n}(ChildProperty));\nexport { ThumbSettings };\n/**\n * Style settings\n */\nvar StyleSettings = /** @class */ (function (_super) {\n __extends(StyleSettings, _super);\n function StyleSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({}, ThumbSettings)\n ], StyleSettings.prototype, \"thumb\", void 0);\n __decorate([\n Property(null)\n ], StyleSettings.prototype, \"selectedRegionColor\", void 0);\n __decorate([\n Property(null)\n ], StyleSettings.prototype, \"unselectedRegionColor\", void 0);\n return StyleSettings;\n}(ChildProperty));\nexport { StyleSettings };\n/**\n * button settings in period selector\n */\nvar Periods = /** @class */ (function (_super) {\n __extends(Periods, _super);\n function Periods() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Years')\n ], Periods.prototype, \"intervalType\", void 0);\n __decorate([\n Property(1)\n ], Periods.prototype, \"interval\", void 0);\n __decorate([\n Property(null)\n ], Periods.prototype, \"text\", void 0);\n __decorate([\n Property(false)\n ], Periods.prototype, \"selected\", void 0);\n return Periods;\n}(ChildProperty));\nexport { Periods };\n/**\n * Period Selector Settings\n */\nvar PeriodSelectorSettings = /** @class */ (function (_super) {\n __extends(PeriodSelectorSettings, _super);\n function PeriodSelectorSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(43)\n ], PeriodSelectorSettings.prototype, \"height\", void 0);\n __decorate([\n Property('Bottom')\n ], PeriodSelectorSettings.prototype, \"position\", void 0);\n __decorate([\n Collection([], Periods)\n ], PeriodSelectorSettings.prototype, \"periods\", void 0);\n return PeriodSelectorSettings;\n}(ChildProperty));\nexport { PeriodSelectorSettings };\n/*\n * Configures the ToolTips in the chart.\n */\nvar RangeTooltipSettings = /** @class */ (function (_super) {\n __extends(RangeTooltipSettings, _super);\n function RangeTooltipSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], RangeTooltipSettings.prototype, \"enable\", void 0);\n __decorate([\n Property(0.85)\n ], RangeTooltipSettings.prototype, \"opacity\", void 0);\n __decorate([\n Property(null)\n ], RangeTooltipSettings.prototype, \"fill\", void 0);\n __decorate([\n Property(null)\n ], RangeTooltipSettings.prototype, \"format\", void 0);\n __decorate([\n Complex(RangeNavigatorTheme.tooltipLabelFont, Font)\n ], RangeTooltipSettings.prototype, \"textStyle\", void 0);\n __decorate([\n Property(null)\n ], RangeTooltipSettings.prototype, \"template\", void 0);\n __decorate([\n Complex({ color: '#cccccc', width: 0.5 }, Border)\n ], RangeTooltipSettings.prototype, \"border\", void 0);\n __decorate([\n Property('OnDemand')\n ], RangeTooltipSettings.prototype, \"displayMode\", void 0);\n return RangeTooltipSettings;\n}(ChildProperty));\nexport { RangeTooltipSettings };\n","export var Theme;\n(function (Theme) {\n /** @private */\n Theme.axisLabelFont = {\n size: '12px',\n fontWeight: 'Normal',\n color: null,\n fontStyle: 'Normal',\n fontFamily: 'Roboto, Segoe UI, Noto, Sans-serif'\n };\n /** @private */\n Theme.smithchartTitleFont = {\n size: '15px',\n fontWeight: 'Normal',\n color: null,\n fontStyle: 'Normal',\n fontFamily: 'Roboto, Segoe UI, Noto, Sans-serif'\n };\n /** @private */\n Theme.smithchartSubtitleFont = {\n size: '13px',\n fontWeight: 'Normal',\n color: null,\n fontStyle: 'Normal',\n fontFamily: 'Roboto, Segoe UI, Noto, Sans-serif'\n };\n /** @private */\n Theme.dataLabelFont = {\n size: '12px',\n fontWeight: 'Normal',\n color: null,\n fontStyle: 'Normal',\n fontFamily: 'Roboto, Segoe UI, Noto, Sans-serif'\n };\n /** @private */\n Theme.legendLabelFont = {\n size: '13px',\n fontWeight: 'Normal',\n color: null,\n fontStyle: 'Normal',\n fontFamily: 'Roboto, Segoe UI, Noto, Sans-serif'\n };\n})(Theme || (Theme = {}));\n/** @private */\nexport function getSeriesColor(theme) {\n var palette;\n switch (theme) {\n case 'Highcontrast':\n palette = ['#79ECE4', '#E98272', '#DFE6B6', '#C6E773', '#BA98FF',\n '#FA83C3', '#00C27A', '#43ACEF', '#D681EF', '#D8BC6E'];\n break;\n case 'Fabric':\n palette = ['#4472c4', '#ed7d31', '#ffc000', '#70ad47', '#5b9bd5',\n '#c1c1c1', '#6f6fe2', '#e269ae', '#9e480e', '#997300'];\n break;\n case 'Bootstrap':\n palette = ['#a16ee5', '#f7ce69', '#55a5c2', '#7ddf1e', '#ff6ea6',\n '#7953ac', '#b99b4f', '#407c92', '#5ea716', '#b91c52'];\n break;\n default:\n palette = ['#00bdae', '#404041', '#357cd2', '#e56590', '#f8b883',\n '#70ad47', '#dd8abd', '#7f84e8', '#7bb4eb', '#ea7a57'];\n break;\n }\n return palette;\n}\n/** @private */\nexport function getThemeColor(theme) {\n var style;\n switch (theme) {\n case 'Highcontrast':\n style = {\n axisLabel: '#ffffff',\n axisLine: '#ffffff',\n majorGridLine: '#BFBFBF',\n minorGridLine: '#969696',\n chartTitle: '#ffffff',\n legendLabel: '#ffffff',\n background: '#000000',\n areaBorder: '#ffffff',\n tooltipFill: '#ffffff',\n dataLabel: '#ffffff',\n tooltipBoldLabel: '#000000',\n tooltipLightLabel: '#000000',\n tooltipHeaderLine: '#969696',\n };\n break;\n default:\n style = {\n axisLabel: '#686868',\n axisLine: '#b5b5b5',\n majorGridLine: '#dbdbdb',\n minorGridLine: '#eaeaea',\n chartTitle: '#424242',\n legendLabel: '#353535',\n background: '#FFFFFF',\n areaBorder: 'Gray',\n tooltipFill: 'rgba(0, 8, 22, 0.75)',\n dataLabel: '#424242',\n tooltipBoldLabel: '#ffffff',\n tooltipLightLabel: '#dbdbdb',\n tooltipHeaderLine: '#ffffff'\n };\n break;\n }\n return style;\n}\n","import { Browser, createElement } from '@syncfusion/ej2-base';\nimport { RectOption } from '../../common/utils/helper';\nimport { getXLocation, getExactData, getRangeValueXByPoint, getNearestValue } from '../utils/helper';\nimport { drawSymbol, PathOption, linear } from '../../chart/index';\nimport { Animation } from '@syncfusion/ej2-base';\n/**\n * Class for slider\n */\nvar RangeSlider = /** @class */ (function () {\n function RangeSlider(range) {\n this.control = range;\n this.points = [];\n this.isIOS = Browser.isIos || Browser.isIos7;\n var thumb = range.navigatorStyleSettings.thumb;\n this.thumbVisible = (range.themeStyle.thumbWidth !== 0 && range.themeStyle.thumbHeight !== 0);\n this.elementId = range.element.id;\n this.thumpPadding = range.themeStyle.thumbWidth / 2;\n this.addEventListener();\n this.thumbColor = range.disableRangeSelector ? 'transparent' :\n (thumb.fill || range.themeStyle.thumbBackground);\n }\n /**\n * Render Slider elements for range navigator\n * @param range\n */\n RangeSlider.prototype.render = function (range) {\n var renderer = range.renderer;\n var style = range.navigatorStyleSettings;\n var disabledColor = (range.disableRangeSelector) ? 'transparent' : null;\n var sliderGroup = renderer.createGroup({\n 'id': this.elementId + '_sliders',\n style: (range.disableRangeSelector) ? 'pointer-events:none;' : ''\n });\n var option = new RectOption(this.elementId + '_leftUnSelectedArea', disabledColor || style.unselectedRegionColor || range.themeStyle.unselectedRectColor, { width: 0 }, 1, {\n x: range.bounds.x, y: range.bounds.y,\n width: range.bounds.width / 3,\n height: range.bounds.height\n });\n this.leftUnSelectedElement = renderer.drawRectangle(option);\n option.id = this.elementId + '_rightUnSelectedArea';\n this.rightUnSelectedElement = renderer.drawRectangle(option);\n option.id = this.elementId + '_SelectedArea';\n option.fill = disabledColor || style.selectedRegionColor || range.themeStyle.selectedRegionColor;\n this.selectedElement = renderer.drawRectangle(option);\n this.selectedElement.setAttribute('style', 'cursor: -webkit-grab');\n this.leftSlider = renderer.createGroup({\n 'id': this.elementId + '_LeftSlider', 'style': 'cursor: ew-resize'\n });\n this.rightSlider = renderer.createGroup({\n 'id': this.elementId + '_RightSlider', 'style': 'cursor: ew-resize'\n });\n this.createThump(renderer, range.bounds, this.leftSlider, this.elementId + '_LeftSlider', sliderGroup);\n this.createThump(renderer, range.bounds, this.rightSlider, this.elementId + '_RightSlider');\n sliderGroup.appendChild(this.leftUnSelectedElement);\n sliderGroup.appendChild(this.rightUnSelectedElement);\n sliderGroup.appendChild(this.selectedElement);\n sliderGroup.appendChild(this.leftSlider);\n sliderGroup.appendChild(this.rightSlider);\n range.svgObject.appendChild(sliderGroup);\n };\n /**\n * Thumb creation performed\n * @param render\n * @param bounds\n * @param parent\n * @param id\n */\n RangeSlider.prototype.createThump = function (render, bounds, parent, id, sliderGroup) {\n var control = this.control;\n var thump = control.navigatorStyleSettings.thumb;\n var style = control.themeStyle;\n var y = bounds.y + bounds.height / 2;\n var x = this.thumpPadding;\n var tickLength = (control.themeStyle.thumbHeight / 2) - 5;\n var disabledColor = control.disableRangeSelector ? 'transparent' : null;\n var lineColor = disabledColor || thump.border.color || style.thumpLineColor;\n var shadowElement;\n parent.appendChild(render.drawPath(new PathOption(id + '_ThumpLine', 'transparent', thump.border.width, control.series.length ? lineColor : 'transparent', 1, null, 'M' + ' ' + (x) + ' ' + (bounds.y) + ' ' + 'L' + ' ' + (x) + ' ' + (bounds.y + bounds.height) + ' ')));\n this.thumpY = y - (control.themeStyle.thumbHeight / 2);\n this.sliderY = bounds.y > this.thumpY ? this.thumpY : bounds.y;\n if (sliderGroup && !control.disableRangeSelector) {\n shadowElement = render.createDefs();\n shadowElement.innerHTML = ' ' +\n '' +\n '' +\n '' +\n ' ';\n sliderGroup.appendChild(shadowElement);\n }\n parent.innerHTML += '';\n if (thump.type === 'Circle') {\n parent.appendChild(drawSymbol({ x: x, y: y }, 'Circle', { width: control.themeStyle.thumbWidth, height: control.themeStyle.thumbHeight }, '', new PathOption(id + '_ThumpSymbol', disabledColor || this.thumbColor, thump.border.width, lineColor, 1, null), 'Thumb'));\n }\n else {\n parent.appendChild(render.drawRectangle(new RectOption(id + '_ThumpSymbol', disabledColor || this.thumbColor, { width: thump.border.width, color: lineColor }, 1, {\n x: x - (control.themeStyle.thumbWidth / 2), y: y - (control.themeStyle.thumbHeight / 2),\n width: control.themeStyle.thumbWidth,\n height: control.themeStyle.thumbHeight\n }, 2, 2)));\n }\n if (this.thumbVisible) {\n parent.appendChild(render.drawPath(new PathOption(id + '_ThumpGrip', 'transparent', 1, disabledColor || control.themeStyle.gripColor, 1, null, 'M' + ' ' + (x + 2) + ' ' + (y + tickLength) + ' ' + 'L' + ' ' + (x + 2) + ' ' + (y - tickLength) + ' ' +\n 'M' + ' ' + (x) + ' ' + (y + tickLength) + ' ' + 'L' + ' ' + (x) + ' ' + (y - tickLength) + ' ' +\n 'M' + ' ' + (x - 2) + ' ' + (y + tickLength) + ' ' + 'L' + ' ' + (x - 2) + ' ' + (y - tickLength) + ' ')));\n }\n };\n /**\n * Set slider value for range navigator\n * @param start\n * @param end\n */\n RangeSlider.prototype.setSlider = function (start, end, trigger, showTooltip) {\n var range = this.control;\n var padding = range.bounds.x;\n var axisRange = range.chartSeries.xAxis.actualRange;\n var isLeightWeight = range.series.length === 0;\n if (!(end >= start)) {\n start = [end, end = start][0];\n }\n start = end >= start ? start : [end, end = start][0];\n start = Math.max(start, axisRange.min);\n end = Math.min(end, axisRange.max);\n this.startX = padding + getXLocation(start, axisRange, range.bounds.width, range.enableRtl);\n this.endX = padding + getXLocation(end, axisRange, range.bounds.width, range.enableRtl);\n var selectedX = range.enableRtl ? this.endX : this.startX;\n var rightPadding = range.enableRtl ? this.startX : this.endX;\n this.sliderWidth = Math.abs(this.endX - this.startX);\n this.selectedElement.setAttribute('x', (selectedX) + '');\n this.selectedElement.setAttribute('width', this.sliderWidth + '');\n this.leftUnSelectedElement.setAttribute('width', (selectedX - padding) + '');\n this.rightUnSelectedElement.setAttribute('x', rightPadding + '');\n this.rightUnSelectedElement.setAttribute('width', (range.bounds.width - (rightPadding - padding)) + '');\n this.leftSlider.setAttribute('transform', 'translate(' + (this.startX - this.thumpPadding) + ', 0)');\n this.rightSlider.setAttribute('transform', 'translate(' + (this.endX - this.thumpPadding) + ', 0)');\n var left = this.control.svgObject.getBoundingClientRect().left -\n this.control.element.getBoundingClientRect().left;\n var leftX = this.control.enableRtl ? this.endX : this.startX;\n var rightX = this.control.enableRtl ? this.startX : this.endX;\n this.leftRect = {\n x: isLeightWeight ? left + padding : padding,\n y: isLeightWeight ? 0 : range.bounds.y,\n width: isLeightWeight ? leftX - padding : leftX,\n height: isLeightWeight ? this.thumpY : range.bounds.height\n };\n this.rightRect = {\n x: isLeightWeight ? left + rightX : rightX,\n y: isLeightWeight ? 0 : range.bounds.y,\n width: (range.bounds.width - (rightPadding - padding)),\n height: isLeightWeight ? this.thumpY : range.bounds.height\n };\n this.midRect = {\n x: isLeightWeight ? leftX + left : 0,\n y: isLeightWeight ? 0 : range.bounds.y,\n width: isLeightWeight ? Math.abs(this.endX - this.startX) : rightX,\n height: isLeightWeight ? this.thumpY : range.bounds.height\n };\n this.currentStart = start;\n this.currentEnd = end;\n if (showTooltip) {\n this.control.rangeTooltipModule.renderLeftTooltip(this);\n this.control.rangeTooltipModule.renderRightTooltip(this);\n }\n if (trigger) {\n this.triggerEvent(axisRange);\n }\n };\n /**\n * Trigger changed event\n * @param range\n */\n RangeSlider.prototype.triggerEvent = function (range) {\n var argsData;\n var xAxis = this.control.chartSeries.xAxis;\n var valueType = xAxis.valueType;\n argsData = {\n cancel: false,\n start: valueType === 'DateTime' ? new Date(this.currentStart) :\n (valueType === 'Logarithmic' ? Math.pow(xAxis.logBase, this.currentStart) : this.currentStart),\n end: valueType === 'DateTime' ? new Date(this.currentEnd) :\n (valueType === 'Logarithmic' ? Math.pow(xAxis.logBase, this.currentEnd) : this.currentEnd),\n name: 'changed',\n selectedData: getExactData(this.points, this.currentStart, this.currentEnd),\n zoomPosition: (this.control.enableRtl ? range.max - this.currentEnd :\n this.currentStart - range.min) / range.delta,\n zoomFactor: (this.currentEnd - this.currentStart) / range.delta\n };\n this.control.trigger('changed', argsData);\n };\n /**\n * @hidden\n */\n RangeSlider.prototype.addEventListener = function () {\n if (this.control.isDestroyed) {\n return;\n }\n this.control.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);\n this.control.on(Browser.touchStartEvent, this.mouseDownHandler, this);\n this.control.on(Browser.touchEndEvent, this.mouseUpHandler, this);\n this.control.on(Browser.isPointer ? 'pointerleave' : 'mouseleave', this.mouseCancelHandler, this);\n };\n /**\n * @hidden\n */\n RangeSlider.prototype.removeEventListener = function () {\n if (this.control.isDestroyed) {\n return;\n }\n this.control.off(Browser.touchMoveEvent, this.mouseMoveHandler);\n this.control.off(Browser.touchStartEvent, this.mouseDownHandler);\n this.control.off(Browser.touchEndEvent, this.mouseUpHandler);\n this.control.off(Browser.isPointer ? 'pointerleave' : 'mouseleave', this.mouseCancelHandler);\n };\n /**\n * Move move handler perfomed here\n * @hidden\n * @param e\n */\n RangeSlider.prototype.mouseMoveHandler = function (e) {\n var control = this.control;\n var axisRange = control.chartSeries.xAxis.actualRange;\n var bounds = control.bounds;\n var start;\n var end;\n this.getCurrentSlider(e.target.id);\n if (this.isDrag && control.mouseX >= bounds.x) {\n switch (this.currentSlider) {\n case 'Left':\n control.startValue = this.getRangeValue(Math.abs(control.mouseX - bounds.x));\n break;\n case 'Right':\n control.endValue = this.getRangeValue(Math.abs(control.mouseX - bounds.x));\n break;\n case 'Middle':\n start = Math.max(this.getRangeValue(Math.abs(this.startX - (this.previousMoveX - control.mouseX) - bounds.x)), axisRange.min);\n end = Math.min(this.getRangeValue(Math.abs(this.endX - (this.previousMoveX - control.mouseX) - bounds.x)), axisRange.max);\n var currentWidth = Math.floor(Math.abs(getXLocation(end, axisRange, control.bounds.width, control.enableRtl) -\n getXLocation(start, axisRange, control.bounds.width, control.enableRtl)));\n if (currentWidth === Math.floor(this.sliderWidth)) {\n control.startValue = start;\n control.endValue = end;\n }\n break;\n }\n if (e.preventDefault && this.isIOS) {\n e.preventDefault();\n }\n this.setSlider(control.startValue, control.endValue, !control.enableDeferredUpdate, (control.rangeTooltipModule && control.tooltip.enable));\n this.previousMoveX = control.mouseX;\n }\n };\n /**\n * To get the range value\n * @param x\n */\n RangeSlider.prototype.getRangeValue = function (x) {\n var control = this.control;\n var axisRange = control.chartSeries.xAxis.actualRange;\n var bounds = control.bounds;\n return getRangeValueXByPoint(x, bounds.width, axisRange, control.enableRtl);\n };\n /**\n * Moused down handler for slider perform here\n * @param e\n */\n RangeSlider.prototype.mouseDownHandler = function (e) {\n this.currentSlider = this.getCurrentSlider(e.target.id);\n this.selectedElement.setAttribute('style', 'cursor: -webkit-grabbing');\n this.isDrag = !(this.currentSlider === 'UnSelectedArea' || !this.currentSlider);\n this.previousMoveX = this.control.mouseDownX;\n };\n /**\n * To get the current slider element\n * @param id\n */\n RangeSlider.prototype.getCurrentSlider = function (id) {\n var hoverColor = this.control.themeStyle.thumbHoverColor;\n if (id.indexOf(this.elementId + '_LeftSlider') > -1) {\n this.leftSlider.childNodes[2].setAttribute('fill', hoverColor);\n return 'Left';\n }\n else if (id.indexOf(this.elementId + '_RightSlider') > -1) {\n this.rightSlider.childNodes[2].setAttribute('fill', hoverColor);\n return 'Right';\n }\n else if (id.indexOf(this.elementId + '_SelectedArea') > -1) {\n return 'Middle';\n }\n else if (id.indexOf('UnSelectedArea') > -1) {\n this.leftSlider.childNodes[2].setAttribute('fill', this.thumbColor);\n this.rightSlider.childNodes[2].setAttribute('fill', this.thumbColor);\n return 'UnSelectedArea';\n }\n else if (id.indexOf(this.elementId + '_AxisLabel_') > -1 && this.control.valueType === 'DateTime') {\n this.labelIndex = +id.split('_')[2];\n return 'firstLevelLabels';\n }\n else if (id.indexOf(this.elementId + '_SecondaryLabel') > -1 && this.control.valueType === 'DateTime') {\n this.labelIndex = +id.split('_')[2];\n return 'secondLevelLabels';\n }\n else {\n this.leftSlider.childNodes[2].setAttribute('fill', this.thumbColor);\n this.rightSlider.childNodes[2].setAttribute('fill', this.thumbColor);\n if (this.control.periodSelectorModule) {\n this.control.periodSelectorModule.triggerChange = true;\n }\n return null;\n }\n };\n /**\n * Mouse up handler performed here\n * @param e\n */\n RangeSlider.prototype.mouseUpHandler = function (e) {\n var control = this.control;\n var range = control.chartSeries.xAxis.actualRange;\n var trigger = control.enableDeferredUpdate;\n var endbledTooltip = control.tooltip.enable;\n if (this.currentSlider === 'UnSelectedArea') {\n var value = void 0;\n var start = void 0;\n var end = void 0;\n var isRtl = control.enableRtl;\n var difference = control.endValue - control.startValue;\n if (control.mouseDownX < this.startX) {\n value = Math.max(this.getRangeValue((control.mouseDownX - (this.sliderWidth / 2) - control.bounds.x)), range.min);\n end = isRtl ? value : (value + difference);\n start = isRtl ? (value - difference) : value;\n }\n else {\n value = Math.min(this.getRangeValue((control.mouseDownX + (this.sliderWidth / 2) - control.bounds.x)), range.max);\n start = isRtl ? value : (value - difference);\n end = isRtl ? (value + difference) : value;\n }\n this.performAnimation(start, end, control);\n trigger = false;\n }\n else if (this.currentSlider === 'firstLevelLabels' || this.currentSlider === 'secondLevelLabels') {\n var secondLabel = control.rangeAxis[this.currentSlider][this.labelIndex + 1];\n this.performAnimation(control.rangeAxis[this.currentSlider][this.labelIndex].value, (secondLabel ? secondLabel.value : range.max), control);\n trigger = false;\n }\n if (this.isDrag && control.allowSnapping) {\n this.setAllowSnapping(control, this.currentStart, this.currentEnd, trigger, endbledTooltip);\n trigger = false;\n }\n if (trigger) {\n this.setSlider(this.currentStart, this.currentEnd, true, endbledTooltip);\n }\n if (this.currentSlider !== null) {\n if (this.control.periodSelectorSettings.periods.length > 0) {\n this.control.periodSelectorModule.triggerChange = false;\n this.control.periodSelectorModule.datePicker.startDate = new Date(this.currentStart);\n this.control.periodSelectorModule.datePicker.endDate = new Date(this.currentEnd);\n }\n }\n this.selectedElement.setAttribute('style', 'cursor: -webkit-grab');\n control.startValue = this.currentStart;\n control.endValue = this.currentEnd;\n this.isDrag = false;\n this.labelIndex = null;\n this.currentSlider = null;\n };\n /**\n * Allow Snapping perfomed here\n * @param control\n * @param start\n * @param end\n */\n RangeSlider.prototype.setAllowSnapping = function (control, start, end, trigger, tooltip) {\n var values = control.rangeAxis.lowerValues;\n values.push(control.chartSeries.xAxis.actualRange.max);\n this.setSlider(getNearestValue(values, start), getNearestValue(values, end), trigger, tooltip);\n control.startValue = this.currentStart;\n control.endValue = this.currentEnd;\n };\n /**\n * Animation Calculation for slider navigation\n * @param start\n * @param end\n */\n RangeSlider.prototype.performAnimation = function (start, end, control) {\n var _this = this;\n var currentStart = this.currentStart;\n var currentEnd = this.currentEnd;\n var isDeffered = control.enableDeferredUpdate;\n var enableTooltip = control.tooltip.enable;\n new Animation({}).animate(createElement('div'), {\n duration: this.control.animationDuration,\n progress: function (args) {\n _this.setSlider(linear(args.timeStamp, 0, start - currentStart, args.duration) + currentStart, linear(args.timeStamp, 0, end - currentEnd, args.duration) + currentEnd, !isDeffered, enableTooltip);\n },\n end: function (model) {\n if (control.allowSnapping) {\n _this.setAllowSnapping(control, start, end, true, enableTooltip);\n }\n else {\n _this.setSlider(start, end, true, enableTooltip);\n }\n _this.control.startValue = _this.currentStart;\n _this.control.endValue = _this.currentEnd;\n if (_this.control.periodSelectorSettings.periods.length > 0) {\n _this.control.periodSelectorModule.triggerChange = false;\n _this.control.periodSelectorModule.datePicker.startDate = new Date(_this.currentStart);\n _this.control.periodSelectorModule.datePicker.endDate = new Date(_this.currentEnd);\n }\n }\n });\n };\n /**\n * Mouse Cancel Handler\n */\n RangeSlider.prototype.mouseCancelHandler = function () {\n this.isDrag = false;\n this.currentSlider = null;\n this.control.startValue = this.currentStart;\n this.control.endValue = this.currentEnd;\n };\n /**\n * Destroy Method Calling here\n */\n RangeSlider.prototype.destroy = function () {\n this.removeEventListener();\n };\n return RangeSlider;\n}());\nexport { RangeSlider };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, NotifyPropertyChanges, Complex, Collection, Browser } from '@syncfusion/ej2-base';\nimport { EventHandler, remove, Internationalization } from '@syncfusion/ej2-base';\nimport { Event } from '@syncfusion/ej2-base';\nimport { createSvg, Size, Rect, measureText } from '../common/utils/helper';\nimport { Border, Margin } from '../common/model/base';\nimport { RangeSeries } from './renderer/chart-render';\nimport { RangeNavigatorAxis } from './renderer/range-axis';\nimport { RangeNavigatorSeries, StyleSettings, RangeTooltipSettings, PeriodSelectorSettings } from './model/range-base';\nimport { RangeSlider } from './renderer/slider';\nimport { RectOption } from '../chart/index';\nimport { getElement, LineSeries } from '../chart/index';\nimport { getRangeThemeColor } from './utils/theme';\nimport { Font } from '../common/model/base';\nimport { MajorGridLines, MajorTickLines } from '../chart/axis/axis';\nimport { RangeNavigatorTheme } from './utils/theme';\nimport { Double } from '../chart/axis/double-axis';\nimport { ExportUtils } from '../common/utils/export';\n/**\n * Range Navigator\n */\nvar RangeNavigator = /** @class */ (function (_super) {\n __extends(RangeNavigator, _super);\n /**\n * Constructor for creating the widget\n * @hidden\n */\n function RangeNavigator(options, element) {\n var _this = _super.call(this, options, element) || this;\n /** @private */\n _this.animateSeries = true;\n _this.chartid = 57725;\n return _this;\n }\n /**\n * Starting point of the control initialization\n */\n RangeNavigator.prototype.preRender = function () {\n this.unWireEvents();\n this.setCulture();\n if (this.element.id === '') {\n var collection = document.getElementsByClassName('e-rangenavigator').length;\n this.element.id = 'rangenavigator_' + this.chartid + '_' + collection;\n }\n this.wireEvents();\n };\n /**\n * To initialize the private variables\n */\n RangeNavigator.prototype.initPrivateVariables = function () {\n this.doubleModule = new Double();\n this.labels = [];\n this.rangeSlider = new RangeSlider(this);\n this.chartSeries = new RangeSeries(this);\n this.lineSeriesModule = new LineSeries();\n this.rangeAxis = new RangeNavigatorAxis(this);\n };\n /**\n * Method to set culture for chart\n */\n RangeNavigator.prototype.setCulture = function () {\n this.intl = new Internationalization();\n };\n /**\n * to initialize the slider\n */\n RangeNavigator.prototype.setSliderValue = function () {\n var isDateTime = this.valueType === 'DateTime';\n var range = this.chartSeries.xAxis.actualRange;\n this.startValue = this.startValue ? this.startValue : (!this.value[0] ? range.min :\n (isDateTime ? this.value[0].getTime() : +this.value[0]));\n this.endValue = this.endValue ? this.endValue : (!this.value[1] ? range.max :\n (isDateTime ? this.value[1].getTime() : +this.value[1]));\n };\n /**\n * To render the range navigator\n */\n RangeNavigator.prototype.render = function () {\n this.trigger('load', { rangeNavigator: this });\n this.setTheme();\n this.initPrivateVariables();\n this.createRangeSvg();\n this.calculateBounds();\n this.chartSeries.renderChart(this);\n var element = document.getElementById('chartmeasuretext');\n if (element) {\n element.remove();\n }\n };\n /**\n * Theming for rangeNavigator\n */\n RangeNavigator.prototype.setTheme = function () {\n /*! Set theme */\n this.themeStyle = getRangeThemeColor(this.theme, this);\n };\n /**\n * Method to create SVG for Range Navigator\n */\n RangeNavigator.prototype.createRangeSvg = function () {\n this.removeSvg();\n createSvg(this);\n this.renderChartBackground();\n };\n /**\n * Bounds calculation for widget performed.\n */\n RangeNavigator.prototype.calculateBounds = function () {\n var labelPadding = this.enableGrouping ? 15 : 8;\n var thumb = this.navigatorStyleSettings.thumb;\n var labelSize = measureText('tempString', this.labelStyle).height;\n var margin = this.margin;\n var isLeightWeight = !this.series.length;\n var tooltipSpace = (!this.disableRangeSelector) &&\n isLeightWeight && this.tooltip.enable ? 35 : 0;\n var selector = this.periodSelectorModule;\n if (this.periodSelectorModule && this.periodSelectorSettings.periods.length > 0) {\n selector.periodSelectorSize = { x: 0, y: 0, height: 0, width: 0 };\n selector.periodSelectorSize.width = this.availableSize.width;\n selector.periodSelectorSize.height = this.periodSelectorSettings.height;\n selector.periodSelectorSize.y = this.periodSelectorSettings.position === 'Bottom' ?\n this.availableSize.height - selector.periodSelectorSize.height : 0;\n }\n var periodSelectorY = this.periodSelectorSettings.position === 'Top' && selector ?\n selector.periodSelectorSize.y + selector.periodSelectorSize.height : 0;\n this.bounds = new Rect((this.themeStyle.thumbWidth / 2 + thumb.border.width + margin.left), margin.top + tooltipSpace + periodSelectorY, this.availableSize.width - this.themeStyle.thumbWidth - (thumb.border.width * 2) - margin.left - margin.right, this.availableSize.height - margin.top - margin.bottom - tooltipSpace - (selector ? selector.periodSelectorSize.height : 0));\n var deductHeight = ((this.labelPosition === 'Outside' || isLeightWeight) ?\n (labelSize + labelPadding) : 0) + ((this.tickPosition === 'Outside' || isLeightWeight) ?\n (this.majorTickLines.height) : 0);\n this.bounds.height -= deductHeight;\n if (isLeightWeight) {\n var height = this.enableGrouping ? this.bounds.height - ((labelSize) + labelPadding) : this.bounds.height;\n this.bounds.y += (this.themeStyle.thumbHeight > height ? (this.themeStyle.thumbHeight - height) / 2 : 0);\n }\n if (this.disableRangeSelector) {\n this.bounds.y = 0;\n this.bounds.height = this.periodSelectorSettings.height;\n }\n };\n /**\n * Creating Chart for range navigator\n */\n RangeNavigator.prototype.renderChart = function () {\n this.chartSeries.renderSeries(this);\n this.rangeAxis.renderGridLines();\n this.rangeAxis.renderAxisLabels();\n this.createSecondaryElement();\n this.setSliderValue();\n this.renderPeriodSelector();\n this.renderSlider();\n this.element.appendChild(this.svgObject);\n this.trigger('loaded', { rangeNavigator: this });\n this.rangeSlider.setSlider(this.startValue, this.endValue, false, this.tooltip.enable && this.tooltip.displayMode === 'Always');\n };\n /**\n * To render period selector value\n */\n RangeNavigator.prototype.renderPeriodSelector = function () {\n if (this.periodSelectorModule) {\n this.periodSelectorModule.renderSelectorElement(this);\n this.periodSelectorModule.renderSelector();\n }\n };\n /**\n * Creating secondary range navigator\n */\n RangeNavigator.prototype.createSecondaryElement = function () {\n // For userInteraction\n if (this.tooltip.enable) {\n var tooltipDiv = this.createElement('div');\n tooltipDiv.id = this.element.id + '_Secondary_Element';\n tooltipDiv.setAttribute('style', 'position: relative');\n this.element.appendChild(tooltipDiv);\n }\n };\n /**\n * Slider Calculation ane rendering performed here\n */\n RangeNavigator.prototype.renderSlider = function () {\n this.rangeSlider.render(this);\n this.rangeSlider.setSlider(this.startValue, this.endValue, true, this.tooltip.enable && this.tooltip.displayMode === 'Always');\n };\n /**\n * To Remove the SVG.\n * @return {boolean}\n * @private\n */\n RangeNavigator.prototype.removeSvg = function () {\n if (getElement(this.element.id + '_Secondary_Element')) {\n remove(getElement(this.element.id + '_Secondary_Element'));\n }\n var removeLength = 0;\n if (this.svgObject) {\n while (this.svgObject.childNodes.length > removeLength) {\n this.svgObject.removeChild(this.svgObject.firstChild);\n }\n if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) {\n remove(this.svgObject);\n }\n }\n };\n /** Wire, UnWire and Event releated calculation Started here */\n /**\n * Method to un-bind events for range navigator\n */\n RangeNavigator.prototype.unWireEvents = function () {\n /*! Find the Events type */\n var startEvent = Browser.touchStartEvent;\n var moveEvent = Browser.touchMoveEvent;\n var stopEvent = Browser.touchEndEvent;\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n /*! UnBind the Event handler */\n EventHandler.remove(this.element, startEvent, this.rangeOnMouseDown);\n EventHandler.remove(this.element, moveEvent, this.mouseMove);\n EventHandler.remove(this.element, stopEvent, this.mouseEnd);\n EventHandler.remove(this.element, 'click', this.rangeOnMouseClick);\n //EventHandler.remove(this.element, 'contextmenu', this.rangeRightClick);\n EventHandler.remove(this.element, cancelEvent, this.mouseLeave);\n window.removeEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.rangeResize);\n };\n /**\n * Method to bind events for range navigator\n */\n RangeNavigator.prototype.wireEvents = function () {\n /*! Find the Events type */\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n /*! Bind the Event handler */\n EventHandler.add(this.element, Browser.touchStartEvent, this.rangeOnMouseDown, this);\n EventHandler.add(this.element, Browser.touchMoveEvent, this.mouseMove, this);\n EventHandler.add(this.element, Browser.touchEndEvent, this.mouseEnd, this);\n EventHandler.add(this.element, 'click', this.rangeOnMouseClick, this);\n //EventHandler.add(this.element, 'contextmenu', this.rangeRightClick, this);\n EventHandler.add(this.element, cancelEvent, this.mouseLeave, this);\n window.addEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.rangeResize.bind(this));\n var element = this.element;\n element.style.touchAction = 'none';\n element.style.msTouchAction = 'none';\n element.style.msContentZooming = 'none';\n element.style.msUserSelect = 'none';\n element.style.webkitUserSelect = 'none';\n element.style.position = 'relative';\n element.style.display = 'block';\n };\n /**\n * Handles the widget resize.\n * @return {boolean}\n * @private\n */\n RangeNavigator.prototype.rangeResize = function (e) {\n var _this = this;\n this.animateSeries = false;\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n var arg = {\n rangeNavigator: this,\n name: 'resized',\n currentSize: new Size(0, 0),\n previousSize: new Size(this.availableSize.width, this.availableSize.height),\n };\n this.resizeTo = setTimeout(function () {\n if (_this.isDestroyed) {\n clearTimeout(_this.resizeTo);\n return;\n }\n _this.createRangeSvg();\n arg.currentSize = _this.availableSize;\n _this.trigger('resized', arg);\n _this.calculateBounds();\n _this.chartSeries.renderChart(_this);\n }, 500);\n return false;\n };\n /**\n * Handles the mouse move.\n * @return {boolean}\n * @private\n */\n RangeNavigator.prototype.mouseMove = function (e) {\n this.mouseX = this.setMouseX(e);\n this.notify(Browser.touchMoveEvent, e);\n return false;\n };\n /**\n * Handles the mouse leave.\n * @return {boolean}\n * @private\n */\n RangeNavigator.prototype.mouseLeave = function (e) {\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n this.mouseX = this.setMouseX(e);\n this.notify(cancelEvent, e);\n return false;\n };\n /**\n * Handles the mouse click on range navigator.\n * @return {boolean}\n * @private\n */\n RangeNavigator.prototype.rangeOnMouseClick = function (e) {\n this.notify('click', e);\n return false;\n };\n /**\n * Handles the print method for range navigator control.\n */\n RangeNavigator.prototype.print = function (id) {\n new ExportUtils(this).print(id);\n };\n /**\n * Handles the export method for range navigator control.\n * @param type\n * @param fileName\n */\n RangeNavigator.prototype.export = function (type, fileName, orientation, controls, width, height) {\n controls = controls ? controls : [this];\n new ExportUtils(this).export(type, fileName, orientation, controls, width, height);\n };\n /**\n * Creating a background element to the svg object\n */\n RangeNavigator.prototype.renderChartBackground = function () {\n var rect = new RectOption(this.element.id + '_ChartBorder', this.themeStyle.background, { width: 0, color: 'transparent' }, 1, new Rect(0, 0, this.availableSize.width, this.availableSize.height));\n this.svgObject.appendChild(this.renderer.drawRectangle(rect));\n };\n /**\n * Handles the mouse down on range navigator.\n * @return {boolean}\n * @private\n */\n RangeNavigator.prototype.rangeOnMouseDown = function (e) {\n this.mouseDownX = this.setMouseX(e);\n this.notify(Browser.touchStartEvent, e);\n return false;\n };\n /**\n * Handles the mouse up.\n * @return {boolean}\n * @private\n */\n RangeNavigator.prototype.mouseEnd = function (e) {\n this.mouseX = this.setMouseX(e);\n this.notify(Browser.touchEndEvent, e);\n return false;\n };\n // private rangeRightClick(event: MouseEvent | PointerEvent): boolean {\n // if (event.buttons === 2 || event.which === 0 || (event).pointerType === 'touch') {\n // event.preventDefault();\n // event.stopPropagation();\n // return false;\n // }\n // return true;\n // }\n /**\n * To find mouse x, y for aligned range navigator element svg position\n */\n RangeNavigator.prototype.setMouseX = function (e) {\n var pageX = e.type.indexOf('touch') > -1 ?\n e.changedTouches[0].clientX : e.clientX;\n var rect = this.element.getBoundingClientRect();\n var svgRect = getElement(this.element.id + '_svg').getBoundingClientRect();\n return (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0);\n };\n /** Wire, UnWire and Event releated calculation End here */\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n RangeNavigator.prototype.getPersistData = function () {\n var keyEntity = ['loaded'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * OnProperty change method calling here\n * @param newProp\n * @param oldProp\n */\n RangeNavigator.prototype.onPropertyChanged = function (newProp, oldProp) {\n var renderer = false;\n var refreshBounds = false;\n var refreshRange = false;\n this.animateSeries = false;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'width':\n case 'height':\n case 'navigatorBorder':\n case 'enableGrouping':\n case 'labelPosition':\n case 'tickPosition':\n case 'labelStyle':\n refreshBounds = true;\n break;\n case 'series':\n case 'enableRtl':\n case 'dataSource':\n case 'xName':\n case 'yName':\n case 'query':\n case 'minimum':\n case 'maximum':\n case 'interval':\n case 'intervalType':\n case 'logBase':\n case 'valueType':\n case 'majorGridLines':\n case 'minorGridLines':\n case 'navigatorStyleSettings':\n case 'labelFormat':\n case 'skeleton':\n case 'skeletonType':\n case 'secondaryLabelAlignment':\n renderer = true;\n break;\n case 'theme':\n this.animateSeries = true;\n break;\n case 'locale':\n _super.prototype.refresh.call(this);\n break;\n case 'value':\n refreshRange = true;\n break;\n }\n }\n if (!refreshBounds && renderer) {\n this.removeSvg();\n this.chartSeries.renderChart(this);\n }\n if (refreshBounds) {\n this.removeSvg();\n this.calculateBounds();\n this.chartSeries.renderChart(this);\n }\n if (!refreshBounds && !renderer && refreshRange) {\n this.setSliderValue();\n this.rangeSlider.setSlider(this.startValue, this.endValue, true, this.tooltip.enable && this.tooltip.displayMode === 'Always');\n }\n };\n /**\n * To provide the array of modules needed for control rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n RangeNavigator.prototype.requiredModules = function () {\n var _this = this;\n var modules = [];\n this.series.map(function (series) {\n modules.push({\n member: series.type + 'Series',\n args: [_this]\n });\n });\n if (this.periodSelectorSettings.periods.length > 0) {\n modules.push({\n member: 'PeriodSelector',\n args: [this]\n });\n }\n if (this.valueType !== 'Double') {\n modules.push({\n member: this.valueType,\n args: [this]\n });\n }\n if (this.tooltip.enable) {\n modules.push({\n member: 'RangeTooltip',\n args: [this]\n });\n }\n return modules;\n };\n /**\n * To get the module name of the widget\n */\n RangeNavigator.prototype.getModuleName = function () {\n return 'rangeNavigator';\n };\n /**\n * To destroy the widget\n * @method destroy\n * @return {void}.\n * @member of rangeNavigator\n */\n RangeNavigator.prototype.destroy = function () {\n this.unWireEvents();\n this.rangeSlider.destroy();\n _super.prototype.destroy.call(this);\n this.element.classList.remove('e-rangenavigator');\n };\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"height\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"dataSource\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"xName\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"yName\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"query\", void 0);\n __decorate([\n Collection([], RangeNavigatorSeries)\n ], RangeNavigator.prototype, \"series\", void 0);\n __decorate([\n Complex({}, RangeTooltipSettings)\n ], RangeNavigator.prototype, \"tooltip\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"minimum\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"maximum\", void 0);\n __decorate([\n Property(null)\n ], RangeNavigator.prototype, \"interval\", void 0);\n __decorate([\n Property('Auto')\n ], RangeNavigator.prototype, \"intervalType\", void 0);\n __decorate([\n Property('Hide')\n ], RangeNavigator.prototype, \"labelIntersectAction\", void 0);\n __decorate([\n Property(10)\n ], RangeNavigator.prototype, \"logBase\", void 0);\n __decorate([\n Property('Double')\n ], RangeNavigator.prototype, \"valueType\", void 0);\n __decorate([\n Property('Outside')\n ], RangeNavigator.prototype, \"labelPosition\", void 0);\n __decorate([\n Property(500)\n ], RangeNavigator.prototype, \"animationDuration\", void 0);\n __decorate([\n Property(false)\n ], RangeNavigator.prototype, \"enableGrouping\", void 0);\n __decorate([\n Property(false)\n ], RangeNavigator.prototype, \"enableDeferredUpdate\", void 0);\n __decorate([\n Property(false)\n ], RangeNavigator.prototype, \"disableRangeSelector\", void 0);\n __decorate([\n Property(false)\n ], RangeNavigator.prototype, \"allowSnapping\", void 0);\n __decorate([\n Property(false)\n ], RangeNavigator.prototype, \"useGroupingSeparator\", void 0);\n __decorate([\n Property()\n ], RangeNavigator.prototype, \"groupBy\", void 0);\n __decorate([\n Property('Outside')\n ], RangeNavigator.prototype, \"tickPosition\", void 0);\n __decorate([\n Complex(RangeNavigatorTheme.axisLabelFont, Font)\n ], RangeNavigator.prototype, \"labelStyle\", void 0);\n __decorate([\n Complex({}, MajorGridLines)\n ], RangeNavigator.prototype, \"majorGridLines\", void 0);\n __decorate([\n Complex({}, MajorTickLines)\n ], RangeNavigator.prototype, \"majorTickLines\", void 0);\n __decorate([\n Complex({}, StyleSettings)\n ], RangeNavigator.prototype, \"navigatorStyleSettings\", void 0);\n __decorate([\n Complex({}, PeriodSelectorSettings)\n ], RangeNavigator.prototype, \"periodSelectorSettings\", void 0);\n __decorate([\n Complex({ color: '#DDDDDD', width: 1 }, Border)\n ], RangeNavigator.prototype, \"navigatorBorder\", void 0);\n __decorate([\n Property('Material')\n ], RangeNavigator.prototype, \"theme\", void 0);\n __decorate([\n Property([])\n ], RangeNavigator.prototype, \"value\", void 0);\n __decorate([\n Property('')\n ], RangeNavigator.prototype, \"labelFormat\", void 0);\n __decorate([\n Property('')\n ], RangeNavigator.prototype, \"skeleton\", void 0);\n __decorate([\n Property('DateTime')\n ], RangeNavigator.prototype, \"skeletonType\", void 0);\n __decorate([\n Property('Middle')\n ], RangeNavigator.prototype, \"secondaryLabelAlignment\", void 0);\n __decorate([\n Complex({ top: 5, bottom: 5, right: 5, left: 5 }, Margin)\n ], RangeNavigator.prototype, \"margin\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"load\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"loaded\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"resized\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"labelRender\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"changed\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"tooltipRender\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"selectorRender\", void 0);\n __decorate([\n Event()\n ], RangeNavigator.prototype, \"beforePrint\", void 0);\n RangeNavigator = __decorate([\n NotifyPropertyChanges\n ], RangeNavigator);\n return RangeNavigator;\n}(Component));\nexport { RangeNavigator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Touch, Component, EventHandler, selectAll, getUniqueID } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, Property, Browser, detach } from '@syncfusion/ej2-base';\nvar CLS_ROOT = 'e-hscroll';\nvar CLS_RTL = 'e-rtl';\nvar CLS_DISABLE = 'e-overlay';\nvar CLS_HSCROLLBAR = 'e-hscroll-bar';\nvar CLS_HSCROLLCON = 'e-hscroll-content';\nvar CLS_NAVARROW = 'e-nav-arrow';\nvar CLS_NAVRIGHTARROW = 'e-nav-right-arrow';\nvar CLS_NAVLEFTARROW = 'e-nav-left-arrow';\nvar CLS_HSCROLLNAV = 'e-scroll-nav';\nvar CLS_HSCROLLNAVRIGHT = 'e-scroll-right-nav';\nvar CLS_HSCROLLNAVLEFT = 'e-scroll-left-nav';\nvar CLS_DEVICE = 'e-scroll-device';\n/**\n * HScroll module is introduces horizontal scroller when content exceeds the current viewing area.\n * It can be useful for the components like Toolbar, Tab which needs horizontal scrolling alone.\n * Hidden content can be view by touch moving or icon click.\n * ```html\n * \n * \n * ```\n */\nvar HScroll = /** @class */ (function (_super) {\n __extends(HScroll, _super);\n /**\n * Initializes a new instance of the HScroll class.\n * @param options - Specifies HScroll model properties as options.\n * @param element - Specifies the element for which horizontal scrolling applies.\n */\n function HScroll(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * Initialize the event handler\n * @private\n */\n HScroll.prototype.preRender = function () {\n this.browser = Browser.info.name;\n this.browserCheck = this.browser === 'mozilla';\n this.isDevice = Browser.isDevice;\n var element = this.element;\n this.ieCheck = this.browser === 'edge' || this.browser === 'msie';\n this.initialize();\n if (element.id === '') {\n element.id = getUniqueID('hscroll');\n this.uniqueId = true;\n }\n element.style.display = 'block';\n if (this.enableRtl) {\n element.classList.add(CLS_RTL);\n }\n };\n /**\n * To Initialize the control rendering\n * @private\n */\n HScroll.prototype.render = function () {\n this.touchModule = new Touch(this.element, { scroll: this.touchHandler.bind(this) });\n if (!this.isDevice) {\n this.createNavIcon(this.element);\n EventHandler.add(this.scrollEle, 'scroll', this.scrollHandler, this);\n }\n else {\n this.element.classList.add(CLS_DEVICE);\n }\n };\n HScroll.prototype.initialize = function () {\n var scrollEle = this.createElement('div', { className: CLS_HSCROLLCON });\n var scrollDiv = this.createElement('div', { className: CLS_HSCROLLBAR });\n scrollDiv.setAttribute('tabindex', '-1');\n var ele = this.element;\n var innerEle = [].slice.call(ele.children);\n for (var _i = 0, innerEle_1 = innerEle; _i < innerEle_1.length; _i++) {\n var ele_1 = innerEle_1[_i];\n scrollEle.appendChild(ele_1);\n }\n scrollDiv.appendChild(scrollEle);\n ele.appendChild(scrollDiv);\n scrollDiv.style.overflowX = 'hidden';\n this.scrollEle = scrollDiv;\n this.scrollItems = scrollEle;\n };\n HScroll.prototype.getPersistData = function () {\n var keyEntity = ['scrollStep'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Returns the current module name.\n * @returns string\n * @private\n */\n HScroll.prototype.getModuleName = function () {\n return 'hScroll';\n };\n /**\n * Removes the control from the DOM and also removes all its related events.\n * @returns void\n */\n HScroll.prototype.destroy = function () {\n var ele = this.element;\n ele.style.display = '';\n ele.classList.remove(CLS_ROOT);\n var nav = selectAll('.e-' + ele.id + '_nav.' + CLS_HSCROLLNAV, ele);\n for (var _i = 0, _a = [].slice.call(this.scrollItems.children); _i < _a.length; _i++) {\n var elem = _a[_i];\n ele.appendChild(elem);\n }\n if (this.uniqueId) {\n this.element.removeAttribute('id');\n }\n detach(this.scrollEle);\n if (nav.length > 0) {\n detach(nav[0]);\n detach(nav[1]);\n }\n EventHandler.remove(this.scrollEle, 'scroll', this.scrollHandler);\n this.touchModule.destroy();\n this.touchModule = null;\n _super.prototype.destroy.call(this);\n };\n /**\n * Specifies the value to disable/enable the HScroll component.\n * When set to `true`, the component will be disabled.\n * @param {boolean} value - Based on this Boolean value, HScroll will be enabled (false) or disabled (true).\n * @returns void.\n */\n HScroll.prototype.disable = function (value) {\n var navEles = selectAll('.e-scroll-nav:not(.' + CLS_DISABLE + ')', this.element);\n value ? this.element.classList.add(CLS_DISABLE) : this.element.classList.remove(CLS_DISABLE);\n navEles.forEach(function (el) {\n el.setAttribute('tabindex', !value ? '0' : '-1');\n });\n };\n HScroll.prototype.createNavIcon = function (element) {\n var id = element.id.concat('_nav');\n var clsRight = 'e-' + element.id.concat('_nav ' + CLS_HSCROLLNAV + ' ' + CLS_HSCROLLNAVRIGHT);\n var nav = this.createElement('div', { id: id.concat('_right'), className: clsRight });\n nav.setAttribute('aria-disabled', 'false');\n var navItem = this.createElement('div', { className: CLS_NAVRIGHTARROW + ' ' + CLS_NAVARROW + ' e-icons' });\n var clsLeft = 'e-' + element.id.concat('_nav ' + CLS_HSCROLLNAV + ' ' + CLS_HSCROLLNAVLEFT);\n var navEle = this.createElement('div', { id: id.concat('_left'), className: clsLeft + ' ' + CLS_DISABLE });\n navEle.setAttribute('aria-disabled', 'true');\n var navLeftItem = this.createElement('div', { className: CLS_NAVLEFTARROW + ' ' + CLS_NAVARROW + ' e-icons' });\n navEle.appendChild(navLeftItem);\n nav.appendChild(navItem);\n nav.setAttribute('tabindex', '0');\n element.appendChild(nav);\n element.insertBefore(navEle, element.firstChild);\n if (this.ieCheck) {\n nav.classList.add('e-ie-align');\n navEle.classList.add('e-ie-align');\n }\n this.eventBinding([nav, navEle]);\n };\n HScroll.prototype.onKeyPress = function (e) {\n var _this = this;\n if (e.key === 'Enter') {\n var timeoutFun_1 = function () {\n _this.keyTimeout = true;\n _this.eleScrolling(10, e.target);\n };\n this.keyTimer = window.setTimeout(function () {\n timeoutFun_1();\n }, 100);\n }\n };\n HScroll.prototype.onKeyUp = function (e) {\n if (e.key !== 'Enter') {\n return;\n }\n if (this.keyTimeout) {\n this.keyTimeout = false;\n }\n else {\n e.target.click();\n }\n clearTimeout(this.keyTimer);\n };\n HScroll.prototype.eventBinding = function (ele) {\n var _this = this;\n ele.forEach(function (el) {\n new Touch(el, { tapHold: _this.tabHoldHandler.bind(_this), tapHoldThreshold: 500 });\n el.addEventListener('keydown', _this.onKeyPress.bind(_this));\n el.addEventListener('keyup', _this.onKeyUp.bind(_this));\n el.addEventListener('mouseup', _this.repeatScroll.bind(_this));\n el.addEventListener('touchend', _this.repeatScroll.bind(_this));\n el.addEventListener('contextmenu', function (e) {\n e.preventDefault();\n });\n EventHandler.add(el, 'click', _this.clickEventHandler, _this);\n });\n };\n HScroll.prototype.repeatScroll = function () {\n clearInterval(this.timeout);\n };\n HScroll.prototype.tabHoldHandler = function (e) {\n var _this = this;\n var trgt = e.originalEvent.target;\n trgt = this.contains(trgt, CLS_HSCROLLNAV) ? trgt.firstElementChild : trgt;\n var scrollDis = 10;\n var timeoutFun = function () {\n _this.eleScrolling(scrollDis, trgt);\n };\n this.timeout = window.setInterval(function () {\n timeoutFun();\n }, 50);\n };\n HScroll.prototype.contains = function (ele, className) {\n return ele.classList.contains(className);\n };\n HScroll.prototype.eleScrolling = function (scrollDis, trgt) {\n var element = this.scrollEle;\n var rootEle = this.element;\n var classList = trgt.classList;\n if (classList.contains(CLS_HSCROLLNAV)) {\n classList = trgt.querySelector('.' + CLS_NAVARROW).classList;\n }\n if (this.contains(rootEle, CLS_RTL) && this.browserCheck) {\n scrollDis = -scrollDis;\n }\n var scrlLeft = element.scrollLeft;\n if ((!this.contains(rootEle, CLS_RTL) || this.browserCheck) || this.ieCheck) {\n if (classList.contains(CLS_NAVRIGHTARROW)) {\n element.scrollLeft = scrlLeft + scrollDis;\n }\n else {\n element.scrollLeft = scrlLeft - scrollDis;\n }\n }\n else {\n if (classList.contains(CLS_NAVLEFTARROW)) {\n element.scrollLeft = scrlLeft + scrollDis;\n }\n else {\n element.scrollLeft = scrlLeft - scrollDis;\n }\n }\n };\n HScroll.prototype.clickEventHandler = function (e) {\n this.eleScrolling(this.scrollStep, e.target);\n };\n HScroll.prototype.touchHandler = function (e) {\n var ele = this.scrollEle;\n var distance;\n distance = e.distanceX;\n if ((this.ieCheck) && this.contains(this.element, CLS_RTL)) {\n distance = -distance;\n }\n if (e.scrollDirection === 'Left') {\n ele.scrollLeft = ele.scrollLeft + distance;\n }\n else if (e.scrollDirection === 'Right') {\n ele.scrollLeft = ele.scrollLeft - distance;\n }\n };\n HScroll.prototype.arrowDisabling = function (addDisable, removeDisable) {\n addDisable.classList.add(CLS_DISABLE);\n addDisable.setAttribute('aria-disabled', 'true');\n addDisable.removeAttribute('tabindex');\n clearInterval(this.timeout);\n removeDisable.classList.remove(CLS_DISABLE);\n removeDisable.setAttribute('aria-disabled', 'false');\n removeDisable.setAttribute('tabindex', '0');\n this.repeatScroll();\n };\n HScroll.prototype.scrollHandler = function (e) {\n var target = e.target;\n var width = target.offsetWidth;\n var rootEle = this.element;\n var navLeftEle = this.element.querySelector('.' + CLS_HSCROLLNAVLEFT);\n var navRightEle = this.element.querySelector('.' + CLS_HSCROLLNAVRIGHT);\n var scrollLeft = target.scrollLeft;\n if (scrollLeft <= 0) {\n scrollLeft = -scrollLeft;\n }\n if (scrollLeft === 0) {\n if ((!this.contains(rootEle, CLS_RTL) || this.browserCheck) || this.ieCheck) {\n this.arrowDisabling(navLeftEle, navRightEle);\n }\n else {\n this.arrowDisabling(navRightEle, navLeftEle);\n }\n }\n else if (Math.ceil(width + scrollLeft + .1) >= target.scrollWidth) {\n if ((!this.contains(rootEle, CLS_RTL) || this.browserCheck) || this.ieCheck) {\n this.arrowDisabling(navRightEle, navLeftEle);\n }\n else {\n this.arrowDisabling(navLeftEle, navRightEle);\n }\n }\n else {\n var disEle = this.element.querySelector('.' + CLS_HSCROLLNAV + '.' + CLS_DISABLE);\n if (disEle) {\n disEle.classList.remove(CLS_DISABLE);\n disEle.setAttribute('aria-disabled', 'false');\n disEle.setAttribute('tabindex', '0');\n }\n }\n };\n /**\n * Gets called when the model property changes.The data that describes the old and new values of property that changed.\n * @param {HScrollModel} newProp\n * @param {HScrollModel} oldProp\n * @returns void\n * @private\n */\n HScroll.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'scrollStep':\n break;\n case 'enableRtl':\n newProp.enableRtl ? this.element.classList.add(CLS_RTL) : this.element.classList.remove(CLS_RTL);\n break;\n }\n }\n };\n __decorate([\n Property(40)\n ], HScroll.prototype, \"scrollStep\", void 0);\n HScroll = __decorate([\n NotifyPropertyChanges\n ], HScroll);\n return HScroll;\n}(Component));\nexport { HScroll };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, EventHandler, Property, Event } from '@syncfusion/ej2-base';\nimport { addClass, removeClass, isVisible, closest, attributes, detach, classList, KeyboardEvents } from '@syncfusion/ej2-base';\nimport { selectAll, setStyleAttribute as setStyle } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined as isNOU, getUniqueID, formatUnit, Collection, compile as templateCompiler } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, ChildProperty, Browser } from '@syncfusion/ej2-base';\nimport { Popup } from '@syncfusion/ej2-popups';\nimport { calculatePosition } from '@syncfusion/ej2-popups';\nimport { Button } from '@syncfusion/ej2-buttons';\nimport { HScroll } from '../common/h-scroll';\nvar CLS_ITEMS = 'e-toolbar-items';\nvar CLS_ITEM = 'e-toolbar-item';\nvar CLS_RTL = 'e-rtl';\nvar CLS_SEPARATOR = 'e-separator';\nvar CLS_POPUPICON = 'e-popup-up-icon';\nvar CLS_POPUPDOWN = 'e-popup-down-icon';\nvar CLS_TEMPLATE = 'e-template';\nvar CLS_DISABLE = 'e-overlay';\nvar CLS_POPUPTEXT = 'e-toolbar-text';\nvar CLS_TBARTEXT = 'e-popup-text';\nvar CLS_TBAROVERFLOW = 'e-overflow-show';\nvar CLS_POPOVERFLOW = 'e-overflow-hide';\nvar CLS_TBARBTN = 'e-tbar-btn';\nvar CLS_TBARNAV = 'e-hor-nav';\nvar CLS_TBARSCRLNAV = 'e-scroll-nav';\nvar CLS_TBARRIGHT = 'e-toolbar-right';\nvar CLS_TBARLEFT = 'e-toolbar-left';\nvar CLS_TBARCENTER = 'e-toolbar-center';\nvar CLS_TBARPOS = 'e-tbar-pos';\nvar CLS_TBARSCROLL = 'e-hscroll-content';\nvar CLS_POPUPNAV = 'e-hor-nav';\nvar CLS_POPUPCLASS = 'e-toolbar-pop';\nvar CLS_POPUP = 'e-toolbar-popup';\nvar CLS_TBARBTNTEXT = 'e-tbar-btn-text';\nvar CLS_TBARNAVACT = 'e-nav-active';\nvar CLS_TBARIGNORE = 'e-ignore';\nvar CLS_POPPRI = 'e-popup-alone';\nvar CLS_HIDDEN = 'e-hidden';\nvar CLS_MULTIROW = 'e-toolbar-multirow';\nvar CLS_MULTIROW_SEPARATOR = 'e-multirow-separator';\nvar CLS_EXTENDABLE_ITEM = 'e-extended-item';\nvar CLS_EXTENDABLE_SEPARATOR = 'e-extended-separator';\nvar CLS_EXTEANDABLE_TOOLBAR = 'e-extended-toolbar';\nvar CLS_EXTENDABLECLASS = 'e-toolbar-extended';\nvar CLS_EXTENDPOPUP = 'e-expended-nav';\nvar CLS_EXTENDEDPOPOPEN = 'e-tbar-extended';\n/**\n * An item object that is used to configure Toolbar commands.\n */\nvar Item = /** @class */ (function (_super) {\n __extends(Item, _super);\n function Item() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Item.prototype, \"id\", void 0);\n __decorate([\n Property('')\n ], Item.prototype, \"text\", void 0);\n __decorate([\n Property('auto')\n ], Item.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], Item.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], Item.prototype, \"showAlwaysInPopup\", void 0);\n __decorate([\n Property('')\n ], Item.prototype, \"prefixIcon\", void 0);\n __decorate([\n Property('')\n ], Item.prototype, \"suffixIcon\", void 0);\n __decorate([\n Property('None')\n ], Item.prototype, \"overflow\", void 0);\n __decorate([\n Property('')\n ], Item.prototype, \"template\", void 0);\n __decorate([\n Property('Button')\n ], Item.prototype, \"type\", void 0);\n __decorate([\n Property('Both')\n ], Item.prototype, \"showTextOn\", void 0);\n __decorate([\n Property(null)\n ], Item.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property('')\n ], Item.prototype, \"tooltipText\", void 0);\n __decorate([\n Property('Left')\n ], Item.prototype, \"align\", void 0);\n return Item;\n}(ChildProperty));\nexport { Item };\n/**\n * The Toolbar control contains a group of commands that are aligned horizontally.\n * ```html\n *
\n * \n * ```\n */\nvar Toolbar = /** @class */ (function (_super) {\n __extends(Toolbar, _super);\n /**\n * Initializes a new instance of the Toolbar class.\n * @param options - Specifies Toolbar model properties as options.\n * @param element - Specifies the element that is rendered as a Toolbar.\n */\n function Toolbar(options, element) {\n var _this = _super.call(this, options, element) || this;\n /**\n * Contains the keyboard configuration of the Toolbar.\n */\n _this.keyConfigs = {\n moveLeft: 'leftarrow',\n moveRight: 'rightarrow',\n moveUp: 'uparrow',\n moveDown: 'downarrow',\n popupOpen: 'enter',\n popupClose: 'escape',\n tab: 'tab',\n home: 'home',\n end: 'end',\n };\n return _this;\n }\n /**\n * Removes the control from the DOM and also removes all its related events.\n * @returns void.\n */\n Toolbar.prototype.destroy = function () {\n var _this = this;\n var ele = this.element;\n _super.prototype.destroy.call(this);\n this.unwireEvents();\n this.tempId.forEach(function (ele) {\n if (!isNOU(_this.element.querySelector(ele))) {\n document.body.appendChild(_this.element.querySelector(ele)).style.display = 'none';\n }\n });\n while (ele.firstChild) {\n ele.removeChild(ele.firstChild);\n }\n if (this.trgtEle) {\n ele.appendChild(this.ctrlTem);\n }\n this.clearProperty();\n this.popObj = null;\n this.tbarAlign = null;\n this.remove(this.element, 'e-toolpop');\n ele.removeAttribute('style');\n ['aria-disabled', 'aria-orientation', 'aria-haspopup', 'role'].forEach(function (attrb) {\n _this.element.removeAttribute(attrb);\n });\n };\n /**\n * Initialize the event handler\n * @private\n */\n Toolbar.prototype.preRender = function () {\n var eventArgs = { enableCollision: true, scrollStep: this.scrollStep };\n this.trigger('beforeCreate', eventArgs);\n this.enableCollision = eventArgs.enableCollision;\n this.scrollStep = eventArgs.scrollStep;\n this.scrollModule = null;\n this.popObj = null;\n this.tempId = [];\n this.tbarItemsCol = this.items;\n this.popupPriCount = 0;\n if (this.enableRtl) {\n this.add(this.element, CLS_RTL);\n }\n };\n Toolbar.prototype.wireEvents = function () {\n EventHandler.add(this.element, 'click', this.clickHandler, this);\n window.addEventListener('resize', this.resize.bind(this));\n this.keyModule = new KeyboardEvents(this.element, {\n keyAction: this.keyActionHandler.bind(this),\n keyConfigs: this.keyConfigs\n });\n EventHandler.add(this.element, 'keydown', this.docKeyDown, this);\n this.element.setAttribute('tabIndex', '0');\n };\n Toolbar.prototype.docKeyDown = function (e) {\n if (e.target.tagName === 'INPUT') {\n return;\n }\n var popCheck = !isNOU(this.popObj) && isVisible(this.popObj.element) && this.overflowMode !== 'Extended';\n if (e.keyCode === 9 && e.target.classList.contains('e-hor-nav') === true && popCheck) {\n this.popObj.hide({ name: 'FadeOut', duration: 100 });\n }\n var keyCheck = (e.keyCode === 40 || e.keyCode === 38 || e.keyCode === 35 || e.keyCode === 36);\n if (keyCheck) {\n e.preventDefault();\n }\n };\n Toolbar.prototype.unwireEvents = function () {\n EventHandler.remove(this.element, 'click', this.clickHandler);\n this.destroyHScroll();\n this.keyModule.destroy();\n EventHandler.remove(document, 'scroll', this.docEvent);\n EventHandler.remove(this.element, 'keydown', this.docKeyDown);\n EventHandler.remove(document, 'click', this.docEvent);\n };\n Toolbar.prototype.clearProperty = function () {\n this.tbarEle = [];\n this.tbarAlgEle = { lefts: [], centers: [], rights: [] };\n };\n Toolbar.prototype.docEvent = function (e) {\n var popEle = closest(e.target, '.e-popup');\n if (this.popObj && isVisible(this.popObj.element) && !popEle && this.overflowMode === 'Popup') {\n this.popObj.hide({ name: 'FadeOut', duration: 100 });\n }\n };\n Toolbar.prototype.destroyHScroll = function () {\n if (this.scrollModule) {\n if (this.tbarAlign) {\n this.add(this.scrollModule.element, CLS_TBARPOS);\n }\n this.scrollModule.destroy();\n this.scrollModule = null;\n }\n };\n Toolbar.prototype.destroyItems = function () {\n [].slice.call(this.element.querySelectorAll('.' + CLS_ITEM)).forEach(function (el) {\n detach(el);\n });\n var tbarItems = this.element.querySelector('.' + CLS_ITEMS);\n if (this.tbarAlign) {\n [].slice.call(tbarItems.children).forEach(function (el) {\n detach(el);\n });\n this.tbarAlign = false;\n this.remove(tbarItems, CLS_TBARPOS);\n }\n this.clearProperty();\n };\n Toolbar.prototype.destroyMode = function () {\n if (this.scrollModule) {\n this.remove(this.scrollModule.element, CLS_RTL);\n this.destroyHScroll();\n }\n this.remove(this.element, CLS_EXTENDEDPOPOPEN);\n if (this.popObj) {\n this.popupRefresh(this.popObj.element, true);\n }\n };\n Toolbar.prototype.add = function (ele, val) {\n ele.classList.add(val);\n };\n Toolbar.prototype.remove = function (ele, val) {\n ele.classList.remove(val);\n };\n Toolbar.prototype.elementFocus = function (ele) {\n var fChild = ele.firstElementChild;\n if (fChild) {\n fChild.focus();\n this.activeEleSwitch(ele);\n }\n else {\n ele.focus();\n }\n };\n Toolbar.prototype.clstElement = function (tbrNavChk, trgt) {\n var clst;\n if (tbrNavChk && this.popObj && isVisible(this.popObj.element)) {\n clst = this.popObj.element.querySelector('.' + CLS_ITEM);\n }\n else if (this.element === trgt || tbrNavChk) {\n clst = this.element.querySelector('.' + CLS_ITEM + ':not(.' + CLS_DISABLE + ' ):not(.' + CLS_SEPARATOR + ' )');\n }\n else {\n clst = closest(trgt, '.' + CLS_ITEM);\n }\n return clst;\n };\n Toolbar.prototype.keyHandling = function (clst, e, trgt, navChk, scrollChk) {\n var popObj = this.popObj;\n var rootEle = this.element;\n var popAnimate = { name: 'FadeOut', duration: 100 };\n switch (e.action) {\n case 'moveRight':\n if (rootEle === trgt) {\n this.elementFocus(clst);\n }\n else if (!navChk) {\n this.eleFocus(clst, 'next');\n }\n break;\n case 'moveLeft':\n if (!navChk) {\n this.eleFocus(clst, 'previous');\n }\n break;\n case 'home':\n case 'end':\n var ele = void 0;\n var nodes = void 0;\n if (clst) {\n var popupCheck = closest(clst, '.e-popup');\n if (popupCheck) {\n if (isVisible(this.popObj.element)) {\n nodes = popupCheck.children;\n if (e.action === 'home') {\n ele = nodes[0];\n }\n else {\n ele = nodes[nodes.length - 1];\n }\n }\n }\n else {\n nodes = this.element.querySelectorAll('.' + CLS_ITEMS + ' .' + CLS_ITEM);\n if (e.action === 'home') {\n ele = nodes[0];\n }\n else {\n ele = nodes[nodes.length - 1];\n }\n }\n if (ele) {\n this.elementFocus(ele);\n }\n }\n break;\n case 'moveUp':\n case 'moveDown':\n var value = e.action === 'moveUp' ? 'previous' : 'next';\n if (popObj && closest(trgt, '.e-popup')) {\n var popEle = popObj.element;\n var popFrstEle = popEle.firstElementChild;\n if ((value === 'previous' && popFrstEle === clst) || (value === 'next' && popEle.lastElementChild === clst)) {\n return;\n }\n else {\n this.eleFocus(clst, value);\n }\n }\n else if (e.action === 'moveDown' && popObj && isVisible(popObj.element)) {\n this.elementFocus(clst);\n }\n break;\n case 'tab':\n if (!scrollChk && !navChk) {\n var ele_1 = clst.firstElementChild;\n if (rootEle === trgt) {\n if (this.activeEle) {\n this.activeEle.focus();\n }\n else {\n this.activeEleRemove(ele_1);\n ele_1.focus();\n }\n this.element.removeAttribute('tabindex');\n }\n }\n break;\n case 'popupClose':\n if (popObj && this.overflowMode !== 'Extended') {\n popObj.hide(popAnimate);\n }\n break;\n case 'popupOpen':\n if (!navChk) {\n return;\n }\n if (popObj && !isVisible(popObj.element)) {\n popObj.element.style.top = rootEle.offsetHeight + 'px';\n popObj.show({ name: 'FadeIn', duration: 100 });\n }\n else {\n popObj.hide(popAnimate);\n }\n break;\n }\n };\n Toolbar.prototype.keyActionHandler = function (e) {\n var trgt = e.target;\n if (trgt.tagName === 'INPUT' || trgt.tagName === 'TEXTAREA' || this.element.classList.contains(CLS_DISABLE)) {\n return;\n }\n e.preventDefault();\n var clst;\n var tbrNavChk = trgt.classList.contains(CLS_TBARNAV);\n var tbarScrollChk = trgt.classList.contains(CLS_TBARSCRLNAV);\n clst = this.clstElement(tbrNavChk, trgt);\n if (clst || tbarScrollChk) {\n this.keyHandling(clst, e, trgt, tbrNavChk, tbarScrollChk);\n }\n };\n /**\n * Specifies the value to disable/enable the Toolbar component.\n * When set to `true`, the component will be disabled.\n * @param {boolean} value - Based on this Boolean value, Toolbar will be enabled (false) or disabled (true).\n * @returns void.\n */\n Toolbar.prototype.disable = function (value) {\n var rootEle = this.element;\n value ? rootEle.classList.add(CLS_DISABLE) : rootEle.classList.remove(CLS_DISABLE);\n rootEle.setAttribute('tabindex', !value ? '0' : '-1');\n if (this.activeEle) {\n this.activeEle.setAttribute('tabindex', !value ? '0' : '-1');\n }\n if (this.scrollModule) {\n this.scrollModule.disable(value);\n }\n if (this.popObj) {\n if (isVisible(this.popObj.element) && this.overflowMode !== 'Extended') {\n this.popObj.hide();\n }\n rootEle.querySelector('#' + rootEle.id + '_nav').setAttribute('tabindex', !value ? '0' : '-1');\n }\n };\n Toolbar.prototype.eleFocus = function (closest, pos) {\n var sib = Object(closest)[pos + 'ElementSibling'];\n var contains = function (el) {\n return el.classList.contains(CLS_SEPARATOR) || el.classList.contains(CLS_DISABLE);\n };\n if (sib) {\n var skipEle = contains(sib);\n if (skipEle) {\n if (Object(sib)[pos + 'ElementSibling']) {\n sib = Object(sib)[pos + 'ElementSibling'];\n skipEle = contains(sib);\n if (skipEle) {\n this.eleFocus(sib, pos);\n return;\n }\n }\n else {\n return;\n }\n }\n this.elementFocus(sib);\n }\n else if (this.tbarAlign) {\n var elem = Object(closest.parentElement)[pos + 'ElementSibling'];\n if (!isNOU(elem) && elem.children.length === 0) {\n elem = Object(elem)[pos + 'ElementSibling'];\n }\n if (!isNOU(elem) && elem.children.length > 0) {\n if (pos === 'next') {\n var el = elem.querySelector('.' + CLS_ITEM);\n if (contains(el)) {\n this.eleFocus(el, pos);\n }\n else {\n el.firstElementChild.focus();\n this.activeEleSwitch(el);\n }\n }\n else {\n var el = elem.lastElementChild;\n if (contains(el)) {\n this.eleFocus(el, pos);\n }\n else {\n this.elementFocus(el);\n }\n }\n }\n }\n };\n Toolbar.prototype.clickHandler = function (e) {\n var trgt = e.target;\n var clsList = trgt.classList;\n var ele = this.element;\n var isPopupElement = !isNOU(closest(trgt, '.' + CLS_POPUPCLASS));\n var popupNav = closest(trgt, ('.' + CLS_TBARNAV));\n if (!popupNav) {\n popupNav = trgt;\n }\n if (!ele.children[0].classList.contains('e-hscroll') && (clsList.contains(CLS_TBARNAV))) {\n clsList = trgt.querySelector('.e-icons').classList;\n }\n if (clsList.contains(CLS_POPUPICON) || clsList.contains(CLS_POPUPDOWN)) {\n this.popupClickHandler(ele, popupNav, CLS_RTL);\n }\n var itemObj;\n var clst = closest(e.target, '.' + CLS_ITEM);\n if ((isNOU(clst) || clst.classList.contains(CLS_DISABLE)) && !popupNav.classList.contains(CLS_TBARNAV)) {\n return;\n }\n if (clst) {\n itemObj = this.items[this.tbarEle.indexOf(clst)];\n }\n var eventArgs = { originalEvent: e, item: itemObj };\n this.trigger('clicked', eventArgs);\n if (!isNOU(this.popObj) && isPopupElement && !eventArgs.cancel && this.overflowMode === 'Popup') {\n this.popObj.hide({ name: 'FadeOut', duration: 100 });\n }\n };\n ;\n Toolbar.prototype.popupClickHandler = function (ele, popupNav, CLS_RTL) {\n var popObj = this.popObj;\n if (isVisible(popObj.element)) {\n popupNav.classList.remove(CLS_TBARNAVACT);\n popObj.hide({ name: 'FadeOut', duration: 100 });\n }\n else {\n if (ele.classList.contains(CLS_RTL)) {\n popObj.enableRtl = true;\n popObj.position = { X: 'left', Y: 'top' };\n }\n if (popObj.offsetX === 0 && !ele.classList.contains(CLS_RTL)) {\n popObj.enableRtl = false;\n popObj.position = { X: 'right', Y: 'top' };\n }\n popObj.dataBind();\n popObj.refreshPosition();\n popObj.element.style.top = this.element.offsetHeight + 'px';\n if (this.overflowMode === 'Extended') {\n popObj.element.style.minHeight = '0px';\n }\n popupNav.classList.add(CLS_TBARNAVACT);\n popObj.show({ name: 'FadeIn', duration: 100 });\n }\n };\n /**\n * To Initialize the control rendering\n * @private\n */\n Toolbar.prototype.render = function () {\n this.initialize();\n this.renderControl();\n this.separator();\n this.wireEvents();\n };\n Toolbar.prototype.initialize = function () {\n var width = formatUnit(this.width);\n var height = formatUnit(this.height);\n if (Browser.info.name !== 'msie' || this.height !== 'auto' || this.overflowMode === 'MultiRow') {\n setStyle(this.element, { 'height': height });\n }\n setStyle(this.element, { 'width': width });\n var ariaAttr = {\n 'role': 'toolbar', 'aria-disabled': 'false', 'aria-haspopup': 'false', 'aria-orientation': 'horizontal',\n };\n attributes(this.element, ariaAttr);\n };\n Toolbar.prototype.renderControl = function () {\n this.trgtEle = (this.element.children.length > 0) ? this.element.querySelector('div') : null;\n this.tbarAlgEle = { lefts: [], centers: [], rights: [] };\n this.renderItems();\n this.renderOverflowMode();\n if (this.tbarAlign) {\n this.itemPositioning();\n }\n if (this.popObj && this.popObj.element.childElementCount > 1 && this.checkPopupRefresh(this.element, this.popObj.element)) {\n this.popupRefresh(this.popObj.element, false);\n }\n };\n Toolbar.prototype.initHScroll = function (element, innerItems) {\n if (!this.scrollModule && this.checkOverflow(element, innerItems[0])) {\n if (this.tbarAlign) {\n this.element.querySelector('.' + CLS_ITEMS + ' .' + CLS_TBARCENTER).removeAttribute('style');\n }\n this.scrollModule = new HScroll({ scrollStep: this.scrollStep, enableRtl: this.enableRtl });\n this.scrollModule.createElement = this.createElement;\n this.scrollModule.appendTo(innerItems[0]);\n this.remove(this.scrollModule.element, CLS_TBARPOS);\n setStyle(this.element, { overflow: 'hidden' });\n }\n };\n Toolbar.prototype.itemWidthCal = function (items) {\n var width = 0;\n var style;\n [].slice.call(selectAll('.' + CLS_ITEM, items)).forEach(function (el) {\n if (isVisible(el)) {\n style = window.getComputedStyle(el);\n width += (el.offsetWidth + parseFloat(style.marginRight) + parseFloat(style.marginLeft));\n }\n });\n return width;\n };\n Toolbar.prototype.checkOverflow = function (element, innerItem) {\n if (isNOU(element) || isNOU(innerItem) || !isVisible(element)) {\n return false;\n }\n var eleWidth = element.offsetWidth;\n var itemWidth = innerItem.offsetWidth;\n if (this.tbarAlign || this.scrollModule || (eleWidth === itemWidth)) {\n itemWidth = this.itemWidthCal(this.scrollModule ? innerItem.querySelector('.e-hscroll-content') : innerItem);\n }\n var popNav = element.querySelector('.' + CLS_TBARNAV);\n var scrollNav = element.querySelector('.' + CLS_TBARSCRLNAV);\n if (itemWidth > eleWidth - (popNav ? popNav.offsetWidth : (scrollNav ? scrollNav.offsetWidth * 2 : 0))) {\n return true;\n }\n else {\n return false;\n }\n };\n /** @hidden */\n Toolbar.prototype.refreshOverflow = function () {\n this.resize();\n };\n Toolbar.prototype.renderOverflowMode = function () {\n var ele = this.element;\n var innerItems = ele.querySelector('.' + CLS_ITEMS);\n var priorityCheck = this.popupPriCount > 0;\n if (ele && ele.children.length > 0) {\n this.offsetWid = ele.offsetWidth;\n this.remove(this.element, 'e-toolpop');\n if (Browser.info.name === 'msie' && this.height === 'auto') {\n ele.style.height = '';\n }\n switch (this.overflowMode) {\n case 'Scrollable':\n if (isNOU(this.scrollModule)) {\n this.initHScroll(ele, ele.getElementsByClassName(CLS_ITEMS));\n }\n break;\n case 'Popup':\n this.add(this.element, 'e-toolpop');\n if (this.tbarAlign) {\n this.removePositioning();\n }\n if (this.checkOverflow(ele, innerItems) || priorityCheck) {\n this.createPopupEle(ele, [].slice.call(selectAll('.' + CLS_ITEMS + ' .' + CLS_ITEM, ele)));\n this.element.querySelector('.' + CLS_TBARNAV).setAttribute('tabIndex', '0');\n }\n if (this.tbarAlign) {\n this.add(innerItems, CLS_TBARPOS);\n this.itemPositioning();\n }\n break;\n case 'MultiRow':\n this.add(innerItems, CLS_MULTIROW);\n if (ele.style.overflow === 'hidden') {\n ele.style.overflow = '';\n }\n if (Browser.info.name === 'msie' || ele.style.height !== 'auto') {\n ele.style.height = 'auto';\n }\n break;\n case 'Extended':\n this.add(this.element, CLS_EXTEANDABLE_TOOLBAR);\n if (this.checkOverflow(ele, innerItems) || priorityCheck) {\n this.createPopupEle(ele, [].slice.call(selectAll('.' + CLS_ITEMS + ' .' + CLS_ITEM, ele)));\n this.element.querySelector('.' + CLS_TBARNAV).setAttribute('tabIndex', '0');\n }\n }\n }\n };\n Toolbar.prototype.separator = function () {\n var element = this.element;\n var eleItem = [].slice.call(element.querySelectorAll('.' + CLS_SEPARATOR));\n var eleInlineItem;\n var multiVar = element.querySelector('.' + CLS_MULTIROW_SEPARATOR);\n var extendVar = element.querySelector('.' + CLS_EXTENDABLE_SEPARATOR);\n eleInlineItem = this.overflowMode === 'MultiRow' ? multiVar : extendVar;\n if (eleInlineItem !== null) {\n if (this.overflowMode === 'MultiRow') {\n eleInlineItem.classList.remove(CLS_MULTIROW_SEPARATOR);\n }\n else if (this.overflowMode === 'Extended') {\n eleInlineItem.classList.remove(CLS_EXTENDABLE_SEPARATOR);\n }\n }\n for (var i = 0; i <= eleItem.length - 1; i++) {\n if (eleItem[i].offsetLeft < 30 && eleItem[i].offsetLeft !== 0) {\n if (this.overflowMode === 'MultiRow') {\n eleItem[i].classList.add(CLS_MULTIROW_SEPARATOR);\n }\n else if (this.overflowMode === 'Extended') {\n eleItem[i].classList.add(CLS_EXTENDABLE_SEPARATOR);\n }\n }\n }\n };\n Toolbar.prototype.createPopupEle = function (ele, innerEle) {\n var innerNav = ele.querySelector('.' + CLS_TBARNAV);\n if (!innerNav) {\n this.createPopupIcon(ele);\n }\n innerNav = ele.querySelector('.' + CLS_TBARNAV);\n var eleWidth = (ele.offsetWidth - (innerNav.offsetWidth));\n this.element.classList.remove('e-rtl');\n setStyle(this.element, { direction: 'initial' });\n this.checkPriority(ele, innerEle, eleWidth, true);\n if (this.enableRtl) {\n this.element.classList.add('e-rtl');\n }\n this.element.style.removeProperty('direction');\n this.createPopup();\n };\n Toolbar.prototype.pushingPoppedEle = function (tbarObj, popupPri, ele, eleHeight, sepHeight) {\n var element = tbarObj.element;\n var nodes = selectAll('.' + CLS_TBAROVERFLOW, ele);\n var nodeIndex = 0;\n var poppedEle = [].slice.call(selectAll('.' + CLS_POPUP, element.querySelector('.' + CLS_ITEMS)));\n var nodePri = 0;\n poppedEle.forEach(function (el, index) {\n nodes = selectAll('.' + CLS_TBAROVERFLOW, ele);\n if (el.classList.contains(CLS_TBAROVERFLOW) && nodes.length > 0) {\n if (tbarObj.tbResize && nodes.length > index) {\n ele.insertBefore(el, nodes[index]);\n ++nodePri;\n }\n else {\n ele.insertBefore(el, ele.children[nodes.length]);\n ++nodePri;\n }\n }\n else if (el.classList.contains(CLS_TBAROVERFLOW)) {\n ele.insertBefore(el, ele.firstChild);\n ++nodePri;\n }\n else if (tbarObj.tbResize && el.classList.contains(CLS_POPOVERFLOW) && ele.children.length > 0 && nodes.length === 0) {\n ele.insertBefore(el, ele.firstChild);\n ++nodePri;\n }\n else if (el.classList.contains(CLS_POPOVERFLOW)) {\n popupPri.push(el);\n }\n else if (tbarObj.tbResize) {\n ele.insertBefore(el, ele.childNodes[nodeIndex + nodePri]);\n ++nodeIndex;\n }\n else {\n ele.appendChild(el);\n }\n if (el.classList.contains(CLS_SEPARATOR)) {\n setStyle(el, { display: '', height: sepHeight + 'px' });\n }\n else {\n setStyle(el, { display: '', height: eleHeight + 'px' });\n }\n });\n popupPri.forEach(function (el) {\n ele.appendChild(el);\n });\n var tbarEle = selectAll('.' + CLS_ITEM, element.querySelector('.' + CLS_ITEMS));\n for (var i = tbarEle.length - 1; i >= 0; i--) {\n var tbarElement = tbarEle[i];\n if (tbarElement.classList.contains(CLS_SEPARATOR) && this.overflowMode !== 'Extended') {\n setStyle(tbarElement, { display: 'none' });\n }\n else {\n break;\n }\n }\n };\n Toolbar.prototype.createPopup = function () {\n var element = this.element;\n var eleHeight;\n var eleItem;\n var sepHeight;\n var sepItem;\n if (this.overflowMode === 'Extended') {\n sepItem = element.querySelector('.' + CLS_SEPARATOR + ':not(.' + CLS_POPUP + ' )');\n sepHeight = (element.style.height === 'auto' || element.style.height === '') ? null : sepItem.offsetHeight;\n }\n eleItem = element.querySelector('.' + CLS_ITEM + ':not(.' + CLS_SEPARATOR + ' ):not(.' + CLS_POPUP + ' )');\n eleHeight = (element.style.height === 'auto' || element.style.height === '') ? null : eleItem.offsetHeight;\n var ele;\n var popupPri = [];\n if (element.querySelector('#' + element.id + '_popup.' + CLS_POPUPCLASS)) {\n ele = element.querySelector('#' + element.id + '_popup.' + CLS_POPUPCLASS);\n }\n else {\n var extendEle = this.createElement('div', {\n id: element.id + '_popup', className: CLS_POPUPCLASS + ' ' + CLS_EXTENDABLECLASS\n });\n var popupEle = this.createElement('div', { id: element.id + '_popup', className: CLS_POPUPCLASS });\n ele = this.overflowMode === 'Extended' ? extendEle : popupEle;\n }\n this.pushingPoppedEle(this, popupPri, ele, eleHeight, sepHeight);\n this.popupInit(element, ele);\n };\n Toolbar.prototype.popupInit = function (element, ele) {\n if (!this.popObj) {\n element.appendChild(ele);\n setStyle(this.element, { overflow: '' });\n var eleStyles = window.getComputedStyle(element);\n var popup = new Popup(null, {\n relateTo: this.element,\n offsetY: parseFloat(eleStyles.height),\n enableRtl: this.enableRtl,\n open: this.popupOpen.bind(this),\n close: this.popupClose.bind(this),\n collision: { Y: this.enableCollision ? 'flip' : 'none' },\n position: this.enableRtl ? { X: 'left', Y: 'top' } : { X: 'right', Y: 'top' }\n });\n if (this.overflowMode === 'Extended') {\n popup.width = parseFloat(eleStyles.width) + ((parseFloat(eleStyles.borderRightWidth)) * 2);\n popup.offsetX = 0;\n }\n popup.appendTo(ele);\n EventHandler.add(document, 'scroll', this.docEvent.bind(this));\n EventHandler.add(document, 'click ', this.docEvent.bind(this));\n popup.element.style.maxHeight = popup.element.offsetHeight + 'px';\n popup.hide();\n this.popObj = popup;\n this.element.setAttribute('aria-haspopup', 'true');\n }\n else {\n var popupEle = this.popObj.element;\n setStyle(popupEle, { maxHeight: '', display: 'block' });\n setStyle(popupEle, { maxHeight: popupEle.offsetHeight + 'px', display: '' });\n }\n };\n Toolbar.prototype.tbarPopupHandler = function (isOpen) {\n if (this.overflowMode === 'Extended') {\n isOpen ? this.add(this.element, CLS_EXTENDEDPOPOPEN) : this.remove(this.element, CLS_EXTENDEDPOPOPEN);\n }\n };\n Toolbar.prototype.popupOpen = function (e) {\n var popObj = this.popObj;\n var eleStyles = window.getComputedStyle(this.element);\n popObj.offsetY = parseFloat(eleStyles.height);\n popObj.dataBind();\n var popupEle = this.popObj.element;\n var toolEle = this.popObj.element.parentElement;\n var popupNav = toolEle.querySelector('.' + CLS_TBARNAV);\n setStyle(popObj.element, { height: 'auto', maxHeight: '' });\n popObj.element.style.maxHeight = popObj.element.offsetHeight + 'px';\n if (this.overflowMode === 'Extended') {\n popObj.element.style.minHeight = '';\n }\n var popupElePos = popupEle.offsetTop + popupEle.offsetHeight + calculatePosition(toolEle).top;\n var popIcon = popupNav.firstElementChild;\n popupNav.classList.add(CLS_TBARNAVACT);\n classList(popIcon, [CLS_POPUPICON], [CLS_POPUPDOWN]);\n this.tbarPopupHandler(true);\n var scrollVal = isNOU(window.scrollY) ? 0 : window.scrollY;\n if (((window.innerHeight + scrollVal) < popupElePos) && (this.element.offsetTop < popupEle.offsetHeight)) {\n var overflowHeight = (popupEle.offsetHeight - ((popupElePos - window.innerHeight - scrollVal) + 5));\n popObj.height = overflowHeight + 'px';\n for (var i = 0; i <= popupEle.childElementCount; i++) {\n var ele = popupEle.children[i];\n if (ele.offsetTop + ele.offsetHeight > overflowHeight) {\n overflowHeight = ele.offsetTop;\n break;\n }\n }\n setStyle(popObj.element, { maxHeight: overflowHeight + 'px' });\n }\n };\n Toolbar.prototype.popupClose = function (e) {\n var element = this.element;\n var popupNav = element.querySelector('.' + CLS_TBARNAV);\n var popIcon = popupNav.firstElementChild;\n popupNav.classList.remove(CLS_TBARNAVACT);\n classList(popIcon, [CLS_POPUPDOWN], [CLS_POPUPICON]);\n this.tbarPopupHandler(false);\n };\n Toolbar.prototype.checkPriority = function (ele, inEle, eleWidth, pre) {\n var popPriority = this.popupPriCount > 0;\n var len = inEle.length;\n var eleWid = eleWidth;\n var sepCheck = 0;\n var itemCount = 0;\n var itemPopCount = 0;\n var checkClass = function (ele, val) {\n var rVal = false;\n val.forEach(function (cls) {\n if (ele.classList.contains(cls)) {\n rVal = true;\n }\n });\n return rVal;\n };\n for (var i = len - 1; i >= 0; i--) {\n var mrgn = parseFloat((window.getComputedStyle(inEle[i])).marginRight);\n mrgn += parseFloat((window.getComputedStyle(inEle[i])).marginLeft);\n var fstEleCheck = inEle[i] === this.tbarEle[0];\n if (fstEleCheck) {\n this.tbarEleMrgn = mrgn;\n }\n var eleWid_1 = fstEleCheck ? (inEle[i].offsetWidth + mrgn) : inEle[i].offsetWidth;\n if (checkClass(inEle[i], [CLS_POPPRI]) && popPriority) {\n inEle[i].classList.add(CLS_POPUP);\n setStyle(inEle[i], { display: 'none', minWidth: eleWid_1 + 'px' });\n itemPopCount++;\n }\n if ((inEle[i].offsetLeft + inEle[i].offsetWidth + mrgn) > eleWidth) {\n if (inEle[i].classList.contains(CLS_SEPARATOR)) {\n if (this.overflowMode === 'Extended') {\n if (itemCount === itemPopCount) {\n var sepEle = inEle[i];\n if (checkClass(sepEle, [CLS_SEPARATOR, CLS_TBARIGNORE])) {\n inEle[i].classList.add(CLS_POPUP);\n itemPopCount++;\n }\n }\n itemCount++;\n }\n else if (this.overflowMode === 'Popup') {\n if (sepCheck > 0 && itemCount === itemPopCount) {\n var sepEle = inEle[i + itemCount + (sepCheck - 1)];\n if (checkClass(sepEle, [CLS_SEPARATOR, CLS_TBARIGNORE])) {\n setStyle(sepEle, { display: 'none' });\n }\n }\n sepCheck++;\n itemCount = 0;\n itemPopCount = 0;\n }\n }\n else {\n itemCount++;\n }\n if (inEle[i].classList.contains(CLS_TBAROVERFLOW) && pre) {\n eleWidth -= (inEle[i].offsetWidth + (mrgn));\n }\n else if (!checkClass(inEle[i], [CLS_SEPARATOR, CLS_TBARIGNORE])) {\n inEle[i].classList.add(CLS_POPUP);\n setStyle(inEle[i], { display: 'none', minWidth: eleWid_1 + 'px' });\n itemPopCount++;\n }\n else {\n eleWidth -= (inEle[i].offsetWidth + (mrgn));\n }\n }\n }\n if (pre) {\n var popedEle = selectAll('.' + CLS_ITEM + ':not(.' + CLS_POPUP + ')', this.element);\n this.checkPriority(ele, popedEle, eleWid, false);\n }\n };\n Toolbar.prototype.createPopupIcon = function (element) {\n var id = element.id.concat('_nav');\n var className = 'e-' + element.id.concat('_nav ' + CLS_POPUPNAV);\n className = this.overflowMode === 'Extended' ? className + ' ' + CLS_EXTENDPOPUP : className;\n var nav = this.createElement('div', { id: id, className: className });\n if (Browser.info.name === 'msie' || Browser.info.name === 'edge') {\n nav.classList.add('e-ie-align');\n }\n var navItem = this.createElement('div', { className: CLS_POPUPDOWN + ' e-icons' });\n nav.appendChild(navItem);\n nav.setAttribute('tabindex', '0');\n element.appendChild(nav);\n };\n Toolbar.prototype.tbarPriRef = function (inEle, indx, sepPri, el, des, elWid, wid, ig) {\n var ignoreCount = ig;\n var popEle = this.popObj.element;\n var query = '.' + CLS_ITEM + ':not(.' + CLS_SEPARATOR + '):not(.' + CLS_TBAROVERFLOW + ')';\n var priEleCnt = selectAll('.' + CLS_POPUP + ':not(.' + CLS_TBAROVERFLOW + ')', popEle).length;\n var checkClass = function (ele, val) {\n return ele.classList.contains(val);\n };\n if (selectAll(query, inEle).length === 0) {\n var eleSep = inEle.children[indx - (indx - sepPri) - 1];\n var ignoreCheck = (!isNOU(eleSep) && checkClass(eleSep, CLS_TBARIGNORE));\n if ((!isNOU(eleSep) && checkClass(eleSep, CLS_SEPARATOR) && !isVisible(eleSep)) || ignoreCheck) {\n var sepDisplay = 'none';\n eleSep.style.display = 'inherit';\n var eleSepWidth = eleSep.offsetWidth + (parseFloat(window.getComputedStyle(eleSep).marginRight) * 2);\n var prevSep = eleSep.previousElementSibling;\n if ((elWid + eleSepWidth) < wid || des) {\n inEle.insertBefore(el, inEle.children[(indx + ignoreCount) - (indx - sepPri)]);\n if (!isNOU(prevSep)) {\n prevSep.style.display = '';\n }\n }\n else {\n if (prevSep.classList.contains(CLS_SEPARATOR)) {\n prevSep.style.display = sepDisplay;\n }\n }\n eleSep.style.display = '';\n }\n else {\n inEle.insertBefore(el, inEle.children[(indx + ignoreCount) - (indx - sepPri)]);\n }\n }\n else {\n inEle.insertBefore(el, inEle.children[(indx + ignoreCount) - priEleCnt]);\n }\n };\n Toolbar.prototype.popupRefresh = function (popupEle, destroy) {\n var _this = this;\n var ele = this.element;\n var popNav = ele.querySelector('.' + CLS_TBARNAV);\n var innerEle = ele.querySelector('.' + CLS_ITEMS);\n if (isNOU(popNav)) {\n return;\n }\n innerEle.removeAttribute('style');\n popupEle.style.display = 'block';\n var width = ele.offsetWidth - (popNav.offsetWidth + innerEle.offsetWidth);\n var popupEleWidth = 0;\n [].slice.call(popupEle.children).forEach(function (el) {\n popupEleWidth += _this.popupEleWidth(el);\n setStyle(el, { 'position': '' });\n });\n if ((width + popNav.offsetWidth) > (popupEleWidth) && this.popupPriCount === 0) {\n destroy = true;\n }\n this.popupEleRefresh(width, popupEle, destroy);\n popupEle.style.display = '';\n if (popupEle.children.length === 0 && popNav && this.popObj) {\n detach(popNav);\n popNav = null;\n this.popObj.destroy();\n detach(this.popObj.element);\n this.popObj = null;\n ele.setAttribute('aria-haspopup', 'false');\n ele.classList.remove('e-toolpop');\n }\n };\n Toolbar.prototype.ignoreEleFetch = function (index, innerEle) {\n var ignoreEle = [].slice.call(innerEle.querySelectorAll('.' + CLS_TBARIGNORE));\n var ignoreInx = [];\n var count = 0;\n if (ignoreEle.length > 0) {\n ignoreEle.forEach(function (ele) {\n ignoreInx.push([].slice.call(innerEle.children).indexOf(ele));\n });\n }\n else {\n return 0;\n }\n ignoreInx.forEach(function (val) {\n if (val <= index) {\n count++;\n }\n });\n return count;\n };\n Toolbar.prototype.checkPopupRefresh = function (root, popEle) {\n popEle.style.display = 'block';\n var elWid = this.popupEleWidth(popEle.firstElementChild);\n popEle.firstElementChild.style.removeProperty('Position');\n var tbarWidth = root.offsetWidth - root.querySelector('.' + CLS_TBARNAV).offsetWidth;\n var tbarItemsWid = root.querySelector('.' + CLS_ITEMS).offsetWidth;\n popEle.style.removeProperty('display');\n if (tbarWidth > (elWid + tbarItemsWid)) {\n return true;\n }\n return false;\n };\n Toolbar.prototype.popupEleWidth = function (el) {\n el.style.position = 'absolute';\n var elWidth = el.offsetWidth;\n var btnText = el.querySelector('.' + CLS_TBARBTNTEXT);\n if (el.classList.contains('e-tbtn-align') || el.classList.contains(CLS_TBARTEXT)) {\n var btn = el.children[0];\n if (!isNOU(btnText) && el.classList.contains(CLS_TBARTEXT)) {\n btnText.style.display = 'none';\n }\n else if (!isNOU(btnText) && el.classList.contains(CLS_POPUPTEXT)) {\n btnText.style.display = 'block';\n }\n btn.style.minWidth = '0%';\n elWidth = parseFloat(el.style.minWidth);\n btn.style.minWidth = '';\n if (!isNOU(btnText)) {\n btnText.style.display = '';\n }\n }\n return elWidth;\n };\n Toolbar.prototype.popupEleRefresh = function (width, popupEle, destroy) {\n var popPriority = this.popupPriCount > 0;\n var eleSplice = this.tbarEle;\n var priEleCnt;\n var index;\n var checkOverflow;\n var innerEle = this.element.querySelector('.' + CLS_ITEMS);\n var ignoreCount = 0;\n var _loop_1 = function (el) {\n if (el.classList.contains(CLS_POPPRI) && popPriority && !destroy) {\n return \"continue\";\n }\n var elWidth = this_1.popupEleWidth(el);\n if (el === this_1.tbarEle[0]) {\n elWidth += this_1.tbarEleMrgn;\n }\n el.style.position = '';\n if (elWidth < width || destroy) {\n el.style.minWidth = '';\n if (!el.classList.contains(CLS_POPOVERFLOW)) {\n el.classList.remove(CLS_POPUP);\n }\n index = this_1.tbarEle.indexOf(el);\n if (this_1.tbarAlign) {\n var pos = this_1.items[index].align;\n index = this_1.tbarAlgEle[(pos + 's').toLowerCase()].indexOf(el);\n eleSplice = this_1.tbarAlgEle[(pos + 's').toLowerCase()];\n innerEle = this_1.element.querySelector('.' + CLS_ITEMS + ' .' + 'e-toolbar-' + pos.toLowerCase());\n }\n var sepBeforePri_1 = 0;\n if (this_1.overflowMode !== 'Extended') {\n eleSplice.slice(0, index).forEach(function (el) {\n if (el.classList.contains(CLS_TBAROVERFLOW) || el.classList.contains(CLS_SEPARATOR)) {\n if (el.classList.contains(CLS_SEPARATOR)) {\n el.style.display = '';\n width -= el.offsetWidth;\n }\n sepBeforePri_1++;\n }\n });\n }\n ignoreCount = this_1.ignoreEleFetch(index, innerEle);\n if (el.classList.contains(CLS_TBAROVERFLOW)) {\n this_1.tbarPriRef(innerEle, index, sepBeforePri_1, el, destroy, elWidth, width, ignoreCount);\n width -= el.offsetWidth;\n }\n else if (index === 0) {\n innerEle.insertBefore(el, innerEle.firstChild);\n width -= el.offsetWidth;\n }\n else {\n priEleCnt = selectAll('.' + CLS_TBAROVERFLOW, this_1.popObj.element).length;\n innerEle.insertBefore(el, innerEle.children[(index + ignoreCount) - priEleCnt]);\n width -= el.offsetWidth;\n }\n el.style.height = '';\n }\n else {\n return \"break\";\n }\n };\n var this_1 = this;\n for (var _i = 0, _a = [].slice.call(popupEle.children); _i < _a.length; _i++) {\n var el = _a[_i];\n var state_1 = _loop_1(el);\n if (state_1 === \"break\")\n break;\n }\n checkOverflow = this.checkOverflow(this.element, this.element.getElementsByClassName(CLS_ITEMS)[0]);\n if (checkOverflow && !destroy) {\n this.renderOverflowMode();\n }\n };\n Toolbar.prototype.removePositioning = function () {\n var item = this.element.querySelector('.' + CLS_ITEMS);\n if (isNOU(item) || !item.classList.contains(CLS_TBARPOS)) {\n return;\n }\n this.remove(item, CLS_TBARPOS);\n var innerItem = [].slice.call(item.childNodes);\n innerItem[1].removeAttribute('style');\n innerItem[2].removeAttribute('style');\n };\n Toolbar.prototype.refreshPositioning = function () {\n var item = this.element.querySelector('.' + CLS_ITEMS);\n this.add(item, CLS_TBARPOS);\n this.itemPositioning();\n };\n Toolbar.prototype.itemPositioning = function () {\n var item = this.element.querySelector('.' + CLS_ITEMS);\n if (isNOU(item) || !item.classList.contains(CLS_TBARPOS)) {\n return;\n }\n var popupNav = this.element.querySelector('.' + CLS_TBARNAV);\n var innerItem;\n if (this.scrollModule) {\n innerItem = [].slice.call(item.querySelector('.' + CLS_TBARSCROLL).children);\n }\n else {\n innerItem = [].slice.call(item.childNodes);\n }\n var margin = innerItem[0].offsetWidth + innerItem[2].offsetWidth;\n var tbarWid = this.element.offsetWidth;\n if (popupNav) {\n tbarWid -= popupNav.offsetWidth;\n var popWid = popupNav.offsetWidth + 'px';\n innerItem[2].removeAttribute('style');\n this.enableRtl ? innerItem[2].style.left = popWid : innerItem[2].style.right = popWid;\n }\n if (tbarWid <= margin) {\n return;\n }\n var value = (((tbarWid - margin)) - innerItem[1].offsetWidth) / 2;\n innerItem[1].removeAttribute('style');\n var mrgn = (innerItem[0].offsetWidth + value) + 'px';\n this.enableRtl ? innerItem[1].style.marginRight = mrgn : innerItem[1].style.marginLeft = mrgn;\n };\n Toolbar.prototype.tbarItemAlign = function (item, itemEle, pos) {\n var _this = this;\n if (item.showAlwaysInPopup && item.overflow !== 'Show') {\n return;\n }\n var alignDiv = [];\n alignDiv.push(this.createElement('div', { className: CLS_TBARLEFT }));\n alignDiv.push(this.createElement('div', { className: CLS_TBARCENTER }));\n alignDiv.push(this.createElement('div', { className: CLS_TBARRIGHT }));\n if (pos === 0 && item.align !== 'Left') {\n alignDiv.forEach(function (ele) {\n itemEle.appendChild(ele);\n });\n this.tbarAlign = true;\n this.add(itemEle, CLS_TBARPOS);\n }\n else if (item.align !== 'Left') {\n var alignEle = itemEle.childNodes;\n var leftAlign_1 = alignDiv[0];\n [].slice.call(alignEle).forEach(function (el) {\n _this.tbarAlgEle.lefts.push(el);\n leftAlign_1.appendChild(el);\n });\n itemEle.appendChild(leftAlign_1);\n itemEle.appendChild(alignDiv[1]);\n itemEle.appendChild(alignDiv[2]);\n this.tbarAlign = true;\n this.add(itemEle, CLS_TBARPOS);\n }\n };\n Toolbar.prototype.ctrlTemplate = function () {\n var _this = this;\n this.ctrlTem = this.trgtEle.cloneNode(true);\n this.add(this.trgtEle, CLS_ITEMS);\n this.tbarEle = [];\n var innerEle = [].slice.call(this.trgtEle.children);\n innerEle.forEach(function (ele) {\n if (ele.tagName === 'DIV') {\n _this.tbarEle.push(ele);\n ele.setAttribute('aria-disabled', 'false');\n _this.add(ele, CLS_ITEM);\n }\n });\n };\n Toolbar.prototype.renderItems = function () {\n var ele = this.element;\n var itemEleDom;\n var innerItem;\n var innerPos;\n var items = this.items;\n if (ele && ele.children.length > 0) {\n itemEleDom = ele.querySelector('.' + CLS_ITEMS);\n }\n if (this.trgtEle != null) {\n this.ctrlTemplate();\n }\n else if (ele && items.length > 0) {\n if (!itemEleDom) {\n itemEleDom = this.createElement('div', { className: CLS_ITEMS });\n }\n for (var i = 0; i < items.length; i++) {\n innerItem = this.renderSubComponent(items[i], i);\n if (this.tbarEle.indexOf(innerItem) === -1) {\n this.tbarEle.push(innerItem);\n }\n if (!this.tbarAlign) {\n this.tbarItemAlign(items[i], itemEleDom, i);\n }\n innerPos = itemEleDom.querySelector('.e-toolbar-' + items[i].align.toLowerCase());\n if (innerPos) {\n if (!(items[i].showAlwaysInPopup && items[i].overflow !== 'Show')) {\n this.tbarAlgEle[(items[i].align + 's').toLowerCase()].push(innerItem);\n }\n innerPos.appendChild(innerItem);\n }\n else {\n itemEleDom.appendChild(innerItem);\n }\n }\n ele.appendChild(itemEleDom);\n }\n };\n Toolbar.prototype.setAttr = function (attr, element) {\n var key = Object.keys(attr);\n var keyVal;\n for (var i = 0; i < key.length; i++) {\n keyVal = key[i];\n keyVal === 'class' ? this.add(element, attr[keyVal]) : element.setAttribute(keyVal, attr[keyVal]);\n }\n };\n /**\n * Enables or disables the specified Toolbar item.\n * @param {HTMLElement|NodeList} items - DOM element or an array of items to be enabled or disabled.\n * @param {boolean} isEnable - Boolean value that determines whether the command should be enabled or disabled.\n * By default, `isEnable` is set to true.\n * @returns void.\n */\n Toolbar.prototype.enableItems = function (items, isEnable) {\n var elements = items;\n var len = elements.length;\n if (isNOU(isEnable)) {\n isEnable = true;\n }\n var enable = function (isEnable, ele) {\n if (isEnable) {\n ele.classList.remove(CLS_DISABLE);\n ele.setAttribute('aria-disabled', 'false');\n }\n else {\n ele.classList.add(CLS_DISABLE);\n ele.setAttribute('aria-disabled', 'true');\n }\n };\n if (len && len > 1) {\n for (var _i = 0, _a = [].slice.call(elements); _i < _a.length; _i++) {\n var ele = _a[_i];\n enable(isEnable, ele);\n }\n isEnable ? removeClass(elements, CLS_DISABLE) : addClass(elements, CLS_DISABLE);\n }\n else {\n var ele = void 0;\n ele = (len && len === 1) ? elements[0] : items;\n enable(isEnable, ele);\n }\n };\n /**\n * Adds new items to the Toolbar that accepts an array as Toolbar items.\n * @param {ItemsModel[]} items - DOM element or an array of items to be added to the Toolbar.\n * @param {number} index - Number value that determines where the command is to be added. By default, index is 0.\n * @returns void.\n */\n Toolbar.prototype.addItems = function (items, index) {\n var innerItems;\n var itemsDiv = this.element.querySelector('.' + CLS_ITEMS);\n if (isNOU(itemsDiv)) {\n this.itemsRerender(items);\n return;\n }\n var innerEle;\n var itemAgn = 'Left';\n if (isNOU(index)) {\n index = 0;\n }\n items.forEach(function (e) {\n if (!isNOU(e.align) && e.align !== 'Left' && itemAgn === 'Left') {\n itemAgn = e.align;\n }\n });\n for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {\n var item = items_1[_i];\n if (isNOU(item.type)) {\n item.type = 'Button';\n }\n innerItems = selectAll('.' + CLS_ITEM, this.element);\n item.align = itemAgn;\n innerEle = this.renderSubComponent(item, index);\n if (this.tbarEle.length >= index && innerItems.length >= 0) {\n if (isNOU(this.scrollModule)) {\n this.destroyMode();\n }\n var algIndex = item.align[0] === 'L' ? 0 : item.align[0] === 'C' ? 1 : 2;\n var ele = void 0;\n if (!this.tbarAlign && itemAgn !== 'Left') {\n this.tbarItemAlign(item, itemsDiv, 1);\n this.tbarAlign = true;\n ele = closest(innerItems[0], '.' + CLS_ITEMS).children[algIndex];\n ele.appendChild(innerEle);\n this.tbarAlgEle[(item.align + 's').toLowerCase()].push(innerEle);\n this.refreshPositioning();\n }\n else if (this.tbarAlign) {\n ele = closest(innerItems[0], '.' + CLS_ITEMS).children[algIndex];\n ele.insertBefore(innerEle, ele.children[index]);\n this.tbarAlgEle[(item.align + 's').toLowerCase()].splice(index, 0, innerEle);\n this.refreshPositioning();\n }\n else if (innerItems.length === 0) {\n innerItems = selectAll('.' + CLS_ITEMS, this.element);\n innerItems[0].appendChild(innerEle);\n }\n else {\n innerItems[0].parentNode.insertBefore(innerEle, innerItems[index]);\n }\n this.items.splice(index, 0, item);\n this.tbarEle.splice(index, 0, innerEle);\n index++;\n this.offsetWid = itemsDiv.offsetWidth;\n }\n }\n itemsDiv.style.width = '';\n this.renderOverflowMode();\n };\n /**\n * Removes the items from the Toolbar. Acceptable arguments are index of item/HTMLElement/node list.\n * @param {number|HTMLElement|NodeList|HTMLElement[]} args\n * Index or DOM element or an Array of item which is to be removed from the Toolbar.\n * @returns void.\n */\n Toolbar.prototype.removeItems = function (args) {\n var elements = args;\n var index;\n var innerItems = [].slice.call(selectAll('.' + CLS_ITEM, this.element));\n if (typeof (elements) === 'number') {\n index = parseInt(args.toString(), 10);\n this.removeItemByIndex(index, innerItems);\n }\n else {\n if (elements && elements.length > 1) {\n for (var _i = 0, _a = [].slice.call(elements); _i < _a.length; _i++) {\n var ele = _a[_i];\n index = this.tbarEle.indexOf(ele);\n this.removeItemByIndex(index, innerItems);\n innerItems = selectAll('.' + CLS_ITEM, this.element);\n }\n }\n else {\n var ele = (elements && elements.length && elements.length === 1) ? elements[0] : args;\n index = innerItems.indexOf(ele);\n this.removeItemByIndex(index, innerItems);\n }\n }\n this.resize();\n };\n Toolbar.prototype.removeItemByIndex = function (index, innerItems) {\n if (this.tbarEle[index] && innerItems[index]) {\n var eleIdx = this.tbarEle.indexOf(innerItems[index]);\n if (this.tbarAlign) {\n var indexAgn = void 0;\n indexAgn = this.tbarAlgEle[(this.items[eleIdx].align + 's').toLowerCase()].indexOf(this.tbarEle[eleIdx]);\n this.tbarAlgEle[(this.items[eleIdx].align + 's').toLowerCase()].splice(indexAgn, 1);\n }\n detach(innerItems[index]);\n this.items.splice(eleIdx, 1);\n this.tbarEle.splice(eleIdx, 1);\n }\n };\n Toolbar.prototype.templateRender = function (templateProp, innerEle, item, index) {\n var itemType = item.type;\n var eleObj = templateProp;\n var isComponent;\n if (typeof (templateProp) === 'object') {\n isComponent = typeof (eleObj.appendTo) === 'function';\n }\n if (typeof (templateProp) === 'string' || !isComponent) {\n var templateFn = void 0;\n var val = templateProp;\n val = (typeof (templateProp) === 'string') ? templateProp.trim() : templateProp;\n var e = void 0;\n try {\n if (typeof (templateProp) === 'object' && !isNOU(templateProp.tagName)) {\n innerEle.appendChild(templateProp);\n }\n else if (document.querySelectorAll(val).length) {\n var ele = document.querySelector(val);\n var tempStr = ele.outerHTML.trim();\n innerEle.appendChild(ele);\n ele.style.display = '';\n if (!isNOU(tempStr)) {\n this.tempId.push(val);\n }\n }\n }\n catch (e) {\n templateFn = templateCompiler(val);\n }\n var tempArray = void 0;\n if (!isNOU(templateFn)) {\n tempArray = templateFn({}, this, 'template');\n }\n if (!isNOU(tempArray) && tempArray.length > 0) {\n [].slice.call(tempArray).forEach(function (ele) {\n if (!isNOU(ele.tagName)) {\n ele.style.display = '';\n }\n innerEle.appendChild(ele);\n });\n }\n }\n else if (itemType === 'Input') {\n var ele = this.createElement('input');\n item.id ? (ele.id = item.id) : (ele.id = getUniqueID('tbr-ipt'));\n innerEle.appendChild(ele);\n eleObj.appendTo(ele);\n }\n this.add(innerEle, CLS_TEMPLATE);\n this.tbarEle.push(innerEle);\n };\n Toolbar.prototype.buttonRendering = function (item, innerEle) {\n var dom = this.createElement('button', { className: CLS_TBARBTN });\n dom.setAttribute('type', 'button');\n var textStr = item.text;\n var iconCss;\n var iconPos;\n item.id ? (dom.id = item.id) : dom.id = getUniqueID('e-tbr-btn');\n var btnTxt = this.createElement('div', { className: 'e-tbar-btn-text' });\n if (textStr) {\n btnTxt.innerHTML = textStr;\n dom.appendChild(btnTxt);\n dom.classList.add('e-tbtn-txt');\n }\n else {\n this.add(innerEle, 'e-tbtn-align');\n }\n if (item.prefixIcon || item.suffixIcon) {\n if ((item.prefixIcon && item.suffixIcon) || item.prefixIcon) {\n iconCss = item.prefixIcon + ' e-icons';\n iconPos = 'Left';\n }\n else {\n iconCss = item.suffixIcon + ' e-icons';\n iconPos = 'Right';\n }\n }\n var btnObj = new Button({ iconCss: iconCss, iconPosition: iconPos });\n btnObj.createElement = this.createElement;\n btnObj.appendTo(dom);\n if (item.width) {\n setStyle(dom, { 'width': formatUnit(item.width) });\n }\n return dom;\n };\n Toolbar.prototype.renderSubComponent = function (item, index) {\n var innerEle;\n var dom;\n innerEle = this.createElement('div', { className: CLS_ITEM });\n innerEle.setAttribute('aria-disabled', 'false');\n if (!this.tbarEle) {\n this.tbarEle = [];\n }\n if (item.htmlAttributes) {\n this.setAttr(item.htmlAttributes, innerEle);\n }\n if (item.tooltipText) {\n var tempDom = this.createElement('div', { innerHTML: item.tooltipText });\n innerEle.setAttribute('title', tempDom.textContent);\n }\n if (item.cssClass) {\n innerEle.className = innerEle.className + ' ' + item.cssClass;\n }\n if (item.template) {\n this.templateRender(item.template, innerEle, item, index);\n }\n else {\n switch (item.type) {\n case 'Button':\n dom = this.buttonRendering(item, innerEle);\n dom.setAttribute('tabindex', '-1');\n innerEle.appendChild(dom);\n innerEle.addEventListener('click', this.itemClick.bind(this));\n break;\n case 'Separator':\n this.add(innerEle, CLS_SEPARATOR);\n break;\n }\n }\n if (item.showTextOn) {\n var sTxt = item.showTextOn;\n if (sTxt === 'Toolbar') {\n this.add(innerEle, CLS_POPUPTEXT);\n this.add(innerEle, 'e-tbtn-align');\n }\n else if (sTxt === 'Overflow') {\n this.add(innerEle, CLS_TBARTEXT);\n }\n }\n if (item.overflow) {\n var overflow = item.overflow;\n if (overflow === 'Show') {\n this.add(innerEle, CLS_TBAROVERFLOW);\n }\n else if (overflow === 'Hide') {\n if (!innerEle.classList.contains(CLS_SEPARATOR)) {\n this.add(innerEle, CLS_POPOVERFLOW);\n }\n }\n }\n if (item.overflow !== 'Show' && item.showAlwaysInPopup && !innerEle.classList.contains(CLS_SEPARATOR)) {\n this.add(innerEle, CLS_POPPRI);\n this.popupPriCount++;\n }\n return innerEle;\n };\n Toolbar.prototype.itemClick = function (e) {\n this.activeEleSwitch(e.currentTarget);\n };\n Toolbar.prototype.activeEleSwitch = function (ele) {\n this.activeEleRemove(ele.firstElementChild);\n this.activeEle.focus();\n };\n Toolbar.prototype.activeEleRemove = function (curEle) {\n if (!isNOU(this.activeEle)) {\n this.activeEle.setAttribute('tabindex', '-1');\n }\n this.activeEle = curEle;\n if (isNOU(this.trgtEle) && !curEle.parentElement.classList.contains(CLS_TEMPLATE)) {\n curEle.removeAttribute('tabindex');\n }\n else {\n this.activeEle.setAttribute('tabindex', '0');\n }\n };\n Toolbar.prototype.getPersistData = function () {\n return this.addOnPersist([]);\n };\n /**\n * Returns the current module name.\n * @returns string\n * @private\n */\n Toolbar.prototype.getModuleName = function () {\n return 'toolbar';\n };\n Toolbar.prototype.itemsRerender = function (newProp) {\n this.items = this.tbarItemsCol;\n this.destroyMode();\n this.destroyItems();\n this.items = newProp;\n this.tbarItemsCol = this.items;\n this.renderItems();\n this.renderOverflowMode();\n };\n Toolbar.prototype.resize = function () {\n var ele = this.element;\n this.tbResize = true;\n if (this.tbarAlign) {\n this.itemPositioning();\n }\n if (this.popObj && this.overflowMode === 'Popup') {\n this.popObj.hide();\n }\n var checkOverflow = this.checkOverflow(ele, ele.getElementsByClassName(CLS_ITEMS)[0]);\n if (!checkOverflow) {\n this.destroyHScroll();\n }\n if (checkOverflow && this.scrollModule && (this.offsetWid === ele.offsetWidth)) {\n return;\n }\n if (this.offsetWid > ele.offsetWidth || checkOverflow) {\n this.renderOverflowMode();\n }\n if (this.popObj) {\n if (this.overflowMode === 'Extended') {\n var eleStyles = window.getComputedStyle(this.element);\n this.popObj.width = parseFloat(eleStyles.width) + ((parseFloat(eleStyles.borderRightWidth)) * 2);\n }\n if (this.tbarAlign) {\n this.removePositioning();\n }\n this.popupRefresh(this.popObj.element, false);\n if (this.tbarAlign) {\n this.refreshPositioning();\n }\n }\n this.offsetWid = ele.offsetWidth;\n this.tbResize = false;\n this.separator();\n };\n /**\n * Gets called when the model property changes.The data that describes the old and new values of the property that changed.\n * @param {ToolbarModel} newProp\n * @param {ToolbarModel} oldProp\n * @returns void\n * @private\n */\n Toolbar.prototype.onPropertyChanged = function (newProp, oldProp) {\n var tEle = this.element;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'items':\n if (!(newProp.items instanceof Array && oldProp.items instanceof Array)) {\n var changedProb = Object.keys(newProp.items);\n for (var i = 0; i < changedProb.length; i++) {\n var index = parseInt(Object.keys(newProp.items)[i], 10);\n var property = Object.keys(newProp.items[index])[0];\n var oldProperty = Object(oldProp.items[index])[property];\n var newProperty = Object(newProp.items[index])[property];\n if (this.tbarAlign || property === 'align') {\n this.refresh();\n break;\n }\n var popupPriCheck = property === 'showAlwaysInPopup' && !newProperty;\n var booleanCheck = property === 'overflow' && this.popupPriCount !== 0;\n if ((popupPriCheck) || (this.items[index].showAlwaysInPopup) && booleanCheck) {\n --this.popupPriCount;\n }\n if (isNOU(this.scrollModule)) {\n this.destroyMode();\n }\n var itemCol = [].slice.call(selectAll('.' + CLS_ITEMS + ' .' + CLS_ITEM, tEle));\n detach(itemCol[index]);\n this.tbarEle.splice(index, 1);\n this.addItems([this.items[index]], index);\n this.items.splice(index, 1);\n if (this.items[index].template) {\n this.tbarEle.splice(this.items.length, 1);\n }\n }\n }\n else {\n this.itemsRerender(newProp.items);\n }\n break;\n case 'width':\n var wid = tEle.offsetWidth;\n setStyle(tEle, { 'width': formatUnit(newProp.width) });\n this.renderOverflowMode();\n if (this.popObj && wid < tEle.offsetWidth) {\n this.popupRefresh(this.popObj.element, false);\n }\n break;\n case 'height':\n setStyle(this.element, { 'height': formatUnit(newProp.height) });\n break;\n case 'overflowMode':\n this.destroyMode();\n this.renderOverflowMode();\n if (this.enableRtl) {\n this.add(tEle, CLS_RTL);\n }\n this.refreshOverflow();\n break;\n case 'enableRtl':\n newProp.enableRtl ? this.add(tEle, CLS_RTL) : this.remove(tEle, CLS_RTL);\n if (!isNOU(this.scrollModule)) {\n newProp.enableRtl ? this.add(this.scrollModule.element, CLS_RTL) : this.remove(this.scrollModule.element, CLS_RTL);\n }\n if (!isNOU(this.popObj)) {\n newProp.enableRtl ? this.add(this.popObj.element, CLS_RTL) : this.remove(this.popObj.element, CLS_RTL);\n }\n if (this.tbarAlign) {\n this.itemPositioning();\n }\n break;\n }\n }\n };\n /**\n * Shows or hides the Toolbar item that is in the specified index.\n * @param {number} index - Index value of target item.\n * @param {boolean} value - Based on this Boolean value, item will be hide (true) or show (false). By default, value is false.\n * @returns void.\n */\n Toolbar.prototype.hideItem = function (index, value) {\n if (this.tbarEle[index]) {\n var innerItems = [].slice.call(selectAll('.' + CLS_ITEM, this.element));\n if (value === true) {\n innerItems[index].classList.add(CLS_HIDDEN);\n }\n else {\n innerItems[index].classList.remove(CLS_HIDDEN);\n }\n this.refreshOverflow();\n }\n };\n __decorate([\n Collection([], Item)\n ], Toolbar.prototype, \"items\", void 0);\n __decorate([\n Property('auto')\n ], Toolbar.prototype, \"width\", void 0);\n __decorate([\n Property('auto')\n ], Toolbar.prototype, \"height\", void 0);\n __decorate([\n Property('Scrollable')\n ], Toolbar.prototype, \"overflowMode\", void 0);\n __decorate([\n Property(false)\n ], Toolbar.prototype, \"enableRtl\", void 0);\n __decorate([\n Event()\n ], Toolbar.prototype, \"clicked\", void 0);\n __decorate([\n Event()\n ], Toolbar.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Toolbar.prototype, \"destroyed\", void 0);\n __decorate([\n Event()\n ], Toolbar.prototype, \"beforeCreate\", void 0);\n Toolbar = __decorate([\n NotifyPropertyChanges\n ], Toolbar);\n return Toolbar;\n}(Component));\nexport { Toolbar };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, EventHandler, Property, Event, KeyboardEvents, rippleEffect } from '@syncfusion/ej2-base';\nimport { getUniqueID, compile as templateCompiler } from '@syncfusion/ej2-base';\nimport { addClass, isVisible, closest, attributes, classList, detach, select } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, ChildProperty, Collection, Animation } from '@syncfusion/ej2-base';\nimport { setStyleAttribute as setStyle, Complex } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined as isNOU, formatUnit, selectAll } from '@syncfusion/ej2-base';\nvar CLS_ACRDN_ROOT = 'e-acrdn-root';\nvar CLS_ROOT = 'e-accordion';\nvar CLS_ITEM = 'e-acrdn-item';\nvar CLS_ITEMFOCUS = 'e-item-focus';\nvar CLS_ITEMHIDE = 'e-hide';\nvar CLS_HEADER = 'e-acrdn-header';\nvar CLS_HEADERICN = 'e-acrdn-header-icon';\nvar CLS_HEADERCTN = 'e-acrdn-header-content';\nvar CLS_CONTENT = 'e-acrdn-panel';\nvar CLS_CTENT = 'e-acrdn-content';\nvar CLS_TOOGLEICN = 'e-toggle-icon';\nvar CLS_COLLAPSEICN = 'e-tgl-collapse-icon e-icons';\nvar CLS_EXPANDICN = 'e-expand-icon';\nvar CLS_RTL = 'e-rtl';\nvar CLS_CTNHIDE = 'e-content-hide';\nvar CLS_SLCT = 'e-select';\nvar CLS_SLCTED = 'e-selected';\nvar CLS_ACTIVE = 'e-active';\nvar CLS_ANIMATE = 'e-animate';\nvar CLS_DISABLE = 'e-overlay';\nvar CLS_TOGANIMATE = 'e-toggle-animation';\nvar CLS_NEST = 'e-nested';\nvar CLS_EXPANDSTATE = 'e-expand-state';\nvar AccordionActionSettings = /** @class */ (function (_super) {\n __extends(AccordionActionSettings, _super);\n function AccordionActionSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('SlideDown')\n ], AccordionActionSettings.prototype, \"effect\", void 0);\n __decorate([\n Property(400)\n ], AccordionActionSettings.prototype, \"duration\", void 0);\n __decorate([\n Property('linear')\n ], AccordionActionSettings.prototype, \"easing\", void 0);\n return AccordionActionSettings;\n}(ChildProperty));\nexport { AccordionActionSettings };\nvar AccordionAnimationSettings = /** @class */ (function (_super) {\n __extends(AccordionAnimationSettings, _super);\n function AccordionAnimationSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({ effect: 'SlideUp', duration: 400, easing: 'linear' }, AccordionActionSettings)\n ], AccordionAnimationSettings.prototype, \"collapse\", void 0);\n __decorate([\n Complex({ effect: 'SlideDown', duration: 400, easing: 'linear' }, AccordionActionSettings)\n ], AccordionAnimationSettings.prototype, \"expand\", void 0);\n return AccordionAnimationSettings;\n}(ChildProperty));\nexport { AccordionAnimationSettings };\n/**\n * An item object that is used to configure Accordion items.\n */\nvar AccordionItem = /** @class */ (function (_super) {\n __extends(AccordionItem, _super);\n function AccordionItem() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(undefined)\n ], AccordionItem.prototype, \"content\", void 0);\n __decorate([\n Property(undefined)\n ], AccordionItem.prototype, \"header\", void 0);\n __decorate([\n Property(undefined)\n ], AccordionItem.prototype, \"cssClass\", void 0);\n __decorate([\n Property(undefined)\n ], AccordionItem.prototype, \"iconCss\", void 0);\n __decorate([\n Property(false)\n ], AccordionItem.prototype, \"expanded\", void 0);\n return AccordionItem;\n}(ChildProperty));\nexport { AccordionItem };\n/**\n * The Accordion is a vertically collapsible content panel that displays one or more panels at a time within the available space.\n * ```html\n *
\n * \n * ```\n */\nvar Accordion = /** @class */ (function (_super) {\n __extends(Accordion, _super);\n /**\n * Initializes a new instance of the Accordion class.\n * @param options - Specifies Accordion model properties as options.\n * @param element - Specifies the element that is rendered as an Accordion.\n */\n function Accordion(options, element) {\n var _this = _super.call(this, options, element) || this;\n /**\n * Contains the keyboard configuration of the Accordion.\n */\n _this.keyConfigs = {\n moveUp: 'uparrow',\n moveDown: 'downarrow',\n enter: 'enter',\n space: 'space',\n home: 'home',\n end: 'end',\n };\n return _this;\n }\n /**\n * Removes the control from the DOM and also removes all its related events.\n * @returns void\n */\n Accordion.prototype.destroy = function () {\n var _this = this;\n var ele = this.element;\n _super.prototype.destroy.call(this);\n this.unwireEvents();\n this.isDestroy = true;\n this.templateEle.forEach(function (eleStr) {\n if (!isNOU(_this.element.querySelector(eleStr))) {\n document.body.appendChild(_this.element.querySelector(eleStr)).style.display = 'none';\n }\n });\n while (ele.firstChild) {\n ele.removeChild(ele.firstChild);\n }\n if (this.trgtEle) {\n while (this.ctrlTem.firstChild) {\n ele.appendChild(this.ctrlTem.firstChild);\n }\n }\n ele.removeAttribute('style');\n ['aria-disabled', 'aria-multiselectable', 'role'].forEach(function (attrb) {\n _this.element.removeAttribute(attrb);\n });\n };\n Accordion.prototype.preRender = function () {\n var nested = closest(this.element, '.' + CLS_CONTENT);\n this.isNested = false;\n this.templateEle = [];\n if (!this.isDestroy) {\n this.isDestroy = false;\n }\n if (!isNOU(nested)) {\n nested.classList.add(CLS_NEST);\n this.isNested = true;\n }\n else {\n this.element.classList.add(CLS_ACRDN_ROOT);\n }\n if (this.enableRtl) {\n this.add(this.element, CLS_RTL);\n }\n if (!this.enablePersistence || isNOU(this.expandedItems)) {\n this.expandedItems = [];\n }\n };\n Accordion.prototype.add = function (ele, val) {\n ele.classList.add(val);\n };\n Accordion.prototype.remove = function (ele, val) {\n ele.classList.remove(val);\n };\n /**\n * To initialize the control rendering\n * @private\n */\n Accordion.prototype.render = function () {\n this.initialize();\n this.renderControl();\n this.wireEvents();\n };\n Accordion.prototype.initialize = function () {\n var width = formatUnit(this.width);\n var height = formatUnit(this.height);\n setStyle(this.element, { 'width': width, 'height': height });\n var ariaAttr = {\n 'aria-disabled': 'false', 'role': 'presentation', 'aria-multiselectable': 'true'\n };\n if (this.expandedItems.length > 0) {\n this.initExpand = this.expandedItems;\n }\n attributes(this.element, ariaAttr);\n if (this.expandMode === 'Single') {\n this.element.setAttribute('aria-multiselectable', 'false');\n }\n };\n Accordion.prototype.renderControl = function () {\n this.trgtEle = (this.element.children.length > 0) ? select('div', this.element) : null;\n this.renderItems();\n this.initItemExpand();\n };\n Accordion.prototype.unwireEvents = function () {\n EventHandler.remove(this.element, 'click', this.clickHandler);\n if (!isNOU(this.keyModule)) {\n this.keyModule.destroy();\n }\n };\n Accordion.prototype.wireEvents = function () {\n EventHandler.add(this.element, 'click', this.clickHandler, this);\n if (!this.isNested && !this.isDestroy) {\n rippleEffect(this.element, { selector: '.' + CLS_HEADER });\n }\n if (!this.isNested) {\n this.keyModule = new KeyboardEvents(this.element, {\n keyAction: this.keyActionHandler.bind(this),\n keyConfigs: this.keyConfigs,\n eventName: 'keydown'\n });\n }\n };\n Accordion.prototype.focusIn = function (e) {\n e.target.parentElement.classList.add(CLS_ITEMFOCUS);\n };\n Accordion.prototype.focusOut = function (e) {\n e.target.parentElement.classList.remove(CLS_ITEMFOCUS);\n };\n Accordion.prototype.ctrlTemplate = function () {\n var _this = this;\n this.ctrlTem = this.element.cloneNode(true);\n var innerEles = this.element.children;\n var content;\n addClass(innerEles, [CLS_ITEM]);\n [].slice.call(innerEles).forEach(function (el) {\n el.id = getUniqueID('acrdn_item');\n if (el.children.length > 0) {\n _this.add(el.children[0], CLS_HEADER);\n var header = el.children[0];\n attributes(header, { 'tabindex': '0', 'role': 'heading', 'aria-level': innerEles.length.toString() });\n header.id = getUniqueID('acrdn_header');\n EventHandler.add(header, 'focus', _this.focusIn, _this);\n EventHandler.add(header, 'blur', _this.focusOut, _this);\n var headerEle = header.firstElementChild;\n if (headerEle) {\n headerEle.classList.add(CLS_HEADERCTN);\n }\n content = el.children[1];\n if (content) {\n content.id = getUniqueID('acrdn_panel');\n header.setAttribute('aria-controls', content.id);\n content.style.display = '';\n el.classList.add(CLS_SLCT);\n el.children[0].appendChild(_this.toggleIconGenerate());\n classList(content, [CLS_CONTENT, CLS_CTNHIDE], []);\n attributes(content, { 'aria-labelledby': header.id, 'aria-hidden': 'true' });\n content = content.firstElementChild;\n if (content) {\n content.classList.add(CLS_CTENT);\n content.style.display = '';\n }\n }\n }\n });\n };\n Accordion.prototype.toggleIconGenerate = function () {\n var tglIcon = this.createElement('div', { className: CLS_TOOGLEICN });\n var hdrColIcon = this.createElement('span', { className: CLS_COLLAPSEICN });\n tglIcon.appendChild(hdrColIcon);\n return tglIcon;\n };\n Accordion.prototype.initItemExpand = function () {\n var len = this.initExpand.length;\n if (len === 0) {\n return;\n }\n if (this.expandMode === 'Single') {\n this.expandItem(true, this.initExpand[len - 1]);\n }\n else {\n for (var i = 0; i < len; i++) {\n this.expandItem(true, this.initExpand[i]);\n }\n }\n };\n Accordion.prototype.renderItems = function () {\n var _this = this;\n var ele = this.element;\n var innerItem;\n if (isNOU(this.initExpand)) {\n this.initExpand = [];\n }\n var items = this.items;\n if (!isNOU(this.trgtEle)) {\n this.ctrlTemplate();\n }\n else if (ele && items.length > 0) {\n items.forEach(function (item, index) {\n innerItem = _this.renderInnerItem(item, index);\n ele.appendChild(innerItem);\n if (innerItem.childElementCount > 0) {\n EventHandler.add(innerItem.querySelector('.' + CLS_HEADER), 'focus', _this.focusIn, _this);\n EventHandler.add(innerItem.querySelector('.' + CLS_HEADER), 'blur', _this.focusOut, _this);\n }\n });\n }\n };\n Accordion.prototype.clickHandler = function (e) {\n var _this = this;\n var trgt = e.target;\n var eventArgs = {};\n var index;\n var tglIcon;\n var acrdEle = closest(trgt, '.' + CLS_ROOT);\n if (acrdEle !== this.element) {\n return;\n }\n trgt.classList.add('e-target');\n var acrdnItem = closest(trgt, '.' + CLS_ITEM);\n var acrdnHdr = closest(trgt, '.' + CLS_HEADER);\n var acrdnCtn = closest(trgt, '.' + CLS_CONTENT);\n if (acrdnItem && (isNOU(acrdnHdr) || isNOU(acrdnCtn))) {\n acrdnHdr = acrdnItem.children[0];\n acrdnCtn = acrdnItem.children[1];\n }\n if (acrdnHdr) {\n tglIcon = select('.' + CLS_TOOGLEICN, acrdnHdr);\n }\n var acrdnCtnItem;\n if (acrdnCtn) {\n acrdnCtnItem = closest(acrdnCtn, '.' + CLS_ITEM);\n }\n var acrdActive = [];\n index = this.getIndexByItem(acrdnItem);\n if (acrdnCtnItem) {\n eventArgs.item = this.items[this.getIndexByItem(acrdnCtnItem)];\n }\n eventArgs.originalEvent = e;\n var ctnCheck = !isNOU(tglIcon) && isNOU(this.trgtEle) && acrdnItem.childElementCount <= 1;\n if (ctnCheck && (isNOU(acrdnCtn) || !isNOU(select('.' + CLS_HEADER + ' .' + CLS_TOOGLEICN, acrdnCtnItem)))) {\n acrdnItem.appendChild(this.contentRendering(index));\n this.ariaAttrUpdate(acrdnItem);\n }\n this.trigger('clicked', eventArgs);\n var cntclkCheck = (acrdnCtn && !isNOU(select('.e-target', acrdnCtn)));\n cntclkCheck = cntclkCheck && (isNOU(select('.' + CLS_ROOT, acrdnCtn)) || !(closest(trgt, '.' + CLS_ROOT) === this.element));\n trgt.classList.remove('e-target');\n if (trgt.classList.contains(CLS_CONTENT) || trgt.classList.contains(CLS_CTENT) || cntclkCheck) {\n return;\n }\n [].slice.call(this.element.children).forEach(function (el) {\n if (el.classList.contains(CLS_ACTIVE)) {\n acrdActive.push(el);\n }\n });\n var acrdAniEle = [].slice.call(this.element.querySelectorAll('.' + CLS_ITEM + ' [' + CLS_ANIMATE + ']'));\n if (acrdAniEle.length > 0) {\n for (var _i = 0, acrdAniEle_1 = acrdAniEle; _i < acrdAniEle_1.length; _i++) {\n var el = acrdAniEle_1[_i];\n acrdActive.push(el.parentElement);\n }\n }\n var sameContentCheck = acrdActive.indexOf(acrdnCtnItem) !== -1 && acrdnCtn.getAttribute('e-animate') === 'true';\n var sameHeader = false;\n if (!isNOU(acrdnItem) && !isNOU(acrdnHdr)) {\n var acrdnCtn_1 = select('.' + CLS_CONTENT, acrdnItem);\n var acrdnRoot = closest(acrdnItem, '.' + CLS_ACRDN_ROOT);\n var expandState = acrdnRoot.querySelector('.' + CLS_EXPANDSTATE);\n if (isNOU(acrdnCtn_1)) {\n return;\n }\n sameHeader = (expandState === acrdnItem);\n if (isVisible(acrdnCtn_1) && (!sameContentCheck || acrdnCtnItem.classList.contains(CLS_SLCTED))) {\n this.collapse(acrdnCtn_1);\n }\n else {\n if ((acrdActive.length > 0) && this.expandMode === 'Single' && !sameContentCheck) {\n acrdActive.forEach(function (el) {\n _this.collapse(select('.' + CLS_CONTENT, el));\n el.classList.remove(CLS_EXPANDSTATE);\n });\n }\n this.expand(acrdnCtn_1);\n }\n if (!isNOU(expandState) && !sameHeader) {\n expandState.classList.remove(CLS_EXPANDSTATE);\n }\n }\n };\n Accordion.prototype.eleMoveFocus = function (action, root, trgt) {\n var clst;\n var clstItem = closest(trgt, '.' + CLS_ITEM);\n if (trgt === root) {\n clst = ((action === 'moveUp' ? trgt.lastElementChild : trgt).querySelector('.' + CLS_HEADER));\n }\n else if (trgt.classList.contains(CLS_HEADER)) {\n clstItem = (action === 'moveUp' ? clstItem.previousElementSibling : clstItem.nextElementSibling);\n if (clstItem) {\n clst = select('.' + CLS_HEADER, clstItem);\n }\n }\n if (clst) {\n clst.focus();\n }\n };\n Accordion.prototype.keyActionHandler = function (e) {\n var trgt = e.target;\n var header = closest(e.target, CLS_HEADER);\n if (isNOU(header) && !trgt.classList.contains(CLS_ROOT) && !trgt.classList.contains(CLS_HEADER)) {\n return;\n }\n var clst;\n var root = this.element;\n var content;\n switch (e.action) {\n case 'moveUp':\n this.eleMoveFocus(e.action, root, trgt);\n break;\n case 'moveDown':\n this.eleMoveFocus(e.action, root, trgt);\n break;\n case 'space':\n case 'enter':\n content = trgt.nextElementSibling;\n if (!isNOU(content) && content.classList.contains(CLS_CONTENT)) {\n if (content.getAttribute('e-animate') !== 'true') {\n trgt.click();\n }\n }\n else {\n trgt.click();\n }\n break;\n case 'home':\n case 'end':\n clst = e.action === 'home' ? root.firstElementChild.children[0] : root.lastElementChild.children[0];\n clst.focus();\n break;\n }\n };\n Accordion.prototype.headerEleGenerate = function () {\n var header = this.createElement('div', { className: CLS_HEADER, id: getUniqueID('acrdn_header') });\n var ariaAttr = {\n 'tabindex': '0', 'role': 'heading', 'aria-expanded': 'false', 'aria-selected': 'false',\n 'aria-disabled': 'false', 'aria-level': this.items.length.toString()\n };\n attributes(header, ariaAttr);\n return header;\n };\n Accordion.prototype.renderInnerItem = function (item, index) {\n var innerEle;\n innerEle = this.createElement('div', { className: CLS_ITEM });\n innerEle.id = getUniqueID('acrdn_item');\n if (item.header) {\n var ctnEle = this.headerEleGenerate();\n var hdrEle = this.createElement('div', { className: CLS_HEADERCTN });\n ctnEle.appendChild(hdrEle);\n ctnEle.appendChild(this.fetchElement(hdrEle, item.header, index, true));\n innerEle.appendChild(ctnEle);\n }\n var hdr = select('.' + CLS_HEADER, innerEle);\n if (item.expanded && !isNOU(index) && (!this.enablePersistence)) {\n if (this.initExpand.indexOf(index) === -1) {\n this.initExpand.push(index);\n }\n }\n if (item.cssClass) {\n innerEle.classList.add(item.cssClass);\n }\n if (item.iconCss) {\n var hdrIcnEle = this.createElement('div', { className: CLS_HEADERICN });\n var icon = this.createElement('span', { className: item.iconCss + ' e-icons' });\n hdrIcnEle.appendChild(icon);\n if (isNOU(hdr)) {\n hdr = this.headerEleGenerate();\n hdr.appendChild(hdrIcnEle);\n innerEle.appendChild(hdr);\n }\n else {\n hdr.insertBefore(hdrIcnEle, hdr.childNodes[0]);\n }\n }\n if (item.content) {\n var hdrIcon = this.toggleIconGenerate();\n if (isNOU(hdr)) {\n hdr = this.headerEleGenerate();\n innerEle.appendChild(hdr);\n }\n hdr.appendChild(hdrIcon);\n this.add(innerEle, CLS_SLCT);\n }\n return innerEle;\n };\n Accordion.prototype.fetchElement = function (ele, value, index, isHeader) {\n var templateFn;\n var temString;\n try {\n if (document.querySelectorAll(value).length) {\n var eleVal = document.querySelector(value);\n temString = eleVal.outerHTML.trim();\n ele.appendChild(eleVal);\n eleVal.style.display = '';\n }\n }\n catch (e) {\n templateFn = templateCompiler(value);\n }\n var tempArray;\n if (!isNOU(templateFn)) {\n tempArray = templateFn();\n }\n if (!isNOU(tempArray) && tempArray.length > 0 && !(isNOU(tempArray[0].tagName) && tempArray.length === 1)) {\n [].slice.call(tempArray).forEach(function (el) {\n if (!isNOU(el.tagName)) {\n el.style.display = '';\n }\n ele.appendChild(el);\n });\n }\n else if (ele.childElementCount === 0) {\n ele.innerHTML = value;\n }\n if (!isNOU(temString)) {\n this.templateEle.push(value);\n }\n return ele;\n };\n Accordion.prototype.ariaAttrUpdate = function (itemEle) {\n var header = select('.' + CLS_HEADER, itemEle);\n var content = select('.' + CLS_CONTENT, itemEle);\n header.setAttribute('aria-controls', content.id);\n content.setAttribute('aria-labelledby', header.id);\n };\n Accordion.prototype.contentRendering = function (index) {\n var content = this.items[index].content;\n var itemcnt = this.createElement('div', { className: CLS_CONTENT + ' ' + CLS_CTNHIDE, id: getUniqueID('acrdn_panel') });\n attributes(itemcnt, { 'aria-hidden': 'true' });\n var ctn = this.createElement('div', { className: CLS_CTENT });\n itemcnt.appendChild(this.fetchElement(ctn, content, index, false));\n return itemcnt;\n };\n Accordion.prototype.expand = function (trgt) {\n var eventArgs;\n var trgtItemEle = closest(trgt, '.' + CLS_ITEM);\n if (isNOU(trgt) || (isVisible(trgt) && trgt.getAttribute('e-animate') !== 'true') || trgtItemEle.classList.contains(CLS_DISABLE)) {\n return;\n }\n var acrdnRoot = closest(trgtItemEle, '.' + CLS_ACRDN_ROOT);\n var expandState = acrdnRoot.querySelector('.' + CLS_EXPANDSTATE);\n var animation = {\n name: this.animation.expand.effect,\n duration: this.animation.expand.duration,\n timingFunction: this.animation.expand.easing\n };\n var icon = select('.' + CLS_TOOGLEICN, trgtItemEle).firstElementChild;\n eventArgs = { element: trgtItemEle,\n item: this.items[this.getIndexByItem(trgtItemEle)],\n isExpanded: true };\n var eff = animation.name;\n this.trigger('expanding', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n icon.classList.add(CLS_TOGANIMATE);\n this.expandedItemsPush(trgtItemEle);\n if (!isNOU(expandState)) {\n expandState.classList.remove(CLS_EXPANDSTATE);\n }\n trgtItemEle.classList.add(CLS_EXPANDSTATE);\n if ((animation.name === 'None')) {\n this.expandProgress('begin', icon, trgt, trgtItemEle, eventArgs);\n this.expandProgress('end', icon, trgt, trgtItemEle, eventArgs);\n return;\n }\n this.expandAnimation(eff, icon, trgt, trgtItemEle, animation, eventArgs);\n };\n Accordion.prototype.expandAnimation = function (ef, icn, trgt, trgtItemEle, animate, args) {\n var _this = this;\n var height;\n var trgtHgt;\n this.lastActiveItemId = trgtItemEle.id;\n if (ef === 'SlideDown') {\n animate.begin = function () {\n _this.expandProgress('begin', icn, trgt, trgtItemEle, args);\n trgt.style.position = 'absolute';\n height = trgtItemEle.offsetHeight;\n trgtHgt = trgt.offsetHeight;\n trgt.style.maxHeight = (trgt.offsetHeight) + 'px';\n trgtItemEle.style.maxHeight = '';\n };\n animate.progress = function () {\n trgtItemEle.style.minHeight = (height + trgt.offsetHeight) + 'px';\n };\n animate.end = function () {\n setStyle(trgt, { 'position': '', 'maxHeight': '' });\n trgtItemEle.style.minHeight = '';\n _this.expandProgress('end', icn, trgt, trgtItemEle, args);\n };\n }\n else {\n animate.begin = function () {\n _this.expandProgress('begin', icn, trgt, trgtItemEle, args);\n };\n animate.end = function () {\n _this.expandProgress('end', icn, trgt, trgtItemEle, args);\n };\n }\n new Animation(animate).animate(trgt);\n };\n Accordion.prototype.expandProgress = function (progress, icon, trgt, trgtItemEle, eventArgs) {\n this.remove(trgt, CLS_CTNHIDE);\n this.add(trgtItemEle, CLS_SLCTED);\n this.add(icon, CLS_EXPANDICN);\n if (progress === 'end') {\n this.add(trgtItemEle, CLS_ACTIVE);\n trgt.setAttribute('aria-hidden', 'false');\n attributes(trgt.previousElementSibling, { 'aria-selected': 'true', 'aria-expanded': 'true' });\n icon.classList.remove(CLS_TOGANIMATE);\n this.trigger('expanded', eventArgs);\n }\n };\n Accordion.prototype.expandedItemsPush = function (item) {\n var index = this.getIndexByItem(item);\n if (this.expandedItems.indexOf(index) === -1) {\n this.expandedItems.push(index);\n }\n };\n Accordion.prototype.getIndexByItem = function (item) {\n return [].slice.call(this.element.children).indexOf(item);\n };\n Accordion.prototype.expandedItemsPop = function (item) {\n var index = this.getIndexByItem(item);\n this.expandedItems.splice(this.expandedItems.indexOf(index), 1);\n };\n Accordion.prototype.collapse = function (trgt) {\n var eventArgs;\n var trgtItemEle = closest(trgt, '.' + CLS_ITEM);\n if (isNOU(trgt) || !isVisible(trgt) || trgtItemEle.classList.contains(CLS_DISABLE)) {\n return;\n }\n var animation = {\n name: this.animation.collapse.effect,\n duration: this.animation.collapse.duration,\n timingFunction: this.animation.collapse.easing,\n };\n var icon = select('.' + CLS_TOOGLEICN, trgtItemEle).firstElementChild;\n eventArgs = { element: trgtItemEle,\n item: this.items[this.getIndexByItem(trgtItemEle)],\n isExpanded: false };\n var eff = animation.name;\n this.trigger('expanding', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.expandedItemsPop(trgtItemEle);\n trgtItemEle.classList.add(CLS_EXPANDSTATE);\n icon.classList.add(CLS_TOGANIMATE);\n if ((animation.name === 'None')) {\n this.collapseProgress('begin', icon, trgt, trgtItemEle, eventArgs);\n this.collapseProgress('end', icon, trgt, trgtItemEle, eventArgs);\n return;\n }\n this.collapseAnimation(eff, trgt, trgtItemEle, icon, animation, eventArgs);\n };\n Accordion.prototype.collapseAnimation = function (ef, trgt, trgtItEl, icn, animate, args) {\n var _this = this;\n var height;\n var trgtHeight;\n var itemHeight;\n var remain;\n this.lastActiveItemId = trgtItEl.id;\n if (ef === 'SlideUp') {\n animate.begin = function () {\n itemHeight = trgtItEl.offsetHeight;\n trgtItEl.style.minHeight = itemHeight + 'px';\n trgt.style.position = 'absolute';\n height = trgtItEl.offsetHeight;\n trgtHeight = trgt.offsetHeight;\n trgt.style.maxHeight = trgtHeight + 'px';\n _this.collapseProgress('begin', icn, trgt, trgtItEl, args);\n };\n animate.progress = function () {\n remain = ((height - (trgtHeight - trgt.offsetHeight)));\n if (remain < itemHeight) {\n trgtItEl.style.minHeight = remain + 'px';\n }\n };\n animate.end = function () {\n trgt.style.display = 'none';\n _this.collapseProgress('end', icn, trgt, trgtItEl, args);\n trgtItEl.style.minHeight = '';\n setStyle(trgt, { 'position': '', 'maxHeight': '', 'display': '' });\n };\n }\n else {\n animate.begin = function () {\n _this.collapseProgress('begin', icn, trgt, trgtItEl, args);\n };\n animate.end = function () {\n _this.collapseProgress('end', icn, trgt, trgtItEl, args);\n };\n }\n new Animation(animate).animate(trgt);\n };\n Accordion.prototype.collapseProgress = function (progress, icon, trgt, trgtItemEle, eventArgs) {\n this.remove(icon, CLS_EXPANDICN);\n this.remove(trgtItemEle, CLS_SLCTED);\n if (progress === 'end') {\n this.add(trgt, CLS_CTNHIDE);\n icon.classList.remove(CLS_TOGANIMATE);\n this.remove(trgtItemEle, CLS_ACTIVE);\n trgt.setAttribute('aria-hidden', 'true');\n attributes(trgt.previousElementSibling, { 'aria-selected': 'false', 'aria-expanded': 'false' });\n this.trigger('expanded', eventArgs);\n }\n };\n /**\n * Returns the current module name.\n * @returns string\n * @private\n */\n Accordion.prototype.getModuleName = function () {\n return 'accordion';\n };\n Accordion.prototype.itemAttribUpdate = function () {\n var itemEle = [].slice.call(this.element.children);\n var itemLen = this.items.length;\n itemEle.forEach(function (ele) {\n select('.' + CLS_HEADER, ele).setAttribute('aria-level', '' + itemLen);\n });\n };\n /**\n * Adds new item to the Accordion with the specified index of the Accordion.\n * @param {AccordionItemModel} item - Item array that is to be added to the Accordion.\n * @param {number} index - Number value that determines where the item should be added.\n * By default, item is added at the last index if the index is not specified.\n * @returns void\n */\n Accordion.prototype.addItem = function (item, index) {\n var ele = this.element;\n if (isNOU(index)) {\n index = this.items.length;\n }\n if (ele.childElementCount >= index) {\n this.items.splice(index, 0, item);\n var innerItemEle = this.renderInnerItem(item, index);\n if (ele.childElementCount === index) {\n ele.appendChild(innerItemEle);\n }\n else {\n ele.insertBefore(innerItemEle, ele.children[index]);\n }\n EventHandler.add(innerItemEle.querySelector('.' + CLS_HEADER), 'focus', this.focusIn, this);\n EventHandler.add(innerItemEle.querySelector('.' + CLS_HEADER), 'blur', this.focusOut, this);\n this.itemAttribUpdate();\n }\n this.expandedItems = [];\n this.expandedItemRefresh(ele);\n if (item.expanded) {\n this.expandItem(true, index);\n }\n };\n Accordion.prototype.expandedItemRefresh = function (ele) {\n var _this = this;\n [].slice.call(ele.children).forEach(function (el) {\n if (el.classList.contains(CLS_SLCTED)) {\n _this.expandedItemsPush(el);\n }\n });\n };\n /**\n * Dynamically removes item from Accordion.\n * @param {number} index - Number value that determines which item should be removed.\n * @returns void.\n */\n Accordion.prototype.removeItem = function (index) {\n var ele = this.element.children[index];\n if (isNOU(ele)) {\n return;\n }\n detach(ele);\n this.items.splice(index, 1);\n this.itemAttribUpdate();\n this.expandedItems = [];\n this.expandedItemRefresh(this.element);\n };\n /**\n * Sets focus to the specified index item header in Accordion.\n * @param {number} index - Number value that determines which item should be focused.\n * @returns void.\n */\n Accordion.prototype.select = function (index) {\n var ele = this.element.children[index];\n if (isNOU(ele) || isNOU(select('.' + CLS_HEADER, ele))) {\n return;\n }\n ele.children[0].focus();\n };\n /**\n * Shows or hides the specified item from Accordion.\n * @param {number} index - Number value that determines which item should be hidden/shown.\n * @param {Boolean} isHidden - Boolean value that determines the action either hide (true) or show (false). Default value is false.\n * If the `isHidden` value is false, the item is shown or else item it is hidden.\n * @returns void.\n */\n Accordion.prototype.hideItem = function (index, isHidden) {\n var ele = this.element.children[index];\n if (isNOU(ele)) {\n return;\n }\n if (isNOU(isHidden)) {\n isHidden = true;\n }\n isHidden ? this.add(ele, CLS_ITEMHIDE) : this.remove(ele, CLS_ITEMHIDE);\n };\n /**\n * Enables/Disables the specified Accordion item.\n * @param {number} index - Number value that determines which item should be enabled/disabled.\n * @param {boolean} isEnable - Boolean value that determines the action as enable (true) or disable (false).\n * If the `isEnable` value is true, the item is enabled or else it is disabled.\n * @returns void.\n */\n Accordion.prototype.enableItem = function (index, isEnable) {\n var ele = this.element.children[index];\n if (isNOU(ele)) {\n return;\n }\n var eleHeader = ele.firstElementChild;\n if (isEnable) {\n this.remove(ele, CLS_DISABLE);\n attributes(eleHeader, { 'tabindex': '0', 'aria-disabled': 'false' });\n eleHeader.focus();\n }\n else {\n if (ele.classList.contains(CLS_ACTIVE)) {\n this.expandItem(false, index);\n this.eleMoveFocus('movedown', this.element, eleHeader);\n }\n this.add(ele, CLS_DISABLE);\n eleHeader.setAttribute('aria-disabled', 'true');\n eleHeader.removeAttribute('tabindex');\n }\n };\n /**\n * Expands/Collapses the specified Accordion item.\n * @param {boolean} isExpand - Boolean value that determines the action as expand or collapse.\n * @param {number} index - Number value that determines which item should be expanded/collapsed.`index` is optional parameter.\n * Without Specifying index, based on the `isExpand` value all Accordion item can be expanded or collapsed.\n * @returns void.\n */\n Accordion.prototype.expandItem = function (isExpand, index) {\n var _this = this;\n var root = this.element;\n if (isNOU(index)) {\n if (this.expandMode === 'Single' && isExpand) {\n var ele = root.children[root.childElementCount - 1];\n this.itemExpand(isExpand, ele, this.getIndexByItem(ele));\n }\n else {\n var item = select('#' + this.lastActiveItemId, this.element);\n [].slice.call(this.element.children).forEach(function (el) {\n _this.itemExpand(isExpand, el, _this.getIndexByItem(el));\n el.classList.remove(CLS_EXPANDSTATE);\n });\n var expandedItem = select('.' + CLS_EXPANDSTATE, this.element);\n if (expandedItem) {\n expandedItem.classList.remove(CLS_EXPANDSTATE);\n }\n if (item) {\n item.classList.add(CLS_EXPANDSTATE);\n }\n }\n }\n else {\n var ele = this.element.children[index];\n if (isNOU(ele) || !ele.classList.contains(CLS_SLCT) || (ele.classList.contains(CLS_ACTIVE) && isExpand)) {\n return;\n }\n else {\n if (this.expandMode === 'Single') {\n this.expandItem(false);\n }\n this.itemExpand(isExpand, ele, index);\n }\n }\n };\n Accordion.prototype.itemExpand = function (isExpand, ele, index) {\n var ctn = ele.children[1];\n if (ele.classList.contains(CLS_DISABLE)) {\n return;\n }\n if (isNOU(ctn) && isExpand) {\n ctn = this.contentRendering(index);\n ele.appendChild(ctn);\n this.ariaAttrUpdate(ele);\n }\n else if (isNOU(ctn)) {\n return;\n }\n isExpand ? this.expand(ctn) : this.collapse(ctn);\n };\n Accordion.prototype.destroyItems = function () {\n [].slice.call(this.element.querySelectorAll('.' + CLS_ITEM)).forEach(function (el) { detach(el); });\n };\n Accordion.prototype.updateItem = function (item, index) {\n if (!isNOU(item)) {\n var itemObj = this.items[index];\n this.items.splice(index, 1);\n detach(item);\n this.addItem(itemObj, index);\n }\n };\n Accordion.prototype.getPersistData = function () {\n var keyEntity = ['expandedItems'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Gets called when the model property changes.The data that describes the old and new values of the property that changed.\n * @param {AccordionModel} newProp\n * @param {AccordionModel} oldProp\n * @returns void\n * @private\n */\n Accordion.prototype.onPropertyChanged = function (newProp, oldProp) {\n var acrdn = this.element;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'items':\n if (!(newProp.items instanceof Array && oldProp.items instanceof Array)) {\n var changedProp = Object.keys(newProp.items);\n for (var j = 0; j < changedProp.length; j++) {\n var index = parseInt(Object.keys(newProp.items)[j], 10);\n var property = Object.keys(newProp.items[index])[0];\n var item = selectAll('.' + CLS_ITEM, this.element)[index];\n var oldVal = Object(oldProp.items[index])[property];\n var newVal = Object(newProp.items[index])[property];\n if (property === 'header' || property === 'iconCss' || property === 'expanded') {\n this.updateItem(item, index);\n }\n if (property === 'cssClass' && !isNOU(item)) {\n item.classList.remove(oldVal);\n item.classList.add(newVal);\n }\n if (property === 'content' && !isNOU(item) && item.children.length === 2) {\n if (item.classList.contains(CLS_SLCTED)) {\n this.expandItem(false, index);\n }\n detach(item.querySelector('.' + CLS_CONTENT));\n }\n }\n }\n else {\n this.destroyItems();\n this.renderItems();\n this.initItemExpand();\n }\n break;\n case 'enableRtl':\n newProp.enableRtl ? this.add(acrdn, CLS_RTL) : this.remove(acrdn, CLS_RTL);\n break;\n case 'height':\n setStyle(this.element, { 'height': formatUnit(newProp.height) });\n break;\n case 'width':\n setStyle(this.element, { 'width': formatUnit(newProp.width) });\n break;\n case 'expandMode':\n if (newProp.expandMode === 'Single') {\n this.element.setAttribute('aria-multiselectable', 'false');\n if (this.expandedItems.length > 1) {\n this.expandItem(false);\n }\n }\n else {\n this.element.setAttribute('aria-multiselectable', 'true');\n }\n break;\n }\n }\n };\n __decorate([\n Collection([], AccordionItem)\n ], Accordion.prototype, \"items\", void 0);\n __decorate([\n Property('100%')\n ], Accordion.prototype, \"width\", void 0);\n __decorate([\n Property('auto')\n ], Accordion.prototype, \"height\", void 0);\n __decorate([\n Property('Multiple')\n ], Accordion.prototype, \"expandMode\", void 0);\n __decorate([\n Complex({}, AccordionAnimationSettings)\n ], Accordion.prototype, \"animation\", void 0);\n __decorate([\n Event()\n ], Accordion.prototype, \"clicked\", void 0);\n __decorate([\n Event()\n ], Accordion.prototype, \"expanding\", void 0);\n __decorate([\n Event()\n ], Accordion.prototype, \"expanded\", void 0);\n __decorate([\n Event()\n ], Accordion.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Accordion.prototype, \"destroyed\", void 0);\n Accordion = __decorate([\n NotifyPropertyChanges\n ], Accordion);\n return Accordion;\n}(Component));\nexport { Accordion };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, ChildProperty, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { Event, EventHandler, KeyboardEvents, Touch } from '@syncfusion/ej2-base';\nimport { attributes, Animation } from '@syncfusion/ej2-base';\nimport { Browser, Collection, setValue, getValue, getUniqueID, getInstance } from '@syncfusion/ej2-base';\nimport { select, selectAll, closest, detach, append, rippleEffect, isVisible } from '@syncfusion/ej2-base';\nimport { ListBase } from '@syncfusion/ej2-lists';\nimport { calculatePosition, isCollide, fit, getScrollableParent, getZindexPartial } from '@syncfusion/ej2-popups';\nvar DOWNARROW = 'downarrow';\nvar ENTER = 'enter';\nvar ESCAPE = 'escape';\nvar FOCUSED = 'e-focused';\nvar HEADER = 'e-menu-header';\nvar LEFTARROW = 'leftarrow';\nvar RIGHTARROW = 'rightarrow';\nvar RTL = 'e-rtl';\nvar SELECTED = 'e-selected';\nvar SEPARATOR = 'e-separator';\nvar UPARROW = 'uparrow';\nvar WRAPPER = 'e-contextmenu-wrapper';\nvar CARET = 'e-caret';\nvar ITEM = 'e-menu-item';\nvar DISABLED = 'e-disabled';\nvar HIDE = 'e-menu-hide';\nvar ICONS = 'e-icons';\n/**\n * Specifies context menu items.\n */\nvar MenuItem = /** @class */ (function (_super) {\n __extends(MenuItem, _super);\n function MenuItem() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], MenuItem.prototype, \"iconCss\", void 0);\n __decorate([\n Property('')\n ], MenuItem.prototype, \"id\", void 0);\n __decorate([\n Property(false)\n ], MenuItem.prototype, \"separator\", void 0);\n __decorate([\n Collection([], MenuItem)\n ], MenuItem.prototype, \"items\", void 0);\n __decorate([\n Property('')\n ], MenuItem.prototype, \"text\", void 0);\n __decorate([\n Property('')\n ], MenuItem.prototype, \"url\", void 0);\n return MenuItem;\n}(ChildProperty));\nexport { MenuItem };\n/**\n * The ContextMenu is a graphical user interface that appears on the user right click/touch hold operation.\n * ```html\n *
\n * \n * ```\n * ```typescript\n * \n * ```\n */\nvar ContextMenu = /** @class */ (function (_super) {\n __extends(ContextMenu, _super);\n /**\n * Constructor for creating the widget.\n * @private\n */\n function ContextMenu(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.animation = new Animation({});\n _this.navIdx = [];\n _this.isTapHold = false;\n return _this;\n }\n /**\n * Initialized animation with parent menu animation settings.\n * @private\n */\n ContextMenu.prototype.preRender = function () {\n if (this.element.tagName === 'EJS-CONTEXTMENU') {\n this.element.style.display = 'none';\n this.element.classList.remove('e-' + this.getModuleName());\n this.element.classList.remove('e-control');\n var ejInst = getValue('ej2_instances', this.element);\n var ul = this.createElement('ul');\n this.ngElement = this.element;\n this.element = ul;\n this.element.classList.add('e-control');\n this.element.classList.add('e-' + this.getModuleName());\n setValue('ej2_instances', ejInst, this.element);\n if (!this.element.id) {\n this.element.id = getUniqueID(this.getModuleName());\n }\n }\n };\n /**\n * Initialize the control rendering\n * @private\n */\n ContextMenu.prototype.render = function () {\n this.initWrapper();\n this.renderItems();\n this.wireEvents();\n };\n ContextMenu.prototype.initWrapper = function () {\n var wrapper = this.getWrapper();\n if (!wrapper) {\n wrapper = this.createElement('div', { className: WRAPPER });\n document.body.appendChild(wrapper);\n }\n if (this.cssClass) {\n wrapper.classList.add(this.cssClass);\n }\n if (this.enableRtl) {\n wrapper.classList.add(RTL);\n }\n attributes(this.element, { 'role': 'menu', 'tabindex': '0' });\n wrapper.appendChild(this.element);\n };\n ContextMenu.prototype.renderItems = function () {\n if (!this.items.length) {\n this.items = ListBase.createJsonFromElement(this.element);\n this.element.innerHTML = '';\n }\n var ul = this.createItems(this.items);\n append(Array.prototype.slice.call(ul.children), this.element);\n this.element.classList.add('e-menu-parent');\n };\n ContextMenu.prototype.wireEvents = function () {\n var wrapper = this.getWrapper();\n if (this.target) {\n var target = void 0;\n var targetElems = selectAll(this.target);\n for (var i = 0, len = targetElems.length; i < len; i++) {\n target = targetElems[i];\n if (Browser.isIos) {\n new Touch(target, { tapHold: this.touchHandler.bind(this) });\n }\n else {\n EventHandler.add(target, 'contextmenu', this.cmenuHandler, this);\n }\n }\n this.targetElement = target;\n for (var _i = 0, _a = getScrollableParent(this.targetElement); _i < _a.length; _i++) {\n var parent_1 = _a[_i];\n EventHandler.add(parent_1, 'scroll', this.scrollHandler, this);\n }\n }\n if (!Browser.isDevice) {\n EventHandler.add(wrapper, 'mouseover', this.moverHandler, this);\n EventHandler.add(document, 'mousedown', this.mouseDownHandler, this);\n }\n this.delegateClickHandler = this.clickHandler.bind(this);\n EventHandler.add(document, 'click', this.delegateClickHandler, this);\n new KeyboardEvents(wrapper, {\n keyAction: this.keyBoardHandler.bind(this),\n keyConfigs: {\n downarrow: DOWNARROW,\n uparrow: UPARROW,\n enter: ENTER,\n leftarrow: LEFTARROW,\n rightarrow: RIGHTARROW,\n escape: ESCAPE\n }\n });\n rippleEffect(wrapper, { selector: '.' + ITEM });\n };\n ContextMenu.prototype.mouseDownHandler = function (e) {\n if (closest(e.target, '.' + WRAPPER) !== this.getWrapper()) {\n this.closeMenu(this.navIdx.length, e);\n }\n };\n ContextMenu.prototype.keyBoardHandler = function (e) {\n e.preventDefault();\n switch (e.action) {\n case DOWNARROW:\n case UPARROW:\n this.upDownKeyHandler(e);\n break;\n case RIGHTARROW:\n this.rightEnterKeyHandler(e);\n break;\n case LEFTARROW:\n this.leftEscKeyHandler(e);\n break;\n case ENTER:\n this.rightEnterKeyHandler(e);\n break;\n case ESCAPE:\n this.leftEscKeyHandler(e);\n break;\n }\n };\n ContextMenu.prototype.upDownKeyHandler = function (e) {\n var wrapper = this.getWrapper();\n var cul = wrapper.children[this.navIdx.length];\n var defaultIdx = e.action === DOWNARROW ? 0 : cul.childElementCount - 1;\n var fliIdx = defaultIdx;\n var fli = this.getLIByClass(cul, FOCUSED);\n if (fli) {\n fliIdx = this.getIdx(cul, fli);\n fli.classList.remove(FOCUSED);\n e.action === DOWNARROW ? fliIdx++ : fliIdx--;\n if (fliIdx === (e.action === DOWNARROW ? cul.childElementCount : -1)) {\n fliIdx = defaultIdx;\n }\n }\n var cli = cul.children[fliIdx];\n fliIdx = this.isValidLI(cli, fliIdx, e.action);\n cul.children[fliIdx].classList.add(FOCUSED);\n cul.children[fliIdx].focus();\n };\n ContextMenu.prototype.isValidLI = function (cli, index, action) {\n var wrapper = this.getWrapper();\n var cul = wrapper.children[this.navIdx.length];\n if (cli.classList.contains(SEPARATOR) || cli.classList.contains(DISABLED) || cli.classList.contains(HIDE)) {\n ((action === DOWNARROW) || (action === RIGHTARROW)) ? index++ : index--;\n }\n cli = cul.children[index];\n if (cli.classList.contains(SEPARATOR) || cli.classList.contains(DISABLED) || cli.classList.contains(HIDE)) {\n index = this.isValidLI(cli, index, action);\n }\n return index;\n };\n ContextMenu.prototype.rightEnterKeyHandler = function (e) {\n var eventArgs;\n var wrapper = this.getWrapper();\n var cul = wrapper.children[this.navIdx.length];\n var fli = this.getLIByClass(cul, FOCUSED);\n if (fli) {\n var fliIdx = this.getIdx(cul, fli);\n var navIdx = this.navIdx.concat(fliIdx);\n var index = void 0;\n var item = this.getItem(navIdx);\n if (item.items.length) {\n this.navIdx.push(fliIdx);\n this.openMenu(fli, item, null, null, e);\n fli.classList.remove(FOCUSED);\n fli.classList.add(SELECTED);\n if (e.action === ENTER) {\n eventArgs = { element: fli, item: item };\n this.trigger('select', eventArgs);\n }\n fli.focus();\n cul = wrapper.children[this.navIdx.length];\n index = this.isValidLI(cul.children[0], 0, e.action);\n cul.children[index].classList.add(FOCUSED);\n cul.children[index].focus();\n }\n else {\n if (e.action === ENTER) {\n fli.classList.remove(FOCUSED);\n fli.classList.add(SELECTED);\n eventArgs = { element: fli, item: item };\n this.trigger('select', eventArgs);\n this.closeMenu(null, e);\n }\n }\n }\n };\n ContextMenu.prototype.leftEscKeyHandler = function (e) {\n if (this.navIdx.length) {\n var wrapper = this.getWrapper();\n this.closeMenu(this.navIdx.length, e);\n var cul = wrapper.children[this.navIdx.length];\n var sli = this.getLIByClass(cul, SELECTED);\n if (sli) {\n sli.setAttribute('aria-expanded', 'false');\n sli.classList.remove(SELECTED);\n sli.classList.add(FOCUSED);\n sli.focus();\n }\n }\n else {\n if (e.action === ESCAPE) {\n this.closeMenu(null, e);\n }\n }\n };\n ContextMenu.prototype.scrollHandler = function (e) {\n this.closeMenu(null, e);\n };\n ContextMenu.prototype.touchHandler = function (e) {\n this.isTapHold = true;\n this.cmenuHandler(e.originalEvent);\n };\n ContextMenu.prototype.cmenuHandler = function (e) {\n e.preventDefault();\n this.closeMenu(null, e);\n if (this.canOpen(e.target)) {\n if (e.changedTouches) {\n this.openMenu(null, null, e.changedTouches[0].pageY + 1, e.changedTouches[0].pageX + 1, e);\n }\n else {\n this.openMenu(null, null, e.pageY + 1, e.pageX + 1, e);\n }\n }\n };\n /**\n * Closes the ContextMenu if it is opened.\n */\n ContextMenu.prototype.close = function () {\n this.closeMenu();\n };\n ContextMenu.prototype.closeMenu = function (ulIndex, e) {\n if (ulIndex === void 0) { ulIndex = 0; }\n if (e === void 0) { e = null; }\n if (this.isMenuVisible()) {\n var ul = void 0;\n var item = void 0;\n var items = void 0;\n var closeArgs = void 0;\n var beforeCloseArgs = void 0;\n var wrapper = this.getWrapper();\n for (var cnt = wrapper.childElementCount; cnt > ulIndex; cnt--) {\n item = this.navIdx.length ? this.getItem(this.navIdx) : null;\n items = item ? item.items : this.items;\n ul = wrapper.children[cnt - 1];\n beforeCloseArgs = { element: ul, parentItem: item, items: items, event: e, cancel: false };\n this.trigger('beforeClose', beforeCloseArgs);\n if (!beforeCloseArgs.cancel) {\n this.toggleAnimation(ul, false);\n this.navIdx.length = ulIndex ? ulIndex - 1 : ulIndex;\n closeArgs = { element: ul, parentItem: item, items: items };\n this.trigger('onClose', closeArgs);\n }\n }\n }\n };\n ContextMenu.prototype.isMenuVisible = function () {\n return (this.navIdx.length > 0 || (this.element.classList.contains('e-contextmenu') && isVisible(this.element).valueOf()));\n };\n ContextMenu.prototype.canOpen = function (target) {\n var canOpen = true;\n if (this.filter) {\n canOpen = false;\n var filter = this.filter.split(' ');\n for (var i = 0, len = target.classList.length; i < len; i++) {\n if (filter.indexOf(target.classList[i]) > -1) {\n canOpen = true;\n break;\n }\n }\n }\n return canOpen;\n };\n /**\n * This method is used to open the ContextMenu in specified position.\n * @param top - To specify ContextMenu vertical positioning.\n * @param left - To specify ContextMenu horizontal positioning.\n * @param target - To calculate z-index for ContextMenu based upon the specified target.\n * @method open\n * @returns void\n */\n ContextMenu.prototype.open = function (top, left, target) {\n this.openMenu(null, null, top, left, null, target);\n };\n ContextMenu.prototype.openMenu = function (li, item, top, left, e, target) {\n if (top === void 0) { top = 0; }\n if (left === void 0) { left = 0; }\n if (e === void 0) { e = null; }\n if (target === void 0) { target = this.targetElement; }\n var ul;\n var navIdx;\n var wrapper = this.getWrapper();\n if (li) {\n ul = this.createItems(item.items);\n if (Browser.isDevice) {\n wrapper.lastChild.style.display = 'none';\n var data = { text: item.text, iconCss: ICONS + ' e-previous' };\n var hdata = new MenuItem(this.items[0], null, data, true);\n var hli = this.createItems([hdata]).children[0];\n hli.classList.add(HEADER);\n ul.insertBefore(hli, ul.children[0]);\n }\n ul.style.zIndex = this.element.style.zIndex;\n wrapper.appendChild(ul);\n }\n else {\n ul = this.element;\n ul.style.zIndex = getZindexPartial(target ? target : this.element).toString();\n }\n navIdx = this.getIndex(li ? li.id : null, true);\n var items = li ? item.items : this.items;\n var eventArgs = { element: ul, items: items, parentItem: item, event: e, cancel: false };\n this.trigger('beforeOpen', eventArgs);\n if (eventArgs.cancel) {\n this.navIdx.pop();\n }\n else {\n this.setPosition(li, ul, top, left);\n this.toggleAnimation(ul);\n }\n };\n ContextMenu.prototype.setPosition = function (li, ul, top, left) {\n var px = 'px';\n this.toggleVisiblity(ul);\n if (ul === this.element) {\n var collide = isCollide(ul, null, left, top);\n if (collide.indexOf('right') > -1) {\n left = left - ul.offsetWidth;\n }\n if (collide.indexOf('bottom') > -1) {\n var offset = fit(ul, null, { X: false, Y: true }, { top: top, left: left });\n top = offset.top - 20;\n }\n collide = isCollide(ul, null, left, top);\n if (collide.indexOf('left') > -1) {\n var offset = fit(ul, null, { X: true, Y: false }, { top: top, left: left });\n left = offset.left;\n }\n }\n else {\n if (Browser.isDevice) {\n top = Number(this.element.style.top.replace(px, ''));\n left = Number(this.element.style.left.replace(px, ''));\n }\n else {\n var x = this.enableRtl ? 'left' : 'right';\n var offset = calculatePosition(li, x, 'top');\n top = offset.top;\n left = offset.left;\n var collide = isCollide(ul, null, this.enableRtl ? left - ul.offsetWidth : left, top);\n var xCollision = collide.indexOf('left') > -1 || collide.indexOf('right') > -1;\n if (xCollision) {\n offset = calculatePosition(li, this.enableRtl ? 'right' : 'left', 'top');\n left = offset.left;\n }\n if (this.enableRtl || xCollision) {\n left = (this.enableRtl && xCollision) ? left : left - ul.offsetWidth;\n }\n if (collide.indexOf('bottom') > -1) {\n offset = fit(ul, null, { X: false, Y: true }, { top: top, left: left });\n top = offset.top;\n }\n }\n }\n this.toggleVisiblity(ul, false);\n ul.style.top = top + px;\n ul.style.left = left + px;\n };\n ContextMenu.prototype.toggleVisiblity = function (ul, isVisible) {\n if (isVisible === void 0) { isVisible = true; }\n ul.style.visibility = isVisible ? 'hidden' : '';\n ul.style.display = isVisible ? 'block' : 'none';\n };\n ContextMenu.prototype.createItems = function (items) {\n var _this = this;\n var showIcon = this.hasField(items, 'iconCss');\n var listBaseOptions = {\n showIcon: showIcon,\n moduleName: 'menu',\n itemCreating: function (args) {\n if (!args.curData.id) {\n args.curData.id = getUniqueID('menuitem');\n }\n args.curData.htmlAttributes = {\n role: 'menuitem',\n tabindex: '-1'\n };\n },\n itemCreated: function (args) {\n if (args.curData.separator) {\n args.item.classList.add(SEPARATOR);\n args.item.removeAttribute('role');\n }\n if (showIcon && !args.curData.iconCss && !args.curData.separator) {\n args.item.classList.add('e-blankicon');\n }\n if (args.curData.items && args.curData.items.length) {\n var span = _this.createElement('span', { className: ICONS + ' ' + CARET });\n args.item.appendChild(span);\n args.item.setAttribute('aria-haspopup', 'true');\n args.item.setAttribute('aria-expanded', 'false');\n args.item.removeAttribute('role');\n args.item.classList.add('e-menu-caret-icon');\n }\n var eventArgs = { item: args.curData, element: args.item };\n _this.trigger('beforeItemRender', eventArgs);\n }\n };\n var ul = ListBase.createList(this.createElement, this.toRawObject(items.slice()), listBaseOptions, true);\n ul.setAttribute('tabindex', '0');\n return ul;\n };\n ContextMenu.prototype.toRawObject = function (items) {\n var item;\n var menuItems = [];\n for (var i = 0, len = items.length; i < len; i++) {\n item = items[i].properties;\n menuItems.push(item);\n }\n return menuItems;\n };\n ContextMenu.prototype.moverHandler = function (e) {\n var wrapper = this.getWrapper();\n var trgt = e.target;\n var cli = this.getLI(trgt);\n if (cli && closest(cli, '.' + WRAPPER)) {\n var fli = select('.' + FOCUSED, wrapper);\n if (fli) {\n fli.classList.remove(FOCUSED);\n }\n cli.classList.add(FOCUSED);\n if (!this.showItemOnClick) {\n this.clickHandler(e);\n }\n }\n };\n ContextMenu.prototype.hasField = function (items, field) {\n for (var i = 0, len = items.length; i < len; i++) {\n if (items[i][field]) {\n return true;\n }\n }\n return false;\n };\n ContextMenu.prototype.getWrapper = function () {\n return closest(this.element, '.' + WRAPPER);\n };\n ContextMenu.prototype.clickHandler = function (e) {\n if (this.isTapHold) {\n this.isTapHold = false;\n }\n else {\n var wrapper = this.getWrapper();\n var trgt = e.target;\n var cli = this.getLI(trgt);\n var cliWrapper = cli ? closest(cli, '.' + WRAPPER) : null;\n var isInstLI = cli && cliWrapper && wrapper.firstElementChild.id === cliWrapper.firstElementChild.id;\n if (isInstLI && e.type === 'click' && !cli.classList.contains(HEADER)) {\n this.setLISelected(cli);\n var navIdx = this.getIndex(cli.id, true);\n var item = this.getItem(navIdx);\n var eventArgs = { element: cli, item: item };\n this.trigger('select', eventArgs);\n }\n if (isInstLI && (e.type === 'mouseover' || Browser.isDevice || this.showItemOnClick)) {\n var ul = void 0;\n if (cli.classList.contains(HEADER)) {\n ul = wrapper.children[this.navIdx.length - 1];\n this.toggleAnimation(ul);\n var sli = this.getLIByClass(ul, SELECTED);\n if (sli) {\n sli.classList.remove(SELECTED);\n }\n detach(cli.parentNode);\n this.navIdx.pop();\n }\n else {\n if (!cli.classList.contains(SEPARATOR)) {\n var showSubMenu = true;\n var cul = cli.parentNode;\n var cliIdx = this.getIdx(cul, cli);\n if (!Browser.isDevice) {\n var culIdx = this.getIdx(wrapper, cul);\n if (this.navIdx[culIdx] === cliIdx) {\n showSubMenu = false;\n }\n if (culIdx !== this.navIdx.length && (e.type !== 'mouseover' || showSubMenu)) {\n var sli = this.getLIByClass(cul, SELECTED);\n if (sli) {\n sli.classList.remove(SELECTED);\n }\n this.closeMenu(culIdx + 1, e);\n }\n }\n if (showSubMenu) {\n var idx = this.navIdx.concat(cliIdx);\n var item = this.getItem(idx);\n if (item.items.length) {\n if (e.type === 'mouseover') {\n this.setLISelected(cli);\n }\n cli.setAttribute('aria-expanded', 'true');\n this.navIdx.push(cliIdx);\n this.openMenu(cli, item, null, null, e);\n }\n else {\n if (e.type !== 'mouseover') {\n this.closeMenu(null, e);\n }\n }\n }\n }\n }\n }\n else {\n if (trgt.tagName !== 'UL' || trgt.parentElement !== wrapper) {\n if (!cli || !cli.querySelector('.' + CARET)) {\n this.closeMenu(null, e);\n }\n }\n }\n }\n };\n ContextMenu.prototype.setLISelected = function (li) {\n var sli = this.getLIByClass(li.parentElement, SELECTED);\n if (sli) {\n sli.classList.remove(SELECTED);\n }\n li.classList.remove(FOCUSED);\n li.classList.add(SELECTED);\n };\n ContextMenu.prototype.getLIByClass = function (ul, classname) {\n for (var i = 0, len = ul.children.length; i < len; i++) {\n if (ul.children[i].classList.contains(classname)) {\n return ul.children[i];\n }\n }\n return null;\n };\n ContextMenu.prototype.getItem = function (navIdx) {\n navIdx = navIdx.slice();\n var idx = navIdx.pop();\n var items = this.getItems(navIdx);\n return items[idx];\n };\n ContextMenu.prototype.getItems = function (navIdx) {\n var items = this.items;\n for (var i = 0; i < navIdx.length; i++) {\n items = items[navIdx[i]].items;\n }\n return items;\n };\n ContextMenu.prototype.getIdx = function (ul, li, skipHdr) {\n if (skipHdr === void 0) { skipHdr = true; }\n var idx = Array.prototype.indexOf.call(ul.children, li);\n if (skipHdr && ul.children[0].classList.contains(HEADER)) {\n idx--;\n }\n return idx;\n };\n ContextMenu.prototype.getLI = function (elem) {\n if (elem.tagName === 'LI') {\n return elem;\n }\n return closest(elem, 'li');\n };\n /**\n * Called internally if any of the property value changed\n * @private\n * @param {ContextMenuModel} newProp\n * @param {ContextMenuModel} oldProp\n * @returns void\n */\n ContextMenu.prototype.onPropertyChanged = function (newProp, oldProp) {\n var wrapper = this.getWrapper();\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'cssClass':\n if (oldProp.cssClass) {\n wrapper.classList.remove(oldProp.cssClass);\n }\n if (newProp.cssClass) {\n wrapper.classList.add(newProp.cssClass);\n }\n break;\n case 'enableRtl':\n wrapper.classList.toggle(RTL);\n break;\n case 'filter':\n this.closeMenu();\n this.filter = newProp.filter;\n break;\n case 'showItemOnClick':\n this.unWireEvents();\n this.showItemOnClick = newProp.showItemOnClick;\n this.wireEvents();\n break;\n case 'target':\n this.unWireEvents();\n this.target = newProp.target;\n this.wireEvents();\n break;\n case 'items':\n var idx = void 0;\n var navIdx = void 0;\n var item = void 0;\n var keys = Object.keys(newProp.items);\n for (var i = 0; i < keys.length; i++) {\n navIdx = this.getChangedItemIndex(newProp, [], Number(keys[i]));\n if (navIdx.length <= this.getWrapper().children.length) {\n idx = navIdx.pop();\n item = this.getItems(navIdx);\n this.insertAfter([item[idx]], item[idx].text);\n this.removeItem(item, navIdx, idx);\n }\n navIdx.length = 0;\n }\n break;\n }\n }\n };\n ContextMenu.prototype.getChangedItemIndex = function (newProp, index, idx) {\n index.push(idx);\n var key = Object.keys(newProp.items[idx]).pop();\n if (key === 'items') {\n var item = newProp.items[idx];\n this.getChangedItemIndex(item, index, Number(Object.keys(item.items).pop()));\n }\n else {\n if (key === 'isParentArray' && index.length > 1) {\n index.pop();\n }\n }\n return index;\n };\n ContextMenu.prototype.removeItem = function (item, navIdx, idx) {\n item.splice(idx, 1);\n var uls = this.getWrapper().children;\n if (navIdx.length < uls.length) {\n detach(uls[navIdx.length].children[idx]);\n }\n };\n /**\n * Used to unwire the bind events.\n * @private\n */\n ContextMenu.prototype.unWireEvents = function () {\n var wrapper = this.getWrapper();\n if (this.target) {\n var target = void 0;\n var touchModule = void 0;\n var targetElems = selectAll(this.target);\n for (var i = 0, len = targetElems.length; i < len; i++) {\n target = targetElems[i];\n if (Browser.isIos) {\n touchModule = getInstance(target, Touch);\n if (touchModule) {\n touchModule.destroy();\n }\n }\n else {\n EventHandler.remove(target, 'contextmenu', this.cmenuHandler);\n }\n }\n for (var _i = 0, _a = getScrollableParent(this.targetElement); _i < _a.length; _i++) {\n var parent_2 = _a[_i];\n EventHandler.remove(parent_2, 'scroll', this.scrollHandler);\n }\n }\n if (!Browser.isDevice) {\n EventHandler.remove(wrapper, 'mouseover', this.moverHandler);\n EventHandler.remove(document, 'mousedown', this.mouseDownHandler);\n }\n EventHandler.remove(document, 'click', this.delegateClickHandler);\n var keyboardModule = getInstance(wrapper, KeyboardEvents);\n if (keyboardModule) {\n keyboardModule.destroy();\n }\n };\n ContextMenu.prototype.toggleAnimation = function (ul, isMenuOpen) {\n var _this = this;\n if (isMenuOpen === void 0) { isMenuOpen = true; }\n if (this.animationSettings.effect === 'None' || !isMenuOpen) {\n this.end(ul, isMenuOpen);\n }\n else {\n this.animation.animate(ul, {\n name: this.animationSettings.effect,\n duration: this.animationSettings.duration,\n timingFunction: this.animationSettings.easing,\n begin: function (options) {\n options.element.style.display = 'block';\n options.element.style.maxHeight = options.element.getBoundingClientRect().height + 'px';\n },\n end: function (options) {\n _this.end(options.element, isMenuOpen);\n }\n });\n }\n };\n ContextMenu.prototype.end = function (ul, isMenuOpen) {\n if (isMenuOpen) {\n ul.style.display = 'block';\n ul.style.maxHeight = '';\n var item = this.navIdx.length ? this.getItem(this.navIdx) : null;\n var eventArgs = { element: ul, parentItem: item, items: item ? item.items : this.items };\n this.trigger('onOpen', eventArgs);\n if (ul.querySelector('.' + FOCUSED)) {\n ul.querySelector('.' + FOCUSED).focus();\n }\n else {\n var ele = void 0;\n ele = this.getWrapper().children[this.getIdx(this.getWrapper(), ul) - 1];\n if (ele) {\n ele.querySelector('.' + SELECTED).focus();\n }\n else {\n this.element.focus();\n }\n }\n }\n else {\n if (ul === this.element) {\n var fli = this.getLIByClass(this.element, FOCUSED);\n if (fli) {\n fli.classList.remove(FOCUSED);\n }\n var sli = this.getLIByClass(this.element, SELECTED);\n if (sli) {\n sli.classList.remove(SELECTED);\n }\n ul.style.display = 'none';\n }\n else {\n detach(ul);\n }\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @returns string\n */\n ContextMenu.prototype.getPersistData = function () {\n return '';\n };\n /**\n * Get component name.\n * @returns string\n * @private\n */\n ContextMenu.prototype.getModuleName = function () {\n return 'contextmenu';\n };\n ContextMenu.prototype.getIndex = function (data, isUniqueId, items, navIdx, isCallBack) {\n if (items === void 0) { items = this.items; }\n if (navIdx === void 0) { navIdx = []; }\n if (isCallBack === void 0) { isCallBack = false; }\n var item;\n for (var i = 0, len = items.length; i < len; i++) {\n item = items[i];\n if ((isUniqueId ? item.id : item.text) === data) {\n navIdx.push(i);\n break;\n }\n else if (item.items.length) {\n navIdx = this.getIndex(data, isUniqueId, item.items, navIdx, true);\n if (navIdx[navIdx.length - 1] === -1) {\n if (i !== len - 1) {\n navIdx.pop();\n }\n }\n else {\n navIdx.unshift(i);\n break;\n }\n }\n else {\n if (i === len - 1) {\n navIdx.push(-1);\n }\n }\n }\n return (!isCallBack && navIdx[0] === -1) ? [] : navIdx;\n };\n /**\n * This method is used to enable or disable the menu items in the ContextMenu based on the items and enable argument.\n * @param items - Text items that needs to be enabled/disabled.\n * @param enable - Set `true`/`false` to enable/disable the list items.\n * @param isUniqueId - Set `true` if it is a unique id.\n * @returns void\n */\n ContextMenu.prototype.enableItems = function (items, enable, isUniqueId) {\n if (enable === void 0) { enable = true; }\n var ul;\n var idx;\n var navIdx;\n var disabled = DISABLED;\n var wrapper = this.getWrapper();\n for (var i = 0; i < items.length; i++) {\n navIdx = this.getIndex(items[i], isUniqueId);\n idx = navIdx.pop();\n ul = wrapper.children[navIdx.length];\n if (ul) {\n if (enable) {\n if (Browser.isDevice && !ul.classList.contains('e-contextmenu')) {\n ul.children[idx + 1].classList.remove(disabled);\n }\n else {\n ul.children[idx].classList.remove(disabled);\n }\n }\n else {\n if (Browser.isDevice && !ul.classList.contains('e-contextmenu')) {\n ul.children[idx + 1].classList.add(disabled);\n }\n else {\n ul.children[idx].classList.add(disabled);\n }\n }\n }\n }\n };\n /**\n * This method is used to show the menu items in the ContextMenu based on the items text.\n * @param items - Text items that needs to be shown.\n * @param isUniqueId - Set `true` if it is a unique id.\n * @returns void\n */\n ContextMenu.prototype.showItems = function (items, isUniqueId) {\n this.showHideItems(items, false, isUniqueId);\n };\n /**\n * This method is used to hide the menu items in the ContextMenu based on the items text.\n * @param items - Text items that needs to be hidden.\n * @param isUniqueId - Set `true` if it is a unique id.\n * @returns void\n */\n ContextMenu.prototype.hideItems = function (items, isUniqueId) {\n this.showHideItems(items, true, isUniqueId);\n };\n ContextMenu.prototype.showHideItems = function (items, ishide, isUniqueId) {\n var ul;\n var index;\n var navIdx;\n var wrapper = this.getWrapper();\n for (var i = 0; i < items.length; i++) {\n navIdx = this.getIndex(items[i], isUniqueId);\n index = navIdx.pop();\n ul = wrapper.children[navIdx.length];\n if (ul) {\n if (ishide) {\n if (Browser.isDevice && !ul.classList.contains('e-contextmenu')) {\n ul.children[index + 1].classList.add(HIDE);\n }\n else {\n ul.children[index].classList.add(HIDE);\n }\n }\n else {\n if (Browser.isDevice && !ul.classList.contains('e-contextmenu')) {\n ul.children[index + 1].classList.remove(HIDE);\n }\n else {\n ul.children[index].classList.remove(HIDE);\n }\n }\n }\n }\n };\n /**\n * It is used to remove the menu items from the ContextMenu based on the items text.\n * @param items - Text items that needs to be removed.\n * @param isUniqueId - Set `true` if it is a unique id.\n * @returns void\n */\n ContextMenu.prototype.removeItems = function (items, isUniqueId) {\n var idx;\n var navIdx;\n var iitems;\n for (var i = 0; i < items.length; i++) {\n navIdx = this.getIndex(items[i], isUniqueId);\n idx = navIdx.pop();\n iitems = this.getItems(navIdx);\n this.removeItem(iitems, navIdx, idx);\n }\n };\n /**\n * It is used to insert the menu items after the specified menu item text.\n * @param items - Items that needs to be inserted.\n * @param text - Text item after that the element to be inserted.\n * @param isUniqueId - Set `true` if it is a unique id.\n * @returns void\n */\n ContextMenu.prototype.insertAfter = function (items, text, isUniqueId) {\n this.insertItems(items, text, isUniqueId);\n };\n /**\n * It is used to insert the menu items before the specified menu item text.\n * @param items - Items that needs to be inserted.\n * @param text - Text item before that the element to be inserted.\n * @param isUniqueId - Set `true` if it is a unique id.\n * @returns void\n */\n ContextMenu.prototype.insertBefore = function (items, text, isUniqueId) {\n this.insertItems(items, text, isUniqueId, false);\n };\n ContextMenu.prototype.insertItems = function (items, text, isUniqueId, isAfter) {\n if (isAfter === void 0) { isAfter = true; }\n var li;\n var idx;\n var navIdx;\n var iitems;\n var menuitem;\n var showIcon;\n for (var i = 0; i < items.length; i++) {\n navIdx = this.getIndex(text, isUniqueId);\n idx = navIdx.pop();\n iitems = this.getItems(navIdx);\n menuitem = new MenuItem(iitems[0], 'items', items[i], true);\n iitems.splice(isAfter ? idx + 1 : idx, 0, menuitem);\n var uls = this.getWrapper().children;\n if (navIdx.length < uls.length) {\n idx = isAfter ? idx + 1 : idx;\n showIcon = this.hasField(iitems, 'iconCss');\n li = this.createItems(iitems).children[idx];\n uls[navIdx.length].insertBefore(li, uls[navIdx.length].children[idx]);\n }\n }\n };\n /**\n * Destroys the widget.\n * @returns void\n */\n ContextMenu.prototype.destroy = function () {\n var _this = this;\n var wrapper = this.getWrapper();\n if (wrapper) {\n _super.prototype.destroy.call(this);\n this.unWireEvents();\n if (this.ngElement) {\n this.ngElement.style.display = 'block';\n }\n else {\n this.closeMenu();\n this.element.innerHTML = '';\n ['top', 'left', 'display', 'z-index'].forEach(function (key) {\n _this.element.style.removeProperty(key);\n });\n ['role', 'tabindex', 'class', 'style'].forEach(function (key) {\n if (['class', 'style'].indexOf(key) === -1 || !_this.element.getAttribute(key)) {\n _this.element.removeAttribute(key);\n }\n });\n wrapper.parentNode.insertBefore(this.element, wrapper);\n }\n detach(wrapper);\n }\n };\n __decorate([\n Property('')\n ], ContextMenu.prototype, \"cssClass\", void 0);\n __decorate([\n Property('')\n ], ContextMenu.prototype, \"filter\", void 0);\n __decorate([\n Property(false)\n ], ContextMenu.prototype, \"showItemOnClick\", void 0);\n __decorate([\n Collection([], MenuItem)\n ], ContextMenu.prototype, \"items\", void 0);\n __decorate([\n Property('')\n ], ContextMenu.prototype, \"target\", void 0);\n __decorate([\n Property({ duration: 400, easing: 'ease', effect: 'SlideDown' })\n ], ContextMenu.prototype, \"animationSettings\", void 0);\n __decorate([\n Event()\n ], ContextMenu.prototype, \"beforeItemRender\", void 0);\n __decorate([\n Event()\n ], ContextMenu.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], ContextMenu.prototype, \"onOpen\", void 0);\n __decorate([\n Event()\n ], ContextMenu.prototype, \"beforeClose\", void 0);\n __decorate([\n Event()\n ], ContextMenu.prototype, \"onClose\", void 0);\n __decorate([\n Event()\n ], ContextMenu.prototype, \"select\", void 0);\n ContextMenu = __decorate([\n NotifyPropertyChanges\n ], ContextMenu);\n return ContextMenu;\n}(Component));\nexport { ContextMenu };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, Event, closest, Collection, Complex, attributes, detach } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, ChildProperty, select, isVisible } from '@syncfusion/ej2-base';\nimport { KeyboardEvents, Browser, formatUnit, L10n } from '@syncfusion/ej2-base';\nimport { setStyleAttribute as setStyle, isNullOrUndefined as isNOU, selectAll } from '@syncfusion/ej2-base';\nimport { EventHandler, rippleEffect, Touch, compile, Animation } from '@syncfusion/ej2-base';\nimport { Toolbar } from '../toolbar/toolbar';\nvar CLS_TAB = 'e-tab';\nvar CLS_HEADER = 'e-tab-header';\nvar CLS_CONTENT = 'e-content';\nvar CLS_NEST = 'e-nested';\nvar CLS_ITEMS = 'e-items';\nvar CLS_ITEM = 'e-item';\nvar CLS_TEMPLATE = 'e-template';\nvar CLS_RTL = 'e-rtl';\nvar CLS_ACTIVE = 'e-active';\nvar CLS_DISABLE = 'e-disable';\nvar CLS_HIDDEN = 'e-hidden';\nvar CLS_FOCUS = 'e-focused';\nvar CLS_ICONS = 'e-icons';\nvar CLS_ICON = 'e-icon';\nvar CLS_ICON_CLOSE = 'e-close-icon';\nvar CLS_CLOSE_SHOW = 'e-close-show';\nvar CLS_TEXT = 'e-tab-text';\nvar CLS_INDICATOR = 'e-indicator';\nvar CLS_WRAP = 'e-tab-wrap';\nvar CLS_TEXT_WRAP = 'e-text-wrap';\nvar CLS_TAB_ICON = 'e-tab-icon';\nvar CLS_TB_ITEMS = 'e-toolbar-items';\nvar CLS_TB_ITEM = 'e-toolbar-item';\nvar CLS_TB_POP = 'e-toolbar-pop';\nvar CLS_TB_POPUP = 'e-toolbar-popup';\nvar CLS_POPUP_OPEN = 'e-popup-open';\nvar CLS_POPUP_CLOSE = 'e-popup-close';\nvar CLS_PROGRESS = 'e-progress';\nvar CLS_IGNORE = 'e-ignore';\nvar CLS_OVERLAY = 'e-overlay';\nvar TabActionSettings = /** @class */ (function (_super) {\n __extends(TabActionSettings, _super);\n function TabActionSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('SlideLeftIn')\n ], TabActionSettings.prototype, \"effect\", void 0);\n __decorate([\n Property(600)\n ], TabActionSettings.prototype, \"duration\", void 0);\n __decorate([\n Property('ease')\n ], TabActionSettings.prototype, \"easing\", void 0);\n return TabActionSettings;\n}(ChildProperty));\nexport { TabActionSettings };\nvar TabAnimationSettings = /** @class */ (function (_super) {\n __extends(TabAnimationSettings, _super);\n function TabAnimationSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({ effect: 'SlideLeftIn', duration: 600, easing: 'ease' }, TabActionSettings)\n ], TabAnimationSettings.prototype, \"previous\", void 0);\n __decorate([\n Complex({ effect: 'SlideRightIn', duration: 600, easing: 'ease' }, TabActionSettings)\n ], TabAnimationSettings.prototype, \"next\", void 0);\n return TabAnimationSettings;\n}(ChildProperty));\nexport { TabAnimationSettings };\n/**\n * Objects used for configuring the Tab item header properties.\n */\nvar Header = /** @class */ (function (_super) {\n __extends(Header, _super);\n function Header() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Header.prototype, \"text\", void 0);\n __decorate([\n Property('')\n ], Header.prototype, \"iconCss\", void 0);\n __decorate([\n Property('left')\n ], Header.prototype, \"iconPosition\", void 0);\n return Header;\n}(ChildProperty));\nexport { Header };\n/**\n * An array of object that is used to configure the Tab.\n */\nvar TabItem = /** @class */ (function (_super) {\n __extends(TabItem, _super);\n function TabItem() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({}, Header)\n ], TabItem.prototype, \"header\", void 0);\n __decorate([\n Property('')\n ], TabItem.prototype, \"content\", void 0);\n __decorate([\n Property('')\n ], TabItem.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], TabItem.prototype, \"disabled\", void 0);\n return TabItem;\n}(ChildProperty));\nexport { TabItem };\n/**\n * Tab is a content panel to show multiple contents in a single space, one at a time.\n * Each Tab item has an associated content, that will be displayed based on the active Tab header item.\n * ```html\n *
\n * \n * ```\n */\nvar Tab = /** @class */ (function (_super) {\n __extends(Tab, _super);\n /**\n * Initializes a new instance of the Tab class.\n * @param options - Specifies Tab model properties as options.\n * @param element - Specifies the element that is rendered as a Tab.\n */\n function Tab(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.show = { name: 'SlideDown', duration: 100 };\n _this.hide = { name: 'SlideUp', duration: 100 };\n _this.animateOptions = {};\n _this.animObj = new Animation(_this.animateOptions);\n _this.maxHeight = 0;\n _this.title = 'Close';\n _this.lastIndex = 0;\n /**\n * Contains the keyboard configuration of the Tab.\n */\n _this.keyConfigs = {\n tab: 'tab',\n home: 'home',\n end: 'end',\n enter: 'enter',\n space: 'space',\n delete: 'delete',\n moveLeft: 'leftarrow',\n moveRight: 'rightarrow',\n moveUp: 'uparrow',\n moveDown: 'downarrow'\n };\n return _this;\n }\n /**\n * Removes the component from the DOM and detaches all its related event handlers, attributes and classes.\n * @returns void\n */\n Tab.prototype.destroy = function () {\n var _this = this;\n if (!isNOU(this.tbObj)) {\n this.tbObj.destroy();\n }\n this.unWireEvents();\n ['role', 'aria-disabled', 'aria-activedescendant', 'tabindex', 'aria-orientation'].forEach(function (val) {\n _this.element.removeAttribute(val);\n });\n this.expTemplateContent();\n if (!this.isTemplate) {\n this.element.innerHTML = '';\n }\n else {\n var cntEle = select('.' + CLS_TAB + ' > .' + CLS_CONTENT, this.element);\n this.element.classList.remove(CLS_TEMPLATE);\n if (!isNOU(cntEle)) {\n cntEle.innerHTML = this.cnt;\n }\n }\n _super.prototype.destroy.call(this);\n this.trigger('destroyed');\n };\n /**\n * Initialize component\n * @private\n */\n Tab.prototype.preRender = function () {\n var nested = closest(this.element, '.' + CLS_CONTENT);\n this.prevIndex = 0;\n this.isNested = false;\n this.isPopup = false;\n this.initRender = true;\n this.isSwipeed = false;\n this.itemIndexArray = [];\n this.templateEle = [];\n if (!isNOU(nested)) {\n nested.parentElement.classList.add(CLS_NEST);\n this.isNested = true;\n }\n var name = Browser.info.name;\n var css = (name === 'msie') ? 'e-ie' : (name === 'edge') ? 'e-edge' : (name === 'safari') ? 'e-safari' : '';\n setStyle(this.element, { 'width': formatUnit(this.width), 'height': formatUnit(this.height) });\n this.setCssClass(this.element, this.cssClass, true);\n attributes(this.element, { role: 'tablist', 'aria-disabled': 'false', 'aria-activedescendant': '' });\n this.setCssClass(this.element, css, true);\n };\n /**\n * Initialize the component rendering\n * @private\n */\n Tab.prototype.render = function () {\n this.btnCls = this.createElement('span', { className: CLS_ICONS + ' ' + CLS_ICON_CLOSE, attrs: { title: this.title } });\n this.renderContainer();\n this.wireEvents();\n this.initRender = false;\n };\n Tab.prototype.renderContainer = function () {\n var ele = this.element;\n if (this.items.length > 0 && ele.children.length === 0) {\n ele.appendChild(this.createElement('div', { className: CLS_CONTENT }));\n this.setOrientation(this.headerPlacement, this.createElement('div', { className: CLS_HEADER }));\n this.isTemplate = false;\n }\n else if (this.element.children.length > 0) {\n this.isTemplate = true;\n ele.classList.add(CLS_TEMPLATE);\n var header = ele.querySelector('.' + CLS_HEADER);\n if (header && this.headerPlacement === 'Bottom') {\n this.setOrientation(this.headerPlacement, header);\n }\n }\n if (!isNOU(select('.' + CLS_HEADER, this.element)) && !isNOU(select('.' + CLS_CONTENT, this.element))) {\n this.renderHeader();\n this.tbItems = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element);\n if (!isNOU(this.tbItems)) {\n rippleEffect(this.tbItems, { selector: '.e-tab-wrap' });\n }\n this.renderContent();\n if (selectAll('.' + CLS_TB_ITEM, this.element).length > 0) {\n this.tbItems = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element);\n this.bdrLine = this.createElement('div', { className: CLS_INDICATOR + ' ' + CLS_HIDDEN + ' ' + CLS_IGNORE });\n var scrCnt = select('.e-hscroll-content', this.tbItems);\n if (!isNOU(scrCnt)) {\n scrCnt.insertBefore(this.bdrLine, scrCnt.firstChild);\n }\n else {\n this.tbItems.insertBefore(this.bdrLine, this.tbItems.firstChild);\n }\n this.setContentHeight(true);\n this.select(this.selectedItem);\n }\n this.setRTL(this.enableRtl);\n }\n };\n Tab.prototype.renderHeader = function () {\n var _this = this;\n var tabItems = [];\n this.hdrEle = select('.' + CLS_HEADER, this.element);\n if (!this.isTemplate) {\n tabItems = this.parseObject(this.items, 0);\n }\n else {\n var count = this.hdrEle.children.length;\n var hdrItems = [];\n for (var i = 0; i < count; i++) {\n hdrItems.push(this.hdrEle.children.item(i).innerHTML);\n }\n if (count > 0) {\n this.hdrEle.innerHTML = '';\n this.hdrEle.appendChild(this.createElement('div', { className: CLS_ITEMS }));\n hdrItems.forEach(function (item, index) {\n _this.lastIndex = index;\n var attr = {\n className: CLS_ITEM, id: CLS_ITEM + '_' + index,\n attrs: { role: 'tab', 'aria-controls': CLS_CONTENT + '_' + index, 'aria-selected': 'false' }\n };\n var txt = _this.createElement('span', {\n className: CLS_TEXT, innerHTML: item, attrs: { 'role': 'presentation' }\n }).outerHTML;\n var cont = _this.createElement('div', {\n className: CLS_TEXT_WRAP, innerHTML: txt + _this.btnCls.outerHTML\n }).outerHTML;\n var wrap = _this.createElement('div', { className: CLS_WRAP, innerHTML: cont, attrs: { tabIndex: '-1' } });\n select('.' + CLS_ITEMS, _this.element).appendChild(_this.createElement('div', attr));\n selectAll('.' + CLS_ITEM, _this.element)[index].appendChild(wrap);\n });\n }\n }\n this.tbObj = new Toolbar({\n width: '100%',\n overflowMode: this.overflowMode,\n items: (tabItems.length !== 0) ? tabItems : [],\n clicked: this.clickHandler.bind(this)\n });\n this.tbObj.createElement = this.createElement;\n this.tbObj.appendTo(this.hdrEle);\n attributes(this.element, { 'aria-orientation': 'horizontal' });\n this.setCloseButton(this.showCloseButton);\n this.setProperties({ headerPlacement: (this.element.children.item(0).classList.contains(CLS_HEADER)) ? 'Top' : 'Bottom' }, true);\n };\n Tab.prototype.renderContent = function () {\n this.cntEle = select('.' + CLS_CONTENT, this.element);\n var hdrItem = selectAll('.' + CLS_TB_ITEM, this.element);\n if (this.isTemplate) {\n this.cnt = (this.cntEle.children.length > 0) ? this.cntEle.innerHTML : '';\n var contents = this.cntEle.children;\n for (var i = 0; i < hdrItem.length; i++) {\n if (contents.length - 1 >= i) {\n contents.item(i).className += CLS_ITEM;\n attributes(contents.item(i), { 'role': 'tabpanel', 'aria-labelledby': CLS_ITEM + '_' + i });\n contents.item(i).id = CLS_CONTENT + '_' + i;\n }\n }\n }\n };\n Tab.prototype.reRenderItems = function () {\n this.renderContainer();\n if (!isNOU(this.cntEle)) {\n this.touchModule = new Touch(this.cntEle, { swipe: this.swipeHandler.bind(this) });\n }\n };\n Tab.prototype.parseObject = function (items, index) {\n var _this = this;\n var tbCount = selectAll('.' + CLS_TB_ITEM, this.element).length;\n var tItems = [];\n var txtWrapEle;\n items.forEach(function (item, i) {\n if (isNOU(item.header) || isNOU(item.header.text)) {\n _this.items.splice(i, 0);\n return;\n }\n var pos = (isNOU(item.header.iconPosition)) ? '' : item.header.iconPosition;\n var css = (isNOU(item.header.iconCss)) ? '' : item.header.iconCss;\n var txt = item.header.text;\n _this.lastIndex = ((tbCount === 0) ? i : ((_this.isReplace) ? (index + i) : (_this.lastIndex + 1)));\n var disabled = (item.disabled) ? ' ' + CLS_DISABLE + ' ' + CLS_OVERLAY : '';\n txtWrapEle = _this.createElement('div', { className: CLS_TEXT, attrs: { 'role': 'presentation' } });\n var tHtml = ((txt instanceof Object) ? txt.outerHTML : txt);\n var txtEmpty = (!isNOU(tHtml) && tHtml !== '');\n if (!isNOU(txt.tagName)) {\n txtWrapEle.appendChild(txt);\n }\n else {\n _this.headerTextCompile(txtWrapEle, txt);\n }\n var tEle;\n var icon = _this.createElement('span', {\n className: CLS_ICONS + ' ' + CLS_TAB_ICON + ' ' + CLS_ICON + '-' + pos + ' ' + css\n });\n var tCont = _this.createElement('div', { className: CLS_TEXT_WRAP });\n tCont.appendChild(txtWrapEle);\n if ((txt === '' || txt === undefined) && css === '') {\n return;\n }\n else {\n if ((txt !== '' && txt !== undefined) && css !== '') {\n if ((pos === 'left' || pos === 'top')) {\n tCont.insertBefore(icon, tCont.firstElementChild);\n }\n else {\n tCont.appendChild(icon);\n }\n tEle = txtWrapEle;\n }\n else {\n tEle = ((css === '') ? txtWrapEle : icon);\n if (tEle === icon) {\n detach(txtWrapEle);\n tCont.appendChild(icon);\n }\n }\n }\n var wrapAttrs = (item.disabled) ? {} : { tabIndex: '-1' };\n tCont.appendChild(_this.btnCls.cloneNode(true));\n var wrap = _this.createElement('div', { className: CLS_WRAP, attrs: wrapAttrs });\n wrap.appendChild(tCont);\n if (_this.itemIndexArray === []) {\n _this.itemIndexArray.push(CLS_ITEM + '_' + _this.lastIndex);\n }\n else {\n _this.itemIndexArray.splice((index + i), 0, CLS_ITEM + '_' + _this.lastIndex);\n }\n var attrObj = {\n id: CLS_ITEM + '_' + _this.lastIndex, role: 'tab', 'aria-selected': 'false'\n };\n var tItem = { htmlAttributes: attrObj, template: wrap };\n tItem.cssClass = item.cssClass + ' ' + disabled + ' ' + ((css !== '') ? 'e-i' + pos : '') + ' ' + ((!txtEmpty) ? CLS_ICON : '');\n if (pos === 'top' || pos === 'bottom') {\n _this.element.classList.add('e-vertical-icon');\n }\n tItems.push(tItem);\n });\n return tItems;\n };\n Tab.prototype.removeActiveClass = function (id) {\n var hdrActEle = selectAll(':root .' + CLS_HEADER + ' .' + CLS_TB_ITEM + '.' + CLS_ACTIVE, this.element)[0];\n if (this.headerPlacement === 'Bottom') {\n hdrActEle = selectAll(':root .' + CLS_HEADER + ' .' + CLS_TB_ITEM + '.' + CLS_ACTIVE, this.element.children[1])[0];\n }\n if (!isNOU(hdrActEle)) {\n hdrActEle.classList.remove(CLS_ACTIVE);\n var no = this.extIndex(hdrActEle.id);\n var trg = this.findEle(select('.' + CLS_CONTENT, this.element).children, CLS_CONTENT + '_' + no);\n }\n };\n Tab.prototype.checkPopupOverflow = function (ele) {\n this.tbPop = select('.' + CLS_TB_POP, this.element);\n var popIcon = select('.e-hor-nav', this.element);\n var tbrItems = select('.' + CLS_TB_ITEMS, this.element);\n if ((this.enableRtl && ((popIcon.offsetLeft + popIcon.offsetWidth) > tbrItems.offsetLeft))\n || (!this.enableRtl && popIcon.offsetLeft < tbrItems.offsetWidth)) {\n ele.classList.add(CLS_TB_POPUP);\n this.tbPop.insertBefore(ele.cloneNode(true), selectAll('.' + CLS_TB_POPUP, this.tbPop)[0]);\n ele.outerHTML = '';\n }\n return true;\n };\n Tab.prototype.popupHandler = function (target) {\n var ripEle = target.querySelector('.e-ripple-element');\n if (!isNOU(ripEle)) {\n ripEle.outerHTML = '';\n target.querySelector('.' + CLS_WRAP).classList.remove('e-ripple');\n }\n this.tbItem = selectAll('.' + CLS_TB_ITEMS + ' .' + CLS_TB_ITEM, this.hdrEle);\n var lastChild = this.tbItem[this.tbItem.length - 1];\n if (this.tbItem.length !== 0) {\n target.classList.remove(CLS_TB_POPUP);\n this.tbItems.appendChild(target.cloneNode(true));\n this.actEleId = target.id;\n target.outerHTML = '';\n if (this.checkPopupOverflow(lastChild)) {\n var prevEle = this.tbItems.lastChild.previousElementSibling;\n this.checkPopupOverflow(prevEle);\n }\n this.isPopup = true;\n }\n return selectAll('.' + CLS_TB_ITEM, this.tbItems).length - 1;\n };\n Tab.prototype.setCloseButton = function (val) {\n var trg = select('.' + CLS_HEADER, this.element);\n (val === true) ? trg.classList.add(CLS_CLOSE_SHOW) : trg.classList.remove(CLS_CLOSE_SHOW);\n this.tbObj.refreshOverflow();\n this.refreshActElePosition();\n };\n Tab.prototype.prevCtnAnimation = function (prev, current) {\n var animation;\n var checkRTL = this.enableRtl || this.element.classList.contains(CLS_RTL);\n if (this.isPopup || prev <= current) {\n if (this.animation.previous.effect === 'SlideLeftIn') {\n animation = { name: 'SlideLeftOut',\n duration: this.animation.previous.duration, timingFunction: this.animation.previous.easing };\n }\n else {\n animation = null;\n }\n }\n else {\n if (this.animation.next.effect === 'SlideRightIn') {\n animation = { name: 'SlideRightOut',\n duration: this.animation.next.duration, timingFunction: this.animation.next.easing };\n }\n else {\n animation = null;\n }\n }\n return animation;\n };\n Tab.prototype.triggerPrevAnimation = function (oldCnt, prevIndex) {\n var _this = this;\n var animateObj = this.prevCtnAnimation(prevIndex, this.selectedItem);\n if (!isNOU(animateObj)) {\n animateObj.begin = function () {\n setStyle(oldCnt, { 'position': 'absolute' });\n oldCnt.classList.add(CLS_PROGRESS);\n oldCnt.classList.add('e-view');\n };\n animateObj.end = function () {\n oldCnt.style.display = 'none';\n oldCnt.classList.remove(CLS_ACTIVE);\n oldCnt.classList.remove(CLS_PROGRESS);\n oldCnt.classList.remove('e-view');\n setStyle(oldCnt, { 'display': '', 'position': '' });\n if (oldCnt.childNodes.length === 0 && !_this.isTemplate) {\n detach(oldCnt);\n }\n };\n new Animation(animateObj).animate(oldCnt);\n }\n else {\n oldCnt.classList.remove(CLS_ACTIVE);\n }\n };\n Tab.prototype.triggerAnimation = function (id, value) {\n var _this = this;\n var prevIndex = this.prevIndex;\n var itemCollection = [].slice.call(this.element.querySelector('.' + CLS_CONTENT).children);\n var oldCnt;\n itemCollection.forEach(function (item) {\n if (item.id === _this.prevActiveEle) {\n oldCnt = item;\n }\n });\n var prevEle = this.tbItem[prevIndex];\n var no = this.extIndex(this.tbItem[this.selectedItem].id);\n var newCnt = this.getTrgContent(this.cntEle, no);\n if (isNOU(oldCnt) && !isNOU(prevEle)) {\n var idNo = this.extIndex(prevEle.id);\n oldCnt = this.getTrgContent(this.cntEle, idNo);\n }\n this.prevActiveEle = newCnt.id;\n if (this.initRender || value === false || this.animation === {} || isNOU(this.animation)) {\n if (oldCnt && oldCnt !== newCnt) {\n oldCnt.classList.remove(CLS_ACTIVE);\n }\n return;\n }\n var cnt = select('.' + CLS_CONTENT, this.element);\n var animateObj;\n if (this.prevIndex > this.selectedItem && !this.isPopup) {\n var openEff = this.animation.previous.effect;\n animateObj = {\n name: ((openEff === 'None') ? '' : ((openEff !== 'SlideLeftIn') ? openEff : 'SlideLeftIn')),\n duration: this.animation.previous.duration,\n timingFunction: this.animation.previous.easing\n };\n }\n else if (this.isPopup || this.prevIndex < this.selectedItem || this.prevIndex === this.selectedItem) {\n var clsEff = this.animation.next.effect;\n animateObj = {\n name: ((clsEff === 'None') ? '' : ((clsEff !== 'SlideRightIn') ? clsEff : 'SlideRightIn')),\n duration: this.animation.next.duration,\n timingFunction: this.animation.next.easing\n };\n }\n animateObj.progress = function () {\n cnt.classList.add(CLS_PROGRESS);\n _this.setActiveBorder();\n };\n animateObj.end = function () {\n cnt.classList.remove(CLS_PROGRESS);\n newCnt.classList.add(CLS_ACTIVE);\n };\n if (!this.initRender && !isNOU(oldCnt)) {\n this.triggerPrevAnimation(oldCnt, prevIndex);\n }\n this.isPopup = false;\n if (animateObj.name === '') {\n newCnt.classList.add(CLS_ACTIVE);\n }\n else {\n new Animation(animateObj).animate(newCnt);\n }\n };\n Tab.prototype.keyPressed = function (trg) {\n var trgParent = closest(trg, '.' + CLS_HEADER + ' .' + CLS_TB_ITEM);\n var trgIndex = this.getEleIndex(trgParent);\n if (!isNOU(this.popEle) && trg.classList.contains('e-hor-nav')) {\n (this.popEle.classList.contains(CLS_POPUP_OPEN)) ? this.popObj.hide(this.hide) : this.popObj.show(this.show);\n }\n else if (trg.classList.contains('e-scroll-nav')) {\n trg.click();\n }\n else {\n if (!isNOU(trgParent) && trgParent.classList.contains(CLS_ACTIVE) === false) {\n this.select(trgIndex);\n if (!isNOU(this.popEle)) {\n this.popObj.hide(this.hide);\n }\n }\n }\n };\n Tab.prototype.getEleIndex = function (item) {\n return Array.prototype.indexOf.call(selectAll('.' + CLS_HEADER + ' .' + CLS_TB_ITEM, this.element), item);\n };\n Tab.prototype.extIndex = function (id) {\n return id.replace(CLS_ITEM + '_', '');\n };\n Tab.prototype.expTemplateContent = function () {\n var _this = this;\n this.templateEle.forEach(function (eleStr) {\n if (!isNOU(_this.element.querySelector(eleStr))) {\n document.body.appendChild(_this.element.querySelector(eleStr)).style.display = 'none';\n }\n });\n };\n Tab.prototype.templateCompile = function (ele, cnt) {\n var tempEle = this.createElement('div');\n this.compileElement(tempEle, cnt, 'content');\n if (tempEle.childNodes.length !== 0) {\n ele.appendChild(tempEle);\n }\n };\n Tab.prototype.compileElement = function (ele, val, prop) {\n if (typeof val === 'string') {\n val = val.trim();\n }\n var templateFn = compile(val);\n var templateFUN;\n if (!isNOU(templateFn)) {\n templateFUN = templateFn({}, this, prop);\n }\n if (!isNOU(templateFn) && templateFUN.length > 0) {\n [].slice.call(templateFUN).forEach(function (el) {\n ele.appendChild(el);\n });\n }\n };\n Tab.prototype.headerTextCompile = function (element, text) {\n this.compileElement(element, text, 'headerText');\n };\n Tab.prototype.getContent = function (ele, cnt, callType) {\n var eleStr;\n if (typeof cnt === 'string' || isNOU(cnt.innerHTML)) {\n if (cnt[0] === '.' || cnt[0] === '#') {\n if (document.querySelectorAll(cnt).length) {\n var eleVal = document.querySelector(cnt);\n eleStr = eleVal.outerHTML.trim();\n if (callType === 'clone') {\n ele.appendChild(eleVal.cloneNode(true));\n }\n else {\n ele.appendChild(eleVal);\n eleVal.style.display = '';\n }\n }\n else {\n this.templateCompile(ele, cnt);\n }\n }\n else {\n this.templateCompile(ele, cnt);\n }\n }\n else {\n ele.appendChild(cnt);\n }\n if (!isNOU(eleStr)) {\n if (this.templateEle.indexOf(cnt.toString()) === -1) {\n this.templateEle.push(cnt.toString());\n }\n }\n };\n Tab.prototype.getTrgContent = function (cntEle, no) {\n var ele;\n if (this.element.classList.contains(CLS_NEST)) {\n ele = select('.' + CLS_NEST + '> .' + CLS_CONTENT + ' > #' + CLS_CONTENT + '_' + no, this.element);\n }\n else {\n ele = this.findEle(cntEle.children, CLS_CONTENT + '_' + no);\n }\n return ele;\n };\n Tab.prototype.findEle = function (items, key) {\n var ele;\n for (var i = 0; i < items.length; i++) {\n if (items[i].id === key) {\n ele = items[i];\n break;\n }\n }\n return ele;\n };\n Tab.prototype.setOrientation = function (place, ele) {\n (place === 'Bottom') ? this.element.appendChild(ele) : this.element.insertBefore(ele, select('.' + CLS_CONTENT, this.element));\n };\n Tab.prototype.setCssClass = function (ele, cls, val) {\n if (cls === '') {\n return;\n }\n var list = cls.split(' ');\n for (var i = 0; i < list.length; i++) {\n if (val) {\n ele.classList.add(list[i]);\n }\n else {\n ele.classList.remove(list[i]);\n }\n }\n };\n Tab.prototype.setContentHeight = function (val) {\n if (isNOU(this.cntEle)) {\n return;\n }\n var height;\n var hdrEle = select('.' + CLS_HEADER, this.element);\n if (this.heightAdjustMode === 'None') {\n if (this.height === 'auto') {\n return;\n }\n else {\n setStyle(this.cntEle, { 'height': (this.element.offsetHeight - hdrEle.offsetHeight) + 'px' });\n }\n }\n else if (this.heightAdjustMode === 'Fill') {\n setStyle(this.element, { 'height': '100%' });\n setStyle(this.cntEle, { 'height': 'auto' });\n }\n else if (this.heightAdjustMode === 'Auto') {\n var cnt = selectAll('.' + CLS_CONTENT + ' > .' + CLS_ITEM, this.element);\n if (this.isTemplate === true) {\n for (var i = 0; i < cnt.length; i++) {\n cnt[i].setAttribute('style', 'display:block; visibility: visible');\n this.maxHeight = Math.max(this.maxHeight, this.getHeight(cnt[i]));\n cnt[i].style.removeProperty('display');\n cnt[i].style.removeProperty('visibility');\n }\n }\n else {\n this.cntEle = select('.' + CLS_CONTENT, this.element);\n if (val === true) {\n this.cntEle.appendChild(this.createElement('div', {\n id: (CLS_CONTENT + '_' + 0), className: CLS_ITEM + ' ' + CLS_ACTIVE,\n attrs: { 'role': 'tabpanel', 'aria-labelledby': CLS_ITEM + '_' + 0 }\n }));\n }\n var ele = this.cntEle.children.item(0);\n for (var i = 0; i < this.items.length; i++) {\n this.getContent(ele, this.items[i].content, 'clone');\n this.maxHeight = Math.max(this.maxHeight, this.getHeight(ele));\n ele.innerHTML = '';\n }\n this.templateEle = [];\n this.getContent(ele, this.items[0].content, 'render');\n ele.classList.remove(CLS_ACTIVE);\n }\n setStyle(this.cntEle, { 'height': this.maxHeight + 'px' });\n }\n else {\n setStyle(this.cntEle, { 'height': 'auto' });\n }\n };\n Tab.prototype.getHeight = function (ele) {\n var cs = window.getComputedStyle(ele);\n return ele.offsetHeight + parseFloat(cs.getPropertyValue('padding-top')) + parseFloat(cs.getPropertyValue('padding-bottom')) +\n parseFloat(cs.getPropertyValue('margin-top')) + parseFloat(cs.getPropertyValue('margin-bottom'));\n };\n Tab.prototype.setActiveBorder = function () {\n var trg = select('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE, this.element);\n if (this.headerPlacement === 'Bottom') {\n trg = select('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE, this.element.children[1]);\n }\n if (trg === null) {\n return;\n }\n var root = closest(trg, '.' + CLS_TAB);\n if (this.element !== root) {\n return;\n }\n var hsCnt = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS + ' .e-hscroll-content', this.element.children[0]);\n this.tbItems = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element);\n var bar = select('.' + CLS_HEADER + ' .' + CLS_INDICATOR, this.element);\n if (this.headerPlacement === 'Bottom') {\n hsCnt = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS + ' .e-hscroll-content', this.element.children[1]);\n }\n var tbWidth = (isNOU(hsCnt)) ? this.tbItems.offsetWidth : hsCnt.offsetWidth;\n if (tbWidth !== 0) {\n setStyle(bar, { 'left': trg.offsetLeft + 'px', 'right': tbWidth - (trg.offsetLeft + trg.offsetWidth) + 'px' });\n }\n else {\n setStyle(bar, { 'left': 'auto', 'right': 'auto' });\n }\n if (!isNOU(this.bdrLine)) {\n this.bdrLine.classList.remove(CLS_HIDDEN);\n }\n };\n Tab.prototype.setActive = function (value) {\n this.tbItem = selectAll('.' + CLS_HEADER + ' .' + CLS_TB_ITEM, this.element);\n var trg = this.tbItem[value];\n if (value >= 0) {\n this.setProperties({ selectedItem: value }, true);\n }\n if (value < 0 || isNaN(value) || this.tbItem.length === 0) {\n return;\n }\n if (trg.classList.contains(CLS_ACTIVE)) {\n this.setActiveBorder();\n return;\n }\n if (!this.isTemplate) {\n var prev = this.tbItem[this.prevIndex];\n if (!isNOU(prev)) {\n prev.removeAttribute('aria-controls');\n }\n attributes(trg, { 'aria-controls': CLS_CONTENT + '_' + value });\n }\n var id = trg.id;\n this.removeActiveClass(id);\n trg.classList.add(CLS_ACTIVE);\n trg.setAttribute('aria-selected', 'true');\n var no = Number(this.extIndex(id));\n if (isNOU(this.prevActiveEle)) {\n this.prevActiveEle = CLS_CONTENT + '_' + no;\n }\n attributes(this.element, { 'aria-activedescendant': id });\n if (this.isTemplate) {\n if (select('.' + CLS_CONTENT, this.element).children.length > 0) {\n var trg_1 = this.findEle(select('.' + CLS_CONTENT, this.element).children, CLS_CONTENT + '_' + no);\n if (!isNOU(trg_1)) {\n trg_1.classList.add(CLS_ACTIVE);\n }\n this.triggerAnimation(id, this.enableAnimation);\n }\n }\n else {\n this.cntEle = select('.' + CLS_TAB + ' > .' + CLS_CONTENT, this.element);\n var item = this.getTrgContent(this.cntEle, this.extIndex(id));\n if (isNOU(item)) {\n this.cntEle.appendChild(this.createElement('div', {\n id: CLS_CONTENT + '_' + this.extIndex(id), className: CLS_ITEM + ' ' + CLS_ACTIVE,\n attrs: { role: 'tabpanel', 'aria-labelledby': CLS_ITEM + '_' + this.extIndex(id) }\n }));\n var eleTrg = this.getTrgContent(this.cntEle, this.extIndex(id));\n var itemIndex = Array.prototype.indexOf.call(this.itemIndexArray, trg.id);\n this.getContent(eleTrg, this.items[itemIndex].content, 'render');\n }\n else {\n item.classList.add(CLS_ACTIVE);\n }\n this.triggerAnimation(id, this.enableAnimation);\n }\n this.setActiveBorder();\n var curActItem = select('.' + CLS_HEADER + ' #' + id, this.element);\n this.refreshItemVisibility(curActItem);\n curActItem.firstChild.focus();\n var eventArg = {\n previousItem: this.prevItem,\n previousIndex: this.prevIndex,\n selectedItem: trg,\n selectedIndex: value,\n isSwiped: this.isSwipeed\n };\n if (!this.initRender || this.selectedItem !== 0) {\n this.trigger('selected', eventArg);\n }\n };\n Tab.prototype.setItems = function (items) {\n this.isReplace = true;\n this.tbItems = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element);\n this.tbObj.items = this.parseObject(items, 0);\n this.tbObj.dataBind();\n this.isReplace = false;\n };\n Tab.prototype.setRTL = function (value) {\n this.tbObj.enableRtl = value;\n this.tbObj.dataBind();\n this.setCssClass(this.element, CLS_RTL, value);\n this.refreshActiveBorder();\n };\n Tab.prototype.refreshActiveBorder = function () {\n if (!isNOU(this.bdrLine)) {\n this.bdrLine.classList.add(CLS_HIDDEN);\n }\n this.setActiveBorder();\n };\n Tab.prototype.wireEvents = function () {\n window.addEventListener('resize', this.refreshActElePosition.bind(this));\n EventHandler.add(this.element, 'mouseover', this.hoverHandler, this);\n EventHandler.add(this.element, 'keydown', this.spaceKeyDown, this);\n if (!isNOU(this.cntEle)) {\n this.touchModule = new Touch(this.cntEle, { swipe: this.swipeHandler.bind(this) });\n }\n this.keyModule = new KeyboardEvents(this.element, { keyAction: this.keyHandler.bind(this), keyConfigs: this.keyConfigs });\n this.tabKeyModule = new KeyboardEvents(this.element, {\n keyAction: this.keyHandler.bind(this),\n keyConfigs: { openPopup: 'shift+f10', tab: 'tab', shiftTab: 'shift+tab' },\n eventName: 'keydown'\n });\n };\n Tab.prototype.unWireEvents = function () {\n this.keyModule.destroy();\n this.tabKeyModule.destroy();\n if (!isNOU(this.cntEle)) {\n this.touchModule.destroy();\n }\n window.removeEventListener('resize', this.refreshActElePosition.bind(this));\n this.element.removeEventListener('mouseover', this.hoverHandler.bind(this));\n };\n Tab.prototype.clickHandler = function (args) {\n this.element.classList.remove(CLS_FOCUS);\n var trg = args.originalEvent.target;\n var trgParent = closest(trg, '.' + CLS_TB_ITEM);\n var trgIndex = this.getEleIndex(trgParent);\n if (trg.classList.contains(CLS_ICON_CLOSE)) {\n this.removeTab(trgIndex);\n }\n else {\n this.isPopup = false;\n if (!isNOU(trgParent) && trgIndex !== this.selectedItem) {\n this.select(trgIndex);\n }\n }\n };\n Tab.prototype.swipeHandler = function (e) {\n if (e.velocity < 3 && isNOU(e.originalEvent.changedTouches)) {\n return;\n }\n this.isSwipeed = true;\n if (e.swipeDirection === 'Right' && this.selectedItem !== 0) {\n for (var k = this.selectedItem - 1; k >= 0; k--) {\n if (!this.tbItem[k].classList.contains('e-hidden')) {\n this.select(k);\n break;\n }\n }\n }\n else if (e.swipeDirection === 'Left' && (this.selectedItem !== selectAll('.' + CLS_TB_ITEM, this.element).length - 1)) {\n for (var i = this.selectedItem + 1; i < this.tbItem.length; i++) {\n if (!this.tbItem[i].classList.contains('e-hidden')) {\n this.select(i);\n break;\n }\n }\n }\n this.isSwipeed = false;\n };\n Tab.prototype.spaceKeyDown = function (e) {\n if ((e.keyCode === 32 && e.which === 32) || (e.keyCode === 35 && e.which === 35)) {\n var clstHead = closest(e.target, '.' + CLS_HEADER);\n if (!isNOU(clstHead)) {\n e.preventDefault();\n }\n }\n };\n Tab.prototype.keyHandler = function (e) {\n if (this.element.classList.contains(CLS_DISABLE)) {\n return;\n }\n this.element.classList.add(CLS_FOCUS);\n var trg = e.target;\n var actEle = select('.' + CLS_HEADER + ' .' + CLS_ACTIVE, this.element);\n var tabItem = selectAll('.' + CLS_TB_ITEM + ':not(.' + CLS_TB_POPUP + ')', this.element);\n this.popEle = select('.' + CLS_TB_POP, this.element);\n if (!isNOU(this.popEle)) {\n this.popObj = this.popEle.ej2_instances[0];\n }\n switch (e.action) {\n case 'space':\n case 'enter':\n if (trg.parentElement.classList.contains(CLS_DISABLE)) {\n return;\n }\n if (e.action === 'enter' && trg.classList.contains('e-hor-nav')) {\n break;\n }\n this.keyPressed(trg);\n break;\n case 'tab':\n case 'shiftTab':\n if (trg.classList.contains(CLS_WRAP)\n && closest(trg, '.' + CLS_TB_ITEM).classList.contains(CLS_ACTIVE) === false) {\n trg.setAttribute('tabindex', '-1');\n }\n if (this.popObj && isVisible(this.popObj.element)) {\n this.popObj.hide(this.hide);\n }\n actEle.children.item(0).setAttribute('tabindex', '0');\n break;\n case 'moveLeft':\n case 'moveRight':\n var item = closest(document.activeElement, '.' + CLS_TB_ITEM);\n if (!isNOU(item)) {\n this.refreshItemVisibility(item);\n }\n break;\n case 'openPopup':\n e.preventDefault();\n if (!isNOU(this.popEle) && this.popEle.classList.contains(CLS_POPUP_CLOSE)) {\n this.popObj.show(this.show);\n }\n break;\n case 'delete':\n var trgParent = closest(trg, '.' + CLS_TB_ITEM);\n if (this.showCloseButton === true && !isNOU(trgParent)) {\n var nxtSib = trgParent.nextSibling;\n if (!isNOU(nxtSib) && nxtSib.classList.contains(CLS_TB_ITEM)) {\n nxtSib.firstChild.focus();\n }\n this.removeTab(this.getEleIndex(trgParent));\n }\n this.setActiveBorder();\n break;\n }\n };\n Tab.prototype.refreshActElePosition = function () {\n var activeEle = select('.' + CLS_TB_ITEM + '.' + CLS_TB_POPUP + '.' + CLS_ACTIVE, this.element);\n if (!isNOU(activeEle)) {\n this.select(this.getEleIndex(activeEle));\n }\n this.refreshActiveBorder();\n };\n Tab.prototype.refreshItemVisibility = function (target) {\n var scrCnt = select('.e-hscroll-content', this.tbItems);\n if (!isNOU(scrCnt)) {\n var scrBar = select('.e-hscroll-bar', this.tbItems);\n var scrStart = scrBar.scrollLeft;\n var scrEnd = scrStart + scrBar.offsetWidth;\n var eleStart = target.offsetLeft;\n var eleWidth = target.offsetWidth;\n var eleEnd = target.offsetLeft + target.offsetWidth;\n if ((scrStart < eleStart) && (scrEnd < eleEnd)) {\n var eleViewRange = scrEnd - eleStart;\n scrBar.scrollLeft = scrStart + (eleWidth - eleViewRange);\n }\n else {\n if ((scrStart > eleStart) && (scrEnd > eleEnd)) {\n var eleViewRange = eleEnd - scrStart;\n scrBar.scrollLeft = scrStart - (eleWidth - eleViewRange);\n }\n }\n }\n else {\n return;\n }\n };\n Tab.prototype.hoverHandler = function (e) {\n var trg = e.target;\n if (!isNOU(trg.classList) && trg.classList.contains(CLS_ICON_CLOSE)) {\n trg.setAttribute('title', new L10n('tab', { closeButtonTitle: this.title }, this.locale).getConstant('closeButtonTitle'));\n }\n };\n /**\n * Enables or disables the specified Tab item. On passing value as `false`, the item will be disabled.\n * @param {number} index - Index value of target Tab item.\n * @param {boolean} value - Boolean value that determines whether the command should be enabled or disabled.\n * By default, isEnable is true.\n * @returns void.\n */\n Tab.prototype.enableTab = function (index, value) {\n var tbItems = selectAll('.' + CLS_TB_ITEM, this.element)[index];\n if (isNOU(tbItems)) {\n return;\n }\n if (value === true) {\n tbItems.classList.remove(CLS_DISABLE, CLS_OVERLAY);\n tbItems.firstChild.setAttribute('tabindex', '-1');\n }\n else {\n tbItems.classList.add(CLS_DISABLE, CLS_OVERLAY);\n tbItems.firstChild.removeAttribute('tabindex');\n if (tbItems.classList.contains(CLS_ACTIVE)) {\n this.select(index + 1);\n }\n }\n if (!isNOU(this.items[index])) {\n this.items[index].disabled = !value;\n this.dataBind();\n }\n tbItems.setAttribute('aria-disabled', (value === true) ? 'false' : 'true');\n };\n /**\n * Adds new items to the Tab that accepts an array as Tab items.\n * @param {TabItemsModel[]} items - An array of item that is added to the Tab.\n * @param {number} index - Number value that determines where the items to be added. By default, index is 0.\n * @returns void.\n */\n Tab.prototype.addTab = function (items, index) {\n var _this = this;\n var lastEleIndex = 0;\n if (!this.isReplace) {\n this.trigger('adding', { addedItems: items });\n }\n this.hdrEle = select('.' + CLS_HEADER, this.element);\n if (isNOU(this.hdrEle)) {\n this.items = items;\n this.reRenderItems();\n return;\n }\n var itemsCount = selectAll('.' + CLS_TB_ITEM, this.element).length;\n if (itemsCount !== 0) {\n lastEleIndex = this.lastIndex + 1;\n }\n if (isNOU(index)) {\n index = itemsCount - 1;\n }\n if (itemsCount < index || index < 0 || isNaN(index)) {\n return;\n }\n if (itemsCount === 0 && !isNOU(this.hdrEle)) {\n this.hdrEle.style.display = '';\n }\n if (!isNOU(this.bdrLine)) {\n this.bdrLine.classList.add(CLS_HIDDEN);\n }\n this.tbItems = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element);\n var tabItems = this.parseObject(items, index);\n items.forEach(function (item, place) {\n _this.items.splice((index + place), 0, item);\n if (_this.isTemplate && !isNOU(item.header) && !isNOU(item.header.text)) {\n var no = lastEleIndex + place;\n var ele = _this.createElement('div', {\n id: CLS_CONTENT + '_' + no, className: CLS_ITEM, attrs: { role: 'tabpanel', 'aria-labelledby': CLS_ITEM + '_' + no }\n });\n _this.cntEle.insertBefore(ele, _this.cntEle.children[(index + place)]);\n var eleTrg = _this.getTrgContent(_this.cntEle, no.toString());\n _this.getContent(eleTrg, item.content, 'render');\n }\n });\n this.tbObj.addItems(tabItems, index);\n if (!this.isReplace) {\n this.trigger('added', { addedItems: items });\n }\n if (this.selectedItem === index) {\n this.select(index);\n }\n else {\n this.setActiveBorder();\n }\n };\n /**\n * Removes the items in the Tab from the specified index.\n * @param {number} index - Index of target item that is going to be removed.\n * @returns void.\n */\n Tab.prototype.removeTab = function (index) {\n var trg = selectAll('.' + CLS_TB_ITEM, this.element)[index];\n var removeArgs = { removedItem: trg, removedIndex: index };\n this.trigger('removing', removeArgs);\n if (isNOU(trg)) {\n return;\n }\n this.tbObj.removeItems(index);\n this.items.splice(index, 1);\n this.itemIndexArray.splice(index, 1);\n this.refreshActiveBorder();\n var cntTrg = select('#' + CLS_CONTENT + '_' + this.extIndex(trg.id), select('.' + CLS_CONTENT, this.element));\n if (!isNOU(cntTrg)) {\n detach(cntTrg);\n }\n this.trigger('removed', removeArgs);\n if (trg.classList.contains(CLS_ACTIVE)) {\n index = (index > selectAll('.' + CLS_TB_ITEM + ':not(.' + CLS_TB_POPUP + ')', this.element).length - 1) ? index - 1 : index;\n this.enableAnimation = false;\n this.selectedItem = index;\n this.select(index);\n }\n if (selectAll('.' + CLS_TB_ITEM, this.element).length === 0) {\n this.hdrEle.style.display = 'none';\n }\n this.enableAnimation = true;\n };\n /**\n * Shows or hides the Tab that is in the specified index.\n * @param {number} index - Index value of target item.\n * @param {boolean} value - Based on this Boolean value, item will be hide (false) or show (true). By default, value is true.\n * @returns void.\n */\n Tab.prototype.hideTab = function (index, value) {\n var item = selectAll('.' + CLS_TB_ITEM, this.element)[index];\n if (isNOU(item)) {\n return;\n }\n if (isNOU(value)) {\n value = true;\n }\n this.bdrLine.classList.add(CLS_HIDDEN);\n if (value === true) {\n item.classList.add(CLS_HIDDEN);\n if (item.classList.contains(CLS_ACTIVE)) {\n if (index !== 0) {\n for (var i = index - 1; i >= 0; i--) {\n if (!this.tbItem[i].classList.contains('e-hidden')) {\n this.select(i);\n break;\n }\n else if (i === 0) {\n for (var k = index + 1; k < this.tbItem.length; k++) {\n if (!this.tbItem[k].classList.contains('e-hidden')) {\n this.select(k);\n break;\n }\n }\n }\n }\n }\n else {\n for (var k = index + 1; k < this.tbItem.length; k++) {\n if (!this.tbItem[k].classList.contains('e-hidden')) {\n this.select(k);\n break;\n }\n }\n }\n }\n }\n else {\n item.classList.remove(CLS_HIDDEN);\n }\n this.setActiveBorder();\n item.setAttribute('aria-hidden', '' + value);\n };\n /**\n * Specifies the index or HTMLElement to select an item from the Tab.\n * @param {number | HTMLElement} args - Index or DOM element is used for selecting an item from the Tab.\n * @returns void.\n */\n Tab.prototype.select = function (args) {\n this.tbItems = select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element);\n this.tbItem = selectAll('.' + CLS_HEADER + ' .' + CLS_TB_ITEM, this.element);\n this.prevItem = this.tbItem[this.prevIndex];\n var trg = this.tbItem[args];\n if (!isNOU(this.prevItem) && !this.prevItem.classList.contains(CLS_DISABLE)) {\n this.prevItem.children.item(0).setAttribute('tabindex', '-1');\n }\n var eventArg = {\n previousItem: this.prevItem,\n previousIndex: this.prevIndex,\n selectedItem: this.tbItem[this.selectedItem],\n selectedIndex: this.selectedItem,\n selectingItem: trg,\n selectingIndex: args,\n isSwiped: this.isSwipeed\n };\n if (!this.initRender || this.selectedItem !== 0) {\n this.trigger('selecting', eventArg);\n }\n if (eventArg.cancel) {\n return;\n }\n if (typeof args === 'number') {\n if (!isNOU(this.tbItem[args]) && this.tbItem[args].classList.contains(CLS_DISABLE)) {\n for (var i = args + 1; i < this.items.length; i++) {\n if (this.items[i].disabled === false) {\n args = i;\n break;\n }\n else {\n args = 0;\n }\n }\n }\n if (this.tbItem.length > args && args >= 0 && !isNaN(args)) {\n if (!this.tbItem[this.selectedItem].classList.contains('e-hidden')) {\n this.prevIndex = this.selectedItem;\n }\n else {\n for (var i = this.selectedItem; i >= 0; i--) {\n if (!this.tbItem[i].classList.contains('e-hidden')) {\n this.prevIndex = i;\n break;\n }\n }\n }\n if (this.tbItem[args].classList.contains(CLS_TB_POPUP)) {\n this.setActive(this.popupHandler(this.tbItem[args]));\n }\n else {\n this.setActive(args);\n }\n }\n else {\n this.setActive(0);\n }\n }\n else if (args instanceof (HTMLElement)) {\n this.setActive(this.getEleIndex(args));\n }\n };\n /**\n * Specifies the value to disable/enable the Tab component.\n * When set to `true`, the component will be disabled.\n * @param {boolean} value - Based on this Boolean value, Tab will be enabled (false) or disabled (true).\n * @returns void.\n */\n Tab.prototype.disable = function (value) {\n this.setCssClass(this.element, CLS_DISABLE, value);\n this.element.setAttribute('aria-disabled', '' + value);\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @returns string\n */\n Tab.prototype.getPersistData = function () {\n return this.addOnPersist(['selectedItem', 'actEleId']);\n };\n /**\n * Returns the current module name.\n * @returns string\n * @private\n */\n Tab.prototype.getModuleName = function () {\n return 'tab';\n };\n /**\n * Gets called when the model property changes.The data that describes the old and new values of the property that changed.\n * @param {TabModel} newProp\n * @param {TabModel} oldProp\n * @returns void\n * @private\n */\n Tab.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'width':\n setStyle(this.element, { width: formatUnit(newProp.width) });\n break;\n case 'height':\n setStyle(this.element, { height: formatUnit(newProp.height) });\n this.setContentHeight(false);\n break;\n case 'cssClass':\n this.setCssClass(this.element, newProp.cssClass, true);\n break;\n case 'items':\n if (!(newProp.items instanceof Array && oldProp.items instanceof Array)) {\n var changedProp = Object.keys(newProp.items);\n for (var i = 0; i < changedProp.length; i++) {\n var index = parseInt(Object.keys(newProp.items)[i], 10);\n var property = Object.keys(newProp.items[index])[0];\n var oldVal = Object(oldProp.items[index])[property];\n var newVal = Object(newProp.items[index])[property];\n var hdrItem = select('.' + CLS_TB_ITEMS + ' #' + CLS_ITEM + '_' + index, this.element);\n var cntItem = select('.' + CLS_CONTENT + ' #' + CLS_CONTENT + '_' + index, this.element);\n if (property === 'header') {\n var arr = [];\n arr.push(this.items[index]);\n this.items.splice(index, 1);\n this.itemIndexArray.splice(index, 1);\n this.tbObj.items.splice(index, 1);\n var isHiddenEle = hdrItem.classList.contains(CLS_HIDDEN);\n detach(hdrItem);\n this.isReplace = true;\n this.addTab(arr, index);\n if (isHiddenEle) {\n this.hideTab(index);\n }\n this.isReplace = false;\n }\n if (property === 'content' && !isNOU(cntItem)) {\n var strVal = typeof newVal === 'string' || isNOU(newVal.innerHTML);\n if (strVal && (newVal[0] === '.' || newVal[0] === '#') && newVal.length) {\n var eleVal = document.querySelector(newVal);\n cntItem.appendChild(eleVal);\n eleVal.style.display = '';\n }\n else if (newVal === '' && oldVal[0] === '#') {\n document.body.appendChild(this.element.querySelector(oldVal)).style.display = 'none';\n cntItem.innerHTML = newVal;\n }\n else {\n cntItem.innerHTML = newVal;\n }\n }\n if (property === 'cssClass') {\n if (!isNOU(hdrItem)) {\n hdrItem.classList.remove(oldVal);\n hdrItem.classList.add(newVal);\n }\n if (!isNOU(cntItem)) {\n cntItem.classList.remove(oldVal);\n cntItem.classList.add(newVal);\n }\n }\n if (property === 'disabled') {\n this.enableTab(index, ((newVal === true) ? false : true));\n }\n }\n }\n else {\n this.lastIndex = 0;\n if (isNOU(this.tbObj)) {\n this.reRenderItems();\n }\n else {\n this.setItems(newProp.items);\n if (this.templateEle.length > 0) {\n this.expTemplateContent();\n }\n this.templateEle = [];\n select('.' + CLS_TAB + ' > .' + CLS_CONTENT, this.element).innerHTML = '';\n this.select(this.selectedItem);\n }\n }\n break;\n case 'showCloseButton':\n this.setCloseButton(newProp.showCloseButton);\n break;\n case 'selectedItem':\n this.selectedItem = oldProp.selectedItem;\n this.select(newProp.selectedItem);\n break;\n case 'headerPlacement':\n var tempHdrEle = select('.' + CLS_HEADER, this.element);\n this.setOrientation(newProp.headerPlacement, tempHdrEle);\n this.select(this.selectedItem);\n break;\n case 'enableRtl':\n this.setRTL(newProp.enableRtl);\n break;\n case 'overflowMode':\n this.tbObj.overflowMode = newProp.overflowMode;\n this.tbObj.dataBind();\n this.refreshActElePosition();\n break;\n case 'heightAdjustMode':\n this.setContentHeight(false);\n this.select(this.selectedItem);\n break;\n }\n }\n };\n __decorate([\n Collection([], TabItem)\n ], Tab.prototype, \"items\", void 0);\n __decorate([\n Property('100%')\n ], Tab.prototype, \"width\", void 0);\n __decorate([\n Property('auto')\n ], Tab.prototype, \"height\", void 0);\n __decorate([\n Property('')\n ], Tab.prototype, \"cssClass\", void 0);\n __decorate([\n Property(0)\n ], Tab.prototype, \"selectedItem\", void 0);\n __decorate([\n Property('Top')\n ], Tab.prototype, \"headerPlacement\", void 0);\n __decorate([\n Property('Content')\n ], Tab.prototype, \"heightAdjustMode\", void 0);\n __decorate([\n Property('Scrollable')\n ], Tab.prototype, \"overflowMode\", void 0);\n __decorate([\n Property(false)\n ], Tab.prototype, \"enableRtl\", void 0);\n __decorate([\n Property(false)\n ], Tab.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(false)\n ], Tab.prototype, \"showCloseButton\", void 0);\n __decorate([\n Complex({}, TabAnimationSettings)\n ], Tab.prototype, \"animation\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"adding\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"added\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"selecting\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"selected\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"removing\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"removed\", void 0);\n __decorate([\n Event()\n ], Tab.prototype, \"destroyed\", void 0);\n Tab = __decorate([\n NotifyPropertyChanges\n ], Tab);\n return Tab;\n}(Component));\nexport { Tab };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, isUndefined, Browser, compile } from '@syncfusion/ej2-base';\nimport { Property, NotifyPropertyChanges, ChildProperty, Complex } from '@syncfusion/ej2-base';\nimport { Event, EventHandler, KeyboardEvents } from '@syncfusion/ej2-base';\nimport { rippleEffect, Animation } from '@syncfusion/ej2-base';\nimport { Draggable, Droppable } from '@syncfusion/ej2-base';\nimport { addClass, removeClass, closest, matches, detach, select, selectAll, isVisible, append } from '@syncfusion/ej2-base';\nimport { DataManager, Query } from '@syncfusion/ej2-data';\nimport { isNullOrUndefined as isNOU, Touch, getValue, setValue } from '@syncfusion/ej2-base';\nimport { ListBase } from '@syncfusion/ej2-lists';\nimport { createCheckBox, rippleMouseHandler } from '@syncfusion/ej2-buttons';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';\nvar ROOT = 'e-treeview';\nvar CONTROL = 'e-control';\nvar COLLAPSIBLE = 'e-icon-collapsible';\nvar EXPANDABLE = 'e-icon-expandable';\nvar LISTITEM = 'e-list-item';\nvar LISTTEXT = 'e-list-text';\nvar PARENTITEM = 'e-list-parent';\nvar HOVER = 'e-hover';\nvar ACTIVE = 'e-active';\nvar LOAD = 'e-icons-spinner';\nvar PROCESS = 'e-process';\nvar ICON = 'e-icons';\nvar TEXTWRAP = 'e-text-content';\nvar INPUT = 'e-input';\nvar INPUTGROUP = 'e-input-group';\nvar TREEINPUT = 'e-tree-input';\nvar EDITING = 'e-editing';\nvar RTL = 'e-rtl';\nvar DRAGITEM = 'e-drag-item';\nvar DROPPABLE = 'e-droppable';\nvar DRAGGING = 'e-dragging';\nvar SIBLING = 'e-sibling';\nvar DROPIN = 'e-drop-in';\nvar DROPNEXT = 'e-drop-next';\nvar DROPOUT = 'e-drop-out';\nvar NODROP = 'e-no-drop';\nvar FULLROWWRAP = 'e-fullrow-wrap';\nvar FULLROW = 'e-fullrow';\nvar SELECTED = 'e-selected';\nvar EXPANDED = 'e-expanded';\nvar NODECOLLAPSED = 'e-node-collapsed';\nvar DISABLE = 'e-disable';\nvar CONTENT = 'e-content';\nvar DOWNTAIL = 'e-downtail';\nvar DROPCOUNT = 'e-drop-count';\nvar CHECK = 'e-check';\nvar INDETERMINATE = 'e-stop';\nvar CHECKBOXWRAP = 'e-checkbox-wrapper';\nvar CHECKBOXFRAME = 'e-frame';\nvar CHECKBOXRIPPLE = 'e-ripple-container';\nvar FOCUS = 'e-node-focus';\nvar IMAGE = 'e-list-img';\nvar BIGGER = 'e-bigger';\nvar SMALL = 'e-small';\nvar treeAriaAttr = {\n treeRole: 'tree',\n itemRole: 'treeitem',\n listRole: 'group',\n itemText: '',\n wrapperRole: '',\n};\n/**\n * Configures the fields to bind to the properties of node in the TreeView component.\n */\nvar FieldsSettings = /** @class */ (function (_super) {\n __extends(FieldsSettings, _super);\n function FieldsSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('child')\n ], FieldsSettings.prototype, \"child\", void 0);\n __decorate([\n Property([])\n ], FieldsSettings.prototype, \"dataSource\", void 0);\n __decorate([\n Property('expanded')\n ], FieldsSettings.prototype, \"expanded\", void 0);\n __decorate([\n Property('hasChildren')\n ], FieldsSettings.prototype, \"hasChildren\", void 0);\n __decorate([\n Property('htmlAttributes')\n ], FieldsSettings.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property('iconCss')\n ], FieldsSettings.prototype, \"iconCss\", void 0);\n __decorate([\n Property('id')\n ], FieldsSettings.prototype, \"id\", void 0);\n __decorate([\n Property('imageUrl')\n ], FieldsSettings.prototype, \"imageUrl\", void 0);\n __decorate([\n Property('isChecked')\n ], FieldsSettings.prototype, \"isChecked\", void 0);\n __decorate([\n Property('parentID')\n ], FieldsSettings.prototype, \"parentID\", void 0);\n __decorate([\n Property(null)\n ], FieldsSettings.prototype, \"query\", void 0);\n __decorate([\n Property('selected')\n ], FieldsSettings.prototype, \"selected\", void 0);\n __decorate([\n Property(null)\n ], FieldsSettings.prototype, \"tableName\", void 0);\n __decorate([\n Property('text')\n ], FieldsSettings.prototype, \"text\", void 0);\n __decorate([\n Property('tooltip')\n ], FieldsSettings.prototype, \"tooltip\", void 0);\n __decorate([\n Property('navigateUrl')\n ], FieldsSettings.prototype, \"navigateUrl\", void 0);\n return FieldsSettings;\n}(ChildProperty));\nexport { FieldsSettings };\n/**\n * Configures animation settings for the TreeView component.\n */\nvar ActionSettings = /** @class */ (function (_super) {\n __extends(ActionSettings, _super);\n function ActionSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('SlideDown')\n ], ActionSettings.prototype, \"effect\", void 0);\n __decorate([\n Property(400)\n ], ActionSettings.prototype, \"duration\", void 0);\n __decorate([\n Property('linear')\n ], ActionSettings.prototype, \"easing\", void 0);\n return ActionSettings;\n}(ChildProperty));\nexport { ActionSettings };\n/**\n * Configures the animation settings for expanding and collapsing nodes in TreeView.\n */\nvar NodeAnimationSettings = /** @class */ (function (_super) {\n __extends(NodeAnimationSettings, _super);\n function NodeAnimationSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({ effect: 'SlideUp', duration: 400, easing: 'linear' }, ActionSettings)\n ], NodeAnimationSettings.prototype, \"collapse\", void 0);\n __decorate([\n Complex({ effect: 'SlideDown', duration: 400, easing: 'linear' }, ActionSettings)\n ], NodeAnimationSettings.prototype, \"expand\", void 0);\n return NodeAnimationSettings;\n}(ChildProperty));\nexport { NodeAnimationSettings };\n/**\n * The TreeView component is used to represent hierarchical data in a tree like structure with advanced\n * functions to perform edit, drag and drop, selection with check-box, and more.\n * ```html\n *
\n * ```\n * ```typescript\n * let treeObj: TreeView = new TreeView();\n * treeObj.appendTo('#tree');\n * ```\n */\nvar TreeView = /** @class */ (function (_super) {\n __extends(TreeView, _super);\n function TreeView(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.mouseDownStatus = false;\n return _this;\n }\n TreeView_1 = TreeView;\n /**\n * Get component name.\n * @returns string\n * @private\n */\n TreeView.prototype.getModuleName = function () {\n return 'treeview';\n };\n /**\n * Initialize the event handler\n */\n TreeView.prototype.preRender = function () {\n var _this = this;\n this.checkActionNodes = [];\n this.dragStartAction = false;\n this.isAnimate = false;\n this.keyConfigs = {\n escape: 'escape',\n end: 'end',\n enter: 'enter',\n f2: 'f2',\n home: 'home',\n moveDown: 'downarrow',\n moveLeft: 'leftarrow',\n moveRight: 'rightarrow',\n moveUp: 'uparrow',\n ctrlDown: 'ctrl+downarrow',\n ctrlUp: 'ctrl+uparrow',\n ctrlEnter: 'ctrl+enter',\n ctrlHome: 'ctrl+home',\n ctrlEnd: 'ctrl+end',\n ctrlA: 'ctrl+A',\n shiftDown: 'shift+downarrow',\n shiftUp: 'shift+uparrow',\n shiftEnter: 'shift+enter',\n shiftHome: 'shift+home',\n shiftEnd: 'shift+end',\n csDown: 'ctrl+shift+downarrow',\n csUp: 'ctrl+shift+uparrow',\n csEnter: 'ctrl+shift+enter',\n csHome: 'ctrl+shift+home',\n csEnd: 'ctrl+shift+end',\n space: 'space',\n };\n this.listBaseOption = {\n expandCollapse: true,\n showIcon: true,\n expandIconClass: EXPANDABLE,\n ariaAttributes: treeAriaAttr,\n expandIconPosition: 'Left',\n itemCreated: function (e) {\n _this.beforeNodeCreate(e);\n },\n };\n this.updateListProp(this.fields);\n this.aniObj = new Animation({});\n this.treeList = [];\n this.isLoaded = false;\n this.setTouchClass();\n if (isNOU(this.selectedNodes)) {\n this.setProperties({ selectedNodes: [] }, true);\n }\n if (isNOU(this.checkedNodes)) {\n this.setProperties({ checkedNodes: [] }, true);\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @returns string\n * @hidden\n */\n TreeView.prototype.getPersistData = function () {\n var keyEntity = ['selectedNodes', 'checkedNodes'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * To Initialize the control rendering\n * @private\n */\n TreeView.prototype.render = function () {\n this.isAnimate = true;\n this.initialize();\n this.setDataBinding();\n this.setExpandOnType();\n this.setRipple();\n this.wireEditingEvents(this.allowEditing);\n this.setDragAndDrop(this.allowDragAndDrop);\n this.wireEvents();\n };\n TreeView.prototype.initialize = function () {\n this.element.setAttribute('role', 'tree');\n this.element.setAttribute('tabindex', '0');\n this.element.setAttribute('aria-activedescendant', this.element.id + '_active');\n this.setCssClass(null, this.cssClass);\n this.setEnableRtl();\n this.setFullRow(this.fullRowSelect);\n this.nodeTemplateFn = this.templateComplier(this.nodeTemplate);\n };\n TreeView.prototype.setEnableRtl = function () {\n this.enableRtl ? addClass([this.element], RTL) : removeClass([this.element], RTL);\n };\n TreeView.prototype.setRipple = function () {\n var tempStr = '.' + FULLROW + ',.' + TEXTWRAP;\n var rippleModel = {\n selector: tempStr,\n ignore: '.' + TEXTWRAP + ' > .' + ICON + ',.' + INPUTGROUP + ',.' + INPUT + ', .' + CHECKBOXWRAP\n };\n this.rippleFn = rippleEffect(this.element, rippleModel);\n var iconModel = {\n selector: '.' + TEXTWRAP + ' > .' + ICON,\n isCenterRipple: true,\n };\n this.rippleIconFn = rippleEffect(this.element, iconModel);\n };\n TreeView.prototype.setFullRow = function (isEnabled) {\n isEnabled ? addClass([this.element], FULLROWWRAP) : removeClass([this.element], FULLROWWRAP);\n };\n TreeView.prototype.setMultiSelect = function (isEnabled) {\n var firstUl = select('.' + PARENTITEM, this.element);\n if (isEnabled) {\n firstUl.setAttribute('aria-multiselectable', 'true');\n }\n else {\n firstUl.removeAttribute('aria-multiselectable');\n }\n };\n TreeView.prototype.templateComplier = function (template) {\n if (template) {\n var e = void 0;\n try {\n if (document.querySelectorAll(template).length) {\n return compile(document.querySelector(template).innerHTML.trim());\n }\n }\n catch (e) {\n return compile(template);\n }\n }\n return undefined;\n };\n TreeView.prototype.setDataBinding = function () {\n var _this = this;\n this.treeList.push('false');\n if (this.fields.dataSource instanceof DataManager) {\n this.fields.dataSource.executeQuery(this.getQuery(this.fields)).then(function (e) {\n _this.treeList.pop();\n _this.treeData = e.result;\n _this.isNumberTypeId = _this.getType();\n _this.setRootData();\n _this.renderItems(true);\n if (_this.treeList.length === 0 && !_this.isLoaded) {\n _this.finalize();\n }\n });\n }\n else {\n this.treeList.pop();\n if (isNOU(this.fields.dataSource)) {\n this.rootData = this.treeData = [];\n }\n else {\n this.treeData = this.fields.dataSource;\n this.setRootData();\n }\n this.renderItems(false);\n }\n if (this.treeList.length === 0 && !this.isLoaded) {\n this.finalize();\n }\n };\n TreeView.prototype.getQuery = function (mapper, value) {\n if (value === void 0) { value = null; }\n var columns = [];\n var query;\n if (!mapper.query) {\n query = new Query();\n var prop = this.getActualProperties(mapper);\n for (var _i = 0, _a = Object.keys(prop); _i < _a.length; _i++) {\n var col = _a[_i];\n if (col !== 'dataSource' && col !== 'tableName' && col !== 'child' && !!mapper[col]\n && columns.indexOf(mapper[col]) === -1) {\n columns.push(mapper[col]);\n }\n }\n query.select(columns);\n if (prop.hasOwnProperty('tableName')) {\n query.from(mapper.tableName);\n }\n }\n else {\n query = mapper.query.clone();\n }\n ListBase.addSorting(this.sortOrder, mapper.text, query);\n if (!isNOU(value) && !isNOU(mapper.parentID)) {\n query.where(mapper.parentID, 'equal', (this.isNumberTypeId ? parseFloat(value) : value));\n }\n return query;\n };\n TreeView.prototype.getType = function () {\n return this.treeData[0] ? ((typeof getValue(this.fields.id, this.treeData[0]) === 'number') ? true : false) : false;\n };\n TreeView.prototype.setRootData = function () {\n this.dataType = this.getDataType(this.treeData, this.fields);\n if (this.dataType === 1) {\n this.groupedData = this.getGroupedData(this.treeData, this.fields.parentID);\n var rootItems = this.getChildNodes(this.treeData, undefined, true);\n if (isNOU(rootItems)) {\n this.rootData = [];\n }\n else {\n this.rootData = rootItems;\n }\n }\n else {\n this.rootData = this.treeData;\n }\n };\n TreeView.prototype.renderItems = function (isSorted) {\n this.listBaseOption.ariaAttributes.level = 1;\n this.ulElement = ListBase.createList(this.createElement, isSorted ? this.rootData : this.getSortedData(this.rootData), this.listBaseOption);\n this.element.appendChild(this.ulElement);\n this.finalizeNode(this.element);\n };\n TreeView.prototype.beforeNodeCreate = function (e) {\n if (this.showCheckBox) {\n var checkboxEle = createCheckBox(this.createElement, true, { cssClass: this.touchClass });\n var icon = select('div.' + ICON, e.item);\n var id = e.item.getAttribute('data-uid');\n e.item.childNodes[0].insertBefore(checkboxEle, e.item.childNodes[0].childNodes[isNOU(icon) ? 0 : 1]);\n var checkValue = getValue(e.fields.isChecked, e.curData);\n if (this.checkedNodes.indexOf(id) > -1) {\n select('.' + CHECKBOXFRAME, checkboxEle).classList.add(CHECK);\n checkboxEle.setAttribute('aria-checked', 'true');\n this.addCheck(e.item);\n }\n else if (!isNOU(checkValue) && checkValue.toString() === 'true') {\n select('.' + CHECKBOXFRAME, checkboxEle).classList.add(CHECK);\n checkboxEle.setAttribute('aria-checked', 'true');\n this.addCheck(e.item);\n }\n else {\n checkboxEle.setAttribute('aria-checked', 'false');\n }\n var frame = select('.' + CHECKBOXFRAME, checkboxEle);\n EventHandler.add(frame, 'mousedown', this.frameMouseHandler, this);\n EventHandler.add(frame, 'mouseup', this.frameMouseHandler, this);\n }\n if (this.fullRowSelect) {\n this.createFullRow(e.item);\n }\n if (this.allowMultiSelection && !e.item.classList.contains(SELECTED)) {\n e.item.setAttribute('aria-selected', 'false');\n }\n var fields = e.fields;\n this.addActionClass(e, fields.selected, SELECTED);\n this.addActionClass(e, fields.expanded, EXPANDED);\n if (!isNOU(this.nodeTemplateFn)) {\n var textEle = e.item.querySelector('.' + LISTTEXT);\n textEle.innerHTML = '';\n append(this.nodeTemplateFn(e.curData), textEle);\n }\n var eventArgs = {\n node: e.item,\n nodeData: e.curData,\n text: e.text,\n };\n this.trigger('drawNode', eventArgs);\n };\n TreeView.prototype.frameMouseHandler = function (e) {\n var rippleSpan = select('.' + CHECKBOXRIPPLE, e.target.parentElement);\n rippleMouseHandler(e, rippleSpan);\n };\n TreeView.prototype.addActionClass = function (e, action, cssClass) {\n var data = e.curData;\n var actionValue = getValue(action, data);\n if (!isNOU(actionValue) && actionValue.toString() !== 'false') {\n e.item.classList.add(cssClass);\n }\n };\n TreeView.prototype.getDataType = function (ds, mapper) {\n if (this.fields.dataSource instanceof DataManager) {\n for (var i = 0; i < ds.length; i++) {\n if ((typeof mapper.child === 'string') && isNOU(getValue(mapper.child, ds[i]))) {\n return 1;\n }\n }\n return 2;\n }\n for (var i = 0, len = ds.length; i < len; i++) {\n if ((typeof mapper.child === 'string') && !isNOU(getValue(mapper.child, ds[i]))) {\n return 2;\n }\n if (!isNOU(getValue(mapper.parentID, ds[i])) || !isNOU(getValue(mapper.hasChildren, ds[i]))) {\n return 1;\n }\n }\n return 1;\n };\n TreeView.prototype.getGroupedData = function (dataSource, groupBy) {\n var cusQuery = new Query().group(groupBy);\n var ds = ListBase.getDataSource(dataSource, cusQuery);\n var grpItem = [];\n for (var j = 0; j < ds.length; j++) {\n var itemObj = ds[j].items;\n grpItem.push(itemObj);\n }\n return grpItem;\n };\n TreeView.prototype.getSortedData = function (list) {\n if (list && this.sortOrder !== 'None') {\n list = ListBase.getDataSource(list, ListBase.addSorting(this.sortOrder, this.fields.text));\n }\n return list;\n };\n TreeView.prototype.finalizeNode = function (element) {\n var iNodes = selectAll('.' + IMAGE, element);\n for (var k = 0; k < iNodes.length; k++) {\n iNodes[k].setAttribute('alt', IMAGE);\n }\n if (this.isLoaded) {\n var sNodes = selectAll('.' + SELECTED, element);\n for (var i = 0; i < sNodes.length; i++) {\n this.selectNode(sNodes[i], null);\n break;\n }\n removeClass(sNodes, SELECTED);\n }\n var cNodes = selectAll('.' + LISTITEM + ':not(.' + EXPANDED + ')', element);\n for (var j = 0; j < cNodes.length; j++) {\n var icon = select('div.' + ICON, cNodes[j]);\n if (icon && icon.classList.contains(EXPANDABLE)) {\n cNodes[j].setAttribute('aria-expanded', 'false');\n addClass([cNodes[j]], NODECOLLAPSED);\n }\n }\n var eNodes = selectAll('.' + EXPANDED, element);\n for (var i = 0; i < eNodes.length; i++) {\n this.renderChildNodes(eNodes[i]);\n }\n removeClass(eNodes, EXPANDED);\n this.updateList();\n if (this.isLoaded) {\n this.updateCheckedProp();\n }\n };\n TreeView.prototype.updateCheckedProp = function () {\n var _this = this;\n if (this.showCheckBox) {\n var nodes_1 = [].concat([], this.checkedNodes);\n this.checkedNodes.forEach(function (value, index) {\n var checkBox = _this.element.querySelector('[data-uid=\"' + value + '\"]');\n if (isNOU(checkBox)) {\n nodes_1 = nodes_1.filter(function (e) { return e !== value; });\n }\n });\n this.setProperties({ checkedNodes: nodes_1 }, true);\n }\n };\n TreeView.prototype.ensureParentCheckState = function (element) {\n if (!isNOU(element)) {\n if (element.classList.contains(ROOT)) {\n return;\n }\n var ulElement = element;\n if (element.classList.contains(LISTITEM)) {\n ulElement = select('.' + PARENTITEM, element);\n }\n var checkedNodes = selectAll('.' + CHECK, ulElement);\n var nodes = selectAll('.' + LISTITEM, ulElement);\n var checkBoxEle = element.getElementsByClassName(CHECKBOXWRAP)[0];\n if (nodes.length === checkedNodes.length) {\n this.changeState(checkBoxEle, 'check', null, true, true);\n }\n else if (checkedNodes.length > 0) {\n this.changeState(checkBoxEle, 'indeterminate', null, true, true);\n }\n else if (checkedNodes.length === 0) {\n this.changeState(checkBoxEle, 'uncheck', null, true, true);\n }\n var parentUL = closest(element, '.' + PARENTITEM);\n if (!isNOU(parentUL)) {\n var currentParent = closest(parentUL, '.' + LISTITEM);\n this.ensureParentCheckState(currentParent);\n }\n }\n };\n TreeView.prototype.ensureChildCheckState = function (element, e) {\n if (!isNOU(element)) {\n var childElement = select('.' + PARENTITEM, element);\n var checkBoxes = void 0;\n if (!isNOU(childElement)) {\n checkBoxes = selectAll('.' + CHECKBOXWRAP, childElement);\n var isChecked = element.getElementsByClassName(CHECKBOXFRAME)[0].classList.contains(CHECK);\n var checkedState = void 0;\n for (var index = 0; index < checkBoxes.length; index++) {\n if (!isNOU(this.currentLoadData) && !isNOU(getValue(this.fields.isChecked, this.currentLoadData[index]))) {\n checkedState = getValue(this.fields.isChecked, this.currentLoadData[index]) ? 'check' : 'uncheck';\n }\n else {\n var isNodeChecked = checkBoxes[index].getElementsByClassName(CHECKBOXFRAME)[0].classList.contains(CHECK);\n checkedState = (!this.isLoaded && isNodeChecked) ? 'check' : (isChecked ? 'check' : 'uncheck');\n }\n this.changeState(checkBoxes[index], checkedState, e, true, true);\n }\n }\n }\n };\n TreeView.prototype.doCheckBoxAction = function (nodes, doCheck) {\n if (!isNOU(nodes)) {\n for (var i = 0, len = nodes.length; i < len; i++) {\n var liEle = this.getElement(nodes[i]);\n if (isNOU(liEle)) {\n continue;\n }\n var checkBox = select('.' + PARENTITEM + ' .' + CHECKBOXWRAP, liEle);\n this.validateCheckNode(checkBox, !doCheck, liEle, null);\n }\n }\n else {\n var checkBoxes = selectAll('.' + CHECKBOXWRAP, this.element);\n for (var index = 0; index < checkBoxes.length; index++) {\n this.changeState(checkBoxes[index], doCheck ? 'check' : 'uncheck');\n }\n }\n };\n TreeView.prototype.changeState = function (wrapper, state, e, isPrevent, isAdd) {\n var ariaState;\n var eventArgs;\n var currLi = closest(wrapper, '.' + LISTITEM);\n if (!isPrevent) {\n this.checkActionNodes = [];\n eventArgs = this.getCheckEvent(currLi, state, e);\n this.trigger('nodeChecking', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n }\n var frameSpan = wrapper.getElementsByClassName(CHECKBOXFRAME)[0];\n if (state === 'check' && !frameSpan.classList.contains(CHECK)) {\n frameSpan.classList.remove(INDETERMINATE);\n frameSpan.classList.add(CHECK);\n this.addCheck(currLi);\n ariaState = 'true';\n }\n else if (state === 'uncheck' && (frameSpan.classList.contains(CHECK) || frameSpan.classList.contains(INDETERMINATE))) {\n removeClass([frameSpan], [CHECK, INDETERMINATE]);\n this.removeCheck(currLi);\n ariaState = 'false';\n }\n else if (state === 'indeterminate' && !frameSpan.classList.contains(INDETERMINATE)) {\n frameSpan.classList.remove(CHECK);\n frameSpan.classList.add(INDETERMINATE);\n this.removeCheck(currLi);\n ariaState = 'mixed';\n }\n ariaState = state === 'check' ? 'true' : state === 'uncheck' ? 'false' : ariaState;\n if (!isNOU(ariaState)) {\n wrapper.setAttribute('aria-checked', ariaState);\n }\n if (isAdd) {\n var data = [].concat([], this.checkActionNodes);\n eventArgs = this.getCheckEvent(currLi, state, e);\n if (isUndefined(isPrevent)) {\n eventArgs.data = data;\n }\n }\n if (!isPrevent) {\n if (!isNOU(ariaState)) {\n wrapper.setAttribute('aria-checked', ariaState);\n eventArgs.data[0].checked = ariaState;\n this.trigger('nodeChecked', eventArgs);\n this.checkActionNodes = [];\n }\n }\n };\n TreeView.prototype.addCheck = function (liEle) {\n var id = liEle.getAttribute('data-uid');\n if (!isNOU(id) && this.checkedNodes.indexOf(id) === -1) {\n this.checkedNodes.push(id);\n }\n };\n TreeView.prototype.removeCheck = function (liEle) {\n var index = this.checkedNodes.indexOf(liEle.getAttribute('data-uid'));\n if (index > -1) {\n this.checkedNodes.splice(index, 1);\n }\n };\n TreeView.prototype.getCheckEvent = function (currLi, action, e) {\n this.checkActionNodes.push(this.getNodeData(currLi));\n var nodeData = this.checkActionNodes;\n return { action: action, cancel: false, isInteracted: isNOU(e) ? false : true, node: currLi, data: nodeData };\n };\n TreeView.prototype.finalize = function () {\n var firstUl = select('.' + PARENTITEM, this.element);\n firstUl.setAttribute('role', treeAriaAttr.treeRole);\n this.setMultiSelect(this.allowMultiSelection);\n var firstNode = select('.' + LISTITEM, this.element);\n if (firstNode) {\n addClass([firstNode], FOCUS);\n this.updateIdAttr(null, firstNode);\n }\n this.doSelectionAction();\n this.updateCheckedProp();\n this.isLoaded = true;\n this.isAnimate = false;\n var eventArgs = { data: this.treeData };\n this.trigger('dataBound', eventArgs);\n };\n TreeView.prototype.doSelectionAction = function () {\n var sNodes = selectAll('.' + SELECTED, this.element);\n var sUids = this.selectedNodes;\n if (sUids.length > 0) {\n this.setProperties({ selectedNodes: [] }, true);\n for (var i = 0; i < sUids.length; i++) {\n var sNode = select('[data-uid=\"' + sUids[i] + '\"]', this.element);\n this.selectNode(sNode, null, true);\n if (!this.allowMultiSelection) {\n break;\n }\n }\n }\n else {\n this.selectGivenNodes(sNodes);\n }\n removeClass(sNodes, SELECTED);\n };\n TreeView.prototype.selectGivenNodes = function (sNodes) {\n for (var i = 0; i < sNodes.length; i++) {\n if (!sNodes[i].classList.contains('e-disable')) {\n this.selectNode(sNodes[i], null, true);\n }\n if (!this.allowMultiSelection) {\n break;\n }\n }\n };\n TreeView.prototype.clickHandler = function (event) {\n var target = event.originalEvent.target;\n EventHandler.remove(this.element, 'contextmenu', this.preventContextMenu);\n if (!target || this.dragStartAction) {\n return;\n }\n else {\n var classList = target.classList;\n var li = closest(target, '.' + LISTITEM);\n if (!li) {\n return;\n }\n else {\n this.removeHover();\n this.setFocusElement(li);\n if (this.showCheckBox && !li.classList.contains('e-disable')) {\n var checkWrapper = closest(target, '.' + CHECKBOXWRAP);\n if (!isNOU(checkWrapper)) {\n var checkElement = select('.' + CHECKBOXFRAME, checkWrapper);\n this.validateCheckNode(checkWrapper, checkElement.classList.contains(CHECK), li, event.originalEvent);\n this.triggerClickEvent(event.originalEvent, li);\n return;\n }\n }\n if (classList.contains(EXPANDABLE)) {\n this.expandAction(li, target, event);\n }\n else if (classList.contains(COLLAPSIBLE)) {\n this.collapseNode(li, target, event);\n }\n else {\n if (!classList.contains(PARENTITEM) && !classList.contains(LISTITEM)) {\n this.toggleSelect(li, event.originalEvent, false);\n }\n }\n this.triggerClickEvent(event.originalEvent, li);\n }\n }\n };\n TreeView.prototype.nodeCheckingEvent = function (wrapper, isCheck, e) {\n var currLi = closest(wrapper, '.' + LISTITEM);\n this.checkActionNodes = [];\n var ariaState = !isCheck ? 'true' : 'false';\n if (!isNOU(ariaState)) {\n wrapper.setAttribute('aria-checked', ariaState);\n }\n var eventArgs = this.getCheckEvent(currLi, isCheck ? 'uncheck' : 'check', e);\n this.trigger('nodeChecking', eventArgs);\n return eventArgs;\n };\n TreeView.prototype.nodeCheckedEvent = function (wrapper, isCheck, e) {\n var currLi = closest(wrapper, '.' + LISTITEM);\n var eventArgs = this.getCheckEvent(wrapper, isCheck ? 'uncheck' : 'check', e);\n eventArgs.data = eventArgs.data.splice(0, eventArgs.data.length - 1);\n this.trigger('nodeChecked', eventArgs);\n };\n TreeView.prototype.triggerClickEvent = function (e, li) {\n var eventArgs = {\n event: e,\n node: li,\n };\n this.trigger('nodeClicked', eventArgs);\n };\n TreeView.prototype.expandNode = function (currLi, icon) {\n var _this = this;\n if (icon.classList.contains(LOAD)) {\n this.hideSpinner(icon);\n }\n removeClass([icon], EXPANDABLE);\n addClass([icon], COLLAPSIBLE);\n var start = 0;\n var end = 0;\n var proxy = this;\n var ul = select('.' + PARENTITEM, currLi);\n var liEle = currLi;\n this.setHeight(liEle, ul);\n if (!this.isAnimate) {\n this.aniObj.animate(ul, {\n name: this.animation.expand.effect,\n duration: this.animation.expand.duration,\n timingFunction: this.animation.expand.easing,\n begin: function (args) {\n liEle.style.overflow = 'hidden';\n start = liEle.offsetHeight;\n end = select('.' + TEXTWRAP, currLi).offsetHeight;\n },\n progress: function (args) {\n args.element.style.display = 'block';\n proxy.animateHeight(args, start, end);\n },\n end: function (args) {\n args.element.style.display = 'block';\n _this.expandedNode(liEle, ul, icon);\n }\n });\n }\n else {\n this.expandedNode(liEle, ul, icon);\n }\n };\n TreeView.prototype.expandedNode = function (currLi, ul, icon) {\n ul.style.display = 'block';\n currLi.style.display = 'block';\n currLi.style.overflow = '';\n currLi.style.height = '';\n removeClass([icon], PROCESS);\n currLi.setAttribute('aria-expanded', 'true');\n removeClass([currLi], NODECOLLAPSED);\n if (this.isLoaded && this.expandArgs) {\n this.expandArgs = this.getExpandEvent(currLi, null);\n this.trigger('nodeExpanded', this.expandArgs);\n }\n };\n TreeView.prototype.collapseNode = function (currLi, icon, e) {\n var _this = this;\n if (icon.classList.contains(PROCESS)) {\n return;\n }\n else {\n addClass([icon], PROCESS);\n }\n var colArgs;\n if (this.isLoaded) {\n colArgs = this.getExpandEvent(currLi, e);\n this.trigger('nodeCollapsing', colArgs);\n if (colArgs.cancel) {\n removeClass([icon], PROCESS);\n return;\n }\n }\n removeClass([icon], COLLAPSIBLE);\n addClass([icon], EXPANDABLE);\n var start = 0;\n var end = 0;\n var proxy = this;\n var ul = select('.' + PARENTITEM, currLi);\n var liEle = currLi;\n addClass([currLi], NODECOLLAPSED);\n this.aniObj.animate(ul, {\n name: this.animation.collapse.effect,\n duration: this.animation.collapse.duration,\n timingFunction: this.animation.collapse.easing,\n begin: function (args) {\n liEle.style.overflow = 'hidden';\n start = select('.' + TEXTWRAP, currLi).offsetHeight;\n end = liEle.offsetHeight;\n },\n progress: function (args) {\n proxy.animateHeight(args, start, end);\n },\n end: function (args) {\n liEle.style.overflow = '';\n args.element.style.display = 'none';\n liEle.style.height = '';\n removeClass([icon], PROCESS);\n currLi.setAttribute('aria-expanded', 'false');\n if (_this.isLoaded) {\n _this.trigger('nodeCollapsed', colArgs);\n }\n }\n });\n };\n TreeView.prototype.setHeight = function (currLi, ul) {\n ul.style.display = 'block';\n ul.style.visibility = 'hidden';\n currLi.style.height = currLi.offsetHeight + 'px';\n ul.style.display = 'none';\n ul.style.visibility = '';\n };\n TreeView.prototype.animateHeight = function (args, start, end) {\n var remaining = (args.duration - args.timeStamp) / args.duration;\n var currentHeight = (end - start) * remaining + start;\n args.element.parentElement.style.height = currentHeight + 'px';\n };\n TreeView.prototype.renderChildNodes = function (parentLi, expandChild) {\n var _this = this;\n var eicon = select('div.' + ICON, parentLi);\n if (isNOU(eicon)) {\n return;\n }\n this.showSpinner(eicon);\n var childItems;\n if (this.fields.dataSource instanceof DataManager) {\n var level = this.parents(parentLi, '.' + PARENTITEM).length;\n var mapper_1 = this.getChildFields(this.fields, level, 1);\n if (isNOU(mapper_1) || isNOU(mapper_1.dataSource)) {\n detach(eicon);\n parentLi.removeAttribute('aria-expanded');\n return;\n }\n this.treeList.push('false');\n mapper_1.dataSource.executeQuery(this.getQuery(mapper_1, parentLi.getAttribute('data-uid'))).then(function (e) {\n _this.treeList.pop();\n childItems = e.result;\n _this.currentLoadData = childItems;\n if (isNOU(childItems) || childItems.length === 0) {\n detach(eicon);\n parentLi.removeAttribute('aria-expanded');\n }\n else {\n _this.updateListProp(mapper_1);\n var id = parentLi.getAttribute('data-uid');\n var nodeData = _this.getNodeObject(id);\n setValue('child', childItems, nodeData);\n _this.listBaseOption.ariaAttributes.level = parseFloat(parentLi.getAttribute('aria-level')) + 1;\n parentLi.appendChild(ListBase.createList(_this.createElement, childItems, _this.listBaseOption));\n _this.expandNode(parentLi, eicon);\n _this.ensureCheckNode(parentLi);\n _this.finalizeNode(parentLi);\n _this.renderSubChild(parentLi, expandChild);\n }\n if (_this.treeList.length === 0 && !_this.isLoaded) {\n _this.finalize();\n }\n });\n }\n else {\n childItems = this.getChildNodes(this.treeData, parentLi.getAttribute('data-uid'));\n this.currentLoadData = childItems;\n if (isNOU(childItems) || childItems.length === 0) {\n detach(eicon);\n parentLi.removeAttribute('aria-expanded');\n return;\n }\n else {\n this.listBaseOption.ariaAttributes.level = parseFloat(parentLi.getAttribute('aria-level')) + 1;\n parentLi.appendChild(ListBase.createList(this.createElement, this.getSortedData(childItems), this.listBaseOption));\n this.expandNode(parentLi, eicon);\n this.ensureCheckNode(parentLi);\n this.finalizeNode(parentLi);\n this.renderSubChild(parentLi, expandChild);\n }\n }\n };\n TreeView.prototype.ensureCheckNode = function (element) {\n if (this.showCheckBox) {\n this.ensureChildCheckState(element);\n this.ensureParentCheckState(element);\n }\n this.currentLoadData = null;\n };\n TreeView.prototype.getFields = function (mapper, nodeLevel, dataLevel) {\n if (nodeLevel === dataLevel) {\n return mapper;\n }\n else {\n return this.getFields(this.getChildMapper(mapper), nodeLevel, dataLevel + 1);\n }\n };\n TreeView.prototype.getChildFields = function (mapper, nodeLevel, dataLevel) {\n var childData;\n if (nodeLevel === dataLevel) {\n return this.getChildMapper(mapper);\n }\n else {\n return this.getChildFields(this.getChildMapper(mapper), nodeLevel, dataLevel + 1);\n }\n };\n TreeView.prototype.getChildMapper = function (mapper) {\n return (typeof mapper.child === 'string' || isNOU(mapper.child)) ? mapper : mapper.child;\n };\n TreeView.prototype.getChildNodes = function (obj, parentId, isRoot) {\n if (isRoot === void 0) { isRoot = false; }\n var childNodes;\n if (isNOU(obj)) {\n return childNodes;\n }\n else if (this.dataType === 1) {\n return this.getChildGroup(this.groupedData, parentId, isRoot);\n }\n else {\n if (typeof this.fields.child === 'string') {\n for (var i = 0, objlen = obj.length; i < objlen; i++) {\n var dataId = getValue(this.fields.id, obj[i]);\n if (dataId && dataId.toString() === parentId) {\n return getValue(this.fields.child, obj[i]);\n }\n else if (!isNOU(getValue(this.fields.child, obj[i]))) {\n childNodes = this.getChildNodes(getValue(this.fields.child, obj[i]), parentId);\n if (childNodes !== undefined) {\n break;\n }\n }\n }\n }\n }\n return childNodes;\n };\n TreeView.prototype.getChildGroup = function (data, parentId, isRoot) {\n var childNodes;\n if (isNOU(data)) {\n return childNodes;\n }\n for (var i = 0, objlen = data.length; i < objlen; i++) {\n if (!isNOU(data[i][0]) && !isNOU(getValue(this.fields.parentID, data[i][0]))) {\n if (getValue(this.fields.parentID, data[i][0]).toString() === parentId) {\n return data[i];\n }\n }\n else if (isRoot) {\n return data[i];\n }\n else {\n return [];\n }\n }\n return childNodes;\n };\n TreeView.prototype.renderSubChild = function (element, expandChild) {\n if (expandChild) {\n var cIcons = selectAll('.' + EXPANDABLE, element);\n for (var i = 0, len = cIcons.length; i < len; i++) {\n var icon = cIcons[i];\n var curLi = closest(icon, '.' + LISTITEM);\n this.expandArgs = this.getExpandEvent(curLi, null);\n this.trigger('nodeExpanding', this.expandArgs);\n this.renderChildNodes(curLi, expandChild);\n }\n }\n };\n TreeView.prototype.toggleSelect = function (li, e, multiSelect) {\n if (!li.classList.contains('e-disable')) {\n if (this.allowMultiSelection && ((e && e.ctrlKey) || multiSelect) && this.isActive(li)) {\n this.unselectNode(li, e);\n }\n else {\n this.selectNode(li, e, multiSelect);\n }\n }\n };\n TreeView.prototype.isActive = function (li) {\n return li.classList.contains(ACTIVE) ? true : false;\n };\n TreeView.prototype.selectNode = function (li, e, multiSelect) {\n if (isNOU(li) || (!this.allowMultiSelection && this.isActive(li) && !isNOU(e))) {\n this.setFocusElement(li);\n return;\n }\n var eventArgs;\n if (this.isLoaded) {\n eventArgs = this.getSelectEvent(li, 'select', e);\n this.trigger('nodeSelecting', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n }\n if (!this.allowMultiSelection || (!multiSelect && (!e || (e && !e.ctrlKey)))) {\n this.removeSelectAll();\n }\n if (this.allowMultiSelection && e && e.shiftKey) {\n if (!this.startNode) {\n this.startNode = li;\n }\n var startIndex = this.liList.indexOf(this.startNode);\n var endIndex = this.liList.indexOf(li);\n if (startIndex > endIndex) {\n var temp = startIndex;\n startIndex = endIndex;\n endIndex = temp;\n }\n for (var i = startIndex; i <= endIndex; i++) {\n var currNode = this.liList[i];\n if (isVisible(currNode) && !currNode.classList.contains('e-disable')) {\n this.addSelect(currNode);\n }\n }\n }\n else {\n this.startNode = li;\n this.addSelect(li);\n }\n this.setFocusElement(li);\n if (this.isLoaded) {\n this.trigger('nodeSelected', eventArgs);\n }\n };\n TreeView.prototype.unselectNode = function (li, e) {\n var eventArgs;\n if (this.isLoaded) {\n eventArgs = this.getSelectEvent(li, 'un-select', e);\n this.trigger('nodeSelecting', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n }\n this.removeSelect(li);\n this.setFocusElement(li);\n if (this.isLoaded) {\n this.trigger('nodeSelected', eventArgs);\n }\n };\n TreeView.prototype.setFocusElement = function (li) {\n if (!isNOU(li)) {\n var focusedNode = this.getFocusedNode();\n if (focusedNode) {\n removeClass([focusedNode], FOCUS);\n }\n addClass([li], FOCUS);\n this.updateIdAttr(focusedNode, li);\n }\n };\n TreeView.prototype.addSelect = function (liEle) {\n liEle.setAttribute('aria-selected', 'true');\n addClass([liEle], ACTIVE);\n var id = liEle.getAttribute('data-uid');\n if (!isNOU(id) && this.selectedNodes.indexOf(id) === -1) {\n this.selectedNodes.push(id);\n }\n };\n TreeView.prototype.removeSelect = function (liEle) {\n if (this.allowMultiSelection) {\n liEle.setAttribute('aria-selected', 'false');\n }\n else {\n liEle.removeAttribute('aria-selected');\n }\n removeClass([liEle], ACTIVE);\n var index = this.selectedNodes.indexOf(liEle.getAttribute('data-uid'));\n if (index > -1) {\n this.selectedNodes.splice(index, 1);\n }\n };\n TreeView.prototype.removeSelectAll = function () {\n var selectedLI = this.element.querySelectorAll('.' + ACTIVE);\n for (var _i = 0, selectedLI_1 = selectedLI; _i < selectedLI_1.length; _i++) {\n var ele = selectedLI_1[_i];\n if (this.allowMultiSelection) {\n ele.setAttribute('aria-selected', 'false');\n }\n else {\n ele.removeAttribute('aria-selected');\n }\n }\n removeClass(selectedLI, ACTIVE);\n this.setProperties({ selectedNodes: [] }, true);\n };\n TreeView.prototype.getSelectEvent = function (currLi, action, e) {\n var nodeData = this.getNodeData(currLi);\n return { action: action, cancel: false, isInteracted: isNOU(e) ? false : true, node: currLi, nodeData: nodeData };\n };\n TreeView.prototype.setExpandOnType = function () {\n this.expandOnType = (this.expandOn === 'Auto') ? (Browser.isDevice ? 'Click' : 'DblClick') : this.expandOn;\n };\n TreeView.prototype.expandHandler = function (e) {\n var target = e.originalEvent.target;\n if (!target || target.classList.contains(INPUT) || target.classList.contains(ROOT) ||\n target.classList.contains(PARENTITEM) || target.classList.contains(LISTITEM) ||\n target.classList.contains(ICON) || this.showCheckBox && closest(target, '.' + CHECKBOXWRAP)) {\n return;\n }\n else {\n this.expandCollapseAction(closest(target, '.' + LISTITEM), e);\n }\n };\n TreeView.prototype.expandCollapseAction = function (currLi, e) {\n var icon = select('div.' + ICON, currLi);\n if (!icon || icon.classList.contains(PROCESS)) {\n return;\n }\n else {\n var classList = icon.classList;\n if (classList.contains(EXPANDABLE)) {\n this.expandAction(currLi, icon, e);\n }\n else {\n this.collapseNode(currLi, icon, e);\n }\n }\n };\n TreeView.prototype.expandAction = function (currLi, icon, e, expandChild) {\n if (icon.classList.contains(PROCESS)) {\n return;\n }\n else {\n addClass([icon], PROCESS);\n }\n if (this.isLoaded) {\n this.expandArgs = this.getExpandEvent(currLi, e);\n this.trigger('nodeExpanding', this.expandArgs);\n if (this.expandArgs.cancel) {\n removeClass([icon], PROCESS);\n return;\n }\n }\n var ul = select('.' + PARENTITEM, currLi);\n if (ul && ul.nodeName === 'UL') {\n this.expandNode(currLi, icon);\n }\n else {\n this.renderChildNodes(currLi, expandChild);\n }\n };\n TreeView.prototype.keyActionHandler = function (e) {\n var target = e.target;\n var focusedNode = this.getFocusedNode();\n if (target && target.classList.contains(INPUT)) {\n var inpEle = target;\n if (e.action === 'enter') {\n inpEle.blur();\n this.element.focus();\n addClass([focusedNode], HOVER);\n }\n else if (e.action === 'escape') {\n inpEle.value = this.oldText;\n inpEle.blur();\n this.element.focus();\n addClass([focusedNode], HOVER);\n }\n return;\n }\n e.preventDefault();\n var eventArgs = {\n cancel: false,\n event: e,\n node: focusedNode,\n };\n this.trigger('keyPress', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n switch (e.action) {\n case 'space':\n if (this.showCheckBox) {\n this.checkNode(e);\n }\n break;\n case 'moveRight':\n this.openNode(this.enableRtl ? false : true, e);\n break;\n case 'moveLeft':\n this.openNode(this.enableRtl ? true : false, e);\n break;\n case 'shiftDown':\n this.shiftKeySelect(true, e);\n break;\n case 'moveDown':\n case 'ctrlDown':\n case 'csDown':\n this.navigateNode(true);\n break;\n case 'shiftUp':\n this.shiftKeySelect(false, e);\n break;\n case 'moveUp':\n case 'ctrlUp':\n case 'csUp':\n this.navigateNode(false);\n break;\n case 'home':\n case 'shiftHome':\n case 'ctrlHome':\n case 'csHome':\n this.navigateRootNode(true);\n break;\n case 'end':\n case 'shiftEnd':\n case 'ctrlEnd':\n case 'csEnd':\n this.navigateRootNode(false);\n break;\n case 'enter':\n case 'ctrlEnter':\n case 'shiftEnter':\n case 'csEnter':\n this.toggleSelect(focusedNode, e);\n break;\n case 'f2':\n if (this.allowEditing && !focusedNode.classList.contains('e-disable')) {\n this.createTextbox(focusedNode, e);\n }\n break;\n case 'ctrlA':\n if (this.allowMultiSelection) {\n var sNodes = selectAll('.' + LISTITEM + ':not(.' + ACTIVE + ')', this.element);\n this.selectGivenNodes(sNodes);\n }\n break;\n }\n };\n TreeView.prototype.navigateToFocus = function (isUp) {\n var focusNode = this.getFocusedNode().querySelector('.' + TEXTWRAP);\n var pos = focusNode.getBoundingClientRect();\n var parent = this.getScrollParent(this.element);\n if (!isNOU(parent)) {\n var parentPos = parent.getBoundingClientRect();\n if (pos.bottom > parentPos.bottom) {\n parent.scrollTop += pos.bottom - parentPos.bottom;\n }\n else if (pos.top < parentPos.top) {\n parent.scrollTop -= parentPos.top - pos.top;\n }\n }\n var isVisible = this.isVisibleInViewport(focusNode);\n if (!isVisible) {\n focusNode.scrollIntoView(isUp);\n }\n };\n TreeView.prototype.isVisibleInViewport = function (txtWrap) {\n var pos = txtWrap.getBoundingClientRect();\n return (pos.top >= 0 && pos.left >= 0 && pos.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&\n pos.right <= (window.innerWidth || document.documentElement.clientWidth));\n };\n TreeView.prototype.getScrollParent = function (node) {\n if (isNOU(node)) {\n return null;\n }\n return (node.scrollHeight > node.clientHeight) ? node : this.getScrollParent(node.parentElement);\n };\n TreeView.prototype.shiftKeySelect = function (isTowards, e) {\n if (this.allowMultiSelection) {\n var focusedNode = this.getFocusedNode();\n var nextNode = isTowards ? this.getNextNode(focusedNode) : this.getPrevNode(focusedNode);\n this.removeHover();\n this.setFocusElement(nextNode);\n this.toggleSelect(nextNode, e, false);\n this.navigateToFocus(!isTowards);\n }\n else {\n this.navigateNode(isTowards);\n }\n };\n TreeView.prototype.checkNode = function (e) {\n var focusedNode = this.getFocusedNode();\n var checkWrap = select('.' + CHECKBOXWRAP, focusedNode);\n var isChecked = select(' .' + CHECKBOXFRAME, checkWrap).classList.contains(CHECK);\n if (!focusedNode.classList.contains('e-disable')) {\n this.validateCheckNode(checkWrap, isChecked, focusedNode, e);\n }\n };\n TreeView.prototype.validateCheckNode = function (checkWrap, isCheck, li, e) {\n var eventArgs = this.nodeCheckingEvent(checkWrap, isCheck, e);\n if (eventArgs.cancel) {\n return;\n }\n this.changeState(checkWrap, isCheck ? 'uncheck' : 'check', e, true);\n this.ensureChildCheckState(li);\n this.ensureParentCheckState(closest(closest(li, '.' + PARENTITEM), '.' + LISTITEM));\n this.nodeCheckedEvent(checkWrap, isCheck, e);\n };\n TreeView.prototype.openNode = function (toBeOpened, e) {\n var focusedNode = this.getFocusedNode();\n var icon = select('div.' + ICON, focusedNode);\n if (toBeOpened) {\n if (!icon) {\n return;\n }\n else if (icon.classList.contains(EXPANDABLE)) {\n this.expandAction(focusedNode, icon, e);\n }\n else {\n this.focusNextNode(focusedNode, true);\n }\n }\n else {\n if (icon && icon.classList.contains(COLLAPSIBLE)) {\n this.collapseNode(focusedNode, icon, e);\n }\n else {\n var parentLi = closest(closest(focusedNode, '.' + PARENTITEM), '.' + LISTITEM);\n if (!parentLi) {\n return;\n }\n else {\n if (!parentLi.classList.contains('e-disable')) {\n this.setFocus(focusedNode, parentLi);\n this.navigateToFocus(true);\n }\n }\n }\n }\n };\n TreeView.prototype.navigateNode = function (isTowards) {\n var focusedNode = this.getFocusedNode();\n this.focusNextNode(focusedNode, isTowards);\n };\n TreeView.prototype.navigateRootNode = function (isBackwards) {\n var focusedNode = this.getFocusedNode();\n var rootNode = isBackwards ? this.getRootNode() : this.getEndNode();\n if (!rootNode.classList.contains('e-disable')) {\n this.setFocus(focusedNode, rootNode);\n this.navigateToFocus(isBackwards);\n }\n };\n TreeView.prototype.getFocusedNode = function () {\n var selectedItem;\n var fNode = select('.' + LISTITEM + '.' + FOCUS, this.element);\n if (isNOU(fNode)) {\n selectedItem = select('.' + LISTITEM, this.element);\n }\n return isNOU(fNode) ? (isNOU(selectedItem) ? this.element.firstElementChild : selectedItem) : fNode;\n };\n TreeView.prototype.focusNextNode = function (li, isTowards) {\n var nextNode = isTowards ? this.getNextNode(li) : this.getPrevNode(li);\n this.setFocus(li, nextNode);\n this.navigateToFocus(!isTowards);\n if (nextNode.classList.contains('e-disable')) {\n var lastChild = nextNode.lastChild;\n if (nextNode.previousSibling == null && nextNode.classList.contains('e-level-1')) {\n this.focusNextNode(nextNode, true);\n }\n else if (nextNode.nextSibling == null && nextNode.classList.contains('e-node-collapsed')) {\n this.focusNextNode(nextNode, false);\n }\n else if (nextNode.nextSibling == null && lastChild.classList.contains('e-text-content')) {\n this.focusNextNode(nextNode, false);\n }\n else {\n this.focusNextNode(nextNode, isTowards);\n }\n }\n };\n TreeView.prototype.getNextNode = function (li) {\n var index = this.liList.indexOf(li);\n var nextNode;\n do {\n index++;\n nextNode = this.liList[index];\n if (isNOU(nextNode)) {\n return li;\n }\n } while (!isVisible(nextNode));\n return nextNode;\n };\n TreeView.prototype.getPrevNode = function (li) {\n var index = this.liList.indexOf(li);\n var prevNode;\n do {\n index--;\n prevNode = this.liList[index];\n if (isNOU(prevNode)) {\n return li;\n }\n } while (!isVisible(prevNode));\n return prevNode;\n };\n TreeView.prototype.getRootNode = function () {\n var index = 0;\n var rootNode;\n do {\n rootNode = this.liList[index];\n index++;\n } while (!isVisible(rootNode));\n return rootNode;\n };\n TreeView.prototype.getEndNode = function () {\n var index = this.liList.length - 1;\n var endNode;\n do {\n endNode = this.liList[index];\n index--;\n } while (!isVisible(endNode));\n return endNode;\n };\n TreeView.prototype.setFocus = function (preNode, nextNode) {\n removeClass([preNode], [HOVER, FOCUS]);\n if (!nextNode.classList.contains('e-disable')) {\n addClass([nextNode], [HOVER, FOCUS]);\n this.updateIdAttr(preNode, nextNode);\n }\n };\n TreeView.prototype.updateIdAttr = function (preNode, nextNode) {\n this.element.removeAttribute('aria-activedescendant');\n if (preNode) {\n preNode.removeAttribute('id');\n }\n nextNode.setAttribute('id', this.element.id + '_active');\n this.element.setAttribute('aria-activedescendant', this.element.id + '_active');\n };\n TreeView.prototype.focusIn = function () {\n if (!this.mouseDownStatus) {\n addClass([this.getFocusedNode()], HOVER);\n }\n this.mouseDownStatus = false;\n };\n TreeView.prototype.focusOut = function () {\n removeClass([this.getFocusedNode()], HOVER);\n };\n TreeView.prototype.onMouseOver = function (e) {\n var target = e.target;\n var classList = target.classList;\n var currentLi = closest(target, '.' + LISTITEM);\n if (!currentLi || classList.contains(PARENTITEM) || classList.contains(LISTITEM)) {\n this.removeHover();\n return;\n }\n else {\n if (currentLi && !currentLi.classList.contains('e-disable')) {\n this.setHover(currentLi);\n }\n }\n };\n TreeView.prototype.setHover = function (li) {\n if (!li.classList.contains(HOVER)) {\n this.removeHover();\n addClass([li], HOVER);\n }\n };\n ;\n TreeView.prototype.onMouseLeave = function (e) {\n this.removeHover();\n };\n TreeView.prototype.removeHover = function () {\n var hoveredNode = selectAll('.' + HOVER, this.element);\n if (hoveredNode && hoveredNode.length) {\n removeClass(hoveredNode, HOVER);\n }\n };\n ;\n TreeView.prototype.getNodeData = function (currLi, fromDS) {\n if (!isNOU(currLi) && currLi.classList.contains(LISTITEM) && closest(currLi, '.' + CONTROL).classList.contains(ROOT)) {\n var id = currLi.getAttribute('data-uid');\n var text = this.getText(currLi, fromDS);\n var pNode = closest(currLi.parentNode, '.' + LISTITEM);\n var pid = pNode ? pNode.getAttribute('data-uid') : null;\n var selected = currLi.classList.contains(ACTIVE);\n var expanded = (currLi.getAttribute('aria-expanded') === 'true') ? true : false;\n var checked = null;\n if (this.showCheckBox) {\n checked = select('.' + CHECKBOXWRAP, currLi).getAttribute('aria-checked');\n }\n return { id: id, text: text, parentID: pid, selected: selected, expanded: expanded, isChecked: checked };\n }\n return { id: '', text: '', parentID: '', selected: '', expanded: '', isChecked: '' };\n };\n TreeView.prototype.getText = function (currLi, fromDS) {\n if (fromDS) {\n var nodeData = this.getNodeObject(currLi.getAttribute('data-uid'));\n var level = parseFloat(currLi.getAttribute('aria-level'));\n var nodeFields = this.getFields(this.fields, level, 1);\n return getValue(nodeFields.text, nodeData);\n }\n return select('.' + LISTTEXT, currLi).textContent;\n };\n TreeView.prototype.getExpandEvent = function (currLi, e) {\n var nodeData = this.getNodeData(currLi);\n return { cancel: false, isInteracted: isNOU(e) ? false : true, node: currLi, nodeData: nodeData, event: e };\n };\n TreeView.prototype.reRenderNodes = function () {\n this.element.innerHTML = '';\n this.setTouchClass();\n this.setProperties({ selectedNodes: [], checkedNodes: [] }, true);\n this.isLoaded = false;\n this.setDataBinding();\n };\n TreeView.prototype.setCssClass = function (oldClass, newClass) {\n if (!isNOU(oldClass) && oldClass !== '') {\n removeClass([this.element], oldClass.split(' '));\n }\n if (!isNOU(newClass) && newClass !== '') {\n addClass([this.element], newClass.split(' '));\n }\n };\n TreeView.prototype.editingHandler = function (e) {\n var target = e.target;\n if (!target || target.classList.contains(ROOT) || target.classList.contains(PARENTITEM) ||\n target.classList.contains(LISTITEM) || target.classList.contains(ICON) ||\n target.classList.contains(INPUT) || target.classList.contains(INPUTGROUP)) {\n return;\n }\n else {\n var liEle = closest(target, '.' + LISTITEM);\n this.createTextbox(liEle, e);\n }\n };\n TreeView.prototype.createTextbox = function (liEle, e) {\n var oldInpEle = select('.' + TREEINPUT, this.element);\n if (oldInpEle) {\n oldInpEle.blur();\n }\n var textEle = select('.' + LISTTEXT, liEle);\n this.updateOldText(liEle);\n var innerEle = this.createElement('input', { className: TREEINPUT, attrs: { value: this.oldText } });\n var eventArgs = this.getEditEvent(liEle, null, innerEle.outerHTML);\n this.trigger('nodeEditing', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n var inpWidth = textEle.offsetWidth + 5;\n var style = 'width:' + inpWidth + 'px';\n addClass([liEle], EDITING);\n textEle.innerHTML = eventArgs.innerHtml;\n var inpEle = select('.' + TREEINPUT, textEle);\n this.inputObj = Input.createInput({\n element: inpEle,\n properties: {\n enableRtl: this.enableRtl,\n }\n }, this.createElement);\n this.inputObj.container.setAttribute('style', style);\n inpEle.focus();\n var inputEle = inpEle;\n inputEle.setSelectionRange(0, inputEle.value.length);\n this.wireInputEvents(inpEle);\n };\n TreeView.prototype.updateOldText = function (liEle) {\n var id = liEle.getAttribute('data-uid');\n this.editData = this.getNodeObject(id);\n var level = parseFloat(liEle.getAttribute('aria-level'));\n this.editFields = this.getFields(this.fields, level, 1);\n this.oldText = getValue(this.editFields.text, this.editData);\n };\n TreeView.prototype.inputFocusOut = function (e) {\n if (!select('.' + TREEINPUT, this.element)) {\n return;\n }\n var target = e.target;\n var newText = target.value;\n var txtEle = closest(target, '.' + LISTTEXT);\n var liEle = closest(target, '.' + LISTITEM);\n detach(this.inputObj.container);\n this.appendNewText(liEle, txtEle, newText, true);\n };\n TreeView.prototype.appendNewText = function (liEle, txtEle, newText, isInput) {\n var eventArgs = this.getEditEvent(liEle, newText, null);\n this.trigger('nodeEdited', eventArgs);\n newText = eventArgs.cancel ? eventArgs.oldText : eventArgs.newText;\n var newData = setValue(this.editFields.text, newText, this.editData);\n if (!isNOU(this.nodeTemplateFn)) {\n txtEle.innerHTML = '';\n append(this.nodeTemplateFn(newData), txtEle);\n }\n else {\n txtEle.innerHTML = newText;\n }\n if (isInput) {\n removeClass([liEle], EDITING);\n txtEle.focus();\n }\n };\n TreeView.prototype.getElement = function (ele) {\n if (isNOU(ele)) {\n return null;\n }\n else if (typeof ele === 'string') {\n return this.element.querySelector('[data-uid=\"' + ele + '\"]');\n }\n else if (typeof ele === 'object') {\n return ele;\n }\n else {\n return null;\n }\n };\n TreeView.prototype.getEditEvent = function (liEle, newText, inpEle) {\n var data = this.getNodeData(liEle);\n return { cancel: false, newText: newText, node: liEle, nodeData: data, oldText: this.oldText, innerHtml: inpEle };\n };\n TreeView.prototype.getNodeObject = function (id) {\n var childNodes;\n if (isNOU(id)) {\n return childNodes;\n }\n else if (this.dataType === 1) {\n for (var i = 0, objlen = this.treeData.length; i < objlen; i++) {\n var dataId = getValue(this.fields.id, this.treeData[i]);\n if (!isNOU(this.treeData[i]) && !isNOU(dataId) && dataId.toString() === id) {\n return this.treeData[i];\n }\n }\n }\n else {\n return this.getChildNodeObject(this.treeData, this.fields, id);\n }\n return childNodes;\n };\n TreeView.prototype.getChildNodeObject = function (obj, mapper, id) {\n var newList;\n if (isNOU(obj)) {\n return newList;\n }\n for (var i = 0, objlen = obj.length; i < objlen; i++) {\n var dataId = getValue(mapper.id, obj[i]);\n if (obj[i] && dataId && dataId.toString() === id) {\n return obj[i];\n }\n else if (typeof mapper.child === 'string' && !isNOU(getValue(mapper.child, obj[i]))) {\n var childData = getValue(mapper.child, obj[i]);\n newList = this.getChildNodeObject(childData, this.getChildMapper(mapper), id);\n if (newList !== undefined) {\n break;\n }\n }\n else if (this.fields.dataSource instanceof DataManager && !isNOU(getValue('child', obj[i]))) {\n var child = 'child';\n newList = this.getChildNodeObject(getValue(child, obj[i]), this.getChildMapper(mapper), id);\n if (newList !== undefined) {\n break;\n }\n }\n }\n return newList;\n };\n TreeView.prototype.setDragAndDrop = function (toBind) {\n if (toBind) {\n this.initializeDrag();\n }\n else {\n this.destroyDrag();\n }\n };\n TreeView.prototype.initializeDrag = function () {\n var _this = this;\n var virtualEle;\n var proxy = this;\n this.dragObj = new Draggable(this.element, {\n enableTailMode: true,\n enableAutoScroll: true,\n dragTarget: '.' + TEXTWRAP,\n helper: function (e) {\n _this.dragTarget = e.sender.target;\n var dragRoot = closest(_this.dragTarget, '.' + ROOT);\n var dragWrap = closest(_this.dragTarget, '.' + TEXTWRAP);\n _this.dragLi = closest(_this.dragTarget, '.' + LISTITEM);\n if (_this.fullRowSelect && !dragWrap && _this.dragTarget.classList.contains(FULLROW)) {\n dragWrap = _this.dragTarget.nextElementSibling;\n }\n if (!_this.dragTarget || !e.element.isSameNode(dragRoot) || !dragWrap ||\n _this.dragTarget.classList.contains(ROOT) || _this.dragTarget.classList.contains(PARENTITEM) ||\n _this.dragTarget.classList.contains(LISTITEM) || _this.dragLi.classList.contains('e-disable')) {\n return false;\n }\n var cloneEle = (dragWrap.cloneNode(true));\n if (isNOU(select('div.' + ICON, cloneEle))) {\n var icon = proxy.createElement('div', { className: ICON + ' ' + EXPANDABLE });\n cloneEle.insertBefore(icon, cloneEle.children[0]);\n }\n var cssClass = DRAGITEM + ' ' + ROOT + ' ' + _this.cssClass + ' ' + (_this.enableRtl ? RTL : '');\n virtualEle = proxy.createElement('div', { className: cssClass });\n virtualEle.appendChild(cloneEle);\n var nLen = _this.selectedNodes.length;\n if (nLen > 1 && _this.allowMultiSelection && _this.dragLi.classList.contains(ACTIVE)) {\n var cNode = proxy.createElement('span', { className: DROPCOUNT, innerHTML: '' + nLen });\n virtualEle.appendChild(cNode);\n }\n document.body.appendChild(virtualEle);\n document.body.style.cursor = '';\n _this.dragData = _this.getNodeData(_this.dragLi);\n return virtualEle;\n },\n dragStart: function (e) {\n addClass([_this.element], DRAGGING);\n var eventArgs = _this.getDragEvent(e.event, _this, null, e.target);\n if (eventArgs.draggedNode.classList.contains(EDITING)) {\n eventArgs.cancel = true;\n }\n else {\n _this.trigger('nodeDragStart', eventArgs);\n }\n if (eventArgs.cancel) {\n detach(virtualEle);\n removeClass([_this.element], DRAGGING);\n _this.dragStartAction = false;\n }\n else {\n _this.dragStartAction = true;\n }\n },\n drag: function (e) {\n _this.dragObj.setProperties({ cursorAt: { top: (!isNOU(e.event.targetTouches) || Browser.isDevice) ? 60 : -20 } });\n _this.dragAction(e, virtualEle);\n },\n dragStop: function (e) {\n removeClass([_this.element], DRAGGING);\n _this.removeVirtualEle();\n var dropTarget = e.target;\n var dropRoot = (closest(dropTarget, '.' + DROPPABLE));\n if (!dropTarget || !dropRoot) {\n detach(e.helper);\n document.body.style.cursor = '';\n }\n var eventArgs = _this.getDragEvent(e.event, _this, dropTarget, dropTarget);\n _this.trigger('nodeDragStop', eventArgs);\n if (eventArgs.cancel) {\n if (e.helper.parentNode) {\n detach(e.helper);\n }\n document.body.style.cursor = '';\n }\n _this.dragStartAction = false;\n }\n });\n this.dropObj = new Droppable(this.element, {\n out: function (e) {\n if (!isNOU(e) && !e.target.classList.contains(SIBLING)) {\n document.body.style.cursor = 'not-allowed';\n }\n },\n over: function (e) {\n document.body.style.cursor = '';\n },\n drop: function (e) {\n _this.dropAction(e);\n }\n });\n };\n TreeView.prototype.dragAction = function (e, virtualEle) {\n var dropRoot = closest(e.target, '.' + DROPPABLE);\n var dropWrap = closest(e.target, '.' + TEXTWRAP);\n var icon = select('div.' + ICON, virtualEle);\n removeClass([icon], [DROPIN, DROPNEXT, DROPOUT, NODROP]);\n this.removeVirtualEle();\n document.body.style.cursor = '';\n var classList = e.target.classList;\n if (this.fullRowSelect && !dropWrap && !isNOU(classList) && classList.contains(FULLROW)) {\n dropWrap = e.target.nextElementSibling;\n }\n if (dropRoot) {\n var dropLi = closest(e.target, '.' + LISTITEM);\n if (!dropRoot.classList.contains(ROOT) || (dropWrap &&\n (!dropLi.isSameNode(this.dragLi) && !this.isDescendant(this.dragLi, dropLi)))) {\n if (dropLi && e && (e.event.offsetY < 7)) {\n addClass([icon], DROPNEXT);\n var virEle = this.createElement('div', { className: SIBLING });\n var index = this.fullRowSelect ? (1) : (0);\n dropLi.insertBefore(virEle, dropLi.children[index]);\n }\n else if (dropLi && e && (e.target.offsetHeight > 0 && e.event.offsetY > (e.target.offsetHeight - 10))) {\n addClass([icon], DROPNEXT);\n var virEle = this.createElement('div', { className: SIBLING });\n var index = this.fullRowSelect ? (2) : (1);\n dropLi.insertBefore(virEle, dropLi.children[index]);\n }\n else {\n addClass([icon], DROPIN);\n }\n }\n else if (e.target.nodeName === 'LI' && (!dropLi.isSameNode(this.dragLi) && !this.isDescendant(this.dragLi, dropLi))) {\n addClass([icon], DROPNEXT);\n this.renderVirtualEle(e);\n }\n else if (e.target.classList.contains(SIBLING)) {\n addClass([icon], DROPNEXT);\n }\n else {\n addClass([icon], DROPOUT);\n }\n }\n else {\n addClass([icon], NODROP);\n document.body.style.cursor = 'not-allowed';\n }\n this.trigger('nodeDragging', this.getDragEvent(e.event, this, e.target, e.target));\n };\n TreeView.prototype.dropAction = function (e) {\n var offsetY = e.event.offsetY;\n var dropTarget = e.target;\n var dragObj;\n var dragInstance = e.dragData.draggable;\n for (var i = 0; i < dragInstance.ej2_instances.length; i++) {\n if (dragInstance.ej2_instances[i] instanceof TreeView_1) {\n dragObj = dragInstance.ej2_instances[i];\n break;\n }\n }\n if (dragObj && dragObj.dragTarget) {\n var dragTarget = dragObj.dragTarget;\n var dragLi = (closest(dragTarget, '.' + LISTITEM));\n var dropLi = (closest(dropTarget, '.' + LISTITEM));\n if (dropLi == null && dropTarget.classList.contains(ROOT)) {\n dropLi = dropTarget.firstElementChild;\n }\n detach(e.droppedElement);\n document.body.style.cursor = '';\n if (!dropLi || dropLi.isSameNode(dragLi) || this.isDescendant(dragLi, dropLi)) {\n return;\n }\n if (dragObj.allowMultiSelection && (dragLi.classList.contains(ACTIVE) || (offsetY < 7 ||\n (e.target.offsetHeight > 0 && offsetY > (e.target.offsetHeight - 10))))) {\n var sNodes = selectAll('.' + ACTIVE, dragObj.element);\n for (var i = 0; i < sNodes.length; i++) {\n if (dropLi.isSameNode(sNodes[i]) || this.isDescendant(sNodes[i], dropLi)) {\n continue;\n }\n this.appendNode(dropTarget, sNodes[i], dropLi, e, dragObj, offsetY);\n }\n }\n else {\n this.appendNode(dropTarget, dragLi, dropLi, e, dragObj, offsetY);\n }\n }\n this.trigger('nodeDropped', this.getDragEvent(e.event, dragObj, dropTarget, e.target, e.dragData.draggedElement));\n };\n TreeView.prototype.appendNode = function (dropTarget, dragLi, dropLi, e, dragObj, offsetY) {\n if (!dragLi.classList.contains('e-disable') && !dropLi.classList.contains('e-disable')) {\n if (dropTarget.nodeName === 'LI') {\n this.dropAsSiblingNode(dragLi, dropLi, e, dragObj);\n }\n else if (dropTarget.firstElementChild && dropTarget.classList.contains(ROOT)) {\n if (dropTarget.firstElementChild.nodeName === 'UL') {\n this.dropAsSiblingNode(dragLi, dropLi, e, dragObj);\n }\n }\n else {\n this.dropAsChildNode(dragLi, dropLi, dragObj, null, e, offsetY);\n }\n }\n };\n TreeView.prototype.dropAsSiblingNode = function (dragLi, dropLi, e, dragObj) {\n var dropUl = closest(dropLi, '.' + PARENTITEM);\n var dragParentUl = closest(dragLi, '.' + PARENTITEM);\n var dragParentLi = closest(dragParentUl, '.' + LISTITEM);\n var pre;\n if (e.target.offsetHeight > 0 && e.event.offsetY > e.target.offsetHeight - 2) {\n pre = false;\n }\n else if (e.event.offsetY < 2) {\n pre = true;\n }\n dropUl.insertBefore(dragLi, pre ? e.target : e.target.nextElementSibling);\n this.updateElement(dragParentUl, dragParentLi);\n this.updateAriaLevel(dragLi);\n if (dragObj.element.id === this.element.id) {\n this.updateList();\n }\n else {\n dragObj.updateInstance();\n this.updateInstance();\n }\n };\n TreeView.prototype.dropAsChildNode = function (dragLi, dropLi, dragObj, index, e, pos) {\n var dragParentUl = closest(dragLi, '.' + PARENTITEM);\n var dragParentLi = closest(dragParentUl, '.' + LISTITEM);\n var dropParentUl = closest(dropLi, '.' + PARENTITEM);\n if (e && (pos < 7)) {\n dropParentUl.insertBefore(dragLi, dropLi);\n }\n else if (e && (e.target.offsetHeight > 0 && pos > (e.target.offsetHeight - 10))) {\n dropParentUl.insertBefore(dragLi, dropLi.nextElementSibling);\n }\n else {\n var dropUl = this.expandParent(dropLi);\n dropUl.insertBefore(dragLi, dropUl.childNodes[index]);\n }\n this.updateElement(dragParentUl, dragParentLi);\n this.updateAriaLevel(dragLi);\n if (dragObj.element.id === this.element.id) {\n this.updateList();\n }\n else {\n dragObj.updateInstance();\n this.updateInstance();\n }\n };\n TreeView.prototype.expandParent = function (dropLi) {\n var dropIcon = select('div.' + ICON, dropLi);\n if (dropIcon && dropIcon.classList.contains(EXPANDABLE)) {\n this.expandAction(dropLi, dropIcon, null);\n }\n var dropUl = select('.' + PARENTITEM, dropLi);\n if (isNOU(dropUl)) {\n this.trigger('nodeExpanding', this.getExpandEvent(dropLi, null));\n if (isNOU(dropIcon)) {\n ListBase.generateIcon(this.createElement, dropLi, COLLAPSIBLE, this.listBaseOption);\n }\n var icon = select('div.' + ICON, dropLi);\n removeClass([icon], EXPANDABLE);\n dropUl = ListBase.generateUL(this.createElement, [], null, this.listBaseOption);\n dropLi.appendChild(dropUl);\n dropLi.setAttribute('aria-expanded', 'true');\n removeClass([dropLi], NODECOLLAPSED);\n this.trigger('nodeExpanded', this.getExpandEvent(dropLi, null));\n }\n return dropUl;\n };\n TreeView.prototype.updateElement = function (dragParentUl, dragParentLi) {\n if (dragParentLi && dragParentUl.childElementCount === 0) {\n var dragIcon = select('div.' + ICON, dragParentLi);\n detach(dragParentUl);\n detach(dragIcon);\n dragParentLi.removeAttribute('aria-expanded');\n }\n };\n TreeView.prototype.updateAriaLevel = function (dragLi) {\n var level = this.parents(dragLi, '.' + PARENTITEM).length;\n dragLi.setAttribute('aria-level', '' + level);\n this.updateChildAriaLevel(select('.' + PARENTITEM, dragLi), level + 1);\n };\n TreeView.prototype.updateChildAriaLevel = function (element, level) {\n if (!isNOU(element)) {\n var cNodes = element.childNodes;\n for (var i = 0, len = cNodes.length; i < len; i++) {\n var liEle = cNodes[i];\n liEle.setAttribute('aria-level', '' + level);\n this.updateChildAriaLevel(select('.' + PARENTITEM, liEle), level + 1);\n }\n }\n };\n TreeView.prototype.renderVirtualEle = function (e) {\n var pre;\n if (e.event.offsetY > e.target.offsetHeight - 2) {\n pre = false;\n }\n else if (e.event.offsetY < 2) {\n pre = true;\n }\n var virEle = this.createElement('div', { className: SIBLING });\n var index = this.fullRowSelect ? (pre ? 1 : 2) : (pre ? 0 : 1);\n e.target.insertBefore(virEle, e.target.children[index]);\n };\n TreeView.prototype.removeVirtualEle = function () {\n var sibEle = select('.' + SIBLING);\n if (sibEle) {\n detach(sibEle);\n }\n };\n TreeView.prototype.destroyDrag = function () {\n if (this.dragObj && this.dropObj) {\n this.dragObj.destroy();\n this.dropObj.destroy();\n }\n };\n TreeView.prototype.getDragEvent = function (event, obj, dropTarget, target, dragNode) {\n var dropLi = dropTarget ? closest(dropTarget, '.' + LISTITEM) : null;\n var dropData = dropLi ? this.getNodeData(dropLi) : null;\n var draggedNode = obj ? obj.dragLi : dragNode;\n var draggedNodeData = obj ? obj.dragData : null;\n var newParent = dropTarget ? this.parents(dropTarget, '.e-list-item') : null;\n var targetParent = null;\n var pre = null;\n if (dropTarget) {\n if (newParent.length === 0) {\n targetParent = null;\n }\n else if (dropTarget.classList.contains('e-list-item')) {\n targetParent = newParent[0];\n }\n else {\n targetParent = newParent[1];\n }\n }\n if (dropTarget && closest(dropTarget, '.e-treeview')) {\n if (event.offsetY <= 5) {\n pre = 'Before';\n }\n else if (target.offsetHeight <= 32 && event.offsetY < target.offsetHeight - 10) {\n pre = 'Child';\n targetParent = closest(dropTarget, '.e-list-item');\n }\n else {\n pre = 'After';\n }\n }\n return {\n cancel: false,\n event: event,\n draggedNode: draggedNode,\n draggedNodeData: draggedNodeData,\n droppedNode: dropLi,\n droppedNodeData: dropData,\n target: target,\n dropTarget: targetParent\n };\n };\n TreeView.prototype.addFullRow = function (toAdd) {\n var len = this.liList.length;\n if (toAdd) {\n for (var i = 0; i < len; i++) {\n this.createFullRow(this.liList[i]);\n }\n }\n else {\n for (var i = 0; i < len; i++) {\n var rowDiv = select('.' + FULLROW, this.liList[i]);\n detach(rowDiv);\n }\n }\n };\n TreeView.prototype.createFullRow = function (item) {\n var rowDiv = this.createElement('div', { className: FULLROW });\n item.insertBefore(rowDiv, item.childNodes[0]);\n };\n TreeView.prototype.addMultiSelect = function (toAdd) {\n if (toAdd) {\n var liEles = selectAll('.' + LISTITEM + ':not([aria-selected=\"true\"])', this.element);\n for (var _i = 0, liEles_1 = liEles; _i < liEles_1.length; _i++) {\n var ele = liEles_1[_i];\n ele.setAttribute('aria-selected', 'false');\n }\n }\n else {\n var liEles = selectAll('.' + LISTITEM + '[aria-selected=\"false\"]', this.element);\n for (var _a = 0, liEles_2 = liEles; _a < liEles_2.length; _a++) {\n var ele = liEles_2[_a];\n ele.removeAttribute('aria-selected');\n }\n }\n };\n TreeView.prototype.collapseByLevel = function (element, level, excludeHiddenNodes) {\n if (level > 0 && !isNOU(element)) {\n var cNodes = this.getVisibleNodes(excludeHiddenNodes, element.childNodes);\n for (var i = 0, len = cNodes.length; i < len; i++) {\n var liEle = cNodes[i];\n var icon = select('.' + COLLAPSIBLE, select('.' + TEXTWRAP, liEle));\n if (!isNOU(icon)) {\n this.collapseNode(liEle, icon, null);\n }\n this.collapseByLevel(select('.' + PARENTITEM, liEle), level - 1, excludeHiddenNodes);\n }\n }\n };\n TreeView.prototype.collapseAllNodes = function (excludeHiddenNodes) {\n var cIcons = this.getVisibleNodes(excludeHiddenNodes, selectAll('.' + COLLAPSIBLE, this.element));\n for (var i = 0, len = cIcons.length; i < len; i++) {\n var icon = cIcons[i];\n var liEle = closest(icon, '.' + LISTITEM);\n this.collapseNode(liEle, icon, null);\n }\n };\n TreeView.prototype.expandByLevel = function (element, level, excludeHiddenNodes) {\n if (level > 0 && !isNOU(element)) {\n var eNodes = this.getVisibleNodes(excludeHiddenNodes, element.childNodes);\n for (var i = 0, len = eNodes.length; i < len; i++) {\n var liEle = eNodes[i];\n var icon = select('.' + EXPANDABLE, select('.' + TEXTWRAP, liEle));\n if (!isNOU(icon)) {\n this.expandAction(liEle, icon, null);\n }\n this.expandByLevel(select('.' + PARENTITEM, liEle), level - 1, excludeHiddenNodes);\n }\n }\n };\n TreeView.prototype.expandAllNodes = function (excludeHiddenNodes) {\n var eIcons = this.getVisibleNodes(excludeHiddenNodes, selectAll('.' + EXPANDABLE, this.element));\n for (var i = 0, len = eIcons.length; i < len; i++) {\n var icon = eIcons[i];\n var liEle = closest(icon, '.' + LISTITEM);\n this.expandAction(liEle, icon, null, true);\n }\n };\n TreeView.prototype.getVisibleNodes = function (excludeHiddenNodes, nodes) {\n var vNodes = Array.prototype.slice.call(nodes);\n if (excludeHiddenNodes) {\n for (var i = 0; i < vNodes.length; i++) {\n if (!isVisible(vNodes[i])) {\n vNodes.splice(i, 1);\n i--;\n }\n }\n }\n return vNodes;\n };\n TreeView.prototype.removeNode = function (node) {\n var dragParentUl = closest(node, '.' + PARENTITEM);\n var dragParentLi = closest(dragParentUl, '.' + LISTITEM);\n detach(node);\n this.updateElement(dragParentUl, dragParentLi);\n this.updateInstance();\n };\n TreeView.prototype.updateInstance = function () {\n this.updateList();\n this.updateSelectedNodes();\n };\n TreeView.prototype.updateList = function () {\n this.liList = Array.prototype.slice.call(selectAll('.' + LISTITEM, this.element));\n };\n TreeView.prototype.updateSelectedNodes = function () {\n this.setProperties({ selectedNodes: [] }, true);\n var sNodes = selectAll('.' + ACTIVE, this.element);\n this.selectGivenNodes(sNodes);\n };\n TreeView.prototype.doGivenAction = function (nodes, selector, toExpand) {\n for (var i = 0, len = nodes.length; i < len; i++) {\n var liEle = this.getElement(nodes[i]);\n if (isNOU(liEle)) {\n continue;\n }\n var icon = select('.' + selector, select('.' + TEXTWRAP, liEle));\n if (!isNOU(icon)) {\n toExpand ? this.expandAction(liEle, icon, null) : this.collapseNode(liEle, icon, null);\n }\n }\n };\n TreeView.prototype.addGivenNodes = function (nodes, dropLi, index, isRemote) {\n var level = dropLi ? parseFloat(dropLi.getAttribute('aria-level')) + 1 : 1;\n if (isRemote) {\n this.updateMapper(level);\n }\n var li = ListBase.createListItemFromJson(this.createElement, nodes, this.listBaseOption, level);\n var dropUl = dropLi ? this.expandParent(dropLi) : select('.' + PARENTITEM, this.element);\n var refNode = dropUl.childNodes[index];\n for (var i = 0; i < li.length; i++) {\n dropUl.insertBefore(li[i], refNode);\n }\n this.finalizeNode(dropUl);\n };\n TreeView.prototype.updateMapper = function (level) {\n var mapper = (level === 1) ? this.fields : this.getChildFields(this.fields, level - 1, 1);\n this.updateListProp(mapper);\n };\n TreeView.prototype.updateListProp = function (mapper) {\n var prop = this.getActualProperties(mapper);\n this.listBaseOption.fields = prop;\n this.listBaseOption.fields.url = prop.hasOwnProperty('navigateUrl') ? prop.navigateUrl : 'navigateUrl';\n };\n TreeView.prototype.doDisableAction = function (nodes) {\n for (var i = 0, len = nodes.length; i < len; i++) {\n var liEle = this.getElement(nodes[i]);\n if (isNOU(liEle)) {\n continue;\n }\n liEle.setAttribute('aria-disabled', 'true');\n addClass([liEle], DISABLE);\n }\n };\n TreeView.prototype.doEnableAction = function (nodes) {\n for (var i = 0, len = nodes.length; i < len; i++) {\n var liEle = this.getElement(nodes[i]);\n if (isNOU(liEle)) {\n continue;\n }\n liEle.removeAttribute('aria-disabled');\n removeClass([liEle], DISABLE);\n }\n };\n TreeView.prototype.setTouchClass = function () {\n var ele = closest(this.element, '.' + BIGGER);\n this.touchClass = isNOU(ele) ? '' : SMALL;\n };\n TreeView.prototype.wireInputEvents = function (inpEle) {\n EventHandler.add(inpEle, 'blur', this.inputFocusOut, this);\n };\n TreeView.prototype.wireEditingEvents = function (toBind) {\n if (toBind) {\n var proxy_1 = this;\n this.touchEditObj = new Touch(this.element, {\n tap: function (e) {\n if (e.tapCount === 2) {\n e.originalEvent.preventDefault();\n proxy_1.editingHandler(e.originalEvent);\n }\n }\n });\n }\n else {\n if (this.touchEditObj) {\n this.touchEditObj.destroy();\n }\n }\n };\n TreeView.prototype.wireClickEvent = function (toBind) {\n if (toBind) {\n var proxy_2 = this;\n this.touchClickObj = new Touch(this.element, {\n tap: function (e) {\n e.originalEvent.preventDefault();\n proxy_2.clickHandler(e);\n }\n });\n }\n else {\n if (this.touchClickObj) {\n this.touchClickObj.destroy();\n }\n }\n };\n TreeView.prototype.wireExpandOnEvent = function (toBind) {\n var _this = this;\n if (toBind) {\n var proxy_3 = this;\n this.touchExpandObj = new Touch(this.element, {\n tap: function (e) {\n if (_this.expandOnType === 'Click' || (_this.expandOnType === 'DblClick' && e.tapCount === 2)) {\n proxy_3.expandHandler(e);\n }\n }\n });\n }\n else {\n if (this.touchExpandObj) {\n this.touchExpandObj.destroy();\n }\n }\n };\n TreeView.prototype.mouseDownHandler = function (e) {\n this.mouseDownStatus = true;\n if (e.shiftKey || e.ctrlKey) {\n e.preventDefault();\n }\n if (e.ctrlKey && this.allowMultiSelection) {\n EventHandler.add(this.element, 'contextmenu', this.preventContextMenu, this);\n }\n };\n ;\n TreeView.prototype.preventContextMenu = function (e) {\n e.preventDefault();\n };\n TreeView.prototype.wireEvents = function () {\n EventHandler.add(this.element, 'mousedown', this.mouseDownHandler, this);\n this.wireClickEvent(true);\n this.wireExpandOnEvent(true);\n EventHandler.add(this.element, 'focus', this.focusIn, this);\n EventHandler.add(this.element, 'blur', this.focusOut, this);\n EventHandler.add(this.element, 'mouseover', this.onMouseOver, this);\n EventHandler.add(this.element, 'mouseout', this.onMouseLeave, this);\n this.keyboardModule = new KeyboardEvents(this.element, {\n keyAction: this.keyActionHandler.bind(this),\n keyConfigs: this.keyConfigs,\n eventName: 'keydown',\n });\n };\n TreeView.prototype.unWireEvents = function () {\n EventHandler.remove(this.element, 'mousedown', this.mouseDownHandler);\n this.wireClickEvent(false);\n this.wireExpandOnEvent(false);\n EventHandler.remove(this.element, 'focus', this.focusIn);\n EventHandler.remove(this.element, 'blur', this.focusOut);\n EventHandler.remove(this.element, 'mouseover', this.onMouseOver);\n EventHandler.remove(this.element, 'mouseout', this.onMouseLeave);\n this.keyboardModule.destroy();\n };\n TreeView.prototype.parents = function (element, selector) {\n var matched = [];\n var el = element.parentNode;\n while (!isNOU(el)) {\n if (matches(el, selector)) {\n matched.push(el);\n }\n el = el.parentNode;\n }\n return matched;\n };\n TreeView.prototype.isDescendant = function (parent, child) {\n var node = child.parentNode;\n while (!isNOU(node)) {\n if (node === parent) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n };\n TreeView.prototype.showSpinner = function (element) {\n addClass([element], LOAD);\n createSpinner({\n target: element,\n width: Browser.isDevice ? 16 : 14\n }, this.createElement);\n showSpinner(element);\n };\n TreeView.prototype.hideSpinner = function (element) {\n hideSpinner(element);\n element.innerHTML = '';\n removeClass([element], LOAD);\n };\n TreeView.prototype.setCheckedNodes = function (nodes) {\n nodes = JSON.parse(JSON.stringify(nodes));\n this.uncheckAll(this.checkedNodes);\n if (nodes.length > 0) {\n this.checkAll(nodes);\n }\n };\n /**\n * Called internally if any of the property value changed.\n * @param {TreeView} newProp\n * @param {TreeView} oldProp\n * @returns void\n * @private\n */\n TreeView.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'allowDragAndDrop':\n this.setDragAndDrop(this.allowDragAndDrop);\n break;\n case 'allowEditing':\n this.wireEditingEvents(this.allowEditing);\n break;\n case 'allowMultiSelection':\n if (this.selectedNodes.length > 1) {\n var sNode = this.getElement(this.selectedNodes[0]);\n this.isLoaded = false;\n this.removeSelectAll();\n this.selectNode(sNode, null);\n this.isLoaded = true;\n }\n this.setMultiSelect(this.allowMultiSelection);\n this.addMultiSelect(this.allowMultiSelection);\n break;\n case 'checkedNodes':\n if (this.showCheckBox) {\n this.checkedNodes = oldProp.checkedNodes;\n this.setCheckedNodes(newProp.checkedNodes);\n }\n break;\n case 'cssClass':\n this.setCssClass(oldProp.cssClass, newProp.cssClass);\n break;\n case 'enableRtl':\n this.setEnableRtl();\n break;\n case 'expandOn':\n this.wireExpandOnEvent(false);\n this.setExpandOnType();\n this.wireExpandOnEvent(true);\n break;\n case 'fields':\n this.updateListProp(this.fields);\n this.reRenderNodes();\n break;\n case 'fullRowSelect':\n this.setFullRow(this.fullRowSelect);\n this.addFullRow(this.fullRowSelect);\n break;\n case 'nodeTemplate':\n this.nodeTemplateFn = this.templateComplier(this.nodeTemplate);\n this.reRenderNodes();\n break;\n case 'selectedNodes':\n this.removeSelectAll();\n this.setProperties({ selectedNodes: newProp.selectedNodes }, true);\n this.doSelectionAction();\n break;\n case 'showCheckBox':\n this.reRenderNodes();\n break;\n case 'sortOrder':\n this.reRenderNodes();\n break;\n }\n }\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers. It also removes the attributes and classes.\n */\n TreeView.prototype.destroy = function () {\n this.element.removeAttribute('aria-activedescendant');\n this.element.removeAttribute('tabindex');\n this.unWireEvents();\n this.wireEditingEvents(false);\n this.rippleFn();\n this.rippleIconFn();\n this.setCssClass(this.cssClass, null);\n this.setDragAndDrop(false);\n this.setFullRow(false);\n this.element.innerHTML = '';\n _super.prototype.destroy.call(this);\n };\n /**\n * Adds the collection of TreeView nodes based on target and index position. If target node is not specified,\n * then the nodes are added as children of the given parentID or in the root level of TreeView.\n * @param { { [key: string]: Object }[] } nodes - Specifies the array of JSON data that has to be added.\n * @param { string | Element } target - Specifies ID of TreeView node/TreeView node as target element.\n * @param { number } index - Specifies the index to place the newly added nodes in the target element.\n */\n TreeView.prototype.addNodes = function (nodes, target, index) {\n if (isNOU(nodes)) {\n return;\n }\n var dropLi = this.getElement(target);\n nodes = this.getSortedData(nodes);\n if (this.fields.dataSource instanceof DataManager) {\n this.addGivenNodes(nodes, dropLi, index, true);\n }\n else if (this.dataType === 2) {\n this.addGivenNodes(nodes, dropLi, index);\n }\n else {\n if (dropLi) {\n this.addGivenNodes(nodes, dropLi, index);\n }\n else {\n for (var i = 0; i < nodes.length; i++) {\n var pid = getValue(this.fields.parentID, nodes[i]);\n dropLi = pid ? this.getElement(pid.toString()) : pid;\n this.addGivenNodes([nodes[i]], dropLi, index);\n }\n }\n }\n };\n /**\n * Instead of clicking on the TreeView node for editing, we can enable it by using\n * `beginEdit` property. On passing the node ID or element through this property, the edit textBox\n * will be created for the particular node thus allowing us to edit it.\n * @param {string | Element} node - Specifies ID of TreeView node/TreeView node.\n */\n TreeView.prototype.beginEdit = function (node) {\n var ele = this.getElement(node);\n if (!isNOU(ele)) {\n this.createTextbox(ele, null);\n }\n };\n /**\n * Checks all the unchecked nodes. You can also check specific nodes by passing array of unchecked nodes\n * as argument to this method.\n * @param {string[] | Element[]} nodes - Specifies the array of TreeView nodes ID/array of TreeView node.\n */\n TreeView.prototype.checkAll = function (nodes) {\n if (this.showCheckBox) {\n this.doCheckBoxAction(nodes, true);\n }\n };\n /**\n * Collapses all the expanded TreeView nodes. You can collapse specific nodes by passing array of nodes as argument to this method.\n * You can also collapse all the nodes excluding the hidden nodes by setting **excludeHiddenNodes** to true. If you want to collapse\n * a specific level of nodes, set **level** as argument to collapseAll method.\n * @param {string[] | Element[]} nodes - Specifies the array of TreeView nodes ID/ array of TreeView node.\n * @param {number} level - TreeView nodes will collapse up to the given level.\n * @param {boolean} excludeHiddenNodes - Whether or not to exclude hidden nodes of TreeView when collapsing all nodes.\n */\n TreeView.prototype.collapseAll = function (nodes, level, excludeHiddenNodes) {\n if (!isNOU(nodes)) {\n this.doGivenAction(nodes, COLLAPSIBLE, false);\n }\n else {\n if (level > 0) {\n this.collapseByLevel(select('.' + PARENTITEM, this.element), level, excludeHiddenNodes);\n }\n else {\n this.collapseAllNodes(excludeHiddenNodes);\n }\n }\n };\n /**\n * Disables the collection of nodes by passing the ID of nodes or node elements in the array.\n * @param {string[] | Element[]} nodes - Specifies the array of TreeView nodes ID/array of TreeView nodes.\n */\n TreeView.prototype.disableNodes = function (nodes) {\n if (!isNOU(nodes)) {\n this.doDisableAction(nodes);\n }\n };\n /**\n * Enables the collection of disabled nodes by passing the ID of nodes or node elements in the array.\n * @param {string[] | Element[]} nodes - Specifies the array of TreeView nodes ID/array of TreeView nodes.\n */\n TreeView.prototype.enableNodes = function (nodes) {\n if (!isNOU(nodes)) {\n this.doEnableAction(nodes);\n }\n };\n /**\n * Ensures visibility of the TreeView node by using node ID or node element.\n * When many TreeView nodes are present and we need to find a particular node, `ensureVisible` property\n * helps bring the node to visibility by expanding the TreeView and scrolling to the specific node.\n * @param {string | Element} node - Specifies ID of TreeView node/TreeView nodes.\n */\n TreeView.prototype.ensureVisible = function (node) {\n var liEle = this.getElement(node);\n if (isNOU(liEle)) {\n return;\n }\n var parents = this.parents(liEle, '.' + LISTITEM);\n this.expandAll(parents);\n setTimeout(function () { liEle.scrollIntoView(true); }, 450);\n };\n /**\n * Expands all the collapsed TreeView nodes. You can expand the specific nodes by passing the array of collapsed nodes\n * as argument to this method. You can also expand all the collapsed nodes by excluding the hidden nodes by setting\n * **excludeHiddenNodes** to true to this method. To expand a specific level of nodes, set **level** as argument to expandAll method.\n * @param {string[] | Element[]} nodes - Specifies the array of TreeView nodes ID/array of TreeView nodes.\n * @param {number} level - TreeView nodes will expand up to the given level.\n * @param {boolean} excludeHiddenNodes - Whether or not to exclude hidden nodes when expanding all nodes.\n */\n TreeView.prototype.expandAll = function (nodes, level, excludeHiddenNodes) {\n if (!isNOU(nodes)) {\n this.doGivenAction(nodes, EXPANDABLE, true);\n }\n else {\n if (level > 0) {\n this.expandByLevel(select('.' + PARENTITEM, this.element), level, excludeHiddenNodes);\n }\n else {\n this.expandAllNodes(excludeHiddenNodes);\n }\n }\n };\n /**\n * Get the node's data such as id, text, parentID, selected, isChecked, and expanded by passing the node element or it's ID.\n * @param {string | Element} node - Specifies ID of TreeView node/TreeView node.\n */\n TreeView.prototype.getNode = function (node) {\n var ele = this.getElement(node);\n return this.getNodeData(ele, true);\n };\n /**\n * Moves the collection of nodes within the same TreeView based on target or its index position.\n * @param {string[] | Element[]} sourceNodes - Specifies the array of TreeView nodes ID/array of TreeView node.\n * @param {string | Element} target - Specifies ID of TreeView node/TreeView node as target element.\n * @param {number} index - Specifies the index to place the moved nodes in the target element.\n */\n TreeView.prototype.moveNodes = function (sourceNodes, target, index) {\n var dropLi = this.getElement(target);\n if (isNOU(dropLi)) {\n return;\n }\n for (var i = 0; i < sourceNodes.length; i++) {\n var dragLi = this.getElement(sourceNodes[i]);\n if (isNOU(dragLi) || dropLi.isSameNode(dragLi) || this.isDescendant(dragLi, dropLi)) {\n continue;\n }\n this.dropAsChildNode(dragLi, dropLi, this, index);\n }\n };\n /**\n * Removes the collection of TreeView nodes by passing the array of node details as argument to this method.\n * @param {string[] | Element[]} nodes - Specifies the array of TreeView nodes ID/array of TreeView node.\n */\n TreeView.prototype.removeNodes = function (nodes) {\n if (!isNOU(nodes)) {\n for (var i = 0, len = nodes.length; i < len; i++) {\n var liEle = this.getElement(nodes[i]);\n if (isNOU(liEle)) {\n continue;\n }\n this.removeNode(liEle);\n }\n }\n };\n /**\n * Replaces the text of the TreeView node with the given text.\n * @param {string | Element} target - Specifies ID of TreeView node/TreeView node as target element.\n * @param {string} newText - Specifies the new text of TreeView node.\n */\n TreeView.prototype.updateNode = function (target, newText) {\n if (isNOU(target) || isNOU(newText) || !this.allowEditing) {\n return;\n }\n var liEle = this.getElement(target);\n if (isNOU(liEle)) {\n return;\n }\n var txtEle = select('.' + LISTTEXT, liEle);\n this.updateOldText(liEle);\n var eventArgs = this.getEditEvent(liEle, null, null);\n this.trigger('nodeEditing', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.appendNewText(liEle, txtEle, newText, false);\n };\n /**\n * Unchecks all the checked nodes. You can also uncheck the specific nodes by passing array of checked nodes\n * as argument to this method.\n * @param {string[] | Element[]} nodes - Specifies the array of TreeView nodes ID/array of TreeView node.\n */\n TreeView.prototype.uncheckAll = function (nodes) {\n if (this.showCheckBox) {\n this.doCheckBoxAction(nodes, false);\n }\n };\n __decorate([\n Property(false)\n ], TreeView.prototype, \"allowDragAndDrop\", void 0);\n __decorate([\n Property(false)\n ], TreeView.prototype, \"allowEditing\", void 0);\n __decorate([\n Property(false)\n ], TreeView.prototype, \"allowMultiSelection\", void 0);\n __decorate([\n Complex({}, NodeAnimationSettings)\n ], TreeView.prototype, \"animation\", void 0);\n __decorate([\n Property()\n ], TreeView.prototype, \"checkedNodes\", void 0);\n __decorate([\n Property('')\n ], TreeView.prototype, \"cssClass\", void 0);\n __decorate([\n Property(false)\n ], TreeView.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(false)\n ], TreeView.prototype, \"enableRtl\", void 0);\n __decorate([\n Property('Auto')\n ], TreeView.prototype, \"expandOn\", void 0);\n __decorate([\n Complex({}, FieldsSettings)\n ], TreeView.prototype, \"fields\", void 0);\n __decorate([\n Property(true)\n ], TreeView.prototype, \"fullRowSelect\", void 0);\n __decorate([\n Property()\n ], TreeView.prototype, \"nodeTemplate\", void 0);\n __decorate([\n Property()\n ], TreeView.prototype, \"selectedNodes\", void 0);\n __decorate([\n Property('None')\n ], TreeView.prototype, \"sortOrder\", void 0);\n __decorate([\n Property(false)\n ], TreeView.prototype, \"showCheckBox\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"dataBound\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"drawNode\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"destroyed\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"keyPress\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeChecked\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeChecking\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeClicked\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeCollapsed\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeCollapsing\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeDragging\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeDragStart\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeDragStop\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeDropped\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeEdited\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeEditing\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeExpanded\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeExpanding\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeSelected\", void 0);\n __decorate([\n Event()\n ], TreeView.prototype, \"nodeSelecting\", void 0);\n TreeView = TreeView_1 = __decorate([\n NotifyPropertyChanges\n ], TreeView);\n return TreeView;\n var TreeView_1;\n}(Component));\nexport { TreeView };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, formatUnit, EventHandler, Event, isNullOrUndefined, closest } from '@syncfusion/ej2-base';\nimport { Property, NotifyPropertyChanges, Browser } from '@syncfusion/ej2-base';\nimport { setStyleAttribute as setStyle, addClass, removeClass, Touch } from '@syncfusion/ej2-base';\nvar CONTROL = 'e-control';\nvar ROOT = 'e-sidebar';\nvar DOCKER = 'e-dock';\nvar CLOSE = 'e-close';\nvar OPEN = 'e-open';\nvar TRASITION = 'e-transition';\nvar DEFAULTBACKDROP = 'e-sidebar-overlay';\nvar CONTEXTBACKDROP = 'e-backdrop';\nvar RTL = 'e-rtl';\nvar RIGHT = 'e-right';\nvar LEFT = 'e-left';\nvar OVER = 'e-over';\nvar PUSH = 'e-push';\nvar SLIDE = 'e-slide';\nvar VISIBILITY = 'e-visibility';\nvar MAINCONTENTANIMATION = 'e-content-animation';\nvar DISABLEANIMATION = 'e-disable-animation';\nvar CONTEXT = 'e-sidebar-context';\nvar SIDEBARABSOLUTE = 'e-sidebar-absolute';\n/**\n * Sidebar is an expandable or collapsible\n * component that typically act as a side container to place the primary or secondary content alongside of the main content.\n * ```html\n * \n * ```\n * ```typescript\n * \n * ```\n */\nvar Sidebar = /** @class */ (function (_super) {\n __extends(Sidebar, _super);\n function Sidebar(options, element) {\n return _super.call(this, options, element) || this;\n }\n Sidebar.prototype.preRender = function () {\n this.setWidth();\n };\n Sidebar.prototype.render = function () {\n this.initialize();\n this.wireEvents();\n };\n Sidebar.prototype.initialize = function () {\n this.setTarget();\n this.addClass();\n this.setZindex();\n if (this.enableDock) {\n this.setDock();\n }\n if (this.isOpen) {\n this.show();\n }\n else {\n this.setMediaQuery();\n }\n this.setType(this.type);\n this.setCloseOnDocumentClick();\n this.setEnableRTL();\n };\n Sidebar.prototype.setEnableRTL = function () {\n this.enableRtl ? (addClass([this.element], RTL)) :\n (removeClass([this.element], RTL));\n };\n Sidebar.prototype.setTarget = function () {\n this.targetParentElement = this.element.previousElementSibling || this.element.parentElement;\n if (typeof (this.target) === 'string') {\n this.setProperties({ target: document.querySelector(this.target) }, true);\n }\n if (this.target) {\n this.target.insertBefore(this.element, this.target.children[0]);\n addClass([this.element], SIDEBARABSOLUTE);\n addClass([this.target], CONTEXT);\n }\n };\n Sidebar.prototype.setCloseOnDocumentClick = function () {\n if (this.closeOnDocumentClick) {\n EventHandler.add(document, 'mousedown touchstart', this.documentclickHandler, this);\n }\n else {\n EventHandler.remove(document, 'mousedown touchstart', this.documentclickHandler);\n }\n };\n Sidebar.prototype.setWidth = function () {\n if (this.enableDock && this.position === 'Left') {\n setStyle(this.element, { 'width': this.setDimension(this.dockSize) });\n }\n else if (this.enableDock && this.position === 'Right') {\n setStyle(this.element, { 'width': this.setDimension(this.dockSize) });\n }\n else if (!this.enableDock) {\n setStyle(this.element, { 'width': this.setDimension(this.width) });\n }\n };\n Sidebar.prototype.setDimension = function (width) {\n if (typeof width === 'number') {\n width = formatUnit(width);\n }\n else if (typeof width === 'string') {\n width = (width.match(/px|%|em/)) ? width : formatUnit(width);\n }\n else {\n width = '100%';\n }\n return width;\n };\n Sidebar.prototype.setZindex = function () {\n setStyle(this.element, { 'z-index': '' + this.zIndex });\n };\n Sidebar.prototype.addClass = function () {\n var classELement = document.querySelector('.e-main-content');\n if (!isNullOrUndefined((classELement ||\n this.element.nextElementSibling))) {\n addClass([classELement || this.element.nextElementSibling], [MAINCONTENTANIMATION]);\n }\n if (!this.enableDock && this.type !== 'Auto') {\n addClass([this.element], [VISIBILITY]);\n }\n removeClass([this.element], [OPEN, CLOSE, RIGHT, LEFT, SLIDE, PUSH, OVER]);\n this.element.classList.add(ROOT);\n addClass([this.element], (this.position === 'Right') ? RIGHT : LEFT);\n if (this.type === 'Auto' && !Browser.isDevice && !this.enableDock) {\n addClass([this.element], OPEN);\n }\n else {\n addClass([this.element], CLOSE);\n }\n };\n Sidebar.prototype.destroyBackDrop = function () {\n var sibling = document.querySelector('.e-main-content') ||\n this.element.nextElementSibling;\n if (this.target && this.showBackdrop && sibling) {\n removeClass([sibling], CONTEXTBACKDROP);\n }\n else if (this.showBackdrop && this.modal) {\n this.modal.style.display = 'none';\n this.modal.outerHTML = '';\n this.modal = null;\n }\n };\n /**\n * Hide the Sidebar component.\n * @returns void\n */\n Sidebar.prototype.hide = function () {\n var closeArguments = { model: this, element: this.element, cancel: false };\n this.trigger('close', closeArguments);\n if (!closeArguments.cancel) {\n if (this.element.classList.contains(CLOSE)) {\n return;\n }\n if (this.element.classList.contains(OPEN)) {\n var changeArguments = { name: 'change', element: this.element };\n this.trigger('change', changeArguments);\n }\n addClass([this.element], CLOSE);\n removeClass([this.element], OPEN);\n this.enableDock ? setStyle(this.element, { 'width': formatUnit(this.dockSize) }) :\n setStyle(this.element, { 'width': formatUnit(this.width) });\n this.setDock();\n this.setType(this.type);\n var sibling = document.querySelector('.e-main-content') ||\n this.element.nextElementSibling;\n if (!this.enableDock && sibling) {\n sibling.style.transform = 'translateX(' + 0 + 'px)';\n this.position === 'Left' ? sibling.style.marginLeft = '0px' : sibling.style.marginRight = '0px';\n }\n this.destroyBackDrop();\n this.setCloseOnDocumentClick();\n this.setAnimation();\n if (this.type === 'Slide') {\n document.body.classList.remove('e-sidebar-overflow');\n }\n this.setProperties({ isOpen: false }, true);\n }\n };\n /**\n * Shows the Sidebar component.\n * @returns void\n */\n Sidebar.prototype.show = function () {\n var openArguments = { model: this, element: this.element, cancel: false };\n this.trigger('open', openArguments);\n if (!openArguments.cancel) {\n removeClass([this.element], VISIBILITY);\n if (this.element.classList.contains(OPEN)) {\n return;\n }\n if (this.element.classList.contains(CLOSE)) {\n var changeArguments = { name: 'change', element: this.element };\n this.trigger('change', changeArguments);\n }\n addClass([this.element], [OPEN, TRASITION]);\n setStyle(this.element, { 'transform': '' });\n removeClass([this.element], CLOSE);\n setStyle(this.element, { 'width': formatUnit(this.width) });\n var elementWidth = this.element.getBoundingClientRect().width;\n this.setType(this.type);\n this.createBackDrop();\n this.setCloseOnDocumentClick();\n this.setAnimation();\n if (this.type === 'Slide') {\n document.body.classList.add('e-sidebar-overflow');\n }\n this.setProperties({ isOpen: true }, true);\n }\n };\n Sidebar.prototype.setAnimation = function () {\n if (this.animate) {\n removeClass([this.element], DISABLEANIMATION);\n }\n else {\n addClass([this.element], DISABLEANIMATION);\n }\n };\n Sidebar.prototype.setDock = function () {\n if (this.enableDock && this.position === 'Left' && !this.getState()) {\n setStyle(this.element, { 'transform': 'translateX(' + -100 + '%) translateX(' + this.setDimension(this.dockSize) + ')' });\n }\n else if (this.enableDock && this.position === 'Right' && !this.getState()) {\n setStyle(this.element, { 'transform': 'translateX(' + 100 + '%) translateX(' + '-' + this.setDimension(this.dockSize) + ')' });\n }\n if (this.element.classList.contains(CLOSE) && this.enableDock) {\n setStyle(this.element, { 'width': this.setDimension(this.dockSize) });\n }\n };\n Sidebar.prototype.createBackDrop = function () {\n if (this.target && this.showBackdrop) {\n var sibling = document.querySelector('.e-main-content') ||\n this.element.nextElementSibling;\n addClass([sibling], CONTEXTBACKDROP);\n }\n else if (this.showBackdrop && !this.modal && this.getState()) {\n this.modal = this.createElement('div');\n this.modal.className = DEFAULTBACKDROP;\n this.modal.style.display = 'block';\n document.body.appendChild(this.modal);\n }\n };\n Sidebar.prototype.getPersistData = function () {\n return this.addOnPersist(['type', 'position', 'isOpen']);\n };\n /**\n * Returns the current module name.\n * @returns string\n * @private\n */\n Sidebar.prototype.getModuleName = function () {\n return 'sidebar';\n };\n /**\n * Shows or hides the Sidebar based on the current state.\n * @returns void\n */\n Sidebar.prototype.toggle = function (e) {\n this.element.classList.contains(OPEN) ? this.hide() : this.show();\n };\n Sidebar.prototype.getState = function () {\n return this.element.classList.contains(OPEN) ? true : false;\n };\n Sidebar.prototype.setMediaQuery = function () {\n if (this.mediaQuery && this.mediaQuery.matches) {\n this.show();\n }\n else if (this.mediaQuery && this.getState()) {\n this.hide();\n }\n };\n Sidebar.prototype.resize = function (e) {\n if (this.type === 'Auto') {\n if (Browser.isDevice) {\n addClass([this.element], OVER);\n }\n else {\n addClass([this.element], PUSH);\n }\n }\n this.setMediaQuery();\n };\n Sidebar.prototype.documentclickHandler = function (e) {\n if (closest(e.target, '.' + CONTROL + '' + '.' + ROOT)) {\n return;\n }\n this.hide();\n };\n Sidebar.prototype.enableGestureHandler = function (args) {\n if (this.position === 'Left' && args.swipeDirection === 'Right' &&\n (args.startX <= 20 && args.distanceX >= 50 && args.velocity >= 0.5)) {\n this.show();\n }\n else if (this.position === 'Left' && args.swipeDirection === 'Left') {\n this.hide();\n }\n else if (this.position === 'Right' && args.swipeDirection === 'Right') {\n this.hide();\n }\n else if (this.position === 'Right' && args.swipeDirection === 'Left'\n && (window.innerWidth - args.startX <= 20 && args.distanceX >= 50 && args.velocity >= 0.5)) {\n this.show();\n }\n };\n Sidebar.prototype.setEnableGestures = function () {\n if (this.enableGestures) {\n this.mainContentEle = new Touch(document.body, { swipe: this.enableGestureHandler.bind(this) });\n this.sidebarEle = new Touch(this.element, { swipe: this.enableGestureHandler.bind(this) });\n }\n else {\n if (this.mainContentEle && this.sidebarEle) {\n this.mainContentEle.destroy();\n this.sidebarEle.destroy();\n }\n }\n };\n Sidebar.prototype.wireEvents = function () {\n this.setEnableGestures();\n window.addEventListener('resize', this.resize.bind(this));\n };\n Sidebar.prototype.unWireEvents = function () {\n window.removeEventListener('resize', this.resize.bind(this));\n EventHandler.remove(document, 'mousedown touchstart', this.documentclickHandler);\n if (this.mainContentEle) {\n this.mainContentEle.destroy();\n }\n if (this.sidebarEle) {\n this.sidebarEle.destroy();\n }\n };\n Sidebar.prototype.onPropertyChanged = function (newProp, oldProp) {\n var sibling = document.querySelector('.e-main-content') ||\n this.element.nextElementSibling;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'isOpen':\n this.isOpen ? this.show() : this.hide();\n break;\n case 'width':\n this.setWidth();\n if (!this.getState()) {\n this.setDock();\n }\n break;\n case 'animate':\n this.setAnimation();\n break;\n case 'type':\n removeClass([this.element], [VISIBILITY]);\n this.addClass();\n this.setType(this.type);\n break;\n case 'position':\n this.element.style.transform = '';\n this.setDock();\n if (sibling) {\n this.position === 'Left' ? sibling.style.marginRight = '0px' : sibling.style.marginLeft = '0px';\n }\n if (this.position === 'Right') {\n removeClass([this.element], LEFT);\n addClass([this.element], RIGHT);\n }\n else {\n removeClass([this.element], RIGHT);\n addClass([this.element], LEFT);\n }\n this.setType(this.type);\n break;\n case 'showBackdrop':\n if (this.showBackdrop) {\n this.createBackDrop();\n }\n else {\n if (this.modal) {\n this.modal.style.display = 'none';\n this.modal.outerHTML = '';\n this.modal = null;\n }\n }\n break;\n case 'target':\n if (typeof (this.target) === 'string') {\n this.setProperties({ target: document.querySelector(this.target) }, true);\n }\n if (isNullOrUndefined(this.target)) {\n removeClass([this.element], SIDEBARABSOLUTE);\n removeClass([oldProp.target], CONTEXT);\n setStyle(sibling, { 'margin-left': 0, 'margin-right': 0 });\n document.body.insertAdjacentElement('afterbegin', this.element);\n }\n else {\n _super.prototype.refresh.call(this);\n }\n break;\n case 'closeOnDocumentClick':\n this.setCloseOnDocumentClick();\n break;\n case 'enableDock':\n if (!this.getState()) {\n this.setDock();\n }\n break;\n case 'zIndex':\n this.setZindex();\n break;\n case 'mediaQuery':\n this.setMediaQuery();\n break;\n case 'enableGestures':\n this.setEnableGestures();\n break;\n case 'enableRtl':\n this.setEnableRTL();\n break;\n }\n }\n };\n Sidebar.prototype.setType = function (type) {\n var elementWidth = this.element.getBoundingClientRect().width;\n this.setZindex();\n if (this.enableDock) {\n addClass([this.element], DOCKER);\n }\n var sibling = document.querySelector('.e-main-content') ||\n this.element.nextElementSibling;\n if (sibling) {\n sibling.style.transform = 'translateX(' + 0 + 'px)';\n if (!Browser.isDevice && this.type !== 'Auto') {\n this.position === 'Left' ? sibling.style.marginLeft = '0px' : sibling.style.marginRight = '0px';\n }\n }\n var margin = this.position === 'Left' ? elementWidth + 'px' : elementWidth + 'px';\n var eleWidth = this.position === 'Left' ? elementWidth : -(elementWidth);\n removeClass([this.element], [PUSH, OVER, SLIDE]);\n switch (type) {\n case 'Push':\n addClass([this.element], [PUSH]);\n if (sibling && (this.enableDock || this.element.classList.contains(OPEN))) {\n this.position === 'Left' ? sibling.style.marginLeft = margin : sibling.style.marginRight = margin;\n }\n break;\n case 'Slide':\n addClass([this.element], [SLIDE]);\n if (sibling && (this.enableDock || this.element.classList.contains(OPEN))) {\n sibling.style.transform = 'translateX(' + eleWidth + 'px)';\n }\n break;\n case 'Over':\n addClass([this.element], [OVER]);\n if (this.enableDock && this.element.classList.contains(CLOSE)) {\n if (sibling) {\n this.position === 'Left' ? sibling.style.marginLeft = margin : sibling.style.marginRight = margin;\n }\n }\n break;\n case 'Auto':\n addClass([this.element], [TRASITION]);\n if (Browser.isDevice) {\n if (sibling && (this.enableDock) && !this.getState()) {\n this.position === 'Left' ? sibling.style.marginLeft = margin : sibling.style.marginRight = margin;\n addClass([this.element], PUSH);\n }\n else {\n addClass([this.element], OVER);\n }\n }\n else {\n addClass([this.element], PUSH);\n if (sibling && (this.enableDock || this.element.classList.contains(OPEN))) {\n this.position === 'Left' ? sibling.style.marginLeft = margin : sibling.style.marginRight = margin;\n }\n this.setProperties({ isOpen: true }, true);\n }\n this.createBackDrop();\n }\n };\n /**\n * Removes the control from the DOM and removes all its related events\n * @returns void\n */\n Sidebar.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n removeClass([this.element], [OPEN, CLOSE, PUSH, SLIDE, OVER, LEFT, RIGHT, TRASITION, DISABLEANIMATION,\n CONTEXTBACKDROP, MAINCONTENTANIMATION, VISIBILITY]);\n this.destroyBackDrop();\n this.element.style.width = '';\n this.element.style.zIndex = '';\n this.element.style.transform = '';\n var sibling = document.querySelector('.e-main-content')\n || this.element.nextElementSibling;\n if (!isNullOrUndefined(sibling)) {\n sibling.style.margin = '';\n sibling.style.transform = '';\n }\n if (this.target) {\n removeClass([this.element], SIDEBARABSOLUTE);\n removeClass([this.target], CONTEXT);\n if (this.targetParentElement.parentElement.tagName !== 'HTML') {\n this.targetParentElement.parentNode.insertBefore(this.element, this.targetParentElement.nextSibling);\n }\n }\n this.unWireEvents();\n };\n __decorate([\n Property('auto')\n ], Sidebar.prototype, \"dockSize\", void 0);\n __decorate([\n Property(null)\n ], Sidebar.prototype, \"mediaQuery\", void 0);\n __decorate([\n Property(false)\n ], Sidebar.prototype, \"enableDock\", void 0);\n __decorate([\n Property(true)\n ], Sidebar.prototype, \"enableGestures\", void 0);\n __decorate([\n Property(false)\n ], Sidebar.prototype, \"isOpen\", void 0);\n __decorate([\n Property(false)\n ], Sidebar.prototype, \"enableRtl\", void 0);\n __decorate([\n Property(true)\n ], Sidebar.prototype, \"animate\", void 0);\n __decorate([\n Property('auto')\n ], Sidebar.prototype, \"height\", void 0);\n __decorate([\n Property(false)\n ], Sidebar.prototype, \"closeOnDocumentClick\", void 0);\n __decorate([\n Property('Left')\n ], Sidebar.prototype, \"position\", void 0);\n __decorate([\n Property(null)\n ], Sidebar.prototype, \"target\", void 0);\n __decorate([\n Property(false)\n ], Sidebar.prototype, \"showBackdrop\", void 0);\n __decorate([\n Property('Auto')\n ], Sidebar.prototype, \"type\", void 0);\n __decorate([\n Property('auto')\n ], Sidebar.prototype, \"width\", void 0);\n __decorate([\n Property(1000)\n ], Sidebar.prototype, \"zIndex\", void 0);\n __decorate([\n Event()\n ], Sidebar.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Sidebar.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], Sidebar.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], Sidebar.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], Sidebar.prototype, \"destroyed\", void 0);\n Sidebar = __decorate([\n NotifyPropertyChanges\n ], Sidebar);\n return Sidebar;\n}(Component));\nexport { Sidebar };\n","import { createElement, isNullOrUndefined, Browser } from '@syncfusion/ej2-base';\nimport { Toolbar } from '@syncfusion/ej2-navigations';\nimport { DateRangePicker } from '@syncfusion/ej2-calendars';\nimport { getElement } from '../../common/utils/helper';\n/**\n * Period selector class\n */\nvar PeriodSelector = /** @class */ (function () {\n //constructor for period selector\n function PeriodSelector(rangeNavigator) {\n this.control = rangeNavigator;\n }\n /**\n * renderSelector div\n * @param control\n */\n PeriodSelector.prototype.renderSelectorElement = function (control) {\n //render border\n var periodSelectorSize = this.periodSelectorSize;\n var thumbSize = control.themeStyle.thumbWidth;\n this.periodSelectorDiv = createElement('div', {\n id: control.element.id + '_Secondary_Element',\n styles: 'width: ' + (this.periodSelectorSize.width - thumbSize) + 'px;height: ' +\n this.periodSelectorSize.height + 'px;top:' +\n this.periodSelectorSize.y + 'px;left:' +\n (this.periodSelectorSize.x + thumbSize / 2) + 'px; position: absolute'\n });\n this.control.element.appendChild(this.periodSelectorDiv);\n };\n /**\n * renderSelector elements\n */\n PeriodSelector.prototype.renderSelector = function () {\n var _this = this;\n var selectorElement = createElement('div', { id: this.control.element.id + '_selector' });\n this.periodSelectorDiv.appendChild(selectorElement);\n //render toolbar\n var selector = [];\n var buttons = this.control.periodSelectorSettings.periods;\n for (var i = 0; i < buttons.length; i++) {\n selector.push({ align: 'Left', text: buttons[i].text });\n }\n this.calendarId = this.control.element.id + '_calendar';\n selector.push({ template: '
', align: 'Right' });\n var selctorArgs = {\n selector: selector,\n name: 'RangeSelector',\n cancel: false,\n enableCustomFormat: false,\n content: ''\n };\n this.control.trigger('selectorRender', selctorArgs);\n this.toolbar = new Toolbar({\n items: selctorArgs.selector, height: this.periodSelectorSize.height,\n clicked: function (args) {\n _this.buttonClick(args, _this.control);\n }, created: function () {\n _this.nodes = _this.toolbar.element.querySelectorAll('.e-toolbar-left')[0];\n if (isNullOrUndefined(_this.selectedIndex)) {\n buttons.map(function (period, index) {\n if (period.selected) {\n _this.control.startValue = _this.changedRange(period.intervalType, _this.control.endValue, period.interval).getTime();\n _this.selectedIndex = (_this.nodes.childNodes.length - buttons.length) + index;\n }\n });\n }\n _this.setSelectedStyle(_this.selectedIndex);\n }\n });\n this.toolbar.appendTo(selectorElement);\n this.triggerChange = true;\n //render calendar\n this.datePicker = new DateRangePicker({\n min: new Date(this.control.chartSeries.xMin),\n max: new Date(this.control.chartSeries.xMax),\n format: 'dd\\'\\/\\'MM\\'\\/\\'yyyy',\n placeholder: 'Select a range',\n showClearButton: false,\n startDate: new Date(this.control.startValue),\n endDate: new Date(this.control.endValue),\n created: function (args) {\n if (selctorArgs.enableCustomFormat) {\n var datePickerElement = document.getElementsByClassName('e-date-range-wrapper')[0];\n datePickerElement.style.display = 'none';\n datePickerElement.insertAdjacentElement('afterend', createElement('div', { id: 'customRange',\n innerHTML: selctorArgs.content, className: 'e-btn e-small' }));\n getElement('customRange').insertAdjacentElement('afterbegin', (createElement('span', { id: 'dateIcon',\n className: 'e-input-group-icon e-range-icon e-icons', styles: 'margin-right: 10px' })));\n document.getElementById('customRange').onclick = function () {\n _this.datePicker.show(getElement('customRange'));\n };\n }\n },\n change: function (args) {\n if (_this.triggerChange) {\n _this.control.rangeSlider.performAnimation(args.startDate.getTime(), args.endDate.getTime(), _this.control);\n }\n }\n });\n this.datePicker.appendTo('#' + this.calendarId);\n };\n /**\n * To set and deselect the acrive style\n * @param buttons\n */\n PeriodSelector.prototype.setSelectedStyle = function (selectedIndex) {\n if (this.control.disableRangeSelector) {\n for (var i = 0, length_1 = this.nodes.childNodes.length; i < length_1; i++) {\n this.nodes.childNodes[i].childNodes[0].classList.remove('e-active');\n this.nodes.childNodes[i].childNodes[0].classList.remove('e-active');\n }\n this.nodes.childNodes[selectedIndex].childNodes[0].classList.add('e-flat');\n this.nodes.childNodes[selectedIndex].childNodes[0].classList.add('e-active');\n }\n };\n /**\n * Button click handling\n */\n PeriodSelector.prototype.buttonClick = function (args, control) {\n var _this = this;\n var toolBarItems = this.toolbar.items;\n var clickedEle = args.item;\n var slider = control.rangeSlider;\n var updatedStart;\n var updatedEnd;\n var buttons = control.periodSelectorSettings.periods;\n var button = buttons.filter(function (btn) { return (btn.text === clickedEle.text); });\n buttons.map(function (period, index) {\n if (period.text === args.item.text) {\n _this.selectedIndex = (_this.nodes.childNodes.length - buttons.length) + index;\n }\n });\n this.setSelectedStyle(this.selectedIndex);\n if (clickedEle.text.toLowerCase() === 'all') {\n updatedStart = control.chartSeries.xMin;\n updatedEnd = control.chartSeries.xMax;\n slider.performAnimation(updatedStart, updatedEnd, control);\n }\n else if (clickedEle.text.toLowerCase() === 'ytd') {\n updatedStart = new Date(new Date(slider.currentEnd).getFullYear().toString()).getTime();\n updatedEnd = slider.currentEnd;\n slider.performAnimation(updatedStart, updatedEnd, control);\n }\n else if (clickedEle.text.toLowerCase() !== '') {\n updatedStart = this.changedRange(button[0].intervalType, slider.currentEnd, button[0].interval).getTime();\n updatedEnd = slider.currentEnd;\n slider.performAnimation(updatedStart, updatedEnd, control);\n }\n if (getElement(this.calendarId + '_popup') && !Browser.isDevice) {\n var element = getElement(this.calendarId + '_popup');\n element.querySelectorAll('.e-range-header')[0].style.display = 'none';\n }\n };\n /**\n *\n * @param type updatedRange for selector\n * @param end\n * @param interval\n */\n PeriodSelector.prototype.changedRange = function (type, end, interval) {\n var result = new Date(end);\n switch (type) {\n case 'Quarter':\n result.setMonth(result.getMonth() - (3 * interval));\n break;\n case 'Months':\n result.setMonth(result.getMonth() - interval);\n break;\n case 'Weeks':\n result.setDate(result.getDate() - (interval * 7));\n break;\n case 'Days':\n result.setDate(result.getDate() - interval);\n break;\n case 'Hours':\n result.setHours(result.getHours() - interval);\n break;\n case 'Minutes':\n result.setMinutes(result.getMinutes() - interval);\n break;\n case 'Seconds':\n result.setSeconds(result.getSeconds() - interval);\n break;\n default:\n result.setFullYear(result.getFullYear() - interval);\n break;\n }\n return result;\n };\n ;\n /**\n * Get module name\n */\n PeriodSelector.prototype.getModuleName = function () {\n return 'PeriodSelector';\n };\n /**\n * To destroy the period selector.\n * @return {void}\n * @private\n */\n PeriodSelector.prototype.destroy = function () {\n /**\n * destroy method\n */\n };\n return PeriodSelector;\n}());\nexport { PeriodSelector };\n","import { Tooltip as SVGTooltip } from '@syncfusion/ej2-svg-base';\nimport { getElement } from '../../common/utils/helper';\nimport { stopTimer } from '../../common/utils/helper';\nimport { firstToLowerCase } from '../../index';\nimport { measureText, createTemplate } from '../../index';\nimport { createElement } from '@syncfusion/ej2-base';\n/**\n * `Tooltip` module is used to render the tooltip for chart series.\n */\nvar RangeTooltip = /** @class */ (function () {\n /**\n * Constructor for tooltip module.\n * @private.\n */\n function RangeTooltip(range) {\n this.control = range;\n this.elementId = range.element.id;\n }\n /**\n * Left tooltip method called here\n * @param rangeSlider\n */\n RangeTooltip.prototype.renderLeftTooltip = function (rangeSlider) {\n this.fadeOutTooltip();\n var content = this.getTooltipContent(rangeSlider.currentStart);\n var contentWidth = this.getContentSize(content);\n var rect = this.control.enableRtl ? rangeSlider.rightRect : rangeSlider.leftRect;\n if (contentWidth > rect.width) {\n rect = rangeSlider.midRect;\n }\n this.leftTooltip = this.renderTooltip(rect, this.createElement('_leftTooltip'), rangeSlider.startX, content);\n };\n /**\n * get the content size\n * @param value\n */\n RangeTooltip.prototype.getContentSize = function (value) {\n var width;\n var font = this.control.tooltip.textStyle;\n if (this.control.tooltip.template) {\n width = createTemplate(createElement('div', {\n id: 'measureElement',\n styles: 'position: absolute;'\n }), 0, this.control.tooltip.template, this.control).getBoundingClientRect().width;\n }\n else {\n // 20 for tooltip padding\n width = measureText(value[0], font).width + 20;\n }\n return width;\n };\n /**\n * Right tooltip method called here\n * @param rangeSlider\n */\n RangeTooltip.prototype.renderRightTooltip = function (rangeSlider) {\n this.fadeOutTooltip();\n var content = this.getTooltipContent(rangeSlider.currentEnd);\n var contentWidth = this.getContentSize(content);\n var rect = this.control.enableRtl ? rangeSlider.leftRect : rangeSlider.rightRect;\n if (contentWidth > rect.width) {\n rect = rangeSlider.midRect;\n rect.x = !this.control.series.length ? rect.x : 0;\n }\n this.rightTooltip = this.renderTooltip(rect, this.createElement('_rightTooltip'), rangeSlider.endX, content);\n };\n /**\n * Tooltip element creation\n * @param id\n */\n RangeTooltip.prototype.createElement = function (id) {\n if (getElement(this.elementId + id)) {\n return getElement(this.elementId + id);\n }\n else {\n var element = document.createElement('div');\n element.id = this.elementId + id;\n element.className = 'ejSVGTooltip';\n element.setAttribute('style', 'pointer-events:none; position:absolute;z-index: 1');\n getElement(this.elementId + '_Secondary_Element').appendChild(element);\n return element;\n }\n };\n /**\n * Tooltip render called here\n * @param bounds\n * @param parent\n * @param pointX\n * @param value\n */\n RangeTooltip.prototype.renderTooltip = function (bounds, parent, pointX, content) {\n var control = this.control;\n var tooltip = control.tooltip;\n var argsData = {\n cancel: false, name: 'tooltipRender', text: content,\n textStyle: tooltip.textStyle\n };\n this.control.trigger('tooltipRender', argsData);\n var left = control.svgObject.getBoundingClientRect().left -\n control.element.getBoundingClientRect().left;\n if (!argsData.cancel) {\n return new SVGTooltip({\n location: { x: pointX, y: control.rangeSlider.sliderY },\n content: argsData.text, marginX: 2,\n enableShadow: false,\n marginY: 2, arrowPadding: 8, rx: 0, ry: 0,\n inverted: control.series.length > 0,\n areaBounds: bounds, fill: tooltip.fill,\n theme: this.control.theme,\n //enableShadow: false,\n clipBounds: { x: left },\n border: tooltip.border, opacity: tooltip.opacity,\n template: tooltip.template,\n textStyle: argsData.textStyle,\n data: {\n 'start': this.getTooltipContent(this.control.startValue)[0],\n 'end': this.getTooltipContent(this.control.endValue)[0],\n 'value': content[0]\n }\n }, parent);\n }\n else {\n return null;\n }\n };\n /**\n * Tooltip content processed here\n * @param value\n */\n RangeTooltip.prototype.getTooltipContent = function (value) {\n var control = this.control;\n var tooltip = control.tooltip;\n var xAxis = control.chartSeries.xAxis;\n var text;\n var format = tooltip.format || xAxis.labelFormat;\n var isCustom = format.match('{value}') !== null;\n var valueType = xAxis.valueType;\n if (valueType === 'DateTime') {\n text = (control.intl.getDateFormat({\n format: format || 'MM/dd/yyyy',\n type: firstToLowerCase(control.skeletonType),\n skeleton: control.dateTimeModule.getSkeleton(xAxis)\n }))(new Date(value));\n }\n else {\n xAxis.format = control.intl.getNumberFormat({\n format: isCustom ? '' : format,\n useGrouping: control.useGroupingSeparator\n });\n text = control.doubleModule.formatValue(xAxis, isCustom, format, valueType === 'Logarithmic' ? Math.pow(xAxis.logBase, value) : value);\n }\n return [text];\n };\n /**\n * Fadeout animation performed here\n */\n RangeTooltip.prototype.fadeOutTooltip = function () {\n var _this = this;\n var tooltip = this.control.tooltip;\n if (tooltip.displayMode === 'OnDemand') {\n stopTimer(this.toolTipInterval);\n if (this.rightTooltip) {\n this.toolTipInterval = setTimeout(function () {\n _this.leftTooltip.fadeOut();\n _this.rightTooltip.fadeOut();\n }, 1000);\n }\n }\n };\n /**\n * Get module name.\n */\n RangeTooltip.prototype.getModuleName = function () {\n return 'RangeTooltip';\n };\n /**\n * To destroy the tooltip.\n * @return {void}\n * @private\n */\n RangeTooltip.prototype.destroy = function (chart) {\n // Destroy method called here\n };\n return RangeTooltip;\n}());\nexport { RangeTooltip };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty } from '@syncfusion/ej2-base';\nvar SmithchartFont = /** @class */ (function (_super) {\n __extends(SmithchartFont, _super);\n function SmithchartFont() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Segoe UI')\n ], SmithchartFont.prototype, \"fontFamily\", void 0);\n __decorate([\n Property('Normal')\n ], SmithchartFont.prototype, \"fontStyle\", void 0);\n __decorate([\n Property('Regular')\n ], SmithchartFont.prototype, \"fontWeight\", void 0);\n __decorate([\n Property('12px')\n ], SmithchartFont.prototype, \"size\", void 0);\n __decorate([\n Property(1)\n ], SmithchartFont.prototype, \"opacity\", void 0);\n return SmithchartFont;\n}(ChildProperty));\nexport { SmithchartFont };\nvar SmithchartMargin = /** @class */ (function (_super) {\n __extends(SmithchartMargin, _super);\n function SmithchartMargin() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(10)\n ], SmithchartMargin.prototype, \"top\", void 0);\n __decorate([\n Property(10)\n ], SmithchartMargin.prototype, \"bottom\", void 0);\n __decorate([\n Property(10)\n ], SmithchartMargin.prototype, \"right\", void 0);\n __decorate([\n Property(10)\n ], SmithchartMargin.prototype, \"left\", void 0);\n return SmithchartMargin;\n}(ChildProperty));\nexport { SmithchartMargin };\nvar SmithchartBorder = /** @class */ (function (_super) {\n __extends(SmithchartBorder, _super);\n function SmithchartBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], SmithchartBorder.prototype, \"width\", void 0);\n __decorate([\n Property(1)\n ], SmithchartBorder.prototype, \"opacity\", void 0);\n __decorate([\n Property('transparent')\n ], SmithchartBorder.prototype, \"color\", void 0);\n return SmithchartBorder;\n}(ChildProperty));\nexport { SmithchartBorder };\n/**\n * Internal use of type rect\n * @private\n */\nvar SmithchartRect = /** @class */ (function () {\n function SmithchartRect(x, y, width, height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n return SmithchartRect;\n}());\nexport { SmithchartRect };\nvar LabelCollection = /** @class */ (function () {\n function LabelCollection() {\n }\n return LabelCollection;\n}());\nexport { LabelCollection };\nvar LegendSeries = /** @class */ (function () {\n function LegendSeries() {\n }\n return LegendSeries;\n}());\nexport { LegendSeries };\nvar LabelRegion = /** @class */ (function () {\n function LabelRegion() {\n }\n return LabelRegion;\n}());\nexport { LabelRegion };\nvar HorizontalLabelCollection = /** @class */ (function (_super) {\n __extends(HorizontalLabelCollection, _super);\n function HorizontalLabelCollection() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return HorizontalLabelCollection;\n}(LabelCollection));\nexport { HorizontalLabelCollection };\nvar RadialLabelCollections = /** @class */ (function (_super) {\n __extends(RadialLabelCollections, _super);\n function RadialLabelCollections() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return RadialLabelCollections;\n}(HorizontalLabelCollection));\nexport { RadialLabelCollections };\nvar LineSegment = /** @class */ (function () {\n function LineSegment() {\n }\n return LineSegment;\n}());\nexport { LineSegment };\nvar PointRegion = /** @class */ (function () {\n function PointRegion() {\n }\n return PointRegion;\n}());\nexport { PointRegion };\n/**\n * Smithchart internal class for point\n */\nvar Point = /** @class */ (function () {\n function Point() {\n }\n return Point;\n}());\nexport { Point };\nvar ClosestPoint = /** @class */ (function () {\n function ClosestPoint() {\n }\n return ClosestPoint;\n}());\nexport { ClosestPoint };\nvar MarkerOptions = /** @class */ (function () {\n function MarkerOptions(id, fill, borderColor, borderWidth, opacity) {\n this.id = id;\n this.fill = fill;\n this.borderColor = borderColor;\n this.borderWidth = borderWidth;\n this.opacity = opacity;\n }\n return MarkerOptions;\n}());\nexport { MarkerOptions };\nvar SmithchartLabelPosition = /** @class */ (function () {\n function SmithchartLabelPosition() {\n }\n return SmithchartLabelPosition;\n}());\nexport { SmithchartLabelPosition };\nvar Direction = /** @class */ (function () {\n function Direction() {\n this.counterclockwise = 0;\n this.clockwise = 1;\n }\n return Direction;\n}());\nexport { Direction };\nvar DataLabelTextOptions = /** @class */ (function () {\n function DataLabelTextOptions() {\n }\n return DataLabelTextOptions;\n}());\nexport { DataLabelTextOptions };\nvar LabelOption = /** @class */ (function () {\n function LabelOption() {\n }\n return LabelOption;\n}());\nexport { LabelOption };\n/** @private */\nvar SmithchartSize = /** @class */ (function () {\n function SmithchartSize(width, height) {\n this.width = width;\n this.height = height;\n }\n return SmithchartSize;\n}());\nexport { SmithchartSize };\nvar GridArcPoints = /** @class */ (function () {\n function GridArcPoints() {\n }\n return GridArcPoints;\n}());\nexport { GridArcPoints };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { SmithchartFont } from '../utils/utils';\nimport { Theme } from '../model/theme';\nvar LegendTitle = /** @class */ (function (_super) {\n __extends(LegendTitle, _super);\n function LegendTitle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], LegendTitle.prototype, \"visible\", void 0);\n __decorate([\n Property('')\n ], LegendTitle.prototype, \"text\", void 0);\n __decorate([\n Property('')\n ], LegendTitle.prototype, \"description\", void 0);\n __decorate([\n Property('Center')\n ], LegendTitle.prototype, \"textAlignment\", void 0);\n __decorate([\n Complex(Theme.legendLabelFont, SmithchartFont)\n ], LegendTitle.prototype, \"textStyle\", void 0);\n return LegendTitle;\n}(ChildProperty));\nexport { LegendTitle };\nvar LegendLocation = /** @class */ (function (_super) {\n __extends(LegendLocation, _super);\n function LegendLocation() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], LegendLocation.prototype, \"x\", void 0);\n __decorate([\n Property(0)\n ], LegendLocation.prototype, \"y\", void 0);\n return LegendLocation;\n}(ChildProperty));\nexport { LegendLocation };\nvar LegendItemStyleBorder = /** @class */ (function (_super) {\n __extends(LegendItemStyleBorder, _super);\n function LegendItemStyleBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], LegendItemStyleBorder.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], LegendItemStyleBorder.prototype, \"color\", void 0);\n return LegendItemStyleBorder;\n}(ChildProperty));\nexport { LegendItemStyleBorder };\nvar LegendItemStyle = /** @class */ (function (_super) {\n __extends(LegendItemStyle, _super);\n function LegendItemStyle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(10)\n ], LegendItemStyle.prototype, \"width\", void 0);\n __decorate([\n Property(10)\n ], LegendItemStyle.prototype, \"height\", void 0);\n __decorate([\n Complex({}, LegendItemStyleBorder)\n ], LegendItemStyle.prototype, \"border\", void 0);\n return LegendItemStyle;\n}(ChildProperty));\nexport { LegendItemStyle };\nvar LegendBorder = /** @class */ (function (_super) {\n __extends(LegendBorder, _super);\n function LegendBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], LegendBorder.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], LegendBorder.prototype, \"color\", void 0);\n return LegendBorder;\n}(ChildProperty));\nexport { LegendBorder };\nvar SmithchartLegendSettings = /** @class */ (function (_super) {\n __extends(SmithchartLegendSettings, _super);\n function SmithchartLegendSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], SmithchartLegendSettings.prototype, \"visible\", void 0);\n __decorate([\n Property('bottom')\n ], SmithchartLegendSettings.prototype, \"position\", void 0);\n __decorate([\n Property('Center')\n ], SmithchartLegendSettings.prototype, \"alignment\", void 0);\n __decorate([\n Property(null)\n ], SmithchartLegendSettings.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], SmithchartLegendSettings.prototype, \"height\", void 0);\n __decorate([\n Property('circle')\n ], SmithchartLegendSettings.prototype, \"shape\", void 0);\n __decorate([\n Property(null)\n ], SmithchartLegendSettings.prototype, \"rowCount\", void 0);\n __decorate([\n Property(null)\n ], SmithchartLegendSettings.prototype, \"columnCount\", void 0);\n __decorate([\n Property(8)\n ], SmithchartLegendSettings.prototype, \"itemPadding\", void 0);\n __decorate([\n Property(5)\n ], SmithchartLegendSettings.prototype, \"shapePadding\", void 0);\n __decorate([\n Property('')\n ], SmithchartLegendSettings.prototype, \"description\", void 0);\n __decorate([\n Property(true)\n ], SmithchartLegendSettings.prototype, \"toggleVisibility\", void 0);\n __decorate([\n Complex({}, LegendTitle)\n ], SmithchartLegendSettings.prototype, \"title\", void 0);\n __decorate([\n Complex({}, LegendLocation)\n ], SmithchartLegendSettings.prototype, \"location\", void 0);\n __decorate([\n Complex({}, LegendItemStyle)\n ], SmithchartLegendSettings.prototype, \"itemStyle\", void 0);\n __decorate([\n Complex({}, LegendBorder)\n ], SmithchartLegendSettings.prototype, \"border\", void 0);\n __decorate([\n Complex(Theme.legendLabelFont, SmithchartFont)\n ], SmithchartLegendSettings.prototype, \"textStyle\", void 0);\n return SmithchartLegendSettings;\n}(ChildProperty));\nexport { SmithchartLegendSettings };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { SmithchartFont } from '../utils/utils';\nimport { Theme } from '../model/theme';\n/**\n * Configures the major Grid lines in the `axis`.\n */\nvar SmithchartMajorGridLines = /** @class */ (function (_super) {\n __extends(SmithchartMajorGridLines, _super);\n function SmithchartMajorGridLines() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], SmithchartMajorGridLines.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], SmithchartMajorGridLines.prototype, \"dashArray\", void 0);\n __decorate([\n Property(true)\n ], SmithchartMajorGridLines.prototype, \"visible\", void 0);\n __decorate([\n Property(1)\n ], SmithchartMajorGridLines.prototype, \"opacity\", void 0);\n return SmithchartMajorGridLines;\n}(ChildProperty));\nexport { SmithchartMajorGridLines };\n/**\n * Configures the major grid lines in the `axis`.\n */\nvar SmithchartMinorGridLines = /** @class */ (function (_super) {\n __extends(SmithchartMinorGridLines, _super);\n function SmithchartMinorGridLines() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], SmithchartMinorGridLines.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], SmithchartMinorGridLines.prototype, \"dashArray\", void 0);\n __decorate([\n Property(false)\n ], SmithchartMinorGridLines.prototype, \"visible\", void 0);\n __decorate([\n Property(8)\n ], SmithchartMinorGridLines.prototype, \"count\", void 0);\n return SmithchartMinorGridLines;\n}(ChildProperty));\nexport { SmithchartMinorGridLines };\n/**\n * Configures the axis lines in the `axis`.\n */\nvar SmithchartAxisLine = /** @class */ (function (_super) {\n __extends(SmithchartAxisLine, _super);\n function SmithchartAxisLine() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], SmithchartAxisLine.prototype, \"visible\", void 0);\n __decorate([\n Property(1)\n ], SmithchartAxisLine.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], SmithchartAxisLine.prototype, \"dashArray\", void 0);\n return SmithchartAxisLine;\n}(ChildProperty));\nexport { SmithchartAxisLine };\nvar SmithchartAxis = /** @class */ (function (_super) {\n __extends(SmithchartAxis, _super);\n function SmithchartAxis() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], SmithchartAxis.prototype, \"visible\", void 0);\n __decorate([\n Property('Outside')\n ], SmithchartAxis.prototype, \"labelPosition\", void 0);\n __decorate([\n Property('Hide')\n ], SmithchartAxis.prototype, \"labelIntersectAction\", void 0);\n __decorate([\n Complex({}, SmithchartMajorGridLines)\n ], SmithchartAxis.prototype, \"majorGridLines\", void 0);\n __decorate([\n Complex({}, SmithchartMinorGridLines)\n ], SmithchartAxis.prototype, \"minorGridLines\", void 0);\n __decorate([\n Complex({}, SmithchartAxisLine)\n ], SmithchartAxis.prototype, \"axisLine\", void 0);\n __decorate([\n Complex(Theme.axisLabelFont, SmithchartFont)\n ], SmithchartAxis.prototype, \"labelStyle\", void 0);\n return SmithchartAxis;\n}(ChildProperty));\nexport { SmithchartAxis };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { SmithchartFont } from '../utils/utils';\nimport { Theme } from '../model/theme';\nvar Subtitle = /** @class */ (function (_super) {\n __extends(Subtitle, _super);\n function Subtitle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], Subtitle.prototype, \"visible\", void 0);\n __decorate([\n Property('')\n ], Subtitle.prototype, \"text\", void 0);\n __decorate([\n Property('')\n ], Subtitle.prototype, \"description\", void 0);\n __decorate([\n Property('Far')\n ], Subtitle.prototype, \"textAlignment\", void 0);\n __decorate([\n Property(true)\n ], Subtitle.prototype, \"enableTrim\", void 0);\n __decorate([\n Property(null)\n ], Subtitle.prototype, \"maximumWidth\", void 0);\n __decorate([\n Complex(Theme.smithchartSubtitleFont, SmithchartFont)\n ], Subtitle.prototype, \"textStyle\", void 0);\n return Subtitle;\n}(ChildProperty));\nexport { Subtitle };\nvar Title = /** @class */ (function (_super) {\n __extends(Title, _super);\n function Title() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], Title.prototype, \"visible\", void 0);\n __decorate([\n Property('')\n ], Title.prototype, \"text\", void 0);\n __decorate([\n Property('')\n ], Title.prototype, \"description\", void 0);\n __decorate([\n Property('Center')\n ], Title.prototype, \"textAlignment\", void 0);\n __decorate([\n Property(true)\n ], Title.prototype, \"enableTrim\", void 0);\n __decorate([\n Property(null)\n ], Title.prototype, \"maximumWidth\", void 0);\n __decorate([\n Complex({}, Subtitle)\n ], Title.prototype, \"subtitle\", void 0);\n __decorate([\n Complex(Theme.smithchartTitleFont, SmithchartFont)\n ], Title.prototype, \"font\", void 0);\n __decorate([\n Complex(Theme.smithchartTitleFont, SmithchartFont)\n ], Title.prototype, \"textStyle\", void 0);\n return Title;\n}(ChildProperty));\nexport { Title };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { SmithchartFont } from '../utils/utils';\nimport { Theme } from '../model/theme';\nvar SeriesTooltipBorder = /** @class */ (function (_super) {\n __extends(SeriesTooltipBorder, _super);\n function SeriesTooltipBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], SeriesTooltipBorder.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], SeriesTooltipBorder.prototype, \"color\", void 0);\n return SeriesTooltipBorder;\n}(ChildProperty));\nexport { SeriesTooltipBorder };\nvar SeriesTooltip = /** @class */ (function (_super) {\n __extends(SeriesTooltip, _super);\n function SeriesTooltip() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], SeriesTooltip.prototype, \"visible\", void 0);\n __decorate([\n Property(null)\n ], SeriesTooltip.prototype, \"fill\", void 0);\n __decorate([\n Property(0.95)\n ], SeriesTooltip.prototype, \"opacity\", void 0);\n __decorate([\n Property('')\n ], SeriesTooltip.prototype, \"template\", void 0);\n __decorate([\n Complex({}, SeriesTooltipBorder)\n ], SeriesTooltip.prototype, \"border\", void 0);\n return SeriesTooltip;\n}(ChildProperty));\nexport { SeriesTooltip };\nvar SeriesMarkerBorder = /** @class */ (function (_super) {\n __extends(SeriesMarkerBorder, _super);\n function SeriesMarkerBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(3)\n ], SeriesMarkerBorder.prototype, \"width\", void 0);\n __decorate([\n Property('white')\n ], SeriesMarkerBorder.prototype, \"color\", void 0);\n return SeriesMarkerBorder;\n}(ChildProperty));\nexport { SeriesMarkerBorder };\nvar SeriesMarkerDataLabelBorder = /** @class */ (function (_super) {\n __extends(SeriesMarkerDataLabelBorder, _super);\n function SeriesMarkerDataLabelBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0.1)\n ], SeriesMarkerDataLabelBorder.prototype, \"width\", void 0);\n __decorate([\n Property('white')\n ], SeriesMarkerDataLabelBorder.prototype, \"color\", void 0);\n return SeriesMarkerDataLabelBorder;\n}(ChildProperty));\nexport { SeriesMarkerDataLabelBorder };\nvar SeriesMarkerDataLabelConnectorLine = /** @class */ (function (_super) {\n __extends(SeriesMarkerDataLabelConnectorLine, _super);\n function SeriesMarkerDataLabelConnectorLine() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(1)\n ], SeriesMarkerDataLabelConnectorLine.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], SeriesMarkerDataLabelConnectorLine.prototype, \"color\", void 0);\n return SeriesMarkerDataLabelConnectorLine;\n}(ChildProperty));\nexport { SeriesMarkerDataLabelConnectorLine };\nvar SeriesMarkerDataLabel = /** @class */ (function (_super) {\n __extends(SeriesMarkerDataLabel, _super);\n function SeriesMarkerDataLabel() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], SeriesMarkerDataLabel.prototype, \"visible\", void 0);\n __decorate([\n Property('')\n ], SeriesMarkerDataLabel.prototype, \"template\", void 0);\n __decorate([\n Property(null)\n ], SeriesMarkerDataLabel.prototype, \"fill\", void 0);\n __decorate([\n Property(1)\n ], SeriesMarkerDataLabel.prototype, \"opacity\", void 0);\n __decorate([\n Complex({}, SeriesMarkerDataLabelBorder)\n ], SeriesMarkerDataLabel.prototype, \"border\", void 0);\n __decorate([\n Complex({}, SeriesMarkerDataLabelConnectorLine)\n ], SeriesMarkerDataLabel.prototype, \"connectorLine\", void 0);\n __decorate([\n Complex(Theme.dataLabelFont, SmithchartFont)\n ], SeriesMarkerDataLabel.prototype, \"textStyle\", void 0);\n return SeriesMarkerDataLabel;\n}(ChildProperty));\nexport { SeriesMarkerDataLabel };\nvar SeriesMarker = /** @class */ (function (_super) {\n __extends(SeriesMarker, _super);\n function SeriesMarker() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], SeriesMarker.prototype, \"visible\", void 0);\n __decorate([\n Property('circle')\n ], SeriesMarker.prototype, \"shape\", void 0);\n __decorate([\n Property(6)\n ], SeriesMarker.prototype, \"width\", void 0);\n __decorate([\n Property(6)\n ], SeriesMarker.prototype, \"height\", void 0);\n __decorate([\n Property('')\n ], SeriesMarker.prototype, \"imageUrl\", void 0);\n __decorate([\n Property('')\n ], SeriesMarker.prototype, \"fill\", void 0);\n __decorate([\n Property(1)\n ], SeriesMarker.prototype, \"opacity\", void 0);\n __decorate([\n Complex({}, SeriesMarkerBorder)\n ], SeriesMarker.prototype, \"border\", void 0);\n __decorate([\n Complex({}, SeriesMarkerDataLabel)\n ], SeriesMarker.prototype, \"dataLabel\", void 0);\n return SeriesMarker;\n}(ChildProperty));\nexport { SeriesMarker };\nvar SmithchartSeries = /** @class */ (function (_super) {\n __extends(SmithchartSeries, _super);\n function SmithchartSeries() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('visible')\n ], SmithchartSeries.prototype, \"visibility\", void 0);\n __decorate([\n Property([])\n ], SmithchartSeries.prototype, \"points\", void 0);\n __decorate([\n Property('')\n ], SmithchartSeries.prototype, \"resistance\", void 0);\n __decorate([\n Property('')\n ], SmithchartSeries.prototype, \"reactance\", void 0);\n __decorate([\n Property(null)\n ], SmithchartSeries.prototype, \"dataSource\", void 0);\n __decorate([\n Property('')\n ], SmithchartSeries.prototype, \"name\", void 0);\n __decorate([\n Property(null)\n ], SmithchartSeries.prototype, \"fill\", void 0);\n __decorate([\n Property(false)\n ], SmithchartSeries.prototype, \"enableAnimation\", void 0);\n __decorate([\n Property('2000ms')\n ], SmithchartSeries.prototype, \"animationDuration\", void 0);\n __decorate([\n Property(false)\n ], SmithchartSeries.prototype, \"enableSmartLabels\", void 0);\n __decorate([\n Property(1)\n ], SmithchartSeries.prototype, \"width\", void 0);\n __decorate([\n Property(1)\n ], SmithchartSeries.prototype, \"opacity\", void 0);\n __decorate([\n Complex({}, SeriesMarker)\n ], SmithchartSeries.prototype, \"marker\", void 0);\n __decorate([\n Complex({}, SeriesTooltip)\n ], SmithchartSeries.prototype, \"tooltip\", void 0);\n return SmithchartSeries;\n}(ChildProperty));\nexport { SmithchartSeries };\n","import { measureText } from '../../smithchart/utils/helper';\n/* tslint:disable:no-string-literal */\nvar AreaBounds = /** @class */ (function () {\n function AreaBounds() {\n }\n AreaBounds.prototype.calculateAreaBounds = function (smithchart, title, bounds) {\n var x;\n var y;\n var width;\n var height;\n var rightSpace;\n var margin = smithchart.margin;\n var border = smithchart.border;\n var spaceValue = this.getLegendSpace(smithchart, bounds);\n x = spaceValue['leftLegendWidth'] + margin.left + border.width;\n rightSpace = spaceValue['rightLegendWidth'] + margin.left + margin.right + (2 * border.width);\n width = smithchart.availableSize['width'] - (x + rightSpace);\n y = margin['top'] + (2 * smithchart.elementSpacing) + spaceValue['modelTitleHeight'] +\n spaceValue['modelsubTitleHeight'] + spaceValue['topLegendHeight'] + border.width;\n height = smithchart.availableSize['height'] - (spaceValue['modelTitleHeight'] +\n (2 * smithchart.elementSpacing) + spaceValue['modelsubTitleHeight'] + margin['top'] +\n spaceValue['topLegendHeight'] + spaceValue['bottomLegendHeight']);\n return { x: x, y: y, width: width, height: height };\n };\n AreaBounds.prototype.getLegendSpace = function (smithchart, bounds) {\n var title = smithchart.title;\n var legend = smithchart.legendSettings;\n var position = legend.position.toLowerCase();\n var subtitleHeight = 0;\n var modelsubTitleHeight = 0;\n var titleHeight = 0;\n var font = smithchart.font;\n var modelTitleHeight = 0;\n var itemPadding = 10;\n var legendBorder = legend.border.width;\n var leftLegendWidth = 0;\n var rightLegendWidth = 0;\n var topLegendHeight = 0;\n var bottomLegendHeight = 0;\n var ltheight = 0;\n var space;\n if (legend['visible']) {\n space = (bounds.width + (itemPadding / 2) + smithchart.elementSpacing + (2 * legendBorder));\n leftLegendWidth = position === 'left' ? space : 0;\n rightLegendWidth = position === 'right' ? space : 0;\n ltheight = legend['title'].visible ? measureText(legend['title'].text, font)['height'] : 0;\n topLegendHeight = position === 'top' ? smithchart.elementSpacing + bounds.height + ltheight : 0;\n bottomLegendHeight = position === 'bottom' ? smithchart.elementSpacing + bounds.height + ltheight : 0;\n }\n subtitleHeight = measureText(title.subtitle.text, font)['height'];\n modelTitleHeight = (title.text === '' || !title['visible']) ? 0 : (titleHeight);\n modelsubTitleHeight = (title['subtitle'].text === '' || !title['subtitle'].visible) ? 0 : (subtitleHeight);\n return {\n leftLegendWidth: leftLegendWidth, rightLegendWidth: rightLegendWidth,\n topLegendHeight: topLegendHeight, bottomLegendHeight: bottomLegendHeight,\n modelTitleHeight: modelTitleHeight, modelsubTitleHeight: modelsubTitleHeight\n };\n };\n return AreaBounds;\n}());\nexport { AreaBounds };\n","import { measureText } from '../../smithchart/utils/helper';\nimport { HorizontalLabelCollection, LabelRegion, Point, Direction } from '../../smithchart/utils/utils';\nimport { GridArcPoints, RadialLabelCollections } from '../../smithchart/utils/utils';\nimport { PathOption, TextOption, renderTextElement, _getEpsilonValue } from '../../smithchart/utils/helper';\n/* tslint:disable:no-string-literal */\nvar AxisRender = /** @class */ (function () {\n function AxisRender() {\n this.radialLabels = [-50, -20, -10, -5, -4, -3, -2, -1.5, -1, -0.8, -0.6, -0.4, -0.2,\n 0, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2, 3, 4, 5, 10, 20, 50];\n this.radialLabelCollections = [];\n this.horizontalLabelCollections = [];\n this.labelCollections = [];\n this.direction = new Direction();\n }\n AxisRender.prototype.renderArea = function (smithchart, bounds) {\n this.calculateChartArea(smithchart, bounds);\n this.calculateCircleMargin(smithchart, bounds);\n this.calculateXAxisRange(smithchart);\n this.calculateRAxisRange(smithchart);\n this.measureHorizontalAxis(smithchart);\n this.measureRadialAxis(smithchart);\n if (smithchart.horizontalAxis.visible) {\n this.updateHAxis(smithchart);\n }\n if (smithchart.radialAxis.visible) {\n this.updateRAxis(smithchart);\n }\n if (smithchart.horizontalAxis.visible) {\n this.drawHAxisLabels(smithchart);\n }\n if (smithchart.radialAxis.visible) {\n this.drawRAxisLabels(smithchart);\n }\n };\n AxisRender.prototype.updateHAxis = function (smithchart) {\n var majorGridLines = smithchart.horizontalAxis.majorGridLines;\n var minorGridLines = smithchart.horizontalAxis.minorGridLines;\n var axisLine = smithchart.horizontalAxis.axisLine;\n if (majorGridLines.visible) {\n this.updateHMajorGridLines(smithchart);\n }\n if (minorGridLines.visible) {\n this.updateHMinorGridLines(smithchart);\n }\n if (axisLine.visible) {\n this.updateHAxisLine(smithchart);\n }\n };\n AxisRender.prototype.updateRAxis = function (smithchart) {\n var majorGridLines = smithchart.radialAxis.majorGridLines;\n var minorGridLines = smithchart.radialAxis.minorGridLines;\n var axisLine = smithchart.radialAxis.axisLine;\n if (majorGridLines.visible) {\n this.updateRMajorGridLines(smithchart);\n }\n if (minorGridLines.visible) {\n this.updateRMinorGridLines(smithchart);\n }\n if (axisLine.visible) {\n this.updateRAxisLine(smithchart);\n }\n };\n AxisRender.prototype.measureHorizontalAxis = function (smithchart) {\n var majorGridLines = smithchart.horizontalAxis.majorGridLines;\n var minorGridLines = smithchart.horizontalAxis.minorGridLines;\n this.measureHMajorGridLines(smithchart);\n if (minorGridLines.visible) {\n this.measureHMinorGridLines(smithchart);\n }\n };\n AxisRender.prototype.measureRadialAxis = function (smithchart) {\n var majorGridLines = smithchart.radialAxis.majorGridLines;\n var minorGridLines = smithchart.radialAxis.minorGridLines;\n this.measureRMajorGridLines(smithchart);\n if (minorGridLines.visible) {\n this.measureRMinorGridLines(smithchart);\n }\n };\n AxisRender.prototype.calculateChartArea = function (smithchart, bounds) {\n var chartAreaWidth;\n var chartAreaHeight;\n var width = smithchart.availableSize.width;\n var height = smithchart.availableSize.height;\n var x;\n var y;\n width = bounds.width;\n height = bounds.height;\n chartAreaWidth = Math.min(width, height);\n chartAreaHeight = Math.min(width, height);\n x = bounds.x + (bounds.width / 2 - chartAreaWidth / 2);\n y = bounds.y + ((height - chartAreaHeight) / 2 > 0 ? (height - chartAreaHeight) / 2 : 0);\n smithchart.chartArea = { x: x, y: y, width: chartAreaWidth, height: chartAreaHeight };\n };\n AxisRender.prototype.calculateCircleMargin = function (smithchart, bounds) {\n var padding = 10;\n var maxLabelWidth = 0;\n var width = smithchart.chartArea.width;\n var radius = smithchart.radius;\n maxLabelWidth = this.maximumLabelLength(smithchart);\n var labelMargin = (smithchart.radialAxis.labelPosition === 'Outside') ? (maxLabelWidth + padding) : padding;\n var diameter = width - labelMargin * 2 > 0 ? width - labelMargin * 2 : 0;\n var actualRadius = diameter / 2;\n var circleCoefficient = radius > 1 ? 1 : (radius < 0.1 ? 0.1 : radius);\n this.areaRadius = actualRadius * circleCoefficient;\n this.circleLeftX = smithchart.chartArea.x + labelMargin + (actualRadius * (1 - circleCoefficient));\n this.circleTopY = smithchart.chartArea.y + labelMargin + (actualRadius * (1 - circleCoefficient));\n this.circleCenterX = this.circleLeftX + this.areaRadius;\n this.circleCenterY = bounds.y + bounds.height / 2;\n };\n AxisRender.prototype.maximumLabelLength = function (smithchart) {\n var maximumLabelLength = 0;\n var font = smithchart.horizontalAxis.labelStyle;\n var label;\n var textSize;\n for (var i = 0; i < this.radialLabels.length; i++) {\n label = this.radialLabels[i].toString();\n textSize = measureText(label, font);\n if (maximumLabelLength < textSize.width) {\n maximumLabelLength = textSize.width;\n }\n }\n return maximumLabelLength;\n };\n AxisRender.prototype.calculateAxisLabels = function () {\n var spacingBetweenGridLines = 30;\n var previousR = 0;\n var j = 0;\n var labels = [];\n var diameter = this.areaRadius * 2;\n for (var i = 0; i < 2; i = i + 0.1) {\n i = Math.round(i * 10) / 10;\n var coeff = 1 / (i + 1);\n var isOverlap1 = false;\n var isOverlap2 = false;\n var radius = ((diameter * coeff) / 2) * 2;\n if (previousR === 0.0 || i === 1) {\n previousR = radius;\n labels[j] = i;\n j++;\n continue;\n }\n if (i < 1) {\n isOverlap1 = this.isOverlap(1, diameter, radius, spacingBetweenGridLines);\n }\n if (i > 1) {\n isOverlap2 = this.isOverlap(2, diameter, radius, spacingBetweenGridLines);\n }\n if (isOverlap1 || isOverlap2) {\n continue;\n }\n if (previousR - radius >= spacingBetweenGridLines) {\n labels[j] = i;\n j++;\n previousR = radius;\n }\n }\n var staticlabels = [2, 3, 4, 5, 10, 20, 50];\n for (var k = 0; k < staticlabels.length; k++) {\n labels[j] = staticlabels[k];\n j++;\n }\n return labels;\n };\n AxisRender.prototype.isOverlap = function (x, d, previousR, spacingBetweenGridLines) {\n var coeff;\n var radius;\n coeff = 1 / (x + 1); // (1 / 1+r) find the radius for the x value\n radius = ((d * coeff) / 2) * 2;\n return previousR - radius < spacingBetweenGridLines;\n };\n AxisRender.prototype.calculateXAxisRange = function (smithchart) {\n var previousR = 0;\n var x;\n var coeff;\n var radius;\n var cx;\n var diameter = this.areaRadius * 2;\n var horizontalAxisLabels = this.calculateAxisLabels();\n var cy = this.circleCenterY;\n var circleStartX = this.circleLeftX;\n var leftX = this.circleLeftX;\n for (var i = 0; i < horizontalAxisLabels.length; i++) {\n x = horizontalAxisLabels[i];\n coeff = 1 / (x + 1);\n radius = (diameter * coeff) / 2;\n if (smithchart.renderType === 'Impedance') {\n leftX = circleStartX + diameter - (radius * 2);\n }\n cx = leftX + radius;\n this.horizontalLabelCollections.push({\n centerX: cx, centerY: cy, radius: radius, value: x, region: null\n });\n }\n };\n AxisRender.prototype.calculateRAxisRange = function (smithchart) {\n var arcCy;\n var arcRadius;\n var diameter = this.areaRadius * 2;\n var y;\n var point = new Point();\n if (smithchart.renderType === 'Impedance') {\n point.x = this.circleLeftX + diameter;\n point.y = this.circleTopY + this.areaRadius;\n }\n else {\n point.x = this.circleLeftX;\n point.y = this.circleTopY + this.areaRadius;\n }\n for (var i = 0; i < this.radialLabels.length; i++) {\n y = this.radialLabels[i];\n arcRadius = Math.abs(((1 / y) * diameter) / 2);\n if (smithchart.renderType === 'Impedance') {\n arcCy = y > 0 ? point.y - arcRadius : point.y + arcRadius;\n }\n else {\n arcCy = y < 0 ? point.y - arcRadius : point.y + arcRadius;\n }\n this.radialLabelCollections.push({\n centerX: point.x, centerY: arcCy, radius: arcRadius, value: y\n });\n }\n };\n AxisRender.prototype.measureHMajorGridLines = function (smithchart) {\n var arcPoints = [];\n var startPoint;\n var endPoint;\n var radialPoint1;\n var radialPoint2;\n var size;\n this.majorHGridArcPoints = [];\n for (var i = 0; i < this.horizontalLabelCollections.length; i++) {\n var circlePoint = new HorizontalLabelCollection();\n circlePoint = this.horizontalLabelCollections[i];\n arcPoints = this.calculateHMajorArcStartEndPoints(circlePoint.value);\n if (smithchart.renderType === 'Impedance') {\n radialPoint1 = arcPoints[0];\n radialPoint2 = arcPoints[1];\n }\n else {\n radialPoint1 = arcPoints[1];\n radialPoint2 = arcPoints[0];\n }\n size = { width: circlePoint.radius, height: circlePoint.radius };\n if (circlePoint.value !== 0.0 && circlePoint.value !== 50.0) {\n startPoint = this.intersectingCirclePoints(radialPoint1[0].centerX, radialPoint1[0].centerY, radialPoint1[0].radius, circlePoint.centerX, circlePoint.centerY, circlePoint.radius, smithchart.renderType);\n endPoint = this.intersectingCirclePoints(radialPoint2[0].centerX, radialPoint2[0].centerY, radialPoint2[0].radius, circlePoint.centerX, circlePoint.centerY, circlePoint.radius, smithchart.renderType);\n this.majorHGridArcPoints.push({\n startPoint: startPoint,\n endPoint: endPoint,\n rotationAngle: 2 * Math.PI,\n sweepDirection: (smithchart.renderType === 'Impedance') ?\n this.direction['counterclockwise'] : this.direction['clockwise'],\n isLargeArc: true,\n size: size\n });\n }\n else {\n startPoint = { x: circlePoint.centerX + circlePoint.radius, y: circlePoint.centerY };\n endPoint = { x: circlePoint.centerX + circlePoint.radius, y: circlePoint.centerY - 0.05 };\n this.majorHGridArcPoints.push({\n startPoint: startPoint,\n endPoint: endPoint,\n rotationAngle: 2 * Math.PI,\n sweepDirection: this.direction['clockwise'],\n isLargeArc: true,\n size: size\n });\n }\n }\n };\n AxisRender.prototype.measureRMajorGridLines = function (smithchart) {\n var epsilon;\n var radialPoint;\n var y;\n var arcPoints = [];\n var innerInterSectPoint;\n var outerInterSectPoint;\n var outterInterSectRadian;\n var outterInterSectAngle;\n var startPoint;\n var endPoint;\n var size;\n var sweepDirection;\n this.majorRGridArcPoints = [];\n this.labelCollections = [];\n epsilon = _getEpsilonValue();\n for (var i = 0; i < this.radialLabelCollections.length; i++) {\n radialPoint = this.radialLabelCollections[i];\n if (radialPoint.radius <= epsilon) {\n continue;\n }\n y = radialPoint.value;\n arcPoints = this.calculateMajorArcStartEndPoints(radialPoint, Math.abs(y), smithchart);\n innerInterSectPoint = arcPoints[0];\n outerInterSectPoint = arcPoints[1];\n outterInterSectRadian = this.circleXYRadianValue(this.circleCenterX, this.circleCenterY, outerInterSectPoint.x, outerInterSectPoint.y);\n outterInterSectAngle = outterInterSectRadian * (180 / Math.PI);\n if (y !== 0.0) {\n startPoint = { x: innerInterSectPoint.x, y: innerInterSectPoint.y };\n endPoint = { x: outerInterSectPoint.x, y: outerInterSectPoint.y };\n size = { width: radialPoint.radius, height: radialPoint.radius };\n sweepDirection = y > 0 ? this.direction['clockwise'] : this.direction['counterclockwise'];\n this.majorRGridArcPoints.push({\n startPoint: startPoint,\n endPoint: endPoint,\n size: size,\n rotationAngle: 2 * Math.PI,\n isLargeArc: false,\n sweepDirection: sweepDirection\n });\n this.labelCollections.push({\n centerX: outerInterSectPoint.x,\n centerY: outerInterSectPoint.y,\n angle: outterInterSectAngle,\n value: y,\n radius: this.areaRadius,\n region: null\n });\n }\n else {\n startPoint = { x: this.circleLeftX, y: this.circleCenterY };\n endPoint = { x: this.circleCenterX + this.areaRadius, y: this.circleCenterY };\n this.majorRGridArcPoints.push({\n startPoint: startPoint,\n endPoint: endPoint,\n size: null,\n rotationAngle: null,\n isLargeArc: null,\n sweepDirection: null\n });\n this.labelCollections.push({\n centerX: (smithchart.renderType === 'Impedance') ?\n (this.circleCenterX - this.areaRadius) : (this.circleCenterX + this.areaRadius),\n centerY: this.circleCenterY,\n angle: (smithchart.renderType === 'Impedance') ?\n 180 : 360,\n value: y,\n radius: this.areaRadius,\n region: null\n });\n }\n }\n };\n AxisRender.prototype.circleXYRadianValue = function (centerX, centerY, outterX, outterY) {\n var radian;\n radian = Math.atan2(outterY - centerY, outterX - centerX);\n radian = radian < 0 ? (radian + (360 * Math.PI / 180)) : radian;\n return radian;\n };\n AxisRender.prototype.calculateMajorArcStartEndPoints = function (radialPoint, value, smithchart) {\n var arcPoints = [];\n var circlePoint = [];\n var cx;\n var cy;\n cx = this.circleCenterX;\n cy = this.circleCenterY;\n if (value >= 10) {\n arcPoints[0] = (smithchart.renderType === 'Impedance') ?\n { x: cx + this.areaRadius, y: cy } : { x: cx - this.areaRadius, y: cy };\n }\n else if (value >= 3) {\n circlePoint = this.horizontalLabelCollections.filter(function (c) { return c.value === 10; });\n }\n else if (value >= 1) {\n circlePoint = this.horizontalLabelCollections.filter(function (c) { return c.value === 5; });\n }\n else {\n circlePoint = this.horizontalLabelCollections.filter(function (c) { return c.value === 3; });\n }\n if (circlePoint.length > 0) {\n arcPoints[0] = this.intersectingCirclePoints(radialPoint.centerX, radialPoint.centerY, radialPoint.radius, circlePoint[0].centerX, circlePoint[0].centerY, circlePoint[0].radius, smithchart.renderType);\n }\n arcPoints[1] = this.intersectingCirclePoints(radialPoint.centerX, radialPoint.centerY, radialPoint.radius, cx, cy, this.areaRadius, smithchart.renderType);\n return arcPoints;\n };\n AxisRender.prototype.calculateHMajorArcStartEndPoints = function (value) {\n var arcHPoints = [];\n var calValue1;\n var calValue2;\n if (value <= 0.3) {\n calValue1 = 2.0;\n calValue2 = -2.0;\n }\n else if (value <= 1.0) {\n calValue1 = 3.0;\n calValue2 = -3.0;\n }\n else if (value <= 2.0) {\n calValue1 = 5.0;\n calValue2 = -5.0;\n }\n else if (value <= 5.0) {\n calValue1 = 10.0;\n calValue2 = -10.0;\n }\n else {\n calValue1 = 50.0;\n calValue2 = -50.0;\n }\n arcHPoints[0] = this.radialLabelCollections.filter(function (c) { return c.value === calValue1; });\n arcHPoints[1] = this.radialLabelCollections.filter(function (c) { return c.value === calValue2; });\n return arcHPoints;\n };\n AxisRender.prototype.calculateMinorArcStartEndPoints = function (value) {\n var calValue1;\n var calValue2;\n var marcHPoints = [];\n if (value <= 0.1) {\n calValue1 = 1.0;\n calValue2 = -1.0;\n }\n else if (value <= 0.2) {\n calValue1 = 0.8;\n calValue2 = -0.8;\n }\n else if (value <= 0.3) {\n calValue1 = 0.4;\n calValue2 = -0.4;\n }\n else if (value <= 0.6) {\n calValue1 = 1.0;\n calValue2 = -1.0;\n }\n else if (value <= 1.0) {\n calValue1 = 1.5;\n calValue2 = -1.5;\n }\n else if (value <= 1.5) {\n calValue1 = 2.0;\n calValue2 = -2.0;\n }\n else if (value <= 2.0) {\n calValue1 = 1.0;\n calValue2 = -1.0;\n }\n else if (value <= 5.0) {\n calValue1 = 3.0;\n calValue2 = -3.0;\n }\n else {\n calValue1 = 10.0;\n calValue2 = -10.0;\n }\n marcHPoints[0] = this.radialLabelCollections.filter(function (c) { return c['value'] === calValue1; });\n marcHPoints[1] = this.radialLabelCollections.filter(function (c) { return c['value'] === calValue2; });\n return marcHPoints;\n };\n AxisRender.prototype.intersectingCirclePoints = function (x1, y1, r1, x2, y2, r2, renderType) {\n var cx;\n var cy;\n var midRadius;\n var radiusSquare;\n var a;\n var radiusSquare2;\n var c;\n var fx;\n var gx;\n var ix1;\n var ix2;\n var fy;\n var gy;\n var iy1;\n var iy2;\n var point = { x: 0, y: 0 };\n cx = x1 - x2;\n cy = y1 - y2;\n midRadius = Math.sqrt(cx * cx + cy * cy);\n radiusSquare = midRadius * midRadius;\n a = (r1 * r1 - r2 * r2) / (2 * radiusSquare);\n radiusSquare2 = (r1 * r1 - r2 * r2);\n c = Math.sqrt(2 * (r1 * r1 + r2 * r2) / radiusSquare - (radiusSquare2 * radiusSquare2) / (radiusSquare * radiusSquare) - 1);\n fx = (x1 + x2) / 2 + a * (x2 - x1);\n gx = c * (y2 - y1) / 2;\n ix1 = fx + gx;\n ix2 = fx - gx;\n fy = (y1 + y2) / 2 + a * (y2 - y1);\n gy = c * (x1 - x2) / 2;\n iy1 = fy + gy;\n iy2 = fy - gy;\n if (renderType === 'Impedance') {\n if (ix2 < ix1) {\n point.x = ix2;\n point.y = iy2;\n }\n else {\n point.x = ix1;\n point.y = iy1;\n }\n }\n else {\n if (ix1 > ix2) {\n point.x = ix1;\n point.y = iy1;\n }\n else {\n point.x = ix2;\n point.y = iy2;\n }\n }\n return { x: point.x, y: point.y };\n };\n AxisRender.prototype.updateHMajorGridLines = function (smithchart) {\n var majorGridLine = smithchart.horizontalAxis.majorGridLines;\n var groupElement;\n var element;\n var path;\n groupElement = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_horizontalAxisMajorGridLines' });\n path = this.calculateGridLinesPath(this.majorHGridArcPoints);\n var haxismgoptions = new PathOption(smithchart.element.id + '_horizontalAxisMajorGridLines', 'none', majorGridLine['width'], smithchart.themeStyle.majorGridLine, majorGridLine['opacity'], majorGridLine['dashArray'], path);\n element = smithchart.renderer.drawPath(haxismgoptions);\n groupElement.appendChild(element);\n smithchart.svgObject.appendChild(groupElement);\n };\n AxisRender.prototype.updateRMajorGridLines = function (smithchart) {\n var majorGridLine = smithchart.radialAxis.majorGridLines;\n var groupElement;\n var element;\n var path;\n groupElement = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_radialAxisMajorGridLines' });\n path = this.calculateGridLinesPath(this.majorRGridArcPoints);\n var raxismgoptions = new PathOption(smithchart.element.id + '_radialAxisMajorGridLines', 'none', majorGridLine['width'], smithchart.themeStyle.majorGridLine, majorGridLine['opacity'], majorGridLine['dashArray'], path);\n element = smithchart.renderer.drawPath(raxismgoptions);\n groupElement.appendChild(element);\n smithchart.svgObject.appendChild(groupElement);\n };\n AxisRender.prototype.updateHAxisLine = function (smithchart) {\n var radius = this.areaRadius;\n var point1;\n var point2;\n var size;\n var sweep;\n var isLargeArc;\n var angle;\n var axisLine = smithchart.horizontalAxis.axisLine;\n var direction;\n var groupElement = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_hAxisLine' });\n point1 = { x: this.circleCenterX + radius, y: this.circleCenterY };\n point2 = { x: this.circleCenterX + radius, y: (this.circleCenterY - 0.05) };\n size = { width: radius, height: radius };\n sweep = this.direction['clockwise'];\n isLargeArc = 1;\n angle = Math.PI * 2;\n direction = 'M' + '' + point1.x + ' ' + point1.y + ' ' + 'A' + ' ' + size.width +\n ' ' + size.height + ' ' + angle + ' ' + isLargeArc + ' ' + sweep + ' ' + point2.x + ' ' + point2.y + '';\n var options = new PathOption(smithchart.element.id + '_horizontalAxisLine', 'none', axisLine.width, smithchart.themeStyle.axisLine, 1, axisLine.dashArray, direction);\n var element = smithchart.renderer.drawPath(options);\n groupElement.appendChild(element);\n smithchart.svgObject.appendChild(groupElement);\n };\n AxisRender.prototype.updateRAxisLine = function (smithchart) {\n var radius = this.areaRadius;\n var point1;\n var point2;\n var size;\n var sweep;\n var isLargeArc;\n var angle;\n var axisLine = smithchart.radialAxis.axisLine;\n var direction;\n point1 = { x: this.circleCenterX - radius, y: this.circleCenterY };\n point2 = { x: this.circleCenterX + radius, y: this.circleCenterY };\n size = { width: 0, height: 0 };\n sweep = this.direction['counterclockwise'];\n isLargeArc = 0;\n angle = 0;\n direction = 'M' + ' ' + point1.x + ' ' + point1.y + ' ' + 'A' + ' ' +\n size.width + ' ' + size.height + ' ' + angle + ' ' + isLargeArc + ' ' + sweep + ' ' +\n point2.x + ' ' + point2.y + '';\n var options = new PathOption(smithchart.element.id + '_radialAxisLine', 'none', axisLine.width, smithchart.themeStyle.axisLine, 1, axisLine.dashArray, direction);\n var groupElement = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_rAxisLine' });\n var element = smithchart.renderer.drawPath(options);\n groupElement.appendChild(element);\n smithchart.svgObject.appendChild(groupElement);\n };\n AxisRender.prototype.drawHAxisLabels = function (smithchart) {\n var hAxis = smithchart.horizontalAxis;\n var font = smithchart.horizontalAxis.labelStyle;\n var circleAxis;\n var label;\n var x;\n var y;\n var textSize;\n var curLabel;\n var curLabelBounds;\n var curWidth;\n var curX;\n var preLabel;\n var preLabelBounds;\n var preWidth;\n var preX;\n var groupEle = smithchart.renderer.createGroup({ id: smithchart.element.id + '_HAxisLabels' });\n for (var i = 0; i < this.horizontalLabelCollections.length; i++) {\n circleAxis = this.horizontalLabelCollections[i];\n label = this.horizontalLabelCollections[i].value.toString();\n if (circleAxis.value !== 0.0) {\n x = (smithchart.renderType === 'Impedance') ?\n circleAxis.centerX - circleAxis.radius : circleAxis.centerX + circleAxis.radius;\n y = circleAxis.centerY;\n textSize = measureText(label, font);\n x = (smithchart.renderType === 'Impedance') ? x - textSize.width : x;\n if (hAxis.labelPosition === 'Outside') {\n y -= textSize.height / 4;\n }\n else {\n y += textSize.height;\n }\n this.horizontalLabelCollections[i].region = this.calculateRegion(label, textSize, x, y);\n if (hAxis.labelIntersectAction === 'Hide') {\n curLabel = this.horizontalLabelCollections[i];\n curLabelBounds = curLabel.region.bounds;\n curWidth = curLabelBounds.width;\n curX = curLabelBounds.x;\n for (var j = 1; j < i; j++) {\n preLabel = this.horizontalLabelCollections[j];\n preLabelBounds = preLabel.region.bounds;\n preWidth = preLabelBounds.width;\n preX = preLabelBounds.x;\n if ((smithchart.renderType === 'Impedance') &&\n (preX + preWidth) > (curX)) {\n label = '';\n }\n if ((smithchart.renderType === 'Admittance') &&\n (preX) < curX + curWidth) {\n label = '';\n }\n }\n }\n var axisLabelRenderEventArgs = { text: label.toString(), x: x, y: y,\n name: 'axisLabelRender', cancel: false };\n smithchart.trigger('axisLabelRender', axisLabelRenderEventArgs);\n var options = new TextOption(smithchart.element.id + '_HLabel_' + i, axisLabelRenderEventArgs.x, axisLabelRenderEventArgs.y, 'none', axisLabelRenderEventArgs.text);\n var element = renderTextElement(options, font, smithchart.themeStyle.axisLabel, groupEle);\n groupEle.appendChild(element);\n }\n }\n smithchart.svgObject.appendChild(groupEle);\n };\n AxisRender.prototype.drawRAxisLabels = function (smithchart) {\n var paddingRadius = 2;\n var font = smithchart.radialAxis.labelStyle;\n var interSectPoint = new RadialLabelCollections();\n var label;\n var textSize;\n var angle;\n var position;\n var textPosition;\n var curX;\n var curY;\n var curWidth;\n var curHeight;\n var curLabel;\n var curLabelBounds;\n var preX;\n var preY;\n var preWidth;\n var preHeight;\n var preLabel;\n var preLabelBounds;\n var rAxis = smithchart.radialAxis;\n var groupEle = smithchart.renderer.createGroup({ id: smithchart.element.id + '_RAxisLabels' });\n for (var i = 0; i < this.labelCollections.length; i++) {\n interSectPoint = this.labelCollections[i];\n label = interSectPoint.value.toString();\n textSize = measureText(label, font);\n angle = Math.round(interSectPoint.angle * 100) / 100;\n if (rAxis.labelPosition === 'Outside') {\n position = this.circlePointPosition(this.circleCenterX, this.circleCenterY, interSectPoint['angle'], this.areaRadius + paddingRadius);\n textPosition = this.setLabelsOutsidePosition(angle, position.x, position.y, textSize);\n }\n else {\n position = this.circlePointPosition(this.circleCenterX, this.circleCenterY, interSectPoint['angle'], this.areaRadius - paddingRadius);\n textPosition = this.setLabelsInsidePosition(angle, position.x, position.y, textSize);\n }\n this.labelCollections[i]['region'] = this.calculateRegion(label, textSize, textPosition.x, textPosition.y);\n if (rAxis.labelIntersectAction === 'Hide') {\n curLabel = this.labelCollections[i];\n curLabelBounds = curLabel['region']['bounds'];\n curWidth = curLabelBounds['width'];\n curHeight = curLabelBounds['height'];\n curX = curLabelBounds['x'];\n curY = curLabelBounds['y'];\n for (var j = 0; j < i; j++) {\n preLabel = this.labelCollections[j];\n preLabelBounds = preLabel['region']['bounds'];\n preWidth = preLabelBounds['width'];\n preHeight = preLabelBounds['height'];\n preX = preLabelBounds['x'];\n preY = preLabelBounds['y'];\n if ((preX <= curX + curWidth) && (curX <= preX + preWidth) && (preY <= curY + curHeight)\n && (curY <= preY + preHeight)) {\n label = ' ';\n }\n }\n }\n var axisLabelRenderEventArgs = { text: label.toString(), x: textPosition.x,\n y: textPosition.y, name: 'axisLabelRender', cancel: false };\n smithchart.trigger('axisLabelRender', axisLabelRenderEventArgs);\n var options = new TextOption(smithchart.element.id + '_RLabel_' + i, axisLabelRenderEventArgs.x, axisLabelRenderEventArgs.y, 'none', axisLabelRenderEventArgs.text);\n var element = renderTextElement(options, font, smithchart.themeStyle.axisLabel, groupEle);\n groupEle.appendChild(element);\n }\n smithchart.svgObject.appendChild(groupEle);\n };\n AxisRender.prototype.calculateRegion = function (label, textSize, textPositionX, textPositionY) {\n var xAxisLabelRegions = new LabelRegion();\n var bounds = { x: textPositionX, y: textPositionY, width: textSize.width, height: textSize.height };\n xAxisLabelRegions = { bounds: bounds, labelText: label };\n return xAxisLabelRegions;\n };\n AxisRender.prototype.updateHMinorGridLines = function (smithchart) {\n var minorGridLine = smithchart.horizontalAxis.minorGridLines;\n var groupElement;\n var element;\n var path;\n groupElement = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_horizontalAxisMinorGridLines' });\n path = this.calculateGridLinesPath(this.minorHGridArcPoints);\n var haxismioptions = new PathOption(smithchart.element.id + '_horizontalAxisMinorGridLines', 'none', minorGridLine['width'], smithchart.themeStyle.minorGridLine, minorGridLine['opacity'], minorGridLine['dashArray'], path);\n element = smithchart.renderer.drawPath(haxismioptions);\n groupElement.appendChild(element);\n smithchart.svgObject.appendChild(groupElement);\n };\n AxisRender.prototype.updateRMinorGridLines = function (smithchart) {\n var minorGridLine = smithchart.radialAxis.minorGridLines;\n var groupElement;\n var element;\n var path;\n groupElement = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_radialAxisMinorGridLines' });\n path = this.calculateGridLinesPath(this.minorGridArcPoints);\n var raxismioptions = new PathOption(smithchart.element.id + '_radialAxisMinorGridLines', 'none', minorGridLine['width'], smithchart.themeStyle.minorGridLine, minorGridLine['opacity'], minorGridLine['dashArray'], path);\n element = smithchart.renderer.drawPath(raxismioptions);\n groupElement.appendChild(element);\n smithchart.svgObject.appendChild(groupElement);\n };\n AxisRender.prototype.calculateGridLinesPath = function (points) {\n var x1;\n var y1;\n var x2;\n var y2;\n var r1;\n var r2;\n var pathSegment = new GridArcPoints();\n var angle;\n var isLargeArc;\n var sweep;\n var sb = '';\n var path;\n for (var i = 0; i < points.length; i++) {\n pathSegment = points[i];\n x1 = pathSegment.startPoint.x;\n y1 = pathSegment.startPoint.y;\n x2 = pathSegment.endPoint.x;\n y2 = pathSegment.endPoint.y;\n r1 = pathSegment.size ? pathSegment.size.width : 0;\n r2 = pathSegment.size ? pathSegment.size.height : 0;\n angle = pathSegment.rotationAngle ? pathSegment.rotationAngle : 0;\n isLargeArc = pathSegment.isLargeArc ? 1 : 0;\n sweep = pathSegment.sweepDirection ? pathSegment.sweepDirection : 0;\n sb = sb + ('M' + ' ' + x1 + ' ' + y1 + ' ' + 'A' + ' ' + r1 + ' ' + r2 + ' ' +\n angle + ' ' + isLargeArc + ' ' + sweep + ' ' + x2 + ' ' + y2 + ' ');\n }\n path = sb.toString();\n return path;\n };\n AxisRender.prototype.measureHMinorGridLines = function (smithchart) {\n var radialPoint1;\n var radialPoint2;\n var k = 0;\n var arcPoints = [];\n var isLargeArc;\n var startPoint;\n var endPoint;\n var size;\n var cx;\n var maxCount = smithchart.horizontalAxis.minorGridLines.count;\n var diameter;\n var previous;\n var next;\n var space;\n var count;\n var interval;\n var radius;\n var leftX;\n this.minorHGridArcPoints = [];\n diameter = this.areaRadius * 2;\n for (var i = 0; i < this.horizontalLabelCollections.length - 3; i++) {\n previous = this.horizontalLabelCollections[i];\n next = this.horizontalLabelCollections[i + 1];\n space = (previous['radius'] - next['radius']) * 2;\n count = Math.floor((maxCount / 100) * space);\n interval = space / count;\n for (var j = 0; j < count; j++) {\n radius = next['radius'] + (j * interval) / 2;\n leftX = (smithchart.renderType === 'Impedance') ?\n (this.circleLeftX + diameter) - (radius * 2) : this.circleLeftX;\n cx = leftX + radius;\n isLargeArc = next['value'] > 5;\n arcPoints = this.calculateMinorArcStartEndPoints(next['value']);\n if (smithchart.renderType === 'Impedance') {\n radialPoint1 = arcPoints[0];\n radialPoint2 = arcPoints[1];\n }\n else {\n radialPoint1 = arcPoints[1];\n radialPoint2 = arcPoints[0];\n }\n startPoint = this.intersectingCirclePoints(radialPoint1[0].centerX, radialPoint1[0].centerY, radialPoint1[0].radius, cx, previous['centerY'], radius, smithchart.renderType);\n endPoint = this.intersectingCirclePoints(radialPoint2[0].centerX, radialPoint2[0].centerY, radialPoint2[0].radius, cx, previous['centerY'], radius, smithchart.renderType);\n size = { width: radius, height: radius };\n this.minorHGridArcPoints.push({\n startPoint: startPoint,\n endPoint: endPoint,\n rotationAngle: 2 * Math.PI,\n sweepDirection: (smithchart.renderType === 'Impedance') ?\n this.direction['counterclockwise'] : this.direction['clockwise'],\n isLargeArc: isLargeArc,\n size: size\n });\n k++;\n }\n }\n };\n AxisRender.prototype.measureRMinorGridLines = function (smithchart) {\n var maxCount = smithchart.radialAxis.minorGridLines.count;\n var arcCx;\n var nextAngle;\n var k = 0;\n var betweenAngle;\n var circlePoint;\n var circumference;\n var arcStartX;\n var arcStartY;\n var arcStartPoint;\n var previous;\n var next;\n var size;\n var distance;\n var count;\n var interval;\n var centerValue;\n circumference = Math.PI * (this.areaRadius * 2);\n arcStartX = arcCx = (smithchart.renderType === 'Impedance') ?\n this.circleCenterX + this.areaRadius : this.circleCenterX - this.areaRadius;\n arcStartY = this.circleCenterY;\n this.minorGridArcPoints = [];\n arcStartPoint = { x: arcStartX, y: arcStartY };\n for (var i = 2; i < this.labelCollections.length - 3; i++) {\n previous = this.labelCollections[i];\n next = this.labelCollections[i + 1];\n if (smithchart.renderType === 'Impedance') {\n nextAngle = next['angle'] === 360 ? 0 : next['angle'];\n betweenAngle = Math.abs(nextAngle - previous['angle']);\n }\n else {\n nextAngle = previous['angle'] === 360 ? 0 : previous['angle'];\n betweenAngle = Math.abs(nextAngle - next['angle']);\n }\n distance = (circumference / 360) * betweenAngle;\n count = Math.floor((maxCount / 100) * distance);\n interval = betweenAngle / count;\n centerValue = next['value'] > 0 ? next['value'] : previous['value'];\n circlePoint = this.minorGridLineArcIntersectCircle(Math.abs(centerValue));\n for (var j = 1; j < count; j++) {\n var outterInterSectAngle = (interval * j) + (previous['angle'] === 360 ? nextAngle : previous['angle']);\n var outerInterSectPoint = this.circlePointPosition(this.circleCenterX, this.circleCenterY, outterInterSectAngle, this.areaRadius);\n var radius = this.arcRadius(arcStartPoint, outerInterSectPoint, outterInterSectAngle);\n var arcCy = outterInterSectAngle > 180 ? this.circleCenterY - radius : this.circleCenterY + radius;\n var innerInterSectPoint = this.intersectingCirclePoints(arcCx, arcCy, radius, circlePoint[0].centerX, circlePoint[0].centerY, circlePoint[0].radius, smithchart.renderType);\n var startPoint = { x: innerInterSectPoint.x, y: innerInterSectPoint.y };\n var endPoint = { x: outerInterSectPoint.x, y: outerInterSectPoint.y };\n size = { width: radius, height: radius };\n var sweepDirection = previous['value'] >= 0 ? this.direction['clockwise'] : this.direction['counterclockwise'];\n this.minorGridArcPoints.push({\n startPoint: startPoint,\n endPoint: endPoint,\n rotationAngle: 2 * Math.PI,\n sweepDirection: sweepDirection,\n isLargeArc: false,\n size: size\n });\n k++;\n }\n }\n };\n AxisRender.prototype.minorGridLineArcIntersectCircle = function (centerValue) {\n var circlePoint;\n var calValue;\n if (centerValue >= 3) {\n calValue = 20;\n }\n else if (centerValue >= 1.5) {\n calValue = 10;\n }\n else if (centerValue >= 0.6) {\n calValue = 3;\n }\n else {\n calValue = 2;\n }\n circlePoint = this.horizontalLabelCollections.filter(function (c) { return c['value'] === calValue; });\n return circlePoint;\n };\n AxisRender.prototype.circlePointPosition = function (cx, cy, angle, r) {\n var pointX;\n var pointY;\n var radian;\n radian = angle * (Math.PI / 180);\n pointX = cx + r * Math.cos(radian);\n pointY = cy + r * Math.sin(radian);\n return { x: pointX, y: pointY };\n };\n AxisRender.prototype.setLabelsInsidePosition = function (angle, px, py, textSize) {\n var x = px;\n var y = py;\n if (angle === 0 || angle === 360) {\n x -= textSize.width;\n y -= textSize.height / 2;\n }\n else if (angle === 90) {\n x -= textSize.width;\n y += textSize.height / 8;\n }\n else if (angle === 180) {\n y += textSize.height;\n }\n else if (angle === 270) {\n y += textSize.height / 2;\n }\n else if (angle > 0 && angle <= 20) {\n x -= (textSize.width);\n }\n else if (angle > 20 && angle <= 60) {\n x -= (textSize.width + textSize.width / 2);\n y += textSize.height / 2;\n }\n else if (angle > 60 && angle < 90) {\n x -= (textSize.width + textSize.width / 4);\n y += textSize.height / 4;\n }\n else if (angle > 90 && angle <= 135) {\n x -= (textSize.width / 2);\n y += (textSize.height) / 16;\n }\n else if (angle > 135 && angle <= 150) {\n x += (textSize.width / 2);\n y += (textSize.height / 2);\n }\n else if (angle > 150 && angle < 180) {\n x += (textSize.width / 2);\n y += (textSize.height);\n }\n else if (angle > 180 && angle <= 210) {\n x += (textSize.width / 6);\n y += (textSize.height / 6);\n }\n else if (angle > 210 && angle < 240) {\n y += (textSize.height / 4);\n }\n else if (angle > 225 && angle < 270) {\n y += (textSize.height / 3);\n }\n else if (angle > 270 && angle <= 300) {\n x -= (textSize.width + textSize.width / 4);\n y += (textSize.height / 4);\n }\n else if (angle > 300 && angle <= 330) {\n x -= (textSize.width + textSize.width / 3);\n y += (textSize.height / 4);\n }\n else if (angle > 330 && angle <= 340) {\n x -= (textSize.width + textSize.width / 2);\n y += textSize.height / 4;\n }\n else if (angle > 340) {\n x -= textSize.width;\n y += textSize.height / 8;\n }\n return { x: x, y: y };\n };\n AxisRender.prototype.setLabelsOutsidePosition = function (angle, px, py, textSize) {\n var x = px;\n var y = py;\n if (angle === 90) {\n x -= textSize.width / 2;\n y += textSize.height;\n }\n else if (angle === 180) {\n x -= (textSize.width + 5);\n y -= textSize.height / 4;\n }\n else if (angle === 270) {\n x -= textSize.width / 2;\n y -= textSize.height / 4;\n }\n else if (angle === 360) {\n x += 5;\n y -= textSize.height / 2;\n }\n else if (angle > 0 && angle <= 30) {\n x += textSize.width / 4;\n y += textSize.height / 8;\n }\n else if (angle > 30 && angle <= 60) {\n x += textSize.width / 2;\n y += textSize.height / 4;\n }\n else if (angle > 60 && angle <= 90) {\n x -= textSize.width / 2;\n y += textSize.height;\n }\n else if (angle > 90 && angle <= 135) {\n x -= textSize.width;\n y += textSize.height;\n }\n else if (angle > 135 && angle <= 180) {\n x -= (textSize.width + textSize.width / 4);\n y += textSize.height / 4;\n }\n else if (angle > 180 && angle <= 210) {\n x -= textSize.width + textSize.width / 4;\n y -= textSize.height / 4;\n }\n else if (angle > 210 && angle <= 270) {\n x -= textSize.width;\n y -= textSize.height / 4;\n }\n else if (angle > 270 && angle <= 340) {\n y -= textSize.height / 4;\n }\n else if (angle > 340) {\n y += textSize.height / 4;\n x += textSize.width / 6;\n }\n return { x: x, y: y };\n };\n AxisRender.prototype.arcRadius = function (startPoint, endPoint, angle) {\n var mx;\n var my;\n var u;\n var t;\n var cy;\n var radius;\n var radian;\n radian = angle > 180 ? (90 * Math.PI / 180) : (270 * Math.PI / 180); // Angle 90 and 270 used for calculating upper and lower circle\n mx = (endPoint.x - startPoint.x) / 2;\n my = (endPoint.y - startPoint.y) / 2;\n u = (Math.cos(radian) * my - Math.sin(radian) * mx) / (Math.cos(radian) * mx + Math.sin(radian) * my);\n t = (my - mx * u) / Math.sin(radian);\n cy = startPoint.y + Math.sin(radian) * t;\n radius = Math.abs(startPoint.y - cy);\n return radius;\n };\n return AxisRender;\n}());\nexport { AxisRender };\n","import { CircleOption, PathOption } from '../../smithchart/utils/helper';\nimport { SmithchartSize, MarkerOptions } from '../../smithchart/utils/utils';\n/* tslint:disable:no-string-literal */\nvar Marker = /** @class */ (function () {\n function Marker() {\n }\n Marker.prototype.drawMarker = function (smithchart, seriesindex, groupElement, pointsRegion) {\n if (smithchart.series[seriesindex].marker.visible) {\n var marker = smithchart.series[seriesindex].marker;\n var count = smithchart.series[seriesindex].points.length - 1;\n var width = marker.width;\n var height = marker.height;\n var symbolName = marker.shape;\n var gmEle = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' +\n '_series' + seriesindex + '_Marker' });\n groupElement.appendChild(gmEle);\n var borderWidth = marker.border.width;\n var borderColor = marker.border.color;\n var opacity = marker.opacity;\n var fill = marker.fill ? marker.fill : (smithchart.series[seriesindex].fill ||\n smithchart.seriesColors[seriesindex % smithchart.seriesColors.length]);\n for (var i = 0; i < count + 1; i++) {\n var location_1 = pointsRegion[i]['point'];\n var pointIndex = i;\n var options = new MarkerOptions(smithchart.element.id + '_Series' + seriesindex + '_Points' + pointIndex + '_Marker' + pointIndex, fill, borderColor, borderWidth, opacity);\n gmEle.appendChild(this.drawSymbol(symbolName, marker.imageUrl, location_1, new SmithchartSize(width, height), options, smithchart));\n }\n }\n };\n Marker.prototype.drawSymbol = function (symbolName, url, location, size, options, smithchart) {\n var markerEle;\n var shape = symbolName.toLowerCase();\n var circleOptions;\n var pathOptions;\n var path;\n var border = { color: options['borderColor'], width: options['borderWidth'] };\n var opacity = options.opacity;\n var startX = location.x;\n var startY = location.y;\n var radius = Math.sqrt(size.height * size.height + size.width * size.width) / 2;\n switch (shape) {\n case 'circle':\n circleOptions = new CircleOption(options['id'], options['fill'], border, opacity, location.x, location.y, radius, null);\n markerEle = smithchart.renderer.drawCircle(circleOptions);\n break;\n case 'rectangle':\n path = 'M' + ' ' + (startX + (-size.width / 2)) + ' ' + (startY + (-size.height / 2)) +\n ' ' + 'L' + ' ' + (startX + (size.width / 2)) + ' ' + (startY + (-size.height / 2)) + ' ' +\n 'L' + ' ' + (startX + (size.width / 2)) + ' ' + (startY + (size.height / 2)) +\n ' ' + 'L' + ' ' + (startX + (-size.width / 2)) +\n ' ' + (startY + (size.height / 2)) + ' ' + 'L' + ' ' +\n (startX + (-size.width / 2)) + ' ' + (startY + (-size.height / 2)) + 'z';\n pathOptions = new PathOption(options['id'], options['fill'], border.width, border.color, opacity, '', path);\n markerEle = smithchart.renderer.drawPath(pathOptions);\n break;\n case 'triangle':\n path = 'M' + ' ' + (startX + (-size.width / 2)) + ' ' + (startY + (size.height / 2)) + ' ' + 'L' + ' ' + (startX) + ' ' +\n (startY + (-size.height / 2)) + ' ' + 'L' + ' ' + (startX + (size.width / 2)) + ' ' +\n (startY + (size.height / 2)) + ' ' + 'L' + ' ' +\n (startX + (-size.width / 2)) + ' ' + (startY + (size.height / 2)) + 'z';\n pathOptions = new PathOption(options['id'], options['fill'], border.width, border.color, opacity, '', path);\n markerEle = smithchart.renderer.drawPath(pathOptions);\n break;\n case 'diamond':\n path = 'M' + ' ' + (startX + (-size.width / 2)) + ' ' + (startY) + ' ' + 'L' + ' ' +\n (startX) + ' ' + (startY + (-size.height / 2)) + ' ' + 'L' + ' ' + (startX + (size.width / 2)) + ' ' +\n (startY) + ' ' + 'L' + ' ' + (startX) + ' ' + (startY + (size.height / 2)) + ' ' + 'L' + ' ' +\n (startX + (-size.width / 2)) + ' ' + (startY) + 'z';\n pathOptions = new PathOption(options['id'], options['fill'], border.width, border.color, opacity, '', path);\n markerEle = smithchart.renderer.drawPath(pathOptions);\n break;\n case 'pentagon':\n var eq = 72;\n for (var i = 0; i <= 5; i++) {\n var xValue = radius * Math.cos((Math.PI / 180) * (i * eq));\n var yValue = radius * Math.sin((Math.PI / 180) * (i * eq));\n if (i === 0) {\n path = 'M' + ' ' + (startX + xValue) + ' ' + (startY + yValue) + ' ';\n }\n else {\n path = path.concat('L' + ' ' + (startX + xValue) + ' ' + (startY + yValue) + ' ');\n }\n }\n path = path.concat('Z');\n pathOptions = new PathOption(options['id'], options['fill'], border.width, border.color, opacity, '', path);\n markerEle = smithchart.renderer.drawPath(pathOptions);\n break;\n }\n return markerEle;\n };\n return Marker;\n}());\nexport { Marker };\n","/**\n *\n */\nimport { createElement } from '@syncfusion/ej2-base';\nimport { measureText } from '../../smithchart/utils/helper';\nimport { getTemplateFunction, convertElementFromLabel, PathOption } from '../../smithchart/utils/helper';\nimport { SmithchartLabelPosition } from '../../smithchart/utils/utils';\nimport { LabelOption } from '../../smithchart/utils/utils';\n/* tslint:disable:no-string-literal */\nvar DataLabel = /** @class */ (function () {\n function DataLabel() {\n this.textOptions = [];\n this.labelOptions = [];\n this.allPoints = [];\n }\n DataLabel.prototype.drawDataLabel = function (smithchart, seriesindex, groupElement, pointsRegion, bounds) {\n this.textOptions = [];\n this.allPoints = [];\n var margin = smithchart.margin;\n var pointIndex;\n var marker = smithchart.series[seriesindex].marker;\n var region;\n var labelPosition;\n var labelText;\n var textSize;\n var dataLabel = marker.dataLabel;\n var font = dataLabel.textStyle;\n var count = pointsRegion.length;\n for (var i = 0; i < count; i++) {\n labelText = smithchart.series[seriesindex].points[i].reactance.toString();\n textSize = measureText(labelText, font);\n region = pointsRegion[i]['point'];\n var xPos = region.x - textSize.width / 2;\n var yPos = region.y - (textSize.height + marker['height'] + (margin.top));\n var width = textSize.width + (margin.left / 2) + (margin.right / 2);\n var height = textSize.height + (margin.top / 2) + (margin.bottom / 2);\n pointIndex = i;\n labelPosition = new SmithchartLabelPosition();\n labelPosition = { textX: xPos + (margin.left / 2), textY: yPos + (height / 2) + margin.top / 2, x: xPos, y: yPos };\n this.textOptions[i] = {\n id: smithchart.element.id + '_Series' + seriesindex + '_Points' + pointIndex + '_dataLabel' + '_displayText' + i,\n x: labelPosition['textX'],\n y: labelPosition['textY'],\n fill: 'black',\n text: labelText,\n font: font,\n xPosition: xPos,\n yPosition: yPos,\n width: width,\n height: height,\n location: region,\n labelOptions: labelPosition,\n visible: true,\n connectorFlag: null\n };\n }\n var labelOption = new LabelOption();\n labelOption.textOptions = this.textOptions;\n this.labelOptions.push(labelOption);\n this.drawDatalabelSymbol(smithchart, seriesindex, dataLabel, groupElement, bounds, pointsRegion);\n };\n DataLabel.prototype.calculateSmartLabels = function (points, seriesIndex) {\n var length = points['textOptions'].length;\n var count = 0;\n for (var k = 0; k < length; k++) {\n this.allPoints[this.allPoints.length] = points['textOptions'][k];\n this.connectorFlag = false;\n this.compareDataLabels(k, points, count, seriesIndex);\n this.labelOptions[seriesIndex]['textOptions'][k] = points['textOptions'][k];\n this.labelOptions[seriesIndex]['textOptions'][k].connectorFlag = this.connectorFlag;\n }\n };\n DataLabel.prototype.compareDataLabels = function (i, points, count, m) {\n var length = this.allPoints.length;\n var padding = 10;\n var collide;\n var currentLabel;\n var prevLabel;\n for (var j = 0; j < length; j++) {\n prevLabel = this.allPoints[j];\n currentLabel = this.allPoints[length - 1];\n collide = this.isCollide(prevLabel, currentLabel);\n if (collide) {\n this.connectorFlag = true;\n switch (count) {\n case 0:\n // Right\n this.resetValues(currentLabel);\n this.prevLabel = prevLabel;\n currentLabel['xPosition'] = this.prevLabel['xPosition'] + (this.prevLabel['width'] / 2 +\n currentLabel['width'] / 2 + padding);\n currentLabel['x'] = currentLabel['xPosition'] + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 1:\n // Right Bottom\n this.resetValues(currentLabel);\n currentLabel['xPosition'] = this.prevLabel['xPosition'] + this.prevLabel['width'] / 2 +\n currentLabel['width'] / 2 + padding;\n currentLabel['x'] = currentLabel['xPosition'] + padding / 2;\n currentLabel['yPosition'] = currentLabel['location'].y + currentLabel['height'] / 2 + padding / 2;\n currentLabel['y'] = currentLabel['yPosition'] + ((currentLabel['height'] / 2)) + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 2:\n // Bottom\n this.resetValues(currentLabel);\n currentLabel['yPosition'] = currentLabel['location'].y + currentLabel['height'] / 2 + padding / 2;\n currentLabel['y'] = currentLabel['yPosition'] + (currentLabel['height'] / 2) + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 3:\n // Left Bottom\n this.resetValues(currentLabel);\n currentLabel['xPosition'] = this.prevLabel['xPosition'] - this.prevLabel['width'] / 2\n - currentLabel['width'] / 2 - padding;\n currentLabel['x'] = currentLabel['xPosition'] + padding / 2;\n currentLabel['yPosition'] = currentLabel['height'] / 2 + currentLabel['location'].y + padding / 2;\n currentLabel['y'] = currentLabel['yPosition'] + ((currentLabel['height'] / 2)) + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 4:\n // Left\n this.resetValues(currentLabel);\n currentLabel['xPosition'] = (this.prevLabel['xPosition'] - this.prevLabel['width'] / 2 -\n currentLabel['width'] / 2 - padding);\n currentLabel['x'] = currentLabel['xPosition'] + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 5:\n //Left Top\n this.resetValues(currentLabel);\n currentLabel['xPosition'] = this.prevLabel['xPosition'] - this.prevLabel['width'] / 2 -\n currentLabel['width'] / 2 - padding;\n currentLabel['x'] = currentLabel['xPosition'] + padding / 2;\n currentLabel['yPosition'] = this.prevLabel['yPosition'] - currentLabel['height'] - padding;\n currentLabel['y'] = currentLabel['yPosition'] + currentLabel['height'] / 2 + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 6:\n // Top\n this.resetValues(currentLabel);\n currentLabel['yPosition'] = (this.prevLabel['yPosition']) - (currentLabel['height'] + padding);\n currentLabel['y'] = currentLabel['yPosition'] + (currentLabel['height'] / 2) + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 7:\n // Right Top\n this.resetValues(currentLabel);\n currentLabel['xPosition'] = this.prevLabel['xPosition'] + this.prevLabel['width'] / 2 +\n currentLabel['width'] / 2 + padding;\n currentLabel['x'] = currentLabel['xPosition'] + padding / 2;\n currentLabel['yPosition'] = this.prevLabel['yPosition'] - currentLabel['height'] - padding;\n currentLabel['y'] = currentLabel['yPosition'] + (currentLabel['height'] / 2) + padding / 2;\n count += 1;\n this.compareDataLabels(i, points, count, m);\n break;\n case 8:\n count = 0;\n this.compareDataLabels(i, points, count, m);\n break;\n }\n }\n }\n };\n DataLabel.prototype.isCollide = function (dataLabel1, dataLabel2) {\n var state = false;\n if (dataLabel1 !== dataLabel2) {\n state = !(((dataLabel1['y'] + dataLabel1['height']) < (dataLabel2['y'])) ||\n (dataLabel1['y'] > (dataLabel2['y'] + dataLabel2['height'])) ||\n ((dataLabel1['x'] + dataLabel1['width'] / 2) < dataLabel2['x'] - dataLabel2['width'] / 2) ||\n (dataLabel1['x'] - dataLabel1['width'] / 2 > (dataLabel2['x'] + dataLabel2['width'] / 2)));\n }\n return state;\n };\n DataLabel.prototype.resetValues = function (currentPoint) {\n currentPoint['xPosition'] = currentPoint['labelOptions']['x'];\n currentPoint['yPosition'] = currentPoint['labelOptions']['y'];\n currentPoint['x'] = currentPoint['labelOptions']['textX'];\n currentPoint['y'] = currentPoint['labelOptions']['textY'];\n };\n DataLabel.prototype.drawConnectorLines = function (smithchart, seriesIndex, index, currentPoint, groupElement) {\n var xPos = currentPoint['xPosition'];\n var yPos = currentPoint['yPosition'];\n var location = currentPoint['location'];\n var endY;\n if (location.y > currentPoint['y']) {\n endY = (currentPoint['y']);\n }\n else {\n endY = (currentPoint['y'] - currentPoint['height'] / 2); // bottom\n }\n var connectorDirection = 'M' + ' ' + (location.x) + ' ' + (location.y) + ' ' + 'L' + ' ' +\n (currentPoint['x']) + ' ' + (endY);\n var connectorLineValues = smithchart.series[seriesIndex].marker.dataLabel.connectorLine;\n var stroke = connectorLineValues.color ? connectorLineValues.color :\n (smithchart.series[seriesIndex].fill ||\n smithchart.seriesColors[seriesIndex % smithchart.seriesColors.length]);\n var options = new PathOption(smithchart.element.id + '_dataLabelConnectorLine' + '_series' + seriesIndex + '_point' + index, 'none', connectorLineValues.width, stroke, 1, 'none', connectorDirection);\n var element = smithchart.renderer.drawPath(options);\n groupElement.appendChild(element);\n };\n DataLabel.prototype.drawDatalabelSymbol = function (smithchart, seriesindex, dataLabel, groupElement, bounds, pointsRegion) {\n for (var i = 0; i < smithchart.series[seriesindex].points.length; i++) {\n if (dataLabel.template) {\n var labelTemplateElement = createElement('div', {\n id: smithchart.element.id + '_seriesIndex_' + seriesindex + '_Label_Template_Group',\n className: 'template',\n styles: 'position: absolute;'\n /* 'top:' + bounds['x'] + 'px;' +\n 'left:' + bounds['y'] + 'px;' +\n 'height:' + smithchart.availableSize.height + 'px;' +\n 'width:' + smithchart.availableSize.width + 'px;'*/\n });\n document.getElementById(smithchart.element.id + '_Secondary_Element').appendChild(labelTemplateElement);\n var templateFn = void 0;\n var labelElement = void 0;\n var id = dataLabel.template + '_seriesIndex' + seriesindex + '_pointIndex' + i + smithchart.element.id;\n var data = { point: smithchart.series[seriesindex].points[i].reactance };\n templateFn = getTemplateFunction(dataLabel.template);\n var templateElement = templateFn(smithchart);\n labelElement = convertElementFromLabel(templateElement, id, data, seriesindex, smithchart);\n labelTemplateElement.appendChild(labelElement);\n labelElement.style.left = pointsRegion[i].point.x - labelElement.offsetWidth / 2 + 'px';\n labelElement.style.top = pointsRegion[i].point.y - labelElement.offsetHeight -\n smithchart.series[seriesindex].marker.height / 2 + 'px';\n var left = parseInt(labelElement.style.left, 10);\n var top_1 = parseInt(labelElement.style.top, 10);\n var width = labelElement.offsetWidth;\n var height = labelElement.offsetHeight;\n var region = pointsRegion[i]['point'];\n var labelPosition = { textX: left, textY: top_1,\n x: left, y: top_1 };\n this.labelOptions[seriesindex]['textOptions'][i] = {\n id: id,\n x: left,\n y: top_1,\n fill: 'black',\n text: '',\n font: dataLabel.textStyle,\n xPosition: left,\n yPosition: top_1,\n width: width,\n height: height,\n location: region,\n labelOptions: labelPosition,\n visible: true,\n connectorFlag: null\n };\n }\n }\n };\n return DataLabel;\n}());\nexport { DataLabel };\n","import { Marker } from './marker';\nimport { TextOption, renderTextElement } from '../../smithchart/utils/helper';\nimport { SmithchartRect, LineSegment, PointRegion, DataLabelTextOptions } from '../../smithchart/utils/utils';\nimport { _getEpsilonValue, PathOption, RectOption, getAnimationFunction, templateAnimate } from '../../smithchart/utils/helper';\nimport { animationComplete } from '../../smithchart/model/constant';\nimport { DataLabel } from '../../smithchart/series/datalabel';\nimport { Animation } from '@syncfusion/ej2-base';\n/* tslint:disable:no-string-literal */\nvar SeriesRender = /** @class */ (function () {\n function SeriesRender() {\n this.xValues = [];\n this.yValues = [];\n this.pointsRegion = [];\n this.lineSegments = [];\n this.location = [];\n this.dataLabel = new DataLabel();\n }\n SeriesRender.prototype.processData = function (series) {\n var dataArray = series.dataSource;\n var resistance = series.resistance;\n var reactance = series.reactance;\n series.points = [];\n for (var i = 0; i < dataArray.length; i++) {\n series.points.push({ resistance: dataArray[i][resistance],\n reactance: dataArray[i][reactance] });\n }\n };\n // tslint:disable:max-func-body-length\n SeriesRender.prototype.draw = function (smithchart, axisRender, bounds) {\n var groupElement = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_seriesCollections' });\n var resistantCx;\n var reactanceCy;\n var series = smithchart.series;\n var seriesLength = series.length;\n var chartAreaRadius = axisRender.areaRadius;\n var interSectPoint;\n var index;\n for (var m = 0; m < seriesLength; m++) {\n var seriesIndex = m;\n if (series[m].dataSource && series[m].resistance && series[m].reactance) {\n this.processData(series[m]);\n }\n this.pointsRegion[m] = [];\n this.location[m] = [];\n for (var j = 0; j < series[m].points.length; j++) {\n this.xValues[j] = series[m].points[j]['resistance'];\n this.yValues[j] = series[m].points[j]['reactance'];\n }\n var chartAreaCx = axisRender.circleCenterX;\n var chartAreaCy = axisRender.circleCenterY;\n var diameter = axisRender.areaRadius * 2;\n var reactanceStartPoint = { x: chartAreaCx + ((smithchart.renderType === 'Impedance') ?\n chartAreaRadius : -chartAreaRadius), y: chartAreaCy };\n var resistantCy = chartAreaCy;\n var reactanceCx = reactanceStartPoint.x;\n for (var k = 0; k < series[m].points.length; k++) {\n var resistance = this.xValues[k];\n var resistantR = (diameter * (1 / (resistance + 1))) / 2;\n var reactance = this.yValues[k];\n var reactanceR = Math.abs(((1 / reactance) * diameter) / 2);\n if (smithchart.renderType === 'Impedance') {\n reactanceCy = reactance > 0 ? chartAreaCy - reactanceR : chartAreaCy + reactanceR;\n resistantCx = (axisRender.circleLeftX + diameter - resistantR);\n }\n else {\n reactanceCy = reactance < 0 ? chartAreaCy - reactanceR : chartAreaCy + reactanceR;\n resistantCx = (axisRender.circleLeftX + resistantR);\n }\n interSectPoint = axisRender.intersectingCirclePoints(reactanceCx, reactanceCy, reactanceR, resistantCx, resistantCy, resistantR, smithchart.renderType);\n var epsilon = _getEpsilonValue();\n if (Math.abs(reactance) < epsilon) {\n interSectPoint.x = (smithchart.renderType === 'Impedance') ?\n resistantCx - resistantR : resistantCx + resistantR;\n interSectPoint.y = chartAreaCy;\n }\n this.pointsRegion[m][k] = new PointRegion();\n this.pointsRegion[m][k] = { point: interSectPoint, x: resistance, y: reactance };\n this.location[m][k] = { x: interSectPoint.x, y: interSectPoint.y };\n }\n for (var i = 0; i < series[m].points.length - 1; i++) {\n index = i + 1;\n this.lineSegments[i] = new LineSegment();\n this.lineSegments[i] = { x1: this.xValues[i], y1: this.yValues[i], x2: this.xValues[index], y2: this.yValues[index] };\n }\n smithchart.svgObject.appendChild(groupElement);\n this.drawSeries(smithchart, seriesIndex, groupElement, bounds);\n }\n for (var j = 0; j < smithchart.series.length; j++) {\n if (smithchart.series[j].enableSmartLabels && smithchart.series[j].marker.dataLabel.visible) {\n var gdlcEle = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg'\n + '_series' + j + '_Datalabel' + '_connectorLines' });\n var element = document.getElementById(smithchart.element.id + '_svg' + '_seriesCollection' + j);\n if (element) {\n element.appendChild(gdlcEle);\n }\n this.dataLabel.calculateSmartLabels(this.dataLabel.labelOptions[j], j);\n for (var k = 0; k < smithchart.series[j].points.length; k++) {\n var currentPoint = this.dataLabel.labelOptions[j]['textOptions'][k];\n if ((currentPoint.xPosition + currentPoint.width) > (smithchart.chartArea.x + smithchart.chartArea.width)\n || currentPoint.xPosition < smithchart.chartArea.x || currentPoint.yPosition < smithchart.chartArea.y ||\n currentPoint.yPosition + currentPoint.height > smithchart.chartArea.y + smithchart.chartArea.height) {\n this.dataLabel.labelOptions[j].textOptions[k].connectorFlag = false;\n this.dataLabel.labelOptions[j].textOptions[k].visible = false;\n }\n if (currentPoint['connectorFlag']) {\n this.dataLabel.drawConnectorLines(smithchart, j, k, currentPoint, gdlcEle);\n }\n }\n }\n }\n for (var j = 0; j < smithchart.series.length; j++) {\n var dataLabel = smithchart.series[j].marker.dataLabel;\n if (smithchart.series[j].marker.dataLabel.visible) {\n var element = document.getElementById(smithchart.element.id + '_svg' + '_seriesCollection' + j);\n var gdEle = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg'\n + '_series' + j + '_Datalabel' });\n if (element) {\n element.appendChild(gdEle);\n }\n for (var k = 0; k < smithchart.series[j].points.length; k++) {\n var currentPoint = this.dataLabel.labelOptions[j]['textOptions'][k];\n if (!dataLabel.template && currentPoint.visible) {\n var options = new DataLabelTextOptions();\n options = this.dataLabel.labelOptions[j]['textOptions'][k];\n var font = smithchart.font;\n var x = options['xPosition'];\n var y = options['yPosition'];\n var id = smithchart.element.id + '_Series' + j + '_Points' + k + '_dataLabel' + '_symbol' + k;\n var fill = dataLabel['fill'] ? dataLabel['fill'] : (smithchart.series[j].fill ||\n smithchart.seriesColors[j % smithchart.seriesColors.length]);\n var border = smithchart.series[j].marker.dataLabel.border;\n var rectOptions = new RectOption(id, fill, border, options['opacity'], new SmithchartRect(x, y, options['width'], options['height']));\n var dataEle = smithchart.renderer.drawRectangle(rectOptions);\n gdEle.appendChild(dataEle);\n var textRenderEventArgs = { text: options['text'], x: options['x'], y: options['y'], seriesIndex: j,\n pointIndex: k, name: 'textRender', cancel: false };\n smithchart.trigger('textRender', textRenderEventArgs);\n var textoptions = new TextOption(options['id'], textRenderEventArgs.x, textRenderEventArgs.y, 'start', textRenderEventArgs.text);\n var element_1 = renderTextElement(textoptions, font, smithchart.themeStyle.dataLabel, gdEle);\n gdEle.appendChild(element_1);\n }\n else if (dataLabel.template) {\n var element_2 = document.getElementById(dataLabel.template + '_seriesIndex' + j + '_pointIndex' +\n k + smithchart.element.id);\n element_2.style.left = this.dataLabel.labelOptions[j]['textOptions'][k].xPosition + 'px';\n element_2.style.top = this.dataLabel.labelOptions[j]['textOptions'][k].yPosition + 'px';\n }\n }\n }\n }\n for (var i = 0; i < smithchart.series.length; i++) {\n if (smithchart.series[i].enableAnimation && smithchart.animateSeries) {\n if (smithchart.series[i].marker.dataLabel.template) {\n this.animateDataLabelTemplate(i, smithchart);\n }\n var element = document.getElementById(smithchart.element.id + '_svg' + '_seriesCollection' + i);\n this.performAnimation(smithchart, element, i);\n }\n }\n };\n SeriesRender.prototype.drawSeries = function (smithchart, seriesindex, groupElement, bounds) {\n var gsEle = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + '_seriesCollection' + seriesindex,\n 'clip-path': 'url(#' + smithchart.element.id + '_ChartSeriesClipRect_' +\n seriesindex + ')' });\n gsEle.setAttribute('visibility', smithchart.series[seriesindex].visibility);\n groupElement.appendChild(gsEle);\n var sb = '';\n var path;\n var marker = smithchart.series[seriesindex].marker;\n var element;\n var count = smithchart.series[seriesindex].points.length - 1;\n for (var i = 0; i < count; i++) {\n var point1 = this.pointsRegion[seriesindex][i]['point'];\n var point2 = this.pointsRegion[seriesindex][i + 1]['point'];\n sb = sb + ('M' + ' ' + (point1.x) + ' ' + (point1.y) + ' ' + 'L' +\n ' ' + (point2.x) + ' ' + (point2.y) + ' ');\n }\n path = sb.toString();\n var fill = smithchart.series[seriesindex].fill || smithchart.seriesColors[seriesindex % smithchart.seriesColors.length];\n var seriesEventArgs = { text: smithchart.series[seriesindex].name, fill: fill,\n name: 'seriesRender', cancel: false };\n smithchart.trigger('seriesRender', seriesEventArgs);\n var options = new PathOption(smithchart.element.id + '_series' + seriesindex + '_points', 'none', smithchart.series[seriesindex].width, seriesEventArgs.fill, smithchart.series[seriesindex].opacity, 'none', path);\n this.clipRectElement = smithchart.renderer.drawClipPath(new RectOption(smithchart.element.id + '_ChartSeriesClipRect_' + seriesindex, 'transparent', { width: 1, color: 'Gray' }, 1, {\n x: bounds.x, y: bounds.y,\n width: smithchart.availableSize.width,\n height: smithchart.availableSize.height\n }));\n gsEle.appendChild(this.clipRectElement);\n var gspEle = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_svg' + seriesindex });\n element = smithchart.renderer.drawPath(options);\n gspEle.appendChild(element);\n gsEle.appendChild(gspEle);\n var markerrender = new Marker();\n markerrender.drawMarker(smithchart, seriesindex, gsEle, this.pointsRegion[seriesindex]);\n this.dataLabel.drawDataLabel(smithchart, seriesindex, gsEle, this.pointsRegion[seriesindex], bounds);\n };\n SeriesRender.prototype.animateDataLabelTemplate = function (seriesindex, smithchart) {\n var length = smithchart.series[seriesindex].points.length;\n var opacity = 0;\n var delay = 0;\n var duration = parseFloat(smithchart.series[seriesindex].animationDuration);\n for (var i = 0; i < length; i++) {\n var element = document.getElementById(smithchart.series[seriesindex].marker.dataLabel.template +\n '_seriesIndex' + seriesindex + '_pointIndex' + i + smithchart.element.id);\n element.style.visibility = 'hidden';\n templateAnimate(smithchart, element, delay, duration, 'FadeIn');\n // this.fadein(element);\n }\n };\n /*private fadein(element: HTMLElement): void {\n let op: number = 0.1;\n element.style.display = 'block';\n let timer: number = setInterval( (): void => {\n if (op >= 1) {\n clearInterval(timer);\n }\n element.style.opacity = op.toString();\n element.style.filter = 'alpha(opacity=' + op * 100 + ')';\n op += op * 0.1;\n }, 50);\n \n }*/\n SeriesRender.prototype.performAnimation = function (smithchart, gsEle, seriesIndex) {\n var animation = new Animation({});\n var element = document.getElementById('container_svg_seriesCollections');\n var clipRect = gsEle.childNodes[0].childNodes[0].childNodes[0];\n var effect = getAnimationFunction('Linear');\n var reveffect = getAnimationFunction('Reverse');\n var width = +clipRect.getAttribute('width');\n var x = +clipRect.getAttribute('x');\n var value;\n animation.animate(clipRect, {\n duration: parseFloat(smithchart.series[seriesIndex].animationDuration),\n progress: function (args) {\n if (smithchart.renderType === 'Impedance') {\n value = effect(args.timeStamp - args.delay, 0, width, args.duration);\n clipRect.setAttribute('width', value.toString());\n }\n else {\n value = reveffect(args.timeStamp - args.delay, width, 0, args.duration);\n clipRect.setAttribute('x', value.toString());\n }\n },\n end: function (model) {\n if (smithchart.renderType === 'Impedance') {\n clipRect.setAttribute('width', width.toString());\n }\n else {\n clipRect.setAttribute('x', x.toString());\n }\n var event = {\n cancel: false, name: animationComplete, smithchart: smithchart\n };\n smithchart.trigger(animationComplete, event);\n }\n });\n };\n SeriesRender.prototype.getLocation = function (seriesindex, pointIndex) {\n var x;\n var y;\n x = this.location[seriesindex][pointIndex].x;\n y = this.location[seriesindex][pointIndex].y;\n return { x: x, y: y };\n };\n return SeriesRender;\n}());\nexport { SeriesRender };\n","/**\n * Specifies smithchart animationComplete event name.\n * @private\n */\nexport var animationComplete = 'animationComplete';\n/**\n * Specifies smithchart legendRender event name.\n * @private\n */\nexport var legendRender = 'legendRender';\n/**\n * Specifies smithchart titleRender event name.\n * @private\n */\nexport var titleRender = 'titleRender';\n/**\n * Specifies smithchart subtitleRender event name.\n * @private\n */\nexport var subtitleRender = 'subtitleRender';\n/**\n * Specifies smithchart textRender event name.\n * @private\n */\nexport var textRender = 'textRender';\n","import { print as smithchartPrint, createElement, isNullOrUndefined, Browser } from '@syncfusion/ej2-base';\nimport { getElement } from '../utils/helper';\nimport { smithchartBeforePrint } from '../utils/enum';\nimport { PdfPageOrientation, PdfDocument, PdfBitmap } from '@syncfusion/ej2-pdf-export';\n/**\n * Annotation Module handles the Annotation for Maps\n */\nvar ExportUtils = /** @class */ (function () {\n /**\n * Constructor for Maps\n * @param control\n */\n function ExportUtils(control) {\n this.control = control;\n }\n /**\n * To print the Maps\n * @param elements\n */\n ExportUtils.prototype.print = function (elements) {\n this.smithchartPrint = window.open('', 'print', 'height=' + window.outerHeight + ',width=' + window.outerWidth + ',tabbar=no');\n this.smithchartPrint.moveTo(0, 0);\n this.smithchartPrint.resizeTo(screen.availWidth, screen.availHeight);\n var argsData = {\n cancel: false, htmlContent: this.getHTMLContent(elements), name: smithchartBeforePrint\n };\n this.control.trigger(smithchartBeforePrint, argsData);\n if (!argsData.cancel) {\n smithchartPrint(argsData.htmlContent, this.smithchartPrint);\n }\n };\n /**\n * To get the html string of the Maps\n * @param svgElements\n * @private\n */\n ExportUtils.prototype.getHTMLContent = function (svgElements) {\n var div = createElement('div');\n if (svgElements) {\n if (svgElements instanceof Array) {\n svgElements.forEach(function (value) {\n div.appendChild(getElement(value).cloneNode(true));\n });\n }\n else if (svgElements instanceof Element) {\n div.appendChild(svgElements.cloneNode(true));\n }\n else {\n div.appendChild(getElement(svgElements).cloneNode(true));\n }\n }\n else {\n div.appendChild(this.control.element.cloneNode(true));\n }\n return div;\n };\n /**\n * To export the file as image/svg format\n * @param type\n * @param fileName\n */\n ExportUtils.prototype.export = function (exportType, fileName, orientation) {\n var _this = this;\n var canvas = createElement('canvas', {\n id: 'ej2-canvas',\n attrs: {\n 'width': this.control.availableSize.width.toString(),\n 'height': this.control.availableSize.height.toString()\n }\n });\n var isDownload = !(Browser.userAgent.toString().indexOf('HeadlessChrome') > -1);\n orientation = isNullOrUndefined(orientation) ? PdfPageOrientation.Landscape : orientation;\n var svgData = '
' +\n this.control.svgObject.outerHTML +\n ' ';\n var url = window.URL.createObjectURL(new Blob(exportType === 'SVG' ? [svgData] :\n [(new XMLSerializer()).serializeToString(this.control.svgObject)], { type: 'image/svg+xml' }));\n if (exportType === 'SVG') {\n this.triggerDownload(fileName, exportType, url, isDownload);\n }\n else {\n var image_1 = new Image();\n var ctx_1 = canvas.getContext('2d');\n image_1.onload = (function () {\n ctx_1.drawImage(image_1, 0, 0);\n window.URL.revokeObjectURL(url);\n if (exportType === 'PDF') {\n var document_1 = new PdfDocument();\n var imageString = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');\n document_1.pageSettings.orientation = orientation;\n imageString = imageString.slice(imageString.indexOf(',') + 1);\n document_1.pages.add().graphics.drawImage(new PdfBitmap(imageString), 0, 0, (_this.control.availableSize.width - 60), _this.control.availableSize.height);\n if (isDownload) {\n document_1.save(fileName + '.pdf');\n document_1.destroy();\n }\n }\n else {\n _this.triggerDownload(fileName, exportType, canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'), isDownload);\n }\n });\n image_1.src = url;\n }\n };\n /**\n * To trigger the download element\n * @param fileName\n * @param type\n * @param url\n */\n ExportUtils.prototype.triggerDownload = function (fileName, exportType, url, isDownload) {\n createElement('a', {\n attrs: {\n 'download': fileName + '.' + exportType.toLocaleLowerCase(),\n 'href': url\n }\n }).dispatchEvent(new MouseEvent(isDownload ? 'click' : 'move', {\n view: window,\n bubbles: false,\n cancelable: true\n }));\n };\n return ExportUtils;\n}());\nexport { ExportUtils };\n","/**\n * Specifies TreeMap beforePrint event name.\n * @private\n */\nexport var smithchartBeforePrint = 'beforePrint';\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Complex, NotifyPropertyChanges, Property } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, Browser } from '@syncfusion/ej2-base';\nimport { remove, Event, EventHandler } from '@syncfusion/ej2-base';\nimport { createSvg, RectOption, measureText, TextOption, renderTextElement } from '../smithchart/utils/helper';\nimport { removeElement, textTrim } from '../smithchart/utils/helper';\nimport { SmithchartRect } from '../smithchart/utils/utils';\nimport { SmithchartMargin, SmithchartBorder, SmithchartFont } from '../smithchart/utils/utils';\nimport { getThemeColor } from '../smithchart/model/theme';\nimport { SmithchartLegendSettings } from '../smithchart/legend/legend';\nimport { SmithchartAxis } from '../smithchart/axis/axis';\nimport { Title } from '../smithchart/title/title';\nimport { SmithchartSeries } from '../smithchart/series/series';\nimport { AreaBounds } from '../smithchart/utils/area';\nimport { AxisRender } from '../smithchart/axis/axisrender';\nimport { SeriesRender } from '../smithchart/series/seriesrender';\nimport { Collection } from '@syncfusion/ej2-base';\nimport { getSeriesColor } from '../smithchart/model/theme';\nimport { ExportUtils } from '../smithchart/utils/export';\nimport { titleRender, subtitleRender } from '../smithchart/model/constant';\n/* tslint:disable:no-string-literal */\n/**\n * Represents the Smithchart control.\n * ```html\n *
\n * \n * ```\n */\nvar Smithchart = /** @class */ (function (_super) {\n __extends(Smithchart, _super);\n /**\n * Constructor for creating the Smithchart widget\n */\n function Smithchart(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * Get component name\n */\n Smithchart.prototype.getModuleName = function () {\n return 'smithchart';\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n Smithchart.prototype.getPersistData = function () {\n return '';\n };\n /**\n * Method to create SVG element.\n */\n Smithchart.prototype.createChartSvg = function () {\n this.removeSvg();\n createSvg(this);\n };\n Smithchart.prototype.renderTitle = function (title, type, groupEle) {\n var font = title.font ? title.font : title.textStyle;\n var textSize = measureText(title.text, font);\n var x;\n var y;\n var textAlignment = title.textAlignment;\n var titleText = title.text;\n var maxTitleWidth = (isNullOrUndefined(title.maximumWidth)) ?\n Math.abs(this.margin.left + this.margin.right - (this.availableSize.width)) :\n title.maximumWidth;\n var titleWidthEnable = textSize.width > maxTitleWidth ? true : false;\n if (textSize.width > this.availableSize.width) {\n x = this.margin.left + this.border.width;\n }\n else {\n x = textAlignment === 'Center' ? (this.availableSize.width / 2 - textSize['width'] / 2) :\n (textAlignment === 'Near' ? (this.margin.left + this.elementSpacing + this.border.width) : (this.availableSize.width\n - textSize['width'] - (this.margin.right + this.elementSpacing + this.border.width)));\n }\n y = this.margin.top + textSize['height'] / 2 + this.elementSpacing;\n if (title.enableTrim && titleWidthEnable) {\n titleText = textTrim(maxTitleWidth, title.text, font);\n textSize = measureText(titleText, font);\n }\n groupEle = this.renderer.createGroup({ id: this.element.id + '_Title_Group' });\n var titleEventArgs = { text: titleText, x: x, y: y, name: 'titleRender', cancel: false };\n this.trigger(titleRender, titleEventArgs);\n var options = new TextOption(this.element.id + '_Smithchart_' + type, titleEventArgs.x, titleEventArgs.y, 'start', titleEventArgs.text);\n var element = renderTextElement(options, font, this.themeStyle.chartTitle, groupEle);\n element.setAttribute('aria-label', title.description || title.text);\n var titleLocation = { x: x, y: y, textSize: textSize };\n this.svgObject.appendChild(groupEle);\n if (title.subtitle.text !== '' && title.subtitle.visible) {\n this.renderSubtitle(title, type, textSize, this.availableSize, titleLocation, groupEle);\n }\n };\n Smithchart.prototype.renderSubtitle = function (title, type, textSize, size, titleLocation, groupEle) {\n var x;\n var y;\n var font = title.subtitle.textStyle;\n var subTitle = title.subtitle;\n var subTitleSize = measureText(subTitle.text, font);\n var textAnchor;\n var subTitleText = subTitle.text;\n var maxSubTitleWidth = isNullOrUndefined(subTitle.maximumWidth) ?\n (this.bounds.width * 0.75) : subTitle.maximumWidth;\n if (subTitle.enableTrim && subTitleSize.width > maxSubTitleWidth) {\n subTitleText = textTrim(maxSubTitleWidth, subTitle.text, font);\n }\n x = title['subtitle'].textAlignment === 'Far' ? (titleLocation.x + (titleLocation.textSize.width)) :\n (title['subtitle'].textAlignment === 'Near') ? titleLocation.x :\n (titleLocation.x + (titleLocation.textSize.width / 2));\n y = titleLocation.y + (2 * this.elementSpacing);\n textAnchor = title['subtitle'].textAlignment === 'Far' ? 'end' :\n (title['subtitle'].textAlignment === 'Near') ? 'start' : 'middle';\n var subtitleEventArgs = { text: subTitleText, x: x, y: y, name: 'subtitleRender', cancel: false };\n this.trigger(subtitleRender, subtitleEventArgs);\n var options = new TextOption(this.element.id + '_Smithchart_' + type, subtitleEventArgs.x, subtitleEventArgs.y, textAnchor, subtitleEventArgs.text);\n var element = renderTextElement(options, font, this.themeStyle.chartTitle, groupEle);\n element.setAttribute('aria-label', subTitle.description || subTitle.text);\n groupEle.appendChild(element);\n };\n /**\n * @private\n * Render the smithchart border\n */\n Smithchart.prototype.renderBorder = function () {\n var border = this.border;\n var color = this.theme === 'Highcontrast' ? '#000000' : '#FFFFFF';\n this.background = this.background ? this.background : color;\n var borderRect = new RectOption(this.element.id + '_SmithchartBorder', this.background, border, 1, new SmithchartRect(border.width / 2, border.width / 2, this.availableSize.width - border.width, this.availableSize.height - border.width));\n this.svgObject.appendChild(this.renderer.drawRectangle(borderRect));\n };\n /**\n * Called internally if any of the property value changed.\n * @private\n */\n Smithchart.prototype.onPropertyChanged = function (newProp, oldProp) {\n this.animateSeries = false;\n var renderer = false;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'background':\n renderer = true;\n break;\n case 'size':\n this.createChartSvg();\n renderer = true;\n break;\n case 'theme':\n this.animateSeries = true;\n renderer = true;\n break;\n case 'border':\n renderer = true;\n break;\n }\n }\n if (renderer) {\n this.render();\n }\n };\n /**\n * Initialize the event handler.\n */\n Smithchart.prototype.preRender = function () {\n this.trigger('load', { smithchart: this });\n this.unWireEVents();\n this.initPrivateVariable();\n this.wireEVents();\n };\n Smithchart.prototype.initPrivateVariable = function () {\n this.animateSeries = true;\n };\n /**\n * To Initialize the control rendering.\n */\n Smithchart.prototype.setTheme = function () {\n /*! Set theme */\n this.themeStyle = getThemeColor(this.theme);\n this.seriesColors = getSeriesColor(this.theme);\n // let count: number = colors.length;\n // for (let i: number = 0; i < this.series.length; i++) {\n // this.series[i].fill = this.series[i].fill ? this.series[i].fill : colors[i % count];\n // }\n };\n Smithchart.prototype.render = function () {\n this.createChartSvg();\n this.element.appendChild(this.svgObject);\n this.setTheme();\n this.createSecondaryElement();\n this.renderBorder();\n if (this.smithchartLegendModule && this.legendSettings.visible) {\n this.legendBounds = this.smithchartLegendModule.renderLegend(this);\n }\n this.legendBounds = this.legendBounds ? this.legendBounds : { x: 0, y: 0, width: 0, height: 0 };\n var areaBounds = new AreaBounds();\n this.bounds = areaBounds.calculateAreaBounds(this, this.title, this.legendBounds);\n if (this.title.text !== '' && this.title.visible) {\n this.renderTitle(this.title, 'title', null);\n }\n var axisRender = new AxisRender();\n axisRender.renderArea(this, this.bounds);\n this.seriesrender = new SeriesRender();\n this.seriesrender.draw(this, axisRender, this.bounds);\n this.trigger('loaded', { smithchart: this });\n };\n Smithchart.prototype.createSecondaryElement = function () {\n if (isNullOrUndefined(document.getElementById(this.element.id + '_Secondary_Element'))) {\n var secondaryElement = this.createElement('div', {\n id: this.element.id + '_Secondary_Element',\n styles: 'position: absolute;z-index:1;'\n });\n this.element.appendChild(secondaryElement);\n var rect = this.element.getBoundingClientRect();\n var svgRect = document.getElementById(this.element.id + '_svg');\n if (svgRect) {\n var svgClientRect = svgRect.getBoundingClientRect();\n secondaryElement.style.left = Math.max(svgClientRect.left - rect.left, 0) + 'px';\n secondaryElement.style.top = Math.max(svgClientRect.top - rect.top, 0) + 'px';\n }\n }\n else {\n removeElement(this.element.id + '_Secondary_Element');\n }\n };\n /**\n * To destroy the widget\n * @method destroy\n * @return {void}.\n * @member of smithChart\n */\n Smithchart.prototype.destroy = function () {\n this.unWireEVents();\n _super.prototype.destroy.call(this);\n this.element.classList.remove('e-smithchart');\n };\n /**\n * To bind event handlers for smithchart.\n */\n Smithchart.prototype.wireEVents = function () {\n EventHandler.add(this.element, 'click', this.smithchartOnClick, this);\n EventHandler.add(this.element, Browser.touchMoveEvent, this.mouseMove, this);\n EventHandler.add(this.element, Browser.touchEndEvent, this.mouseEnd, this);\n window.addEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.smithchartOnResize.bind(this));\n };\n Smithchart.prototype.mouseMove = function (e) {\n if (e.type === 'touchmove') {\n this.isTouch = true;\n }\n else {\n this.isTouch = e.pointerType === 'touch' || e.pointerType === '2' || this.isTouch;\n }\n if (this.tooltipRenderModule && !this.isTouch) {\n this.tooltipRenderModule.smithchartMouseMove(this, e);\n }\n };\n Smithchart.prototype.mouseEnd = function (e) {\n if (e.type === 'touchend') {\n this.isTouch = true;\n }\n else {\n this.isTouch = e.pointerType === 'touch' || e.pointerType === '2';\n }\n if (this.tooltipRenderModule && this.isTouch) {\n var tooltipElement_1 = this.tooltipRenderModule.smithchartMouseMove(this, e);\n if (tooltipElement_1) {\n this.fadeoutTo = setTimeout(function () {\n tooltipElement_1.fadeOut();\n }, 2000);\n }\n }\n };\n /**\n * To handle the click event for the smithchart.\n */\n /* tslint:disable:no-string-literal */\n Smithchart.prototype.smithchartOnClick = function (e) {\n var targetEle = e.target;\n var targetId = targetEle.id;\n var parentElement = document.getElementById(targetId).parentElement;\n var grpElement = document.getElementById(parentElement.id).parentElement;\n if (grpElement.id === 'containerlegendItem_Group' && this.legendSettings.toggleVisibility) {\n var childElement = parentElement.childNodes[1];\n var circleElement = parentElement.childNodes[0];\n var legendText = childElement.textContent;\n var seriesIndex = void 0;\n var fill = void 0;\n for (var i = 0; i < this.smithchartLegendModule.legendSeries.length; i++) {\n if (legendText === this.smithchartLegendModule.legendSeries[i]['text']) {\n seriesIndex = this.smithchartLegendModule.legendSeries[i].seriesIndex;\n fill = this.smithchartLegendModule.legendSeries[i].fill;\n }\n }\n var seriesElement = document.getElementById(this.element.id + '_svg' + '_seriesCollection' + seriesIndex);\n if (seriesElement.getAttribute('visibility') === 'visible') {\n circleElement.setAttribute('fill', 'gray');\n seriesElement.setAttribute('visibility', 'hidden');\n this.series[seriesIndex].visibility = 'hidden';\n }\n else {\n circleElement.setAttribute('fill', fill);\n seriesElement.setAttribute('visibility', 'visible');\n this.series[seriesIndex].visibility = 'visible';\n }\n }\n };\n /**\n * To unbind event handlers from smithchart.\n */\n Smithchart.prototype.unWireEVents = function () {\n EventHandler.remove(this.element, 'click', this.smithchartOnClick);\n EventHandler.remove(this.element, Browser.touchMoveEvent, this.mouseMove);\n EventHandler.remove(this.element, Browser.touchEndEvent, this.mouseEnd);\n window.removeEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.smithchartOnResize);\n };\n Smithchart.prototype.print = function (id) {\n var exportChart = new ExportUtils(this);\n exportChart.print(id);\n };\n /**\n * Handles the export method for chart control.\n * @param type\n * @param fileName\n */\n Smithchart.prototype.export = function (type, fileName, orientation) {\n var exportMap = new ExportUtils(this);\n exportMap.export(type, fileName, orientation);\n };\n /**\n * To handle the window resize event on smithchart.\n */\n Smithchart.prototype.smithchartOnResize = function (e) {\n var _this = this;\n this.animateSeries = false;\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n this.resizeTo = setTimeout(function () {\n _this.render();\n }, 500);\n return false;\n };\n /**\n * To provide the array of modules needed for smithchart rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n Smithchart.prototype.requiredModules = function () {\n var modules = [];\n if (this.legendSettings.visible) {\n modules.push({\n member: 'SmithchartLegend',\n args: [this]\n });\n }\n for (var i = 0; i < this.series.length; i++) {\n if (this.series[i].tooltip.visible) {\n modules.push({\n member: 'TooltipRender',\n args: [this]\n });\n break;\n }\n }\n return modules;\n };\n /**\n * To Remove the SVG.\n * @return {boolean}\n * @private\n */\n Smithchart.prototype.removeSvg = function () {\n removeElement(this.element.id + '_Secondary_Element');\n var removeLength = 0;\n if (this.svgObject) {\n while (this.svgObject.childNodes.length > removeLength) {\n this.svgObject.removeChild(this.svgObject.firstChild);\n }\n if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) {\n remove(this.svgObject);\n }\n }\n };\n __decorate([\n Property('Impedance')\n ], Smithchart.prototype, \"renderType\", void 0);\n __decorate([\n Property('')\n ], Smithchart.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], Smithchart.prototype, \"height\", void 0);\n __decorate([\n Property(false)\n ], Smithchart.prototype, \"isResponsive\", void 0);\n __decorate([\n Property('Material')\n ], Smithchart.prototype, \"theme\", void 0);\n __decorate([\n Complex({}, SmithchartMargin)\n ], Smithchart.prototype, \"margin\", void 0);\n __decorate([\n Complex({}, SmithchartFont)\n ], Smithchart.prototype, \"font\", void 0);\n __decorate([\n Complex({}, SmithchartBorder)\n ], Smithchart.prototype, \"border\", void 0);\n __decorate([\n Complex({}, Title)\n ], Smithchart.prototype, \"title\", void 0);\n __decorate([\n Collection([{}], SmithchartSeries)\n ], Smithchart.prototype, \"series\", void 0);\n __decorate([\n Complex({}, SmithchartLegendSettings)\n ], Smithchart.prototype, \"legendSettings\", void 0);\n __decorate([\n Complex({}, SmithchartAxis)\n ], Smithchart.prototype, \"horizontalAxis\", void 0);\n __decorate([\n Complex({}, SmithchartAxis)\n ], Smithchart.prototype, \"radialAxis\", void 0);\n __decorate([\n Property(null)\n ], Smithchart.prototype, \"background\", void 0);\n __decorate([\n Property(10)\n ], Smithchart.prototype, \"elementSpacing\", void 0);\n __decorate([\n Property(1)\n ], Smithchart.prototype, \"radius\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"beforePrint\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"animationComplete\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"load\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"loaded\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"legendRender\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"titleRender\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"subtitleRender\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"textRender\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"axisLabelRender\", void 0);\n __decorate([\n Event()\n ], Smithchart.prototype, \"seriesRender\", void 0);\n Smithchart = __decorate([\n NotifyPropertyChanges\n ], Smithchart);\n return Smithchart;\n}(Component));\nexport { Smithchart };\n","import { ClosestPoint, SmithchartRect } from '../../smithchart/utils/utils';\nimport { Tooltip } from '@syncfusion/ej2-svg-base';\nimport { isNullOrUndefined, createElement } from '@syncfusion/ej2-base';\nvar TooltipRender = /** @class */ (function () {\n function TooltipRender() {\n }\n TooltipRender.prototype.smithchartMouseMove = function (smithchart, e) {\n var touchArg;\n var pageX;\n var pageY;\n if (e.type === 'touchend' || e.type === 'touchmove') {\n touchArg = e;\n pageX = touchArg.changedTouches[0].clientX;\n pageY = touchArg.changedTouches[0].clientY;\n this.tooltipElement = undefined;\n }\n else {\n pageY = e.clientY;\n pageX = e.clientX;\n }\n this.setMouseXY(smithchart, pageX, pageY);\n for (var i = 0; i < smithchart.series.length; i++) {\n var series = smithchart.series[i];\n var seriesIndex = i;\n var closestPoint = new ClosestPoint();\n closestPoint = this.closestPointXY(smithchart, this.mouseX, this.mouseY, series, seriesIndex);\n if (closestPoint.location && series.tooltip.visible && series.visibility === 'visible') {\n this.createTooltip(smithchart, e, closestPoint.index, seriesIndex, series);\n break;\n }\n else if (this.tooltipElement && this.tooltipElement.enable && !series.tooltip.template) {\n this.tooltipElement.fadeOut();\n this.tooltipElement.enable = false;\n }\n else if (series.tooltip.template) {\n this.tooltipElement.fadeOut();\n }\n }\n return this.tooltipElement;\n };\n TooltipRender.prototype.setMouseXY = function (smithchart, pageX, pageY) {\n var rect = smithchart.element.getBoundingClientRect();\n var svgRect = document.getElementById(smithchart.element.id + '_svg').getBoundingClientRect();\n this.mouseX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0);\n this.mouseY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0);\n };\n TooltipRender.prototype.createTooltip = function (smithchart, e, pointindex, seriesindex, series) {\n var pointX = series.points[pointindex].resistance;\n var pointY = series.points[pointindex].reactance;\n var tooltipText = [pointX + ' ' + ':' + ' ' + '
' + pointY + ' '];\n var markerHeight = smithchart.series[seriesindex].marker.height / 2;\n var div = document.getElementById(smithchart.element.id + '_smithchart_tooltip_div');\n if (isNullOrUndefined(div)) {\n div = createElement('div', { id: smithchart.element.id + '_smithchart_tooltip_div',\n styles: 'pointer-events: none; position: absolute;z-index:1;' });\n document.getElementById(smithchart.element.id + '_Secondary_Element').appendChild(div);\n }\n this.tooltipElement = new Tooltip({\n enable: true,\n header: '
' + series.name + ' ',\n content: tooltipText,\n border: series.tooltip.border,\n fill: smithchart.themeStyle.tooltipFill,\n data: { reactance: pointY },\n template: series.tooltip.template,\n location: { x: this.locationX + smithchart.element.offsetLeft,\n y: this.locationY - markerHeight + smithchart.element.offsetTop },\n shared: false,\n areaBounds: new SmithchartRect(smithchart.bounds.x, smithchart.bounds.y, smithchart.bounds.width, smithchart.bounds.height),\n palette: [series.fill || smithchart.seriesColors[seriesindex % smithchart.seriesColors.length]],\n shapes: ['Circle'],\n theme: smithchart.theme\n });\n this.tooltipElement.textStyle.fontFamily = 'Roboto, Segoe UI, Noto, Sans-serif';\n this.tooltipElement.appendTo(div);\n };\n TooltipRender.prototype.closestPointXY = function (smithchart, x, y, series, seriesindex) {\n var pointIndex;\n var chartPoint;\n var closePoint;\n for (var j = 0; j < series.points.length; j++) {\n chartPoint = smithchart.seriesrender.getLocation(seriesindex, j);\n this.locationX = chartPoint.x;\n this.locationY = chartPoint.y;\n pointIndex = j;\n var a = x - chartPoint.x;\n var b = y - chartPoint.y;\n var distance = Math.abs(Math.sqrt((a * a) + (b * b)));\n if (distance < series.marker.width) {\n closePoint = chartPoint;\n pointIndex = j;\n break;\n }\n }\n return { location: closePoint, index: pointIndex };\n };\n /**\n * Get module name.\n */\n TooltipRender.prototype.getModuleName = function () {\n return 'TooltipRender';\n };\n /**\n * To destroy the legend.\n * @return {void}\n * @private\n */\n TooltipRender.prototype.destroy = function (smithchart) {\n /**\n * Destroy method performed here\n */\n };\n return TooltipRender;\n}());\nexport { TooltipRender };\n","import { measureText, TextOption, renderTextElement, CircleOption, PathOption, RectOption } from '../../smithchart/utils/helper';\nimport { SmithchartRect, LegendSeries } from '../../smithchart/utils/utils';\n/* tslint:disable:no-string-literal */\nvar SmithchartLegend = /** @class */ (function () {\n function SmithchartLegend() {\n this.legendSeries = [];\n }\n SmithchartLegend.prototype.renderLegend = function (smithchart) {\n this.calculateLegendBounds(smithchart);\n this._drawLegend(smithchart);\n return this.legendActualBounds;\n };\n SmithchartLegend.prototype.calculateLegendBounds = function (smithchart) {\n var legendSeries = new LegendSeries();\n this.legendSeries = [];\n var padding = 10;\n var legend = smithchart.legendSettings;\n var legendSizeHeight = legend.height;\n var legendSizeWidth = legend.width;\n var itemPadding = legend.itemPadding > 0 ? legend.itemPadding : 0;\n var position = legend.position.toLowerCase();\n var font = legend.title.textStyle;\n var width = 0;\n var height = 0;\n var legendItemWidth = 0;\n var legendItemHeight = 0;\n var legendHeight = 0;\n var svgObjectWidth = smithchart.availableSize.width - ((smithchart.elementSpacing * 4) - (legend.border.width * 2)\n + (smithchart.border.width * 2));\n var svgObjectHeight = smithchart.availableSize.height - ((smithchart.elementSpacing * 4) - (legend.border.width * 2)\n + (smithchart.border.width * 2));\n var rowCount = legend.rowCount;\n var columnCount = legend.columnCount;\n var titleSize = measureText(smithchart.legendSettings['title']['text'], font);\n var maxRowWidth = 0;\n var totalRowHeight = 0;\n var curRowWidth = 0;\n var curRowHeight = 0;\n var allowItems;\n var itemsCountRow = 0;\n var length = smithchart.series.length;\n var legendBounds;\n if (smithchart.legendSettings.visible && length !== 0) {\n if (position === 'bottom' || position === 'top' || position === 'custom') {\n if ((rowCount && columnCount) && (rowCount <= columnCount)) {\n rowCount = length / columnCount;\n }\n else if (rowCount == null && columnCount != null) {\n rowCount = length / columnCount;\n }\n else if (rowCount == null && columnCount == null) {\n rowCount = 1;\n }\n if (rowCount) {\n allowItems = Math.ceil(length / rowCount);\n }\n }\n else {\n if ((rowCount && columnCount) && (rowCount <= columnCount)) {\n columnCount = length / rowCount;\n }\n else if (rowCount != null && columnCount == null) {\n columnCount = length / rowCount;\n }\n else if (rowCount == null && columnCount == null) {\n columnCount = 1;\n }\n if (columnCount) {\n allowItems = columnCount;\n }\n }\n for (var i = 0; i < length; i++) {\n this.legendSeries.push({\n text: smithchart.series[i]['name'] ? smithchart.series[i]['name'] : 'series' + i,\n seriesIndex: i,\n shape: smithchart.legendSettings.shape,\n fill: smithchart.series[i].fill || smithchart.seriesColors[i % smithchart.seriesColors.length],\n bounds: null\n });\n var legendsize = this._getLegendSize(smithchart, this.legendSeries[i]);\n legendItemWidth = Math.max(legendsize['width'], legendItemWidth);\n legendItemHeight = Math.max(legendsize['height'], legendItemHeight);\n this.legendSeries[i]['bounds'] = { width: legendItemWidth, height: legendItemHeight };\n itemsCountRow = itemsCountRow + 1;\n curRowWidth = curRowWidth + legendItemWidth + itemPadding;\n curRowHeight = Math.max(legendItemHeight, curRowHeight);\n if (position === 'top' || position === 'bottom' || position === 'custom') {\n if (curRowWidth > svgObjectWidth) {\n curRowWidth -= legendsize.width + itemPadding;\n maxRowWidth = Math.max(maxRowWidth, curRowWidth);\n curRowWidth = legendsize.width + itemPadding;\n totalRowHeight = totalRowHeight + curRowHeight + itemPadding;\n }\n }\n if (itemsCountRow === allowItems || i === length - 1) {\n maxRowWidth = Math.max(maxRowWidth, curRowWidth);\n totalRowHeight = totalRowHeight + curRowHeight + itemPadding;\n legendHeight = totalRowHeight;\n itemsCountRow = 0;\n curRowHeight = 0;\n curRowWidth = 0;\n }\n }\n width = (titleSize.width) > maxRowWidth - itemPadding ? (titleSize.width + padding * 2 + itemPadding) :\n maxRowWidth + padding * 2 - (smithchart.border.width * 2);\n height = legendHeight + smithchart.elementSpacing;\n legendBounds = { x: 0, y: 0, width: width, height: height };\n }\n this.legendActualBounds = legendBounds;\n if (legendSizeWidth != null) {\n this.legendActualBounds.width = legendSizeWidth;\n }\n if (legendSizeHeight != null) {\n this.legendActualBounds.height = legendSizeHeight;\n }\n };\n SmithchartLegend.prototype._getLegendSize = function (smithchart, series) {\n var legend = smithchart.legendSettings;\n var symbolWidth = legend.itemStyle.width;\n var symbolHeight = legend.itemStyle.height;\n var textSize = measureText(series.text, legend.textStyle);\n var width = symbolWidth + textSize.width + legend.shapePadding;\n var height = Math.max(symbolHeight, textSize.height);\n return { width: width, height: height };\n };\n // tslint:disable:max-func-body-length\n SmithchartLegend.prototype._drawLegend = function (smithchart) {\n var legend = smithchart.legendSettings;\n var legendPosition = legend.position.toLowerCase();\n var alignment = legend.alignment;\n var legendBounds = this.legendActualBounds;\n var maxWidth = 0;\n var startX;\n var startY;\n var titleFont = smithchart.title.font ? smithchart.title.font : smithchart.title.textStyle;\n var smithchartTitleHeight = measureText(smithchart.title.text, titleFont).height;\n var smithchartSubtitleHeight = measureText(smithchart.title.subtitle.text, smithchart.title.subtitle.textStyle).height;\n var elementSpacing = smithchart.elementSpacing;\n var offset = smithchartTitleHeight + smithchartSubtitleHeight + elementSpacing + smithchart.margin.top;\n var itemPadding = legend.itemPadding > 0 ? legend.itemPadding : 0;\n var svgObjectWidth = smithchart.availableSize.width;\n var svgObjectHeight = smithchart.availableSize.height;\n var legendBorder = legend.border.width;\n var legendWidth = 0;\n var titleSize = measureText(legend['title']['text'], legend.title.textStyle);\n var legendTitleHeight = titleSize.height;\n var borderSize = smithchart.border.width;\n var svgWidth = svgObjectWidth - ((borderSize * 2));\n var svgHeight = svgObjectHeight - ((borderSize * 2));\n legendBounds.height += legendTitleHeight;\n if (legendPosition !== 'custom') {\n switch (legendPosition) {\n case 'bottom':\n legendBounds.y = svgHeight - (legendBounds.height + (legendBorder) + elementSpacing);\n break;\n case 'top':\n legendBounds.y = borderSize + offset;\n break;\n case 'right':\n legendBounds.x = svgWidth - legendBounds.width - (elementSpacing * 2);\n break;\n case 'left':\n legendBounds.x = borderSize + (elementSpacing * 2);\n break;\n }\n if (legendPosition === 'left' || legendPosition === 'right') {\n switch (alignment) {\n case 'Center':\n legendBounds.y = (svgHeight / 2) - ((legendBounds.height + legendBorder * 2) / 2) + (elementSpacing / 2);\n break;\n case 'Near':\n legendBounds.y = borderSize + (elementSpacing * 2) + offset;\n break;\n case 'Far':\n legendBounds.y = svgHeight - (legendBounds.height + (legendBorder)) - (elementSpacing * 2);\n break;\n }\n }\n else {\n switch (alignment) {\n case 'Center':\n legendBounds.x = (svgWidth / 2) - ((legendBounds.width + legendBorder * 2) / 2) + (elementSpacing / 2);\n break;\n case 'Near':\n legendBounds.x = borderSize + (elementSpacing * 2);\n break;\n case 'Far':\n legendBounds.x = svgWidth - (legendBounds.width + (legendBorder)) - (elementSpacing * 2);\n break;\n }\n }\n }\n else {\n legendBounds.y = (legend.location.y < svgHeight) ? legend.location.y : 0;\n legendBounds.x = (legend.location.x < svgWidth) ? legend.location.x : 0;\n }\n if (legendPosition === 'bottom' || legendPosition === 'top') {\n for (var i = 0; i < this.legendSeries.length; i++) {\n legendWidth += this.legendSeries[i].bounds.width + itemPadding;\n if (legendWidth > svgWidth) {\n legendBounds.x = (svgWidth / 2) - ((legendBounds.width + legendBorder * 2) / 2) + (elementSpacing / 2);\n break;\n }\n }\n }\n var gLegendEle = smithchart.renderer.createGroup({ 'id': smithchart.element.id + '_legend_group' });\n smithchart.svgObject.appendChild(gLegendEle);\n this.legendItemGroup = smithchart.renderer.createGroup({ 'id': smithchart.element.id + 'legendItem_Group' });\n var currentX = startX = elementSpacing;\n var currentY = startY = elementSpacing;\n if (legend.title.text !== '' && legend.title.visible) {\n gLegendEle.appendChild(this.drawLegendTitle(smithchart, legend, legendBounds, gLegendEle));\n currentY = startY = elementSpacing + legendTitleHeight;\n }\n for (var k = 0; k < this.legendSeries.length; k++) {\n if ((legend.rowCount < legend.columnCount || legend.rowCount === legend.columnCount) &&\n (legendPosition === 'top' || legendPosition === 'bottom' || legendPosition === 'custom')) {\n if ((currentX + this.legendSeries[k]['bounds'].width) > legendBounds.width + startX) {\n currentX = elementSpacing;\n currentY += this.legendSeries[k]['bounds'].height + itemPadding;\n }\n this.legendGroup = this.drawLegendItem(smithchart, legend, this.legendSeries[k], k, currentX, (currentY), legendBounds);\n gLegendEle.appendChild(this.legendGroup);\n currentX += this.legendSeries[k]['bounds'].width + itemPadding;\n }\n else {\n if (((currentY + this.legendSeries[k]['bounds'].height + itemPadding) +\n legendTitleHeight + borderSize > legendBounds.height + startY)) {\n currentY = startY;\n currentX += maxWidth + (itemPadding);\n }\n this.legendGroup = this.drawLegendItem(smithchart, legend, this.legendSeries[k], k, (currentX), (currentY), legendBounds);\n gLegendEle.appendChild(this.legendGroup);\n currentY += this.legendSeries[k]['bounds'].height + itemPadding;\n maxWidth = Math.max(maxWidth, this.legendSeries[k]['bounds'].width);\n }\n }\n gLegendEle.setAttribute('transform', 'translate(' + legendBounds.x.toString() + ',' + legendBounds.y.toString() + ')');\n this.drawLegendBorder(gLegendEle, smithchart, legend, legendBounds);\n };\n SmithchartLegend.prototype.drawLegendBorder = function (gLegendEle, smithchart, legend, legendBounds) {\n var borderRect = new RectOption(smithchart.element.id + '_svg' + '_legendRect', 'none', legend.border, 1, new SmithchartRect(0, 0, legendBounds.width, legendBounds.height));\n gLegendEle.appendChild(smithchart.renderer.drawRectangle(borderRect));\n };\n SmithchartLegend.prototype.drawLegendTitle = function (smithchart, legend, legendBounds, gLegendEle) {\n var elementSpacing = smithchart.elementSpacing;\n var titleSize = measureText(legend.title.text, legend.title.textStyle);\n var titleWidth = titleSize.width;\n var titleHeight = titleSize.height;\n var textAlignment = legend.title.textAlignment;\n var startX = 0;\n var legendBoundsWidth = legendBounds.width;\n var startY = elementSpacing + (titleHeight / 2);\n switch (textAlignment) {\n case 'Far':\n startX = legendBoundsWidth - titleWidth - startX;\n break;\n case 'Center':\n startX = legendBoundsWidth / 2 - (titleWidth) / 2;\n break;\n }\n if (startX < 0) {\n startX = 0;\n legendBoundsWidth = titleWidth;\n }\n if (legendBoundsWidth < titleWidth + startX) {\n legendBoundsWidth = titleWidth + startX;\n }\n var options = new TextOption(smithchart.element.id + '_LegendTitleText', startX, startY, 'start', legend.title.text);\n var element = renderTextElement(options, legend.title.textStyle, smithchart.themeStyle.legendLabel, gLegendEle);\n element.setAttribute('aria-label', legend.title.description || legend.title.text);\n return element;\n };\n SmithchartLegend.prototype.drawLegendItem = function (smithchart, legend, legendSeries, k, x, y, legendBounds) {\n var location;\n var radius;\n var symbol = legend.itemStyle;\n var itemPadding = legend.itemPadding;\n var textHeight;\n radius = Math.sqrt(symbol['width'] * symbol['width'] + symbol['height'] * symbol['height']) / 2;\n textHeight = measureText(legendSeries['text'], legend.textStyle).height;\n location = {\n x: x + symbol['width'] / 2,\n y: (y + (textHeight > symbol['height'] ? textHeight : symbol['height']) / 2)\n };\n var legendGroup = smithchart.renderer.createGroup({ id: smithchart.element.id + '_svg' + '_Legend' + k.toString() });\n legendGroup['style']['cursor'] = legend.toggleVisibility ? 'pointer' : 'default';\n var legendEventArgs = { text: legendSeries['text'], fill: legendSeries['fill'],\n shape: legendSeries['shape'], name: 'legendRender', cancel: false };\n smithchart.trigger('legendRender', legendEventArgs);\n var shape = this.drawLegendShape(smithchart, legendSeries, location.x, location.y, k, legend, legendEventArgs);\n legendGroup.appendChild(shape);\n var options = new TextOption(smithchart.element.id + '_LegendItemText' + k.toString(), location.x + symbol['width'] / 2 + legend.shapePadding, location.y + textHeight / 4, 'start', legendEventArgs.text);\n var element = renderTextElement(options, legend.textStyle, smithchart.themeStyle.legendLabel, legendGroup);\n element.setAttribute('aria-label', legend.description || 'Click to show or hide the ' + options.text + ' series');\n legendGroup.appendChild(element);\n this.legendItemGroup.appendChild(legendGroup);\n return this.legendItemGroup;\n };\n SmithchartLegend.prototype.drawLegendShape = function (smithchart, legendSeries, locX, locY, index, legend, legendEventArgs) {\n var element;\n var circleOptions;\n var pathOptions;\n var path;\n var symbol = legend.itemStyle;\n var width = symbol['width'];\n var height = symbol['height'];\n var x = locX + (-width / 2);\n var y = locY + (-height / 2);\n var border = { color: symbol.border.color, width: symbol.border.width };\n var opacity = 1;\n var fill = (smithchart.series[index].visibility === 'visible') ? legendEventArgs.fill : 'grey';\n var shape = legendEventArgs.shape.toLowerCase();\n var radius = Math.sqrt(height * height + width * width) / 2;\n switch (shape) {\n case 'circle':\n circleOptions = new CircleOption(smithchart.element.id + '_svg' + '_LegendItemShape' + index.toString(), fill, border, opacity, locX, locY, radius, null);\n element = smithchart.renderer.drawCircle(circleOptions);\n break;\n case 'rectangle':\n path = 'M' + ' ' + x + ' ' + (locY + (-height / 2)) + ' ' +\n 'L' + ' ' + ((width / 2) + locX) + ' ' + (locY + (-height / 2)) + ' ' +\n 'L' + ' ' + (locX + (width / 2)) + ' ' + (locY + (height / 2)) + ' ' +\n 'L' + ' ' + x + ' ' + (locY + (height / 2)) + ' ' +\n 'L' + ' ' + x + ' ' + (locY + (-height / 2)) + ' z';\n pathOptions = new PathOption(smithchart.element.id + '_svg' + '_LegendItemShape' + index.toString(), fill, border.width, border.color, 1, '', path);\n element = smithchart.renderer.drawPath(pathOptions);\n break;\n case 'diamond':\n path = 'M' + ' ' + x + ' ' + locY + ' ' +\n 'L' + ' ' + locX + ' ' + (locY + (-height / 2)) + ' ' +\n 'L' + ' ' + ((width / 2) + locX) + ' ' + locY + ' ' +\n 'L' + ' ' + locX + ' ' + (locY + (height / 2)) + ' ' +\n 'L' + ' ' + x + ' ' + locY + ' z';\n pathOptions = new PathOption(smithchart.element.id + '_svg' + '_LegendItemShape' + index.toString(), fill, border.width, border.color, 1, '', path);\n element = smithchart.renderer.drawPath(pathOptions);\n break;\n case 'pentagon':\n var eq = 72;\n for (var j = 0; j <= 5; j++) {\n var xValue = radius * Math.cos((Math.PI / 180) * (j * eq));\n var yValue = radius * Math.sin((Math.PI / 180) * (j * eq));\n if (j === 0) {\n path = 'M' + ' ' + (xValue + locX) + ' ' + (locY + yValue) + ' ';\n }\n else {\n path = path.concat('L' + ' ' + (locX + xValue) + ' ' + (locY + yValue) + ' ');\n }\n }\n path = path.concat('Z');\n pathOptions = new PathOption(smithchart.element.id + '_svg' + '_LegendItemShape' + index.toString(), fill, border.width, border.color, 1, '', path);\n element = smithchart.renderer.drawPath(pathOptions);\n break;\n case 'triangle':\n path = 'M' + ' ' + x + ' ' + ((height / 2) + locY) + ' ' +\n 'L' + ' ' + locX + ' ' + (locY + (-height / 2)) + ' ' +\n 'L' + ' ' + (locX + (width / 2)) + ' ' + (locY + (height / 2)) + ' ' +\n 'L' + ' ' + x + ' ' + (locY + (height / 2)) + ' Z';\n pathOptions = new PathOption(smithchart.element.id + '_svg' + '_LegendItemShape' + index.toString(), fill, border.width, border.color, 1, '', path);\n element = smithchart.renderer.drawPath(pathOptions);\n break;\n }\n return element;\n };\n /**\n * Get module name.\n */\n SmithchartLegend.prototype.getModuleName = function () {\n return 'SmithchartLegend';\n };\n /**\n * To destroy the legend.\n * @return {void}\n * @private\n */\n SmithchartLegend.prototype.destroy = function (smithchart) {\n /**\n * Destroy method performed here\n */\n };\n return SmithchartLegend;\n}());\nexport { SmithchartLegend };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n/**\n * Sparkline base API Class declarations.\n */\nimport { Property, ChildProperty, Complex } from '@syncfusion/ej2-base';\n/**\n * Configures the borders in the Sparkline.\n */\nvar SparklineBorder = /** @class */ (function (_super) {\n __extends(SparklineBorder, _super);\n function SparklineBorder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], SparklineBorder.prototype, \"color\", void 0);\n __decorate([\n Property(0)\n ], SparklineBorder.prototype, \"width\", void 0);\n return SparklineBorder;\n}(ChildProperty));\nexport { SparklineBorder };\n/**\n * Configures the fonts in sparklines.\n */\nvar SparklineFont = /** @class */ (function (_super) {\n __extends(SparklineFont, _super);\n function SparklineFont() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], SparklineFont.prototype, \"size\", void 0);\n __decorate([\n Property(null)\n ], SparklineFont.prototype, \"color\", void 0);\n __decorate([\n Property('Roboto, Segoe UI, Noto, Sans-serif')\n ], SparklineFont.prototype, \"fontFamily\", void 0);\n __decorate([\n Property(null)\n ], SparklineFont.prototype, \"fontWeight\", void 0);\n __decorate([\n Property(null)\n ], SparklineFont.prototype, \"fontStyle\", void 0);\n __decorate([\n Property(1)\n ], SparklineFont.prototype, \"opacity\", void 0);\n return SparklineFont;\n}(ChildProperty));\nexport { SparklineFont };\n/**\n * To configure the tracker line settings.\n */\nvar TrackLineSettings = /** @class */ (function (_super) {\n __extends(TrackLineSettings, _super);\n function TrackLineSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], TrackLineSettings.prototype, \"visible\", void 0);\n __decorate([\n Property(null)\n ], TrackLineSettings.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], TrackLineSettings.prototype, \"width\", void 0);\n return TrackLineSettings;\n}(ChildProperty));\nexport { TrackLineSettings };\n/**\n * To configure the tooltip settings for sparkline.\n */\nvar SparklineTooltipSettings = /** @class */ (function (_super) {\n __extends(SparklineTooltipSettings, _super);\n function SparklineTooltipSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], SparklineTooltipSettings.prototype, \"visible\", void 0);\n __decorate([\n Property('')\n ], SparklineTooltipSettings.prototype, \"fill\", void 0);\n __decorate([\n Property('')\n ], SparklineTooltipSettings.prototype, \"template\", void 0);\n __decorate([\n Property('')\n ], SparklineTooltipSettings.prototype, \"format\", void 0);\n __decorate([\n Complex({ color: '#cccccc', width: 0.5 }, SparklineBorder)\n ], SparklineTooltipSettings.prototype, \"border\", void 0);\n __decorate([\n Complex({ size: '13px', fontWeight: 'Normal', fontStyle: 'Normal', fontFamily: 'Roboto, Segoe UI, Noto, Sans-serif' }, SparklineFont)\n ], SparklineTooltipSettings.prototype, \"textStyle\", void 0);\n __decorate([\n Complex({}, TrackLineSettings)\n ], SparklineTooltipSettings.prototype, \"trackLineSettings\", void 0);\n return SparklineTooltipSettings;\n}(ChildProperty));\nexport { SparklineTooltipSettings };\n/**\n * To configure the sparkline container area customization\n */\nvar ContainerArea = /** @class */ (function (_super) {\n __extends(ContainerArea, _super);\n function ContainerArea() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('transparent')\n ], ContainerArea.prototype, \"background\", void 0);\n __decorate([\n Complex({}, SparklineBorder)\n ], ContainerArea.prototype, \"border\", void 0);\n return ContainerArea;\n}(ChildProperty));\nexport { ContainerArea };\n/**\n * To configure axis line settings\n */\nvar LineSettings = /** @class */ (function (_super) {\n __extends(LineSettings, _super);\n function LineSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], LineSettings.prototype, \"visible\", void 0);\n __decorate([\n Property(null)\n ], LineSettings.prototype, \"color\", void 0);\n __decorate([\n Property('')\n ], LineSettings.prototype, \"dashArray\", void 0);\n __decorate([\n Property(1)\n ], LineSettings.prototype, \"width\", void 0);\n __decorate([\n Property(1)\n ], LineSettings.prototype, \"opacity\", void 0);\n return LineSettings;\n}(ChildProperty));\nexport { LineSettings };\n/**\n * To configure the sparkline rangeband\n */\nvar RangeBandSettings = /** @class */ (function (_super) {\n __extends(RangeBandSettings, _super);\n function RangeBandSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], RangeBandSettings.prototype, \"startRange\", void 0);\n __decorate([\n Property(null)\n ], RangeBandSettings.prototype, \"endRange\", void 0);\n __decorate([\n Property(null)\n ], RangeBandSettings.prototype, \"color\", void 0);\n __decorate([\n Property(null)\n ], RangeBandSettings.prototype, \"opacity\", void 0);\n return RangeBandSettings;\n}(ChildProperty));\nexport { RangeBandSettings };\n/**\n * To configure the sparkline axis\n */\nvar AxisSettings = /** @class */ (function (_super) {\n __extends(AxisSettings, _super);\n function AxisSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], AxisSettings.prototype, \"minX\", void 0);\n __decorate([\n Property(null)\n ], AxisSettings.prototype, \"maxX\", void 0);\n __decorate([\n Property(null)\n ], AxisSettings.prototype, \"minY\", void 0);\n __decorate([\n Property(null)\n ], AxisSettings.prototype, \"maxY\", void 0);\n __decorate([\n Property(0)\n ], AxisSettings.prototype, \"value\", void 0);\n __decorate([\n Complex({}, LineSettings)\n ], AxisSettings.prototype, \"lineSettings\", void 0);\n return AxisSettings;\n}(ChildProperty));\nexport { AxisSettings };\n/**\n * To configure the sparkline padding.\n */\nvar Padding = /** @class */ (function (_super) {\n __extends(Padding, _super);\n function Padding() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(5)\n ], Padding.prototype, \"left\", void 0);\n __decorate([\n Property(5)\n ], Padding.prototype, \"right\", void 0);\n __decorate([\n Property(5)\n ], Padding.prototype, \"bottom\", void 0);\n __decorate([\n Property(5)\n ], Padding.prototype, \"top\", void 0);\n return Padding;\n}(ChildProperty));\nexport { Padding };\n/**\n * To configure the sparkline marker options.\n */\nvar SparklineMarkerSettings = /** @class */ (function (_super) {\n __extends(SparklineMarkerSettings, _super);\n function SparklineMarkerSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property([])\n ], SparklineMarkerSettings.prototype, \"visible\", void 0);\n __decorate([\n Property(1)\n ], SparklineMarkerSettings.prototype, \"opacity\", void 0);\n __decorate([\n Property(5)\n ], SparklineMarkerSettings.prototype, \"size\", void 0);\n __decorate([\n Property('#00bdae')\n ], SparklineMarkerSettings.prototype, \"fill\", void 0);\n __decorate([\n Complex({ width: 1 }, SparklineBorder)\n ], SparklineMarkerSettings.prototype, \"border\", void 0);\n return SparklineMarkerSettings;\n}(ChildProperty));\nexport { SparklineMarkerSettings };\n/**\n * To configure the datalabel offset\n */\nvar LabelOffset = /** @class */ (function (_super) {\n __extends(LabelOffset, _super);\n function LabelOffset() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], LabelOffset.prototype, \"x\", void 0);\n __decorate([\n Property(0)\n ], LabelOffset.prototype, \"y\", void 0);\n return LabelOffset;\n}(ChildProperty));\nexport { LabelOffset };\n/**\n * To configure the sparkline dataLabel options.\n */\nvar SparklineDataLabelSettings = /** @class */ (function (_super) {\n __extends(SparklineDataLabelSettings, _super);\n function SparklineDataLabelSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property([])\n ], SparklineDataLabelSettings.prototype, \"visible\", void 0);\n __decorate([\n Property(1)\n ], SparklineDataLabelSettings.prototype, \"opacity\", void 0);\n __decorate([\n Property('transparent')\n ], SparklineDataLabelSettings.prototype, \"fill\", void 0);\n __decorate([\n Property('')\n ], SparklineDataLabelSettings.prototype, \"format\", void 0);\n __decorate([\n Complex({ color: 'transparent', width: 0 }, SparklineBorder)\n ], SparklineDataLabelSettings.prototype, \"border\", void 0);\n __decorate([\n Complex({ size: '14px', fontWeight: 'Medium', fontStyle: 'Medium', fontFamily: 'Roboto, Segoe UI, Noto, Sans-serif' }, SparklineFont)\n ], SparklineDataLabelSettings.prototype, \"textStyle\", void 0);\n __decorate([\n Complex({}, LabelOffset)\n ], SparklineDataLabelSettings.prototype, \"offset\", void 0);\n return SparklineDataLabelSettings;\n}(ChildProperty));\nexport { SparklineDataLabelSettings };\n","import { extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { PathOption, drawPath, drawRectangle, RectOption, Rect, CircleOption, drawCircle } from '../utils/helper';\nimport { measureText, renderTextElement, TextOption } from '../utils/helper';\n/**\n * Sparkline rendering calculation file\n */\nvar SparklineRenderer = /** @class */ (function () {\n /**\n * Sparkline data calculations\n * @param sparkline\n */\n function SparklineRenderer(sparkline) {\n this.sparkline = sparkline;\n }\n /**\n * To process the sparkline data\n */\n SparklineRenderer.prototype.processData = function (data) {\n if (data === void 0) { data = this.sparkline.dataSource; }\n if (!this.sparkline.dataSource.length) {\n return;\n }\n else if (!isNaN(data[0]) || this.sparkline.valueType === 'Numeric') {\n this.sparkline.sparklineData = data; // extend([], data) as Object[];\n }\n else {\n this['process' + this.sparkline.valueType]();\n }\n this.axisCalculation();\n };\n /**\n * To process sparkline category data.\n */\n SparklineRenderer.prototype.processCategory = function (data, x, y) {\n var _this = this;\n if (data === void 0) { data = this.sparkline.dataSource; }\n if (x === void 0) { x = this.sparkline.xName; }\n if (y === void 0) { y = this.sparkline.yName; }\n var temp = [];\n var xValues = [];\n data.forEach(function (value, index) {\n if (xValues.indexOf(value[x]) === -1) {\n xValues.push(value[x]);\n }\n var currentData = {};\n currentData[_this.sparkline.xName] = xValues.indexOf(value[x]);\n currentData[_this.sparkline.yName] = value[y];\n temp.push(currentData);\n });\n this.sparkline.sparklineData = temp;\n };\n /**\n * To process sparkline DateTime data.\n */\n SparklineRenderer.prototype.processDateTime = function (data, x, y) {\n if (data === void 0) { data = this.sparkline.dataSource; }\n if (x === void 0) { x = this.sparkline.xName; }\n if (y === void 0) { y = this.sparkline.yName; }\n var temp = [];\n data.forEach(function (value, index) {\n var currentData = {};\n currentData[x] = value[x].getTime();\n currentData[y] = value[y];\n temp.push(currentData);\n });\n this.sparkline.sparklineData = temp;\n };\n /**\n * To render sparkline series.\n * @private\n */\n SparklineRenderer.prototype.renderSeries = function () {\n var spark = this.sparkline;\n this.clipId = spark.element.id + '_sparkline_clip_path';\n this.drawAxis();\n var args = {\n name: 'seriesRendering', cancel: false, lineWidth: spark.lineWidth, border: spark.border, fill: spark.fill, sparkline: spark\n };\n spark.trigger(args.name, args);\n if (!this.visiblePoints || args.cancel) {\n return;\n }\n if (spark.type !== 'Pie' && spark.type !== 'WinLoss' && spark.rangeBandSettings.length) {\n var group = this.sparkline.renderer.createGroup({ id: this.sparkline.element.id + '_sparkline_rangeband_g' });\n for (var i = 0; i < spark.rangeBandSettings.length; i++) {\n if ((spark.axisSettings.minY <= spark.rangeBandSettings[i].startRange) ||\n (spark.axisSettings.maxY >= spark.rangeBandSettings[i].endRange)) {\n this.rangeBand(spark.rangeBandSettings[i], group, i);\n }\n }\n this.sparkline.svgObject.appendChild(group);\n }\n this['render' + spark.type](this.visiblePoints, args);\n this.renderMarker(this.visiblePoints);\n this.renderLabel(this.visiblePoints);\n };\n /**\n * To render a range band\n */\n SparklineRenderer.prototype.rangeBand = function (rangeBandSettings, group, index) {\n var model = this.sparkline;\n var height = (model.availableSize.height) - model.padding.top * 2;\n var width = (model.availableSize.width) - model.padding.left * 2;\n var stValue = rangeBandSettings.startRange;\n var edValue = rangeBandSettings.endRange;\n var stHeight = (height - ((height / this.unitY) * (stValue - this.min))) + model.padding.top;\n var edHeight = (height - ((height / this.unitY) * (edValue - this.min))) + model.padding.top;\n if (edHeight > (height + model.padding.top)) {\n edHeight = (height + model.padding.top);\n }\n else if (edHeight < (0 + model.padding.top)) {\n edHeight = (0 + model.padding.top);\n }\n if (stHeight > (height + model.padding.top)) {\n stHeight = (height + model.padding.top);\n }\n else if (stHeight < (0 + model.padding.top)) {\n stHeight = (0 + model.padding.top);\n }\n var path = 'M ' + (model.padding.left) + ' ' + stHeight + ' L ' + (width + (model.padding.left)) + ' ' + stHeight +\n ' L ' + (width + (model.padding.left)) + ' ' + edHeight + ' L ' + (model.padding.left) + ' ' + edHeight + ' Z ';\n var pathOption = {\n 'id': model.element.id + '_rangeBand_' + index,\n 'fill': rangeBandSettings.color,\n 'opacity': rangeBandSettings.opacity,\n 'stroke': 'transparent',\n 'stroke-width': model.lineWidth,\n 'd': path,\n 'stroke-dasharray': ''\n };\n drawPath(this.sparkline, pathOption, group);\n };\n /**\n * To render line series\n */\n SparklineRenderer.prototype.renderLine = function (points, args) {\n var spark = this.sparkline;\n var g = this.sparkline.renderer.createGroup({ id: spark.element.id + '_sparkline_g',\n 'clip-path': 'url(#' + this.clipId + ')' });\n var pathOption = new PathOption(spark.element.id + '_sparkline_line', 'transparent', args.lineWidth, args.fill, spark.opacity);\n var d = '';\n for (var i = 0, len = points.length; i < len; i++) {\n if (i === 0) {\n d = 'M ' + points[0].x + ' ' + points[i].y + ' ';\n }\n d += 'L ' + points[i].x + ' ' + points[i].y + ' ';\n }\n pathOption.d = d;\n drawPath(this.sparkline, pathOption, g);\n this.sparkline.svgObject.appendChild(g);\n };\n /**\n * To render pie series\n */\n /* tslint:disable:no-string-literal */\n SparklineRenderer.prototype.renderPie = function (points, args) {\n var spark = this.sparkline;\n var height = spark.availableSize.height - (spark.padding.top + spark.padding.bottom);\n var width = spark.availableSize.width - (spark.padding.left + spark.padding.right);\n var area = (height <= width) ? height / 2 : width / 2;\n var X = spark.availableSize.width / 2; // center position of x\n var Y = spark.availableSize.height / 2; // center position of y\n var deg = 0;\n var stRad;\n var edRad;\n var stroke = args.border.color;\n var opacity = spark.opacity;\n var strokeWidth = args.border.width;\n var colors = (spark.palette.length) ? spark.palette : ['#00bdae', '#404041', '#357cd2', '#e56590', '#f8b883',\n '#70ad47', '#dd8abd', '#7f84e8', '#7bb4eb', '#ea7a57'];\n var group = this.sparkline.renderer.createGroup({ id: spark.element.id + '_sparkline_g' });\n var low;\n var high;\n var locations = extend([], [], points);\n if (spark.highPointColor || spark.lowPointColor) {\n var pointsYvalues = locations.map(function (a) { return a.yVal; });\n low = Math.min.apply(null, pointsYvalues);\n high = Math.max.apply(null, pointsYvalues);\n }\n this.negativePointIndexes = [];\n for (var i = 0, stDeg = 90, edDeg = void 0, flag = void 0; i < points.length; i++) {\n stDeg += deg;\n deg = points[i]['degree'];\n edDeg = stDeg + deg;\n stRad = (stDeg - 90) * Math.PI / 180.0;\n edRad = (edDeg - 90) * Math.PI / 180.0;\n points[i]['stAng'] = stRad;\n points[i]['endAng'] = edRad;\n flag = (deg < 180) ? '0' : '1';\n var temp = points[i]['coordinates'] = {\n sX: X + (area * Math.cos(stRad)), sY: Y +\n (area * Math.sin(stRad)), eX: X + (area * Math.cos(edRad)), eY: Y + (area * Math.sin(edRad))\n };\n var pathArc = 'M ' + X + ' ' + Y + ' L ' + temp['eX'] + ' ' + temp['eY'] + ' A ' + area + ' ' +\n area + ' 0 ' + flag + ',0 ' + temp['sX'] + ' ' + temp['sY'] + ' Z';\n var pathOption = {\n 'id': spark.element.id + '_sparkline_pie_' + i,\n 'opacity': opacity,\n 'fill': colors[i % colors.length],\n 'stroke': stroke,\n 'stroke-width': strokeWidth,\n 'd': pathArc,\n 'stroke-dasharray': ''\n };\n this.getPieSpecialPoint(points[i], spark, pathOption, i, high, low, points.length);\n var pointArgs = this.triggerPointRender('pointRendering', i, pathOption.fill, { color: stroke, width: strokeWidth });\n pathOption.fill = pointArgs.fill;\n pathOption.stroke = pointArgs.border.color;\n pathOption['stroke-width'] = pointArgs.border.width;\n if (!pointArgs.cancel) {\n var element = drawPath(this.sparkline, pathOption, group);\n element.setAttribute('aria-label', spark.dataSource[i][spark.xName] + ' : ' + points[i].yVal);\n }\n var diffRadian = edRad - stRad;\n var mid = {\n x: X + ((area / 2) * Math.cos(stRad + (diffRadian / 2))),\n y: Y + ((area / 2) * Math.sin(stRad + (diffRadian / 2)))\n };\n points[i].location.x = mid.x;\n points[i].location.y = mid.y;\n }\n this.sparkline.svgObject.appendChild(group);\n };\n /**\n * To get special point color and option for Pie series.\n */\n SparklineRenderer.prototype.getPieSpecialPoint = function (temp, spark, option, i, high, low, length) {\n if (temp.yVal < 0 && spark.negativePointColor) {\n option.fill = spark.negativePointColor;\n this.negativePointIndexes.push(i);\n }\n if (i === 0 && spark.startPointColor) {\n option.fill = spark.startPointColor;\n this.startPointIndex = i;\n }\n else if ((i === (length - 1)) && spark.endPointColor) {\n option.fill = spark.endPointColor;\n this.endPointIndex = i;\n }\n if (temp.yVal === high && spark.highPointColor) {\n option.fill = spark.highPointColor;\n this.highPointIndex = i;\n }\n else if (temp.yVal === low && spark.lowPointColor) {\n option.fill = spark.lowPointColor;\n this.lowPointIndex = i;\n }\n };\n /**\n * To render area series\n */\n SparklineRenderer.prototype.renderArea = function (points, args) {\n var spark = this.sparkline;\n var group = this.sparkline.renderer.createGroup({ id: spark.element.id + '_sparkline_g',\n 'clip-path': 'url(#' + this.clipId + ')' });\n var pathOption = new PathOption(spark.element.id + '_sparkline_area', args.fill, 0, 'transparent', spark.opacity);\n var d = '';\n var str = '';\n for (var i = 0, len = points.length; i < len; i++) {\n if (i !== 0) {\n str += 'L ' + points[i].x + ' ' + points[i].y + ' ';\n }\n else {\n d = 'M ' + points[i].x + ' ' + this.axisHeight + ' ';\n str = 'M ' + points[i].x + ' ' + points[i].y + ' ';\n }\n d += 'L ' + points[i].x + ' ' + points[i].y + ' ';\n if (i === (len - 1)) {\n d += 'L ' + points[i].x + ' ' + this.axisHeight + ' Z';\n }\n }\n pathOption.d = d;\n drawPath(this.sparkline, pathOption, group);\n pathOption = new PathOption(spark.element.id + '_sparkline_area_str', 'transparent', args.border.width, args.border.color, spark.opacity, '', str);\n drawPath(this.sparkline, pathOption, group);\n this.sparkline.svgObject.appendChild(group);\n };\n /**\n * To render column series\n */\n SparklineRenderer.prototype.renderColumn = function (points, args) {\n var spark = this.sparkline;\n var locations = extend([], [], points);\n var group = this.sparkline.renderer.createGroup({ id: spark.element.id + '_sparkline_g',\n 'clip-path': 'url(#' + this.clipId + ')' });\n var lowPos;\n var highPos;\n if (this.sparkline.highPointColor || this.sparkline.lowPointColor) {\n var pointsYPos = locations.map(function (a) { return a.markerPosition; });\n highPos = Math.min.apply(null, pointsYPos);\n lowPos = Math.max.apply(null, pointsYPos);\n }\n var id = spark.element.id + '_sparkline_column_';\n var rectOptions = new RectOption(id, '', args.border, spark.opacity, null);\n var paletteLength = spark.palette.length;\n var temp;\n var len = points.length;\n this.negativePointIndexes = [];\n for (var i = 0; i < len; i++) {\n temp = points[i];\n rectOptions.id = id + i;\n rectOptions.fill = (paletteLength) ? spark.palette[i % paletteLength] : args.fill;\n rectOptions.rect = new Rect(temp.x, temp.y, temp.width, temp.height);\n this.getSpecialPoint(true, temp, spark, rectOptions, i, highPos, lowPos, len);\n temp.location.y = (temp.markerPosition <= this.axisHeight) ? temp.y : (temp.y + temp.height);\n temp.location.x = temp.x + (temp.width / 2);\n rectOptions.stroke = args.border.color ? (args.border.color) : rectOptions.fill;\n var pointArgs = this.triggerPointRender('pointRendering', i, rectOptions.fill, { color: rectOptions.stroke, width: args.border.width });\n rectOptions.fill = pointArgs.fill;\n rectOptions.stroke = pointArgs.border.color;\n rectOptions['stroke-width'] = pointArgs.border.width;\n if (!pointArgs.cancel) {\n var element = drawRectangle(spark, rectOptions, group);\n element.setAttribute('aria-label', spark.dataSource[i][spark.xName] + ' : ' + points[i].yVal);\n }\n }\n this.sparkline.svgObject.appendChild(group);\n };\n /**\n * To render WinLoss series\n */\n SparklineRenderer.prototype.renderWinLoss = function (points, args) {\n var spark = this.sparkline;\n var group = this.sparkline.renderer.createGroup({ id: spark.element.id + '_sparkline_g',\n 'clip-path': 'url(#' + this.clipId + ')' });\n var id = spark.element.id + '_sparkline_winloss_';\n var options = new RectOption(id, '', args.border, spark.opacity, null);\n var temp;\n var len = points.length;\n var paletteLength = spark.palette.length;\n for (var i = 0; i < len; i++) {\n temp = points[i];\n options.id = id + i;\n options.fill = (paletteLength) ? spark.palette[i % paletteLength] : ((temp.yVal === this.axisValue) ?\n (this.sparkline.tiePointColor || '#a216f3') : ((temp.yVal > this.axisValue) ? args.fill :\n (spark.negativePointColor || '#e20f07')));\n options.stroke = (args.border.color) ? (args.border.color) : options.fill;\n options.rect = new Rect(temp.x, temp.y, temp.width, temp.height);\n temp.location.x = temp.x + (temp.width / 2);\n temp.location.y = (temp.yVal >= this.axisValue) ? (temp.y) : (temp.y + temp.height);\n var pointArgs = this.triggerPointRender('pointRendering', i, options.fill, { color: options.stroke, width: args.border.width });\n options.fill = pointArgs.fill;\n options.stroke = pointArgs.border.color;\n options['stroke-width'] = pointArgs.border.width;\n if (!pointArgs.cancel) {\n var element = drawRectangle(spark, options, group);\n element.setAttribute('aria-label', spark.dataSource[i][spark.xName] + ' : ' + points[i].yVal);\n }\n }\n this.sparkline.svgObject.appendChild(group);\n };\n SparklineRenderer.prototype.renderMarker = function (points) {\n var spark = this.sparkline;\n var marker = spark.markerSettings;\n if ((spark.type === 'Pie' || spark.type === 'WinLoss' || !marker.visible.length)) {\n return;\n }\n var locations = extend([], [], points);\n var group = this.sparkline.renderer.createGroup({\n id: spark.element.id + '_sparkline_marker_g',\n 'clip-path': 'url(#' + this.clipId + ')'\n });\n var temp;\n var id = spark.element.id + '_sparkline_marker_';\n var option = new CircleOption('', marker.fill, marker.border, marker.opacity, 0, 0, marker.size / 2, '');\n var highPos;\n var lowPos;\n var visible = marker.visible.join();\n if ((visible.toLowerCase().indexOf('high') > -1) || (visible.toLowerCase().indexOf('low') > -1)) {\n var pointsYPos = locations.map(function (a) { return a.markerPosition; });\n highPos = Math.min.apply(null, pointsYPos);\n lowPos = Math.max.apply(null, pointsYPos);\n }\n this.negativePointIndexes = [];\n for (var i = 0, length_1 = points.length; i < length_1; i++) {\n temp = points[i];\n option.id = id + i;\n option.cx = temp.location.x;\n option.cy = temp.location.y;\n option.fill = marker.fill;\n var render = (visible.toLowerCase().indexOf('all') > -1);\n render = this.getSpecialPoint(render, temp, spark, option, i, highPos, lowPos, length_1, visible.toLowerCase());\n option.stroke = marker.border.color || option.fill;\n var markerArgs = {\n name: 'markerRendering', cancel: false, border: { color: option.stroke, width: marker.border.width }, fill: option.fill,\n pointIndex: i, sparkline: this.sparkline, x: option.cx, y: option.cy, size: marker.size\n };\n this.sparkline.trigger(markerArgs.name, markerArgs);\n if (render && !markerArgs.cancel) {\n option.fill = markerArgs.fill;\n option.stroke = markerArgs.border.color;\n option['stroke-width'] = markerArgs.border.width;\n option.r = markerArgs.size / 2;\n var element = drawCircle(spark, option, group);\n element.setAttribute('aria-label', spark.dataSource[i][spark.xName] + ' : ' + points[i].yVal);\n }\n }\n this.sparkline.svgObject.appendChild(group);\n };\n /**\n * To get special point color and option.\n */\n SparklineRenderer.prototype.getSpecialPoint = function (render, temp, spark, option, i, highPos, lowPos, length, visible) {\n if (visible === void 0) { visible = ''; }\n if (temp.markerPosition > this.axisHeight) {\n option.fill = spark.negativePointColor || option.fill;\n this.negativePointIndexes.push(i);\n render = render || (visible.indexOf('negative') > -1);\n }\n if (i === 0) {\n option.fill = spark.startPointColor || option.fill;\n this.startPointIndex = i;\n render = render || (visible.indexOf('start') > -1);\n }\n else if ((i === (length - 1))) {\n option.fill = spark.endPointColor || option.fill;\n this.endPointIndex = i;\n render = render || (visible.indexOf('end') > -1);\n }\n if (temp.markerPosition === highPos) {\n option.fill = spark.highPointColor || option.fill;\n this.highPointIndex = i;\n render = render || (visible.indexOf('high') > -1);\n }\n else if (temp.markerPosition === lowPos) {\n option.fill = spark.lowPointColor || option.fill;\n this.lowPointIndex = i;\n render = render || (visible.indexOf('low') > -1);\n }\n return render;\n };\n /**\n * To render data label for sparkline.\n */\n SparklineRenderer.prototype.renderLabel = function (points) {\n var spark = this.sparkline;\n var dataLabel = spark.dataLabelSettings;\n var color = (spark.theme === 'Highcontrast') ? '#FFFFFF' : '#424242';\n color = (dataLabel.textStyle.color) ? dataLabel.textStyle.color : color;\n if ((spark.type === 'WinLoss' || !dataLabel.visible.length)) {\n return;\n }\n var locations = extend([], [], points);\n var id = spark.element.id + '_sparkline_label_';\n var group = this.sparkline.renderer.createGroup({ id: spark.element.id + '_sparkline_label_g',\n style: 'pointer-events: none;', 'clip-path': 'url(#' + this.clipId + ')' });\n var g;\n var temp;\n var textId = id + 'text_';\n var rectId = id + 'rect_';\n var option = new TextOption('', 0, 0, 'middle', '', 'middle');\n var labelStyle = dataLabel.textStyle;\n var pointsYPos = locations.map(function (a) { return a.markerPosition; });\n var highPos = Math.min.apply(null, pointsYPos);\n var lowPos = Math.max.apply(null, pointsYPos);\n var space = 1;\n var padding = (dataLabel.fill !== 'transparent' || dataLabel.border.width) ? 2 : 0;\n var size = measureText('sparkline_measure_text', labelStyle);\n var rectOptions = new RectOption('', dataLabel.fill, dataLabel.border, dataLabel.opacity, null);\n for (var i = 0, length_2 = points.length; i < length_2; i++) {\n temp = points[i];\n option.id = textId + i;\n option.x = temp.location.x + dataLabel.offset.x;\n option.y = ((spark.type === 'Pie') ? temp.location.y : ((temp.markerPosition > this.axisHeight) ? (temp.location.y +\n (size.height / 2) + space + padding) : (temp.location.y - (size.height / 2) - space - padding))) + dataLabel.offset.y;\n option.text = (dataLabel.format !== '') ? this.formatter(dataLabel.format, this.sparkline.dataSource[i]) :\n temp.yVal.toString();\n var labelArgs = {\n name: 'dataLabelRendering', cancel: false, border: dataLabel.border, fill: dataLabel.fill, pointIndex: i,\n sparkline: this.sparkline, x: option.x, y: option.y, text: option.text, color: color\n };\n this.sparkline.trigger(labelArgs.name, labelArgs);\n size = measureText(labelArgs.text, labelStyle);\n option.text = labelArgs.text;\n var render = (dataLabel.visible.join().toLowerCase().indexOf('all') > -1);\n render = this.getLabelVisible(render, temp, i, dataLabel, length_2, highPos, lowPos);\n if (render && !labelArgs.cancel) {\n rectOptions.id = rectId + i;\n rectOptions.fill = labelArgs.fill;\n rectOptions.stroke = labelArgs.border.color;\n rectOptions['stroke-width'] = labelArgs.border.width;\n option.x = labelArgs.x;\n option.y = labelArgs.y;\n rectOptions.rect = new Rect(option.x - ((size.width / 2) + padding), (option.y - padding - (size.height / 1.75)), size.width + (padding * 2), size.height + (padding * 2));\n g = this.sparkline.renderer.createGroup({ id: id + 'g' + i });\n drawRectangle(spark, rectOptions, g);\n renderTextElement(option, labelStyle, labelArgs.color, g);\n group.appendChild(g);\n }\n }\n this.sparkline.svgObject.appendChild(group);\n };\n /**\n * To get special point color and option.\n */\n SparklineRenderer.prototype.getLabelVisible = function (render, temp, i, label, length, highPos, lowPos) {\n var labelVisible = label.visible.join().toLowerCase();\n if (temp.markerPosition > this.axisHeight) {\n render = render || (labelVisible.indexOf('negative') > -1);\n }\n if (i === 0) {\n render = render || (labelVisible.indexOf('start') > -1);\n }\n else if ((i === (length - 1))) {\n render = render || (labelVisible.indexOf('end') > -1);\n }\n if (temp.markerPosition === highPos) {\n render = render || (labelVisible.indexOf('high') > -1);\n }\n else if (temp.markerPosition === lowPos) {\n render = render || (labelVisible.indexOf('low') > -1);\n }\n return render;\n };\n /**\n * To format text\n */\n SparklineRenderer.prototype.formatter = function (format, data) {\n if (isNullOrUndefined(format)) {\n return null;\n }\n var keys = Object.keys(data);\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var key = keys_1[_i];\n format = format.split('${' + key + '}').join(data[key]);\n }\n return format;\n };\n /**\n * To calculate min max for x and y axis\n */\n SparklineRenderer.prototype.axisCalculation = function () {\n this.findRanges(this.sparkline.sparklineData);\n };\n /**\n * To find x axis interval.\n */\n SparklineRenderer.prototype.getInterval = function (data, x, type) {\n var interval = 1;\n var x1 = data[0][x];\n var x2 = isNullOrUndefined(data[1]) ? undefined : data[1][x];\n if (!isNullOrUndefined(x1) && !isNullOrUndefined(x2)) {\n var temp = extend([], data);\n var validData_1 = [];\n temp.forEach(function (value) {\n if (!isNullOrUndefined(value[x])) {\n validData_1.push(value);\n }\n });\n validData_1.sort(function (a, b) {\n if (isNullOrUndefined(a[x]) || isNullOrUndefined(b[x])) {\n return 0;\n }\n return a[x] - b[x];\n });\n interval = validData_1[1][x] - validData_1[0][x];\n }\n return interval;\n };\n /**\n * To calculate axis ranges internally.\n */\n // tslint:disable-next-line:max-func-body-length\n SparklineRenderer.prototype.findRanges = function (data) {\n var model = this.sparkline;\n var max;\n var min;\n var minX;\n var maxX;\n var maxPointsLength = data.length;\n var temp;\n var sumofValues = 0;\n var isNumericArray = Array.isArray(data) && typeof data[0] !== 'object';\n if (isNumericArray) {\n if (model.type === 'Pie') {\n for (var i = 0; i < maxPointsLength; i++) {\n sumofValues += Math.abs(data[i]);\n }\n }\n else {\n max = Math.max.apply(null, data);\n min = Math.min.apply(null, data);\n minX = 0;\n maxX = maxPointsLength - 1;\n }\n }\n else {\n if (model.type === 'Pie') {\n for (var i = 0; i < maxPointsLength; i++) {\n sumofValues += Math.abs(data[i][model.yName]);\n }\n }\n else {\n if (isNullOrUndefined(data[0][model.xName])) {\n var x_1 = data.map(function (z) { return z[model.yName]; });\n max = Math.max.apply(null, x_1);\n min = Math.min.apply(null, x_1);\n }\n else {\n temp = extend([], data);\n temp = temp.sort(function (a, b) { return a[model.yName] - b[model.yName]; });\n max = temp[temp.length - 1][model.yName];\n min = temp[0][model.yName];\n }\n if (!isNullOrUndefined(data[0][model.xName])) {\n temp = temp.sort(function (a, b) { return a[model.xName] - b[model.xName]; });\n maxX = temp[temp.length - 1][model.xName];\n minX = temp[0][model.xName];\n }\n else {\n minX = 0;\n maxX = maxPointsLength - 1;\n }\n }\n }\n var y2;\n var height;\n var width;\n var x1 = 0;\n var y1;\n var padding = model.padding;\n var point;\n var axis = model.axisSettings;\n var value = axis.value;\n if (model.type !== 'Pie') {\n this.maxLength = maxPointsLength;\n height = model.availableSize.height - (padding.bottom + padding.top);\n width = model.availableSize.width - (padding.left + padding.right);\n maxX = isNullOrUndefined(axis.maxX) ? maxX : axis.maxX;\n minX = isNullOrUndefined(axis.minX) ? minX : axis.minX;\n max = isNullOrUndefined(axis.maxY) ? max : axis.maxY;\n min = isNullOrUndefined(axis.minY) ? min : axis.minY;\n var color = (model.theme === 'Highcontrast') ? '#FFFFFF' : '#000000';\n color = (axis.lineSettings.color) ? axis.lineSettings.color : color;\n var eventArgs = {\n name: 'axisRendering', cancel: false, sparkline: model, maxX: maxX, minX: minX, maxY: max, minY: min,\n value: axis.value, lineColor: color, lineWidth: axis.lineSettings.width\n };\n model.trigger('axisRendering', eventArgs);\n if (eventArgs.cancel) {\n this.visiblePoints = [];\n return;\n }\n maxX = eventArgs.maxX;\n minX = eventArgs.minX;\n max = eventArgs.maxY;\n min = eventArgs.minY;\n value = this.axisValue = eventArgs.value;\n this.axisColor = eventArgs.lineColor;\n this.axisWidth = eventArgs.lineWidth;\n var unitX = maxX - minX;\n var unitY = max - min;\n unitX = (unitX === 0) ? 1 : unitX;\n unitY = (unitY === 0) ? 1 : unitY;\n this.unitX = unitX;\n this.unitY = unitY;\n this.min = min;\n x1 = 0;\n y1 = height - ((height / unitY) * (-min));\n y1 = (min < 0 && max <= 0) ? 0 : (min < 0 && max > 0) ? y1 : height;\n if (value >= min && value <= max) {\n y1 = height - Math.round(height * ((value - min) / this.unitY));\n }\n this.axisHeight = y1 + padding.top;\n }\n var percent;\n var x;\n var y;\n var visiblePoints = [];\n var interval = this.getInterval(data, model.xName, model.valueType);\n for (var i = 0; i < maxPointsLength; i++) {\n if (isNullOrUndefined(data[i][model.xName]) && isNullOrUndefined(data[i][model.yName]) && ((data[i][model.yName]) !== 0)\n && isNumericArray) {\n x = i;\n y = data[i];\n }\n else if (isNullOrUndefined(data[i][model.xName])) {\n x = i;\n y = data[i][model.yName];\n }\n else {\n x = data[i][model.xName];\n y = data[i][model.yName];\n }\n if (isNullOrUndefined(x) || isNullOrUndefined(y)) {\n continue;\n }\n if (model.type === 'Line' || model.type === 'Area') {\n y2 = (min !== max && maxPointsLength !== 1) ? height - Math.round(height * ((y - min) / this.unitY)) : padding.top;\n point = { x: (minX !== maxX) ? Math.round(width * ((x - minX) / this.unitX)) : width / 2, y: y2, markerPosition: y2 };\n }\n else if (model.type === 'Column' || model.type === 'WinLoss') {\n var colWidth = width / (((maxX - minX) / interval) + 1);\n var calSpace = 0.5;\n var space = (calSpace * 2); //calspace is default space for column and winloss\n colWidth -= (space);\n x1 = (((x - minX) / interval) * (colWidth + space)) + (space / 2);\n if (model.type === 'WinLoss') {\n // win or gain column height half of the height , draw(zero) height factor\n var winLossFactor = 0.5;\n var drawHeightFactor = 40;\n y2 = (y > value) ? (height / 4) : (y < value) ? (height * winLossFactor) :\n ((height * winLossFactor) - (height / drawHeightFactor));\n point = { x: x1, y: y2, height: (y !== value) ? (height / 4) : height / 20, width: colWidth,\n markerPosition: (y2 > y1) ? (y1 + Math.abs(y2 - y1)) : y2 };\n }\n else {\n var z = ((height / this.unitY) * (y - min));\n var z1 = (y === min && y > value) ? ((maxPointsLength !== 1 && this.unitY !== 1) ?\n (height / this.unitY) * (min / 2) : (z | 1)) :\n (y === max && y < value && maxPointsLength !== 1 && this.unitY !== 1) ? (height / this.unitY) * (-max / 2) : z;\n y2 = Math.abs(height - z1);\n point = {\n x: x1, y: (y2 > y1) ? y1 : y2, height: Math.abs(y2 - y1),\n width: colWidth, markerPosition: (y2 > y1) ? (y1 + Math.abs(y2 - y1)) : y2\n };\n }\n }\n else if (model.type === 'Pie') {\n percent = (Math.abs(y) / sumofValues) * 100;\n point = {\n percent: percent, degree: ((Math.abs(y) / sumofValues) * 360)\n };\n }\n if (model.type !== 'Pie') {\n point.x += padding.left;\n point.y += padding.top;\n }\n if (model.type !== 'WinLoss') {\n point.markerPosition += padding.top;\n }\n point.location = { x: point.x, y: point.y };\n point.xVal = x;\n point.yVal = y;\n visiblePoints.push(point);\n }\n visiblePoints.sort(function (a, b) {\n return a.x - b.x;\n });\n this.visiblePoints = visiblePoints;\n };\n /**\n * To render the sparkline axis\n */\n SparklineRenderer.prototype.drawAxis = function () {\n var spark = this.sparkline;\n var height = this.axisHeight;\n if ((spark.type !== 'WinLoss') && (spark.type !== 'Pie') && spark.axisSettings.lineSettings.visible) {\n var xAxis = {\n 'id': spark.element.id + '_Sparkline_XAxis',\n 'x1': spark.padding.left, 'y1': height,\n 'x2': spark.availableSize.width - spark.padding.right, 'y2': height,\n 'stroke': this.axisColor,\n 'opacity': spark.axisSettings.lineSettings.opacity,\n 'stroke-dasharray': spark.axisSettings.lineSettings.dashArray,\n 'stroke-width': this.axisWidth,\n 'clip-path': 'url(#' + this.clipId + ')'\n };\n spark.svgObject.appendChild(spark.renderer.drawLine(xAxis));\n }\n };\n /**\n * To trigger point render event\n */\n SparklineRenderer.prototype.triggerPointRender = function (name, i, fill, border) {\n var args = {\n name: name, cancel: false, border: border, fill: fill, sparkline: this.sparkline, pointIndex: i\n };\n this.sparkline.trigger(name, args);\n return args;\n };\n return SparklineRenderer;\n}());\nexport { SparklineRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, NotifyPropertyChanges, Property, Complex } from '@syncfusion/ej2-base';\nimport { remove, L10n, Internationalization, Event, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Browser, EventHandler, Touch, Collection } from '@syncfusion/ej2-base';\nimport { SparklineBorder, SparklineTooltipSettings, ContainerArea, AxisSettings, Padding, SparklineMarkerSettings } from './model/base';\nimport { SparklineDataLabelSettings, RangeBandSettings } from './model/base';\nimport { Size, createSvg, RectOption, Rect, drawRectangle, getIdElement, withInBounds, removeElement } from './utils/helper';\nimport { SparklineRenderer } from './rendering/sparkline-renderer';\n//tslint:disable: no-duplicate-lines\n/**\n * Represents the Sparkline control.\n * ```html\n *
\n * \n * ```\n */\nvar Sparkline = /** @class */ (function (_super) {\n __extends(Sparkline, _super);\n // Sparkline rendering starts from here.\n /**\n * Constructor for creating the Sparkline widget\n */\n function Sparkline(options, element) {\n var _this = _super.call(this, options, element) || this;\n /** @private */\n _this.isDevice = Browser.isDevice;\n return _this;\n }\n /**\n * Initializing pre-required values for sparkline.\n */\n Sparkline.prototype.preRender = function () {\n this.unWireEvents();\n this.trigger('load', { sparkline: this });\n this.sparklineRenderer = new SparklineRenderer(this);\n this.createSVG();\n this.wireEvents();\n this.setCulture();\n };\n /**\n * Sparkline Elements rendering starting.\n */\n Sparkline.prototype.render = function () {\n // Sparkline rendering splitted into rendering and calculations\n this.sparklineRenderer.processData();\n this.renderSparkline();\n this.element.appendChild(this.svgObject);\n this.setSecondaryElementPosition();\n this.trigger('loaded', { sparkline: this });\n };\n /**\n * To render sparkline elements\n */\n Sparkline.prototype.renderSparkline = function () {\n // To render the sparkline elements\n this.renderBorder();\n this.createDiv();\n this.sparklineRenderer.renderSeries();\n };\n /**\n * Create secondary element for the tooltip\n */\n Sparkline.prototype.createDiv = function () {\n var tooltipDiv = this.createElement('div');\n tooltipDiv.id = this.element.id + '_Secondary_Element';\n tooltipDiv.setAttribute('style', 'position: relative');\n this.element.appendChild(tooltipDiv);\n this.element.style.display = 'block';\n this.element.style.position = 'relative';\n };\n /**\n * To set the left and top position for data label template for sparkline\n */\n Sparkline.prototype.setSecondaryElementPosition = function () {\n var element = getIdElement(this.element.id + '_Secondary_Element');\n if (!element) {\n return;\n }\n var rect = this.element.getBoundingClientRect();\n var svgRect = getIdElement(this.element.id + '_svg').getBoundingClientRect();\n element.style.left = Math.max(svgRect.left - rect.left, 0) + 'px';\n element.style.top = Math.max(svgRect.top - rect.top, 0) + 'px';\n };\n /**\n * @private\n * Render the sparkline border\n */\n Sparkline.prototype.renderBorder = function () {\n var width = this.containerArea.border.width;\n var borderRect;\n if (width > 0 || this.containerArea.background !== 'transparent') {\n borderRect = new RectOption(this.element.id + '_SparklineBorder', this.containerArea.background, this.containerArea.border, 1, new Rect(width / 2, width / 2, this.availableSize.width - width, this.availableSize.height - width));\n this.svgObject.appendChild(drawRectangle(this, borderRect));\n }\n // Used to create clip path sparkline\n var padding = this.padding;\n borderRect = new RectOption(this.element.id + '_sparkline_clip_rect', 'transparent', { color: 'transparent', width: 0 }, 1, new Rect(padding.left, padding.top, this.availableSize.width - (padding.left + padding.right), this.availableSize.height - (padding.top + padding.bottom)));\n var clipPath = this.renderer.createClipPath({ id: this.element.id + '_sparkline_clip_path' });\n drawRectangle(this, borderRect, clipPath);\n this.svgObject.appendChild(clipPath);\n };\n /**\n * To create svg element for sparkline\n */\n Sparkline.prototype.createSVG = function () {\n this.removeSvg();\n createSvg(this);\n };\n /**\n * To Remove the Sparkline SVG object\n */\n Sparkline.prototype.removeSvg = function () {\n if (this.svgObject) {\n while (this.svgObject.childNodes.length > 0) {\n this.svgObject.removeChild(this.svgObject.firstChild);\n }\n if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) {\n remove(this.svgObject);\n }\n }\n removeElement(this.element.id + '_Secondary_Element');\n if (this.sparklineTooltipModule) {\n this.sparklineTooltipModule.removeTooltipElements();\n }\n };\n /**\n * Method to set culture for sparkline\n */\n Sparkline.prototype.setCulture = function () {\n this.intl = new Internationalization();\n this.localeObject = new L10n(this.getModuleName(), this.defaultLocalConstants, this.locale);\n };\n /**\n * To provide the array of modules needed for sparkline rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n Sparkline.prototype.requiredModules = function () {\n var modules = [];\n if (this.tooltipSettings.visible || this.tooltipSettings.trackLineSettings.visible) {\n modules.push({\n member: 'SparklineTooltip',\n args: [this]\n });\n }\n return modules;\n };\n /**\n * Method to unbind events for sparkline chart\n */\n Sparkline.prototype.unWireEvents = function () {\n var move = Browser.touchMoveEvent;\n var cancel = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n /*! UnBind the Event handler */\n EventHandler.remove(this.element, Browser.touchMoveEvent, this.sparklineMove);\n EventHandler.remove(this.element, cancel, this.sparklineMouseLeave);\n EventHandler.remove(this.element, Browser.touchEndEvent, this.sparklineMouseEnd);\n window.removeEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.sparklineResize);\n };\n /**\n * Method to bind events for the sparkline\n */\n Sparkline.prototype.wireEvents = function () {\n var cancel = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n /*! Bind the Event handler */\n EventHandler.add(this.element, Browser.touchMoveEvent, this.sparklineMove, this);\n EventHandler.add(this.element, 'click', this.sparklineClick, this);\n EventHandler.add(this.element, cancel, this.sparklineMouseLeave, this);\n EventHandler.add(this.element, Browser.touchEndEvent, this.sparklineMouseEnd, this);\n window.addEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.sparklineResize.bind(this));\n new Touch(this.element);\n };\n /**\n * Sparkline resize event.\n * @private\n */\n Sparkline.prototype.sparklineResize = function (e) {\n var _this = this;\n var args = {\n name: 'resize',\n previousSize: this.availableSize,\n sparkline: this,\n currentSize: new Size(0, 0)\n };\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n this.resizeTo = setTimeout(function () {\n if (_this.isDestroyed) {\n clearTimeout(_this.resizeTo);\n return;\n }\n _this.unWireEvents();\n _this.createSVG();\n _this.refreshing = true;\n _this.wireEvents();\n args.currentSize = _this.availableSize;\n _this.trigger('resize', args);\n _this.render();\n }, 500);\n return false;\n };\n /**\n * Handles the mouse move on sparkline.\n * @return {boolean}\n * @private\n */\n Sparkline.prototype.sparklineMove = function (e) {\n this.setSparklineMouseXY(e);\n this.notify(Browser.touchMoveEvent, e);\n var args = {\n name: 'sparklineMouseMove', cancel: false, sparkline: this, event: e\n };\n this.trigger(args.name, args);\n var pointClick = this.isPointRegion(e);\n if (pointClick.isPointRegion) {\n var pointArgs = {\n name: 'pointRegionMouseMove', cancel: false, event: e, sparkline: this, pointIndex: pointClick.pointIndex\n };\n this.trigger(pointArgs.name, pointArgs);\n }\n return false;\n };\n /**\n * Handles the mouse click on sparkline.\n * @return {boolean}\n * @private\n */\n Sparkline.prototype.sparklineClick = function (e) {\n this.setSparklineMouseXY(e);\n var args = {\n name: 'sparklineMouseClick', cancel: false, sparkline: this, event: e\n };\n this.trigger(args.name, args);\n var pointClick = this.isPointRegion(e);\n if (pointClick.isPointRegion) {\n var pointArgs = {\n name: 'pointRegionMouseClick', cancel: false, event: e, sparkline: this, pointIndex: pointClick.pointIndex\n };\n this.trigger(pointArgs.name, pointArgs);\n }\n return false;\n };\n /**\n * To check mouse event target is point region or not.\n */\n Sparkline.prototype.isPointRegion = function (e) {\n var _this = this;\n var startId = this.element.id + '_';\n var id = e.target.id.replace(startId, '').split('_');\n if (id[1] === this.type.toLowerCase()) {\n var index_1 = parseInt(id[2], 10);\n if ((isNullOrUndefined(index_1) || isNaN(index_1)) && (this.type === 'Line' || this.type === 'Area')) {\n this.sparklineRenderer.visiblePoints.forEach(function (point, i) {\n if (withInBounds(_this.mouseX, _this.mouseY, new Rect(point.x - 5, point.y - 5, 10, 10))) {\n index_1 = i;\n return;\n }\n });\n }\n return { isPointRegion: true, pointIndex: index_1 };\n }\n return { isPointRegion: false, pointIndex: null };\n };\n /**\n * Handles the mouse end.\n * @return {boolean}\n * @private\n */\n Sparkline.prototype.sparklineMouseEnd = function (e) {\n this.setSparklineMouseXY(e);\n this.notify(Browser.touchEndEvent, e);\n return false;\n };\n /**\n * Handles the mouse leave on sparkline.\n * @return {boolean}\n * @private\n */\n Sparkline.prototype.sparklineMouseLeave = function (e) {\n this.setSparklineMouseXY(e);\n this.notify(Browser.isPointer ? 'pointerleave' : 'mouseleave', e);\n return false;\n };\n /**\n * Method to set mouse x, y from events\n */\n Sparkline.prototype.setSparklineMouseXY = function (e) {\n var pageY;\n var pageX;\n if (e.type.indexOf('touch') > -1) {\n this.isTouch = true;\n var touchArg = e;\n pageX = touchArg.changedTouches[0].clientX;\n pageY = touchArg.changedTouches[0].clientY;\n }\n else {\n this.isTouch = e.pointerType === 'touch' || e.pointerType === '2';\n pageY = e.clientY;\n pageX = e.clientX;\n }\n var rect = this.element.getBoundingClientRect();\n var svgRect = getIdElement(this.element.id + '_svg').getBoundingClientRect();\n this.mouseY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0);\n this.mouseX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0);\n };\n /**\n * To change rendering while property value modified.\n * @private\n */\n Sparkline.prototype.onPropertyChanged = function (newProp, oldProp) {\n var render = false;\n var refresh = false;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'xName':\n case 'yName':\n case 'dataSource':\n case 'axisSettings':\n case 'type':\n case 'valueType':\n refresh = true;\n break;\n case 'border':\n case 'markerSettings':\n case 'dataLabelSettings':\n case 'tooltipSettings':\n case 'startPointColor':\n case 'highPointColor':\n case 'lowPointColor':\n case 'endPointColor':\n case 'negativePointColor':\n case 'theme':\n render = true;\n break;\n }\n }\n if (refresh) {\n this.createSVG();\n this.sparklineRenderer.processData();\n this.refreshSparkline();\n }\n else if (render) {\n this.createSVG();\n this.refreshSparkline();\n }\n };\n /**\n * To render sparkline series and appending.\n */\n Sparkline.prototype.refreshSparkline = function () {\n // Issue fix. React had native render method. So OnProperty change used render method won't wrok.\n this.renderSparkline();\n this.element.appendChild(this.svgObject);\n this.setSecondaryElementPosition();\n };\n /**\n * Get component name\n */\n Sparkline.prototype.getModuleName = function () {\n return 'sparkline';\n };\n /**\n * Destroy the component\n */\n Sparkline.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n Sparkline.prototype.getPersistData = function () {\n return '';\n };\n __decorate([\n Property(null)\n ], Sparkline.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], Sparkline.prototype, \"height\", void 0);\n __decorate([\n Complex({}, SparklineBorder)\n ], Sparkline.prototype, \"border\", void 0);\n __decorate([\n Property('Line')\n ], Sparkline.prototype, \"type\", void 0);\n __decorate([\n Property([])\n ], Sparkline.prototype, \"dataSource\", void 0);\n __decorate([\n Property('Numeric')\n ], Sparkline.prototype, \"valueType\", void 0);\n __decorate([\n Property(null)\n ], Sparkline.prototype, \"xName\", void 0);\n __decorate([\n Property(null)\n ], Sparkline.prototype, \"yName\", void 0);\n __decorate([\n Property('#00bdae')\n ], Sparkline.prototype, \"fill\", void 0);\n __decorate([\n Property('')\n ], Sparkline.prototype, \"highPointColor\", void 0);\n __decorate([\n Property('')\n ], Sparkline.prototype, \"lowPointColor\", void 0);\n __decorate([\n Property('')\n ], Sparkline.prototype, \"startPointColor\", void 0);\n __decorate([\n Property('')\n ], Sparkline.prototype, \"endPointColor\", void 0);\n __decorate([\n Property('')\n ], Sparkline.prototype, \"negativePointColor\", void 0);\n __decorate([\n Property('')\n ], Sparkline.prototype, \"tiePointColor\", void 0);\n __decorate([\n Property([])\n ], Sparkline.prototype, \"palette\", void 0);\n __decorate([\n Property(1)\n ], Sparkline.prototype, \"lineWidth\", void 0);\n __decorate([\n Property(1)\n ], Sparkline.prototype, \"opacity\", void 0);\n __decorate([\n Property(null)\n ], Sparkline.prototype, \"format\", void 0);\n __decorate([\n Property(false)\n ], Sparkline.prototype, \"useGroupingSeparator\", void 0);\n __decorate([\n Complex({}, SparklineTooltipSettings)\n ], Sparkline.prototype, \"tooltipSettings\", void 0);\n __decorate([\n Complex({}, ContainerArea)\n ], Sparkline.prototype, \"containerArea\", void 0);\n __decorate([\n Collection([], RangeBandSettings)\n ], Sparkline.prototype, \"rangeBandSettings\", void 0);\n __decorate([\n Complex({}, AxisSettings)\n ], Sparkline.prototype, \"axisSettings\", void 0);\n __decorate([\n Complex({}, SparklineMarkerSettings)\n ], Sparkline.prototype, \"markerSettings\", void 0);\n __decorate([\n Complex({}, SparklineDataLabelSettings)\n ], Sparkline.prototype, \"dataLabelSettings\", void 0);\n __decorate([\n Complex({}, Padding)\n ], Sparkline.prototype, \"padding\", void 0);\n __decorate([\n Property('Material')\n ], Sparkline.prototype, \"theme\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"loaded\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"load\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"tooltipInitialize\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"seriesRendering\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"axisRendering\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"pointRendering\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"pointRegionMouseMove\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"pointRegionMouseClick\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"sparklineMouseMove\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"sparklineMouseClick\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"dataLabelRendering\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"markerRendering\", void 0);\n __decorate([\n Event()\n ], Sparkline.prototype, \"resize\", void 0);\n Sparkline = __decorate([\n NotifyPropertyChanges\n ], Sparkline);\n return Sparkline;\n}(Component));\nexport { Sparkline };\n","import { PathOption, drawPath, getIdElement, Rect, withInBounds } from '../utils/helper';\nimport { Browser, extend, isNullOrUndefined, remove, createElement } from '@syncfusion/ej2-base';\nimport { Tooltip } from '@syncfusion/ej2-svg-base';\n/**\n * Sparkline Tooltip Module\n */\nvar SparklineTooltip = /** @class */ (function () {\n function SparklineTooltip(sparkline) {\n this.sparkline = sparkline;\n this.addEventListener();\n }\n /**\n * @hidden\n */\n SparklineTooltip.prototype.addEventListener = function () {\n if (this.sparkline.isDestroyed) {\n return;\n }\n // this.sparkline.on('mouseleave', this.mouseLeaveHandler, this);\n this.sparkline.on(Browser.isPointer ? 'pointerleave' : 'mouseleave', this.mouseLeaveHandler, this);\n this.sparkline.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);\n this.sparkline.on(Browser.touchEndEvent, this.mouseUpHandler, this);\n };\n SparklineTooltip.prototype.mouseLeaveHandler = function (e) {\n this.removeTooltipElements();\n };\n SparklineTooltip.prototype.mouseUpHandler = function (e) {\n if (!this.sparkline.isTouch) {\n return;\n }\n this.processTooltip(e);\n this.fadeOut();\n };\n SparklineTooltip.prototype.fadeOut = function () {\n clearTimeout(this.clearTooltip);\n this.clearTooltip = setTimeout(this.removeTooltipElements.bind(this), 5000);\n };\n /**\n * To remove tooltip and tracker elements.\n * @private\n */\n SparklineTooltip.prototype.removeTooltipElements = function () {\n this.removeTooltip();\n this.removeTracker();\n };\n SparklineTooltip.prototype.mouseMoveHandler = function (e) {\n this.processTooltip(e);\n };\n SparklineTooltip.prototype.processTooltip = function (e) {\n var pointIndex;\n var spark = this.sparkline;\n var visiblePoints = spark.sparklineRenderer.visiblePoints;\n var mouseX = spark.mouseX;\n var mouseY = spark.mouseY;\n if (spark.type !== 'Pie') {\n var locations = extend([], [], visiblePoints);\n var trackerPositions = locations.map(function (point) { return point.location.x; });\n var temp = Infinity;\n var mousePosition = void 0;\n for (var i = 0, diff = void 0, len = trackerPositions.length; i < len; i++) {\n diff = Math.abs(mouseX - trackerPositions[i]);\n if (temp > diff) {\n temp = diff;\n mousePosition = trackerPositions[i];\n pointIndex = i;\n }\n }\n }\n else {\n var target = e.target.id;\n pointIndex = parseInt(target.split('_pie_')[1], 10);\n }\n if (isNaN(pointIndex) || !withInBounds(mouseX, mouseY, new Rect(0, 0, spark.availableSize.width, spark.availableSize.height))) {\n this.removeTracker();\n this.removeTooltip();\n return;\n }\n if (this.pointIndex === pointIndex) {\n return;\n }\n this.pointIndex = pointIndex;\n this.renderTrackerLine(visiblePoints[pointIndex]);\n this.renderTooltip(visiblePoints[pointIndex]);\n };\n /**\n * To render tracker line\n */\n SparklineTooltip.prototype.renderTrackerLine = function (points) {\n var spark = this.sparkline;\n var tracker = spark.tooltipSettings.trackLineSettings;\n var color = (spark.theme === 'Highcontrast') ? '#FFFFFF' : '#000000';\n color = (tracker.color) ? tracker.color : color;\n if (!tracker.visible || spark.type === 'Pie') {\n return;\n }\n var group = getIdElement(spark.element.id + '_sparkline_tracker_g');\n if (isNullOrUndefined(group)) {\n group = spark.renderer.createGroup({ id: spark.element.id + '_sparkline_tracker_g' });\n spark.svgObject.appendChild(group);\n }\n var pathEle = getIdElement(spark.element.id + '_sparkline_tracker');\n var d = 'M ' + points.location.x + ' ' + spark.padding.top + ' L ' + points.location.x + ' ' +\n (spark.availableSize.height - spark.padding.bottom);\n if (isNullOrUndefined(pathEle)) {\n var pathOption = new PathOption(spark.element.id + '_sparkline_tracker', 'transparent', tracker.width, color, 1);\n pathOption.d = d;\n drawPath(spark, pathOption, group);\n }\n else {\n pathEle.setAttribute('d', d);\n pathEle.setAttribute('stroke-width', tracker.width.toString());\n pathEle.setAttribute('stroke', color);\n }\n };\n /**\n * To render line series\n */\n SparklineTooltip.prototype.renderTooltip = function (points) {\n var spark = this.sparkline;\n var tooltip = spark.tooltipSettings;\n if (!tooltip.visible) {\n return;\n }\n var div = getIdElement(spark.element.id + '_sparkline_tooltip_div');\n if (isNullOrUndefined(div)) {\n div = createElement('div', { id: spark.element.id + '_sparkline_tooltip_div',\n styles: 'pointer-events: none; position: absolute;z-index:1;' });\n getIdElement(spark.element.id + '_Secondary_Element').appendChild(div);\n }\n var size = (spark.markerSettings.visible.length) ? spark.markerSettings.size : 0;\n var x = points.xVal.toString();\n if (spark.valueType === 'Category') {\n x = spark.dataSource[points.xVal][spark.xName];\n }\n else if (spark.valueType === 'DateTime') {\n x = new Date(points.xVal).toDateString();\n }\n var y = points.yVal.toString();\n var text = this.getFormat(spark.tooltipSettings.format, spark, x, this.formatValue(points.yVal, spark).toString());\n var location = { x: points.location.x, y: points.location.y };\n location = spark.type === 'Pie' ? { x: points.location.x, y: points.location.y } : location;\n var tooltipEvent = {\n name: 'tooltipInitialize', cancel: false, text: text,\n textStyle: {\n size: tooltip.textStyle.size,\n opacity: tooltip.textStyle.opacity,\n fontWeight: tooltip.textStyle.fontWeight,\n fontStyle: tooltip.textStyle.fontStyle,\n fontFamily: tooltip.textStyle.fontFamily,\n color: tooltip.textStyle.color,\n }\n };\n spark.trigger(tooltipEvent.name, tooltipEvent);\n if (tooltipEvent.cancel) {\n return;\n }\n var element = new Tooltip({\n content: tooltipEvent.text,\n border: tooltip.border,\n template: tooltip.template,\n data: spark.dataSource[this.pointIndex],\n fill: tooltip.fill,\n textStyle: tooltipEvent.textStyle,\n enableAnimation: false,\n location: { x: location.x, y: location.y },\n shared: false,\n areaBounds: new Rect(0, 0, spark.availableSize.width, spark.availableSize.height),\n theme: spark.theme\n });\n element.appendTo(div);\n };\n /**\n * To get tooltip format.\n */\n SparklineTooltip.prototype.getFormat = function (format, spark, x, y) {\n if (isNullOrUndefined(format) || format === '') {\n return [y];\n }\n var text = format;\n text = text.split('${' + spark.xName + '}').join(x).split('${' + spark.yName + '}').join(y);\n return [text];\n };\n SparklineTooltip.prototype.formatValue = function (value, sparkline) {\n var formatValue;\n var formatFunction;\n if (sparkline.format && !isNaN(Number(value))) {\n formatFunction = sparkline.intl.getNumberFormat({ format: sparkline.format, useGrouping: sparkline.useGroupingSeparator });\n formatValue = formatFunction(value);\n }\n else {\n formatValue = value;\n }\n return formatValue;\n };\n /**\n * To remove tracker line.\n */\n SparklineTooltip.prototype.removeTracker = function () {\n var tracker = this.sparkline.element.querySelector('#' + this.sparkline.element.id + '_sparkline_tracker_g');\n return tracker ? remove(tracker) : null;\n };\n /**\n * To remove tooltip element.\n */\n SparklineTooltip.prototype.removeTooltip = function () {\n this.pointIndex = null;\n var tooltip = this.sparkline.element.querySelector('#' + this.sparkline.element.id + '_sparkline_tooltip_div');\n return tooltip ? remove(tooltip) : null;\n };\n /**\n * Get module name.\n */\n SparklineTooltip.prototype.getModuleName = function () {\n return 'SparklineTooltip';\n };\n /**\n * To destroy the tooltip.\n */\n SparklineTooltip.prototype.destroy = function (sparkline) {\n // To remove tooltip module\n };\n return SparklineTooltip;\n}());\nexport { SparklineTooltip };\n","import * as index from '@syncfusion/ej2-charts';\nindex.Chart.Inject( index.LineSeries,index.ScatterSeries,index.ColumnSeries,index.SplineSeries,index.SplineAreaSeries,index.StripLine,index.AreaSeries,index.ScrollBar,index.StepLineSeries,index.StepAreaSeries,index.StackingColumnSeries,index.StackingAreaSeries,index.BarSeries,index.StackingBarSeries,index.RangeColumnSeries,index.BubbleSeries,index.Tooltip,index.Crosshair,index.Category,index.DateTime,index.Logarithmic,index.Legend,index.Zoom,index.DataLabel,index.Selection,index.ChartAnnotation,index.HiloSeries,index.HiloOpenCloseSeries,index.WaterfallSeries,index.RangeAreaSeries,index.CandleSeries,index.PolarSeries,index.RadarSeries,index.SmaIndicator,index.TmaIndicator,index.EmaIndicator,index.AccumulationDistributionIndicator,index.MacdIndicator,index.AtrIndicator,index.RsiIndicator,index.MomentumIndicator,index.StochasticIndicator,index.BollingerBands,index.BoxAndWhiskerSeries,index.HistogramSeries,index.ErrorBar,index.Trendlines,index.DateTimeCategory,index.MultiColoredLineSeries,index.MultiColoredAreaSeries,index.MultiLevelLabel);\nindex.AccumulationChart.Inject( index.PieSeries,index.FunnelSeries,index.PyramidSeries,index.AccumulationTooltip,index.AccumulationLegend,index.AccumulationSelection,index.AccumulationDataLabel,index.AccumulationAnnotation);\nindex.RangeNavigator.Inject( index.RangeTooltip,index.PeriodSelector,index.AreaSeries,index.StepLineSeries,index.DateTime,index.Logarithmic);\nindex.Sparkline.Inject( index.SparklineTooltip);\nindex.Smithchart.Inject( index.SmithchartLegend,index.TooltipRender);\nexport * from '@syncfusion/ej2-charts';\n","/**\n * Specifies gauge Themes\n */\nexport var Theme;\n(function (Theme) {\n /** @private */\n Theme.axisLabelFont = {\n size: '12px',\n fontWeight: 'Normal',\n color: null,\n fontStyle: 'Normal',\n fontFamily: 'Segoe UI'\n };\n /** @private */\n Theme.axisLineColor = null;\n /** @private */\n Theme.tickLineColor = null;\n /** @private */\n Theme.pointerColor = null;\n})(Theme || (Theme = {}));\n/** @private */\nexport function getRangePalette(theme) {\n var palette = ['#50c917', '#27d5ff', '#fcde0b', '#ffb133', '#ff5985'];\n // switch (theme) {\n // case 'Material':\n // palette = ['#50c917', '#27d5ff', '#fcde0b', '#ffb133', '#ff5985'];\n // break;\n // case 'Fabric':\n // palette = ['#50c917', '#27d5ff', '#fcde0b', '#ffb133', '#ff5985'];\n // break;\n // }\n return palette;\n}\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty, Complex } from '@syncfusion/ej2-base';\n/**\n * Configures the borders in circular gauge.\n */\nvar Border = /** @class */ (function (_super) {\n __extends(Border, _super);\n function Border() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Border.prototype, \"color\", void 0);\n __decorate([\n Property(1)\n ], Border.prototype, \"width\", void 0);\n return Border;\n}(ChildProperty));\nexport { Border };\n/**\n * Configures the fonts in circular gauge.\n */\nvar Font = /** @class */ (function (_super) {\n __extends(Font, _super);\n function Font() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('16px')\n ], Font.prototype, \"size\", void 0);\n __decorate([\n Property('')\n ], Font.prototype, \"color\", void 0);\n __decorate([\n Property('segoe UI')\n ], Font.prototype, \"fontFamily\", void 0);\n __decorate([\n Property('Normal')\n ], Font.prototype, \"fontWeight\", void 0);\n __decorate([\n Property('Normal')\n ], Font.prototype, \"fontStyle\", void 0);\n __decorate([\n Property(1)\n ], Font.prototype, \"opacity\", void 0);\n return Font;\n}(ChildProperty));\nexport { Font };\n/**\n * Configures the margin of circular gauge.\n */\nvar Margin = /** @class */ (function (_super) {\n __extends(Margin, _super);\n function Margin() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(10)\n ], Margin.prototype, \"left\", void 0);\n __decorate([\n Property(10)\n ], Margin.prototype, \"right\", void 0);\n __decorate([\n Property(10)\n ], Margin.prototype, \"top\", void 0);\n __decorate([\n Property(10)\n ], Margin.prototype, \"bottom\", void 0);\n return Margin;\n}(ChildProperty));\nexport { Margin };\n/**\n * Configures the tooltip in circular gauge.\n */\nvar TooltipSettings = /** @class */ (function (_super) {\n __extends(TooltipSettings, _super);\n function TooltipSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], TooltipSettings.prototype, \"enable\", void 0);\n __decorate([\n Property('#ffffff')\n ], TooltipSettings.prototype, \"fill\", void 0);\n __decorate([\n Complex({ color: '#686868', size: '13px' }, Font)\n ], TooltipSettings.prototype, \"textStyle\", void 0);\n __decorate([\n Property(null)\n ], TooltipSettings.prototype, \"format\", void 0);\n __decorate([\n Property(null)\n ], TooltipSettings.prototype, \"template\", void 0);\n __decorate([\n Property(true)\n ], TooltipSettings.prototype, \"enableAnimation\", void 0);\n __decorate([\n Complex({}, Border)\n ], TooltipSettings.prototype, \"border\", void 0);\n return TooltipSettings;\n}(ChildProperty));\nexport { TooltipSettings };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty, Collection } from '@syncfusion/ej2-base';\nimport { Font, Border } from '../model/base';\nimport { Theme } from '../model/theme';\n/**\n * Configures the axis line.\n */\nvar Line = /** @class */ (function (_super) {\n __extends(Line, _super);\n function Line() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(2)\n ], Line.prototype, \"width\", void 0);\n __decorate([\n Property('')\n ], Line.prototype, \"dashArray\", void 0);\n __decorate([\n Property(Theme.axisLineColor)\n ], Line.prototype, \"color\", void 0);\n return Line;\n}(ChildProperty));\nexport { Line };\n/**\n * Configures the axis label.\n */\nvar Label = /** @class */ (function (_super) {\n __extends(Label, _super);\n function Label() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex(Theme.axisLabelFont, Font)\n ], Label.prototype, \"font\", void 0);\n __decorate([\n Property('')\n ], Label.prototype, \"format\", void 0);\n __decorate([\n Property('Inside')\n ], Label.prototype, \"position\", void 0);\n __decorate([\n Property('None')\n ], Label.prototype, \"hiddenLabel\", void 0);\n __decorate([\n Property(false)\n ], Label.prototype, \"autoAngle\", void 0);\n __decorate([\n Property(false)\n ], Label.prototype, \"useRangeColor\", void 0);\n __decorate([\n Property(0)\n ], Label.prototype, \"offset\", void 0);\n return Label;\n}(ChildProperty));\nexport { Label };\n/**\n * Configures the ranges of an axis.\n */\nvar Range = /** @class */ (function (_super) {\n __extends(Range, _super);\n function Range() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], Range.prototype, \"start\", void 0);\n __decorate([\n Property(null)\n ], Range.prototype, \"end\", void 0);\n __decorate([\n Property(null)\n ], Range.prototype, \"radius\", void 0);\n __decorate([\n Property(10)\n ], Range.prototype, \"startWidth\", void 0);\n __decorate([\n Property(10)\n ], Range.prototype, \"endWidth\", void 0);\n __decorate([\n Property(null)\n ], Range.prototype, \"color\", void 0);\n return Range;\n}(ChildProperty));\nexport { Range };\n/**\n * Configures the major and minor tick lines of an axis.\n */\nvar Tick = /** @class */ (function (_super) {\n __extends(Tick, _super);\n function Tick() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], Tick.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], Tick.prototype, \"height\", void 0);\n __decorate([\n Property(null)\n ], Tick.prototype, \"interval\", void 0);\n __decorate([\n Property(0)\n ], Tick.prototype, \"offset\", void 0);\n __decorate([\n Property(Theme.tickLineColor)\n ], Tick.prototype, \"color\", void 0);\n __decorate([\n Property('Inside')\n ], Tick.prototype, \"position\", void 0);\n __decorate([\n Property(false)\n ], Tick.prototype, \"useRangeColor\", void 0);\n return Tick;\n}(ChildProperty));\nexport { Tick };\n/**\n * Configures the needle cap in pointer.\n */\nvar Cap = /** @class */ (function (_super) {\n __extends(Cap, _super);\n function Cap() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('#ffffff')\n ], Cap.prototype, \"color\", void 0);\n __decorate([\n Complex({ color: Theme.pointerColor, width: 8 }, Border)\n ], Cap.prototype, \"border\", void 0);\n __decorate([\n Property(8)\n ], Cap.prototype, \"radius\", void 0);\n return Cap;\n}(ChildProperty));\nexport { Cap };\n/**\n * Configures the back needle in pointers.\n */\nvar NeedleTail = /** @class */ (function (_super) {\n __extends(NeedleTail, _super);\n function NeedleTail() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(Theme.pointerColor)\n ], NeedleTail.prototype, \"color\", void 0);\n __decorate([\n Complex({ color: Theme.pointerColor, width: 0 }, Border)\n ], NeedleTail.prototype, \"border\", void 0);\n __decorate([\n Property('0%')\n ], NeedleTail.prototype, \"length\", void 0);\n return NeedleTail;\n}(ChildProperty));\nexport { NeedleTail };\n/**\n * Configures the animation of pointers.\n */\nvar Animation = /** @class */ (function (_super) {\n __extends(Animation, _super);\n function Animation() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], Animation.prototype, \"enable\", void 0);\n __decorate([\n Property(1000)\n ], Animation.prototype, \"duration\", void 0);\n return Animation;\n}(ChildProperty));\nexport { Animation };\n/**\n * ‘Annotation’ module is used to handle annotation action for an axis.\n */\nvar Annotation = /** @class */ (function (_super) {\n __extends(Annotation, _super);\n function Annotation() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], Annotation.prototype, \"content\", void 0);\n __decorate([\n Property(90)\n ], Annotation.prototype, \"angle\", void 0);\n __decorate([\n Property('50%')\n ], Annotation.prototype, \"radius\", void 0);\n __decorate([\n Property('-1')\n ], Annotation.prototype, \"zIndex\", void 0);\n __decorate([\n Property(false)\n ], Annotation.prototype, \"autoAngle\", void 0);\n __decorate([\n Complex({ size: '12px', color: '#686868' }, Font)\n ], Annotation.prototype, \"textStyle\", void 0);\n __decorate([\n Property(null)\n ], Annotation.prototype, \"description\", void 0);\n return Annotation;\n}(ChildProperty));\nexport { Annotation };\n/**\n * Configures the pointers of an axis.\n */\nvar Pointer = /** @class */ (function (_super) {\n __extends(Pointer, _super);\n function Pointer() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], Pointer.prototype, \"value\", void 0);\n __decorate([\n Property('Needle')\n ], Pointer.prototype, \"type\", void 0);\n __decorate([\n Property(null)\n ], Pointer.prototype, \"imageUrl\", void 0);\n __decorate([\n Property(null)\n ], Pointer.prototype, \"radius\", void 0);\n __decorate([\n Property(20)\n ], Pointer.prototype, \"pointerWidth\", void 0);\n __decorate([\n Complex({}, Cap)\n ], Pointer.prototype, \"cap\", void 0);\n __decorate([\n Complex({}, NeedleTail)\n ], Pointer.prototype, \"needleTail\", void 0);\n __decorate([\n Property(Theme.pointerColor)\n ], Pointer.prototype, \"color\", void 0);\n __decorate([\n Complex({ color: '#DDDDDD', width: 0 }, Border)\n ], Pointer.prototype, \"border\", void 0);\n __decorate([\n Complex(null, Animation)\n ], Pointer.prototype, \"animation\", void 0);\n __decorate([\n Property('Circle')\n ], Pointer.prototype, \"markerShape\", void 0);\n __decorate([\n Property(5)\n ], Pointer.prototype, \"markerHeight\", void 0);\n __decorate([\n Property(null)\n ], Pointer.prototype, \"description\", void 0);\n __decorate([\n Property(5)\n ], Pointer.prototype, \"markerWidth\", void 0);\n return Pointer;\n}(ChildProperty));\nexport { Pointer };\n/**\n * Configures an axis in a gauge.\n */\nvar Axis = /** @class */ (function (_super) {\n __extends(Axis, _super);\n function Axis() {\n /**\n * Specifies the minimum value of an axis.\n * @aspDefaultValueIgnore\n * @default null\n */\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /** @private */\n _this.visibleLabels = [];\n return _this;\n }\n __decorate([\n Property(null)\n ], Axis.prototype, \"minimum\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"maximum\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"radius\", void 0);\n __decorate([\n Complex({}, Line)\n ], Axis.prototype, \"lineStyle\", void 0);\n __decorate([\n Collection([{}], Range)\n ], Axis.prototype, \"ranges\", void 0);\n __decorate([\n Collection([{}], Pointer)\n ], Axis.prototype, \"pointers\", void 0);\n __decorate([\n Collection([{}], Annotation)\n ], Axis.prototype, \"annotations\", void 0);\n __decorate([\n Complex({ width: 2, height: 10 }, Tick)\n ], Axis.prototype, \"majorTicks\", void 0);\n __decorate([\n Complex({ width: 2, height: 5 }, Tick)\n ], Axis.prototype, \"minorTicks\", void 0);\n __decorate([\n Property(200)\n ], Axis.prototype, \"startAngle\", void 0);\n __decorate([\n Property(160)\n ], Axis.prototype, \"endAngle\", void 0);\n __decorate([\n Property('ClockWise')\n ], Axis.prototype, \"direction\", void 0);\n __decorate([\n Property(null)\n ], Axis.prototype, \"background\", void 0);\n __decorate([\n Complex({}, Label)\n ], Axis.prototype, \"labelStyle\", void 0);\n return Axis;\n}(ChildProperty));\nexport { Axis };\n","import { stringToNumber, getLocationFromAngle, getFontStyle } from '../utils/helper';\nimport { getElement, getTemplateFunction, measureElementRect } from '../utils/helper';\nimport { annotationRender } from '../model/constants';\nimport { createElement } from '@syncfusion/ej2-base';\n/**\n * Annotation Module handles the Annotation of the axis.\n */\nvar Annotations = /** @class */ (function () {\n /**\n * Constructor for Annotation module.\n * @private.\n */\n function Annotations(gauge) {\n this.gauge = gauge;\n this.elementId = gauge.element.id;\n }\n /**\n * Method to render the annotation for circular gauge.\n */\n Annotations.prototype.renderAnnotation = function (axis, index) {\n var _this = this;\n var element = createElement('div', {\n id: this.elementId + '_Annotations_' + index\n });\n var parentElement = getElement(this.elementId + '_Secondary_Element');\n axis.annotations.map(function (annotation, annotationIndex) {\n if (annotation.content !== null) {\n _this.createTemplate(element, annotationIndex, index);\n }\n });\n if (parentElement && element.childElementCount) {\n parentElement.appendChild(element);\n }\n };\n /**\n * Method to create annotation template for circular gauge.\n */\n Annotations.prototype.createTemplate = function (element, annotationIndex, axisIndex) {\n var axis = this.gauge.axes[axisIndex];\n var annotation = axis.annotations[annotationIndex];\n var childElement = createElement('div', {\n id: this.elementId + '_Axis_' + axisIndex + '_Annotation_' + annotationIndex,\n styles: 'position: absolute; z-index:' + annotation.zIndex + ';transform:' +\n (annotation.autoAngle ? 'rotate(' + (annotation.angle - 90) + 'deg)' : 'rotate(0deg)') + ';'\n });\n var argsData = {\n cancel: false, name: annotationRender, content: annotation.content,\n axis: axis, annotation: annotation, textStyle: annotation.textStyle\n };\n this.gauge.trigger(annotationRender, argsData);\n var templateFn;\n var templateElement;\n if (!argsData.cancel) {\n templateFn = getTemplateFunction(argsData.content);\n if (templateFn && templateFn(axis).length) {\n templateElement = templateFn(axis);\n while (templateElement.length > 0) {\n childElement.appendChild(templateElement[0]);\n }\n }\n else {\n childElement.appendChild(createElement('div', {\n innerHTML: argsData.content,\n styles: getFontStyle(argsData.textStyle)\n }));\n }\n this.updateLocation(childElement, axis, annotation);\n element.appendChild(childElement);\n }\n };\n /**\n * Method to update the annotation location for circular gauge.\n */\n Annotations.prototype.updateLocation = function (element, axis, annotation) {\n var location = getLocationFromAngle(annotation.angle - 90, stringToNumber(annotation.radius, axis.currentRadius), this.gauge.midPoint);\n var elementRect = measureElementRect(element);\n element.style.left = (location.x - (elementRect.width / 2)) + 'px';\n element.style.top = (location.y - (elementRect.height / 2)) + 'px';\n element.setAttribute('aria-label', annotation.description || 'Annotation');\n };\n /**\n * Get module name.\n */\n Annotations.prototype.getModuleName = function () {\n // Returns te module name\n return 'Annotations';\n };\n /**\n * To destroy the annotation.\n * @return {void}\n * @private\n */\n Annotations.prototype.destroy = function (gauge) {\n // Destroy method performed here\n };\n return Annotations;\n}());\nexport { Annotations };\n","/**\n * Specifies the gauge constant value\n */\n/** @private */\nexport var loaded = 'loaded';\n/** @private */\nexport var load = 'load';\n/** @private */\nexport var animationComplete = 'animationComplete';\n/** @private */\nexport var axisLabelRender = 'axisLabelRender';\n/** @private */\nexport var tooltipRender = 'tooltipRender';\n/** @private */\nexport var annotationRender = 'annotationRender';\n/** @private */\nexport var gaugeMouseMove = 'gaugeMouseMove';\n/** @private */\nexport var gaugeMouseLeave = 'gaugeMouseLeave';\n/** @private */\nexport var gaugeMouseDown = 'gaugeMouseDown';\n/** @private */\nexport var gaugeMouseUp = 'gaugeMouseUp';\n/** @private */\nexport var dragStart = 'dragStart';\n/** @private */\nexport var dragMove = 'dragMove';\n/** @private */\nexport var dragEnd = 'dragEnd';\n/** @private */\nexport var resized = 'resized';\n","import { createElement, setStyleAttribute } from '@syncfusion/ej2-base';\nimport { Tooltip } from '@syncfusion/ej2-popups';\nimport { getPointer, getTemplateFunction } from '../utils/helper';\nimport { getAngleFromValue, getLabelFormat, getElement, getLocationFromAngle } from '../utils/helper';\nimport { tooltipRender } from '../model/constants';\n/**\n * Tooltip Module handles the tooltip of the circular gauge\n */\nvar GaugeTooltip = /** @class */ (function () {\n /**\n * Constructor for Tooltip module.\n * @private.\n */\n function GaugeTooltip(gauge) {\n this.gauge = gauge;\n this.element = gauge.element;\n this.tooltip = gauge.tooltip;\n this.textStyle = this.tooltip.textStyle;\n this.borderStyle = this.tooltip.border;\n this.ejTooltip = new Tooltip({\n opensOn: 'custom',\n beforeRender: this.onBeforeRender.bind(this),\n beforeOpen: this.tooltipCustomization.bind(this),\n openDelay: 0, closeDelay: 1000\n });\n this.ejTooltip.appendTo(this.element);\n }\n /**\n * Method to render the tooltip for circular gauge.\n */\n GaugeTooltip.prototype.renderTooltip = function (target) {\n var currentPointer = getPointer(target.id, this.gauge);\n var element;\n var angle;\n this.currentAxis = this.gauge.axes[currentPointer.axisIndex];\n this.currentPointer = (this.currentAxis.pointers)[currentPointer.pointerIndex];\n angle = getAngleFromValue(this.currentPointer.currentValue, this.currentAxis.visibleRange.max, this.currentAxis.visibleRange.min, this.currentAxis.startAngle, this.currentAxis.endAngle, this.currentAxis.direction === 'ClockWise') % 360;\n element = this.appendTargetElement(angle);\n if (element.getAttribute('data-tooltip-id') === null) {\n this.findPosition(angle);\n this.ejTooltip.open(element);\n }\n };\n /**\n * Method to append the target element for tooltip\n */\n GaugeTooltip.prototype.appendTargetElement = function (angle) {\n var location = getLocationFromAngle(angle, this.currentAxis.currentRadius, this.gauge.midPoint);\n var element = getElement(this.element.id + '_GaugeTooltip');\n if (element) {\n element.style.left = location.x + 'px';\n element.style.top = location.y + 'px';\n }\n else {\n element = createElement('div', {\n id: this.element.id + '_GaugeTooltip',\n styles: 'position:absolute;left:' + location.x + 'px;top:' + location.y +\n 'px;width:2px;height:2px;background:transparent'\n });\n getElement(this.element.id + '_Secondary_Element').appendChild(element);\n }\n return element;\n };\n /**\n * Method to find the position of the tooltip anchor for circular gauge.\n */\n GaugeTooltip.prototype.findPosition = function (angle) {\n switch (true) {\n case (angle >= 0 && angle <= 45):\n this.ejTooltip.position = 'RightBottom';\n break;\n case (angle >= 45 && angle < 90):\n this.ejTooltip.position = 'BottomRight';\n break;\n case (angle >= 90 && angle < 135):\n this.ejTooltip.position = 'BottomLeft';\n break;\n case (angle >= 135 && angle < 180):\n this.ejTooltip.position = 'LeftBottom';\n break;\n case (angle >= 180 && angle < 225):\n this.ejTooltip.position = 'LeftTop';\n break;\n case (angle >= 225 && angle < 270):\n this.ejTooltip.position = 'TopLeft';\n break;\n case (angle >= 270 && angle < 315):\n this.ejTooltip.position = 'TopRight';\n break;\n default:\n this.ejTooltip.position = 'RightTop';\n break;\n }\n this.ejTooltip.dataBind();\n };\n /**\n * Method to perform the tooltip for circular gauge.\n */\n GaugeTooltip.prototype.onBeforeRender = function (args) {\n var tooltipFormat = this.gauge.tooltip.format || this.currentAxis.labelStyle.format;\n var customLabelFormat = tooltipFormat && tooltipFormat.match('{value}') !== null;\n var format = this.gauge.intl.getNumberFormat({\n format: getLabelFormat(tooltipFormat), useGrouping: this.gauge.useGroupingSeparator\n });\n var content = customLabelFormat ?\n tooltipFormat.replace(new RegExp('{value}', 'g'), format(this.currentPointer.currentValue)) :\n format(this.currentPointer.currentValue);\n content = this.tooltip.template ?\n getTemplateFunction(this.tooltip.template)(this.currentAxis)[0] : content;\n var argsData = {\n cancel: false, name: tooltipRender,\n content: content,\n border: this.borderStyle,\n axis: this.currentAxis, pointer: this.currentPointer,\n textStyle: this.textStyle\n };\n this.gauge.trigger(tooltipRender, argsData);\n this.borderStyle = argsData.border;\n args.cancel = argsData.cancel;\n this.ejTooltip.content = argsData.content;\n this.textStyle = argsData.textStyle;\n this.ejTooltip.dataBind();\n };\n /**\n * Method to customize the tooltip elements for circular gauge.\n */\n GaugeTooltip.prototype.tooltipCustomization = function (args) {\n var font = this.textStyle;\n var borderColor = this.borderStyle.color;\n var border = this.borderStyle.width;\n var pointerSize = 5;\n var arrowWidth = (pointerSize - border) + 'px';\n var outerWidth;\n var innerWidth;\n args.element.classList.remove('e-popup-close');\n args.element.classList.add('e-popup-open');\n var arrowEle = args.element.querySelector('.e-arrow-tip');\n setStyleAttribute(args.element, {\n 'backgroundColor': this.tooltip.fill, 'borderColor': borderColor || '#212121',\n 'borderWidth': border + 'px'\n });\n setStyleAttribute(args.element.querySelector('.e-tip-content'), {\n 'color': font.color, 'fontFamily': font.fontFamily, 'fontSize': font.size,\n 'fontWeight': font.fontWeight, 'opacity': font.opacity.toString(), 'fontStyle': font.fontStyle\n });\n setStyleAttribute(args.element.querySelector('.e-arrow-tip'), {\n 'width': 2 * (pointerSize + border) + 'px', 'height': pointerSize + border + 'px'\n });\n if (arrowEle.classList.contains('e-tip-top')) {\n pointerSize = args.element.querySelector('.e-arrow-tip').offsetHeight;\n outerWidth = pointerSize + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-outer'), {\n 'borderRightColor': 'transparent', 'borderLeftColor': 'transparent', 'borderBottomColor': borderColor,\n 'borderLeftWidth': outerWidth, 'borderRightWidth': outerWidth, 'borderBottomWidth': outerWidth,\n });\n innerWidth = (pointerSize - border) + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-inner'), {\n 'borderRightColor': 'transparent', 'borderLeftColor': 'transparent', 'borderBottomColor': this.tooltip.fill,\n 'borderLeftWidth': innerWidth, 'borderRightWidth': innerWidth, 'borderBottomWidth': innerWidth,\n 'left': border + 'px', 'top': border + 'px', 'display': 'none'\n });\n }\n else if (arrowEle.classList.contains('e-tip-bottom')) {\n pointerSize = args.element.querySelector('.e-arrow-tip').offsetHeight;\n outerWidth = pointerSize + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-outer'), {\n 'borderRightColor': 'transparent', 'borderLeftColor': 'transparent', 'borderTopColor': borderColor,\n 'borderLeftWidth': outerWidth, 'borderRightWidth': outerWidth, 'borderTopWidth': outerWidth,\n });\n innerWidth = (pointerSize - border) + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-inner'), {\n 'borderRightColor': 'transparent', 'borderLeftColor': 'transparent', 'borderTopColor': this.tooltip.fill,\n 'borderLeftWidth': innerWidth, 'borderRightWidth': innerWidth, 'borderTopWidth': innerWidth,\n 'left': border + 'px', 'top': '0', 'display': 'none'\n });\n }\n else if (arrowEle.classList.contains('e-tip-left')) {\n setStyleAttribute(args.element.querySelector('.e-arrow-tip'), {\n 'width': pointerSize + border + 'px', 'height': 2 * (pointerSize + border) + 'px'\n });\n pointerSize = args.element.querySelector('.e-arrow-tip').offsetWidth;\n outerWidth = pointerSize + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-outer'), {\n 'borderTopColor': 'transparent', 'borderBottomColor': 'transparent', 'borderRightColor': borderColor,\n 'borderTopWidth': outerWidth, 'borderBottomWidth': outerWidth, 'borderRightWidth': outerWidth\n });\n innerWidth = (pointerSize - border) + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-inner'), {\n 'borderTopColor': 'transparent', 'borderBottomColor': 'transparent', 'borderRightColor': this.tooltip.fill,\n 'borderTopWidth': innerWidth, 'borderBottomWidth': innerWidth, 'borderRightWidth': innerWidth,\n 'left': border + 'px', 'top': border + 'px', 'display': 'none'\n });\n }\n else {\n setStyleAttribute(args.element.querySelector('.e-arrow-tip'), {\n 'width': (pointerSize + border) + 'px', 'height': 2 * (pointerSize + border) + 'px'\n });\n pointerSize = args.element.querySelector('.e-arrow-tip').offsetWidth;\n outerWidth = pointerSize + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-outer'), {\n 'borderTopColor': 'transparent', 'borderBottomColor': 'transparent', 'borderLeftColor': borderColor,\n 'borderTopWidth': outerWidth, 'borderBottomWidth': outerWidth, 'borderLeftWidth': outerWidth\n });\n innerWidth = (pointerSize - border) + 'px';\n setStyleAttribute(args.element.querySelector('.e-arrow-tip-inner'), {\n 'borderTopColor': 'transparent', 'borderBottomColor': 'transparent', 'borderLeftColor': this.tooltip.fill,\n 'borderTopWidth': innerWidth, 'borderBottomWidth': innerWidth, 'borderLeftWidth': innerWidth,\n 'left': (border <= 1 ? 0 : -1) + 'px', 'top': border + 'px', 'display': 'none'\n });\n }\n this.ejTooltip.refresh(args.target);\n setStyleAttribute(args.element, {\n 'display': 'block', 'transitionProperty': 'left,top',\n 'transitionDuration': this.tooltip.enableAnimation ? '1000ms' : '0ms'\n });\n };\n /**\n * Get module name.\n */\n GaugeTooltip.prototype.getModuleName = function () {\n // Returns te module name\n return 'Tooltip';\n };\n /**\n * To destroy the tooltip.\n * @return {void}\n * @private\n */\n GaugeTooltip.prototype.destroy = function (gauge) {\n // Destroy method performed here\n };\n return GaugeTooltip;\n}());\nexport { GaugeTooltip };\n","import { getLocationFromAngle, PathOption, stringToNumber, TextOption, textElement, appendPath, toPixel } from '../utils/helper';\nimport { getAngleFromValue, isCompleteAngle, getPathArc, getRangeColor } from '../utils/helper';\nimport { getRangePalette } from '../model/theme';\n/**\n * Specifies the Axis rendering for circular gauge\n */\nvar AxisRenderer = /** @class */ (function () {\n /**\n * Constructor for axis renderer.\n * @private.\n */\n function AxisRenderer(gauge) {\n this.gauge = gauge;\n }\n /**\n * Method to render the axis element of the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.drawAxisOuterLine = function (axis, index, element, gauge) {\n var background = axis.background;\n this.setRangeColor(axis);\n if (background !== null) {\n appendPath(new PathOption(gauge.element.id + '_AxisOuterLine_' + index, background, 0, 'transparent', null, '0', getPathArc(gauge.midPoint, 0, 360, (Math.min(axis.rect.width, axis.rect.height) / 2)), '', 'pointer-events:none;'), element, gauge);\n }\n };\n /**\n * Method to render the axis line of the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.drawAxisLine = function (axis, index, element, gauge) {\n var startAngle = axis.startAngle;\n var endAngle = axis.endAngle;\n if (axis.lineStyle.width > 0) {\n startAngle = !isCompleteAngle(startAngle, endAngle) ? startAngle : [0, endAngle = 360][0];\n appendPath(new PathOption(gauge.element.id + '_AxisLine_' + index, 'transparent', axis.lineStyle.width, axis.lineStyle.color, null, axis.lineStyle.dashArray, getPathArc(gauge.midPoint, startAngle - 90, endAngle - 90, axis.currentRadius), '', 'pointer-events:none;'), element, gauge);\n }\n };\n /**\n * Method to render the axis labels of the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.drawAxisLabels = function (axis, index, element, gauge) {\n var labelElement = gauge.renderer.createGroup({\n id: gauge.element.id + '_Axis_Labels_' + index\n });\n var min = axis.visibleRange.min;\n var max = axis.visibleRange.max;\n var labelCollection = axis.visibleLabels;\n var location;\n var style = axis.labelStyle;\n var anchor;\n var angle;\n var label;\n var radius = axis.currentRadius;\n var labelPadding = 10;\n if (style.position === 'Outside') {\n radius += (axis.nearSize - (axis.maxLabelSize.height + axis.lineStyle.width / 2)) +\n (labelPadding / 2);\n }\n else {\n radius -= (axis.farSize - (axis.maxLabelSize.height + axis.lineStyle.width / 2) +\n (style.autoAngle ? labelPadding : 0));\n }\n for (var i = 0, length_1 = labelCollection.length; i < length_1; i++) {\n if ((i === 0 && style.hiddenLabel === 'First') ||\n (i === (length_1 - 1) && style.hiddenLabel === 'Last')) {\n continue;\n }\n label = labelCollection[i];\n angle = Math.round(getAngleFromValue(label.value, max, min, axis.startAngle, axis.endAngle, axis.direction === 'ClockWise'));\n location = getLocationFromAngle(angle, radius, gauge.midPoint);\n anchor = this.findAnchor(location, style, angle, label);\n textElement(new TextOption(gauge.element.id + '_Axis_' + index + '_Label_' + i, location.x, location.y, anchor, label.text, style.autoAngle ? 'rotate(' + (angle + 90) + ',' + (location.x) + ',' + location.y + ')' : '', 'auto'), style.font, style.useRangeColor ? getRangeColor(label.value, axis.ranges, style.font.color) : style.font.color, labelElement, 'pointer-events:none;');\n }\n element.appendChild(labelElement);\n };\n /**\n * Method to find the anchor of the axis label.\n * @private\n */\n AxisRenderer.prototype.findAnchor = function (location, style, angle, label) {\n if (style.autoAngle) {\n return 'middle';\n }\n var anchor = style.position === 'Inside' ?\n ((angle > 120 && angle < 240) ? 'start' : ((300 < angle || angle < 60) ? 'end' : 'middle')) :\n ((angle > 120 && angle < 240) ? 'end' : ((300 < angle || angle < 60) ? 'start' : 'middle'));\n location.y += style.position === 'Inside' ?\n ((angle >= 240 && angle <= 300) ? (label.size.height / 2) :\n (angle >= 60 && angle <= 120) ? 0 : label.size.height / 4) :\n ((angle >= 240 && angle <= 300) ? 0 :\n (angle >= 60 && angle <= 120) ? label.size.height / 2 : label.size.height / 4);\n return anchor;\n };\n /**\n * Method to render the axis minor tick lines of the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.drawMinorTickLines = function (axis, index, element, gauge) {\n var minorTickElements = gauge.renderer.createGroup({\n id: gauge.element.id + '_Axis_MinorTickLines_' + index\n });\n var minorLineStyle = axis.minorTicks;\n var minorInterval = minorLineStyle.interval !== null ?\n minorLineStyle.interval : (axis.visibleRange.interval / 2);\n var isRangeColor = minorLineStyle.useRangeColor;\n if (minorLineStyle.width && minorLineStyle.height && minorInterval) {\n for (var i = axis.visibleRange.min, max = axis.visibleRange.max; i <= max; i += minorInterval) {\n if (this.majorValues.indexOf(+i.toFixed(3)) < 0) {\n appendPath(new PathOption(gauge.element.id + '_Axis_Minor_TickLine_' + index + '_' + i, 'transparent', minorLineStyle.width, isRangeColor ? getRangeColor(i, axis.ranges, minorLineStyle.color) : minorLineStyle.color, null, '0', this.calculateTicks(i, minorLineStyle, axis), '', 'pointer-events:none;'), minorTickElements, gauge);\n }\n }\n element.appendChild(minorTickElements);\n }\n };\n /**\n * Method to render the axis major tick lines of the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.drawMajorTickLines = function (axis, index, element, gauge) {\n var majorTickElements = gauge.renderer.createGroup({\n id: gauge.element.id + '_Axis_MajorTickLines_' + index\n });\n var majorLineStyle = axis.majorTicks;\n var isRangeColor = majorLineStyle.useRangeColor;\n this.majorValues = [];\n if (majorLineStyle.width && majorLineStyle.height && axis.visibleRange.interval) {\n for (var i = axis.visibleRange.min, max = axis.visibleRange.max, interval = axis.visibleRange.interval; i <= max; i += interval) {\n this.majorValues.push(+i.toFixed(3));\n appendPath(new PathOption(gauge.element.id + '_Axis_Major_TickLine_' + index + '_' + i, 'transparent', majorLineStyle.width, isRangeColor ? getRangeColor(i, axis.ranges, majorLineStyle.color) : majorLineStyle.color, null, '0', this.calculateTicks(i, majorLineStyle, axis), '', 'pointer-events:none;'), majorTickElements, gauge);\n }\n element.appendChild(majorTickElements);\n }\n };\n /**\n * Method to calcualte the tick elements for the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.calculateTicks = function (value, options, axis) {\n var axisLineWidth = (axis.lineStyle.width / 2) + options.offset;\n var isOutside = options.position === 'Outside';\n var angle = getAngleFromValue(value, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, axis.direction === 'ClockWise');\n var start = getLocationFromAngle(angle, axis.currentRadius +\n (isOutside ? axisLineWidth : -axisLineWidth), this.gauge.midPoint);\n var end = getLocationFromAngle(angle, axis.currentRadius +\n (isOutside ? axisLineWidth : -axisLineWidth) +\n (isOutside ? options.height : -options.height), this.gauge.midPoint);\n return 'M ' + start.x + ' ' + start.y + ' L ' + end.x + ' ' + end.y + ' ';\n };\n /**\n * Method to render the axis range of the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.drawAxisRange = function (axis, index, element, gauge) {\n var _this = this;\n var rangeElement = gauge.renderer.createGroup({\n id: gauge.element.id + '_Axis_Ranges_' + index\n });\n var startAngle;\n var endAngle;\n var isClockWise = axis.direction === 'ClockWise';\n var startValue;\n var endValue;\n var min = axis.visibleRange.min;\n var max = axis.visibleRange.max;\n var startWidth;\n var endWidth;\n axis.ranges.map(function (range, rangeIndex) {\n _this.calculateRangeRadius(axis, range);\n startValue = Math.min(Math.max(range.start, min), range.end);\n endValue = Math.min(Math.max(range.start, range.end), max);\n if (startValue !== endValue) {\n startAngle = getAngleFromValue(startValue, max, min, axis.startAngle, axis.endAngle, isClockWise);\n endAngle = getAngleFromValue(endValue, max, min, axis.startAngle, axis.endAngle, isClockWise);\n if (range.startWidth.length > 0) {\n startWidth = toPixel(range.startWidth, range.currentRadius);\n }\n else {\n startWidth = range.startWidth;\n }\n if (range.endWidth.length > 0) {\n endWidth = toPixel(range.endWidth, range.currentRadius);\n }\n else {\n endWidth = range.endWidth;\n }\n endAngle = isClockWise ? endAngle : [startAngle, startAngle = endAngle][0];\n endWidth = isClockWise ? endWidth : [startWidth, startWidth = endWidth][0];\n appendPath(new PathOption(gauge.element.id + '_Axis_' + index + '_Range_' + rangeIndex, range.rangeColor, 0, range.rangeColor, 1, '0', getPathArc(gauge.midPoint, Math.floor(startAngle), Math.ceil(endAngle), range.currentRadius, startWidth, endWidth), '', 'pointer-events:none;'), rangeElement, gauge);\n }\n });\n element.appendChild(rangeElement);\n };\n /**\n * Method to calculate the radius of the axis range.\n * @return {void}\n */\n AxisRenderer.prototype.calculateRangeRadius = function (axis, range) {\n var radius = range.radius !== null ? range.radius : '100%';\n range.currentRadius = stringToNumber(radius, axis.currentRadius);\n };\n /**\n * Method to get the range color of the circular gauge.\n * @return {void}\n * @private\n */\n AxisRenderer.prototype.setRangeColor = function (axis) {\n var rangeColors = getRangePalette(this.gauge.theme);\n axis.ranges.map(function (range, index) {\n range.rangeColor = range.color ? range.color : rangeColors[index % rangeColors.length];\n });\n };\n return AxisRenderer;\n}());\nexport { AxisRenderer };\n","import { stringToNumber, Size, calculateShapes, appendPath } from '../utils/helper';\nimport { getLocationFromAngle, PathOption } from '../utils/helper';\nimport { linear, getAngleFromValue, getCompleteArc } from '../utils/helper';\nimport { Animation } from '@syncfusion/ej2-base';\nimport { animationComplete } from '../model/constants';\n/**\n * Specifies the Axis rendering for circular gauge\n */\nvar PointerRenderer = /** @class */ (function () {\n /**\n * Constructor for pointer renderer.\n * @private.\n */\n function PointerRenderer(gauge) {\n this.gauge = gauge;\n }\n /**\n * Method to render the axis pointers of the circular gauge.\n * @return {void}\n * @private\n */\n PointerRenderer.prototype.drawPointers = function (axis, axisIndex, element, gauge, animate) {\n var _this = this;\n if (animate === void 0) { animate = true; }\n var pointerElement = gauge.renderer.createGroup({\n id: gauge.element.id + '_Axis_Pointers_' + axisIndex\n });\n var childElement;\n var range;\n axis.pointers.map(function (pointer, pointerIndex) {\n range = axis.visibleRange;\n pointer.pathElement = [];\n _this.calculatePointerRadius(axis, pointer);\n childElement = gauge.renderer.createGroup({\n id: gauge.element.id + '_Axis_' + axisIndex + '_Pointer_' + pointerIndex\n });\n _this['draw' + pointer.type + 'Pointer'](axis, axisIndex, pointerIndex, childElement, gauge);\n _this.setPointerValue(axis, pointer, pointer.currentValue);\n pointerElement.appendChild(childElement);\n if (animate) {\n _this.doPointerAnimation(pointer, axis);\n }\n });\n element.appendChild(pointerElement);\n };\n /**\n * Measure the pointer length of the circular gauge.\n * @return {void}\n */\n PointerRenderer.prototype.calculatePointerRadius = function (axis, pointer) {\n var padding = 5;\n pointer.currentRadius = pointer.radius === null ?\n (axis.currentRadius - (axis.farSize + padding)) :\n stringToNumber(pointer.radius, axis.currentRadius);\n };\n /**\n * Method to render the needle pointer of the ciruclar gauge.\n * @return {void}\n */\n PointerRenderer.prototype.drawNeedlePointer = function (axis, axisIndex, index, parentElement, gauge) {\n var pointer = axis.pointers[index];\n var pointerRadius;\n var location;\n var direction;\n var mid = gauge.midPoint;\n var width = pointer.pointerWidth / 2;\n var rectDirection;\n // To render the needle\n location = getLocationFromAngle(0, pointer.currentRadius, mid);\n direction = 'M ' + mid.x + ' ' + (mid.y - width) + ' L ' + (location.x) + ' ' + mid.y +\n ' L ' + (mid.x) + ' ' + (mid.y + width) + ' Z';\n pointer.pathElement.push(appendPath(new PathOption(gauge.element.id + '_Axis_' + axisIndex + '_Pointer_Needle_' + index, pointer.color, pointer.border.width, pointer.border.color, null, '0', direction), parentElement, gauge));\n pointerRadius = stringToNumber(pointer.needleTail.length, pointer.currentRadius);\n // To render the rect element for touch\n rectDirection = 'M ' + mid.x + ' ' + (mid.y - width) + ' L ' + (location.x) + ' ' + (mid.y - width) +\n ' L ' + location.x + ' ' + (mid.y + width) + ' L ' + mid.x + ' ' + (mid.y + width);\n // To render the needle tail\n if (pointerRadius) {\n location = getLocationFromAngle(180, pointerRadius, gauge.midPoint);\n direction = 'M ' + mid.x + ' ' + (mid.y - width) +\n ' L ' + (location.x) + ' ' + (mid.y - width) +\n ' L ' + (location.x) + ' ' + (mid.y + width) +\n ' L ' + (mid.x) + ' ' + (mid.y + width) + ' Z';\n pointer.pathElement.push(appendPath(new PathOption(gauge.element.id + '_Axis_' + axisIndex + '_Pointer_NeedleTail_' + index, pointer.needleTail.color, pointer.needleTail.border.width, pointer.needleTail.border.color, null, '0', direction), parentElement, gauge));\n rectDirection += ' L ' + location.x + ' ' + (mid.y + width) + ' L ' + location.x + ' ' + (mid.y - width);\n }\n // To render the cap\n if (pointer.cap.radius) {\n pointer.pathElement.push(appendPath(calculateShapes(mid, 'Circle', new Size(pointer.cap.radius * 2, pointer.cap.radius * 2), '', new PathOption(gauge.element.id + '_Axis_' + axisIndex + '_Pointer_NeedleCap_' + index, pointer.cap.color, pointer.cap.border.width, pointer.cap.border.color, null, '0', '', '')), parentElement, gauge, 'Ellipse'));\n }\n pointer.pathElement.push(appendPath(new PathOption(gauge.element.id + '_Axis_' + axisIndex + '_Pointer_NeedleRect_' + index, 'transparent', 0, 'transpanret', null, '0', rectDirection + ' Z'), parentElement, gauge));\n };\n /**\n * Method to set the pointer value of the circular gauge.\n * @return {void}\n * @private\n */\n PointerRenderer.prototype.setPointerValue = function (axis, pointer, value) {\n var location = this.gauge.midPoint;\n var isClockWise = axis.direction === 'ClockWise';\n var startAngle = getAngleFromValue(axis.visibleRange.min, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var endAngle = getAngleFromValue(value, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise);\n endAngle = isClockWise ? endAngle : [startAngle, startAngle = endAngle][0];\n pointer.pathElement.map(function (element) {\n if (pointer.type === 'RangeBar') {\n element.setAttribute('d', getCompleteArc(location, startAngle, endAngle, pointer.currentRadius, (pointer.currentRadius - pointer.pointerWidth)));\n }\n else {\n element.setAttribute('transform', 'rotate(' + getAngleFromValue(value, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise) + ',' + location.x + ',' + location.y + ')');\n }\n element.setAttribute('aria-label', pointer.description || 'Pointer:' + value.toString());\n });\n };\n /**\n * Method to render the marker pointer of the ciruclar gauge.\n * @return {void}\n */\n PointerRenderer.prototype.drawMarkerPointer = function (axis, axisIndex, index, parentElement, gauge) {\n var pointer = axis.pointers[index];\n var location = getLocationFromAngle(0, pointer.currentRadius, gauge.midPoint);\n pointer.pathElement.push(appendPath(calculateShapes(location, pointer.markerShape, new Size(pointer.markerWidth, pointer.markerHeight), pointer.imageUrl, new PathOption(gauge.element.id + '_Axis_' + axisIndex + '_Pointer_Marker_' + index, pointer.color, pointer.border.width, pointer.border.color, null, '0', '', '')), parentElement, gauge, pointer.markerShape === 'Circle' ? 'Ellipse' : (pointer.markerShape === 'Image' ? 'Image' : 'Path')));\n };\n /**\n * Method to render the range bar pointer of the ciruclar gauge.\n * @return {void}\n */\n PointerRenderer.prototype.drawRangeBarPointer = function (axis, axisIndex, index, parentElement, gauge) {\n var pointer = axis.pointers[index];\n pointer.pathElement.push(appendPath(new PathOption(gauge.element.id + '_Axis_' + axisIndex + '_Pointer_RangeBar_' + index, pointer.color, pointer.border.width, pointer.border.color, 1, '0', ''), parentElement, gauge));\n };\n /**\n * Method to perform the animation of the pointer in circular gauge.\n * @return {void}\n */\n PointerRenderer.prototype.doPointerAnimation = function (pointer, axis) {\n var _this = this;\n var startValue = axis.visibleRange.min;\n var endValue = pointer.currentValue;\n if (pointer.animation.enable && startValue !== endValue && this.gauge.animatePointer) {\n pointer.pathElement.map(function (element) {\n if (pointer.type === 'RangeBar') {\n _this.performRangeBarAnimation(element, startValue, endValue, axis, pointer, pointer.currentRadius, (pointer.currentRadius - pointer.pointerWidth));\n }\n else {\n _this.performNeedleAnimation(element, startValue, endValue, axis, pointer, pointer.currentRadius, (pointer.currentRadius - pointer.pointerWidth));\n }\n });\n }\n };\n /**\n * Perform the needle and marker pointer animation for circular gauge.\n * @return {void}\n * @private\n */\n PointerRenderer.prototype.performNeedleAnimation = function (element, start, end, axis, pointer, radius, innerRadius) {\n var _this = this;\n var isClockWise = axis.direction === 'ClockWise';\n var startAngle = getAngleFromValue(start, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var pointAngle = getAngleFromValue(end, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var endAngle = startAngle > pointAngle ? (pointAngle + 360) : pointAngle;\n var sweepAngle;\n new Animation({}).animate(element, {\n duration: pointer.animation.duration,\n progress: function (args) {\n sweepAngle = (start < end || Math.round(startAngle) === Math.round(endAngle)) ?\n isClockWise ? (endAngle - startAngle) : (endAngle - startAngle - 360) :\n isClockWise ? (endAngle - startAngle - 360) : (endAngle - startAngle);\n element.style.animation = 'None';\n element.setAttribute('transform', 'rotate(' + linear(args.timeStamp, startAngle, sweepAngle, args.duration) + ',' +\n _this.gauge.midPoint.x.toString() + ',' + _this.gauge.midPoint.y.toString() + ')');\n },\n end: function (model) {\n _this.setPointerValue(axis, pointer, end);\n if (pointer.type === 'Marker' || (element.id.indexOf('_Pointer_NeedleCap') >= 0)) {\n _this.gauge.trigger(animationComplete, { axis: axis, pointer: pointer });\n }\n }\n });\n };\n /**\n * Perform the range bar pointer animation for circular gauge.\n * @return {void}\n * @private\n */\n PointerRenderer.prototype.performRangeBarAnimation = function (element, start, end, axis, pointer, radius, innerRadius) {\n var _this = this;\n var isClockWise = axis.direction === 'ClockWise';\n var startAngle = getAngleFromValue(start, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var minAngle = getAngleFromValue(axis.visibleRange.min, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var pointAngle = getAngleFromValue(end, axis.visibleRange.max, axis.visibleRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var sweepAngle;\n var endAngle = startAngle > pointAngle ? (pointAngle + 360) : pointAngle;\n new Animation({}).animate(element, {\n duration: pointer.animation.duration,\n progress: function (arg) {\n element.style.animation = 'None';\n sweepAngle = (start < end || Math.round(startAngle) === Math.round(endAngle)) ?\n isClockWise ? (endAngle - startAngle) : (endAngle - startAngle - 360) :\n isClockWise ? (endAngle - startAngle - 360) : (endAngle - startAngle);\n if (isClockWise) {\n element.setAttribute('d', getCompleteArc(_this.gauge.midPoint, minAngle, linear(arg.timeStamp, startAngle, sweepAngle, arg.duration) + 0.0001, radius, innerRadius));\n }\n else {\n element.setAttribute('d', getCompleteArc(_this.gauge.midPoint, linear(arg.timeStamp, startAngle, sweepAngle, arg.duration), minAngle + 0.0001, radius, innerRadius));\n }\n },\n end: function (model) {\n _this.setPointerValue(axis, pointer, end);\n _this.gauge.trigger(animationComplete, { axis: axis, pointer: pointer });\n }\n });\n };\n return PointerRenderer;\n}());\nexport { PointerRenderer };\n","import { createElement } from '@syncfusion/ej2-base';\nimport { calculateSum, VisibleLabels, measureText } from '../utils/helper';\nimport { Size, Rect, stringToNumber, getLabelFormat } from '../utils/helper';\nimport { axisLabelRender } from '../model/constants';\nimport { AxisRenderer } from './axis-renderer';\nimport { PointerRenderer } from './pointer-renderer';\n/**\n * Specifies the CircularGauge Axis Layout\n */\nvar labelPadding = 10;\nvar AxisLayoutPanel = /** @class */ (function () {\n function AxisLayoutPanel(gauge) {\n this.gauge = gauge;\n this.axisRenderer = new AxisRenderer(gauge);\n this.pointerRenderer = new PointerRenderer(gauge);\n }\n /**\n * Measure the calculate the axis size and radius.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.measureAxis = function (rect) {\n this.measureAxisSize(this.gauge, rect);\n this.calculateAxesRadius();\n };\n /**\n * Measure to calculate the axis radius of the circular gauge.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.calculateAxesRadius = function () {\n var totalRadius;\n var currentRadius;\n var rangeMaximumRadius = 0;\n for (var _i = 0, _a = this.gauge.axes; _i < _a.length; _i++) {\n var axis = _a[_i];\n totalRadius = (Math.min(axis.rect.width, axis.rect.height) / 2);\n currentRadius = axis.radius != null ? stringToNumber(axis.radius, totalRadius) : totalRadius;\n rangeMaximumRadius = Math.max.apply(Math, axis.ranges.map(function (value) {\n return value.radius ?\n (value.radius.indexOf('%') < 0 ? 100 : parseInt(value.radius, 10)) : 0;\n }));\n currentRadius = (rangeMaximumRadius > 100 && axis.radius == null) ?\n (currentRadius * 100) / rangeMaximumRadius : currentRadius;\n axis.currentRadius = currentRadius - axis.nearSize;\n axis.visibleRange.interval = this.calculateNumericInterval(axis, axis.rect);\n this.calculateVisibleLabels(axis);\n }\n };\n /**\n * Measure to calculate the axis size.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.measureAxisSize = function (gauge, rect) {\n var _this = this;\n var sum;\n this.computeSize(gauge.axes, rect);\n gauge.axes.map(function (axis, index) {\n sum = calculateSum(index, _this.farSizes.length - 1, _this.farSizes);\n axis.rect = new Rect(rect.x + sum, rect.y + sum, rect.width - (sum * 2), rect.height - (sum * 2));\n });\n };\n /**\n * Calculate the axis values of the circular gauge.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.calculateAxisValues = function (rect) {\n for (var _i = 0, _a = this.gauge.axes; _i < _a.length; _i++) {\n var axis = _a[_i];\n this.calculateVisibleRange(axis, rect);\n this.calculateVisibleLabels(axis);\n }\n };\n /**\n * Calculate the visible range of an axis.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.calculateVisibleRange = function (axis, rect) {\n var interval = axis.majorTicks.interval;\n var minimumValue = Math.min(axis.minimum === null ? 0 : axis.minimum, axis.maximum);\n var maximumValue = Math.max(axis.minimum, axis.maximum === null ? 100 : axis.maximum);\n axis.pointers.map(function (pointer) {\n pointer.currentValue = pointer.value !== null ?\n pointer.value < minimumValue ? minimumValue : pointer.value > maximumValue ? maximumValue : pointer.value\n : minimumValue;\n minimumValue = axis.minimum === null ? Math.min(pointer.currentValue, minimumValue) : minimumValue;\n maximumValue = axis.maximum === null ? Math.max(pointer.currentValue, maximumValue) : maximumValue;\n });\n minimumValue = (minimumValue === maximumValue) ?\n (interval !== null ? minimumValue - interval : minimumValue - 1) : minimumValue;\n axis.visibleRange = { min: minimumValue, max: maximumValue, interval: interval };\n axis.visibleRange.interval = this.calculateNumericInterval(axis, rect);\n };\n /**\n * Calculate the numeric intervals of an axis range.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.calculateNumericInterval = function (axis, rect) {\n if (axis.majorTicks.interval !== null) {\n return axis.majorTicks.interval;\n }\n var totalAngle = axis.endAngle - axis.startAngle;\n totalAngle = totalAngle <= 0 ? (totalAngle + 360) : totalAngle;\n return this.calculateNiceInterval(axis.visibleRange.max, axis.visibleRange.min, axis.currentRadius ? axis.currentRadius : (rect.width / 2), totalAngle);\n };\n /**\n * Calculate the nice interval of an axis range.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.calculateNiceInterval = function (maxValue, minValue, radius, degree) {\n var delta = maxValue - minValue;\n var circumference = 2 * Math.PI * radius * (degree / 360);\n var desiredIntervalsCount = Math.max((circumference * ((0.533 * 3) / 100)), 1);\n var niceInterval = delta / desiredIntervalsCount;\n var minInterval = Math.pow(10, Math.floor(Math.log(niceInterval) / Math.log(10)));\n for (var _i = 0, _a = [10, 5, 2, 1]; _i < _a.length; _i++) {\n var interval = _a[_i];\n var currentInterval = minInterval * interval;\n if (desiredIntervalsCount < (delta / currentInterval)) {\n break;\n }\n niceInterval = currentInterval;\n }\n return niceInterval;\n };\n /**\n * Calculate the visible labels of an axis.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.calculateVisibleLabels = function (axis) {\n var style = axis.labelStyle;\n var customLabelFormat = style.format && style.format.match('{value}') !== null;\n var format = this.gauge.intl.getNumberFormat({\n format: getLabelFormat(style.format), useGrouping: this.gauge.useGroupingSeparator\n });\n var argsData;\n axis.visibleLabels = [];\n for (var i = axis.visibleRange.min, interval = axis.visibleRange.interval, max = axis.visibleRange.max; (i <= max && interval); i += interval) {\n argsData = {\n cancel: false, name: axisLabelRender, axis: axis,\n text: customLabelFormat ? style.format.replace(new RegExp('{value}', 'g'), format(i)) :\n format(i),\n value: i\n };\n this.gauge.trigger(axisLabelRender, argsData);\n if (!argsData.cancel) {\n axis.visibleLabels.push(new VisibleLabels(argsData.text, i));\n }\n }\n this.getMaxLabelWidth(this.gauge, axis);\n };\n /**\n * Measure the axes available size.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.computeSize = function (axes, rect) {\n var lineSize;\n var outerHeight;\n var innerHeight;\n var isMajorTickOutside;\n var isMinorTickOutside;\n var isLabelOutside;\n var axisPadding = 5;\n var majorTickOffset = 0;\n var minorTickOffset = 0;\n var labelOffset = 0;\n this.farSizes = [];\n this.calculateAxisValues(rect);\n for (var _i = 0, axes_1 = axes; _i < axes_1.length; _i++) {\n var axis = axes_1[_i];\n lineSize = (axis.lineStyle.width / 2);\n outerHeight = 0;\n innerHeight = 0;\n isMajorTickOutside = axis.majorTicks.position === 'Outside';\n majorTickOffset = axis.majorTicks.offset;\n isMinorTickOutside = axis.minorTicks.position === 'Outside';\n minorTickOffset = axis.minorTicks.offset;\n isLabelOutside = axis.labelStyle.position === 'Outside';\n labelOffset = axis.labelStyle.offset;\n // Calculating the outer space of the axis\n outerHeight += !(isMajorTickOutside && isMinorTickOutside && isLabelOutside) ? axisPadding : 0;\n outerHeight += (isMajorTickOutside ? (axis.majorTicks.height + lineSize) : 0) +\n (isLabelOutside ? (axis.maxLabelSize.height + labelPadding + labelOffset) : 0) +\n ((isMinorTickOutside && !isMajorTickOutside) ? (axis.minorTicks.height + lineSize) : 0) + lineSize;\n outerHeight += (isMajorTickOutside && isMinorTickOutside) ? Math.max(majorTickOffset, minorTickOffset) :\n (isMajorTickOutside ? majorTickOffset : isMinorTickOutside ? minorTickOffset : 0);\n // Calculating the inner space of the axis\n innerHeight += (!isMajorTickOutside ? (axis.majorTicks.height + lineSize) : 0) +\n (!isLabelOutside ? (axis.maxLabelSize.height + labelPadding + labelOffset) : 0) +\n ((!isMinorTickOutside && isMajorTickOutside) ? (axis.minorTicks.height + lineSize) : 0) + lineSize;\n innerHeight += (!isMajorTickOutside && !isMinorTickOutside) ? Math.max(majorTickOffset, minorTickOffset) :\n (!isMajorTickOutside ? majorTickOffset : !isMinorTickOutside ? minorTickOffset : 0);\n if (this.farSizes[this.farSizes.length - 1]) {\n this.farSizes[this.farSizes.length - 1] += (innerHeight + outerHeight);\n }\n axis.nearSize = outerHeight - axisPadding;\n axis.farSize = innerHeight;\n outerHeight = (this.gauge.axes.length === (this.farSizes.length + 1)) ? 0 : outerHeight;\n this.farSizes.push(outerHeight);\n }\n };\n /**\n * To render the Axis element of the circular gauge.\n * @return {void}\n * @private\n */\n AxisLayoutPanel.prototype.renderAxes = function (animate) {\n var _this = this;\n if (animate === void 0) { animate = true; }\n var gauge = this.gauge;\n var renderer = this.axisRenderer;\n var element;\n var axesElements = gauge.renderer.createGroup({\n 'id': gauge.element.id + '_AxesCollection',\n 'clip-path': 'url(#' + gauge.element.id + '_GaugeAreaClipRect_' + ')'\n });\n // To append the secondary element for annotation and tooltip\n gauge.element.appendChild(createElement('div', {\n id: gauge.element.id + '_Secondary_Element',\n styles: 'position: relative'\n }));\n gauge.axes.map(function (axis, index) {\n element = gauge.renderer.createGroup({\n id: gauge.element.id + '_Axis_Group_' + index\n });\n renderer.drawAxisOuterLine(axis, index, element, gauge);\n renderer.drawAxisRange(axis, index, element, gauge);\n renderer.drawAxisLine(axis, index, element, gauge);\n renderer.drawMajorTickLines(axis, index, element, gauge);\n renderer.drawMinorTickLines(axis, index, element, gauge);\n renderer.drawAxisLabels(axis, index, element, gauge);\n _this.pointerRenderer.drawPointers(axis, index, element, gauge, animate);\n if (gauge.annotationsModule) {\n gauge.annotationsModule.renderAnnotation(axis, index);\n }\n axesElements.appendChild(element);\n });\n // For append clip rect for axes\n gauge.svgObject.appendChild(gauge.renderer.drawClipPath({\n 'id': gauge.element.id + '_GaugeAreaClipRect_',\n 'x': 0, 'y': 0,\n 'width': gauge.availableSize.width,\n 'height': gauge.availableSize.height,\n 'fill': 'transparent', 'stroke': 'transparent'\n }));\n gauge.svgObject.appendChild(axesElements);\n };\n /**\n * Calculate maximum label width for the axis.\n * @return {void}\n */\n AxisLayoutPanel.prototype.getMaxLabelWidth = function (gauge, axis) {\n axis.maxLabelSize = new Size(0, 0);\n for (var _i = 0, _a = axis.visibleLabels; _i < _a.length; _i++) {\n var label = _a[_i];\n label.size = measureText(label.text, axis.labelStyle.font);\n axis.maxLabelSize.width = label.size.width > axis.maxLabelSize.width ?\n label.size.width : axis.maxLabelSize.width;\n axis.maxLabelSize.height = label.size.height > axis.maxLabelSize.height ?\n label.size.height : axis.maxLabelSize.height;\n }\n };\n return AxisLayoutPanel;\n}());\nexport { AxisLayoutPanel };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n/**\n * Circular Gauge\n */\nimport { Property, NotifyPropertyChanges, Component, Complex, Browser } from '@syncfusion/ej2-base';\nimport { Event, SvgRenderer, EventHandler, Collection, Internationalization } from '@syncfusion/ej2-base';\nimport { remove } from '@syncfusion/ej2-base';\nimport { TextOption, textElement, RectOption, getAngleFromLocation, getValueFromAngle, removeElement } from './utils/helper';\nimport { Size, stringToNumber, measureText, Rect, GaugeLocation, getElement, getPointer, setStyles, toPixel } from './utils/helper';\nimport { getAngleFromValue, getPathArc } from './utils/helper';\nimport { Border, Margin, Font, TooltipSettings } from './model/base';\nimport { Axis } from './axes/axis';\nimport { Annotations } from './annotations/annotations';\nimport { GaugeTooltip } from './user-interaction/tooltip';\nimport { load, loaded, gaugeMouseMove, gaugeMouseLeave, gaugeMouseDown } from './model/constants';\nimport { gaugeMouseUp, dragEnd, dragMove, dragStart, resized } from './model/constants';\nimport { AxisLayoutPanel } from './axes/axis-panel';\n/**\n * Represents the Circular gauge control.\n * ```html\n *
\n * \n * ```\n */\nvar CircularGauge = /** @class */ (function (_super) {\n __extends(CircularGauge, _super);\n /**\n * Constructor for creating the widget\n * @hidden\n */\n function CircularGauge(options, element) {\n return _super.call(this, options, element) || this;\n }\n /**\n * To create svg object, renderer and binding events for the container.\n */\n CircularGauge.prototype.preRender = function () {\n this.unWireEvents();\n this.trigger(load, { gauge: this });\n this.themeEffect();\n this.initPrivateVariable();\n this.setCulture();\n this.createSvg();\n this.wireEvents();\n };\n CircularGauge.prototype.themeEffect = function () {\n if (this.theme === 'Highcontrast') {\n this.titleStyle.color = this.titleStyle.color || '#FFFFFF';\n this.setThemeColors('#FFFFFF', '#FFFFFF');\n }\n else {\n this.titleStyle.color = this.titleStyle.color || '#424242';\n this.setThemeColors('#212121', '#757575');\n }\n };\n CircularGauge.prototype.setThemeColors = function (labelcolor, others) {\n for (var _i = 0, _a = this.axes; _i < _a.length; _i++) {\n var axis = _a[_i];\n axis.lineStyle.color = axis.lineStyle.color || others;\n axis.labelStyle.font.color = axis.labelStyle.font.color || labelcolor;\n axis.majorTicks.color = axis.majorTicks.color || others;\n axis.minorTicks.color = axis.minorTicks.color || others;\n for (var _b = 0, _c = axis.pointers; _b < _c.length; _b++) {\n var pointer = _c[_b];\n pointer.color = pointer.color || others;\n pointer.needleTail.color = pointer.needleTail.color || others;\n pointer.needleTail.border.color = pointer.needleTail.border.color || others;\n pointer.cap.color = pointer.cap.color || others;\n pointer.cap.border.color = pointer.cap.border.color || others;\n }\n }\n };\n /**\n * To render the circular gauge elements\n */\n CircularGauge.prototype.render = function () {\n this.calculateBounds();\n this.renderElements();\n };\n /**\n * Method to unbind events for circular gauge\n */\n CircularGauge.prototype.unWireEvents = function () {\n EventHandler.remove(this.element, Browser.touchStartEvent, this.gaugeOnMouseDown);\n EventHandler.remove(this.element, Browser.touchMoveEvent, this.mouseMove);\n EventHandler.remove(this.element, Browser.touchEndEvent, this.mouseEnd);\n EventHandler.remove(this.element, 'contextmenu', this.gaugeRightClick);\n EventHandler.remove(this.element, (Browser.isPointer ? 'pointerleave' : 'mouseleave'), this.mouseLeave);\n window.removeEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.gaugeResize);\n };\n /**\n * Method to bind events for circular gauge\n */\n CircularGauge.prototype.wireEvents = function () {\n /*! Bind the Event handler */\n EventHandler.add(this.element, Browser.touchStartEvent, this.gaugeOnMouseDown, this);\n EventHandler.add(this.element, Browser.touchMoveEvent, this.mouseMove, this);\n EventHandler.add(this.element, Browser.touchEndEvent, this.mouseEnd, this);\n EventHandler.add(this.element, 'contextmenu', this.gaugeRightClick, this);\n EventHandler.add(this.element, (Browser.isPointer ? 'pointerleave' : 'mouseleave'), this.mouseLeave, this);\n window.addEventListener((Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.gaugeResize.bind(this));\n /*! Apply the style for circular gauge */\n this.setGaugeStyle(this.element);\n };\n /**\n * Handles the mouse move.\n * @return {boolean}\n * @private\n */\n CircularGauge.prototype.mouseMove = function (e) {\n var args = this.getMouseArgs(e, 'touchmove', gaugeMouseMove);\n this.trigger(gaugeMouseMove, args);\n var dragArgs;\n var tooltip = this.tooltipModule;\n if (!args.cancel) {\n if (this.tooltip.enable && tooltip) {\n if (args.target.id.indexOf('_Pointer_') >= 0 && !this.activePointer) {\n tooltip.renderTooltip(args.target);\n }\n else {\n tooltip.ejTooltip.close();\n }\n }\n if (this.enablePointerDrag && this.activePointer) {\n dragArgs = {\n axis: this.activeAxis,\n pointer: this.activePointer,\n previousValue: this.activePointer.currentValue,\n name: dragMove,\n currentValue: null\n };\n this.pointerDrag(new GaugeLocation(args.x, args.y));\n dragArgs.currentValue = this.activePointer.currentValue;\n this.trigger(dragMove, dragArgs);\n }\n }\n return false;\n };\n /**\n * Handles the mouse leave.\n * @return {boolean}\n * @private\n */\n CircularGauge.prototype.mouseLeave = function (e) {\n this.activeAxis = null;\n this.activePointer = null;\n this.svgObject.setAttribute('cursor', 'auto');\n var args = this.getMouseArgs(e, 'touchmove', gaugeMouseLeave);\n this.trigger(gaugeMouseLeave, args);\n if (this.tooltip.enable && this.tooltipModule) {\n this.tooltipModule.ejTooltip.close();\n }\n return false;\n };\n /**\n * Handles the mouse right click.\n * @return {boolean}\n * @private\n */\n CircularGauge.prototype.gaugeRightClick = function (event) {\n if (event.buttons === 2 || event.pointerType === 'touch') {\n event.preventDefault();\n event.stopPropagation();\n return false;\n }\n return true;\n };\n /**\n * Handles the pointer draf while mouse move on gauge.\n * @private\n */\n CircularGauge.prototype.pointerDrag = function (location) {\n var axis = this.activeAxis;\n var range = axis.visibleRange;\n var value = getValueFromAngle(getAngleFromLocation(this.midPoint, location), range.max, range.min, axis.startAngle, axis.endAngle, axis.direction === 'ClockWise');\n if (value >= range.min && value <= range.max) {\n this.activePointer.currentValue = value;\n this.activePointer.value = value;\n this.gaugeAxisLayoutPanel.pointerRenderer.setPointerValue(axis, this.activePointer, value);\n }\n };\n /**\n * Handles the mouse down on gauge.\n * @return {boolean}\n * @private\n */\n CircularGauge.prototype.gaugeOnMouseDown = function (e) {\n var currentPointer;\n var args = this.getMouseArgs(e, 'touchstart', gaugeMouseDown);\n this.trigger(gaugeMouseDown, args);\n if (!args.cancel && args.target.id.indexOf('_Pointer_') >= 0 &&\n args.target.id.indexOf(this.element.id + '_Axis_') >= 0) {\n currentPointer = getPointer(args.target.id, this);\n this.activeAxis = this.axes[currentPointer.axisIndex];\n this.activePointer = this.activeAxis.pointers[currentPointer.pointerIndex];\n this.trigger(dragStart, {\n axis: this.activeAxis,\n name: dragStart,\n pointer: this.activePointer,\n currentValue: this.activePointer.currentValue\n });\n this.svgObject.setAttribute('cursor', 'pointer');\n }\n return false;\n };\n /**\n * Handles the mouse end.\n * @return {boolean}\n * @private\n */\n CircularGauge.prototype.mouseEnd = function (e) {\n var args = this.getMouseArgs(e, 'touchend', gaugeMouseUp);\n var isTouch = e.pointerType === 'touch' || e.pointerType === '2' || e.type === 'touchend';\n var tooltipInterval;\n var tooltip = this.tooltipModule;\n this.trigger(gaugeMouseUp, args);\n if (this.activeAxis && this.activePointer) {\n this.trigger(dragEnd, {\n name: dragEnd,\n axis: this.activeAxis,\n pointer: this.activePointer,\n currentValue: this.activePointer.currentValue\n });\n if (!args.cancel && isTouch && this.tooltip.enable && tooltip) {\n if (args.target.id.indexOf('_Pointer_') >= 0) {\n tooltip.renderTooltip(args.target);\n tooltipInterval = window.setTimeout(function () {\n tooltip.ejTooltip.close();\n }, 2000);\n }\n }\n this.activeAxis = null;\n this.activePointer = null;\n }\n this.svgObject.setAttribute('cursor', 'auto');\n return false;\n };\n /**\n * Handles the mouse event arguments.\n * @return {IMouseEventArgs}\n * @private\n */\n CircularGauge.prototype.getMouseArgs = function (e, type, name) {\n var rect = this.element.getBoundingClientRect();\n var location = new GaugeLocation(-rect.left, -rect.top);\n var isTouch = (e.type === type);\n location.x += isTouch ? e.changedTouches[0].clientX : e.clientX;\n location.y += isTouch ? e.changedTouches[0].clientY : e.clientY;\n return {\n cancel: false, name: name,\n x: location.x, y: location.y,\n target: isTouch ? e.target : e.target\n };\n };\n /**\n * Handles the gauge resize.\n * @return {boolean}\n * @private\n */\n CircularGauge.prototype.gaugeResize = function (e) {\n var _this = this;\n var args = {\n gauge: this,\n previousSize: new Size(this.availableSize.width, this.availableSize.height),\n name: resized,\n currentSize: new Size(0, 0)\n };\n this.animatePointer = false;\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n if (this.element.classList.contains('e-circulargauge')) {\n this.resizeTo = window.setTimeout(function () {\n _this.createSvg();\n _this.calculateBounds();\n _this.renderElements();\n args.currentSize = _this.availableSize;\n _this.trigger(resized, args);\n }, 500);\n }\n return false;\n };\n /**\n * Applying styles for circular gauge elements\n */\n CircularGauge.prototype.setGaugeStyle = function (element) {\n element.style.touchAction = this.enablePointerDrag ? 'none' : 'element';\n element.style.msTouchAction = this.enablePointerDrag ? 'none' : 'element';\n element.style.msContentZooming = 'none';\n element.style.msUserSelect = 'none';\n element.style.webkitUserSelect = 'none';\n element.style.position = 'relative';\n };\n /**\n * Method to set culture for gauge\n */\n CircularGauge.prototype.setCulture = function () {\n this.intl = new Internationalization();\n };\n /**\n * Methods to create svg element for circular gauge.\n */\n CircularGauge.prototype.createSvg = function () {\n this.removeSvg();\n this.calculateSvgSize();\n this.svgObject = this.renderer.createSvg({\n id: this.element.id + '_svg',\n width: this.availableSize.width,\n height: this.availableSize.height\n });\n };\n /**\n * To Remove the SVG from circular gauge.\n * @return {boolean}\n * @private\n */\n CircularGauge.prototype.removeSvg = function () {\n removeElement(this.element.id + '_Secondary_Element');\n if (this.svgObject) {\n while (this.svgObject.childNodes.length > 0) {\n this.svgObject.removeChild(this.svgObject.firstChild);\n }\n if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) {\n remove(this.svgObject);\n }\n }\n };\n /**\n * To initialize the circular gauge private variable.\n * @private\n */\n CircularGauge.prototype.initPrivateVariable = function () {\n this.renderer = new SvgRenderer(this.element.id);\n this.gaugeAxisLayoutPanel = new AxisLayoutPanel(this);\n this.animatePointer = true;\n };\n /**\n * To calculate the size of the circular gauge element.\n */\n CircularGauge.prototype.calculateSvgSize = function () {\n var containerWidth = this.element.offsetWidth;\n var containerHeight = this.element.offsetHeight;\n var width = stringToNumber(this.width, containerWidth) || containerWidth || 600;\n var height = stringToNumber(this.height, containerHeight) || containerHeight || 450;\n this.availableSize = new Size(width, height);\n };\n /**\n * Method to calculate the availble size for circular gauge.\n */\n CircularGauge.prototype.calculateBounds = function () {\n var padding = 5;\n var margin = this.margin;\n // Title Height;\n var titleHeight = 0;\n if (this.title) {\n titleHeight = measureText(this.title, this.titleStyle).height + padding;\n }\n var top = margin.top + titleHeight + this.border.width;\n var left = margin.left + this.border.width;\n var width = this.availableSize.width - left - margin.right - this.border.width;\n var height = this.availableSize.height - top - this.border.width - margin.bottom;\n var radius = Math.min(width, height) / 2;\n var rect = new Rect((left + (width / 2) - radius), (top + (height / 2) - radius), radius * 2, radius * 2);\n var centerX = this.centerX !== null ?\n stringToNumber(this.centerX, this.availableSize.width) : rect.x + (rect.width / 2);\n var centerY = this.centerY !== null ?\n stringToNumber(this.centerY, this.availableSize.height) : rect.y + (rect.height / 2);\n this.midPoint = new GaugeLocation(centerX, centerY);\n this.gaugeAxisLayoutPanel.measureAxis(rect);\n };\n /**\n * To render elements for circular gauge\n */\n CircularGauge.prototype.renderElements = function (animate) {\n if (animate === void 0) { animate = true; }\n this.renderBorder();\n this.renderTitle();\n this.gaugeAxisLayoutPanel.renderAxes(animate);\n this.element.appendChild(this.svgObject);\n this.trigger(loaded, { gauge: this });\n };\n /**\n * Method to render the title for circular gauge.\n */\n CircularGauge.prototype.renderTitle = function () {\n if (this.title) {\n var size = measureText(this.title, this.titleStyle);\n var options = new TextOption(this.element.id + '_CircularGaugeTitle', this.availableSize.width / 2, this.margin.top + 3 * (size.height / 4), 'middle', this.title);\n var element = textElement(options, this.titleStyle, this.titleStyle.color, this.svgObject, '');\n element.setAttribute('aria-label', this.description || this.title);\n element.setAttribute('tabindex', this.tabIndex.toString());\n }\n };\n /**\n * Method to render the border for circular gauge.\n */\n CircularGauge.prototype.renderBorder = function () {\n var borderWidth = this.border.width;\n if (borderWidth > 0 || (this.background !== null && this.background !== 'transparent')) {\n this.svgObject.appendChild(this.renderer.drawRectangle(new RectOption(this.element.id + '_CircularGaugeBorder', this.background, this.border, null, new Rect(borderWidth / 2, borderWidth / 2, this.availableSize.width - borderWidth, this.availableSize.height - borderWidth))));\n }\n };\n /**\n * Method to set the pointer value dynamically for circular gauge.\n */\n CircularGauge.prototype.setPointerValue = function (axisIndex, pointerIndex, value) {\n var _this = this;\n var axis = this.axes[axisIndex];\n var pointer = axis.pointers[pointerIndex];\n var pointerRadius = pointer.currentRadius;\n var enableAnimation = pointer.animation.enable;\n value = value < axis.visibleRange.min ? axis.visibleRange.min : value;\n value = value > axis.visibleRange.max ? axis.visibleRange.max : value;\n pointer.pathElement.map(function (element) {\n if (pointer.type === 'RangeBar') {\n setStyles(element, pointer.color, pointer.border);\n if (enableAnimation) {\n _this.gaugeAxisLayoutPanel.pointerRenderer.performRangeBarAnimation(element, pointer.currentValue, value, axis, pointer, pointerRadius, (pointerRadius - pointer.pointerWidth));\n }\n else {\n _this.gaugeAxisLayoutPanel.pointerRenderer.setPointerValue(axis, pointer, value);\n }\n }\n else {\n if (element.id.indexOf('_Pointer_NeedleCap_') >= 0) {\n setStyles(element, pointer.cap.color, pointer.cap.border);\n }\n else if (element.id.indexOf('_Pointer_NeedleTail_') >= 0) {\n setStyles(element, pointer.needleTail.color, pointer.needleTail.border);\n }\n else if (element.id.indexOf('_Pointer_NeedleRect_') >= 0) {\n setStyles(element, 'transparent', { color: 'transparent', width: 0 });\n }\n else {\n setStyles(element, pointer.color, pointer.border);\n }\n if (enableAnimation) {\n _this.gaugeAxisLayoutPanel.pointerRenderer.performNeedleAnimation(element, pointer.currentValue, value, axis, pointer, pointerRadius, (pointerRadius - pointer.pointerWidth));\n }\n else {\n _this.gaugeAxisLayoutPanel.pointerRenderer.setPointerValue(axis, pointer, value);\n }\n }\n });\n pointer.currentValue = value;\n pointer.value = value;\n };\n /**\n * Method to set the annotation content dynamically for circular gauge.\n */\n CircularGauge.prototype.setAnnotationValue = function (axisIndex, annotationIndex, content) {\n var isElementExist = getElement(this.element.id + '_Annotations_' + axisIndex) !== null;\n var element = getElement(this.element.id + '_Annotations_' + axisIndex) ||\n this.createElement('div', {\n id: this.element.id + '_Annotations_' + axisIndex\n });\n var annotation = this.axes[axisIndex].annotations[annotationIndex];\n if (content !== null) {\n removeElement(this.element.id + '_Axis_' + axisIndex + '_Annotation_' + annotationIndex);\n annotation.content = content;\n this.annotationsModule.createTemplate(element, annotationIndex, axisIndex);\n if (!isElementExist) {\n getElement(this.element.id + '_Secondary_Element').appendChild(element);\n }\n }\n };\n /**\n * Method to set the range values dynamically for circular gauge.\n */\n CircularGauge.prototype.setRangeValue = function (axisIndex, rangeIndex, start, end) {\n var element = getElement(this.element.id + '_Axis_' + axisIndex + '_Range_' + rangeIndex);\n var axis = this.axes[axisIndex];\n var range = axis.ranges[rangeIndex];\n var axisRange = axis.visibleRange;\n var isClockWise = axis.direction === 'ClockWise';\n var startValue = Math.min(Math.max(start, axisRange.min), end);\n var endValue = Math.min(Math.max(start, end), axisRange.max);\n var startAngle = getAngleFromValue(startValue, axisRange.max, axisRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var endAngle = getAngleFromValue(endValue, axisRange.max, axisRange.min, axis.startAngle, axis.endAngle, isClockWise);\n var startWidth;\n if (range.startWidth.length > 0) {\n startWidth = toPixel(range.startWidth, range.currentRadius);\n }\n else {\n startWidth = range.startWidth;\n }\n var endWidth;\n if (range.endWidth.length > 0) {\n endWidth = toPixel(range.endWidth, range.currentRadius);\n }\n else {\n endWidth = range.endWidth;\n }\n endAngle = isClockWise ? endAngle : [startAngle, startAngle = endAngle][0];\n endWidth = isClockWise ? endWidth : [startWidth, startWidth = endWidth][0];\n element.setAttribute('d', getPathArc(this.midPoint, Math.round(startAngle), Math.round(endAngle), range.currentRadius, startWidth, endWidth));\n setStyles(element, (range.color ? range.color : range.rangeColor), {\n color: (range.color ? range.color : range.rangeColor),\n width: 0\n });\n };\n /**\n * To destroy the widget\n * @method destroy\n * @return {void}\n * @member of Circular-Gauge\n */\n CircularGauge.prototype.destroy = function () {\n this.unWireEvents();\n this.removeSvg();\n _super.prototype.destroy.call(this);\n };\n /**\n * To provide the array of modules needed for control rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n CircularGauge.prototype.requiredModules = function () {\n var modules = [];\n var annotationEnable = false;\n var axes = this.axes;\n axes.map(function (axis) {\n axis.annotations.map(function (annotation) {\n annotationEnable = annotationEnable || annotation.content !== null;\n });\n });\n if (annotationEnable) {\n modules.push({\n member: 'Annotations',\n args: [this, Annotations]\n });\n }\n if (this.tooltip.enable) {\n modules.push({\n member: 'Tooltip',\n args: [this, GaugeTooltip]\n });\n }\n return modules;\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n CircularGauge.prototype.getPersistData = function () {\n return this.addOnPersist([]);\n };\n /**\n * Called internally if any of the property value changed.\n * @private\n */\n CircularGauge.prototype.onPropertyChanged = function (newProp, oldProp) {\n // property method calculated\n var renderer = false;\n var refreshBounds = false;\n var refreshWithoutAnimation = false;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'height':\n case 'width':\n case 'centerX':\n case 'centerY':\n case 'margin':\n this.createSvg();\n refreshBounds = true;\n break;\n case 'title':\n refreshBounds = (newProp.title === '' || oldProp.title === '');\n renderer = !(newProp.title === '' || oldProp.title === '');\n break;\n case 'titleStyle':\n if (newProp.titleStyle && newProp.titleStyle.size) {\n refreshBounds = true;\n }\n else {\n renderer = true;\n }\n break;\n case 'border':\n renderer = true;\n break;\n case 'background':\n renderer = true;\n break;\n case 'axes':\n refreshWithoutAnimation = true;\n break;\n }\n }\n if (!refreshBounds && renderer) {\n this.removeSvg();\n this.renderElements();\n }\n if (refreshBounds) {\n this.removeSvg();\n this.calculateBounds();\n this.renderElements();\n }\n if (refreshWithoutAnimation && !renderer && !refreshBounds) {\n this.removeSvg();\n this.calculateBounds();\n this.renderElements(false);\n }\n };\n /**\n * Get component name for circular gauge\n * @private\n */\n CircularGauge.prototype.getModuleName = function () {\n return 'circulargauge';\n };\n __decorate([\n Property(null)\n ], CircularGauge.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], CircularGauge.prototype, \"height\", void 0);\n __decorate([\n Complex({ color: 'transparent', width: 0 }, Border)\n ], CircularGauge.prototype, \"border\", void 0);\n __decorate([\n Property('transparent')\n ], CircularGauge.prototype, \"background\", void 0);\n __decorate([\n Property('')\n ], CircularGauge.prototype, \"title\", void 0);\n __decorate([\n Complex({ size: '15px', color: null }, Font)\n ], CircularGauge.prototype, \"titleStyle\", void 0);\n __decorate([\n Complex({}, Margin)\n ], CircularGauge.prototype, \"margin\", void 0);\n __decorate([\n Collection([{}], Axis)\n ], CircularGauge.prototype, \"axes\", void 0);\n __decorate([\n Complex({}, TooltipSettings)\n ], CircularGauge.prototype, \"tooltip\", void 0);\n __decorate([\n Property(false)\n ], CircularGauge.prototype, \"enablePointerDrag\", void 0);\n __decorate([\n Property(null)\n ], CircularGauge.prototype, \"centerX\", void 0);\n __decorate([\n Property(null)\n ], CircularGauge.prototype, \"centerY\", void 0);\n __decorate([\n Property('Material')\n ], CircularGauge.prototype, \"theme\", void 0);\n __decorate([\n Property(false)\n ], CircularGauge.prototype, \"useGroupingSeparator\", void 0);\n __decorate([\n Property(null)\n ], CircularGauge.prototype, \"description\", void 0);\n __decorate([\n Property(1)\n ], CircularGauge.prototype, \"tabIndex\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"loaded\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"load\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"animationComplete\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"axisLabelRender\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"annotationRender\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"tooltipRender\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"dragStart\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"dragMove\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"dragEnd\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"gaugeMouseMove\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"gaugeMouseLeave\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"gaugeMouseDown\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"gaugeMouseUp\", void 0);\n __decorate([\n Event()\n ], CircularGauge.prototype, \"resized\", void 0);\n CircularGauge = __decorate([\n NotifyPropertyChanges\n ], CircularGauge);\n return CircularGauge;\n}(Component));\nexport { CircularGauge };\n","import * as index from '@syncfusion/ej2-circulargauge';\nindex.CircularGauge.Inject( index.GaugeTooltip,index.Annotations);\nexport * from '@syncfusion/ej2-circulargauge';\n","/**\n * Size defines and processes the size(width/height) of the objects\n */\nvar Size = /** @class */ (function () {\n function Size(width, height) {\n this.width = width;\n this.height = height;\n }\n Size.prototype.isEmpty = function () {\n return this.height === 0 && this.width === 0;\n };\n // public static get empty(): Size {\n // return new Size();\n // }\n // public get isEmpty(): boolean {\n // return this.equals(Size.empty);\n // }\n // public equals(size2: Size): boolean {\n // return this.width === size2.width && this.height === size2.height;\n // }\n // public union(size: Size): void {\n // size.width = Math.max(size.width, this.width);\n // size.height = Math.max(size.height, this.height);\n // }\n Size.prototype.clone = function () {\n return new Size(this.width, this.height);\n };\n return Size;\n}());\nexport { Size };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty } from '@syncfusion/ej2-base';\n/**\n * Defines and processes coordinates\n */\nvar Point = /** @class */ (function (_super) {\n __extends(Point, _super);\n function Point() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Point.equals = function (point1, point2) {\n if (point1 === point2) {\n return true;\n }\n if (!point1 || !point2) {\n return false;\n }\n return !point1 || !point2 || point1.x === point2.x && point1.y === point2.y;\n };\n /**\n * check whether the points are given\n */\n Point.isEmptyPoint = function (point) {\n if (point.x && point.y) {\n return false;\n }\n return true;\n };\n // public add(point1: PointModel, point2: PointModel): PointModel {\n // return { x: point1.x + point2.x, y: point1.y + point2.y };\n // }\n // public subtract(point1: PointModel, point2: PointModel): PointModel {\n // return { x: point1.x - point2.x, y: point1.y - point2.y };\n // }\n // public multiply(point1: PointModel, point2: PointModel): PointModel {\n // return {\n // x: point1.x * point2.x, y: point1.y * point2.y\n // };\n // }\n // public crossProduct(point1: PointModel, point2: PointModel): PointModel {\n // return {\n // x: point1.x * point2.y, y: point2.x * point1.y\n // };\n // }\n // public offset(offsetX: number, offsetY: number): void {\n // this.x += offsetX;\n // this.y += offsetY;\n // }\n // public rotate(angle: number): PointModel {\n // let c: number = Math.cos(angle);\n // let s: number = Math.sin(angle);\n // return {\n // x: c * this.x - s * this.y, y: s * this.x + c * this.y\n // };\n // }\n // public distance(point2: PointModel): number {\n // return Math.sqrt(Math.pow(this.x - point2.x, 2) + Math.pow(this.y - point2.y, 2));\n // }\n Point.transform = function (point, angle, length) {\n var pt = { x: 0, y: 0 };\n pt.x = Math.round((point.x + length * Math.cos(angle * Math.PI / 180)) * 100) / 100;\n pt.y = Math.round((point.y + length * Math.sin(angle * Math.PI / 180)) * 100) / 100;\n return pt;\n };\n Point.findLength = function (s, e) {\n var length = Math.sqrt(Math.pow((s.x - e.x), 2) + Math.pow((s.y - e.y), 2));\n return length;\n };\n Point.findAngle = function (point1, point2) {\n var angle = Math.atan2(point2.y - point1.y, point2.x - point1.x);\n angle = (180 * angle / Math.PI);\n angle %= 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n };\n Point.distancePoints = function (pt1, pt2) {\n return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));\n };\n Point.adjustPoint = function (source, target, isStart, length) {\n var pt = isStart ? { x: source.x, y: source.y } : { x: target.x, y: target.y };\n var angle;\n if (source.x === target.x) {\n if (source.y < target.y && isStart || source.y > target.y && !isStart) {\n pt.y += length;\n }\n else {\n pt.y -= length;\n }\n }\n else if (source.y === target.y) {\n if (source.x < target.x && isStart || source.x > target.x && !isStart) {\n pt.x += length;\n }\n else {\n pt.x -= length;\n }\n }\n else {\n if (isStart) {\n angle = this.findAngle(source, target);\n pt = this.transform(source, angle, length);\n }\n else {\n angle = this.findAngle(target, source);\n pt = this.transform(target, angle, length);\n }\n }\n return pt;\n };\n Point.direction = function (pt1, pt2) {\n if (Math.abs(pt2.x - pt1.x) > Math.abs(pt2.y - pt1.y)) {\n return pt1.x < pt2.x ? 'Right' : 'Left';\n }\n else {\n return pt1.y < pt2.y ? 'Bottom' : 'Top';\n }\n };\n __decorate([\n Property(0)\n ], Point.prototype, \"x\", void 0);\n __decorate([\n Property(0)\n ], Point.prototype, \"y\", void 0);\n return Point;\n}(ChildProperty));\nexport { Point };\n","/**\n * Rect defines and processes rectangular regions\n */\nvar Rect = /** @class */ (function () {\n function Rect(x, y, width, height) {\n /**\n * Sets the x-coordinate of the starting point of a rectangular region\n * @default 0\n */\n this.x = Number.MAX_VALUE;\n /**\n * Sets the y-coordinate of the starting point of a rectangular region\n * @default 0\n */\n this.y = Number.MAX_VALUE;\n /**\n * Sets the width of a rectangular region\n * @default 0\n */\n this.width = 0;\n /**\n * Sets the height of a rectangular region\n * @default 0\n */\n this.height = 0;\n if (x === undefined || y === undefined) {\n x = y = Number.MAX_VALUE;\n width = height = 0;\n }\n else {\n if (width === undefined) {\n width = 0;\n }\n if (height === undefined) {\n height = 0;\n }\n }\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n Object.defineProperty(Rect.prototype, \"left\", {\n get: function () {\n return this.x;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"right\", {\n get: function () {\n return this.x + this.width;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"top\", {\n get: function () {\n return this.y;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"bottom\", {\n get: function () {\n return this.y + this.height;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"topLeft\", {\n get: function () {\n return { x: this.left, y: this.top };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"topRight\", {\n get: function () {\n return { x: this.right, y: this.top };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"bottomLeft\", {\n get: function () {\n return { x: this.left, y: this.bottom };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"bottomRight\", {\n get: function () {\n return { x: this.right, y: this.bottom };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"middleLeft\", {\n get: function () {\n return { x: this.left, y: this.y + this.height / 2 };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"middleRight\", {\n get: function () {\n return { x: this.right, y: this.y + this.height / 2 };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"topCenter\", {\n get: function () {\n return { x: this.x + this.width / 2, y: this.top };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"bottomCenter\", {\n get: function () {\n return { x: this.x + this.width / 2, y: this.bottom };\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"center\", {\n get: function () {\n return { x: this.x + this.width / 2, y: this.y + this.height / 2 };\n },\n enumerable: true,\n configurable: true\n });\n Rect.prototype.equals = function (rect1, rect2) {\n return rect1.x === rect2.x && rect1.y === rect2.y && rect1.width === rect2.width && rect1.height === rect2.height;\n };\n Rect.prototype.uniteRect = function (rect) {\n var right = Math.max(Number.NaN === this.right || this.x === Number.MAX_VALUE ? rect.right : this.right, rect.right);\n var bottom = Math.max(Number.NaN === this.bottom || this.y === Number.MAX_VALUE ? rect.bottom : this.bottom, rect.bottom);\n this.x = Math.min(this.left, rect.left);\n this.y = Math.min(this.top, rect.top);\n this.width = right - this.x;\n this.height = bottom - this.y;\n return this;\n };\n Rect.prototype.unitePoint = function (point) {\n if (this.x === Number.MAX_VALUE) {\n this.x = point.x;\n this.y = point.y;\n return;\n }\n var x = Math.min(this.left, point.x);\n var y = Math.min(this.top, point.y);\n var right = Math.max(this.right, point.x);\n var bottom = Math.max(this.bottom, point.y);\n this.x = x;\n this.y = y;\n this.width = right - this.x;\n this.height = bottom - this.y;\n };\n // public intersection(rect: Rect): Rect {\n // if (this.intersects(rect)) {\n // let left: number = Math.max(this.left, rect.left);\n // let top: number = Math.max(this.top, rect.top);\n // let right: number = Math.min(this.right, rect.right);\n // let bottom: number = Math.min(this.bottom, rect.bottom);\n // return new Rect(left, top, right - left, bottom - top);\n // }\n // return Rect.empty;\n // }\n Rect.prototype.Inflate = function (padding) {\n this.x -= padding;\n this.y -= padding;\n this.width += padding * 2;\n this.height += padding * 2;\n return this;\n };\n //public Inflate(size: Size): Rect {\n // this.x -= size.Width;\n // this.y -= size.Height;\n // this.width += size.Width * 2;\n // this.height += size.Height * 2;\n // return this;\n //}\n // public inflate(width: number, height: number): void {\n // this.x -= width;\n // this.y -= height;\n // this.width += width * 2;\n // this.height += height * 2;\n // }\n Rect.prototype.intersects = function (rect) {\n if (this.right < rect.left || this.left > rect.right || this.top > rect.bottom || this.bottom < rect.top) {\n return false;\n }\n return true;\n };\n Rect.prototype.containsRect = function (rect) {\n return this.left <= rect.left && this.right >= rect.right && this.top <= rect.top && this.bottom >= rect.bottom;\n };\n Rect.prototype.containsPoint = function (point, padding) {\n if (padding === void 0) { padding = 0; }\n return this.left - padding <= point.x && this.right + padding >= point.x\n && this.top - padding <= point.y && this.bottom + padding >= point.y;\n };\n // public toPoints(): PointModel[] {\n // let points: PointModel[] = [];\n // points.push(this.topLeft);\n // points.push(this.topRight);\n // points.push(this.bottomLeft);\n // points.push(this.bottomRight);\n // return points;\n // }\n Rect.toBounds = function (points) {\n var rect = new Rect();\n for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {\n var pt = points_1[_i];\n rect.unitePoint(pt);\n }\n return rect;\n };\n Rect.empty = new Rect(Number.MAX_VALUE, Number.MIN_VALUE, 0, 0);\n return Rect;\n}());\nexport { Rect };\n","/**\n * enum module defines the public enumerations\n */\n/**\n * Constraints to define when a port has to be visible\n * Visible - Always shows the port\n * Hidden - Always hides the port\n * Hover - Shows the port when the mouse hovers over a node\n * Connect - Shows the port when a connection end point is dragged over a node\n * Default - By default the ports will be visible when a node is hovered and being tried to connect\n * @aspNumberEnum\n */\nexport var PortVisibility;\n(function (PortVisibility) {\n /** Always shows the port */\n PortVisibility[PortVisibility[\"Visible\"] = 1] = \"Visible\";\n /** Always hides the port */\n PortVisibility[PortVisibility[\"Hidden\"] = 2] = \"Hidden\";\n /** Shows the port when the mouse hovers over a node */\n PortVisibility[PortVisibility[\"Hover\"] = 4] = \"Hover\";\n /** Shows the port when a connection end point is dragged over a node */\n PortVisibility[PortVisibility[\"Connect\"] = 8] = \"Connect\";\n})(PortVisibility || (PortVisibility = {}));\n/**\n * Defines the constraints to Enables / Disables some features of Snapping.\n * None - Snapping does not happen\n * ShowHorizontalLines - Displays only the horizontal gridlines in diagram.\n * ShowVerticalLines - Displays only the Vertical gridlines in diagram.\n * ShowLines - Display both Horizontal and Vertical gridlines.\n * SnapToHorizontalLines - Enables the object to snap only with horizontal gridlines.\n * SnapToVerticalLines - Enables the object to snap only with horizontal gridlines.\n * SnapToLines - Enables the object to snap with both horizontal and Vertical gridlines.\n * snapToObject - Enables the object to snap with the other objects in the diagram.\n * @IgnoreSingular\n * @aspNumberEnum\n */\nexport var SnapConstraints;\n(function (SnapConstraints) {\n /** None - Snapping does not happen */\n SnapConstraints[SnapConstraints[\"None\"] = 0] = \"None\";\n /** ShowHorizontalLines - Displays only the horizontal gridlines in diagram. */\n SnapConstraints[SnapConstraints[\"ShowHorizontalLines\"] = 1] = \"ShowHorizontalLines\";\n /** ShowVerticalLines - Displays only the Vertical gridlines in diagram */\n SnapConstraints[SnapConstraints[\"ShowVerticalLines\"] = 2] = \"ShowVerticalLines\";\n /** ShowLines - Display both Horizontal and Vertical gridlines */\n SnapConstraints[SnapConstraints[\"ShowLines\"] = 3] = \"ShowLines\";\n /** SnapToHorizontalLines - Enables the object to snap only with horizontal gridlines */\n SnapConstraints[SnapConstraints[\"SnapToHorizontalLines\"] = 4] = \"SnapToHorizontalLines\";\n /** SnapToVerticalLines - Enables the object to snap only with horizontal gridlines */\n SnapConstraints[SnapConstraints[\"SnapToVerticalLines\"] = 8] = \"SnapToVerticalLines\";\n /** SnapToLines - Enables the object to snap with both horizontal and Vertical gridlines */\n SnapConstraints[SnapConstraints[\"SnapToLines\"] = 12] = \"SnapToLines\";\n /** SnapToObject - Enables the object to snap with the other objects in the diagram. */\n SnapConstraints[SnapConstraints[\"SnapToObject\"] = 16] = \"SnapToObject\";\n /** Shows gridlines and enables snapping */\n SnapConstraints[SnapConstraints[\"All\"] = 31] = \"All\";\n})(SnapConstraints || (SnapConstraints = {}));\n/**\n * Defines the visibility of the selector handles\n * None - Hides all the selector elements\n * ConnectorSourceThumb - Shows/hides the source thumb of the connector\n * ConnectorTargetThumb - Shows/hides the target thumb of the connector\n * ResizeSouthEast - Shows/hides the bottom right resize handle of the selector\n * ResizeSouthWest - Shows/hides the bottom left resize handle of the selector\n * ResizeNorthEast - Shows/hides the top right resize handle of the selector\n * ResizeNorthWest - Shows/hides the top left resize handle of the selector\n * ResizeEast - Shows/hides the middle right resize handle of the selector\n * ResizeWest - Shows/hides the middle left resize handle of the selector\n * ResizeSouth - Shows/hides the bottom center resize handle of the selector\n * ResizeNorth - Shows/hides the top center resize handle of the selector\n * Rotate - Shows/hides the rotate handle of the selector\n * UserHandles - Shows/hides the user handles of the selector\n * Resize - Shows/hides all resize handles of the selector\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var SelectorConstraints;\n(function (SelectorConstraints) {\n /** Hides all the selector elements */\n SelectorConstraints[SelectorConstraints[\"None\"] = 1] = \"None\";\n /** Shows/hides the source thumb of the connector */\n SelectorConstraints[SelectorConstraints[\"ConnectorSourceThumb\"] = 2] = \"ConnectorSourceThumb\";\n /** Shows/hides the target thumb of the connector */\n SelectorConstraints[SelectorConstraints[\"ConnectorTargetThumb\"] = 4] = \"ConnectorTargetThumb\";\n /** Shows/hides the bottom right resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeSouthEast\"] = 8] = \"ResizeSouthEast\";\n /** Shows/hides the bottom left resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeSouthWest\"] = 16] = \"ResizeSouthWest\";\n /** Shows/hides the top right resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeNorthEast\"] = 32] = \"ResizeNorthEast\";\n /** Shows/hides the top left resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeNorthWest\"] = 64] = \"ResizeNorthWest\";\n /** Shows/hides the middle right resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeEast\"] = 128] = \"ResizeEast\";\n /** Shows/hides the middle left resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeWest\"] = 256] = \"ResizeWest\";\n /** Shows/hides the bottom center resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeSouth\"] = 512] = \"ResizeSouth\";\n /** Shows/hides the top center resize handle of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeNorth\"] = 1024] = \"ResizeNorth\";\n /** Shows/hides the rotate handle of the selector */\n SelectorConstraints[SelectorConstraints[\"Rotate\"] = 2048] = \"Rotate\";\n /** Shows/hides the user handles of the selector */\n SelectorConstraints[SelectorConstraints[\"UserHandle\"] = 4096] = \"UserHandle\";\n /** Shows/hides the default tooltip of nodes and connectors */\n SelectorConstraints[SelectorConstraints[\"ToolTip\"] = 8192] = \"ToolTip\";\n /** Shows/hides all resize handles of the selector */\n SelectorConstraints[SelectorConstraints[\"ResizeAll\"] = 2046] = \"ResizeAll\";\n /** Shows all handles of the selector */\n SelectorConstraints[SelectorConstraints[\"All\"] = 16382] = \"All\";\n})(SelectorConstraints || (SelectorConstraints = {}));\n/**\n * Defines the constraints to enable/disable certain features of connector.\n * * None - Interaction of the connectors cannot be done.\n * * Select - Selects the connector.\n * * Delete - Delete the connector.\n * * Drag - Drag the connector.\n * * DragSourceEnd - Drag the source end of the connector.\n * * DragTargetEnd - Drag the target end of the connector.\n * * DragSegmentThump - Drag the segment thumb of the connector.\n * * AllowDrop - Allow to drop a node.\n * * Bridging - Creates bridge on intersection of two connectors.\n * * BridgeObstacle -\n * * InheritBridging - Creates bridge on intersection of two connectors.\n * * PointerEvents - Sets the pointer events.\n * * Tooltip - Displays a tooltip for the connectors.\n * * InheritToolTip - Displays a tooltip for the connectors.\n * * Interaction - Features of the connector used for interaction.\n * * ReadOnly - Enables ReadOnly\n * * Default - Default features of the connector.\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var ConnectorConstraints;\n(function (ConnectorConstraints) {\n /** Disable all connector Constraints. */\n ConnectorConstraints[ConnectorConstraints[\"None\"] = 1] = \"None\";\n /** Enables connector to be selected. */\n ConnectorConstraints[ConnectorConstraints[\"Select\"] = 2] = \"Select\";\n /** Enables connector to be Deleted. */\n ConnectorConstraints[ConnectorConstraints[\"Delete\"] = 4] = \"Delete\";\n /** Enables connector to be Dragged. */\n ConnectorConstraints[ConnectorConstraints[\"Drag\"] = 8] = \"Drag\";\n /** Enables connectors source end to be selected. */\n ConnectorConstraints[ConnectorConstraints[\"DragSourceEnd\"] = 16] = \"DragSourceEnd\";\n /** Enables connectors target end to be selected. */\n ConnectorConstraints[ConnectorConstraints[\"DragTargetEnd\"] = 32] = \"DragTargetEnd\";\n /** Enables control point and end point of every segment in a connector for editing. */\n ConnectorConstraints[ConnectorConstraints[\"DragSegmentThumb\"] = 64] = \"DragSegmentThumb\";\n /** Enables AllowDrop constraints to the connector. */\n ConnectorConstraints[ConnectorConstraints[\"AllowDrop\"] = 128] = \"AllowDrop\";\n /** Enables bridging to the connector. */\n ConnectorConstraints[ConnectorConstraints[\"Bridging\"] = 256] = \"Bridging\";\n /** Enables or Disables Bridge Obstacles with overlapping of connectors. */\n ConnectorConstraints[ConnectorConstraints[\"BridgeObstacle\"] = 512] = \"BridgeObstacle\";\n /** Enables bridging to the connector. */\n ConnectorConstraints[ConnectorConstraints[\"InheritBridging\"] = 1024] = \"InheritBridging\";\n /** Used to set the pointer events. */\n ConnectorConstraints[ConnectorConstraints[\"PointerEvents\"] = 2048] = \"PointerEvents\";\n /** Enables or disables tool tip for the connectors */\n ConnectorConstraints[ConnectorConstraints[\"Tooltip\"] = 4096] = \"Tooltip\";\n /** Enables or disables tool tip for the connectors */\n ConnectorConstraints[ConnectorConstraints[\"InheritTooltip\"] = 8192] = \"InheritTooltip\";\n /** Enables Interaction. */\n ConnectorConstraints[ConnectorConstraints[\"Interaction\"] = 4218] = \"Interaction\";\n /** Enables ReadOnly */\n ConnectorConstraints[ConnectorConstraints[\"ReadOnly\"] = 16384] = \"ReadOnly\";\n /** Enables all constraints. */\n ConnectorConstraints[ConnectorConstraints[\"Default\"] = 11838] = \"Default\";\n})(ConnectorConstraints || (ConnectorConstraints = {}));\n/**\n * Enables/Disables the annotation constraints\n * ReadOnly - Enables/Disables the ReadOnly Constraints\n * InheritReadOnly - Enables/Disables the InheritReadOnly Constraints\n * Default - Enables/Disables Default constraints\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var AnnotationConstraints;\n(function (AnnotationConstraints) {\n /** Enables/Disables the ReadOnly Constraints */\n AnnotationConstraints[AnnotationConstraints[\"ReadOnly\"] = 2] = \"ReadOnly\";\n /** Enables/Disables the InheritReadOnly Constraints */\n AnnotationConstraints[AnnotationConstraints[\"InheritReadOnly\"] = 4] = \"InheritReadOnly\";\n})(AnnotationConstraints || (AnnotationConstraints = {}));\n/**\n * Enables/Disables certain features of node\n * None - Disable all node Constraints\n * Select - Enables node to be selected\n * Drag - Enables node to be Dragged\n * Rotate - Enables node to be Rotate\n * Shadow - Enables node to display shadow\n * PointerEvents - Enables node to provide pointer option\n * Delete - Enables node to delete\n * InConnect - Enables node to provide in connect option\n * OutConnect - Enables node to provide out connect option\n * Individual - Enables node to provide individual resize option\n * Expandable - Enables node to provide Expandable option\n * AllowDrop - Enables node to provide allow to drop option\n * Inherit - Enables node to inherit the interaction option\n * ResizeNorthEast - Enable ResizeNorthEast of the node\n * ResizeEast - Enable ResizeEast of the node\n * ResizeSouthEast - Enable ResizeSouthEast of the node\n * ResizeSouth - Enable ResizeSouthWest of the node\n * ResizeSouthWest - Enable ResizeSouthWest of the node\n * ResizeSouth - Enable ResizeSouth of the node\n * ResizeSouthWest - Enable ResizeSouthWest of the node\n * ResizeWest - Enable ResizeWest of the node\n * ResizeNorth - Enable ResizeNorth of the node\n * Resize - Enables the Aspect ratio fo the node\n * AspectRatio - Enables the Aspect ratio fo the node\n * Tooltip - Enables or disables tool tip for the Nodes\n * InheritTooltip - Enables or disables tool tip for the Nodes\n * ReadOnly - Enables the ReadOnly support for Annotation\n * Default - Enables all constraints\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var NodeConstraints;\n(function (NodeConstraints) {\n /** Disable all node Constraints. */\n NodeConstraints[NodeConstraints[\"None\"] = 0] = \"None\";\n /** Enables node to be selected. */\n NodeConstraints[NodeConstraints[\"Select\"] = 2] = \"Select\";\n /** Enables node to be Dragged. */\n NodeConstraints[NodeConstraints[\"Drag\"] = 4] = \"Drag\";\n /** Enables node to be Rotate. */\n NodeConstraints[NodeConstraints[\"Rotate\"] = 8] = \"Rotate\";\n /** Enables node to display shadow. */\n NodeConstraints[NodeConstraints[\"Shadow\"] = 16] = \"Shadow\";\n /** Enables node to provide pointer option */\n NodeConstraints[NodeConstraints[\"PointerEvents\"] = 32] = \"PointerEvents\";\n /** Enables node to delete */\n NodeConstraints[NodeConstraints[\"Delete\"] = 64] = \"Delete\";\n /** Enables node to provide in connect option */\n NodeConstraints[NodeConstraints[\"InConnect\"] = 128] = \"InConnect\";\n /** Enables node to provide out connect option */\n NodeConstraints[NodeConstraints[\"OutConnect\"] = 256] = \"OutConnect\";\n /** Enables node to provide individual resize option */\n NodeConstraints[NodeConstraints[\"Individual\"] = 512] = \"Individual\";\n /** Enables node to provide Expandable option */\n NodeConstraints[NodeConstraints[\"Expandable\"] = 1024] = \"Expandable\";\n /** Enables node to provide allow to drop option */\n NodeConstraints[NodeConstraints[\"AllowDrop\"] = 2048] = \"AllowDrop\";\n /** Enables node to inherit the interaction option */\n NodeConstraints[NodeConstraints[\"Inherit\"] = 78] = \"Inherit\";\n /** Enable ResizeNorthEast of the node */\n NodeConstraints[NodeConstraints[\"ResizeNorthEast\"] = 4096] = \"ResizeNorthEast\";\n /** Enable ResizeEast of the node */\n NodeConstraints[NodeConstraints[\"ResizeEast\"] = 8192] = \"ResizeEast\";\n /** Enable ResizeSouthEast of the node */\n NodeConstraints[NodeConstraints[\"ResizeSouthEast\"] = 16384] = \"ResizeSouthEast\";\n /** Enable ResizeSouth of the node */\n NodeConstraints[NodeConstraints[\"ResizeSouth\"] = 32768] = \"ResizeSouth\";\n /** Enable ResizeSouthWest of the node */\n NodeConstraints[NodeConstraints[\"ResizeSouthWest\"] = 65536] = \"ResizeSouthWest\";\n /** Enable ResizeWest of the node */\n NodeConstraints[NodeConstraints[\"ResizeWest\"] = 131072] = \"ResizeWest\";\n /** Enable ResizeNorthWest of the node */\n NodeConstraints[NodeConstraints[\"ResizeNorthWest\"] = 262144] = \"ResizeNorthWest\";\n /** Enable ResizeNorth of the node */\n NodeConstraints[NodeConstraints[\"ResizeNorth\"] = 524288] = \"ResizeNorth\";\n /** Enable Resize of the node */\n NodeConstraints[NodeConstraints[\"Resize\"] = 1044480] = \"Resize\";\n /** Enables the Aspect ratio fo the node */\n NodeConstraints[NodeConstraints[\"AspectRatio\"] = 1048576] = \"AspectRatio\";\n /** Enables or disables tool tip for the Nodes */\n NodeConstraints[NodeConstraints[\"Tooltip\"] = 2097152] = \"Tooltip\";\n /** Enables or disables tool tip for the Nodes */\n NodeConstraints[NodeConstraints[\"InheritTooltip\"] = 4194304] = \"InheritTooltip\";\n /** Enables the ReadOnly support for Annotation */\n NodeConstraints[NodeConstraints[\"ReadOnly\"] = 8388608] = \"ReadOnly\";\n /** Enables all constraints */\n NodeConstraints[NodeConstraints[\"Default\"] = 5240814] = \"Default\";\n})(NodeConstraints || (NodeConstraints = {}));\n/** Enables/Disables the handles of the selector\n * Rotate - Enable Rotate Thumb\n * ConnectorSource - Enable Connector source point\n * ConnectorTarget - Enable Connector target point\n * ResizeNorthEast - Enable ResizeNorthEast Resize\n * ResizeEast - Enable ResizeEast Resize\n * ResizeSouthEast - Enable ResizeSouthEast Resize\n * ResizeSouth - Enable ResizeSouth Resize\n * ResizeSouthWest - Enable ResizeSouthWest Resize\n * ResizeWest - Enable ResizeWest Resize\n * ResizeNorthWest - Enable ResizeNorthWest Resize\n * ResizeNorth - Enable ResizeNorth Resize\n * Default - Enables all constraints\n * @private\n */\nexport var ThumbsConstraints;\n(function (ThumbsConstraints) {\n /** Enable Rotate Thumb */\n ThumbsConstraints[ThumbsConstraints[\"Rotate\"] = 2] = \"Rotate\";\n /** Enable Connector source point */\n ThumbsConstraints[ThumbsConstraints[\"ConnectorSource\"] = 4] = \"ConnectorSource\";\n /** Enable Connector target point */\n ThumbsConstraints[ThumbsConstraints[\"ConnectorTarget\"] = 8] = \"ConnectorTarget\";\n /** Enable ResizeNorthEast Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeNorthEast\"] = 16] = \"ResizeNorthEast\";\n /** Enable ResizeEast Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeEast\"] = 32] = \"ResizeEast\";\n /** Enable ResizeSouthEast Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeSouthEast\"] = 64] = \"ResizeSouthEast\";\n /** Enable ResizeSouth Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeSouth\"] = 128] = \"ResizeSouth\";\n /** Enable ResizeSouthWest Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeSouthWest\"] = 256] = \"ResizeSouthWest\";\n /** Enable ResizeWest Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeWest\"] = 512] = \"ResizeWest\";\n /** Enable ResizeNorthWest Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeNorthWest\"] = 1024] = \"ResizeNorthWest\";\n /** Enable ResizeNorth Resize */\n ThumbsConstraints[ThumbsConstraints[\"ResizeNorth\"] = 2048] = \"ResizeNorth\";\n /** Enables all constraints */\n ThumbsConstraints[ThumbsConstraints[\"Default\"] = 4094] = \"Default\";\n})(ThumbsConstraints || (ThumbsConstraints = {}));\n/**\n * Enables/Disables certain features of diagram\n * None - Disable DiagramConstraints constraints\n * Bridging - Enables/Disable Bridging support for connector\n * UndoRedo - Enables/Disable the Undo/Redo support\n * Tooltip - Enables/Disable Tooltip support\n * UserInteraction - Enables/Disable UserInteraction support for the diagram\n * ApiUpdate - Enables/Disable ApiUpdate support for the diagram\n * PageEditable - Enables/Disable PageEditable support for the diagram\n * Zoom - Enables/Disable Zoom support for the diagram\n * PanX - Enables/Disable PanX support for the diagram\n * PanY - Enables/Disable PanY support for the diagram\n * Pan - Enables/Disable Pan support the diagram\n * Default - Enables/Disable all constraints\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var DiagramConstraints;\n(function (DiagramConstraints) {\n /** Disable DiagramConstraints constraints */\n DiagramConstraints[DiagramConstraints[\"None\"] = 1] = \"None\";\n /** Enables/Disable Bridging support for connector */\n DiagramConstraints[DiagramConstraints[\"Bridging\"] = 2] = \"Bridging\";\n /** Enables/Disable the Undo/Redo support */\n DiagramConstraints[DiagramConstraints[\"UndoRedo\"] = 4] = \"UndoRedo\";\n /** Enables/Disable Tooltip support */\n DiagramConstraints[DiagramConstraints[\"Tooltip\"] = 8] = \"Tooltip\";\n /** Enables/Disable UserInteraction support for the diagram */\n DiagramConstraints[DiagramConstraints[\"UserInteraction\"] = 16] = \"UserInteraction\";\n /** Enables/Disable ApiUpdate support for the diagram */\n DiagramConstraints[DiagramConstraints[\"ApiUpdate\"] = 32] = \"ApiUpdate\";\n /** Enables/Disable PageEditable support for the diagram */\n DiagramConstraints[DiagramConstraints[\"PageEditable\"] = 48] = \"PageEditable\";\n /** Enables/Disable Zoom support for the diagram */\n DiagramConstraints[DiagramConstraints[\"Zoom\"] = 64] = \"Zoom\";\n /** Enables/Disable PanX support for the diagram */\n DiagramConstraints[DiagramConstraints[\"PanX\"] = 128] = \"PanX\";\n /** Enables/Disable PanY support for the diagram */\n DiagramConstraints[DiagramConstraints[\"PanY\"] = 256] = \"PanY\";\n /** Enables/Disable Pan support the diagram */\n DiagramConstraints[DiagramConstraints[\"Pan\"] = 384] = \"Pan\";\n /** Enables/Disable all constraints */\n DiagramConstraints[DiagramConstraints[\"Default\"] = 500] = \"Default\";\n})(DiagramConstraints || (DiagramConstraints = {}));\n/**\n * Activates the diagram tools\n * None - Enables/Disable single select support for the diagram\n * SingleSelect - Enables/Disable single select support for the diagram\n * MultipleSelect - Enables/Disable MultipleSelect select support for the diagram\n * ZoomPan - Enables/Disable ZoomPan support for the diagram\n * DrawOnce - Enables/Disable continuousDraw support for the diagram\n * continuousDraw - Enables/Disable continuousDraw support for the diagram\n * Default - Enables/Disable all constraints\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var DiagramTools;\n(function (DiagramTools) {\n /** Disable all constraints */\n DiagramTools[DiagramTools[\"None\"] = 0] = \"None\";\n /** Enables/Disable single select support for the diagram */\n DiagramTools[DiagramTools[\"SingleSelect\"] = 1] = \"SingleSelect\";\n /** Enables/Disable MultipleSelect select support for the diagram */\n DiagramTools[DiagramTools[\"MultipleSelect\"] = 2] = \"MultipleSelect\";\n /** Enables/Disable ZoomPan support for the diagram */\n DiagramTools[DiagramTools[\"ZoomPan\"] = 4] = \"ZoomPan\";\n /** Enables/Disable DrawOnce support for the diagram */\n DiagramTools[DiagramTools[\"DrawOnce\"] = 8] = \"DrawOnce\";\n /** Enables/Disable continuousDraw support for the diagram */\n DiagramTools[DiagramTools[\"ContinuousDraw\"] = 16] = \"ContinuousDraw\";\n /** Enables/Disable all constraints */\n DiagramTools[DiagramTools[\"Default\"] = 3] = \"Default\";\n})(DiagramTools || (DiagramTools = {}));\n/**\n * Defines the container/canvas transform\n * Self - Sets the transform type as Self\n * Parent - Sets the transform type as Parent\n */\nexport var Transform;\n(function (Transform) {\n /** Self - Sets the transform type as Self */\n Transform[Transform[\"Self\"] = 1] = \"Self\";\n /** Parent - Sets the transform type as Parent */\n Transform[Transform[\"Parent\"] = 2] = \"Parent\";\n})(Transform || (Transform = {}));\n/**\n * Defines the rendering mode for diagram\n * Canvas - Sets the rendering mode type as Canvas\n * Svg - Sets the rendering mode type as Svg\n */\nexport var RenderMode;\n(function (RenderMode) {\n /** Canvas - Sets the rendering mode type as Canvas */\n RenderMode[RenderMode[\"Canvas\"] = 0] = \"Canvas\";\n /** Svg - Sets the rendering mode type as Svg */\n RenderMode[RenderMode[\"Svg\"] = 1] = \"Svg\";\n})(RenderMode || (RenderMode = {}));\n/**\n * Sets a combination of key modifiers, on recognition of which the command will be executed.They are\n * * None - no modifiers are pressed\n * * Control - ctrl key\n * * Meta - meta key im mac\n * * Alt - alt key\n * * Shift - shift key\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var KeyModifiers;\n(function (KeyModifiers) {\n /** No modifiers are pressed */\n KeyModifiers[KeyModifiers[\"None\"] = 0] = \"None\";\n /** The CTRL key */\n KeyModifiers[KeyModifiers[\"Control\"] = 1] = \"Control\";\n /** The Meta key pressed in Mac */\n KeyModifiers[KeyModifiers[\"Meta\"] = 1] = \"Meta\";\n /** The ALT key */\n KeyModifiers[KeyModifiers[\"Alt\"] = 2] = \"Alt\";\n /** The Shift key */\n KeyModifiers[KeyModifiers[\"Shift\"] = 4] = \"Shift\";\n})(KeyModifiers || (KeyModifiers = {}));\n/**\n * Sets the key value, on recognition of which the command will be executed. They are\n * * none - no key\n * * Number0 = The 0 key\n * * Number1 = The 1 key\n * * Number2 = The 2 key\n * * Number3 = The 3 key\n * * Number4 = The 4 key\n * * Number5 = The 5 key\n * * Number6 = The 6 key\n * * Number7 = The 7 key\n * * Number8 = The 8 key\n * * Number9 = The 9 key\n * * Number0 = The 0 key\n * * BackSpace = The BackSpace key\n * * F1 = The f1 key\n * * F2 = The f2 key\n * * F3 = The f3 key\n * * F4 = The f4 key\n * * F5 = The f5 key\n * * F6 = The f6 key\n * * F7 = The f7 key\n * * F8 = The f8 key\n * * F9 = The f9 key\n * * F10 = The f10 key\n * * F11 = The f11 key\n * * F12 = The f12 key\n * * A = The a key\n * * B = The b key\n * * C = The c key\n * * D = The d key\n * * E = The e key\n * * F = The f key\n * * G = The g key\n * * H = The h key\n * * I = The i key\n * * J = The j key\n * * K = The k key\n * * L = The l key\n * * M = The m key\n * * N = The n key\n * * O = The o key\n * * P = The p key\n * * Q = The q key\n * * R = The r key\n * * S = The s key\n * * T = The t key\n * * U = The u key\n * * V = The v key\n * * W = The w key\n * * X = The x key\n * * Y = The y key\n * * Z = The z key\n * * Left = The left key\n * * Right = The right key\n * * Top = The top key\n * * Bottom = The bottom key\n * * Escape = The Escape key\n * * Tab = The tab key\n * * Delete = The delete key\n * * Enter = The enter key\n * * The Space key\n * * The page up key\n * * The page down key\n * * The end key\n * * The home key\n * * The Minus\n * * The Plus\n * * The Star\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var Keys;\n(function (Keys) {\n /** No key pressed */\n Keys[Keys[\"None\"] = null] = \"None\";\n /** The 0 key */\n Keys[Keys[\"Number0\"] = 0] = \"Number0\";\n /** The 1 key */\n Keys[Keys[\"Number1\"] = 1] = \"Number1\";\n /** The 2 key */\n Keys[Keys[\"Number2\"] = 2] = \"Number2\";\n /** The 3 key */\n Keys[Keys[\"Number3\"] = 3] = \"Number3\";\n /** The 4 key */\n Keys[Keys[\"Number4\"] = 4] = \"Number4\";\n /** The 5 key */\n Keys[Keys[\"Number5\"] = 5] = \"Number5\";\n /** The 6 key */\n Keys[Keys[\"Number6\"] = 6] = \"Number6\";\n /** The 7 key */\n Keys[Keys[\"Number7\"] = 7] = \"Number7\";\n /** The 8 key */\n Keys[Keys[\"Number8\"] = 8] = \"Number8\";\n /** The 9 key */\n Keys[Keys[\"Number9\"] = 9] = \"Number9\";\n /** The A key */\n Keys[Keys[\"A\"] = 65] = \"A\";\n /** The B key */\n Keys[Keys[\"B\"] = 66] = \"B\";\n /** The C key */\n Keys[Keys[\"C\"] = 67] = \"C\";\n /** The D key */\n Keys[Keys[\"D\"] = 68] = \"D\";\n /** The E key */\n Keys[Keys[\"E\"] = 69] = \"E\";\n /** The F key */\n Keys[Keys[\"F\"] = 70] = \"F\";\n /** The G key */\n Keys[Keys[\"G\"] = 71] = \"G\";\n /** The H key */\n Keys[Keys[\"H\"] = 72] = \"H\";\n /** The I key */\n Keys[Keys[\"I\"] = 73] = \"I\";\n /** The J key */\n Keys[Keys[\"J\"] = 74] = \"J\";\n /** The K key */\n Keys[Keys[\"K\"] = 75] = \"K\";\n /** The L key */\n Keys[Keys[\"L\"] = 76] = \"L\";\n /** The M key */\n Keys[Keys[\"M\"] = 77] = \"M\";\n /** The N key */\n Keys[Keys[\"N\"] = 78] = \"N\";\n /** The O key */\n Keys[Keys[\"O\"] = 79] = \"O\";\n /** The P key */\n Keys[Keys[\"P\"] = 80] = \"P\";\n /** The Q key */\n Keys[Keys[\"Q\"] = 81] = \"Q\";\n /** The R key */\n Keys[Keys[\"R\"] = 82] = \"R\";\n /** The S key */\n Keys[Keys[\"S\"] = 83] = \"S\";\n /** The T key */\n Keys[Keys[\"T\"] = 84] = \"T\";\n /** The U key */\n Keys[Keys[\"U\"] = 85] = \"U\";\n /** The V key */\n Keys[Keys[\"V\"] = 86] = \"V\";\n /** The W key */\n Keys[Keys[\"W\"] = 87] = \"W\";\n /** The X key */\n Keys[Keys[\"X\"] = 88] = \"X\";\n /** The Y key */\n Keys[Keys[\"Y\"] = 89] = \"Y\";\n /** The Z key */\n Keys[Keys[\"Z\"] = 90] = \"Z\";\n /** The left arrow key */\n Keys[Keys[\"Left\"] = 37] = \"Left\";\n /** The up arrow key */\n Keys[Keys[\"Up\"] = 38] = \"Up\";\n /** The right arrow key */\n Keys[Keys[\"Right\"] = 39] = \"Right\";\n /** The down arrow key */\n Keys[Keys[\"Down\"] = 40] = \"Down\";\n /** The Escape key */\n Keys[Keys[\"Escape\"] = 27] = \"Escape\";\n /** The Space key */\n Keys[Keys[\"Space\"] = 32] = \"Space\";\n /** The page up key */\n Keys[Keys[\"PageUp\"] = 33] = \"PageUp\";\n /** The Space key */\n Keys[Keys[\"PageDown\"] = 34] = \"PageDown\";\n /** The Space key */\n Keys[Keys[\"End\"] = 35] = \"End\";\n /** The Space key */\n Keys[Keys[\"Home\"] = 36] = \"Home\";\n /** The delete key */\n Keys[Keys[\"Delete\"] = 46] = \"Delete\";\n /** The tab key */\n Keys[Keys[\"Tab\"] = 9] = \"Tab\";\n /** The enter key */\n Keys[Keys[\"Enter\"] = 13] = \"Enter\";\n /** The BackSpace key */\n Keys[Keys[\"BackSpace\"] = 8] = \"BackSpace\";\n /** The F1 key */\n Keys[Keys[\"F1\"] = 112] = \"F1\";\n /** The F2 key */\n Keys[Keys[\"F2\"] = 113] = \"F2\";\n /** The F3 key */\n Keys[Keys[\"F3\"] = 114] = \"F3\";\n /** The F4 key */\n Keys[Keys[\"F4\"] = 115] = \"F4\";\n /** The F5 key */\n Keys[Keys[\"F5\"] = 116] = \"F5\";\n /** The F6 key */\n Keys[Keys[\"F6\"] = 117] = \"F6\";\n /** The F7 key */\n Keys[Keys[\"F7\"] = 118] = \"F7\";\n /** The F8 key */\n Keys[Keys[\"F8\"] = 119] = \"F8\";\n /** The F9 key */\n Keys[Keys[\"F9\"] = 120] = \"F9\";\n /** The F10 key */\n Keys[Keys[\"F10\"] = 121] = \"F10\";\n /** The F111 key */\n Keys[Keys[\"F11\"] = 122] = \"F11\";\n /** The F12 key */\n Keys[Keys[\"F12\"] = 123] = \"F12\";\n /** The Star */\n Keys[Keys[\"Star\"] = 56] = \"Star\";\n /** The Plus */\n Keys[Keys[\"Plus\"] = 187] = \"Plus\";\n /** The Minus */\n Keys[Keys[\"Minus\"] = 189] = \"Minus\";\n})(Keys || (Keys = {}));\n/**\n * Enables/Disables certain actions of diagram\n * * Render - Indicates the diagram is in render state.\n * * PublicMethod - Indicates the diagram public method is in action.\n * * ToolAction - Indicates the diagram Tool is in action.\n * * UndoRedo - Indicates the diagram undo/redo is in action.\n * * TextEdit - Indicates the text editing is in progress.\n * * Group - Indicates the group is in progress.\n * * Clear - Indicates diagram have clear all.\n */\nexport var DiagramAction;\n(function (DiagramAction) {\n /** Indicates the diagram is in render state.r */\n DiagramAction[DiagramAction[\"Render\"] = 2] = \"Render\";\n /** Indicates the diagram public method is in action. */\n DiagramAction[DiagramAction[\"PublicMethod\"] = 4] = \"PublicMethod\";\n /** Indicates the diagram Tool is in action. */\n DiagramAction[DiagramAction[\"ToolAction\"] = 8] = \"ToolAction\";\n /** Indicates the diagram undo/redo is in action. */\n DiagramAction[DiagramAction[\"UndoRedo\"] = 16] = \"UndoRedo\";\n /** Indicates the text editing is in progress. */\n DiagramAction[DiagramAction[\"TextEdit\"] = 32] = \"TextEdit\";\n /** Indicates the group is in progress. */\n DiagramAction[DiagramAction[\"Group\"] = 64] = \"Group\";\n /** Indicates diagram have clear all. */\n DiagramAction[DiagramAction[\"Clear\"] = 128] = \"Clear\";\n})(DiagramAction || (DiagramAction = {}));\n/** @private */\nexport var NoOfSegments;\n(function (NoOfSegments) {\n NoOfSegments[NoOfSegments[\"Zero\"] = 0] = \"Zero\";\n NoOfSegments[NoOfSegments[\"One\"] = 1] = \"One\";\n NoOfSegments[NoOfSegments[\"Two\"] = 2] = \"Two\";\n NoOfSegments[NoOfSegments[\"Three\"] = 3] = \"Three\";\n NoOfSegments[NoOfSegments[\"Four\"] = 4] = \"Four\";\n NoOfSegments[NoOfSegments[\"Five\"] = 5] = \"Five\";\n})(NoOfSegments || (NoOfSegments = {}));\n/**\n * events of diagram\n * @private\n */\nexport var DiagramEvent;\n(function (DiagramEvent) {\n DiagramEvent[DiagramEvent[\"collectionChange\"] = 0] = \"collectionChange\";\n DiagramEvent[DiagramEvent[\"rotateChange\"] = 1] = \"rotateChange\";\n DiagramEvent[DiagramEvent[\"positionChange\"] = 2] = \"positionChange\";\n DiagramEvent[DiagramEvent[\"propertyChange\"] = 3] = \"propertyChange\";\n DiagramEvent[DiagramEvent[\"selectionChange\"] = 4] = \"selectionChange\";\n DiagramEvent[DiagramEvent[\"sizeChange\"] = 5] = \"sizeChange\";\n DiagramEvent[DiagramEvent[\"drop\"] = 6] = \"drop\";\n DiagramEvent[DiagramEvent[\"sourcePointChange\"] = 7] = \"sourcePointChange\";\n DiagramEvent[DiagramEvent[\"targetPointChange\"] = 8] = \"targetPointChange\";\n DiagramEvent[DiagramEvent[\"connectionChange\"] = 9] = \"connectionChange\";\n DiagramEvent[DiagramEvent[\"animationComplete\"] = 10] = \"animationComplete\";\n DiagramEvent[DiagramEvent[\"click\"] = 11] = \"click\";\n DiagramEvent[DiagramEvent[\"doubleClick\"] = 12] = \"doubleClick\";\n DiagramEvent[DiagramEvent[\"scrollChange\"] = 13] = \"scrollChange\";\n DiagramEvent[DiagramEvent[\"dragEnter\"] = 14] = \"dragEnter\";\n DiagramEvent[DiagramEvent[\"dragLeave\"] = 15] = \"dragLeave\";\n DiagramEvent[DiagramEvent[\"dragOver\"] = 16] = \"dragOver\";\n DiagramEvent[DiagramEvent[\"textEdit\"] = 17] = \"textEdit\";\n DiagramEvent[DiagramEvent[\"paletteSelectionChange\"] = 18] = \"paletteSelectionChange\";\n DiagramEvent[DiagramEvent[\"historyChange\"] = 19] = \"historyChange\";\n DiagramEvent[DiagramEvent[\"mouseEnter\"] = 20] = \"mouseEnter\";\n DiagramEvent[DiagramEvent[\"mouseLeave\"] = 21] = \"mouseLeave\";\n DiagramEvent[DiagramEvent[\"mouseOver\"] = 22] = \"mouseOver\";\n})(DiagramEvent || (DiagramEvent = {}));\n/** Enables/Disables certain features of port connection\n * @aspNumberEnum\n * @IgnoreSingular\n */\nexport var PortConstraints;\n(function (PortConstraints) {\n /** Disable all constraints */\n PortConstraints[PortConstraints[\"None\"] = 1] = \"None\";\n /** Enables connections with connector */\n PortConstraints[PortConstraints[\"Drag\"] = 2] = \"Drag\";\n /** Enables to create the connection when mouse hover on the port */\n PortConstraints[PortConstraints[\"Draw\"] = 4] = \"Draw\";\n})(PortConstraints || (PortConstraints = {}));\n/**\n * Defines the context menu click\n * contextMenuClick - Sets the context menu click as contextMenuClick\n */\nexport var contextMenuClick = \n/** contextMenuClick - Sets the context menu click as contextMenuClick */\n'contextMenuClick';\n/**\n * Defines the context menu open\n * contextMenuOpen - Sets the context menu open as contextMenuOpen\n */\nexport var contextMenuOpen = \n/** contextMenuOpen - Sets the context menu open as contextMenuOpen */\n'contextMenuOpen';\n","import { Transform } from '../../enum/enum';\nimport { Size } from '../../primitives/size';\nimport { Rect } from '../../primitives/rect';\nimport { getBounds, randomId } from '../../utility/base-util';\n/**\n * DiagramElement module defines the basic unit of diagram\n */\nvar DiagramElement = /** @class */ (function () {\n function DiagramElement() {\n /**\n * Sets/Gets the reference point of the element\n */\n this.pivot = { x: 0.5, y: 0.5 };\n /**\n * Sets or gets whether the content of the element needs to be measured\n */\n this.isDirt = true;\n /**\n * Sets or gets whether the content of the element to be visible\n */\n this.visible = true;\n /**\n * Sets/Gets the x-coordinate of the element\n */\n this.offsetX = 0;\n /**\n * Sets/Gets the y-coordinate of the element\n */\n this.offsetY = 0;\n /**\n * Set the corner of the element\n */\n this.cornerRadius = 0;\n /**\n * Sets/Gets the minimum height of the element\n */\n this.minHeight = undefined;\n /**\n * Sets/Gets the minimum width of the element\n */\n this.minWidth = undefined;\n /**\n * Sets/Gets the maximum width of the element\n */\n this.maxWidth = undefined;\n /**\n * Sets/Gets the maximum height of the element\n */\n this.maxHeight = undefined;\n /**\n * Sets/Gets the width of the element\n */\n this.width = undefined;\n /**\n * Sets/Gets the height of the element\n */\n this.height = undefined;\n /**\n * Sets/Gets the rotate angle of the element\n */\n this.rotateAngle = 0;\n /**\n * Sets/Gets the margin of the element\n */\n this.margin = { left: 0, right: 0, top: 0, bottom: 0 };\n /**\n * Sets/Gets how the element has to be horizontally arranged with respect to its immediate parent\n */\n this.horizontalAlignment = 'Auto';\n /**\n * Sets/Gets how the element has to be vertically arranged with respect to its immediate parent\n */\n this.verticalAlignment = 'Auto';\n /**\n * Sets whether the element has to be aligned with respect to a point/with respect to its immediate parent\n */\n this.relativeMode = 'Point';\n /**\n * Sets whether the element has to be transformed based on its parent or not\n */\n this.transform = Transform.Self | Transform.Parent;\n /**\n * Sets the style of the element\n */\n this.style = { fill: 'white', strokeColor: 'black', opacity: 1, strokeWidth: 1 };\n /**\n * Gets the minimum size that is required by the element\n */\n this.desiredSize = new Size();\n /**\n * Gets the size that the element will be rendered\n */\n this.actualSize = new Size();\n /**\n * Gets the rotate angle that is set to the immediate parent of the element\n */\n this.parentTransform = 0;\n this.isSvgRender = false;\n /**\n * Gets/Sets the boundary of the element\n */\n this.bounds = new Rect(0, 0, 0, 0);\n /**\n * Gets/Sets the corners of the rectangular bounds\n */\n this.corners = new Rect(0, 0, 0, 0);\n /**\n * Defines the appearance of the shadow of the element\n */\n this.shadow = null;\n /**\n * Defines the description of the diagram element\n */\n this.description = '';\n /**\n * Defines whether the element has to be measured or not\n */\n this.staticSize = false;\n this.isRectElement = false;\n //private variables\n this.position = undefined;\n this.unitMode = undefined;\n this.float = false;\n this.floatingBounds = undefined;\n this.id = randomId();\n }\n /**\n * Sets the offset of the element with respect to its parent\n * @param x\n * @param y\n * @param mode\n */\n DiagramElement.prototype.setOffsetWithRespectToBounds = function (x, y, mode) {\n this.unitMode = mode;\n this.position = { x: x, y: y };\n };\n /**\n * Gets the position of the element with respect to its parent\n * @param size\n */\n DiagramElement.prototype.getAbsolutePosition = function (size) {\n if (this.position !== undefined) {\n if (this.unitMode === 'Absolute') {\n return this.position;\n }\n else {\n return {\n x: this.position.x * size.width, y: this.position.y * size.height\n };\n }\n }\n return undefined;\n };\n Object.defineProperty(DiagramElement.prototype, \"outerBounds\", {\n get: function () {\n return this.floatingBounds || this.bounds;\n },\n set: function (bounds) {\n this.floatingBounds = bounds;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Measures the minimum space that the element requires\n * @param availableSize\n */\n DiagramElement.prototype.measure = function (availableSize) {\n var width = this.width !== undefined ? this.width : (availableSize.width || 0) - this.margin.left - this.margin.right;\n var height = this.height !== undefined ? this.height : (availableSize.height || 0) - this.margin.top - this.margin.bottom;\n this.desiredSize = new Size(width, height);\n this.desiredSize = this.validateDesiredSize(this.desiredSize, availableSize);\n return this.desiredSize;\n };\n /**\n * Arranges the element\n * @param desiredSize\n */\n DiagramElement.prototype.arrange = function (desiredSize) {\n this.actualSize = desiredSize;\n this.updateBounds();\n return this.actualSize;\n };\n /**\n * Updates the bounds of the element\n */\n DiagramElement.prototype.updateBounds = function () {\n this.bounds = getBounds(this);\n };\n /**\n * Validates the size of the element with respect to its minimum and maximum size\n * @param desiredSize\n * @param availableSize\n */\n DiagramElement.prototype.validateDesiredSize = function (desiredSize, availableSize) {\n //Empty canvas\n if (this.isRectElement && !this.width && !this.minWidth && !this.maxWidth) {\n desiredSize.width = 50;\n }\n if (this.isRectElement && !this.height && !this.minHeight && !this.maxHeight) {\n desiredSize.height = 50;\n }\n if (desiredSize === undefined || this.width !== undefined &&\n this.height !== undefined) {\n desiredSize = desiredSize || new Size();\n desiredSize.width = this.width === undefined ? (availableSize.width || 0)\n - this.margin.left - this.margin.right : this.width;\n desiredSize.height = this.height === undefined ? (availableSize.height || 0)\n - this.margin.top - this.margin.bottom : this.height;\n }\n //Considering min values\n if (this.minWidth !== undefined) {\n desiredSize.width = Math.max(desiredSize.width, this.minWidth);\n }\n if (this.minHeight !== undefined) {\n desiredSize.height = Math.max(desiredSize.height, this.minHeight);\n }\n //Considering max values\n if (this.maxWidth !== undefined) {\n desiredSize.width = Math.min(desiredSize.width, this.maxWidth);\n }\n if (this.maxHeight !== undefined) {\n desiredSize.height = Math.min(desiredSize.height, this.maxHeight);\n }\n return desiredSize;\n };\n return DiagramElement;\n}());\nexport { DiagramElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty, Collection, ComplexFactory } from '@syncfusion/ej2-base';\nvar getGradientType = function (obj) {\n switch (obj.type) {\n case 'Linear':\n return LinearGradient;\n case 'Radial':\n return RadialGradient;\n default:\n return LinearGradient;\n }\n};\n/**\n * Layout Model module defines the styles and types to arrange objects in containers\n */\nvar Thickness = /** @class */ (function () {\n function Thickness(left, right, top, bottom) {\n this.left = left;\n this.right = right;\n this.top = top;\n this.bottom = bottom;\n }\n return Thickness;\n}());\nexport { Thickness };\n/**\n * Defines the space to be left between an object and its immediate parent\n */\nvar Margin = /** @class */ (function (_super) {\n __extends(Margin, _super);\n function Margin() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], Margin.prototype, \"left\", void 0);\n __decorate([\n Property(0)\n ], Margin.prototype, \"right\", void 0);\n __decorate([\n Property(0)\n ], Margin.prototype, \"top\", void 0);\n __decorate([\n Property(0)\n ], Margin.prototype, \"bottom\", void 0);\n return Margin;\n}(ChildProperty));\nexport { Margin };\n/**\n * Defines the Shadow appearance of the objects\n */\nvar Shadow = /** @class */ (function (_super) {\n __extends(Shadow, _super);\n function Shadow() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(45)\n ], Shadow.prototype, \"angle\", void 0);\n __decorate([\n Property(5)\n ], Shadow.prototype, \"distance\", void 0);\n __decorate([\n Property(0.7)\n ], Shadow.prototype, \"opacity\", void 0);\n __decorate([\n Property('lightgrey')\n ], Shadow.prototype, \"color\", void 0);\n return Shadow;\n}(ChildProperty));\nexport { Shadow };\n/**\n * Defines the stop of gradient\n */\nvar Stop = /** @class */ (function (_super) {\n __extends(Stop, _super);\n function Stop() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Stop.prototype, \"color\", void 0);\n __decorate([\n Property(0)\n ], Stop.prototype, \"offset\", void 0);\n __decorate([\n Property(1)\n ], Stop.prototype, \"opacity\", void 0);\n return Stop;\n}(ChildProperty));\nexport { Stop };\n/**\n * Defines the gradient of styles\n */\nvar Gradient = /** @class */ (function (_super) {\n __extends(Gradient, _super);\n function Gradient() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Collection([], Stop)\n ], Gradient.prototype, \"stops\", void 0);\n __decorate([\n Property('None')\n ], Gradient.prototype, \"type\", void 0);\n __decorate([\n Property('')\n ], Gradient.prototype, \"id\", void 0);\n return Gradient;\n}(ChildProperty));\nexport { Gradient };\n/**\n * Defines the linear gradient of styles\n */\nvar LinearGradient = /** @class */ (function (_super) {\n __extends(LinearGradient, _super);\n function LinearGradient() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], LinearGradient.prototype, \"x1\", void 0);\n __decorate([\n Property(0)\n ], LinearGradient.prototype, \"x2\", void 0);\n __decorate([\n Property(0)\n ], LinearGradient.prototype, \"y1\", void 0);\n __decorate([\n Property(0)\n ], LinearGradient.prototype, \"y2\", void 0);\n return LinearGradient;\n}(Gradient));\nexport { LinearGradient };\n/**\n * Defines the radial gradient of styles\n */\nvar RadialGradient = /** @class */ (function (_super) {\n __extends(RadialGradient, _super);\n function RadialGradient() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], RadialGradient.prototype, \"cx\", void 0);\n __decorate([\n Property(0)\n ], RadialGradient.prototype, \"cy\", void 0);\n __decorate([\n Property(0)\n ], RadialGradient.prototype, \"fx\", void 0);\n __decorate([\n Property(0)\n ], RadialGradient.prototype, \"fy\", void 0);\n __decorate([\n Property(50)\n ], RadialGradient.prototype, \"r\", void 0);\n return RadialGradient;\n}(Gradient));\nexport { RadialGradient };\n/**\n * Defines the style of shape/path\n */\nvar ShapeStyle = /** @class */ (function (_super) {\n __extends(ShapeStyle, _super);\n function ShapeStyle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('white')\n ], ShapeStyle.prototype, \"fill\", void 0);\n __decorate([\n Property('black')\n ], ShapeStyle.prototype, \"strokeColor\", void 0);\n __decorate([\n Property('')\n ], ShapeStyle.prototype, \"strokeDashArray\", void 0);\n __decorate([\n Property(1)\n ], ShapeStyle.prototype, \"strokeWidth\", void 0);\n __decorate([\n Property(1)\n ], ShapeStyle.prototype, \"opacity\", void 0);\n __decorate([\n ComplexFactory(getGradientType)\n ], ShapeStyle.prototype, \"gradient\", void 0);\n return ShapeStyle;\n}(ChildProperty));\nexport { ShapeStyle };\n/**\n * Defines the stroke style of a path\n */\nvar StrokeStyle = /** @class */ (function (_super) {\n __extends(StrokeStyle, _super);\n function StrokeStyle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('transparent')\n ], StrokeStyle.prototype, \"fill\", void 0);\n return StrokeStyle;\n}(ShapeStyle));\nexport { StrokeStyle };\n/**\n * Defines the appearance of text\n */\nvar TextStyle = /** @class */ (function (_super) {\n __extends(TextStyle, _super);\n function TextStyle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('black')\n ], TextStyle.prototype, \"color\", void 0);\n __decorate([\n Property('Arial')\n ], TextStyle.prototype, \"fontFamily\", void 0);\n __decorate([\n Property(12)\n ], TextStyle.prototype, \"fontSize\", void 0);\n __decorate([\n Property(false)\n ], TextStyle.prototype, \"italic\", void 0);\n __decorate([\n Property(false)\n ], TextStyle.prototype, \"bold\", void 0);\n __decorate([\n Property('CollapseSpace')\n ], TextStyle.prototype, \"whiteSpace\", void 0);\n __decorate([\n Property('WrapWithOverflow')\n ], TextStyle.prototype, \"textWrapping\", void 0);\n __decorate([\n Property('Center')\n ], TextStyle.prototype, \"textAlign\", void 0);\n __decorate([\n Property('None')\n ], TextStyle.prototype, \"textDecoration\", void 0);\n __decorate([\n Property('Wrap')\n ], TextStyle.prototype, \"textOverflow\", void 0);\n return TextStyle;\n}(ShapeStyle));\nexport { TextStyle };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { DiagramElement } from '../elements/diagram-element';\nimport { Thickness } from '../appearance';\nimport { Size } from '../../primitives/size';\nimport { Rect } from '../../primitives/rect';\nimport { rotatePoint, getOffset } from '../../utility/base-util';\n/**\n * Container module is used to group related objects\n */\nvar Container = /** @class */ (function (_super) {\n __extends(Container, _super);\n function Container() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /**\n * Gets/Sets the space between the container and its immediate children\n */\n _this.padding = new Thickness(0, 0, 0, 0);\n //private members \n _this.desiredBounds = undefined;\n /** @private */\n _this.measureChildren = true;\n _this.prevRotateAngle = 0;\n return _this;\n }\n /**\n * returns whether the container has child elements or not\n */\n Container.prototype.hasChildren = function () {\n if (this.children !== undefined && this.children.length > 0) {\n return true;\n }\n return false;\n };\n /**\n * Measures the minimum space that the container requires\n *\n * @param availableSize\n */\n Container.prototype.measure = function (availableSize) {\n // measure the element and find the desired size\n this.desiredBounds = undefined;\n var desired = undefined;\n var child;\n var center = { x: 0, y: 0 };\n var y;\n var x;\n var childBounds;\n if (this.hasChildren()) {\n //Measuring the children\n for (var i = 0; i < this.children.length; i++) {\n child = this.children[i];\n var force = child.horizontalAlignment === 'Stretch' || child.verticalAlignment === 'Stretch';\n if (this.measureChildren || force || (child instanceof Container && child.measureChildren !== undefined)) {\n child.measure(availableSize);\n }\n childBounds = this.GetChildrenBounds(child);\n if (child.horizontalAlignment !== 'Stretch' && child.verticalAlignment !== 'Stretch') {\n if (this.desiredBounds === undefined) {\n this.desiredBounds = childBounds;\n }\n else {\n this.desiredBounds.uniteRect(childBounds);\n }\n }\n }\n if (this.desiredBounds !== undefined && this.rotateAngle !== 0) {\n var offsetPt = {\n x: this.desiredBounds.x + this.desiredBounds.width * this.pivot.x,\n y: this.desiredBounds.y + this.desiredBounds.height * this.pivot.y\n };\n var newPoint = rotatePoint(this.rotateAngle, undefined, undefined, offsetPt);\n this.desiredBounds.x = newPoint.x - this.desiredBounds.width * this.pivot.x;\n this.desiredBounds.y = newPoint.y - this.desiredBounds.height * this.pivot.y;\n }\n if (this.desiredBounds) {\n desired = new Size(this.desiredBounds.width, this.desiredBounds.height);\n }\n }\n desired = this.validateDesiredSize(desired, availableSize);\n this.stretchChildren(desired);\n this.desiredSize = desired;\n return desired;\n };\n /**\n * Arranges the container and its children\n * @param desiredSize\n */\n Container.prototype.arrange = function (desiredSize) {\n var child;\n var bounds;\n var childBounds = this.desiredBounds;\n if (childBounds) {\n var x = this.offsetX;\n var y = this.offsetY;\n this.offsetX = childBounds.x + childBounds.width * this.pivot.x;\n this.offsetY = childBounds.y + childBounds.height * this.pivot.y;\n // container has rotateAngle\n if (this.hasChildren()) {\n //Measuring the children\n for (var i = 0; i < this.children.length; i++) {\n child = this.children[i];\n var arrange = false;\n if (child.horizontalAlignment === 'Stretch') {\n child.offsetX = this.offsetX;\n child.parentTransform = this.parentTransform + this.rotateAngle;\n arrange = true;\n }\n if (child.verticalAlignment === 'Stretch') {\n child.offsetY = this.offsetY;\n child.parentTransform = this.parentTransform + this.rotateAngle;\n arrange = true;\n }\n if (arrange || this.measureChildren || (child instanceof Container && child.measureChildren !== undefined)) {\n child.arrange(child.desiredSize);\n }\n }\n }\n }\n this.actualSize = desiredSize;\n this.updateBounds();\n this.prevRotateAngle = this.rotateAngle;\n return desiredSize;\n };\n //protected methods\n /**\n * Stretches the child elements based on the size of the container\n * @param size\n */\n Container.prototype.stretchChildren = function (size) {\n if (this.hasChildren()) {\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (child.horizontalAlignment === 'Stretch' || child.desiredSize.width === undefined) {\n child.desiredSize.width = size.width - child.margin.left - child.margin.right;\n }\n if (child.verticalAlignment === 'Stretch' || child.desiredSize.height === undefined) {\n child.desiredSize.height = size.height - child.margin.top - child.margin.bottom;\n }\n if (child instanceof Container) {\n child.stretchChildren(child.desiredSize);\n }\n }\n }\n };\n /**\n * Considers the padding of the element when measuring its desired size\n * @param size\n */\n Container.prototype.applyPadding = function (size) {\n size.width += this.padding.left + this.padding.right;\n size.height += this.padding.top + this.padding.bottom;\n };\n /**\n * Finds the offset of the child element with respect to the container\n * @param child\n * @param center\n */\n Container.prototype.findChildOffsetFromCenter = function (child, center) {\n var topLeft = { x: center.x - child.desiredSize.width / 2, y: center.y - child.desiredSize.height / 2 };\n var offset = getOffset(topLeft, child);\n //Rotate based on child rotate angle\n offset = rotatePoint(child.rotateAngle, center.x, center.y, offset);\n //Rotate based on parent pivot\n offset = rotatePoint(this.rotateAngle + this.parentTransform, this.offsetX, this.offsetY, offset);\n child.offsetX = offset.x;\n child.offsetY = offset.y;\n };\n //private methods - check its need\n Container.prototype.GetChildrenBounds = function (child) {\n var childBounds;\n var childSize;\n childSize = child.desiredSize.clone();\n var diffAngle = child.rotateAngle - this.rotateAngle;\n var refPoint = { x: child.offsetX, y: child.offsetY };\n var left = refPoint.x - childSize.width * child.pivot.x;\n var top = refPoint.y - childSize.height * child.pivot.y;\n var right = left + childSize.width;\n var bottom = top + childSize.height;\n var topLeft = { x: left, y: top };\n var topRight = { x: right, y: top };\n var bottomLeft = { x: left, y: bottom };\n var bottomRight = { x: right, y: bottom };\n topLeft = rotatePoint(child.rotateAngle, child.offsetX, child.offsetY, topLeft);\n topRight = rotatePoint(child.rotateAngle, child.offsetX, child.offsetY, topRight);\n bottomLeft = rotatePoint(child.rotateAngle, child.offsetX, child.offsetY, bottomLeft);\n bottomRight = rotatePoint(child.rotateAngle, child.offsetX, child.offsetY, bottomRight);\n if (this.rotateAngle !== 0) {\n topLeft = rotatePoint(-this.rotateAngle, undefined, undefined, topLeft);\n topRight = rotatePoint(-this.rotateAngle, undefined, undefined, topRight);\n bottomLeft = rotatePoint(-this.rotateAngle, undefined, undefined, bottomLeft);\n bottomRight = rotatePoint(-this.rotateAngle, undefined, undefined, bottomRight);\n }\n return Rect.toBounds([topLeft, topRight, bottomLeft, bottomRight]);\n };\n return Container;\n}(DiagramElement));\nexport { Container };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Size } from '../../primitives/size';\nimport { DiagramElement } from './diagram-element';\nimport { Rect } from '../../primitives/rect';\nimport { measurePath, findSegmentPoints, translatePoints } from './../../utility/dom-util';\nimport { processPathData, splitArrayCollection, transformPath, getPathString } from '../../utility/path-util';\n/**\n * PathElement takes care of how to align the path based on offsetX and offsetY\n */\nvar PathElement = /** @class */ (function (_super) {\n __extends(PathElement, _super);\n /**\n * set the id for each element\n */\n function PathElement() {\n var _this = _super.call(this) || this;\n /**\n * Gets or sets the geometry of the path element\n */\n _this.pathData = '';\n /**\n * Gets/Sets whether the path has to be transformed to fit the given x,y, width, height\n */\n _this.transformPath = true;\n /**\n * Gets/Sets the equivalent path, that will have the origin as 0,0\n */\n _this.absolutePath = '';\n //Private variables\n _this.absoluteBounds = new Rect();\n return _this;\n }\n Object.defineProperty(PathElement.prototype, \"data\", {\n get: function () {\n return this.pathData;\n },\n set: function (value) {\n if (this.pathData !== value) {\n this.pathData = value;\n this.isDirt = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n /** @private */\n PathElement.prototype.getPoints = function () {\n var _this = this;\n if (!this.pointTimer) {\n this.pointTimer = setTimeout(function () {\n _this.points = null;\n _this.pointTimer = null;\n }, 200);\n }\n this.points = this.points || findSegmentPoints(this);\n return translatePoints(this, this.points);\n };\n /**\n * Measures the minimum space that is required to render the element\n * @param availableSize\n */\n PathElement.prototype.measure = function (availableSize) {\n //Performance issue - Avoiding measuring the connector path\n if (this.staticSize && this.width !== undefined && this.height !== undefined) {\n this.absoluteBounds = new Rect(this.offsetX - this.width * this.pivot.x, this.offsetY - this.height * this.pivot.y, this.width, this.height);\n }\n else if (this.isDirt && (this.transformPath || (this.width === undefined || this.height === undefined))) {\n //Measure the element only whent the path data is changed/ size is not specified\n this.absoluteBounds = measurePath(this.data ? this.data : '');\n }\n if (this.width === undefined) {\n this.desiredSize = new Size(this.absoluteBounds.width, this.height || this.absoluteBounds.height);\n }\n else if (this.height === undefined) {\n this.desiredSize = new Size(this.width || this.absoluteBounds.width, this.absoluteBounds.height);\n }\n else {\n this.desiredSize = new Size(this.width, this.height);\n }\n this.desiredSize = this.validateDesiredSize(this.desiredSize, availableSize);\n return this.desiredSize;\n };\n /**\n * Arranges the path element\n * @param desiredSize\n */\n PathElement.prototype.arrange = function (desiredSize) {\n if (this.isDirt || this.actualSize.width !== desiredSize.width || this.actualSize.height !== desiredSize.height) {\n this.isDirt = true;\n this.absolutePath = this.updatePath(this.data, this.absoluteBounds, desiredSize);\n if (!this.staticSize) {\n this.points = null;\n }\n }\n this.actualSize = this.desiredSize;\n this.updateBounds();\n this.isDirt = false;\n return this.actualSize;\n };\n /**\n * Translates the path to 0,0 and scales the path based on the actual size\n * @param pathData\n * @param bounds\n * @param actualSize\n */\n PathElement.prototype.updatePath = function (pathData, bounds, actualSize) {\n var isScale = false;\n var newPathString = '';\n var scaleX = -bounds.x;\n var scaleY = -bounds.y;\n var arrayCollection = [];\n if (actualSize.width !== bounds.width || actualSize.height !== bounds.height) {\n scaleX = actualSize.width / Number(bounds.width ? bounds.width : 1);\n scaleY = actualSize.height / Number(bounds.height ? bounds.height : 1);\n isScale = true;\n }\n arrayCollection = processPathData(pathData);\n arrayCollection = splitArrayCollection(arrayCollection);\n if ((isScale || this.isDirt) && this.transformPath) {\n newPathString = transformPath(arrayCollection, scaleX, scaleY, isScale, bounds.x, bounds.y, 0, 0);\n }\n else {\n newPathString = getPathString(arrayCollection);\n }\n isScale = false;\n return newPathString;\n };\n return PathElement;\n}(DiagramElement));\nexport { PathElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Size } from '../../primitives/size';\nimport { DiagramElement } from './diagram-element';\nimport { measureNativeContent, getContent, measureNativeSvg } from './../../utility/dom-util';\n/**\n * NativeElement defines the basic native elements\n */\nvar DiagramNativeElement = /** @class */ (function (_super) {\n __extends(DiagramNativeElement, _super);\n /**\n * set the id for each element\n */\n function DiagramNativeElement(nodeId, diagramId) {\n var _this = _super.call(this) || this;\n _this.data = '';\n _this.nodeId = '';\n _this.diagramId = '';\n /**\n * sets scaling factor of the Native Element\n */\n _this.scale = 'Stretch';\n _this.diagramId = diagramId;\n _this.nodeId = nodeId;\n return _this;\n }\n Object.defineProperty(DiagramNativeElement.prototype, \"content\", {\n /**\n * Gets or sets the geometry of the native element\n */\n get: function () {\n return this.data;\n },\n set: function (value) {\n this.data = value;\n this.template = getContent(this, false);\n this.isDirt = true;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Measures minimum space that is required to render the Native Element\n * @param availableSize\n */\n DiagramNativeElement.prototype.measure = function (availableSize) {\n if (this.isDirt) {\n var rect = measureNativeContent(this.template);\n this.contentSize = new Size();\n this.contentSize.width = rect.width;\n this.contentSize.height = rect.height;\n var x = rect.x;\n var y = rect.y;\n this.templatePosition = { x: x, y: y };\n this.isDirt = false;\n }\n if (this.width === undefined || this.height === undefined) {\n var getAvailableSize = measureNativeSvg(this.template);\n this.desiredSize = new Size(getAvailableSize.width, getAvailableSize.height);\n }\n else {\n this.desiredSize = new Size(this.width, this.height);\n }\n this.desiredSize = this.validateDesiredSize(this.desiredSize, availableSize);\n return this.desiredSize;\n };\n /**\n * Arranges the Native Element\n * @param desiredSize\n */\n DiagramNativeElement.prototype.arrange = function (desiredSize) {\n this.actualSize = new Size(this.desiredSize.width, this.desiredSize.height);\n this.updateBounds();\n return this.actualSize;\n };\n return DiagramNativeElement;\n}(DiagramElement));\nexport { DiagramNativeElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Size } from '../../primitives/size';\nimport { DiagramElement } from './diagram-element';\nimport { measureText } from './../../utility/dom-util';\n/**\n * TextElement is used to display text/annotations\n */\nvar TextElement = /** @class */ (function (_super) {\n __extends(TextElement, _super);\n /**\n * set the id for each element\n */\n function TextElement() {\n var _this = _super.call(this) || this;\n /**\n * sets or gets the image source\n */\n _this.textContent = '';\n _this.hyperlink = {\n color: 'blue'\n };\n /** @private */\n _this.doWrap = true;\n _this.textNodes = [];\n /**\n * Defines the appearance of the text element\n */\n _this.style = {\n color: 'black', fill: 'white', strokeColor: 'black',\n strokeWidth: 1, fontFamily: 'Arial', fontSize: 12, whiteSpace: 'CollapseSpace',\n textWrapping: 'WrapWithOverflow', textAlign: 'Center', italic: false, bold: false,\n textDecoration: 'None', strokeDashArray: '', opacity: 5, gradient: null,\n textOverflow: 'Wrap'\n };\n return _this;\n }\n Object.defineProperty(TextElement.prototype, \"content\", {\n get: function () {\n return this.textContent;\n },\n set: function (value) {\n if (this.textContent !== value) {\n this.textContent = value;\n this.isDirt = true;\n this.doWrap = true;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextElement.prototype, \"childNodes\", {\n get: function () {\n return this.textNodes;\n },\n set: function (value) {\n this.textNodes = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextElement.prototype, \"wrapBounds\", {\n get: function () {\n return this.textWrapBounds;\n },\n set: function (value) {\n this.textWrapBounds = value;\n },\n enumerable: true,\n configurable: true\n });\n /** @private */\n TextElement.prototype.refreshTextElement = function () {\n this.isDirt = true;\n };\n /**\n * Measures the minimum size that is required for the text element\n * @param availableSize\n */\n TextElement.prototype.measure = function (availableSize) {\n var size;\n if (this.isDirt) {\n size = measureText(this, this.style, this.content, this.width);\n }\n else {\n size = this.desiredSize;\n }\n if (this.width === undefined || this.height === undefined) {\n this.desiredSize = new Size(size.width, size.height);\n }\n else {\n this.desiredSize = new Size(this.width, this.height);\n }\n this.desiredSize = this.validateDesiredSize(this.desiredSize, availableSize);\n return this.desiredSize;\n };\n /**\n * Arranges the text element\n * @param desiredSize\n */\n TextElement.prototype.arrange = function (desiredSize) {\n if (desiredSize.width !== this.actualSize.width || desiredSize.height !== this.actualSize.height || this.isDirt) {\n this.doWrap = true;\n }\n this.actualSize = desiredSize;\n this.updateBounds();\n this.isDirt = false;\n return this.actualSize;\n };\n return TextElement;\n}(DiagramElement));\nexport { TextElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Size } from '../../primitives/size';\nimport { DiagramElement } from './diagram-element';\nimport { measureImage } from './../../utility/dom-util';\n/**\n * ImageElement defines a basic image elements\n */\nvar ImageElement = /** @class */ (function (_super) {\n __extends(ImageElement, _super);\n /**\n * set the id for each element\n */\n function ImageElement() {\n var _this = _super.call(this) || this;\n /**\n * sets or gets the image source\n */\n _this.imageSource = '';\n /**\n * sets scaling factor of the image\n */\n _this.imageScale = 'None';\n /**\n * sets the alignment of the image\n */\n _this.imageAlign = 'None';\n /**\n * Sets how to stretch the image\n */\n _this.stretch = 'Stretch';\n return _this;\n }\n Object.defineProperty(ImageElement.prototype, \"source\", {\n get: function () {\n return this.imageSource;\n },\n set: function (value) {\n this.imageSource = value;\n this.isDirt = true;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Measures minimum space that is required to render the image\n * @param availableSize\n */\n ImageElement.prototype.measure = function (availableSize) {\n if (this.isDirt && (this.stretch !== 'Stretch' || this.width === undefined && this.height === undefined)) {\n this.contentSize = measureImage(this.source, this.contentSize);\n this.isDirt = false;\n }\n if (this.width !== undefined && this.height !== undefined) {\n this.desiredSize = new Size(this.width, this.height);\n this.contentSize = this.desiredSize;\n }\n else {\n this.desiredSize = this.contentSize;\n }\n this.desiredSize = this.validateDesiredSize(this.desiredSize, availableSize);\n return this.desiredSize;\n };\n /**\n * Arranges the image\n * @param desiredSize\n */\n ImageElement.prototype.arrange = function (desiredSize) {\n this.actualSize = new Size(this.desiredSize.width, this.desiredSize.height);\n this.updateBounds();\n return this.actualSize;\n };\n return ImageElement;\n}(DiagramElement));\nexport { ImageElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Container } from './container';\nimport { rotateSize } from '../../utility/base-util';\nimport { Transform } from '../../enum/enum';\nimport { Size } from '../../primitives/size';\nimport { Rect } from '../../primitives/rect';\n/**\n * Canvas module is used to define a plane(canvas) and to arrange the children based on margin\n */\nvar Canvas = /** @class */ (function (_super) {\n __extends(Canvas, _super);\n function Canvas() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /**\n * Not applicable for canvas\n * @private\n */\n _this.measureChildren = undefined;\n return _this;\n }\n /**\n * Measures the minimum space that the canvas requires\n * @param availableSize\n */\n Canvas.prototype.measure = function (availableSize) {\n var desired = undefined;\n var desiredBounds = undefined;\n if (this.hasChildren()) {\n //Measuring the children\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n child.measure(availableSize);\n var childSize = child.desiredSize.clone();\n if (child.rotateAngle !== 0) {\n childSize = rotateSize(childSize, child.rotateAngle);\n }\n var right = childSize.width + child.margin.right;\n var bottom = childSize.height + child.margin.bottom;\n var childBounds = new Rect(child.margin.left, child.margin.top, right, bottom);\n if (child.float) {\n var position = child.getAbsolutePosition(childSize);\n if (position !== undefined) {\n continue;\n }\n }\n if (desiredBounds === undefined) {\n desiredBounds = childBounds;\n }\n else {\n desiredBounds.uniteRect(childBounds);\n }\n }\n if (desiredBounds) {\n var leftMargin = 0;\n var topMargin = 0;\n leftMargin = Math.max(desiredBounds.left, 0);\n topMargin = Math.max(desiredBounds.top, 0);\n desired = new Size(desiredBounds.width + leftMargin, desiredBounds.height + topMargin);\n }\n }\n desired = _super.prototype.validateDesiredSize.call(this, desired, availableSize);\n _super.prototype.stretchChildren.call(this, desired);\n //Considering padding values\n desired.width += this.padding.left + this.padding.right;\n desired.height += this.padding.top + this.padding.bottom;\n this.desiredSize = desired;\n return desired;\n };\n /**\n * Arranges the child elements of the canvas\n */\n Canvas.prototype.arrange = function (desiredSize) {\n this.outerBounds = new Rect();\n if (this.hasChildren()) {\n var y = void 0;\n var x = void 0;\n y = this.offsetY - desiredSize.height * this.pivot.y + this.padding.top;\n x = this.offsetX - desiredSize.width * this.pivot.x + this.padding.left;\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n if ((child.transform & Transform.Parent) !== 0) {\n child.parentTransform = this.parentTransform + this.rotateAngle;\n var childSize = child.desiredSize.clone();\n if (child.rotateAngle !== 0) {\n childSize = rotateSize(childSize, child.rotateAngle);\n }\n var topLeft = void 0;\n var center = { x: 0, y: 0 };\n var childX = x;\n var childY = y;\n if (child.relativeMode === 'Point') {\n var position = child.getAbsolutePosition(desiredSize);\n if (position !== undefined) {\n childX += position.x;\n childY += position.y;\n }\n }\n if (child.relativeMode === 'Object') {\n topLeft = this.alignChildBasedOnParent(child, childSize, desiredSize, childX, childY);\n }\n else {\n topLeft = this.alignChildBasedOnaPoint(child, childX, childY);\n }\n center = { x: topLeft.x + childSize.width / 2, y: topLeft.y + childSize.height / 2 };\n _super.prototype.findChildOffsetFromCenter.call(this, child, center);\n }\n child.arrange(child.desiredSize);\n this.outerBounds.uniteRect(child.outerBounds);\n }\n }\n this.actualSize = desiredSize;\n this.updateBounds();\n this.outerBounds.uniteRect(this.bounds);\n return desiredSize;\n };\n /**\n * Aligns the child element based on its parent\n * @param child\n * @param childSize\n * @param parentSize\n * @param x\n * @param y\n */\n Canvas.prototype.alignChildBasedOnParent = function (child, childSize, parentSize, x, y) {\n switch (child.horizontalAlignment) {\n case 'Auto':\n case 'Left':\n x += child.margin.left;\n break;\n case 'Right':\n x += parentSize.width - childSize.width - child.margin.right;\n break;\n case 'Stretch':\n case 'Center':\n x += parentSize.width / 2 - childSize.width / 2;\n break;\n }\n switch (child.verticalAlignment) {\n case 'Auto':\n case 'Top':\n y += child.margin.top;\n break;\n case 'Bottom':\n y += parentSize.height - childSize.height - child.margin.bottom;\n break;\n case 'Stretch':\n case 'Center':\n y += parentSize.height / 2 - childSize.height / 2;\n break;\n }\n return { x: x, y: y };\n };\n /**\n * Aligns the child elements based on a point\n * @param child\n * @param x\n * @param y\n */\n Canvas.prototype.alignChildBasedOnaPoint = function (child, x, y) {\n switch (child.horizontalAlignment) {\n case 'Auto':\n case 'Left':\n x += child.margin.left;\n break;\n case 'Stretch':\n case 'Center':\n x -= child.desiredSize.width * child.pivot.x;\n break;\n case 'Right':\n x -= child.desiredSize.width + child.margin.right;\n break;\n }\n switch (child.verticalAlignment) {\n case 'Auto':\n case 'Top':\n y += child.margin.top;\n break;\n case 'Stretch':\n case 'Center':\n y -= child.desiredSize.height * child.pivot.y;\n break;\n case 'Bottom':\n y -= child.desiredSize.height + child.margin.bottom;\n break;\n }\n return { x: x, y: y };\n };\n return Canvas;\n}(Container));\nexport { Canvas };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { ShapeStyle, Margin } from '../core/appearance';\nimport { Point } from '../primitives/point';\nimport { PortConstraints, PortVisibility } from '../enum/enum';\n/**\n * Defines the behavior of connection ports\n */\nvar Port = /** @class */ (function (_super) {\n __extends(Port, _super);\n function Port() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Port.prototype, \"id\", void 0);\n __decorate([\n Property('Center')\n ], Port.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Center')\n ], Port.prototype, \"verticalAlignment\", void 0);\n __decorate([\n Complex({}, Margin)\n ], Port.prototype, \"margin\", void 0);\n __decorate([\n Property(12)\n ], Port.prototype, \"width\", void 0);\n __decorate([\n Property(12)\n ], Port.prototype, \"height\", void 0);\n __decorate([\n Complex({}, ShapeStyle)\n ], Port.prototype, \"style\", void 0);\n __decorate([\n Property('Square')\n ], Port.prototype, \"shape\", void 0);\n __decorate([\n Property(PortVisibility.Connect)\n ], Port.prototype, \"visibility\", void 0);\n __decorate([\n Property('')\n ], Port.prototype, \"pathData\", void 0);\n __decorate([\n Property(PortConstraints.None)\n ], Port.prototype, \"constraints\", void 0);\n __decorate([\n Property()\n ], Port.prototype, \"addInfo\", void 0);\n return Port;\n}(ChildProperty));\nexport { Port };\n/**\n * Defines the behavior of a port, that sticks to a point\n */\nvar PointPort = /** @class */ (function (_super) {\n __extends(PointPort, _super);\n // tslint:disable-next-line:no-any\n function PointPort(parent, propName, defaultValue, isArray) {\n return _super.call(this, parent, propName, defaultValue, isArray) || this;\n }\n __decorate([\n Complex({ x: 0.5, y: 0.5 }, Point)\n ], PointPort.prototype, \"offset\", void 0);\n return PointPort;\n}(Port));\nexport { PointPort };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { TextStyle, Margin } from '../core/appearance';\nimport { Point } from '../primitives/point';\nimport { AnnotationConstraints } from '../enum/enum';\n/**\n * Defines the hyperlink for the annotation\n */\nvar Hyperlink = /** @class */ (function (_super) {\n __extends(Hyperlink, _super);\n function Hyperlink() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('blue')\n ], Hyperlink.prototype, \"color\", void 0);\n __decorate([\n Property('')\n ], Hyperlink.prototype, \"content\", void 0);\n __decorate([\n Property('')\n ], Hyperlink.prototype, \"link\", void 0);\n __decorate([\n Property('None')\n ], Hyperlink.prototype, \"textDecoration\", void 0);\n return Hyperlink;\n}(ChildProperty));\nexport { Hyperlink };\n/**\n * Defines the textual description of nodes/connectors\n */\nvar Annotation = /** @class */ (function (_super) {\n __extends(Annotation, _super);\n function Annotation() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Annotation.prototype, \"content\", void 0);\n __decorate([\n Property(true)\n ], Annotation.prototype, \"visibility\", void 0);\n __decorate([\n Property(AnnotationConstraints.InheritReadOnly)\n ], Annotation.prototype, \"constraints\", void 0);\n __decorate([\n Complex(undefined, Hyperlink)\n ], Annotation.prototype, \"hyperlink\", void 0);\n __decorate([\n Property('')\n ], Annotation.prototype, \"id\", void 0);\n __decorate([\n Property()\n ], Annotation.prototype, \"width\", void 0);\n __decorate([\n Property()\n ], Annotation.prototype, \"height\", void 0);\n __decorate([\n Complex({ strokeWidth: 0, strokeColor: 'transparent', fill: 'transparent' }, TextStyle)\n ], Annotation.prototype, \"style\", void 0);\n __decorate([\n Property('Center')\n ], Annotation.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Center')\n ], Annotation.prototype, \"verticalAlignment\", void 0);\n __decorate([\n Complex({}, Margin)\n ], Annotation.prototype, \"margin\", void 0);\n __decorate([\n Property('Shape')\n ], Annotation.prototype, \"type\", void 0);\n __decorate([\n Property()\n ], Annotation.prototype, \"addInfo\", void 0);\n return Annotation;\n}(ChildProperty));\nexport { Annotation };\n/**\n * Defines the textual description of nodes/connectors with respect to bounds\n */\nvar ShapeAnnotation = /** @class */ (function (_super) {\n __extends(ShapeAnnotation, _super);\n // tslint:disable-next-line:no-any\n function ShapeAnnotation(parent, propName, defaultValue, isArray) {\n return _super.call(this, parent, propName, defaultValue, isArray) || this;\n }\n __decorate([\n Complex({ x: 0.5, y: 0.5 }, Point)\n ], ShapeAnnotation.prototype, \"offset\", void 0);\n return ShapeAnnotation;\n}(Annotation));\nexport { ShapeAnnotation };\n/**\n * Defines the connector annotation\n */\nvar PathAnnotation = /** @class */ (function (_super) {\n __extends(PathAnnotation, _super);\n // tslint:disable-next-line:no-any\n function PathAnnotation(parent, propName, defaultValue, isArray) {\n return _super.call(this, parent, propName, defaultValue, isArray) || this;\n }\n __decorate([\n Property(0.5)\n ], PathAnnotation.prototype, \"offset\", void 0);\n __decorate([\n Complex({ x: 0, y: 0 }, Point)\n ], PathAnnotation.prototype, \"displacement\", void 0);\n __decorate([\n Property('Center')\n ], PathAnnotation.prototype, \"alignment\", void 0);\n return PathAnnotation;\n}(Annotation));\nexport { PathAnnotation };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { Margin } from '../core/appearance';\nimport { Point } from '../primitives/point';\n/**\n * Defines the behavior of default IconShape\n */\nvar IconShape = /** @class */ (function (_super) {\n __extends(IconShape, _super);\n function IconShape() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('None')\n ], IconShape.prototype, \"shape\", void 0);\n __decorate([\n Property('white')\n ], IconShape.prototype, \"fill\", void 0);\n __decorate([\n Property('Auto')\n ], IconShape.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Auto')\n ], IconShape.prototype, \"verticalAlignment\", void 0);\n __decorate([\n Property(10)\n ], IconShape.prototype, \"width\", void 0);\n __decorate([\n Property(10)\n ], IconShape.prototype, \"height\", void 0);\n __decorate([\n Complex({ x: 0.5, y: 1 }, Point)\n ], IconShape.prototype, \"offset\", void 0);\n __decorate([\n Property('#1a1a1a')\n ], IconShape.prototype, \"borderColor\", void 0);\n __decorate([\n Property(1)\n ], IconShape.prototype, \"borderWidth\", void 0);\n __decorate([\n Complex({}, Margin)\n ], IconShape.prototype, \"margin\", void 0);\n __decorate([\n Property('')\n ], IconShape.prototype, \"pathData\", void 0);\n __decorate([\n Property('')\n ], IconShape.prototype, \"content\", void 0);\n __decorate([\n Property(0)\n ], IconShape.prototype, \"cornerRadius\", void 0);\n __decorate([\n Complex({ left: 2, right: 2, top: 2, bottom: 2 }, Margin)\n ], IconShape.prototype, \"padding\", void 0);\n return IconShape;\n}(ChildProperty));\nexport { IconShape };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty, Collection } from '@syncfusion/ej2-base';\nimport { Margin } from '../core/appearance';\nimport { IconShape } from './icon';\nimport { DiagramTooltip } from './tooltip';\nimport { PointPort } from './port';\n/**\n * Defines the common behavior of nodes, connectors and groups\n */\nvar NodeBase = /** @class */ (function (_super) {\n __extends(NodeBase, _super);\n function NodeBase() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], NodeBase.prototype, \"id\", void 0);\n __decorate([\n Property(-1)\n ], NodeBase.prototype, \"zIndex\", void 0);\n __decorate([\n Complex({}, Margin)\n ], NodeBase.prototype, \"margin\", void 0);\n __decorate([\n Property(true)\n ], NodeBase.prototype, \"visible\", void 0);\n __decorate([\n Collection([], PointPort)\n ], NodeBase.prototype, \"ports\", void 0);\n __decorate([\n Property(true)\n ], NodeBase.prototype, \"isExpanded\", void 0);\n __decorate([\n Complex({}, DiagramTooltip)\n ], NodeBase.prototype, \"tooltip\", void 0);\n __decorate([\n Complex({}, IconShape)\n ], NodeBase.prototype, \"expandIcon\", void 0);\n __decorate([\n Complex({}, IconShape)\n ], NodeBase.prototype, \"collapseIcon\", void 0);\n __decorate([\n Property(false)\n ], NodeBase.prototype, \"excludeFromLayout\", void 0);\n __decorate([\n Property()\n ], NodeBase.prototype, \"addInfo\", void 0);\n return NodeBase;\n}(ChildProperty));\nexport { NodeBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty, Collection, Complex } from '@syncfusion/ej2-base';\nimport { Container } from '../core/containers/container';\nimport { Node } from '../objects/node';\nimport { Connector } from '../objects/connector';\nimport { Point } from '../primitives/point';\nimport { Size } from '../primitives/size';\nimport { SelectorConstraints } from '../enum/enum';\nimport { Margin } from '../core/appearance';\n/**\n * Defines the behavior of selector\n */\nvar UserHandle = /** @class */ (function (_super) {\n __extends(UserHandle, _super);\n function UserHandle() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], UserHandle.prototype, \"name\", void 0);\n __decorate([\n Property('')\n ], UserHandle.prototype, \"pathData\", void 0);\n __decorate([\n Property('#000000')\n ], UserHandle.prototype, \"backgroundColor\", void 0);\n __decorate([\n Property('top')\n ], UserHandle.prototype, \"side\", void 0);\n __decorate([\n Property('')\n ], UserHandle.prototype, \"borderColor\", void 0);\n __decorate([\n Property(0.5)\n ], UserHandle.prototype, \"borderWidth\", void 0);\n __decorate([\n Property(25)\n ], UserHandle.prototype, \"size\", void 0);\n __decorate([\n Property('white')\n ], UserHandle.prototype, \"pathColor\", void 0);\n __decorate([\n Property(10)\n ], UserHandle.prototype, \"displacement\", void 0);\n __decorate([\n Property(true)\n ], UserHandle.prototype, \"visible\", void 0);\n __decorate([\n Property(0)\n ], UserHandle.prototype, \"offset\", void 0);\n __decorate([\n Complex({}, Margin)\n ], UserHandle.prototype, \"margin\", void 0);\n __decorate([\n Property('Center')\n ], UserHandle.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Center')\n ], UserHandle.prototype, \"verticalAlignment\", void 0);\n return UserHandle;\n}(ChildProperty));\nexport { UserHandle };\n/**\n * Defines the behavior of the selected objects\n */\nvar Selector = /** @class */ (function (_super) {\n __extends(Selector, _super);\n function Selector() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Initializes the UI of the container\n */\n Selector.prototype.init = function (diagram) {\n var container = new Container();\n container.measureChildren = false;\n var consize = new Size();\n container.children = [];\n if (this.nodes || this.connectors) {\n for (var i = 0; i < this.nodes.length; i++) {\n var node = diagram.nameTable[this.nodes[i].id];\n var wrapper = node.wrapper;\n // this.width = wrapper.actualSize.width; \n // this.height = wrapper.actualSize.height;\n // this.rotateAngle = wrapper.rotateAngle;\n // this.offsetX = wrapper.offsetX;\n // this.offsetY = wrapper.offsetY;\n container.children.push(wrapper);\n }\n for (var j = 0; j < this.connectors.length; j++) {\n var connector = diagram.nameTable[this.connectors[j].id];\n var wrapper = connector.wrapper;\n // this.width = wrapper.actualSize.width; this.height = wrapper.actualSize.height;\n // this.rotateAngle = wrapper.rotateAngle; this.offsetX = wrapper.offsetX;\n // this.offsetY = wrapper.offsetY;\n container.children.push(wrapper);\n }\n }\n this.wrapper = container;\n return container;\n };\n __decorate([\n Property(null)\n ], Selector.prototype, \"wrapper\", void 0);\n __decorate([\n Collection([], Node)\n ], Selector.prototype, \"nodes\", void 0);\n __decorate([\n Collection([], Connector)\n ], Selector.prototype, \"connectors\", void 0);\n __decorate([\n Property()\n ], Selector.prototype, \"width\", void 0);\n __decorate([\n Property()\n ], Selector.prototype, \"height\", void 0);\n __decorate([\n Property(0)\n ], Selector.prototype, \"rotateAngle\", void 0);\n __decorate([\n Property(0)\n ], Selector.prototype, \"offsetX\", void 0);\n __decorate([\n Property(0)\n ], Selector.prototype, \"offsetY\", void 0);\n __decorate([\n Complex({ x: 0.5, y: 0.5 }, Point)\n ], Selector.prototype, \"pivot\", void 0);\n __decorate([\n Property('CompleteIntersect')\n ], Selector.prototype, \"rubberBandSelectionMode\", void 0);\n __decorate([\n Collection([], UserHandle)\n ], Selector.prototype, \"userHandles\", void 0);\n __decorate([\n Property(SelectorConstraints.All)\n ], Selector.prototype, \"constraints\", void 0);\n return Selector;\n}(ChildProperty));\nexport { Selector };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { DiagramElement } from './diagram-element';\nimport { getContent } from '../../utility/dom-util';\n/**\n * HTMLElement defines the basic html elements\n */\nvar DiagramHtmlElement = /** @class */ (function (_super) {\n __extends(DiagramHtmlElement, _super);\n /**\n * set the id for each element\n */\n function DiagramHtmlElement(nodeId, diagramId) {\n var _this = _super.call(this) || this;\n _this.data = '';\n _this.nodeId = '';\n _this.diagramId = '';\n _this.diagramId = diagramId;\n _this.nodeId = nodeId;\n return _this;\n }\n Object.defineProperty(DiagramHtmlElement.prototype, \"content\", {\n /**\n * Gets or sets the geometry of the html element\n */\n get: function () {\n return this.data;\n },\n set: function (value) {\n this.data = value;\n this.template = getContent(this, true);\n this.isDirt = true;\n },\n enumerable: true,\n configurable: true\n });\n return DiagramHtmlElement;\n}(DiagramElement));\nexport { DiagramHtmlElement };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n///
\nimport { Property, Complex, Collection, ChildProperty, ComplexFactory } from '@syncfusion/ej2-base';\nimport { Margin, TextStyle, Shadow } from '../core/appearance';\nimport { Point } from '../primitives/point';\nimport { Size } from '../primitives/size';\nimport { Container } from '../core/containers/container';\nimport { Canvas } from '../core/containers/canvas';\nimport { getBasicShape } from './dictionary/basic-shapes';\nimport { DiagramElement } from '../core/elements/diagram-element';\nimport { PathElement } from '../core/elements/path-element';\nimport { TextElement } from '../core/elements/text-element';\nimport { ImageElement } from '../core/elements/image-element';\nimport { DiagramNativeElement } from '../core/elements/native-element';\nimport { PointPort } from './port';\nimport { ShapeAnnotation } from './annotation';\nimport { getPortShape, getIconShape } from './dictionary/common';\nimport { getFlowShape } from './dictionary/flow-shapes';\nimport { NodeConstraints } from '../enum/enum';\nimport { checkPortRestriction } from './../utility/diagram-util';\nimport { randomId, getFunction } from './../utility/base-util';\nimport { NodeBase } from './node-base';\nimport { canShadow } from './../utility/constraints-util';\nimport { PortVisibility } from '../enum/enum';\nimport { measurePath } from './../utility/dom-util';\nimport { getPolygonPath } from './../utility/path-util';\nimport { DiagramHtmlElement } from '../core/elements/html-element';\nvar getShapeType = function (obj) {\n switch (obj.type) {\n case 'Basic':\n return BasicShape;\n case 'Flow':\n return FlowShape;\n case 'Path':\n return Path;\n case 'Image':\n return Image;\n case 'Text':\n return Text;\n case 'Bpmn':\n return BpmnShape;\n case 'Native':\n return Native;\n case 'HTML':\n return Html;\n default:\n return BasicShape;\n }\n};\n/**\n * Defines the behavior of default shape\n */\nvar Shape = /** @class */ (function (_super) {\n __extends(Shape, _super);\n function Shape() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Basic')\n ], Shape.prototype, \"type\", void 0);\n return Shape;\n}(ChildProperty));\nexport { Shape };\n/**\n * Defines the behavior of path shape\n */\nvar Path = /** @class */ (function (_super) {\n __extends(Path, _super);\n function Path() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Path')\n ], Path.prototype, \"type\", void 0);\n __decorate([\n Property('')\n ], Path.prototype, \"data\", void 0);\n return Path;\n}(Shape));\nexport { Path };\n/**\n * Defines the behavior of Native shape\n */\nvar Native = /** @class */ (function (_super) {\n __extends(Native, _super);\n function Native() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Native')\n ], Native.prototype, \"type\", void 0);\n __decorate([\n Property('')\n ], Native.prototype, \"content\", void 0);\n __decorate([\n Property('Stretch')\n ], Native.prototype, \"scale\", void 0);\n return Native;\n}(Shape));\nexport { Native };\n/**\n * Defines the behavior of html shape\n */\nvar Html = /** @class */ (function (_super) {\n __extends(Html, _super);\n function Html() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('HTML')\n ], Html.prototype, \"type\", void 0);\n __decorate([\n Property('')\n ], Html.prototype, \"content\", void 0);\n return Html;\n}(Shape));\nexport { Html };\n/**\n * Defines the behavior of image shape\n */\nvar Image = /** @class */ (function (_super) {\n __extends(Image, _super);\n function Image() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Image')\n ], Image.prototype, \"type\", void 0);\n __decorate([\n Property('')\n ], Image.prototype, \"source\", void 0);\n __decorate([\n Property('')\n ], Image.prototype, \"scale\", void 0);\n __decorate([\n Property('None')\n ], Image.prototype, \"align\", void 0);\n return Image;\n}(Shape));\nexport { Image };\n/**\n * Defines the behavior of the text shape\n */\nvar Text = /** @class */ (function (_super) {\n __extends(Text, _super);\n function Text() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Text')\n ], Text.prototype, \"type\", void 0);\n __decorate([\n Property('')\n ], Text.prototype, \"content\", void 0);\n __decorate([\n Complex({}, Margin)\n ], Text.prototype, \"margin\", void 0);\n return Text;\n}(Shape));\nexport { Text };\n/**\n * Defines the behavior of the basic shape\n */\nvar BasicShape = /** @class */ (function (_super) {\n __extends(BasicShape, _super);\n function BasicShape() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Basic')\n ], BasicShape.prototype, \"type\", void 0);\n __decorate([\n Property('Rectangle')\n ], BasicShape.prototype, \"shape\", void 0);\n __decorate([\n Property(0)\n ], BasicShape.prototype, \"cornerRadius\", void 0);\n __decorate([\n Collection([], Point)\n ], BasicShape.prototype, \"points\", void 0);\n return BasicShape;\n}(Shape));\nexport { BasicShape };\n/**\n * Defines the behavior of the flow shape\n */\nvar FlowShape = /** @class */ (function (_super) {\n __extends(FlowShape, _super);\n function FlowShape() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Flow')\n ], FlowShape.prototype, \"type\", void 0);\n __decorate([\n Property('Terminator')\n ], FlowShape.prototype, \"shape\", void 0);\n return FlowShape;\n}(Shape));\nexport { FlowShape };\n/**\n * Defines the behavior of the bpmn gateway shape\n */\nvar BpmnGateway = /** @class */ (function (_super) {\n __extends(BpmnGateway, _super);\n function BpmnGateway() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('None')\n ], BpmnGateway.prototype, \"type\", void 0);\n return BpmnGateway;\n}(ChildProperty));\nexport { BpmnGateway };\n/**\n * Defines the behavior of the bpmn data object\n */\nvar BpmnDataObject = /** @class */ (function (_super) {\n __extends(BpmnDataObject, _super);\n function BpmnDataObject() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('None')\n ], BpmnDataObject.prototype, \"type\", void 0);\n __decorate([\n Property(false)\n ], BpmnDataObject.prototype, \"collection\", void 0);\n return BpmnDataObject;\n}(ChildProperty));\nexport { BpmnDataObject };\n/**\n * Defines the behavior of the bpmn task shape\n */\nvar BpmnTask = /** @class */ (function (_super) {\n __extends(BpmnTask, _super);\n function BpmnTask() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('None')\n ], BpmnTask.prototype, \"type\", void 0);\n __decorate([\n Property('None')\n ], BpmnTask.prototype, \"loop\", void 0);\n __decorate([\n Property(false)\n ], BpmnTask.prototype, \"call\", void 0);\n __decorate([\n Property(false)\n ], BpmnTask.prototype, \"compensation\", void 0);\n return BpmnTask;\n}(ChildProperty));\nexport { BpmnTask };\n/**\n * Defines the behavior of the bpmn Event shape\n */\nvar BpmnEvent = /** @class */ (function (_super) {\n __extends(BpmnEvent, _super);\n function BpmnEvent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Start')\n ], BpmnEvent.prototype, \"event\", void 0);\n __decorate([\n Property('None')\n ], BpmnEvent.prototype, \"trigger\", void 0);\n return BpmnEvent;\n}(ChildProperty));\nexport { BpmnEvent };\n/**\n * Defines the behavior of the bpmn sub event\n */\nvar BpmnSubEvent = /** @class */ (function (_super) {\n __extends(BpmnSubEvent, _super);\n function BpmnSubEvent() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('None')\n ], BpmnSubEvent.prototype, \"trigger\", void 0);\n __decorate([\n Property('Start')\n ], BpmnSubEvent.prototype, \"event\", void 0);\n __decorate([\n Property('')\n ], BpmnSubEvent.prototype, \"id\", void 0);\n __decorate([\n Complex({}, Point)\n ], BpmnSubEvent.prototype, \"offset\", void 0);\n __decorate([\n Collection([], ShapeAnnotation)\n ], BpmnSubEvent.prototype, \"annotations\", void 0);\n __decorate([\n Collection([], PointPort)\n ], BpmnSubEvent.prototype, \"ports\", void 0);\n __decorate([\n Property()\n ], BpmnSubEvent.prototype, \"width\", void 0);\n __decorate([\n Property()\n ], BpmnSubEvent.prototype, \"height\", void 0);\n __decorate([\n Complex({}, Margin)\n ], BpmnSubEvent.prototype, \"margin\", void 0);\n __decorate([\n Property('Center')\n ], BpmnSubEvent.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Center')\n ], BpmnSubEvent.prototype, \"verticalAlignment\", void 0);\n __decorate([\n Property(true)\n ], BpmnSubEvent.prototype, \"visible\", void 0);\n return BpmnSubEvent;\n}(ChildProperty));\nexport { BpmnSubEvent };\nvar BpmnTransactionSubProcess = /** @class */ (function (_super) {\n __extends(BpmnTransactionSubProcess, _super);\n function BpmnTransactionSubProcess() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({ id: 'success', event: 'End', offset: { x: 1, y: 0.5 } }, BpmnSubEvent)\n ], BpmnTransactionSubProcess.prototype, \"success\", void 0);\n __decorate([\n Complex({ id: 'failure', event: 'Intermediate', trigger: 'Error', offset: { x: 0.25, y: 1 } }, BpmnSubEvent)\n ], BpmnTransactionSubProcess.prototype, \"failure\", void 0);\n __decorate([\n Complex({ id: 'cancel', event: 'Intermediate', trigger: 'Cancel', offset: { x: 0.75, y: 1 } }, BpmnSubEvent)\n ], BpmnTransactionSubProcess.prototype, \"cancel\", void 0);\n return BpmnTransactionSubProcess;\n}(ChildProperty));\nexport { BpmnTransactionSubProcess };\n/**\n * Defines the behavior of the BPMNSubProcess\n */\nvar BpmnSubProcess = /** @class */ (function (_super) {\n __extends(BpmnSubProcess, _super);\n function BpmnSubProcess() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('None')\n ], BpmnSubProcess.prototype, \"type\", void 0);\n __decorate([\n Property(false)\n ], BpmnSubProcess.prototype, \"adhoc\", void 0);\n __decorate([\n Property('Default')\n ], BpmnSubProcess.prototype, \"boundary\", void 0);\n __decorate([\n Property(false)\n ], BpmnSubProcess.prototype, \"compensation\", void 0);\n __decorate([\n Property('None')\n ], BpmnSubProcess.prototype, \"loop\", void 0);\n __decorate([\n Property(true)\n ], BpmnSubProcess.prototype, \"collapsed\", void 0);\n __decorate([\n Collection([], BpmnSubEvent)\n ], BpmnSubProcess.prototype, \"events\", void 0);\n __decorate([\n Complex({}, BpmnTransactionSubProcess)\n ], BpmnSubProcess.prototype, \"transaction\", void 0);\n __decorate([\n Property(undefined)\n ], BpmnSubProcess.prototype, \"processes\", void 0);\n return BpmnSubProcess;\n}(ChildProperty));\nexport { BpmnSubProcess };\n/**\n * Defines the behavior of the bpmn activity shape\n */\nvar BpmnActivity = /** @class */ (function (_super) {\n __extends(BpmnActivity, _super);\n function BpmnActivity() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Task')\n ], BpmnActivity.prototype, \"activity\", void 0);\n __decorate([\n Complex({}, BpmnTask)\n ], BpmnActivity.prototype, \"task\", void 0);\n __decorate([\n Complex({}, BpmnSubProcess)\n ], BpmnActivity.prototype, \"subProcess\", void 0);\n return BpmnActivity;\n}(ChildProperty));\nexport { BpmnActivity };\n/**\n * Defines the behavior of the bpmn annotation\n */\nvar BpmnAnnotation = /** @class */ (function (_super) {\n __extends(BpmnAnnotation, _super);\n // tslint:disable-next-line:no-any\n function BpmnAnnotation(parent, propName, defaultValue, isArray) {\n return _super.call(this, parent, propName, defaultValue, isArray) || this;\n }\n __decorate([\n Property('')\n ], BpmnAnnotation.prototype, \"text\", void 0);\n __decorate([\n Property('')\n ], BpmnAnnotation.prototype, \"id\", void 0);\n __decorate([\n Property()\n ], BpmnAnnotation.prototype, \"angle\", void 0);\n __decorate([\n Property()\n ], BpmnAnnotation.prototype, \"height\", void 0);\n __decorate([\n Property()\n ], BpmnAnnotation.prototype, \"width\", void 0);\n __decorate([\n Property()\n ], BpmnAnnotation.prototype, \"length\", void 0);\n return BpmnAnnotation;\n}(ChildProperty));\nexport { BpmnAnnotation };\n/**\n * Defines the behavior of the bpmn shape\n */\nvar BpmnShape = /** @class */ (function (_super) {\n __extends(BpmnShape, _super);\n function BpmnShape() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Bpmn')\n ], BpmnShape.prototype, \"type\", void 0);\n __decorate([\n Property('Event')\n ], BpmnShape.prototype, \"shape\", void 0);\n __decorate([\n Complex({}, BpmnEvent)\n ], BpmnShape.prototype, \"event\", void 0);\n __decorate([\n Complex({}, BpmnGateway)\n ], BpmnShape.prototype, \"gateway\", void 0);\n __decorate([\n Complex({}, BpmnDataObject)\n ], BpmnShape.prototype, \"dataObject\", void 0);\n __decorate([\n Complex({}, BpmnActivity)\n ], BpmnShape.prototype, \"activity\", void 0);\n __decorate([\n Collection([], BpmnAnnotation)\n ], BpmnShape.prototype, \"annotations\", void 0);\n return BpmnShape;\n}(Shape));\nexport { BpmnShape };\n/**\n * Defines the behavior of nodes\n */\nvar Node = /** @class */ (function (_super) {\n __extends(Node, _super);\n // tslint:disable-next-line:no-any\n function Node(parent, propName, defaultValue, isArray) {\n var _this = _super.call(this, parent, propName, defaultValue, isArray) || this;\n /** @private */\n _this.parentId = '';\n /** @private */\n _this.processId = '';\n /** @private */\n _this.outEdges = [];\n /** @private */\n _this.inEdges = [];\n return _this;\n }\n Object.defineProperty(Node.prototype, \"actualSize\", {\n /** @private */\n get: function () {\n if (this.wrapper !== null) {\n return this.wrapper.actualSize;\n }\n else {\n return new Size(this.width || 0, this.height || 0);\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Allows to initialize the UI of a node\n */\n /** @private */\n /* tslint:disable */\n Node.prototype.init = function (diagram) {\n var content = new DiagramElement();\n var textStyle;\n var changedProperties = 'changedProperties';\n var oldProperties = 'oldProperties';\n this.shape[changedProperties] = {};\n this.shape[oldProperties] = {};\n switch (this.shape.type) {\n case 'Path':\n var pathContent = new PathElement();\n pathContent.data = this.shape.data;\n content = pathContent;\n break;\n case 'Image':\n var imageContent = new ImageElement();\n imageContent.source = this.shape.source;\n imageContent.imageAlign = this.shape.align;\n imageContent.imageScale = this.shape.scale;\n content = imageContent;\n break;\n case 'Text':\n var textContent = new TextElement();\n textContent.content = this.shape.content;\n content = textContent;\n textStyle = this.style;\n content.style = textStyle;\n break;\n case 'Basic':\n if (this.shape.shape === 'Rectangle') {\n var basicshape = new DiagramElement();\n content = basicshape;\n content.cornerRadius = this.shape.cornerRadius;\n }\n else if (this.shape.shape === 'Polygon') {\n var path = new PathElement();\n path.data = getPolygonPath(this.shape.points);\n content = path;\n }\n else {\n var basicshape = new PathElement();\n var basicshapedata = getBasicShape(this.shape.shape);\n basicshape.data = basicshapedata;\n content = basicshape;\n }\n break;\n case 'Flow':\n var flowshape = new PathElement();\n var flowshapedata = getFlowShape(this.shape.shape);\n flowshape.data = flowshapedata;\n content = flowshape;\n break;\n case 'Bpmn':\n if (diagram.bpmnModule) {\n content = diagram.bpmnModule.initBPMNContent(content, this, diagram);\n var subProcess = this.shape.activity.subProcess;\n if (subProcess.processes && subProcess.processes.length) {\n var children = this.shape.activity.subProcess.processes;\n for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {\n var i = children_1[_i];\n if (diagram.nameTable[i] && (!diagram.nameTable[i].processId || diagram.nameTable[i].processId === this.id)) {\n diagram.nameTable[i].processId = this.id;\n if (subProcess.collapsed) {\n diagram.updateElementVisibility(diagram.nameTable[i].wrapper, diagram.nameTable[i], !subProcess.collapsed);\n }\n content.children.push(diagram.nameTable[i].wrapper);\n }\n }\n }\n }\n break;\n case 'Native':\n var nativeContent = new DiagramNativeElement(this.id, diagram.element.id);\n nativeContent.content = this.shape.content;\n nativeContent.scale = this.shape.scale;\n content = nativeContent;\n break;\n case 'HTML':\n var htmlContent = new DiagramHtmlElement(this.id, diagram.element.id);\n htmlContent.content = this.shape.content;\n content = htmlContent;\n break;\n }\n content.id = this.id + '_content';\n content.relativeMode = 'Object';\n if (this.width !== undefined) {\n content.width = this.width;\n }\n content.horizontalAlignment = 'Stretch';\n if (this.height !== undefined) {\n content.height = this.height;\n }\n if (this.minHeight !== undefined) {\n content.minHeight = this.minHeight;\n }\n if (this.maxHeight !== undefined) {\n content.maxHeight = this.maxHeight;\n }\n if (this.minWidth !== undefined) {\n content.minWidth = this.minWidth;\n }\n if (this.maxWidth !== undefined) {\n content.maxWidth = this.maxWidth;\n }\n if (this.shape.shape === 'Rectangle' && !this.shape.cornerRadius) {\n content.isRectElement = true;\n }\n content.verticalAlignment = 'Stretch';\n if (this.shape instanceof Text) {\n content.margin = this.shape.margin;\n }\n if (canShadow(this)) {\n if ((this.constraints & NodeConstraints.Shadow) !== 0) {\n content.shadow = this.shadow;\n }\n }\n if (this.shape.type !== 'Bpmn' || this.shape.shape === 'Message' ||\n this.shape.shape === 'DataSource') {\n if (this.shape.type !== 'Text') {\n content.style = this.style;\n }\n }\n return content;\n };\n /* tslint:enable */\n /** @private */\n Node.prototype.initContainer = function () {\n if (!this.id) {\n this.id = randomId();\n }\n // Creates canvas element\n var canvas = this.children ? new Container() : new Canvas();\n canvas.id = this.id;\n canvas.offsetX = this.offsetX;\n canvas.offsetY = this.offsetY;\n canvas.visible = this.visible;\n canvas.style.fill = this.backgroundColor;\n canvas.style.strokeColor = this.borderColor;\n canvas.style.strokeWidth = this.borderWidth;\n canvas.rotateAngle = this.rotateAngle;\n canvas.minHeight = this.minHeight;\n canvas.minWidth = this.minWidth;\n canvas.maxHeight = this.maxHeight;\n canvas.maxWidth = this.maxWidth;\n canvas.pivot = this.pivot;\n canvas.margin = this.margin;\n this.wrapper = canvas;\n return canvas;\n };\n /** @private */\n Node.prototype.initPorts = function (accessibilityContent, container) {\n var canvas = this.wrapper;\n var port;\n for (var i = 0; this.ports !== undefined, i < this.ports.length; i++) {\n port = this.initPortWrapper(this.ports[i]);\n // tslint:disable-next-line:no-any\n var wrapperContent = void 0;\n var contentAccessibility = getFunction(accessibilityContent);\n if (contentAccessibility) {\n wrapperContent = contentAccessibility(port, this);\n }\n port.description = wrapperContent ? wrapperContent : port.id;\n container.children.push(port);\n }\n };\n Node.prototype.getIconOffet = function (layout, icon) {\n var x;\n var y;\n if (layout.orientation === 'BottomToTop') {\n x = icon.offset.x;\n y = 1 - icon.offset.y;\n }\n else if (layout.orientation === 'LeftToRight') {\n x = icon.offset.y;\n y = icon.offset.x;\n }\n else if (layout.orientation === 'RightToLeft') {\n x = 1 - icon.offset.y;\n y = icon.offset.x;\n }\n else {\n x = icon.offset.x;\n y = icon.offset.y;\n }\n return { x: x, y: y };\n };\n /** @private */\n Node.prototype.initIcons = function (accessibilityContent, layout, container, diagramId) {\n var canvas = this.wrapper;\n var offset;\n var icon = this.isExpanded ? this.expandIcon : this.collapseIcon;\n if (icon.shape !== 'None') {\n var iconContainer = new Canvas();\n iconContainer.float = true;\n var children = [];\n iconContainer.id = this.id + '_icon_content';\n iconContainer.children = children;\n iconContainer.height = icon.height;\n iconContainer.width = icon.width;\n iconContainer.style.strokeColor = 'transparent';\n iconContainer.margin = icon.margin;\n iconContainer.horizontalAlignment = 'Center';\n iconContainer.verticalAlignment = 'Center';\n iconContainer.visible = this.visible;\n offset = this.getIconOffet(layout, icon);\n iconContainer.setOffsetWithRespectToBounds(offset.x, offset.y, 'Fraction');\n iconContainer.relativeMode = 'Point';\n this.initIconSymbol(icon, iconContainer, accessibilityContent, diagramId);\n // tslint:disable-next-line:no-any\n var wrapperContent = void 0;\n var contentAccessibility = getFunction(accessibilityContent);\n if (contentAccessibility) {\n wrapperContent = contentAccessibility(icon, this);\n }\n iconContainer.description = wrapperContent ? wrapperContent : iconContainer.id;\n container.children.push(iconContainer);\n }\n };\n /** @private */\n Node.prototype.initAnnotations = function (accessibilityContent, container) {\n var annotation;\n for (var i = 0; this.annotations !== undefined, i < this.annotations.length; i++) {\n annotation = this.initAnnotationWrapper(this.annotations[i]);\n // tslint:disable-next-line:no-any\n var wrapperContent = void 0;\n var contentAccessibility = getFunction(accessibilityContent);\n if (contentAccessibility) {\n wrapperContent = contentAccessibility(annotation, this);\n }\n annotation.description = wrapperContent ? wrapperContent : annotation.id;\n container.children.push(annotation);\n }\n };\n /** @private */\n Node.prototype.initPortWrapper = function (ports) {\n ports.id = ports.id || randomId();\n // Creates port element\n var portContent = new PathElement();\n portContent.height = ports.height;\n portContent.width = ports.width;\n var pathdata = (ports.shape === 'Custom') ? ports.pathData : getPortShape(ports.shape);\n portContent.id = this.id + '_' + (ports.id);\n portContent.margin = ports.margin;\n portContent.data = pathdata;\n var style = ports.style;\n portContent.style = {\n fill: style.fill, strokeColor: style.strokeColor, gradient: null,\n opacity: style.opacity, strokeDashArray: style.strokeDashArray, strokeWidth: style.strokeWidth\n };\n portContent.horizontalAlignment = ports.horizontalAlignment;\n portContent.verticalAlignment = ports.verticalAlignment;\n portContent.setOffsetWithRespectToBounds(ports.offset.x, ports.offset.y, 'Fraction');\n if (this.width !== undefined || this.height !== undefined) {\n portContent.float = true;\n }\n portContent.relativeMode = 'Point';\n portContent.visible = checkPortRestriction(ports, PortVisibility.Visible) &&\n !checkPortRestriction(ports, PortVisibility.Hover) && !checkPortRestriction(ports, PortVisibility.Connect) ? true : false;\n return portContent;\n };\n /** @private */\n Node.prototype.initAnnotationWrapper = function (annotation) {\n annotation.id = annotation.id || randomId();\n var label = annotation;\n var annotationcontent = new TextElement();\n annotationcontent.constraints = annotation.constraints;\n annotationcontent.height = annotation.height;\n annotationcontent.width = annotation.width;\n annotationcontent.visible = annotation.visibility;\n annotationcontent.id = this.id + '_' + annotation.id;\n var style = annotation.style;\n var link = annotation.hyperlink.link ? annotation.hyperlink : undefined;\n annotationcontent.style = {\n fill: style.fill, strokeColor: style.strokeColor, strokeWidth: style.strokeWidth,\n bold: style.bold, textWrapping: style.textWrapping,\n color: link ? link.color || annotationcontent.hyperlink.color : style.color, whiteSpace: style.whiteSpace,\n fontFamily: style.fontFamily, fontSize: style.fontSize, italic: style.italic, gradient: null, opacity: style.opacity,\n strokeDashArray: style.strokeDashArray, textAlign: style.textAlign, textOverflow: annotation.style.textOverflow,\n textDecoration: link ? link.textDecoration || annotationcontent.hyperlink.textDecoration : style.textDecoration,\n };\n annotationcontent.hyperlink.link = annotation.hyperlink.link || undefined;\n annotationcontent.hyperlink.content = annotation.hyperlink.content || undefined;\n annotationcontent.hyperlink.textDecoration = annotation.hyperlink.textDecoration || undefined;\n annotationcontent.content = link ? link.content || annotationcontent.hyperlink.link : annotation.content;\n if (this.width !== undefined) {\n annotationcontent.width = this.width - annotation.margin.left - annotation.margin.right;\n }\n annotationcontent.margin = annotation.margin;\n annotationcontent.horizontalAlignment = annotation.horizontalAlignment;\n annotationcontent.verticalAlignment = annotation.verticalAlignment;\n annotationcontent.setOffsetWithRespectToBounds(label.offset.x, label.offset.y, 'Fraction');\n if (this.width !== undefined || this.height !== undefined) {\n annotationcontent.float = true;\n }\n annotationcontent.relativeMode = 'Point';\n return annotationcontent;\n };\n Node.prototype.initIconContainer = function (options, iconContainer) {\n var rect = new DiagramElement();\n rect.id = iconContainer.id + '_rect';\n rect.height = options.height;\n rect.width = options.width;\n rect.visible = iconContainer.visible;\n rect.margin = options.margin;\n rect.cornerRadius = options.cornerRadius;\n rect.style = {\n fill: options.fill, strokeColor: options.borderColor,\n strokeWidth: options.borderWidth\n };\n rect.setOffsetWithRespectToBounds(0.5, 0.5, 'Fraction');\n rect.horizontalAlignment = 'Center';\n rect.verticalAlignment = 'Center';\n rect.relativeMode = 'Object';\n rect.description = rect.description || 'Click here to expand or collapse';\n return rect;\n };\n Node.prototype.initIconSymbol = function (options, iconContainer, accessibilityContent, diagramId) {\n var iconContent;\n iconContainer.children.push(this.initIconContainer(options, iconContainer));\n if (options.shape === 'Template') {\n iconContent = new DiagramNativeElement(this.id, diagramId);\n iconContent.content = options.content;\n iconContent.height = 10;\n iconContent.width = 10;\n }\n else {\n iconContent = new PathElement();\n iconContent.data = getIconShape(options);\n var iconContentBounds = measurePath(iconContent.data);\n iconContent.height =\n iconContentBounds.height < 10 ? iconContentBounds.height : 10 - (options.padding.bottom + options.padding.top);\n iconContent.width =\n iconContentBounds.width < 10 ? iconContentBounds.width : 10 - (options.padding.left + options.padding.right);\n }\n iconContent.id = iconContainer.id + '_shape';\n iconContent.horizontalAlignment = 'Center';\n iconContent.verticalAlignment = 'Center';\n iconContent.visible = iconContainer.visible;\n iconContent.visible = iconContainer.visible;\n iconContent.style = {\n fill: 'black', strokeColor: options.borderColor,\n strokeWidth: options.borderWidth\n };\n iconContent.setOffsetWithRespectToBounds(0.5, 0.5, 'Fraction');\n iconContent.relativeMode = 'Object';\n iconContent.description = iconContainer.description || 'Click here to expand or collapse';\n iconContainer.children.push(iconContent);\n };\n __decorate([\n Collection([], ShapeAnnotation)\n ], Node.prototype, \"annotations\", void 0);\n __decorate([\n Property(0)\n ], Node.prototype, \"offsetX\", void 0);\n __decorate([\n Property(0)\n ], Node.prototype, \"offsetY\", void 0);\n __decorate([\n Complex({ x: 0.5, y: 0.5 }, Point)\n ], Node.prototype, \"pivot\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"width\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"height\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"minWidth\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"minHeight\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"maxWidth\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"maxHeight\", void 0);\n __decorate([\n Property(0)\n ], Node.prototype, \"rotateAngle\", void 0);\n __decorate([\n Complex({}, TextStyle)\n ], Node.prototype, \"style\", void 0);\n __decorate([\n Property('transparent')\n ], Node.prototype, \"backgroundColor\", void 0);\n __decorate([\n Property('none')\n ], Node.prototype, \"borderColor\", void 0);\n __decorate([\n Property(0)\n ], Node.prototype, \"borderWidth\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"data\", void 0);\n __decorate([\n ComplexFactory(getShapeType)\n ], Node.prototype, \"shape\", void 0);\n __decorate([\n Property(null)\n ], Node.prototype, \"wrapper\", void 0);\n __decorate([\n Property(NodeConstraints.Default)\n ], Node.prototype, \"constraints\", void 0);\n __decorate([\n Complex({}, Shadow)\n ], Node.prototype, \"shadow\", void 0);\n __decorate([\n Property()\n ], Node.prototype, \"children\", void 0);\n return Node;\n}(NodeBase));\nexport { Node };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property } from '@syncfusion/ej2-base';\nimport { createSvgElement, setAttributeSvg } from '../diagram/utility/dom-util';\nimport { Size } from '../diagram/primitives/size';\nimport { getFunction } from '../diagram/utility/base-util';\n/**\n * Represents the Ruler component that measures the Diagram objects, indicate positions, and align Diagram elements.\n * ```html\n *
Show Ruler
\n * ```\n * ```typescript\n * \n * ```\n */\nvar Ruler = /** @class */ (function (_super) {\n __extends(Ruler, _super);\n /**\n * Constructor for creating the Ruler Component\n */\n function Ruler(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.offset = 0;\n _this.scale = 1;\n return _this;\n }\n /**\n * Initializes the values of private members.\n * @private\n */\n Ruler.prototype.preRender = function () {\n this.unWireEvents();\n this.wireEvents();\n };\n /**\n * Renders the rulers.\n * @private\n */\n Ruler.prototype.render = function () {\n this.updateRulerGeometry();\n };\n /**\n * Core method to return the component name.\n * @private\n */\n Ruler.prototype.getModuleName = function () {\n return 'Ruler';\n };\n /**\n * To destroy the ruler\n * @return {void}\n */\n Ruler.prototype.destroy = function () {\n this.unWireEvents();\n this.notify('destroy', {});\n _super.prototype.destroy.call(this);\n this.element.classList.remove('e-ruler');\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @return {string}\n */\n Ruler.prototype.getPersistData = function () {\n var keyEntity = ['loaded'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Refreshes the ruler when the Ruler properties are updated\n * @param options\n */\n Ruler.prototype.onPropertyChanged = function (newProp, oldProp) {\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'length':\n case 'interval':\n case 'segmentWidth':\n case 'tickAlignment':\n case 'markerColor':\n case 'thickness':\n this.updateRuler();\n break;\n }\n }\n };\n Ruler.prototype.updateRulerGeometry = function () {\n this.element.style.textAlign = 'left';\n this.renderRulerSpace();\n this.updateRuler();\n };\n Ruler.prototype.renderRulerSpace = function () {\n var rulerGeometry = this.getRulerGeometry();\n var div = document.getElementById(this.element.id + '_ruler_space');\n if (!div) {\n div = document.createElement('div');\n div.setAttribute('id', this.element.id + '_ruler_space');\n div.style.height = rulerGeometry.height + 'px';\n div.style.width = rulerGeometry.width + 'px';\n div.style.cssFloat = 'left';\n this.element.appendChild(div);\n }\n return div;\n };\n Ruler.prototype.updateRuler = function () {\n var rulerSize = this.getRulerSize();\n var rulerGeometry = this.getRulerGeometry();\n var length = 0;\n var offset = 0;\n var availableSize = new Size();\n var svg = this.getRulerSVG(rulerGeometry);\n if (svg) {\n length = this.length;\n availableSize.height = rulerSize;\n offset = this.offset;\n if (length && length !== Infinity) {\n var unitLength = length + this.segmentWidth;\n var unitOffset = offset;\n this.updateSegments(unitOffset, (unitLength + Math.abs(unitOffset)), svg, rulerSize);\n }\n }\n };\n Ruler.prototype.updateSegments = function (start, end, svg, rulerSize) {\n var run = start;\n var trans = { trans: 0 };\n while (run < end) {\n var rulerSegment = this.getNewSegment(run, svg);\n if (rulerSegment) {\n svg.appendChild(rulerSegment.segment);\n run = this.updateSegment(start, end, rulerSegment, run, trans, rulerSize);\n }\n }\n };\n Ruler.prototype.updateSegment = function (start, end, rulerSegment, run, trans, rulerSize) {\n var segWidth = this.updateSegmentWidth(this.scale);\n if (run === start) {\n this.startValue = Math.floor(start / segWidth) * segWidth / this.scale;\n this.startValue = (this.startValue % 1) !== 0 ? Number((this.startValue).toFixed(1)) : this.startValue;\n rulerSegment.label.textContent = this.startValue.toString();\n this.defStartValue = run = this.startValue * this.scale;\n if (this.orientation === 'Horizontal') {\n this.hRulerOffset = start - run;\n }\n else {\n this.vRulerOffset = start - run;\n }\n }\n else {\n this.startValue = (run / this.scale);\n this.startValue = (this.startValue % 1) !== 0 ? Number((this.startValue).toFixed(1)) : this.startValue;\n rulerSegment.label.textContent = this.startValue.toString();\n }\n this.updateTickLabel(rulerSegment, rulerSize);\n var translate = (this.orientation === 'Horizontal') ? ((trans.trans + 0.5) + ',0.5') : ('0.5,' + (trans.trans + 0.5));\n rulerSegment.segment.setAttribute('transform', 'translate(' + translate + ')');\n trans.trans += segWidth;\n run += segWidth;\n return run;\n };\n Ruler.prototype.updateTickLabel = function (rulerSegment, rulerSize) {\n var bBox = rulerSegment.segment.lastChild.getBBox();\n var isHorizontal = (this.orientation === 'Horizontal') ? true : false;\n var isRightOrBottom = (this.tickAlignment === 'RightOrBottom') ? true : false;\n var x = isHorizontal ? 2 : 0;\n var y = isHorizontal ? (isRightOrBottom ? (rulerSize / 2 + (11 / 2) - (11 / 2)) :\n (rulerSize / 2 + (11 / 2))) : bBox.height;\n var translate = isRightOrBottom ? (-(bBox.width + 2) + ',' + ((rulerSize / 2) - bBox.height)) :\n (-(bBox.width + 2) + ',' + ((rulerSize / 2) - bBox.height / 2));\n var attr = isHorizontal ? { 'x': x, 'y': y } :\n { 'x': x, 'y': y, 'transform': 'rotate(270)' + 'translate(' + translate + ')' };\n setAttributeSvg(rulerSegment.segment.lastChild, attr);\n };\n Ruler.prototype.getNewSegment = function (run, svg) {\n var segment = this.createNewTicks(run, svg);\n var label = this.createTickLabel(svg, segment);\n return { segment: segment, label: label };\n };\n Ruler.prototype.createNewTicks = function (run, svg) {\n var tick;\n var tickInterval;\n var segmentWidth = this.updateSegmentWidth(this.scale);\n var g;\n var attr = { 'class': 'e-ruler-segment' };\n g = createSvgElement('g', attr);\n for (var i = 0; i < this.interval; i++) {\n tickInterval = segmentWidth / this.interval;\n tick = this.createTick(svg, tickInterval, i + 1, run);\n g.appendChild(tick);\n }\n return g;\n };\n Ruler.prototype.getLinePoint = function (svg, tickInterval, length) {\n var segmentWidth = this.updateSegmentWidth(this.scale);\n var rulerSize = this.getRulerSize();\n tickInterval = tickInterval * (length - 1);\n length = ((tickInterval % segmentWidth) === 0) ? rulerSize : rulerSize * 0.3;\n return length;\n };\n Ruler.prototype.createTick = function (svg, tickInterval, length, run) {\n var ruler;\n var line;\n var linePoint = this.getLinePoint(svg, tickInterval, length);\n var rulerSize = this.getRulerSize();\n var args;\n var attr;\n var isHorizontal = (this.orientation === 'Horizontal') ? true : false;\n var isRightOrBottom = (this.tickAlignment === 'RightOrBottom') ? true : false;\n var arrangeTick = getFunction(this.arrangeTick);\n args = { ruler: ruler, tickLength: linePoint, tickInterval: ((this.segmentWidth / this.interval) * (length - 1)) };\n if (arrangeTick) {\n arrangeTick(args);\n }\n linePoint = args.tickLength;\n var point = tickInterval * (length - 1);\n var x1 = isHorizontal ? point : (isRightOrBottom ? rulerSize : 0);\n var x2 = isHorizontal ? point : (isRightOrBottom ? (rulerSize - linePoint) : (rulerSize - (rulerSize - linePoint)));\n var y1 = isHorizontal ? (isRightOrBottom ? rulerSize : (rulerSize - (rulerSize - linePoint))) : point;\n var y2 = isHorizontal ? (isRightOrBottom ? (rulerSize - linePoint) : 0) : point;\n attr = { 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2, 'stroke-width': '1', 'stroke': 'black' };\n line = createSvgElement('line', attr);\n line.setAttribute('class', 'e-ruler-tick');\n return line;\n };\n Ruler.prototype.createTickLabel = function (svg, segment) {\n var text;\n if (segment) {\n var attr = { 'class': 'e-ruler-tick-label' };\n text = createSvgElement('text', attr);\n segment.appendChild(text);\n }\n return text;\n };\n /**\n * @private\n * @param scale\n */\n Ruler.prototype.updateSegmentWidth = function (scale) {\n if (this.segmentWidth !== 100) {\n return this.segmentWidth;\n }\n var five = 25;\n var multiples = 1;\n var div;\n var scaleRound;\n var fifty = 100;\n scaleRound = Math.pow(2, Math.round(Math.log(scale) / Math.log(2)));\n div = fifty;\n div = (fifty / scaleRound);\n while (div > 100) {\n multiples /= 10;\n div /= 10;\n }\n while (div < 25) {\n multiples *= 10;\n div *= 10;\n }\n if (div >= five && div % five !== 0) {\n div = Math.round(div / five) * five;\n }\n return div * scale / multiples;\n };\n Ruler.prototype.createMarkerLine = function (rulerSvg, rulerObj, attr) {\n var line;\n if (rulerObj) {\n line = rulerSvg.getElementById(rulerObj.id + '_marker');\n if (line) {\n line.parentNode.removeChild(line);\n }\n line = createSvgElement('line', attr);\n }\n return line;\n };\n /**\n * @private\n * @param rulerObj\n * @param currentPoint\n */\n Ruler.prototype.drawRulerMarker = function (rulerObj, currentPoint, offset) {\n var rulerSvg;\n var rulerSize;\n var scale;\n var diff;\n var i;\n var attr;\n var line;\n var isHorizontal = this.orientation === 'Horizontal' ? true : false;\n var rulerSvgElements = rulerObj.getElementsByTagName('svg');\n for (i = 0; i < rulerSvgElements.length; i++) {\n if (rulerSvgElements[i]) {\n rulerSvg = rulerSvgElements[i];\n }\n break;\n }\n if (rulerSvg) {\n rulerSize = this.getRulerSize();\n attr = {\n 'id': rulerObj.id + '_marker', 'x1': 0, 'y1': 0, 'x2': (isHorizontal ? 0 : rulerSize),\n 'y2': (isHorizontal ? rulerSize : 0), 'stroke': this.markerColor, 'stroke-width': 1.5,\n 'class': 'e-d-ruler-marker'\n };\n line = this.createMarkerLine(rulerSvg, rulerObj, attr);\n scale = this.scale;\n diff = this.offset - this.defStartValue;\n var point = isHorizontal ? currentPoint.x : currentPoint.y;\n var move = (point * scale) + offset + diff;\n line.setAttribute('transform', 'translate(' + (isHorizontal ? ((move + 0.5) + ' 0.5') : ('0.5 ' + (move + 0.5))) + ')');\n rulerSvg.appendChild(line);\n }\n };\n Ruler.prototype.getRulerGeometry = function () {\n return new Size(this.element ? this.element.getBoundingClientRect().width : 0, this.element ? this.element.getBoundingClientRect().height : 0);\n };\n Ruler.prototype.getRulerSize = function () {\n return this.thickness;\n };\n Ruler.prototype.getRulerSVG = function (rulerGeometry) {\n var rulerSpace;\n var rulerSize = this.getRulerSize();\n var svg;\n if (this.element) {\n rulerSpace = document.getElementById(this.element.id + '_ruler_space');\n if (rulerSpace) {\n var attr = {\n 'id': this.element.id + '_Ruler_svg',\n width: this.orientation === 'Horizontal' ? (rulerGeometry.width + 200) : rulerSize + 'px',\n height: this.orientation === 'Horizontal' ? rulerSize : (rulerGeometry.height + 200) + 'px',\n style: 'position:inherit;'\n };\n svg = createSvgElement('svg', attr);\n if (rulerSpace.childNodes.length > 0) {\n for (var i = rulerSpace.childNodes.length - 1; i >= 0; i--) {\n rulerSpace.childNodes[i].parentNode.removeChild(rulerSpace.childNodes[i]);\n }\n }\n rulerSpace.appendChild(svg);\n }\n }\n return svg;\n };\n /**\n * Method to bind events for the ruler\n */\n Ruler.prototype.wireEvents = function () {\n //wire Events\n };\n /**\n * Method to unbind events for the ruler\n */\n Ruler.prototype.unWireEvents = function () {\n //unWire Events\n };\n __decorate([\n Property(5)\n ], Ruler.prototype, \"interval\", void 0);\n __decorate([\n Property(100)\n ], Ruler.prototype, \"segmentWidth\", void 0);\n __decorate([\n Property('Horizontal')\n ], Ruler.prototype, \"orientation\", void 0);\n __decorate([\n Property('RightOrBottom')\n ], Ruler.prototype, \"tickAlignment\", void 0);\n __decorate([\n Property('red')\n ], Ruler.prototype, \"markerColor\", void 0);\n __decorate([\n Property(25)\n ], Ruler.prototype, \"thickness\", void 0);\n __decorate([\n Property(null)\n ], Ruler.prototype, \"arrangeTick\", void 0);\n __decorate([\n Property(400)\n ], Ruler.prototype, \"length\", void 0);\n return Ruler;\n}(Component));\nexport { Ruler };\n","import { Size } from './../primitives/size';\nimport { Point } from './../primitives/point';\nimport { processPathData, pathSegmentCollection, getRectanglePath } from './../utility/path-util';\nimport { overFlow } from './../utility/base-util';\n/**\n * Canvas Renderer\n */\n/** @private */\nvar CanvasRenderer = /** @class */ (function () {\n function CanvasRenderer() {\n }\n CanvasRenderer.getContext = function (canvas) {\n return canvas.getContext('2d');\n };\n CanvasRenderer.setCanvasSize = function (canvas, width, height) {\n if (canvas) {\n canvas.setAttribute('width', width.toString());\n canvas.setAttribute('height', height.toString());\n }\n };\n ;\n CanvasRenderer.prototype.renderGradient = function (options, ctx, x, y) {\n var max;\n var min;\n var grd;\n if (options.gradient.type !== 'None') {\n for (var i = 0; i < options.gradient.stops.length; i++) {\n max = max !== undefined ? options.gradient.stops[i].offset : Math.max(max, options.gradient.stops[i].offset);\n min = min !== undefined ? options.gradient.stops[i].offset : Math.min(min, options.gradient.stops[i].offset);\n }\n if (options.gradient.type === 'Linear') {\n var linear = options.gradient;\n grd = ctx.createLinearGradient(x + linear.x1, y + linear.y1, x + linear.x2, y + linear.y2);\n }\n else {\n var radial = options.gradient;\n grd = ctx.createRadialGradient(x + radial.fx, y + radial.fy, 0, x + radial.cx, y + radial.cy, radial.r);\n }\n for (var i = 0; i < options.gradient.stops.length; i++) {\n var stop_1 = options.gradient.stops[i];\n var offset = min < 0 ? (max + stop_1.offset) / (2 * max) : stop_1.offset / max;\n grd.addColorStop(offset, stop_1.color);\n }\n ctx.fillStyle = grd;\n }\n return ctx;\n };\n CanvasRenderer.prototype.renderShadow = function (options, canvas, collection) {\n if (collection === void 0) { collection = null; }\n var ctx = CanvasRenderer.getContext(canvas);\n ctx.save();\n ctx.beginPath();\n ctx.strokeStyle = ctx.fillStyle = options.shadow.color;\n ctx.globalAlpha = options.shadow.opacity;\n var ptModel = { x: 0, y: 0 };\n var point = Point.transform(ptModel, options.shadow.angle, options.shadow.distance);\n var transX = options.x + point.x;\n var transY = options.y + point.y;\n var pivotX = transX + options.width * options.pivotX;\n var pivotY = transY + options.height * options.pivotY;\n this.rotateContext(canvas, options.angle, pivotX, pivotY);\n if (collection) {\n ctx.translate(transX, transY);\n this.renderPath(canvas, options, collection);\n ctx.translate(-transX, -transY);\n }\n else {\n ctx.rect(transX, transY, options.width, options.height);\n ctx.fillRect(transX, transY, options.width, options.height);\n }\n ctx.fill();\n ctx.stroke();\n ctx.closePath();\n ctx.restore();\n };\n CanvasRenderer.createCanvas = function (id, width, height) {\n var canvasObj = document.createElement('canvas');\n canvasObj.setAttribute('id', id);\n this.setCanvasSize(canvasObj, width, height);\n return canvasObj;\n };\n ;\n CanvasRenderer.prototype.setStyle = function (canvas, style) {\n var ctx = CanvasRenderer.getContext(canvas);\n if (style.fill === 'none') {\n style.fill = 'transparent';\n }\n if (style.stroke === 'none') {\n style.stroke = 'transparent';\n }\n ctx.strokeStyle = style.stroke;\n ctx.lineWidth = style.strokeWidth;\n if (style.strokeWidth === 0) {\n ctx.strokeStyle = 'transparent';\n }\n ctx.globalAlpha = style.opacity;\n var dashArray = [];\n if (style.dashArray) {\n dashArray = this.parseDashArray(style.dashArray);\n }\n ctx.setLineDash(dashArray);\n if (style.gradient && style.gradient.type !== 'None') {\n this.renderGradient(style, ctx, 0, 0);\n }\n else {\n ctx.fillStyle = style.fill;\n }\n };\n CanvasRenderer.prototype.rotateContext = function (canvas, angle, x, y) {\n var ctx = CanvasRenderer.getContext(canvas);\n ctx.translate(x, y);\n ctx.rotate(angle * Math.PI / 180);\n ctx.translate(-x, -y);\n };\n CanvasRenderer.prototype.setFontStyle = function (canvas, text) {\n var ctx = CanvasRenderer.getContext(canvas);\n var font = '';\n if (text.italic) {\n font += 'italic ';\n }\n if (text.bold) {\n font += 'bold ';\n }\n font += (text.fontSize) + 'px ';\n font += text.fontFamily;\n ctx.font = font;\n };\n CanvasRenderer.prototype.parseDashArray = function (dashArray) {\n var dashes = [];\n var separator = dashArray.indexOf(' ') !== -1 ? ' ' : ',';\n var splittedDashes = dashArray.split(separator);\n for (var _i = 0, splittedDashes_1 = splittedDashes; _i < splittedDashes_1.length; _i++) {\n var i = splittedDashes_1[_i];\n dashes.push(Number(i));\n }\n return dashes;\n };\n //Rendering Part\n CanvasRenderer.prototype.drawRectangle = function (canvas, options) {\n if (options.visible === true) {\n if (options.cornerRadius) {\n options.data = getRectanglePath(options.cornerRadius, options.height, options.width);\n this.drawPath(canvas, options);\n }\n else {\n var ctx = CanvasRenderer.getContext(canvas);\n if (options.shadow) {\n this.renderShadow(options, canvas);\n }\n ctx.save();\n ctx.beginPath();\n var cornerRadius = options.cornerRadius;\n var pivotX = options.x + options.width * options.pivotX;\n var pivotY = options.y + options.height * options.pivotY;\n this.rotateContext(canvas, options.angle, pivotX, pivotY);\n this.setStyle(canvas, options);\n ctx.rect(options.x, options.y, options.width, options.height);\n ctx.fillRect(options.x, options.y, options.width, options.height);\n ctx.fill();\n ctx.stroke();\n ctx.closePath();\n ctx.restore();\n }\n }\n };\n // public updateSelectionRegion(canvas: HTMLCanvasElement, options: RectAttributes): void {\n // this.drawRectangle(canvas, options);\n // }\n // public drawLine(canvas: HTMLCanvasElement, options: LineAttributes): void {\n // let ctx: CanvasRenderingContext2D = CanvasRenderer.getContext(canvas);\n // ctx.save();\n // ctx.beginPath();\n // let pivotX: number = options.x + options.width * options.pivotX;\n // let pivotY: number = options.y + options.height * options.pivotY;\n // this.rotateContext(canvas, options.angle, pivotX, pivotY);\n // this.setStyle(canvas, options as StyleAttributes);\n // ctx.translate(options.x, options.y);\n // ctx.moveTo(options.startPoint.x, options.startPoint.y);\n // ctx.lineTo(options.endPoint.x, options.endPoint.y);\n // ctx.translate(-options.x, -options.y);\n // ctx.stroke();\n // ctx.closePath();\n // ctx.restore();\n // }\n // public drawCircle(canvas: HTMLCanvasElement, options: CircleAttributes): void {\n // let ctx: CanvasRenderingContext2D = CanvasRenderer.getContext(canvas);\n // ctx.save();\n // ctx.beginPath();\n // let pivotY: number = options.y + options.height * options.pivotY;\n // let pivotX: number = options.x + options.width * options.pivotX;\n // this.setStyle(canvas, options as StyleAttributes);\n // this.rotateContext(canvas, options.angle, pivotX, pivotY);\n // ctx.arc(options.centerX, options.centerY, options.radius, 0, 2 * Math.PI);\n // ctx.fill();\n // ctx.stroke();\n // ctx.closePath();\n // ctx.restore();\n // }\n CanvasRenderer.prototype.drawPath = function (canvas, options) {\n var collection = [];\n collection = processPathData(options.data);\n collection = pathSegmentCollection(collection);\n if (options.shadow) {\n this.renderShadow(options, canvas, collection);\n }\n var ctx = CanvasRenderer.getContext(canvas);\n ctx.save();\n ctx.beginPath();\n var pivotY = options.y + options.height * options.pivotY;\n var pivotX = options.x + options.width * options.pivotX;\n this.rotateContext(canvas, options.angle, pivotX, pivotY);\n this.setStyle(canvas, options);\n ctx.translate(options.x, options.y);\n this.renderPath(canvas, options, collection);\n ctx.fill();\n ctx.translate(-options.x, -options.y);\n ctx.stroke();\n ctx.restore();\n };\n CanvasRenderer.prototype.renderPath = function (canvas, options, collection) {\n if (options.visible === true) {\n var ctx = CanvasRenderer.getContext(canvas);\n var x0 = void 0;\n var y0 = void 0;\n var x1 = void 0;\n var y1 = void 0;\n var x2 = void 0;\n var y2 = void 0;\n var x = void 0;\n var y = void 0;\n var length_1;\n var i = void 0;\n var newSeg = void 0;\n var segs = collection;\n for (x = 0, y = 0, i = 0, length_1 = segs.length; i < length_1; ++i) {\n var obj = segs[i];\n var seg = obj;\n var char = seg.command;\n if ('x1' in seg) {\n x1 = seg.x1;\n }\n if ('x2' in seg) {\n x2 = seg.x2;\n }\n if ('y1' in seg) {\n y1 = seg.y1;\n }\n if ('y2' in seg) {\n y2 = seg.y2;\n }\n if ('x' in seg) {\n x = seg.x;\n }\n if ('y' in seg) {\n y = seg.y;\n }\n switch (char) {\n case 'M':\n ctx.moveTo(x, y);\n seg.x = x;\n seg.y = y;\n break;\n case 'L':\n ctx.lineTo(x, y);\n seg.x = x;\n seg.y = y;\n break;\n case 'C':\n ctx.bezierCurveTo(x1, y1, x2, y2, x, y);\n seg.x = x;\n seg.y = y;\n seg.x1 = x1;\n seg.y1 = y1;\n seg.x2 = x2;\n seg.y2 = y2;\n break;\n case 'Q':\n ctx.quadraticCurveTo(x1, y1, x, y);\n seg.x = x;\n seg.y = y;\n seg.x1 = x1;\n seg.y1 = y1;\n break;\n case 'A':\n var curr = { x: x0, y: y0 };\n var rx = seg.r1;\n var ry = seg.r2;\n var xAxisRotation = seg.angle * (Math.PI / 180.0);\n var largeArc = seg.largeArc;\n var sweep = seg.sweep;\n var cp = { x: x, y: y };\n var currp = {\n x: Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,\n y: -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0\n };\n var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2);\n if (l > 1) {\n rx *= Math.sqrt(l);\n ry *= Math.sqrt(l);\n }\n var k = (Math.pow(ry, 2) * Math.pow(currp.x, 2));\n var s = (largeArc === sweep ? -1 : 1) * Math.sqrt(((Math.pow(rx, 2) * Math.pow(ry, 2)) - (Math.pow(rx, 2) * Math.pow(currp.y, 2)) - k) /\n (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2)));\n if (isNaN(s)) {\n s = 0;\n }\n var cpp = { x: s * rx * currp.y / ry, y: s * -ry * currp.x / rx };\n var centp = {\n x: (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,\n y: (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y\n };\n var a1 = this.a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]);\n var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry];\n var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry];\n var ad = this.a(u, v);\n if (this.r(u, v) <= -1) {\n ad = Math.PI;\n }\n if (this.r(u, v) >= 1) {\n ad = 0;\n }\n var dir = !sweep ? -1.0 : 1.0;\n var ah = a1 + dir * (ad / 2.0);\n var halfWay = {\n x: centp.x + rx * Math.cos(ah),\n y: centp.y + ry * Math.sin(ah)\n };\n seg.centp = centp;\n seg.xAxisRotation = xAxisRotation;\n seg.rx = rx;\n seg.ry = ry;\n seg.a1 = a1;\n seg.ad = ad;\n seg.sweep = sweep;\n if (ctx != null) {\n var ra = rx > ry ? rx : ry;\n var sx = rx > ry ? 1 : rx / ry;\n var sy = rx > ry ? ry / rx : 1;\n ctx.save();\n ctx.translate(centp.x, centp.y);\n ctx.rotate(xAxisRotation);\n ctx.scale(sx, sy);\n ctx.arc(0, 0, ra, a1, a1 + ad, !sweep);\n ctx.scale(1 / sx, 1 / sy);\n ctx.rotate(-xAxisRotation);\n ctx.translate(-centp.x, -centp.y);\n ctx.restore();\n }\n break;\n case 'Z':\n case 'z':\n ctx.closePath();\n x = x0;\n y = y0;\n break;\n }\n x0 = x;\n y0 = y;\n }\n }\n };\n CanvasRenderer.prototype.drawText = function (canvas, options) {\n if (options.content && options.visible === true) {\n var ctx = CanvasRenderer.getContext(canvas);\n ctx.save();\n this.setStyle(canvas, options);\n var pivotX = options.x + options.width * options.pivotX;\n var pivotY = options.y + options.height * options.pivotY;\n this.rotateContext(canvas, options.angle, pivotX, pivotY);\n this.setFontStyle(canvas, options);\n var i = 0;\n var childNodes = [];\n childNodes = options.childNodes;\n var wrapBounds = options.wrapBounds;\n ctx.fillStyle = options.color;\n if (wrapBounds) {\n var position = this.labelAlign(options, wrapBounds, childNodes);\n for (i = 0; i < childNodes.length; i++) {\n var child = childNodes[i];\n var offsetX = position.x + child.x - wrapBounds.x;\n var offsetY = position.y + child.dy * i + ((options.fontSize) * 0.8);\n if (wrapBounds.width > options.width && options.textOverflow !== 'Wrap') {\n child.text = overFlow(child.text, options);\n }\n ctx.fillText(child.text, offsetX, offsetY);\n if (options.textDecoration === 'Underline'\n || options.textDecoration === 'Overline'\n || options.textDecoration === 'LineThrough') {\n var startPointX = offsetX;\n var startPointY = void 0;\n var textlength = ctx.measureText(child.text).width;\n var endPointX = offsetX + textlength;\n var endPointY = void 0;\n switch (options.textDecoration) {\n case 'Underline':\n startPointY = offsetY + 2;\n endPointY = offsetY + 2;\n break;\n case 'Overline':\n startPointY = (position.y + child.dy * i);\n endPointY = (position.y + child.dy * i);\n break;\n case 'LineThrough':\n startPointY = ((offsetY + position.y + child.dy * i) / 2) + 2;\n endPointY = ((offsetY + position.y + child.dy * i) / 2) + 2;\n }\n ctx.beginPath();\n ctx.moveTo(startPointX, startPointY);\n ctx.lineTo(endPointX, endPointY);\n ctx.strokeStyle = options.color;\n ctx.lineWidth = options.fontSize * .08;\n ctx.globalAlpha = options.opacity;\n ctx.stroke();\n }\n }\n }\n ctx.restore();\n }\n };\n CanvasRenderer.prototype.drawImage = function (canvas, obj) {\n var _this = this;\n if (obj.visible) {\n var ctx_1 = CanvasRenderer.getContext(canvas);\n ctx_1.save();\n var pivotX = obj.x + obj.width * obj.pivotX;\n var pivotY = obj.y + obj.height * obj.pivotY;\n var imageObj = new Image();\n imageObj.src = obj.source;\n /**\n * Since Clipping portion for node with slice option is not calculated properly\n * if (obj.sourceX !== undefined && obj.sourceY !== undefined && obj.sourceWidth !== undefined\n * && obj.sourceHeight !== undefined) {\n * ctx.drawImage(imageObj, obj.sourceX, obj.sourceY, obj.sourceWidth, obj.sourceHeight, obj.x, obj.y, obj.width, obj.height);\n * } else {\n * ctx.drawImage(imageObj, obj.x, obj.y, obj.width, obj.height);\n * }\n */\n imageObj.onload = function () {\n ctx_1.rotate(obj.angle * Math.PI / 180);\n var image = new Image();\n image.src = obj.source;\n _this.image(ctx_1, image, obj.x, obj.y, obj.width, obj.height, obj);\n ctx_1.rotate(-(obj.angle * Math.PI / 180));\n };\n ctx_1.restore();\n }\n };\n CanvasRenderer.prototype.image = function (ctx, image, x, y, width, height, alignOptions) {\n ctx.beginPath();\n var srcWidth = image.width;\n var srcHeight = image.height;\n var destinationW = width;\n var destinationH = height;\n var resultWidth = 0;\n var resultHeight = 0;\n if (alignOptions && alignOptions.alignment !== 'None') {\n var xalign = alignOptions.alignment.toLowerCase().substr(1, 3);\n var yalign = alignOptions.alignment.toLowerCase().substr(5, 3);\n if (alignOptions.scale === 'Slice') {\n var a = function () {\n resultWidth = destinationW;\n resultHeight = srcHeight * destinationW / srcWidth;\n };\n var b = function () {\n resultWidth = srcWidth * destinationH / srcHeight;\n resultHeight = destinationH;\n };\n if (destinationW > destinationH) {\n a();\n if (destinationH > resultHeight) {\n b();\n }\n }\n else if (destinationW === destinationH) {\n if (srcWidth > srcHeight) {\n b();\n }\n else {\n a();\n }\n }\n else {\n b();\n if (destinationW > resultWidth) {\n a();\n }\n }\n var x1 = this.getSliceOffset(xalign, resultWidth, destinationW, srcWidth);\n var y1 = this.getSliceOffset(yalign, resultHeight, destinationH, srcHeight);\n var sWidth = srcWidth - x1;\n var sHeight = srcHeight - y1;\n var dWidth = resultWidth - (x1 * (resultWidth / srcWidth));\n var dHeight = resultHeight - (y1 * (resultHeight / srcHeight));\n var canvas1 = document.createElement('canvas');\n canvas1.setAttribute('width', width.toString());\n canvas1.setAttribute('height', height.toString());\n var ctx1 = canvas1.getContext('2d');\n ctx1.drawImage(image, x1, y1, sWidth, sHeight, 0, 0, dWidth, dHeight);\n ctx.drawImage(canvas1, x, y, width, height);\n }\n else if (alignOptions.scale === 'Meet') {\n var srcRatio = (srcHeight / srcWidth);\n var destRatio = (destinationH / destinationW);\n resultWidth = destRatio > srcRatio ? destinationW : destinationH / srcRatio;\n resultHeight = destRatio > srcRatio ? destinationW * srcRatio : destinationH;\n x += this.getMeetOffset(xalign, resultWidth, destinationW);\n y += this.getMeetOffset(yalign, resultHeight, destinationH);\n ctx.drawImage(image, 0, 0, srcWidth, srcHeight, x, y, resultWidth, resultHeight);\n }\n else {\n ctx.drawImage(image, x, y, width, height);\n }\n }\n else {\n ctx.drawImage(image, x, y, width, height);\n }\n ctx.closePath();\n };\n CanvasRenderer.prototype.getSliceOffset = function (arg, res, dest, src) {\n switch (arg) {\n case 'min': return 0;\n case 'mid': return (res - dest) / 2 * src / res;\n case 'max': return (res - dest) * src / res;\n default: return 0;\n }\n };\n CanvasRenderer.prototype.getMeetOffset = function (arg, res, dest) {\n var max = Math.max(res, dest);\n var min = Math.min(res, dest);\n switch (arg) {\n case 'min': return 0;\n case 'mid': return (max - min) / 2;\n case 'max': return max - min;\n default: return 0;\n }\n };\n //end region\n // vector magnitude\n CanvasRenderer.prototype.m = function (v) { return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)); };\n // ratio between two vectors\n CanvasRenderer.prototype.r = function (u, v) { return (u[0] * v[0] + u[1] * v[1]) / (this.m(u) * this.m(v)); };\n // angle between two vectors\n CanvasRenderer.prototype.a = function (u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(this.r(u, v)); };\n // text utility\n CanvasRenderer.prototype.labelAlign = function (text, wrapBounds, childNodes) {\n var bounds = new Size(wrapBounds.width, childNodes.length * (text.fontSize));\n var position = { x: 0, y: 0 };\n var labelX = text.x;\n var labelY = text.y;\n var offsetx = text.width * 0.5;\n var offsety = text.height * 0.5;\n var pointx = offsetx;\n var pointy = offsety;\n if (text.textAlign === 'left') {\n pointx = 0;\n }\n else if (text.textAlign === 'center') {\n if (wrapBounds.width > text.width && (text.textOverflow === 'Ellipsis' || text.textOverflow === 'Clip')) {\n pointx = 0;\n }\n else {\n pointx = text.width * 0.5;\n }\n }\n else if (text.textAlign === 'right') {\n pointx = (text.width * 1);\n }\n position.x = labelX + pointx + (wrapBounds ? wrapBounds.x : 0);\n position.y = labelY + pointy - bounds.height / 2;\n return position;\n };\n return CanvasRenderer;\n}());\nexport { CanvasRenderer };\n","import { Point } from './../primitives/point';\nimport { Size } from './../primitives/size';\nimport { pathSegmentCollection, processPathData } from './../utility/path-util';\nimport { setAttributeSvg } from './../utility/dom-util';\nimport { overFlow, wordBreakToString } from './../utility/base-util';\nimport { CanvasRenderer } from './../rendering/canvas-renderer';\nimport { createSvgElement, createHtmlElement, getBackgroundLayerSvg } from '../utility/dom-util';\n/**\n * SVG Renderer\n */\n/** @private */\nvar SvgRenderer = /** @class */ (function () {\n function SvgRenderer() {\n }\n SvgRenderer.prototype.renderShadow = function (options, canvas, collection, parentSvg) {\n if (collection === void 0) { collection = null; }\n var pointModel = { x: 0, y: 0 };\n var point = Point.transform(pointModel, options.shadow.angle, options.shadow.distance);\n var tX = options.x + point.x;\n var tY = options.y + point.y;\n var pivotX = tX + options.width * options.pivotX;\n var pivotY = tY + options.height * options.pivotY;\n var type;\n var shadowElement;\n if (parentSvg) {\n shadowElement = parentSvg.getElementById(canvas.id + '_shadow');\n }\n if (!shadowElement) {\n type = collection ? 'path' : 'rect';\n shadowElement = document.createElementNS('http://www.w3.org/2000/svg', type);\n canvas.appendChild(shadowElement);\n }\n var attr = {\n 'id': canvas.id + '_shadow', 'fill': options.shadow.color, 'stroke': options.shadow.color,\n 'opacity': options.shadow.opacity.toString(),\n 'transform': 'rotate(' + options.angle + ',' + (options.x + options.width * options.pivotX) + ','\n + (options.y + options.height * options.pivotY) + ')' +\n 'translate(' + (options.x + point.x) + ',' + (options.y + point.y) + ')'\n };\n if (parentSvg) {\n var svgContainer = parentSvg.getElementById(canvas.id);\n if (svgContainer) {\n svgContainer.insertBefore(shadowElement, svgContainer.firstChild);\n }\n }\n setAttributeSvg(shadowElement, attr);\n if (!collection) {\n setAttributeSvg(shadowElement, { 'width': options.width, 'height': options.height });\n }\n else if (collection) {\n this.renderPath(shadowElement, options, collection);\n }\n };\n SvgRenderer.prototype.parseDashArray = function (dashArray) {\n var dashes = [];\n return dashes;\n };\n SvgRenderer.prototype.drawRectangle = function (svg, options, diagramId, onlyRect, isSelector, parentSvg, ariaLabel) {\n if (options.shadow && !onlyRect) {\n this.renderShadow(options, svg, undefined, parentSvg);\n }\n var id;\n if (options.id === svg.id) {\n id = options.id + '_container';\n }\n else {\n id = options.id;\n }\n var rect;\n if (parentSvg) {\n rect = parentSvg.getElementById(id);\n }\n if (!rect || isSelector) {\n rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');\n svg.appendChild(rect);\n }\n var shadowElement;\n if (parentSvg && !options.shadow) {\n shadowElement = parentSvg.getElementById(options.id + '_groupElement_shadow');\n if (shadowElement) {\n shadowElement.parentNode.removeChild(shadowElement);\n }\n }\n var attr = {\n 'id': id, 'x': options.x.toString(), 'y': options.y.toString(), 'width': options.width.toString(),\n 'height': options.height.toString(), 'visibility': options.visible ? 'visible' : 'hidden',\n 'transform': 'rotate(' + options.angle + ','\n + (options.x + options.width * options.pivotX) + ',' + (options.y + options.height * options.pivotY) + ')',\n 'rx': options.cornerRadius || 0, 'ry': options.cornerRadius || 0, 'opacity': options.opacity,\n 'aria-label': ariaLabel ? ariaLabel : ''\n };\n if (options.class) {\n attr['class'] = options.class;\n }\n var poiterEvents = 'pointer-events';\n if (!ariaLabel) {\n attr[poiterEvents] = 'none';\n }\n setAttributeSvg(rect, attr);\n this.setSvgStyle(rect, options, diagramId);\n };\n SvgRenderer.prototype.updateSelectionRegion = function (gElement, options) {\n var rect;\n rect = gElement.parentNode.getElementById(options.id);\n var attr;\n attr = {\n 'id': options.id, 'x': options.x.toString(), 'y': options.y.toString(), 'width': options.width.toString(),\n 'height': options.height.toString(), 'transform': 'rotate(' + options.angle + ','\n + (options.x + options.width * options.pivotX) + ',' + (options.y + options.height * options.pivotY) + ')',\n class: 'e-diagram-selected-region'\n };\n if (!rect) {\n rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');\n gElement.appendChild(rect);\n }\n this.setSvgStyle(rect, options);\n setAttributeSvg(rect, attr);\n };\n SvgRenderer.prototype.createGElement = function (elementType, attribute) {\n var gElement = createSvgElement(elementType, attribute);\n return gElement;\n };\n /** @private */\n SvgRenderer.prototype.drawLine = function (gElement, options) {\n var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n this.setSvgStyle(line, options);\n var pivotX = options.x + options.width * options.pivotX;\n var pivotY = options.y + options.height * options.pivotY;\n var kk = '';\n var attr = {\n 'id': options.id,\n 'x1': options.startPoint.x + options.x,\n 'y1': options.startPoint.y + options.y,\n 'x2': options.endPoint.x + options.x,\n 'y2': options.endPoint.y + options.y,\n 'stroke': options.stroke,\n 'stroke-width': options.strokeWidth.toString(), 'opacity': options.opacity.toString(),\n 'transform': 'rotate(' + options.angle + ' ' + pivotX + ' ' + pivotY + ')',\n 'visibility': options.visible ? 'visible' : 'hidden',\n };\n if (options.class) {\n attr['class'] = options.class;\n }\n setAttributeSvg(line, attr);\n gElement.appendChild(line);\n };\n /** @private */\n SvgRenderer.prototype.drawCircle = function (gElement, options, enableSelector, ariaLabel) {\n var circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');\n this.setSvgStyle(circle, options);\n var classval = options.class || '';\n if (!enableSelector) {\n classval += ' e-disabled';\n }\n var attr = {\n 'id': options.id,\n 'cx': options.centerX,\n 'cy': options.centerY,\n 'r': options.radius,\n 'visibility': options.visible ? 'visible' : 'hidden',\n 'class': classval,\n 'aria-label': ariaLabel ? ariaLabel['aria-label'] : ''\n };\n circle.style.display = options.visible ? 'block' : 'none';\n setAttributeSvg(circle, attr);\n gElement.appendChild(circle);\n };\n SvgRenderer.prototype.drawPath = function (svg, options, diagramId, isSelector, parentSvg, ariaLabel) {\n var id;\n var x = Math.floor((Math.random() * 10) + 1);\n id = svg.id + '_shape' + x.toString();\n var collection = [];\n collection = processPathData(options.data);\n collection = pathSegmentCollection(collection);\n if (options.shadow) {\n this.renderShadow(options, svg, collection, parentSvg);\n }\n var shadowElement;\n if (parentSvg && !options.shadow) {\n shadowElement = parentSvg.getElementById(options.id + '_groupElement_shadow');\n if (shadowElement) {\n shadowElement.parentNode.removeChild(shadowElement);\n }\n }\n var path;\n if (parentSvg) {\n path = parentSvg.getElementById(options.id);\n }\n if (!path || isSelector) {\n path = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n svg.appendChild(path);\n }\n this.renderPath(path, options, collection);\n var attr = {\n 'id': options.id, 'transform': 'rotate(' + options.angle + ',' + (options.x + options.width * options.pivotX) + ','\n + (options.y + options.height * options.pivotY) + ')' + 'translate(' + (options.x) + ',' + (options.y) + ')',\n 'visibility': options.visible ? 'visible' : 'hidden', 'opacity': options.opacity,\n 'aria-label': ariaLabel ? ariaLabel : ''\n };\n if (options.class) {\n attr['class'] = options.class;\n }\n setAttributeSvg(path, attr);\n this.setSvgStyle(path, options, diagramId);\n };\n SvgRenderer.prototype.renderPath = function (svg, options, collection) {\n var x1;\n var y1;\n var x2;\n var y2;\n var x;\n var y;\n var length;\n var i;\n var segments = collection;\n var d = '';\n for (x = 0, y = 0, i = 0, length = segments.length; i < length; ++i) {\n var obj = segments[i];\n var segment = obj;\n var char = segment.command;\n if ('x1' in segment) {\n x1 = segment.x1;\n }\n if ('x2' in segment) {\n x2 = segment.x2;\n }\n if ('y1' in segment) {\n y1 = segment.y1;\n }\n if ('y2' in segment) {\n y2 = segment.y2;\n }\n if ('x' in segment) {\n x = segment.x;\n }\n if ('y' in segment) {\n y = segment.y;\n }\n switch (char) {\n case 'M':\n d = d + 'M' + x.toString() + ',' + y.toString() + ' ';\n break;\n case 'L':\n d = d + 'L' + x.toString() + ',' + y.toString() + ' ';\n break;\n case 'C':\n d = d + 'C' + x1.toString() + ',' + y1.toString() + ',' + x2.toString() + ',' + y2.toString() + ',';\n d += x.toString() + ',' + y.toString() + ' ';\n break;\n case 'Q':\n d = d + 'Q' + x1.toString() + ',' + y1.toString() + ',' + x.toString() + ',' + y.toString() + ' ';\n break;\n case 'A':\n d = d + 'A' + segment.r1.toString() + ',' + segment.r2.toString() + ',' + segment.angle.toString() + ',';\n d += segment.largeArc.toString() + ',' + segment.sweep + ',' + x.toString() + ',' + y.toString() + ' ';\n break;\n case 'Z':\n case 'z':\n d = d + 'Z' + ' ';\n break;\n }\n }\n svg.setAttribute('d', d);\n };\n SvgRenderer.prototype.setSvgFontStyle = function (text, options) {\n text.style.fontStyle = options.italic ? 'italic' : 'normal';\n text.style.fontWeight = options.bold ? 'bold' : 'normal';\n text.style.fontSize = options.fontSize.toString() + 'px';\n text.style.fontFamily = options.fontFamily;\n };\n SvgRenderer.prototype.drawText = function (canvas, options, parentSvg, ariaLabel, diagramId) {\n if (options.content !== undefined) {\n var textNode = void 0;\n var childNodes = void 0;\n var wrapBounds = void 0;\n var position = void 0;\n var child = void 0;\n var tspanElement = void 0;\n var offsetX = 0;\n var offsetY = 0;\n var i = 0;\n var text = void 0;\n if (parentSvg) {\n text = parentSvg.getElementById(options.id + '_text');\n }\n if (text) {\n if (options.doWrap) {\n while (text.firstChild) {\n text.removeChild(text.firstChild);\n }\n }\n }\n else {\n options.doWrap = true;\n text = document.createElementNS('http://www.w3.org/2000/svg', 'text');\n if (options.whiteSpace === 'pre-wrap') {\n text.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');\n }\n canvas.appendChild(text);\n }\n var pivotX = options.x + options.width * options.pivotX;\n var pivotY = options.y + options.height * options.pivotY;\n if (options.doWrap) {\n this.setSvgStyle(text, options, diagramId);\n this.setSvgFontStyle(text, options);\n textNode = document.createTextNode(options.content);\n childNodes = options.childNodes;\n wrapBounds = options.wrapBounds;\n position = this.svgLabelAlign(options, wrapBounds, childNodes);\n if (wrapBounds.width > options.width && options.textOverflow !== 'Wrap') {\n childNodes[0].text = overFlow(options.content, options);\n }\n for (i = 0; i < childNodes.length; i++) {\n tspanElement = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');\n textNode = document.createTextNode(childNodes[i].text);\n child = childNodes[i];\n offsetX = position.x + child.x - wrapBounds.x;\n offsetY = position.y + child.dy * (i) + ((options.fontSize) * 0.8);\n setAttributeSvg(tspanElement, { 'x': offsetX.toString(), 'y': offsetY.toString() });\n text.setAttribute('fill', child.text);\n tspanElement.appendChild(textNode);\n text.appendChild(tspanElement);\n }\n }\n if (options.textDecoration && options.textDecoration === 'LineThrough') {\n options.textDecoration = wordBreakToString(options.textDecoration);\n }\n var attr = {\n 'id': options.id + '_text', 'fill': options.color, 'visibility': options.visible ? 'visible' : 'hidden',\n 'text-decoration': options.textDecoration, 'transform': 'rotate(' + options.angle + ','\n + (pivotX) + ',' + (pivotY) + ')'\n + 'translate(' + (options.x) + ',' + (options.y) + ')', 'opacity': options.opacity,\n 'aria-label': ariaLabel ? ariaLabel : ''\n };\n setAttributeSvg(text, attr);\n }\n };\n SvgRenderer.prototype.drawImage = function (canvas, obj, parentSvg) {\n var id = obj.id + '_image';\n var image;\n if (parentSvg) {\n image = parentSvg.getElementById(obj.id + 'image');\n }\n if (!image) {\n image = document.createElementNS('http://www.w3.org/2000/svg', 'image');\n canvas.appendChild(image);\n }\n var imageObj = new Image();\n imageObj.src = obj.source;\n var scale = obj.scale !== 'None' ? obj.scale : '';\n var imgAlign = obj.alignment;\n var aspectRatio = imgAlign.charAt(0).toLowerCase() + imgAlign.slice(1);\n if (scale) {\n aspectRatio += ' ' + scale.charAt(0).toLowerCase() + scale.slice(1);\n }\n var attr = {\n 'id': obj.id + 'image', 'x': obj.x.toString(), 'y': obj.y.toString(), 'transform': 'rotate(' + obj.angle + ','\n + (obj.x + obj.width * obj.pivotX) + ',' + (obj.y + obj.height * obj.pivotY) + ')',\n 'width': obj.width.toString(), 'visibility': obj.visible ? 'visible' : 'hidden',\n 'height': obj.height.toString(), 'preserveAspectRatio': aspectRatio\n };\n setAttributeSvg(image, attr);\n image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', imageObj.src.toString());\n };\n /** @private */\n SvgRenderer.prototype.drawHTMLContent = function (element, canvas, transform) {\n var htmlElement;\n if (canvas) {\n var i = void 0;\n for (i = 0; i < canvas.childNodes.length; i++) {\n if (canvas.childNodes[i].id === element.id + '_html_element') {\n htmlElement = canvas.childNodes[i];\n }\n }\n }\n if (!htmlElement) {\n var attr = {\n 'id': element.id + '_html_element',\n 'class': 'foreign-object'\n };\n htmlElement = createHtmlElement('div', attr);\n htmlElement.appendChild(element.template.cloneNode(true));\n canvas.appendChild(htmlElement);\n }\n htmlElement.setAttribute('style', 'height:' + (element.actualSize.height) + 'px; width:' + (element.actualSize.width) +\n 'px;left:' + (element.corners.x) + 'px; top:' + ((element.corners.y)) + 'px;' +\n 'position:absolute;transform:rotate(' + element.parentTransform + 'deg);' +\n 'pointer-events:all;visibility:' + ((element.visible) ? 'visible' : 'hidden') + ';');\n };\n /** @private */\n SvgRenderer.prototype.drawNativeContent = function (element, canvas, height, width, parentSvg) {\n var nativeElement;\n var clipPath;\n if (parentSvg) {\n nativeElement = parentSvg.getElementById(element.id + '_native_element');\n clipPath = parentSvg.getElementById(element.id + '_clip');\n }\n if (!nativeElement) {\n nativeElement = document.createElementNS('http://www.w3.org/2000/svg', 'g');\n nativeElement.setAttribute('id', element.id + '_native_element');\n nativeElement.appendChild(element.template.cloneNode(true));\n canvas.appendChild(nativeElement);\n }\n if (clipPath) {\n nativeElement.removeChild(clipPath);\n }\n nativeElement.setAttribute('style', 'visibility:' + ((element.visible) ? 'visible' : 'hidden') + ';');\n this.setNativTransform(element, nativeElement, height, width);\n if (element.scale === 'Slice') {\n this.drawClipPath(element, nativeElement, height, width, parentSvg);\n }\n setAttributeSvg(nativeElement, element.description ? { 'aria-label': element.description } : {});\n };\n SvgRenderer.prototype.setNativTransform = function (element, nativeElement, height, width) {\n var contentWidth = element.contentSize.width !== 0 ? element.contentSize.width : 1;\n var contentHeight = element.contentSize.height !== 0 ? element.contentSize.height : 1;\n var x = element.templatePosition.x * width / contentWidth;\n var y = element.templatePosition.y * height / contentHeight;\n nativeElement.setAttribute('transform', 'rotate(' + element.parentTransform + ',' + element.offsetX + ',' + element.offsetY +\n ') translate(' + (element.offsetX - x - width * element.pivot.x) + ',' + (element.offsetY - y - height * element.pivot.y) +\n ') scale(' + (width / contentWidth) + ',' + (height / contentHeight) + ')');\n };\n /**\n * used to crop the given native element into a rectangle of the given size\n * @private\n * @param node\n * @param group\n * @param height\n * @param width\n * @param parentSvg\n */\n SvgRenderer.prototype.drawClipPath = function (node, group, height, width, parentSvg) {\n var contentWidth = node.contentSize.width;\n var contentHeight = node.contentSize.height;\n var actualWidth = node.actualSize.width;\n var actualHeight = node.actualSize.height;\n var clipWidth = node.width / (width / contentWidth);\n var clipHeight = node.height / (height / contentHeight);\n var x = node.templatePosition.x + (node.width >= node.height ? 0 : (contentWidth - clipWidth) / 2);\n var y = node.templatePosition.y + (node.height >= node.width ? 0 : (contentHeight - clipHeight) / 2);\n var clipPath = parentSvg.getElementById(node.id + '_clip');\n clipPath = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath');\n clipPath.setAttribute('id', node.id + '_clip');\n group.appendChild(clipPath);\n var rect = parentSvg.getElementById(node.id + '_clip_rect');\n rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');\n clipPath.appendChild(rect);\n var attr = {\n 'id': node.id + '_clip_rect', 'width': clipWidth.toString(), 'height': clipHeight.toString(),\n 'x': x.toString(), 'y': y.toString()\n };\n setAttributeSvg(rect, attr);\n group.setAttribute('clip-path', 'url(#' + node.id + '_clip)');\n return group;\n };\n SvgRenderer.prototype.renderGradient = function (options, svg, diagramId) {\n var max;\n var min;\n var grd;\n var svgContainer = getBackgroundLayerSvg(diagramId);\n var defs = svgContainer.getElementById(diagramId + 'gradient_pattern');\n if (!defs) {\n defs = createSvgElement('defs', { id: diagramId + 'gradient_pattern' });\n svgContainer.insertBefore(defs, svgContainer.firstChild);\n }\n var radial;\n var linear;\n var stop;\n var offset;\n if (options.gradient.type !== 'None') {\n for (var i = 0; i < options.gradient.stops.length; i++) {\n max = !max ? options.gradient.stops[i].offset : Math.max(max, options.gradient.stops[i].offset);\n min = !min ? options.gradient.stops[i].offset : Math.min(min, options.gradient.stops[i].offset);\n }\n if (options.gradient.type === 'Linear') {\n linear = options.gradient;\n linear.id = svg.id + '_linear';\n grd = svgContainer.getElementById(svg.id + '_linear');\n if (grd) {\n grd.parentNode.removeChild(grd);\n }\n grd = this.createLinearGradient(linear);\n defs.appendChild(grd);\n }\n else {\n radial = options.gradient;\n radial.id = svg.id + '_radial';\n grd = svgContainer.getElementById(svg.id + '_radial');\n grd = svgContainer.getElementById(svg.id + '_linear');\n if (grd) {\n grd.parentNode.removeChild(grd);\n }\n grd = this.createRadialGradient(radial);\n defs.appendChild(grd);\n }\n for (var i = 0; i < options.gradient.stops.length; i++) {\n var stop_1 = options.gradient.stops[i];\n var offset_1 = min < 0 ? (max + stop_1.offset) / (2 * max) : stop_1.offset / max;\n var stopElement = document.createElementNS('http://www.w3.org/2000/svg', 'stop');\n setAttributeSvg(stopElement, { 'offset': offset_1.toString(), 'style': 'stop-color:' + stop_1.color });\n grd.appendChild(stopElement);\n }\n }\n return grd;\n };\n SvgRenderer.prototype.createLinearGradient = function (linear) {\n var lineargradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient');\n var attr = {\n 'id': linear.id, 'x1': linear.x1 + '%', 'y1': linear.y1 + '%', 'x2': linear.x2 + '%', 'y2': linear.y2 + '%'\n };\n setAttributeSvg(lineargradient, attr);\n return lineargradient;\n };\n SvgRenderer.prototype.createRadialGradient = function (radial) {\n var radialgradient = document.createElementNS('http://www.w3.org/2000/svg', 'radialGradient');\n var attr = {\n 'id': radial.id, 'cx': radial.cx + '%', 'cy': radial.cy + '%', 'r': radial.r + '%', 'fx': radial.fx + '%', 'fy': radial.fy + '%'\n };\n setAttributeSvg(radialgradient, attr);\n return radialgradient;\n };\n SvgRenderer.prototype.setSvgStyle = function (svg, style, diagramId) {\n if (style.fill === 'none') {\n style.fill = 'transparent';\n }\n if (style.stroke === 'none') {\n style.stroke = 'transparent';\n }\n var dashArray = [];\n var fill;\n if (style.dashArray !== undefined) {\n var canvasRenderer = new CanvasRenderer();\n dashArray = canvasRenderer.parseDashArray(style.dashArray);\n }\n if (style.gradient && style.gradient.type !== 'None') {\n var grd = this.renderGradient(style, svg, diagramId);\n fill = 'url(#' + grd.id + ')';\n }\n else {\n fill = style.fill;\n }\n if (style.stroke) {\n svg.setAttribute('stroke', style.stroke);\n }\n if (style.strokeWidth !== undefined) {\n svg.setAttribute('stroke-width', style.strokeWidth.toString());\n }\n if (dashArray) {\n svg.setAttribute('stroke-dasharray', dashArray.toString());\n }\n if (fill) {\n svg.setAttribute('fill', fill);\n }\n };\n //end region\n // text utility\n SvgRenderer.prototype.svgLabelAlign = function (text, wrapBound, childNodes) {\n var bounds = new Size(wrapBound.width, childNodes.length * (text.fontSize));\n var pos = { x: 0, y: 0 };\n var x = 0;\n var y = 0;\n var offsetX = text.width * 0.5;\n var offsety = text.height * 0.5;\n var pointX = offsetX;\n var pointY = offsety;\n if (text.textAlign === 'left') {\n pointX = 0;\n }\n else if (text.textAlign === 'center') {\n if (wrapBound.width > text.width && (text.textOverflow === 'Ellipsis' || text.textOverflow === 'Clip')) {\n pointX = 0;\n }\n else {\n pointX = text.width * 0.5;\n }\n }\n else if (text.textAlign === 'right') {\n pointX = (text.width * 1);\n }\n pos.x = x + pointX + (wrapBound ? wrapBound.x : 0);\n pos.y = y + pointY - bounds.height / 2;\n return pos;\n };\n return SvgRenderer;\n}());\nexport { SvgRenderer };\n","import { PathElement } from '../core/elements/path-element';\nimport { ImageElement } from '../core/elements/image-element';\nimport { TextElement } from '../core/elements/text-element';\nimport { Container } from '../core/containers/container';\nimport { rotateMatrix, identityMatrix, transformPointByMatrix } from '../primitives/matrix';\nimport { Size } from '../primitives/size';\nimport { wordBreakToString, whiteSpaceToString, textAlignToString } from '../utility/base-util';\nimport { getUserHandlePosition, canShowCorner } from '../utility/diagram-util';\nimport { getDiagramElement, getAdornerLayer, getGridLayer, getHTMLLayer } from '../utility/dom-util';\nimport { measurePath, getBackgroundLayerSvg, getBackgroundImageLayer, setAttributeSvg } from '../utility/dom-util';\nimport { getDiagramLayer, getExpandCollapseLayer, getPortsLayer, getNativeLayer } from '../utility/dom-util';\nimport { SnapConstraints } from '../enum/enum';\nimport { ThumbsConstraints, SelectorConstraints } from '../enum/enum';\nimport { SvgRenderer } from './svg-renderer';\nimport { CanvasRenderer } from './canvas-renderer';\nimport { processPathData, splitArrayCollection, transformPath } from '../utility/path-util';\nimport { DiagramNativeElement } from '../core/elements/native-element';\nimport { DiagramHtmlElement } from '../core/elements/html-element';\nimport { Point } from '../primitives/point';\n/**\n * Renderer module is used to render basic diagram elements\n */\n/** @private */\nvar DiagramRenderer = /** @class */ (function () {\n function DiagramRenderer(name, svgRender, isSvgMode) {\n this.renderer = null;\n this.isSvgMode = true;\n this.diagramId = name;\n this.element = getDiagramElement(this.diagramId);\n this.svgRenderer = svgRender;\n this.isSvgMode = isSvgMode;\n this.renderer = isSvgMode ? new SvgRenderer() : new CanvasRenderer();\n }\n DiagramRenderer.prototype.setCursor = function (canvas, cursor) {\n canvas.style.cursor = cursor;\n };\n /** @private */\n DiagramRenderer.prototype.setLayers = function () {\n this.iconSvgLayer = this.element.getElementsByClassName('e-ports-expand-layer')[0];\n this.adornerSvgLayer = this.element.getElementsByClassName('e-adorner-layer')[0];\n this.nativeSvgLayer = this.element.getElementsByClassName('e-native-layer')[0];\n this.diagramSvgLayer = this.element.getElementsByClassName('e-diagram-layer')[0];\n };\n DiagramRenderer.prototype.getAdornerLayer = function () {\n var adornerLayer = getAdornerLayer(this.diagramId);\n return adornerLayer;\n };\n DiagramRenderer.prototype.getParentSvg = function (element, targetElement, canvas) {\n if (this.diagramId && element && element.id) {\n if (element.id.split('_icon_content').length > 1 || element.id.split('_nodeport').length > 1) {\n return this.iconSvgLayer;\n }\n if (targetElement && targetElement === 'selector') {\n return this.adornerSvgLayer;\n }\n else if (element instanceof DiagramNativeElement) {\n return this.nativeSvgLayer;\n }\n else {\n return this.diagramSvgLayer;\n }\n }\n return canvas;\n };\n DiagramRenderer.prototype.getParentElement = function (element, defaultParent, svgElement) {\n var layerGElement = defaultParent;\n if (svgElement && this.diagramId && element && element.id) {\n if (element.id.split('_icon_content').length > 1) {\n layerGElement = svgElement.getElementById(this.diagramId + '_diagramExpander');\n defaultParent = null;\n }\n else if (element.id.split('_nodeport').length > 1) {\n layerGElement = svgElement.getElementById(this.diagramId + '_diagramPorts');\n }\n else if (element instanceof DiagramNativeElement) {\n layerGElement = svgElement.getElementById(this.diagramId + '_nativeLayer');\n defaultParent = null;\n }\n else {\n layerGElement = svgElement.getElementById(this.diagramId + '_diagramLayer');\n }\n var groupElement = this.getGroupElement(element, defaultParent || layerGElement);\n layerGElement = groupElement.g;\n if (groupElement.svg) {\n svgElement = groupElement.svg;\n }\n }\n return { g: layerGElement, svg: svgElement };\n };\n DiagramRenderer.prototype.getGroupElement = function (element, canvas) {\n var gElement;\n var parentSvg = this.getParentSvg(element);\n var svgElement;\n if (canvas && parentSvg) {\n if (parentSvg) {\n gElement = parentSvg.getElementById(element.id + '_groupElement');\n if (!gElement && parentSvg !== this.nativeSvgLayer) {\n var nativeSvg = this.nativeSvgLayer;\n gElement = nativeSvg.getElementById(element.id + '_groupElement');\n svgElement = nativeSvg;\n }\n }\n if (!gElement) {\n gElement = this.svgRenderer.createGElement('g', { id: element.id + '_groupElement' });\n canvas.appendChild(gElement);\n }\n }\n return { g: gElement, svg: svgElement };\n };\n DiagramRenderer.prototype.renderElement = function (element, canvas, htmlLayer, transform, parentSvg, createParent) {\n if (element instanceof Container) {\n this.renderContainer(element, canvas, htmlLayer, transform, parentSvg, createParent);\n }\n else if (element instanceof ImageElement) {\n this.renderImageElement(element, canvas, transform, parentSvg);\n }\n else if (element instanceof PathElement) {\n this.renderPathElement(element, canvas, transform, parentSvg);\n }\n else if (element instanceof TextElement) {\n this.renderTextElement(element, canvas, transform, parentSvg);\n }\n else if (element instanceof DiagramNativeElement) {\n this.renderNativeElement(element, canvas, transform, parentSvg);\n }\n else if (element instanceof DiagramHtmlElement) {\n this.renderHTMLElement(element, canvas, htmlLayer, transform, parentSvg);\n }\n else {\n this.renderRect(element, canvas, transform, parentSvg);\n }\n };\n DiagramRenderer.prototype.drawSelectionRectangle = function (x, y, w, h, canvas, t) {\n x = (x + t.tx) * t.scale;\n y = (y + t.ty) * t.scale;\n var options = {\n width: w * t.scale, height: h * t.scale,\n x: x + 0.5, y: y + 0.5, fill: 'transparent', stroke: 'gray', angle: 0,\n pivotX: 0.5, pivotY: 0.5, strokeWidth: 1,\n dashArray: '6 3', opacity: 1,\n visible: true, id: canvas.id + '_selected_region'\n };\n var adornerLayer = this.getAdornerLayer();\n this.svgRenderer.updateSelectionRegion(adornerLayer, options);\n };\n /**\n * @private\n */\n DiagramRenderer.prototype.renderHighlighter = function (element, canvas, transform) {\n var width = element.actualSize.width || 2;\n var height = element.actualSize.height || 2;\n var x = element.offsetX - width * element.pivot.x;\n var y = element.offsetY - height * element.pivot.y;\n x = (x + transform.tx) * transform.scale;\n y = (y + transform.ty) * transform.scale;\n var options = {\n width: width * transform.scale, height: height * transform.scale,\n x: x, y: y, fill: 'transparent', stroke: '#8CC63F', angle: element.rotateAngle,\n pivotX: element.pivot.x, pivotY: element.pivot.y, strokeWidth: 4,\n dashArray: '', opacity: 1, cornerRadius: 0,\n visible: true, id: canvas.id + '_highlighter', class: 'e-diagram-highlighter'\n };\n this.svgRenderer.drawRectangle(canvas, options, this.diagramId);\n };\n DiagramRenderer.prototype.drawLine = function (canvas, options) {\n this.svgRenderer.drawLine(canvas, options);\n };\n DiagramRenderer.prototype.drawPath = function (canvas, options) {\n this.svgRenderer.drawPath(canvas, options, this.diagramId);\n };\n DiagramRenderer.prototype.renderResizeHandle = function (element, canvas, constraints, currentZoom, selectorConstraints, transform, canMask, enableNode) {\n var left = element.offsetX - element.actualSize.width * element.pivot.x;\n var top = element.offsetY - element.actualSize.height * element.pivot.y;\n var height = element.actualSize.height;\n var width = element.actualSize.width;\n if (constraints & ThumbsConstraints.Rotate) {\n this.renderPivotLine(element, canvas, transform, selectorConstraints, canMask);\n this.renderRotateThumb(element, canvas, transform, selectorConstraints, canMask);\n }\n this.renderBorder(element, canvas, transform, enableNode);\n var nodeWidth = element.actualSize.width * currentZoom;\n var nodeHeight = element.actualSize.height * currentZoom;\n if (nodeWidth >= 40 && nodeHeight >= 40) {\n //Hide corners when the size is less than 40\n if (selectorConstraints & SelectorConstraints.ResizeNorthWest) {\n this.renderCircularHandle('resizeNorthWest', element, left, top, canvas, canShowCorner(selectorConstraints, 'ResizeNorthWest'), constraints & ThumbsConstraints.ResizeNorthWest, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on top left side direction' }, undefined, 'e-diagram-resize-handle e-northwest');\n }\n if (selectorConstraints & SelectorConstraints.ResizeNorthEast) {\n this.renderCircularHandle('resizeNorthEast', element, left + width, top, canvas, canShowCorner(selectorConstraints, 'ResizeNorthEast'), constraints & ThumbsConstraints.ResizeNorthEast, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on top right side direction' }, undefined, 'e-diagram-resize-handle e-northeast');\n }\n if (selectorConstraints & SelectorConstraints.ResizeSouthWest) {\n this.renderCircularHandle('resizeSouthWest', element, left, top + height, canvas, canShowCorner(selectorConstraints, 'ResizeSouthWest'), constraints & ThumbsConstraints.ResizeSouthWest, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on bottom left side direction' }, undefined, 'e-diagram-resize-handle e-southwest');\n }\n if (selectorConstraints & SelectorConstraints.ResizeSouthEast) {\n this.renderCircularHandle('resizeSouthEast', element, left + width, top + height, canvas, canShowCorner(selectorConstraints, 'ResizeSouthEast'), constraints & ThumbsConstraints.ResizeSouthEast, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on bottom right side direction' }, undefined, 'e-diagram-resize-handle e-southeast');\n }\n }\n if (selectorConstraints & SelectorConstraints.ResizeNorth) {\n this.renderCircularHandle('resizeNorth', element, left + width / 2, top, canvas, canShowCorner(selectorConstraints, 'ResizeNorth'), constraints & ThumbsConstraints.ResizeNorth, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on top side direction' }, undefined, 'e-diagram-resize-handle e-north');\n }\n if (selectorConstraints & SelectorConstraints.ResizeSouth) {\n this.renderCircularHandle('resizeSouth', element, left + width / 2, top + height, canvas, canShowCorner(selectorConstraints, 'ResizeSouth'), constraints & ThumbsConstraints.ResizeSouth, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on bottom side direction' }, undefined, 'e-diagram-resize-handle e-south');\n }\n if (selectorConstraints & SelectorConstraints.ResizeWest) {\n this.renderCircularHandle('resizeWest', element, left, top + height / 2, canvas, canShowCorner(selectorConstraints, 'ResizeWest'), constraints & ThumbsConstraints.ResizeWest, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on left side direction' }, undefined, 'e-diagram-resize-handle e-west');\n }\n if (selectorConstraints & SelectorConstraints.ResizeEast) {\n this.renderCircularHandle('resizeEast', element, left + width, top + height / 2, canvas, canShowCorner(selectorConstraints, 'ResizeEast'), constraints & ThumbsConstraints.ResizeEast, transform, undefined, canMask, { 'aria-label': 'Thumb to resize the selected object on right side direction' }, undefined, 'e-diagram-resize-handle e-east');\n }\n };\n DiagramRenderer.prototype.renderEndPointHandle = function (selector, canvas, constraints, selectorConstraints, transform, connectedSource, connectedTarget, isSegmentEditing) {\n var sourcePoint = selector.sourcePoint;\n var targetPoint = selector.targetPoint;\n var wrapper = selector.wrapper;\n var i;\n var segment;\n this.renderCircularHandle('connectorSourceThumb', wrapper, sourcePoint.x, sourcePoint.y, canvas, canShowCorner(selectorConstraints, 'ConnectorSourceThumb'), constraints & ThumbsConstraints.ConnectorSource, transform, connectedSource, undefined, { 'aria-label': 'Thumb to move the source point of the connector' }, undefined, 'e-diagram-endpoint-handle e-targetend');\n this.renderCircularHandle('connectorTargetThumb', wrapper, targetPoint.x, targetPoint.y, canvas, canShowCorner(selectorConstraints, 'ConnectorTargetThumb'), constraints & ThumbsConstraints.ConnectorTarget, transform, connectedTarget, undefined, { 'aria-label': 'Thumb to move the target point of the connector' }, undefined, 'e-diagram-endpoint-handle e-targetend');\n if (isSegmentEditing) {\n if ((selector.type === 'Straight' || selector.type === 'Bezier') && selector.segments.length > 0) {\n for (i = 0; i < selector.segments.length - 1; i++) {\n segment = selector.segments[i];\n this.renderCircularHandle(('segementThumb_' + (i + 1)), wrapper, segment.point.x, segment.point.y, canvas, true, constraints & ThumbsConstraints.ConnectorSource, transform, connectedSource, null, null, i);\n }\n }\n else {\n for (i = 0; i < selector.segments.length; i++) {\n var seg = selector.segments[i];\n this.renderOrthogonalThumbs('orthoThumb_' + (i + 1), wrapper, seg, canvas, canShowCorner(selectorConstraints, 'ConnectorSourceThumb'), transform);\n }\n }\n }\n if (selector.type === 'Bezier') {\n for (i = 0; i < selector.segments.length; i++) {\n var segment_1 = selector.segments[i];\n var bezierPoint = !Point.isEmptyPoint(segment_1.point1) ? segment_1.point1\n : segment_1.bezierPoint1;\n this.renderCircularHandle('bezierPoint_' + (i + 1) + '_1', wrapper, bezierPoint.x, bezierPoint.y, canvas, canShowCorner(selectorConstraints, 'ConnectorSourceThumb'), constraints & ThumbsConstraints.ConnectorSource, transform, undefined, undefined, { 'aria-label': 'Thumb to move the source point of the connector' }, undefined, 'e-diagram-bezier-handle e-source');\n if (canShowCorner(selectorConstraints, 'ConnectorSourceThumb')) {\n this.renderBezierLine('bezierLine_' + (i + 1) + '_1', wrapper, canvas, segment_1.points[0], !Point.isEmptyPoint(segment_1.point1) ? segment_1.point1 : segment_1.bezierPoint1, transform);\n }\n bezierPoint = !Point.isEmptyPoint(segment_1.point2) ? segment_1.point2 : segment_1.bezierPoint2;\n this.renderCircularHandle('bezierPoint_' + (i + 1) + '_2', wrapper, bezierPoint.x, bezierPoint.y, canvas, canShowCorner(selectorConstraints, 'ConnectorTargetThumb'), constraints & ThumbsConstraints.ConnectorTarget, transform, undefined, undefined, { 'aria-label': 'Thumb to move the target point of the connector' }, undefined, 'e-diagram-bezier-handle e-target');\n if (canShowCorner(selectorConstraints, 'ConnectorTargetThumb')) {\n this.renderBezierLine('bezierLine_' + (i + 1) + '_2', wrapper, canvas, segment_1.points[1], !Point.isEmptyPoint(segment_1.point2) ? segment_1.point2 : segment_1.bezierPoint2, transform);\n }\n }\n }\n };\n DiagramRenderer.prototype.renderOrthogonalThumbs = function (id, selector, segment, canvas, visibility, t) {\n var orientation;\n var visible;\n var length;\n var j = 0;\n for (j = 0; j < segment.points.length - 1; j++) {\n length = Point.distancePoints(segment.points[j], segment.points[j + 1]);\n orientation = (segment.points[j].y.toFixed(2) === segment.points[j + 1].y.toFixed(2)) ? 'horizontal' : 'vertical';\n visible = (length >= 50) ? true : false;\n this.renderOrthogonalThumb((id + '_' + (j + 1)), selector, (((segment.points[j].x + segment.points[j + 1].x) / 2)), (((segment.points[j].y + segment.points[j + 1].y) / 2)), canvas, visible, orientation, t);\n }\n };\n DiagramRenderer.prototype.renderOrthogonalThumb = function (id, selector, x, y, canvas, visible, orientation, t) {\n var path;\n var h;\n var v;\n if (orientation === 'horizontal') {\n path = 'M0,7 L15,0 L30,7 L15,14 z';\n h = -15;\n v = -7;\n }\n else {\n path = 'M7,0 L0,15 L7,30 L14,15 z';\n h = -7;\n v = -15;\n }\n var options = {\n x: ((x + t.tx) * t.scale) + h, y: ((y + t.ty) * t.scale) + v, angle: 0,\n fill: '#e2e2e2', stroke: 'black', strokeWidth: 1, dashArray: '', data: path,\n width: 20, height: 20, pivotX: 0, pivotY: 0, opacity: 1, visible: visible, id: id\n };\n this.svgRenderer.drawPath(canvas, options, this.diagramId);\n };\n DiagramRenderer.prototype.renderPivotLine = function (element, canvas, transform, selectorConstraints, canMask) {\n var wrapper = element;\n var dashArray = '2,3';\n var visible = (selectorConstraints & SelectorConstraints.Rotate) ? true : false;\n if (canMask) {\n visible = false;\n }\n var options = this.getBaseAttributes(wrapper, transform);\n options.fill = 'None';\n options.stroke = 'black';\n options.strokeWidth = 1;\n options.dashArray = dashArray;\n options.visible = visible;\n var scale = transform.scale;\n options.x *= scale;\n options.y *= scale;\n options.width *= scale;\n options.height *= scale;\n options.id = 'pivotLine';\n options.class = 'e-diagram-pivot-line';\n var startPoint = { x: wrapper.actualSize.width * wrapper.pivot.x * scale, y: -20 };\n var endPoint = { x: wrapper.actualSize.width * wrapper.pivot.x * scale, y: 0 };\n options.startPoint = startPoint;\n options.endPoint = endPoint;\n this.svgRenderer.drawLine(canvas, options);\n };\n DiagramRenderer.prototype.renderBezierLine = function (id, wrapper, canvas, start, end, transform) {\n var dashArray = '3,3';\n var options = this.getBaseAttributes(wrapper, transform);\n options.id = id;\n options.stroke = 'black';\n options.strokeWidth = 1;\n options.dashArray = dashArray;\n options.fill = 'None';\n options.class = 'e-diagram-bezier-line';\n options.x = 0;\n options.y = 0;\n var scale = transform.scale;\n var x1 = (start.x + transform.tx) * scale;\n var y1 = (start.y + transform.ty) * scale;\n var x2 = (end.x + transform.tx) * scale;\n var y2 = (end.y + transform.ty) * scale;\n var startPoint = { x: x1, y: y1 };\n var endPoint = { x: x2, y: y2 };\n options.startPoint = startPoint;\n options.endPoint = endPoint;\n this.svgRenderer.drawLine(canvas, options);\n };\n DiagramRenderer.prototype.renderCircularHandle = function (id, selector, cx, cy, canvas, visible, enableSelector, t, connected, canMask, ariaLabel, count, className) {\n var wrapper = selector;\n var radius = 7;\n var newPoint = { x: cx, y: cy };\n if (wrapper.rotateAngle !== 0 || wrapper.parentTransform !== 0) {\n var matrix = identityMatrix();\n rotateMatrix(matrix, wrapper.rotateAngle + wrapper.parentTransform, wrapper.offsetX, wrapper.offsetY);\n newPoint = transformPointByMatrix(matrix, newPoint);\n }\n var options = this.getBaseAttributes(wrapper);\n options.stroke = 'black';\n options.strokeWidth = 1;\n if (count !== undefined) {\n radius = 5;\n options.id = 'segmentEnd_' + count;\n options.fill = '#e2e2e2';\n }\n else {\n radius = 7;\n options.fill = connected ? '#8CC63F' : 'white';\n }\n options.centerX = (newPoint.x + t.tx) * t.scale;\n options.centerY = (newPoint.y + t.ty) * t.scale;\n options.radius = radius;\n options.angle = 0;\n options.id = id;\n options.visible = visible;\n options.class = className;\n if (connected) {\n options.class += ' e-connected';\n }\n if (canMask) {\n options.visible = false;\n }\n this.svgRenderer.drawCircle(canvas, options, enableSelector, ariaLabel);\n };\n DiagramRenderer.prototype.renderBorder = function (selector, canvas, transform, enableNode) {\n var wrapper = selector;\n var options = this.getBaseAttributes(wrapper, transform);\n options.x *= transform.scale;\n options.y *= transform.scale;\n options.width *= transform.scale;\n options.height *= transform.scale;\n options.fill = 'transparent';\n options.stroke = '#097F7F';\n options.strokeWidth = 0.6;\n options.dashArray = '6,3';\n options.class = 'e-diagram-border';\n options.id = 'borderRect';\n if (!enableNode) {\n options.class += ' e-disabled';\n }\n options.cornerRadius = 0;\n var parentSvg = this.getParentSvg(selector, 'selector');\n this.svgRenderer.drawRectangle(canvas, options, this.diagramId, undefined, true, parentSvg);\n };\n DiagramRenderer.prototype.renderUserHandler = function (selectorItem, canvas, transform) {\n var wrapper = selectorItem.wrapper;\n for (var _i = 0, _a = selectorItem.userHandles; _i < _a.length; _i++) {\n var obj = _a[_i];\n var element = new PathElement();\n var newPoint = void 0;\n var data = obj.pathData;\n newPoint = getUserHandlePosition(selectorItem, obj, transform);\n newPoint.x = (newPoint.x + transform.tx) * transform.scale;\n newPoint.y = (newPoint.y + transform.ty) * transform.scale;\n if (obj.visible) {\n obj.visible = (selectorItem.constraints & SelectorConstraints.UserHandle) ? true : false;\n }\n var option = this.getBaseAttributes(wrapper);\n option.id = obj.name + '_userhandle';\n option.fill = obj.backgroundColor;\n option.stroke = obj.borderColor;\n option.strokeWidth = obj.borderWidth;\n option.centerX = newPoint.x;\n option.centerY = newPoint.y;\n option.radius = obj.size * 0.5;\n option.class = 'e-diagram-userhandle-circle';\n option.angle = 0;\n option.visible = obj.visible;\n option.opacity = 1;\n this.svgRenderer.drawCircle(canvas, option, 1, { 'aria-label': obj.name + 'user handle' });\n var pathPading = 5;\n var arrayCollection = [];\n arrayCollection = processPathData(data);\n arrayCollection = splitArrayCollection(arrayCollection);\n var pathSize = measurePath(data);\n //requiredSize/contentSize\n var scaleX = (obj.size - 0.45 * obj.size) / pathSize.width;\n var scaleY = (obj.size - 0.45 * obj.size) / pathSize.height;\n var newData = transformPath(arrayCollection, scaleX, scaleY, true, pathSize.x, pathSize.y, 0, 0);\n pathSize = measurePath(newData);\n var options = {\n x: newPoint.x - pathSize.width / 2,\n y: newPoint.y - pathSize.height / 2,\n angle: 0, id: '',\n class: 'e-diagram-userhandle-path',\n fill: obj.pathColor, stroke: obj.backgroundColor, strokeWidth: 0.5, dashArray: '', data: newData,\n width: obj.size - pathPading, height: obj.size - pathPading, pivotX: 0, pivotY: 0, opacity: 1, visible: obj.visible\n };\n this.svgRenderer.drawPath(canvas, options, this.diagramId, undefined, undefined, { 'aria-label': obj.name + 'user handle' });\n }\n };\n DiagramRenderer.prototype.renderRotateThumb = function (wrapper, canvas, transform, selectorConstraints, canMask) {\n var element = new PathElement();\n var newPoint;\n var size = new Size();\n size.width = 18;\n size.height = 16;\n var top = wrapper.offsetY - wrapper.actualSize.height * wrapper.pivot.y;\n var left = wrapper.offsetX - wrapper.actualSize.width * wrapper.pivot.x;\n var visible = (selectorConstraints & SelectorConstraints.Rotate) ? true : false;\n if (canMask) {\n visible = false;\n }\n var data = 'M 16.856144362449648 10.238890446662904 L 18.000144362449646 3.437890446662903' +\n 'L 15.811144362449646 4.254890446662903 C 14.837144362449646 2.5608904466629028 13.329144362449647 ' +\n ' 1.2598904466629026 11.485144362449645 0.5588904466629026 C 9.375144362449646 - 0.24510955333709716 7.071144362449646 ' +\n ' - 0.18010955333709716 5.010144362449646 0.7438904466629028 C 2.942144362449646 1.6678904466629028 1.365144362449646' +\n ' 3.341890446662903 0.558144362449646 5.452890446662903 C - 0.244855637550354 7.567890446662903 - 0.17985563755035394' +\n ' 9.866890446662904 0.7431443624496461 11.930890446662904 C 1.6681443624496461 13.994890446662904 3.343144362449646' +\n ' 15.575890446662903 5.457144362449647 16.380890446662903 C 6.426144362449647 16.7518904466629 7.450144362449647' +\n ' 16.9348904466629 8.470144362449647 16.9348904466629 C 9.815144362449647 16.9348904466629 11.155144362449647 ' +\n '16.6178904466629 12.367144362449647 15.986890446662901 L 11.351144362449647 14.024890446662901 C 9.767144362449647' +\n ' 14.8468904466629 7.906144362449647 14.953890446662902 6.237144362449647 14.3178904466629 C 4.677144362449647' +\n ' 13.7218904466629 3.444144362449647 12.5558904466629 2.758144362449647 11.028890446662901 C 2.078144362449646 ' +\n '9.501890446662903 2.031144362449646 7.802890446662903 2.622144362449646 6.243890446662903 C 3.216144362449646' +\n ' 4.6798904466629025 4.387144362449646 3.442890446662903 5.914144362449646 2.760890446662903 C 7.437144362449646 ' +\n '2.078890446662903 9.137144362449646 2.0298904466629026 10.700144362449645 2.6258904466629027 C 11.946144362449646 ' +\n '3.100890446662903 12.971144362449646 3.9538904466629026 13.686144362449646 5.049890446662903 L 11.540144362449645 ' +\n '5.850890446662903 L 16.856144362449648 10.238890446662904 Z';\n var pivotX = left + wrapper.pivot.x * wrapper.actualSize.width;\n var pivotY = top;\n pivotX = (pivotX + transform.tx) * transform.scale;\n pivotY = (pivotY + transform.ty) * transform.scale;\n newPoint = { x: pivotX - size.width * 0.5, y: pivotY - 30 - size.height * 0.5 };\n if (wrapper.rotateAngle !== 0 || wrapper.parentTransform !== 0) {\n var matrix = identityMatrix();\n rotateMatrix(matrix, wrapper.rotateAngle + wrapper.parentTransform, (transform.tx + wrapper.offsetX) * transform.scale, (transform.ty + wrapper.offsetY) * transform.scale);\n newPoint = transformPointByMatrix(matrix, newPoint);\n }\n var options = {\n x: newPoint.x,\n y: newPoint.y,\n angle: wrapper.rotateAngle,\n fill: '#231f20', stroke: 'black', strokeWidth: 0.5, dashArray: '', data: data,\n width: 20, height: 20, pivotX: 0, pivotY: 0, opacity: 1, visible: visible, id: wrapper.id, class: 'e-diagram-rotate-handle'\n };\n options.id = 'rotateThumb';\n this.svgRenderer.drawPath(canvas, options, this.diagramId, true, undefined, { 'aria-label': 'Thumb to rotate the selected object' });\n };\n DiagramRenderer.prototype.renderPathElement = function (element, canvas, transform, parentSvg) {\n var options = this.getBaseAttributes(element, transform);\n options.data = element.absolutePath;\n options.data = element.absolutePath;\n var ariaLabel = element.description ? element.description : element.id;\n this.renderer.drawPath(canvas, options, this.diagramId, undefined, parentSvg, ariaLabel);\n };\n DiagramRenderer.prototype.renderSvgGridlines = function (snapSettings, gridSvg, t, rulerSettings, hRuler, vRuler) {\n //render gridlines\n var pattern = document.createElementNS('http://www.w3.org/2000/svg', 'pattern');\n var defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');\n defs.setAttribute('id', this.diagramId + '_grid_pattern_defn');\n if (snapSettings.constraints & SnapConstraints.ShowHorizontalLines ||\n snapSettings.constraints & SnapConstraints.ShowVerticalLines) {\n pattern.setAttribute('id', this.diagramId + '_pattern');\n }\n var hWidth = 0;\n var hHeight = 0;\n var hSegmentwidth = 0;\n var vSegmentwidth = 0;\n var scale = 1;\n var isRulerGrid = false;\n if (rulerSettings.showRulers && rulerSettings.dynamicGrid && hRuler && vRuler) {\n hSegmentwidth = vRuler.updateSegmentWidth(t.scale);\n vSegmentwidth = hRuler.updateSegmentWidth(t.scale);\n snapSettings.horizontalGridlines.scaledIntervals = [hSegmentwidth / hRuler.interval];\n snapSettings.verticalGridlines.scaledIntervals = [vSegmentwidth / vRuler.interval];\n isRulerGrid = true;\n }\n else {\n for (var _i = 0, _a = snapSettings.verticalGridlines.lineIntervals; _i < _a.length; _i++) {\n var entry = _a[_i];\n hWidth += entry;\n }\n for (var _b = 0, _c = snapSettings.horizontalGridlines.lineIntervals; _b < _c.length; _b++) {\n var entry = _c[_b];\n hHeight += entry;\n }\n scale = this.scaleSnapInterval(snapSettings, t.scale);\n }\n hWidth = isRulerGrid ? vSegmentwidth : hWidth * scale;\n hHeight = isRulerGrid ? hSegmentwidth : hHeight * scale;\n var attr = {\n id: this.diagramId + '_pattern', x: 0, y: 0, width: hWidth,\n height: hHeight, patternUnits: 'userSpaceOnUse'\n };\n setAttributeSvg(pattern, attr);\n this.horizontalSvgGridlines(pattern, hWidth, hHeight, scale, snapSettings, rulerSettings, vRuler, isRulerGrid);\n this.verticalSvgGridlines(pattern, hWidth, hHeight, scale, snapSettings, rulerSettings, hRuler, isRulerGrid);\n defs.appendChild(pattern);\n gridSvg.appendChild(defs);\n };\n DiagramRenderer.prototype.horizontalSvgGridlines = function (pattern, hWidth, hHeight, scale, snapSettings, rulerSettings, vRuler, isRulerGrid) {\n var space = 0;\n var dashArray = [];\n var hLine;\n if (snapSettings.constraints & SnapConstraints.ShowHorizontalLines) {\n var intervals = snapSettings.horizontalGridlines.lineIntervals;\n var strokestyle = snapSettings.horizontalGridlines.lineColor;\n if (snapSettings.horizontalGridlines.lineDashArray) {\n dashArray = this.renderer.parseDashArray(snapSettings.horizontalGridlines.lineDashArray);\n }\n if (rulerSettings.showRulers && rulerSettings.dynamicGrid && vRuler) {\n intervals = this.updateLineIntervals(intervals, rulerSettings, vRuler, hHeight);\n }\n for (var i = 0; i < intervals.length; i = i + 2) {\n hLine = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n var d = space + intervals[i] / 2;\n d = isRulerGrid ? d : d * scale;\n var attr = {\n 'stroke-width': intervals[i], 'stroke': snapSettings.horizontalGridlines.lineColor,\n 'd': 'M0,' + (d) + ' L' + hWidth + ',' + (d) + ' Z',\n 'dashArray': dashArray.toString(),\n 'class': intervals[i] === 1.25 ? 'e-diagram-thick-grid' : 'e-diagram-thin-grid'\n };\n setAttributeSvg(hLine, attr);\n pattern.appendChild(hLine);\n space += intervals[i + 1] + intervals[i];\n }\n }\n };\n DiagramRenderer.prototype.verticalSvgGridlines = function (pattern, hWidth, hHeight, scale, snapSettings, rulerSettings, hRuler, isRulerGrid) {\n var space = 0;\n var dashArray = [];\n var vLine;\n if (snapSettings.constraints & SnapConstraints.ShowVerticalLines) {\n var intervals = snapSettings.verticalGridlines.lineIntervals;\n var strokestyle = snapSettings.verticalGridlines.lineColor;\n if (snapSettings.verticalGridlines.lineDashArray) {\n dashArray = this.renderer.parseDashArray(snapSettings.verticalGridlines.lineDashArray);\n }\n if (rulerSettings.showRulers && rulerSettings.dynamicGrid && hRuler) {\n intervals = this.updateLineIntervals(intervals, rulerSettings, hRuler, hWidth);\n }\n for (var i = 0; i < intervals.length; i = i + 2) {\n vLine = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n var d = space + intervals[i] / 2;\n d = isRulerGrid ? d : d * scale;\n var attr = {\n 'stroke-width': intervals[i], 'stroke': snapSettings.verticalGridlines.lineColor,\n 'd': 'M' + (d) + ',0 L' + (d) + ',' + hHeight + ' Z',\n 'dashArray': dashArray.toString(),\n 'class': intervals[i] === 1.25 ? 'e-diagram-thick-grid' : 'e-diagram-thin-grid'\n };\n setAttributeSvg(vLine, attr);\n pattern.appendChild(vLine);\n space += intervals[i + 1] + intervals[i];\n }\n }\n };\n DiagramRenderer.prototype.updateGrid = function (snapSettings, svgGrid, transform, rulerSettings, hRuler, vRuler) {\n var grid = svgGrid.getElementById(this.diagramId + '_grid_rect');\n var i;\n var isRulerGrid = false;\n if (grid) {\n var pattern = svgGrid.getElementById(this.diagramId + '_pattern');\n if (pattern) {\n pattern.parentNode.removeChild(pattern);\n }\n var hSegmentwidth = 0;\n var vSegmentwidth = 0;\n var scale = 1;\n if (rulerSettings.showRulers && rulerSettings.dynamicGrid && vRuler && hRuler) {\n hSegmentwidth = vRuler.updateSegmentWidth(transform.scale);\n vSegmentwidth = hRuler.updateSegmentWidth(transform.scale);\n isRulerGrid = true;\n snapSettings.horizontalGridlines.scaledIntervals = [hSegmentwidth / hRuler.interval];\n snapSettings.verticalGridlines.scaledIntervals = [vSegmentwidth / vRuler.interval];\n }\n else {\n scale = this.scaleSnapInterval(snapSettings, transform.scale);\n }\n var height = 0;\n for (i = 0; i < snapSettings.horizontalGridlines.lineIntervals.length; i++) {\n height += snapSettings.horizontalGridlines.lineIntervals[i];\n }\n var width = 0;\n for (i = 0; i < snapSettings.verticalGridlines.lineIntervals.length; i++) {\n width += snapSettings.verticalGridlines.lineIntervals[i];\n }\n var attr = {\n x: -transform.tx * transform.scale,\n y: -transform.ty * transform.scale\n };\n setAttributeSvg(grid, attr);\n width = isRulerGrid ? vSegmentwidth : width * scale;\n height = isRulerGrid ? hSegmentwidth : height * scale;\n attr = {\n id: this.diagramId + '_pattern', x: 0, y: 0, width: width,\n height: height, patternUnits: 'userSpaceOnUse'\n };\n pattern = document.createElementNS('http://www.w3.org/2000/svg', 'pattern');\n setAttributeSvg(pattern, attr);\n this.horizontalSvgGridlines(pattern, width, height, scale, snapSettings, rulerSettings, vRuler, isRulerGrid);\n this.verticalSvgGridlines(pattern, width, height, scale, snapSettings, rulerSettings, hRuler, isRulerGrid);\n var defs = svgGrid.getElementById(this.diagramId + '_grid_pattern_defn');\n defs.appendChild(pattern);\n }\n };\n DiagramRenderer.prototype.updateLineIntervals = function (intervals, rulerSettings, ruler, segmentWidth) {\n var newInterval = [];\n var tickInterval = segmentWidth / ruler.interval;\n for (var i = 0; i < ruler.interval * 2; i++) {\n if (i % 2 === 0) {\n newInterval[i] = (i === 0) ? 1.25 : 0.25;\n }\n else {\n newInterval[i] = tickInterval - newInterval[i - 1];\n }\n }\n return newInterval;\n };\n DiagramRenderer.prototype.scaleSnapInterval = function (snapSettings, scale) {\n if (scale >= 2) {\n while (scale >= 2) {\n scale /= 2;\n }\n }\n else if (scale <= 0.5) {\n while (scale <= 0.5) {\n scale *= 2;\n }\n }\n var i;\n snapSettings.horizontalGridlines.scaledIntervals = snapSettings.horizontalGridlines.snapIntervals;\n snapSettings.verticalGridlines.scaledIntervals = snapSettings.verticalGridlines.snapIntervals;\n if (scale !== 1) {\n var gridlines = snapSettings.horizontalGridlines;\n gridlines.scaledIntervals = [];\n for (i = 0; i < gridlines.snapIntervals.length; i++) {\n gridlines.scaledIntervals[i] = gridlines.snapIntervals[i] * scale;\n }\n gridlines = snapSettings.verticalGridlines;\n gridlines.scaledIntervals = [];\n for (i = 0; i < gridlines.snapIntervals.length; i++) {\n gridlines.scaledIntervals[i] = gridlines.snapIntervals[i] * scale;\n }\n }\n return scale;\n };\n DiagramRenderer.prototype.renderTextElement = function (element, canvas, transform, parentSvg) {\n var options = this.getBaseAttributes(element, transform);\n options.cornerRadius = 0;\n this.renderer.drawRectangle(canvas, options, this.diagramId, undefined, undefined, parentSvg);\n options.whiteSpace = whiteSpaceToString(element.style.whiteSpace, element.style.textWrapping);\n options.content = element.content;\n options.breakWord = wordBreakToString(element.style.textWrapping);\n options.textAlign = textAlignToString(element.style.textAlign);\n options.color = element.style.color;\n options.italic = element.style.italic;\n options.bold = element.style.bold;\n options.fontSize = element.style.fontSize;\n options.fontFamily = element.style.fontFamily;\n options.textOverflow = element.style.textOverflow;\n options.textDecoration = element.style.textDecoration;\n options.doWrap = element.doWrap;\n options.wrapBounds = element.wrapBounds;\n options.childNodes = element.childNodes;\n options.dashArray = '';\n options.strokeWidth = 0;\n options.fill = '';\n var ariaLabel = element.description ? element.description : element.content ? element.content : element.id;\n this.renderer.drawText(canvas, options, parentSvg, ariaLabel, this.diagramId);\n if (this.isSvgMode) {\n element.doWrap = false;\n }\n };\n DiagramRenderer.prototype.renderNativeElement = function (element, canvas, transform, parentSvg) {\n var templateWidth;\n var templateHeight;\n var nativeSvg = this.getParentSvg(element, undefined, canvas) || parentSvg;\n var nativeLayer = this.getParentElement(element, canvas, nativeSvg).g || canvas;\n var options = this.getBaseAttributes(element, transform);\n options.fill = 'transparent';\n options.cornerRadius = element.cornerRadius;\n options.stroke = 'transparent';\n this.renderer.drawRectangle(canvas, options, this.diagramId, undefined, undefined, parentSvg);\n switch (element.scale) {\n case 'None':\n templateWidth = element.contentSize.width;\n templateHeight = element.contentSize.height;\n break;\n case 'Stretch':\n templateWidth = element.actualSize.width;\n templateHeight = element.actualSize.height;\n break;\n case 'Meet':\n if (element.actualSize.width <= element.actualSize.height) {\n templateWidth = templateHeight = element.actualSize.width;\n }\n else {\n templateWidth = templateHeight = element.actualSize.height;\n }\n break;\n case 'Slice':\n if (element.actualSize.width >= element.actualSize.height) {\n templateWidth = templateHeight = element.actualSize.width;\n }\n else {\n templateWidth = templateHeight = element.actualSize.height;\n }\n break;\n }\n if (this.svgRenderer) {\n this.svgRenderer.drawNativeContent(element, nativeLayer, templateHeight, templateWidth, nativeSvg);\n }\n };\n DiagramRenderer.prototype.renderHTMLElement = function (element, canvas, htmlLayer, transform, parentSvg) {\n var options = this.getBaseAttributes(element, transform);\n options.fill = 'transparent';\n options.cornerRadius = element.cornerRadius;\n options.stroke = 'transparent';\n this.renderer.drawRectangle(canvas, options, this.diagramId, undefined, undefined, parentSvg);\n if (this.svgRenderer) {\n this.svgRenderer.drawHTMLContent(element, htmlLayer.children[0], transform);\n }\n };\n DiagramRenderer.prototype.renderImageElement = function (element, canvas, transform, parentSvg) {\n var options = this.getBaseAttributes(element, transform);\n options.cornerRadius = 0;\n this.renderer.drawRectangle(canvas, options, this.diagramId, undefined, undefined, parentSvg);\n // let sx: number; let sy: number;\n var imageWidth;\n var imageHeight;\n var sourceWidth;\n var sourceHeight;\n if (element.stretch === 'Stretch') {\n imageWidth = element.actualSize.width;\n imageHeight = element.actualSize.height;\n }\n else {\n var contentWidth = element.contentSize.width;\n var contentHeight = element.contentSize.height;\n var widthRatio = options.width / contentWidth;\n var heightRatio = options.height / contentHeight;\n var ratio = void 0;\n switch (element.stretch) {\n case 'Meet':\n ratio = Math.min(widthRatio, heightRatio);\n imageWidth = contentWidth * ratio;\n imageHeight = contentHeight * ratio;\n options.x += Math.abs(options.width - imageWidth) / 2;\n options.y += Math.abs(options.height - imageHeight) / 2;\n break;\n case 'Slice':\n widthRatio = options.width / contentWidth;\n heightRatio = options.height / contentHeight;\n ratio = Math.max(widthRatio, heightRatio);\n imageWidth = contentWidth * ratio;\n imageHeight = contentHeight * ratio;\n sourceWidth = options.width / imageWidth * contentWidth;\n sourceHeight = options.height / imageHeight * contentHeight;\n break;\n case 'None':\n imageWidth = contentWidth;\n imageHeight = contentHeight;\n break;\n }\n }\n options.width = imageWidth;\n options.height = imageHeight;\n //Commented for code coverage\n //(options as ImageAttributes).sourceX = sx;\n //(options as ImageAttributes).sourceY = sy;\n options.sourceWidth = sourceWidth;\n options.sourceHeight = sourceHeight;\n options.source = element.source;\n options.alignment = element.imageAlign;\n options.scale = element.imageScale;\n options.description = element.description ? element.description : element.id;\n this.renderer.drawImage(canvas, options, parentSvg);\n };\n DiagramRenderer.prototype.renderContainer = function (group, canvas, htmlLayer, transform, parentSvg, createParent) {\n var svgParent = { svg: parentSvg, g: canvas };\n if (this.diagramId) {\n parentSvg = this.getParentSvg(group) || parentSvg;\n if (this.isSvgMode) {\n var groupElement = void 0;\n groupElement = this.getParentElement(group, canvas, parentSvg).g || canvas;\n parentSvg = this.getParentSvg(this.hasNativeParent(group.children)) || parentSvg;\n var svgNativeParent = this.getParentElement(this.hasNativeParent(group.children), groupElement, parentSvg);\n svgParent.svg = svgNativeParent.svg || parentSvg;\n svgParent.g = svgNativeParent.g || groupElement;\n if (createParent) {\n if (parentSvg) {\n if (!parentSvg.getElementById(svgParent.g.id)) {\n canvas.appendChild(svgParent.g);\n }\n }\n canvas = svgParent.g;\n }\n else {\n canvas = svgParent.g;\n }\n }\n }\n this.renderRect(group, canvas, transform, parentSvg);\n if (group.hasChildren()) {\n var parentG = void 0;\n var svgParent_1;\n for (var _i = 0, _a = group.children; _i < _a.length; _i++) {\n var child = _a[_i];\n parentSvg = this.getParentSvg(this.hasNativeParent(group.children) || child) || parentSvg;\n if (this.isSvgMode) {\n svgParent_1 = this.getParentElement(this.hasNativeParent(group.children) || child, canvas, parentSvg);\n parentG = svgParent_1.g || canvas;\n if (svgParent_1.svg) {\n parentSvg = svgParent_1.svg;\n }\n }\n this.renderElement(child, parentG || canvas, htmlLayer, transform, parentSvg, true);\n }\n }\n };\n DiagramRenderer.prototype.hasNativeParent = function (children, count) {\n if (children && children.length > 0 && (count || 0 < 3)) {\n var child = children[0];\n if (child instanceof DiagramNativeElement) {\n return child;\n }\n else if (child.children && child.children.length) {\n this.hasNativeParent(child.children, count++ || 0);\n }\n }\n return undefined;\n };\n DiagramRenderer.prototype.renderRect = function (element, canvas, transform, parentSvg) {\n var options = this.getBaseAttributes(element, transform);\n options.cornerRadius = element.cornerRadius || 0;\n var ariaLabel = element.description ? element.description : element.id;\n this.renderer.drawRectangle(canvas, options, this.diagramId, undefined, undefined, parentSvg, ariaLabel);\n };\n DiagramRenderer.prototype.drawRect = function (canvas, options) {\n options.cornerRadius = 0;\n this.svgRenderer.drawRectangle(canvas, options, this.diagramId);\n };\n DiagramRenderer.prototype.getBaseAttributes = function (element, transform) {\n var options = {\n width: element.actualSize.width, height: element.actualSize.height,\n x: element.offsetX - element.actualSize.width * element.pivot.x + 0.5,\n y: element.offsetY - element.actualSize.height * element.pivot.y + 0.5,\n fill: element.style.fill, stroke: element.style.strokeColor, angle: element.rotateAngle + element.parentTransform,\n pivotX: element.pivot.x, pivotY: element.pivot.y, strokeWidth: element.style.strokeWidth,\n dashArray: element.style.strokeDashArray || '', opacity: element.style.opacity, shadow: element.shadow,\n gradient: element.style.gradient, visible: element.visible, id: element.id, description: element.description,\n };\n if (transform) {\n options.x += transform.tx;\n options.y += transform.ty;\n }\n return options;\n };\n DiagramRenderer.renderSvgBackGroundImage = function (background, diagramElement, x, y, width, height) {\n var container = document.getElementById(diagramElement.id);\n var backgroundLayer = getBackgroundLayerSvg(diagramElement.id);\n var target = backgroundLayer.getElementById(diagramElement.id + '_image');\n if (!target && background.source) {\n var bgimageLayer = getBackgroundImageLayer(diagramElement.id);\n target = document.createElementNS('http://www.w3.org/2000/svg', 'image');\n target.setAttribute('id', diagramElement.id + '_image');\n bgimageLayer.appendChild(target);\n }\n if (target) {\n target.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', background.source);\n var scale = background.scale !== 'None' ? background.scale : '';\n var imgAlign = background.align;\n var aspectRatio = imgAlign.charAt(0).toLowerCase() + imgAlign.slice(1) + ' '\n + scale.charAt(0).toLowerCase() + scale.slice(1);\n var container_1 = document.getElementById(diagramElement.id);\n var attr = {\n 'id': diagramElement.id + '_image', 'x': x, 'y': y,\n 'width': width, 'height': height,\n 'preserveAspectRatio': aspectRatio\n };\n setAttributeSvg(target, attr);\n }\n };\n DiagramRenderer.prototype.transformLayers = function (transform, svgMode) {\n //diagram layer\n if (svgMode) {\n var diagramLayer = getDiagramLayer(this.diagramId);\n diagramLayer.setAttribute('transform', 'translate('\n + (transform.tx * transform.scale) + ',' + (transform.ty * transform.scale) + '),scale('\n + transform.scale + ')');\n }\n //background\n //gridline\n var gridLayer = getGridLayer(this.diagramId);\n gridLayer.setAttribute('transform', 'translate(' + (transform.tx * transform.scale) + ','\n + (transform.ty * transform.scale) + ')');\n //portslayer \n var portsLayer = getPortsLayer(this.diagramId);\n portsLayer.setAttribute('transform', 'translate('\n + (transform.tx * transform.scale) + ',' + (transform.ty * transform.scale) + '),scale('\n + transform.scale + ')');\n //expandlayer\n var expandLayer = getExpandCollapseLayer(this.diagramId);\n expandLayer.setAttribute('transform', 'translate('\n + (transform.tx * transform.scale) + ',' + (transform.ty * transform.scale) + '),scale('\n + transform.scale + ')');\n //nativelayer\n var nativeLayer = getNativeLayer(this.diagramId);\n nativeLayer.setAttribute('transform', 'translate('\n + (transform.tx * transform.scale) + ',' + (transform.ty * transform.scale) + '),scale('\n + transform.scale + ')');\n //htmlLayer\n var htmlLayer = getHTMLLayer(this.diagramId).children[0];\n htmlLayer.style.transform = 'translate('\n + (transform.tx * transform.scale) + 'px,' + (transform.ty * transform.scale) + 'px)scale('\n + transform.scale + ')';\n };\n /** @private */\n DiagramRenderer.prototype.updateNode = function (element, diagramElementsLayer, htmlLayer, transform) {\n this.renderElement(element, diagramElementsLayer, htmlLayer, transform, this.getParentSvg(element));\n };\n return DiagramRenderer;\n}());\nexport { DiagramRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { Margin } from '../core/appearance';\n/**\n * Defines the BackgroundImage of diagram\n */\nvar Background = /** @class */ (function (_super) {\n __extends(Background, _super);\n function Background() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Background.prototype, \"source\", void 0);\n __decorate([\n Property('transparent')\n ], Background.prototype, \"color\", void 0);\n __decorate([\n Property('None')\n ], Background.prototype, \"scale\", void 0);\n __decorate([\n Property('None')\n ], Background.prototype, \"align\", void 0);\n return Background;\n}(ChildProperty));\nexport { Background };\n/**\n * Defines PageSettings\n */\nvar PageSettings = /** @class */ (function (_super) {\n __extends(PageSettings, _super);\n function PageSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(null)\n ], PageSettings.prototype, \"width\", void 0);\n __decorate([\n Property(null)\n ], PageSettings.prototype, \"height\", void 0);\n __decorate([\n Complex({}, Margin)\n ], PageSettings.prototype, \"margin\", void 0);\n __decorate([\n Property('Landscape')\n ], PageSettings.prototype, \"orientation\", void 0);\n __decorate([\n Property('Infinity')\n ], PageSettings.prototype, \"boundaryConstraints\", void 0);\n __decorate([\n Complex({}, Background)\n ], PageSettings.prototype, \"background\", void 0);\n __decorate([\n Property(false)\n ], PageSettings.prototype, \"multiplePage\", void 0);\n __decorate([\n Property(false)\n ], PageSettings.prototype, \"showPageBreaks\", void 0);\n return PageSettings;\n}(ChildProperty));\nexport { PageSettings };\n/**\n * Diagram ScrollSettings module handles the scroller properties of the diagram\n */\nvar ScrollSettings = /** @class */ (function (_super) {\n __extends(ScrollSettings, _super);\n function ScrollSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(0)\n ], ScrollSettings.prototype, \"horizontalOffset\", void 0);\n __decorate([\n Property(0)\n ], ScrollSettings.prototype, \"verticalOffset\", void 0);\n __decorate([\n Property(1)\n ], ScrollSettings.prototype, \"currentZoom\", void 0);\n __decorate([\n Property(0)\n ], ScrollSettings.prototype, \"viewPortWidth\", void 0);\n __decorate([\n Property(0)\n ], ScrollSettings.prototype, \"viewPortHeight\", void 0);\n __decorate([\n Property(0.2)\n ], ScrollSettings.prototype, \"minZoom\", void 0);\n __decorate([\n Property(30)\n ], ScrollSettings.prototype, \"maxZoom\", void 0);\n __decorate([\n Property('Diagram')\n ], ScrollSettings.prototype, \"scrollLimit\", void 0);\n __decorate([\n Property()\n ], ScrollSettings.prototype, \"scrollableArea\", void 0);\n __decorate([\n Property(false)\n ], ScrollSettings.prototype, \"canAutoScroll\", void 0);\n __decorate([\n Complex({ left: 15, right: 15, top: 15, bottom: 15 }, Margin)\n ], ScrollSettings.prototype, \"autoScrollBorder\", void 0);\n return ScrollSettings;\n}(ChildProperty));\nexport { ScrollSettings };\n","/**\n * ServiceLocator\n * @hidden\n */\nvar ServiceLocator = /** @class */ (function () {\n function ServiceLocator() {\n this.services = {};\n }\n ServiceLocator.prototype.register = function (name, type) {\n this.services[name] = type;\n };\n ServiceLocator.prototype.getService = function (name) {\n return this.services[name];\n };\n return ServiceLocator;\n}());\nexport { ServiceLocator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\nimport { SnapConstraints } from '../enum/enum';\n/**\n * Defines gridlines\n */\nvar Gridlines = /** @class */ (function (_super) {\n __extends(Gridlines, _super);\n function Gridlines() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('lightgray')\n ], Gridlines.prototype, \"lineColor\", void 0);\n __decorate([\n Property('')\n ], Gridlines.prototype, \"lineDashArray\", void 0);\n __decorate([\n Property([1.25, 18.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75])\n ], Gridlines.prototype, \"lineIntervals\", void 0);\n __decorate([\n Property([20])\n ], Gridlines.prototype, \"snapIntervals\", void 0);\n return Gridlines;\n}(ChildProperty));\nexport { Gridlines };\n/**\n * Defines the public properties of diagram\n */\nvar SnapSettings = /** @class */ (function (_super) {\n __extends(SnapSettings, _super);\n function SnapSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Complex({}, Gridlines)\n ], SnapSettings.prototype, \"horizontalGridlines\", void 0);\n __decorate([\n Complex({}, Gridlines)\n ], SnapSettings.prototype, \"verticalGridlines\", void 0);\n __decorate([\n Property(SnapConstraints.All)\n ], SnapSettings.prototype, \"constraints\", void 0);\n __decorate([\n Property(5)\n ], SnapSettings.prototype, \"snapAngle\", void 0);\n __decorate([\n Property(5)\n ], SnapSettings.prototype, \"snapObjectDistance\", void 0);\n return SnapSettings;\n}(ChildProperty));\nexport { SnapSettings };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty, Complex } from '@syncfusion/ej2-base';\n/**\n * defines the Properties for the Diagram Ruler\n */\nvar DiagramRuler = /** @class */ (function (_super) {\n __extends(DiagramRuler, _super);\n function DiagramRuler() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(5)\n ], DiagramRuler.prototype, \"interval\", void 0);\n __decorate([\n Property(100)\n ], DiagramRuler.prototype, \"segmentWidth\", void 0);\n __decorate([\n Property('Horizontal')\n ], DiagramRuler.prototype, \"orientation\", void 0);\n __decorate([\n Property('RightOrBottom')\n ], DiagramRuler.prototype, \"tickAlignment\", void 0);\n __decorate([\n Property('red')\n ], DiagramRuler.prototype, \"markerColor\", void 0);\n __decorate([\n Property(25)\n ], DiagramRuler.prototype, \"thickness\", void 0);\n __decorate([\n Property(null)\n ], DiagramRuler.prototype, \"arrangeTick\", void 0);\n return DiagramRuler;\n}(ChildProperty));\nexport { DiagramRuler };\n/**\n * Defines rulers\n */\nvar RulerSettings = /** @class */ (function (_super) {\n __extends(RulerSettings, _super);\n function RulerSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], RulerSettings.prototype, \"showRulers\", void 0);\n __decorate([\n Property(true)\n ], RulerSettings.prototype, \"dynamicGrid\", void 0);\n __decorate([\n Complex({ orientation: 'Horizontal' }, DiagramRuler)\n ], RulerSettings.prototype, \"horizontalRuler\", void 0);\n __decorate([\n Complex({ orientation: 'Vertical' }, DiagramRuler)\n ], RulerSettings.prototype, \"verticalRuler\", void 0);\n return RulerSettings;\n}(ChildProperty));\nexport { RulerSettings };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty } from '@syncfusion/ej2-base';\n/**\n * data source defines the basic unit of diagram\n */\nvar DataSource = /** @class */ (function (_super) {\n __extends(DataSource, _super);\n function DataSource() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], DataSource.prototype, \"id\", void 0);\n __decorate([\n Property(null)\n ], DataSource.prototype, \"dataManager\", void 0);\n __decorate([\n Property('')\n ], DataSource.prototype, \"root\", void 0);\n __decorate([\n Property('')\n ], DataSource.prototype, \"parentId\", void 0);\n __decorate([\n Property()\n ], DataSource.prototype, \"data\", void 0);\n __decorate([\n Property()\n ], DataSource.prototype, \"doBinding\", void 0);\n return DataSource;\n}(ChildProperty));\nexport { DataSource };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Margin } from '../core/appearance';\nimport { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';\n/**\n * Defines the behavior of the automatic layouts\n */\nvar Layout = /** @class */ (function (_super) {\n __extends(Layout, _super);\n function Layout() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Layout.prototype, \"fixedNode\", void 0);\n __decorate([\n Property(30)\n ], Layout.prototype, \"horizontalSpacing\", void 0);\n __decorate([\n Property(30)\n ], Layout.prototype, \"verticalSpacing\", void 0);\n __decorate([\n Property(30)\n ], Layout.prototype, \"maxIteration\", void 0);\n __decorate([\n Property(40)\n ], Layout.prototype, \"springFactor\", void 0);\n __decorate([\n Property(50)\n ], Layout.prototype, \"springLength\", void 0);\n __decorate([\n Complex({ left: 50, top: 50, right: 0, bottom: 0 }, Margin)\n ], Layout.prototype, \"margin\", void 0);\n __decorate([\n Property('Auto')\n ], Layout.prototype, \"horizontalAlignment\", void 0);\n __decorate([\n Property('Auto')\n ], Layout.prototype, \"verticalAlignment\", void 0);\n __decorate([\n Property('TopToBottom')\n ], Layout.prototype, \"orientation\", void 0);\n __decorate([\n Property('Auto')\n ], Layout.prototype, \"connectionDirection\", void 0);\n __decorate([\n Property('Default')\n ], Layout.prototype, \"connectorSegments\", void 0);\n __decorate([\n Property('None')\n ], Layout.prototype, \"type\", void 0);\n __decorate([\n Property()\n ], Layout.prototype, \"getLayoutInfo\", void 0);\n __decorate([\n Property()\n ], Layout.prototype, \"getBranch\", void 0);\n __decorate([\n Property()\n ], Layout.prototype, \"bounds\", void 0);\n __decorate([\n Property(true)\n ], Layout.prototype, \"enableAnimation\", void 0);\n __decorate([\n Property('')\n ], Layout.prototype, \"root\", void 0);\n return Layout;\n}(ChildProperty));\nexport { Layout };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Node } from '../objects/node';\nimport { Connector } from '../objects/connector';\nimport { Point } from '../primitives/point';\nimport { BpmnSubEvent } from '../objects/node';\nimport { PointPort } from '../objects/port';\nimport { rotatePoint, cloneObject } from '../utility/base-util';\nimport { Rect } from '../primitives/rect';\nimport { getPolygonPath } from '../utility/path-util';\nimport { canOutConnect, canInConnect, canAllowDrop } from '../utility/constraints-util';\nimport { transformPointByMatrix, rotateMatrix, identityMatrix } from '../primitives/matrix';\nimport { NodeConstraints, DiagramEvent } from './../enum/enum';\nimport { contains } from './actions';\n/**\n * Defines the interactive tools\n */\nvar ToolBase = /** @class */ (function () {\n /**\n * Initializes the tool\n * @param command Command that is corresponding to the current action\n */\n function ToolBase(command, protectChange) {\n if (protectChange === void 0) { protectChange = false; }\n /**\n * Command that is corresponding to the current action\n */\n this.commandHandler = null;\n /**\n * Sets/Gets whether the interaction is being done\n */\n this.inAction = false;\n /**\n * Sets/Gets the protect change\n */\n this.isProtectChange = false;\n /**\n * Sets/Gets the current element that is under mouse\n */\n this.currentElement = null;\n this.blocked = false;\n this.isTooltipVisible = false;\n /** @private */\n this.childTable = {};\n /**\n * Sets/Gets the previous object when mouse down\n */\n this.undoElement = { nodes: [], connectors: [] };\n this.undoParentElement = { nodes: [], connectors: [] };\n this.commandHandler = command;\n this.isProtectChange = protectChange;\n }\n ToolBase.prototype.startAction = function (currentElement) {\n this.currentElement = currentElement;\n this.inAction = true;\n };\n ToolBase.prototype.mouseDown = function (args) {\n this.currentElement = args.source;\n this.startPosition = this.currentPosition = this.prevPosition = args.position;\n this.isTooltipVisible = true;\n this.startAction(args.source);\n this.commandHandler.startTransaction(this.isProtectChange);\n };\n ToolBase.prototype.mouseMove = function (args) {\n this.currentPosition = args.position;\n //this.currentElement = currentElement;\n return !this.blocked;\n };\n ToolBase.prototype.mouseUp = function (args) {\n this.currentPosition = args.position;\n // this.currentElement = currentElement;\n this.isTooltipVisible = false;\n this.commandHandler.endTransaction(this.isProtectChange);\n //At the end\n this.endAction();\n };\n ToolBase.prototype.endAction = function () {\n if (!this.isTooltipVisible) {\n this.commandHandler.closeTooltip();\n }\n this.commandHandler = null;\n this.currentElement = null;\n this.currentPosition = null;\n this.inAction = false;\n this.blocked = false;\n };\n ToolBase.prototype.mouseWheel = function (args) {\n this.currentPosition = args.position;\n };\n ToolBase.prototype.mouseLeave = function (args) {\n this.mouseUp(args);\n };\n return ToolBase;\n}());\nexport { ToolBase };\n/**\n * Helps to select the objects\n */\nvar SelectTool = /** @class */ (function (_super) {\n __extends(SelectTool, _super);\n function SelectTool() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n SelectTool.prototype.mouseDown = function (args) {\n this.inAction = true;\n _super.prototype.mouseDown.call(this, args);\n };\n SelectTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n //draw selected region\n if (this.inAction && Point.equals(this.currentPosition, this.prevPosition) === false) {\n var rect = Rect.toBounds([this.prevPosition, this.currentPosition]);\n this.commandHandler.drawSelectionRectangle(rect.x, rect.y, rect.width, rect.height);\n }\n return !this.blocked;\n };\n SelectTool.prototype.mouseUp = function (args) {\n //rubber band selection\n if (Point.equals(this.currentPosition, this.prevPosition) === false && this.inAction) {\n var region = Rect.toBounds([this.prevPosition, this.currentPosition]);\n this.commandHandler.doRubberBandSelection(region);\n }\n else {\n //single selection\n var arrayNodes = this.commandHandler.getSelectedObject();\n if (!this.commandHandler.hasSelection() || !args.info || !args.info.ctrlKey) {\n this.commandHandler.clearSelection(args.source === null ? true : false);\n if (args.source) {\n this.commandHandler.selectObjects([args.source], false, arrayNodes);\n }\n }\n else {\n //handling multiple selection\n if (args && args.source) {\n if (!this.commandHandler.isSelected(args.source)) {\n this.commandHandler.selectObjects([args.source], true);\n }\n else {\n if (args.clickCount === 1) {\n this.commandHandler.unSelect(args.source);\n }\n }\n }\n }\n }\n this.inAction = false;\n _super.prototype.mouseUp.call(this, args);\n };\n SelectTool.prototype.mouseLeave = function (args) {\n if (this.inAction) {\n this.mouseUp(args);\n }\n };\n return SelectTool;\n}(ToolBase));\nexport { SelectTool };\n/**\n * Helps to edit the selected connectors\n */\nvar ConnectTool = /** @class */ (function (_super) {\n __extends(ConnectTool, _super);\n function ConnectTool(commandHandler, endPoint) {\n var _this = _super.call(this, commandHandler, true) || this;\n _this.endPoint = endPoint;\n return _this;\n }\n ConnectTool.prototype.mouseDown = function (args) {\n this.inAction = true;\n this.undoElement = undefined;\n if (!(this instanceof ConnectorDrawingTool)) {\n this.undoElement = cloneObject(args.source);\n }\n _super.prototype.mouseDown.call(this, args);\n var oldValue;\n var connectors;\n if (args.source && args.source.connectors) {\n oldValue = { x: this.prevPosition.x, y: this.prevPosition.y };\n connectors = args.source.connectors[0];\n }\n // Sets the selected segment \n if (this.endPoint === 'BezierSourceThumb' || this.endPoint === 'BezierTargetThumb') {\n for (var i = 0; i < connectors.segments.length; i++) {\n var segment = connectors.segments[i];\n var segmentpoint1 = !Point.isEmptyPoint(segment.point1) ? segment.point1 : segment.bezierPoint1;\n var segmentpoint2 = !Point.isEmptyPoint(segment.point2) ? segment.point2 : segment.bezierPoint2;\n if (contains(this.currentPosition, segmentpoint1, connectors.hitPadding) ||\n contains(this.currentPosition, segmentpoint2, connectors.hitPadding)) {\n this.selectedSegment = segment;\n }\n }\n }\n this.currentPosition = args.position;\n };\n ConnectTool.prototype.mouseUp = function (args) {\n this.commandHandler.updateSelector();\n this.commandHandler.removeSnap();\n if ((!(this instanceof ConnectorDrawingTool)) && ((this.endPoint === 'ConnectorSourceEnd' &&\n ((!Point.equals(args.source.connectors[0].sourcePoint, this.undoElement.connectors[0].sourcePoint) ||\n (args.source.connectors[0].sourceID !== this.undoElement.connectors[0].sourceID)))) ||\n (this.endPoint === 'ConnectorTargetEnd' &&\n ((!Point.equals(args.source.connectors[0].targetPoint, this.undoElement.connectors[0].targetPoint))\n || (args.source.connectors[0].targetID !== this.undoElement.connectors[0].targetID))))) {\n var oldValues = void 0;\n var connector = void 0;\n if (args.source && args.source.connectors) {\n oldValues = {\n x: this.prevPosition.x, y: this.prevPosition.y\n };\n connector = args.source.connectors[0];\n }\n var targetPortName = void 0;\n var targetNodeNode = void 0;\n if (args.target) {\n var target = this.commandHandler.findTarget(args.targetWrapper, args.target, this.endPoint === 'ConnectorSourceEnd');\n (target instanceof PointPort) ? targetPortName = target.id : targetNodeNode = target.id;\n }\n var arg = {\n connector: connector, state: 'Completed', targetNode: targetNodeNode,\n oldValue: oldValues, newValue: oldValues, cancel: false, targetPort: targetPortName\n };\n var trigger = this.endPoint === 'ConnectorSourceEnd' ? DiagramEvent.sourcePointChange : DiagramEvent.targetPointChange;\n this.commandHandler.triggerEvent(trigger, arg);\n this.commandHandler.removeTerminalSegment(connector, true);\n if (this.undoElement && args.source) {\n var obj = void 0;\n obj = cloneObject(args.source);\n var entry = {\n type: 'ConnectionChanged', redoObject: cloneObject(obj), undoObject: cloneObject(this.undoElement),\n category: 'Internal'\n };\n this.commandHandler.addHistoryEntry(entry);\n }\n }\n else if (!(this instanceof ConnectorDrawingTool) &&\n (this.endPoint === 'BezierTargetThumb' || this.endPoint === 'BezierSourceThumb')) {\n if (this.undoElement && args.source) {\n var obj = void 0;\n obj = cloneObject(args.source);\n var entry = {\n type: 'SegmentChanged', redoObject: obj, undoObject: this.undoElement, category: 'Internal'\n };\n this.commandHandler.addHistoryEntry(entry);\n }\n }\n _super.prototype.mouseUp.call(this, args);\n };\n ConnectTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n if ((!(this instanceof ConnectorDrawingTool)) && ((this.endPoint === 'ConnectorSourceEnd' &&\n Point.equals(args.source.connectors[0].sourcePoint, this.undoElement.connectors[0].sourcePoint)) ||\n (this.endPoint === 'ConnectorTargetEnd' &&\n Point.equals(args.source.connectors[0].targetPoint, this.undoElement.connectors[0].targetPoint)))) {\n var oldValue = void 0;\n var connectors = void 0;\n if (args.source && args.source.connectors) {\n oldValue = { x: this.prevPosition.x, y: this.prevPosition.y };\n connectors = args.source.connectors[0];\n }\n var targetPort = void 0;\n var targetNode = void 0;\n if (args.target) {\n targetNode = args.target.id;\n var target = this.commandHandler.findTarget(args.targetWrapper, args.target, this.endPoint === 'ConnectorSourceEnd');\n (target instanceof PointPort || target instanceof BpmnSubEvent) ? targetPort = target.id : targetNode = target.id;\n }\n var arg = {\n connector: connectors, state: 'Start', targetNode: targetNode,\n oldValue: oldValue, newValue: oldValue, cancel: false, targetPort: targetPort\n };\n var trigger = this.endPoint === 'ConnectorSourceEnd' ?\n DiagramEvent.sourcePointChange : DiagramEvent.targetPointChange;\n this.commandHandler.triggerEvent(trigger, arg);\n }\n this.currentPosition = args.position;\n if (this.currentPosition && this.prevPosition) {\n var diffX = this.currentPosition.x - this.prevPosition.x;\n var diffY = this.currentPosition.y - this.prevPosition.y;\n var newValue = void 0;\n var oldValue = void 0;\n this.currentPosition = this.commandHandler.snapConnectorEnd(this.currentPosition);\n var connector = void 0;\n if (args.source && args.source.connectors) {\n newValue = {\n x: this.currentPosition.x, y: this.currentPosition.y,\n };\n oldValue = {\n x: this.prevPosition.x, y: this.prevPosition.y\n };\n connector = args.source.connectors[0];\n }\n var targetPortId = void 0;\n var targetNodeId = void 0;\n if (args.target) {\n var target = this.commandHandler.findTarget(args.targetWrapper, args.target, this.endPoint === 'ConnectorSourceEnd');\n (target instanceof PointPort) ? targetPortId = target.id : targetNodeId = target.id;\n }\n var arg = {\n connector: connector, state: 'Progress', targetNode: targetNodeId,\n oldValue: oldValue, newValue: newValue, cancel: false, targetPort: targetPortId\n };\n if (!(this instanceof ConnectorDrawingTool)) {\n var trigger = this.endPoint === 'ConnectorSourceEnd' ?\n DiagramEvent.sourcePointChange : DiagramEvent.targetPointChange;\n this.commandHandler.triggerEvent(trigger, arg);\n }\n if (!arg.cancel && this.inAction && this.endPoint !== undefined && diffX !== 0 || diffY !== 0) {\n this.blocked = !this.commandHandler.dragConnectorEnds(this.endPoint, args.source, this.currentPosition, this.selectedSegment, args.target, targetPortId);\n this.commandHandler.updateSelector();\n if (args.target && ((this.endPoint === 'ConnectorSourceEnd' && canOutConnect(args.target))\n || (this.endPoint === 'ConnectorTargetEnd' && canInConnect(args.target)))) {\n if (this.commandHandler.canDisconnect(this.endPoint, args, targetPortId, targetNodeId)) {\n this.commandHandler.disConnect(args.source, this.endPoint);\n }\n this.commandHandler.connect(this.endPoint, args);\n }\n else if (this.endPoint.indexOf('Bezier') === -1) {\n this.commandHandler.disConnect(args.source, this.endPoint);\n this.commandHandler.updateSelector();\n }\n }\n if (this.commandHandler.canEnableDefaultTooltip()) {\n var content = this.getTooltipContent(args.position);\n this.commandHandler.showTooltip(args.source, args.position, content, 'ConnectTool', this.isTooltipVisible);\n this.isTooltipVisible = false;\n }\n }\n this.prevPosition = this.currentPosition;\n return !this.blocked;\n };\n ConnectTool.prototype.mouseLeave = function (args) {\n this.mouseUp(args);\n };\n ConnectTool.prototype.getTooltipContent = function (position) {\n return 'X:' + Math.round(position.x) + ' ' + 'Y:' + Math.round(position.y);\n };\n ConnectTool.prototype.endAction = function () {\n _super.prototype.endAction.call(this);\n this.prevPosition = null;\n this.endPoint = null;\n };\n return ConnectTool;\n}(ToolBase));\nexport { ConnectTool };\n/**\n * Drags the selected objects\n */\nvar MoveTool = /** @class */ (function (_super) {\n __extends(MoveTool, _super);\n function MoveTool(commandHandler, objType) {\n var _this = _super.call(this, commandHandler, true) || this;\n _this.currentTarget = null;\n _this.objectType = objType;\n return _this;\n }\n MoveTool.prototype.mouseDown = function (args) {\n if (args.source instanceof Node || args.source instanceof Connector) {\n this.commandHandler.selectObjects([args.source], args.info && args.info.ctrlKey);\n var selectedObject = { nodes: [], connectors: [] };\n if (args.source instanceof Node) {\n selectedObject.nodes.push(cloneObject(args.source));\n }\n else {\n selectedObject.connectors.push(cloneObject(args.source));\n }\n this.undoElement = cloneObject(selectedObject);\n }\n else {\n this.undoElement = cloneObject(args.source);\n }\n this.undoParentElement = this.commandHandler.getSubProcess(args.source);\n _super.prototype.mouseDown.call(this, args);\n this.initialOffset = { x: 0, y: 0 };\n };\n MoveTool.prototype.mouseUp = function (args) {\n var obj;\n var historyAdded = false;\n if (this.objectType !== 'Port') {\n if (args.source instanceof Node || args.source instanceof Connector) {\n var redoObject = { nodes: [], connectors: [] };\n if (args.source instanceof Node) {\n redoObject.nodes.push(cloneObject(args.source));\n }\n else {\n redoObject.connectors.push(cloneObject(args.source));\n }\n obj = cloneObject(redoObject);\n var wrapper = args.source.wrapper;\n obj.offsetX = wrapper.offsetX;\n obj.offsetY = wrapper.offsetY;\n }\n else {\n obj = cloneObject(args.source);\n }\n if (obj.offsetX !== this.undoElement.offsetX || obj.offsetY !== this.undoElement.offsetY) {\n var oldValues = void 0;\n var newValues = void 0;\n if (args.source) {\n newValues = { offsetX: args.source.wrapper.offsetX, offsetY: args.source.wrapper.offsetY };\n oldValues = { offsetX: args.source.wrapper.offsetX, offsetY: args.source.wrapper.offsetY };\n }\n var arg = {\n source: args.source, state: 'Completed', oldValue: oldValues, newValue: newValues,\n target: this.currentTarget, targetPosition: this.currentPosition, allowDrop: true, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.positionChange, arg);\n this.commandHandler.startGroupAction();\n historyAdded = true;\n var entry = {\n type: 'PositionChanged',\n redoObject: cloneObject(obj), undoObject: cloneObject(this.undoElement), category: 'Internal'\n };\n if (obj.nodes[0] && obj.nodes[0].processId) {\n var entry_1 = {\n type: 'SizeChanged', category: 'Internal',\n undoObject: this.undoParentElement, redoObject: this.commandHandler.getSubProcess(args.source)\n };\n this.commandHandler.addHistoryEntry(entry_1);\n }\n this.commandHandler.addHistoryEntry(entry);\n }\n var snappedPoint = this.commandHandler.snapPoint(this.prevPosition, this.currentPosition, 0, 0);\n this.commandHandler.removeSnap();\n this.commandHandler.removeHighlighter();\n if (args.source && this.currentTarget && canAllowDrop(this.currentTarget) &&\n this.commandHandler.isDroppable(args.source, this.currentTarget)) {\n this.commandHandler.drop(this.currentElement, this.currentTarget, this.currentPosition);\n var arg = {\n element: args.source, target: this.currentTarget, position: this.currentPosition, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.drop, arg);\n }\n this.commandHandler.updateSelector();\n if (historyAdded) {\n this.commandHandler.endGroupAction();\n }\n }\n _super.prototype.mouseUp.call(this, args);\n };\n MoveTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n var isSame = false;\n if (args.source instanceof Node || args.source instanceof Connector) {\n if (args.source instanceof Node) {\n if (args.source.offsetX === this.undoElement.nodes[0].offsetX &&\n args.source.offsetY === this.undoElement.nodes[0].offsetY) {\n isSame = true;\n }\n }\n else {\n if (Point.equals(args.source.sourcePoint, this.undoElement.connectors[0].sourcePoint) &&\n Point.equals(args.source.targetPoint, this.undoElement.connectors[0].targetPoint)) {\n isSame = true;\n }\n }\n }\n else {\n if (args.source.wrapper.offsetX === this.undoElement.wrapper.offsetX &&\n args.source.wrapper.offsetY === this.undoElement.wrapper.offsetY) {\n isSame = true;\n }\n }\n var oldValues;\n if (args.source) {\n oldValues = { offsetX: args.source.wrapper.offsetX, offsetY: args.source.wrapper.offsetY };\n }\n var arg = {\n source: args.source, state: 'Start', oldValue: oldValues, newValue: oldValues,\n target: args.target, targetPosition: args.position, allowDrop: true, cancel: false\n };\n if (isSame) {\n this.commandHandler.triggerEvent(DiagramEvent.positionChange, arg);\n }\n this.currentPosition = args.position;\n if (this.objectType !== 'Port') {\n var x = this.currentPosition.x - this.prevPosition.x;\n var y = this.currentPosition.y - this.prevPosition.y;\n var diffX = this.initialOffset.x + (this.currentPosition.x - this.prevPosition.x);\n var diffY = this.initialOffset.y + (this.currentPosition.y - this.prevPosition.y);\n this.commandHandler.dragOverElement(args, this.currentPosition);\n this.commandHandler.disConnect(args.source);\n this.commandHandler.removeSnap();\n var oldValues_1;\n var newValues = void 0;\n var snappedPoint = this.commandHandler.snapPoint(this.prevPosition, this.currentPosition, diffX, diffY);\n this.initialOffset.x = diffX - snappedPoint.x;\n this.initialOffset.y = diffY - snappedPoint.y;\n if (args.source) {\n oldValues_1 = { offsetX: args.source.wrapper.offsetX, offsetY: args.source.wrapper.offsetY };\n newValues = {\n offsetX: args.source.wrapper.offsetX + snappedPoint.x,\n offsetY: args.source.wrapper.offsetY + snappedPoint.y\n };\n }\n if (this.currentTarget && args.target !== this.currentTarget) {\n this.commandHandler.removeChildFromBPmn(args.source, args.target, this.currentTarget);\n }\n this.currentTarget = args.target;\n var arg_1 = {\n source: args.source, state: 'Progress', oldValue: oldValues_1, newValue: newValues,\n target: args.target, targetPosition: args.position, allowDrop: true, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.positionChange, arg_1);\n if (!arg_1.cancel) {\n this.blocked = !this.commandHandler.dragSelectedObjects(snappedPoint.x, snappedPoint.y);\n var blocked = !(this.commandHandler.mouseOver(this.currentElement, this.currentTarget, this.currentPosition));\n this.blocked = this.blocked || blocked;\n }\n if (this.currentTarget && (args.source !== this.currentTarget) &&\n this.commandHandler.isDroppable(args.source, this.currentTarget)) {\n this.commandHandler.drawHighlighter(this.currentTarget);\n }\n else {\n this.commandHandler.removeHighlighter();\n }\n if (this.commandHandler.canEnableDefaultTooltip()) {\n var content = this.getTooltipContent(args.source);\n this.commandHandler.showTooltip(args.source, args.position, content, 'MoveTool', this.isTooltipVisible);\n this.isTooltipVisible = false;\n }\n }\n else {\n this.commandHandler.portDrag(args.source, args.sourceWrapper, args.position.x - this.prevPosition.x, args.position.y - this.prevPosition.y);\n }\n this.prevPosition = this.currentPosition;\n return !this.blocked;\n };\n MoveTool.prototype.getTooltipContent = function (node) {\n return 'X:' + Math.round(node.wrapper.bounds.x) + ' ' + 'Y:' + Math.round(node.wrapper.bounds.y);\n };\n MoveTool.prototype.mouseLeave = function (args) {\n this.mouseUp(args);\n };\n MoveTool.prototype.endAction = function () {\n _super.prototype.endAction.call(this);\n this.currentTarget = null;\n this.prevPosition = null;\n };\n return MoveTool;\n}(ToolBase));\nexport { MoveTool };\n/**\n * Rotates the selected objects\n */\nvar RotateTool = /** @class */ (function (_super) {\n __extends(RotateTool, _super);\n function RotateTool(commandHandler) {\n return _super.call(this, commandHandler, true) || this;\n }\n RotateTool.prototype.mouseDown = function (args) {\n this.undoElement = cloneObject(args.source);\n if (this.undoElement.nodes[0] && this.undoElement.nodes[0].children) {\n var objects = [];\n var nodes = this.commandHandler.getAllDescendants(this.undoElement.nodes[0], objects);\n for (var i = 0; i < nodes.length; i++) {\n var node = this.commandHandler.cloneChild(nodes[i].id);\n this.childTable[nodes[i].id] = cloneObject(node);\n }\n }\n _super.prototype.mouseDown.call(this, args);\n };\n RotateTool.prototype.mouseUp = function (args) {\n if (this.undoElement.rotateAngle !== args.source.wrapper.rotateAngle) {\n var oldValue = { rotateAngle: args.source.wrapper.rotateAngle };\n var arg = {\n source: args.source, state: 'Completed', oldValue: oldValue,\n newValue: oldValue, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.rotateChange, arg);\n var obj = void 0;\n obj = cloneObject(args.source);\n var entry = {\n type: 'RotationChanged', redoObject: cloneObject(obj), undoObject: cloneObject(this.undoElement), category: 'Internal',\n childTable: this.childTable\n };\n this.commandHandler.addHistoryEntry(entry);\n this.commandHandler.updateSelector();\n }\n _super.prototype.mouseUp.call(this, args);\n };\n RotateTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n if (this.undoElement.rotateAngle === args.source.wrapper.rotateAngle) {\n var oldValue_1 = { rotateAngle: args.source.wrapper.rotateAngle };\n var arg_2 = {\n source: args.source, state: 'Start', oldValue: oldValue_1, newValue: oldValue_1, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.rotateChange, arg_2);\n }\n this.currentPosition = args.position;\n var refPoint = { x: this.currentElement.wrapper.offsetX, y: this.currentElement.wrapper.offsetY };\n var angle = Point.findAngle(refPoint, this.currentPosition) + 90;\n var snapAngle = this.commandHandler.snapAngle(angle);\n angle = snapAngle !== 0 ? snapAngle : angle;\n angle = (angle + 360) % 360;\n var oldValue = { rotateAngle: args.source.wrapper.rotateAngle };\n var newValue = { rotateAngle: angle };\n var arg = {\n source: args.source, state: 'Progress', oldValue: oldValue,\n newValue: newValue, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.rotateChange, arg);\n if (!arg.cancel) {\n this.blocked = !(this.commandHandler.rotateSelectedItems(angle - this.currentElement.wrapper.rotateAngle));\n }\n if (this.commandHandler.canEnableDefaultTooltip()) {\n var content = this.getTooltipContent(args.source);\n this.commandHandler.showTooltip(args.source, args.position, content, 'RotateTool', this.isTooltipVisible);\n this.isTooltipVisible = false;\n }\n return !this.blocked;\n };\n RotateTool.prototype.getTooltipContent = function (node) {\n return Math.round((node.rotateAngle % 360)).toString() + '\\xB0';\n };\n RotateTool.prototype.mouseLeave = function (args) {\n this.mouseUp(args);\n };\n RotateTool.prototype.endAction = function () {\n _super.prototype.endAction.call(this);\n };\n return RotateTool;\n}(ToolBase));\nexport { RotateTool };\n/**\n * Scales the selected objects\n */\nvar ResizeTool = /** @class */ (function (_super) {\n __extends(ResizeTool, _super);\n function ResizeTool(commandHandler, corner) {\n var _this = _super.call(this, commandHandler, true) || this;\n _this.initialBounds = new Rect();\n _this.corner = corner;\n return _this;\n }\n ResizeTool.prototype.mouseDown = function (args) {\n this.undoElement = cloneObject(args.source);\n this.undoParentElement = this.commandHandler.getSubProcess(args.source);\n _super.prototype.mouseDown.call(this, args);\n if (this.undoElement.nodes[0] && this.undoElement.nodes[0].children) {\n var elements = [];\n var nodes = this.commandHandler.getAllDescendants(this.undoElement.nodes[0], elements);\n for (var i = 0; i < nodes.length; i++) {\n var node = this.commandHandler.cloneChild(nodes[i].id);\n this.childTable[nodes[i].id] = cloneObject(node);\n }\n }\n _super.prototype.mouseDown.call(this, args);\n this.initialBounds.x = args.source.wrapper.offsetX;\n this.initialBounds.y = args.source.wrapper.offsetY;\n this.initialBounds.height = args.source.wrapper.actualSize.height;\n this.initialBounds.width = args.source.wrapper.actualSize.width;\n };\n ResizeTool.prototype.mouseUp = function (args) {\n this.commandHandler.removeSnap();\n if (this.undoElement.offsetX !== args.source.wrapper.offsetX || this.undoElement.offsetY !== args.source.wrapper.offsetY) {\n this.blocked = this.updateSize(args.source, this.currentPosition, this.prevPosition, this.corner);\n var oldValue = {\n offsetX: args.source.wrapper.offsetX, offsetY: args.source.wrapper.offsetY,\n width: args.source.wrapper.actualSize.width, height: args.source.wrapper.actualSize.height\n };\n var arg = {\n source: args.source, state: 'Completed',\n oldValue: oldValue, newValue: oldValue, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.sizeChange, arg);\n var obj = cloneObject(args.source);\n var entry = {\n type: 'SizeChanged', redoObject: cloneObject(obj), undoObject: cloneObject(this.undoElement), category: 'Internal',\n childTable: this.childTable\n };\n this.commandHandler.startGroupAction();\n this.commandHandler.addHistoryEntry(entry);\n if (obj.nodes[0] && obj.nodes[0].processId) {\n var entry_2 = {\n type: 'SizeChanged', redoObject: this.commandHandler.getSubProcess(args.source),\n undoObject: this.undoParentElement, category: 'Internal'\n };\n this.commandHandler.addHistoryEntry(entry_2);\n }\n this.commandHandler.endGroupAction();\n }\n _super.prototype.mouseUp.call(this, args);\n return !this.blocked;\n };\n ResizeTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n if (this.undoElement.offsetX === args.source.wrapper.offsetX && this.undoElement.offsetY === args.source.wrapper.offsetY) {\n var oldValue = {\n offsetX: args.source.wrapper.offsetX, offsetY: args.source.wrapper.offsetY,\n width: args.source.wrapper.actualSize.width, height: args.source.wrapper.actualSize.height\n };\n var arg = {\n source: args.source, state: 'Start', oldValue: oldValue, newValue: this.currentElement, cancel: false\n };\n this.commandHandler.triggerEvent(DiagramEvent.sizeChange, arg);\n }\n this.currentPosition = args.position;\n var x = this.currentPosition.x - this.startPosition.x;\n var y = this.currentPosition.y - this.startPosition.y;\n var changes = { x: x, y: y };\n changes = rotatePoint(-this.currentElement.wrapper.rotateAngle, undefined, undefined, changes);\n var sx = (this.currentElement.wrapper.actualSize.width + changes.x) / this.currentElement.wrapper.actualSize.width;\n var sy = (this.currentElement.wrapper.actualSize.height + changes.y) / this.currentElement.wrapper.actualSize.height;\n changes = this.getChanges(changes);\n this.commandHandler.removeSnap();\n this.blocked = !(this.updateSize(args.source, this.startPosition, this.currentPosition, this.corner));\n if (this.commandHandler.canEnableDefaultTooltip()) {\n var content = this.getTooltipContent(args.source);\n this.commandHandler.showTooltip(args.source, args.position, content, 'ResizeTool', this.isTooltipVisible);\n this.isTooltipVisible = false;\n }\n this.prevPosition = this.currentPosition;\n return !this.blocked;\n };\n ResizeTool.prototype.mouseLeave = function (args) {\n this.mouseUp(args);\n };\n ResizeTool.prototype.getTooltipContent = function (node) {\n return 'W:' + Math.round(node.wrapper.bounds.width) + ' ' + 'H:' + Math.round(node.wrapper.bounds.height);\n };\n ResizeTool.prototype.getPivot = function () {\n switch (this.corner) {\n case 'ResizeWest':\n return { x: 1, y: 0.5 };\n case 'ResizeEast':\n return { x: 0, y: 0.5 };\n case 'ResizeNorth':\n return { x: 0.5, y: 1 };\n case 'ResizeSouth':\n return { x: 0.5, y: 0 };\n case 'ResizeNorthEast':\n return { x: 0, y: 1 };\n case 'ResizeNorthWest':\n return { x: 1, y: 1 };\n case 'ResizeSouthEast':\n return { x: 0, y: 0 };\n case 'ResizeSouthWest':\n return { x: 1, y: 0 };\n }\n return { x: 0.5, y: 0.5 };\n };\n ResizeTool.prototype.getChanges = function (change) {\n switch (this.corner) {\n case 'ResizeEast':\n return { x: change.x, y: 0 };\n case 'ResizeSouthEast':\n return change;\n case 'ResizeSouth':\n return { x: 0, y: change.y };\n case 'ResizeNorth':\n return { x: 0, y: -change.y };\n case 'ResizeNorthEast':\n return { x: change.x, y: -change.y };\n case 'ResizeNorthWest':\n return { x: -change.x, y: -change.y };\n case 'ResizeWest':\n return { x: -change.x, y: 0 };\n case 'ResizeSouthWest':\n return { x: -change.x, y: change.y };\n }\n return change;\n };\n /**\n * Updates the size with delta width and delta height using scaling.\n */\n ResizeTool.prototype.updateSize = function (shape, startPoint, endPoint, corner) {\n var horizontalsnap = { snapped: false, offset: 0, left: false, right: false };\n var verticalsnap = { snapped: false, offset: 0, top: false, bottom: false };\n var difx = this.currentPosition.x - this.startPosition.x;\n var dify = this.currentPosition.y - this.startPosition.y;\n var snapEnabled = this.commandHandler.snappingModule\n && this.commandHandler.snappingModule.canSnap();\n var snapLine = snapEnabled ? this.commandHandler.snappingModule.getLayer() : null;\n var matrix;\n matrix = identityMatrix();\n rotateMatrix(matrix, -shape.rotateAngle, 0, 0);\n var x = shape.offsetX;\n var y = shape.offsetY;\n var w = shape.width;\n var h = shape.height;\n x = x - w * shape.pivot.x;\n y = y - h * shape.pivot.y;\n var deltaWidth = 0;\n var deltaHeight = 0;\n var initialBounds = this.initialBounds;\n var diff;\n switch (corner) {\n case 'ResizeWest':\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n deltaHeight = 1;\n difx = snapEnabled ? this.commandHandler.snappingModule.snapLeft(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) : difx;\n dify = 0;\n deltaWidth = (initialBounds.width - difx) / shape.width;\n break;\n case 'ResizeEast':\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n difx = snapEnabled ? this.commandHandler.snappingModule.snapRight(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n difx;\n dify = 0;\n deltaWidth = (initialBounds.width + difx) / shape.width;\n deltaHeight = 1;\n break;\n case 'ResizeNorth':\n deltaWidth = 1;\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n dify = snapEnabled ? this.commandHandler.snappingModule.snapTop(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n dify;\n deltaHeight = (initialBounds.height - dify) / shape.height;\n break;\n case 'ResizeSouth':\n deltaWidth = 1;\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n dify = snapEnabled ? this.commandHandler.snappingModule.snapBottom(horizontalsnap, verticalsnap, snapLine, diff.x, diff.y, shape, endPoint === startPoint, this.initialBounds) :\n dify;\n deltaHeight = (initialBounds.height + dify) / shape.height;\n break;\n case 'ResizeNorthEast':\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n difx = snapEnabled ? this.commandHandler.snappingModule.snapRight(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n difx;\n dify = snapEnabled ? this.commandHandler.snappingModule.snapTop(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n dify;\n deltaWidth = (initialBounds.width + difx) / shape.width;\n deltaHeight = (initialBounds.height - dify) / shape.height;\n break;\n case 'ResizeNorthWest':\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n dify = snapEnabled ? this.commandHandler.snappingModule.snapTop(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n dify;\n difx = snapEnabled ? this.commandHandler.snappingModule.snapLeft(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n difx;\n deltaWidth = (initialBounds.width - difx) / shape.width;\n deltaHeight = (initialBounds.height - dify) / shape.height;\n break;\n case 'ResizeSouthEast':\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n dify = snapEnabled ? this.commandHandler.snappingModule.snapBottom(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n dify;\n difx = snapEnabled ? this.commandHandler.snappingModule.snapRight(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, this.initialBounds) :\n difx;\n deltaHeight = (initialBounds.height + dify) / shape.height;\n deltaWidth = (initialBounds.width + difx) / shape.width;\n break;\n case 'ResizeSouthWest':\n diff = transformPointByMatrix(matrix, ({ x: difx, y: dify }));\n difx = diff.x;\n dify = diff.y;\n dify = snapEnabled ? this.commandHandler.snappingModule.snapBottom(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, initialBounds) : dify;\n difx = snapEnabled ? this.commandHandler.snappingModule.snapLeft(horizontalsnap, verticalsnap, snapLine, difx, dify, shape, endPoint === startPoint, initialBounds) : difx;\n deltaWidth = (initialBounds.width - difx) / shape.width;\n deltaHeight = (initialBounds.height + dify) / shape.height;\n break;\n }\n return this.scaleObjects(matrix, deltaWidth, deltaHeight, corner, startPoint, endPoint, shape);\n };\n /**\n * Aspect ratio used to resize the width or height based on resizing the height or width\n */\n ResizeTool.prototype.scaleObjects = function (matrix, deltaWidth, deltaHeight, corner, startPoint, endPoint, source) {\n if (source.nodes.length === 1 && source.nodes[0].constraints & NodeConstraints.AspectRatio) {\n if (corner === 'ResizeWest' || corner === 'ResizeEast' || corner === 'ResizeNorth' || corner === 'ResizeSouth') {\n if (!(deltaHeight === 1 && deltaWidth === 1)) {\n deltaHeight = deltaWidth = Math.max(deltaHeight === 1 ? 0 : deltaHeight, deltaWidth === 1 ? 0 : deltaWidth);\n }\n }\n else if (startPoint !== endPoint) {\n deltaHeight = deltaWidth = Math.max(deltaHeight, deltaWidth);\n }\n else {\n deltaHeight = deltaWidth = 0;\n }\n }\n var oldValue = {\n offsetX: source.offsetX, offsetY: source.offsetY,\n width: source.width, height: source.height\n };\n this.blocked = this.commandHandler.scaleSelectedItems(deltaWidth, deltaHeight, this.getPivot());\n var newValue = {\n offsetX: source.offsetX, offsetY: source.offsetY,\n width: source.width, height: source.height\n };\n var arg = { source: source, state: 'Progress', oldValue: oldValue, newValue: newValue, cancel: false };\n this.commandHandler.triggerEvent(DiagramEvent.sizeChange, arg);\n if (arg.cancel) {\n this.commandHandler.scaleSelectedItems(1 / deltaWidth, 1 / deltaHeight, this.getPivot());\n }\n return this.blocked;\n };\n return ResizeTool;\n}(ToolBase));\nexport { ResizeTool };\n/**\n * Draws a node that is defined by the user\n */\nvar NodeDrawingTool = /** @class */ (function (_super) {\n __extends(NodeDrawingTool, _super);\n function NodeDrawingTool(commandHandler, sourceObject) {\n var _this = _super.call(this, commandHandler, true) || this;\n _this.sourceObject = sourceObject;\n return _this;\n }\n NodeDrawingTool.prototype.mouseDown = function (args) {\n _super.prototype.mouseDown.call(this, args);\n this.inAction = true;\n };\n NodeDrawingTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n var checkBoundaryConstraints;\n var node = {\n offsetX: this.currentPosition.x, width: 3, height: 3,\n offsetY: this.currentPosition.y\n };\n if (!this.drawingObject) {\n this.drawingObject = this.commandHandler.drawObject(node);\n }\n if (this.inAction && Point.equals(this.currentPosition, this.prevPosition) === false) {\n var rect = Rect.toBounds([this.prevPosition, this.currentPosition]);\n checkBoundaryConstraints = this.commandHandler.checkBoundaryConstraints(undefined, undefined, rect);\n if (checkBoundaryConstraints) {\n this.commandHandler.updateNodeDimension(this.drawingObject, rect);\n }\n }\n return checkBoundaryConstraints;\n };\n NodeDrawingTool.prototype.mouseUp = function (args) {\n var checkBoundaryConstraints;\n var rect = Rect.toBounds([this.prevPosition, this.currentPosition]);\n checkBoundaryConstraints = this.commandHandler.checkBoundaryConstraints(undefined, undefined, rect);\n if (this.drawingObject && this.drawingObject instanceof Node) {\n this.commandHandler.addObjectToDiagram(this.drawingObject);\n this.drawingObject = null;\n }\n _super.prototype.mouseUp.call(this, args);\n this.inAction = false;\n };\n NodeDrawingTool.prototype.endAction = function () {\n _super.prototype.endAction.call(this);\n };\n NodeDrawingTool.prototype.mouseLeave = function (args) {\n if (this.inAction) {\n this.mouseUp(args);\n }\n };\n return NodeDrawingTool;\n}(ToolBase));\nexport { NodeDrawingTool };\n/**\n * Draws a connector that is defined by the user\n */\nvar ConnectorDrawingTool = /** @class */ (function (_super) {\n __extends(ConnectorDrawingTool, _super);\n function ConnectorDrawingTool(commandHandler, endPoint, sourceObject) {\n var _this = _super.call(this, commandHandler, endPoint) || this;\n _this.sourceObject = sourceObject;\n return _this;\n }\n ConnectorDrawingTool.prototype.mouseDown = function (args) {\n _super.prototype.mouseDown.call(this, args);\n this.inAction = true;\n };\n ConnectorDrawingTool.prototype.mouseMove = function (args) {\n if (this.inAction) {\n var connector = {\n sourcePoint: this.currentPosition, targetPoint: this.currentPosition,\n };\n if (!this.drawingObject) {\n this.drawingObject = this.commandHandler.drawObject(connector);\n }\n args.source = this.drawingObject;\n if (args.target) {\n this.commandHandler.connect(this.endPoint, args);\n }\n this.endPoint = 'ConnectorTargetEnd';\n }\n if (!this.inAction) {\n this.commandHandler.updateSelector();\n if (args.source && args.sourceWrapper) {\n this.commandHandler.renderHighlighter(args, true);\n }\n }\n _super.prototype.mouseMove.call(this, args);\n return !this.blocked;\n };\n ConnectorDrawingTool.prototype.mouseUp = function (args) {\n if (this.drawingObject && this.drawingObject instanceof Connector) {\n this.commandHandler.addObjectToDiagram(this.drawingObject);\n this.drawingObject = null;\n }\n this.inAction = false;\n _super.prototype.mouseUp.call(this, args);\n };\n ConnectorDrawingTool.prototype.endAction = function () {\n _super.prototype.endAction.call(this);\n };\n ConnectorDrawingTool.prototype.mouseLeave = function (args) {\n if (this.inAction) {\n this.mouseUp(args);\n }\n };\n return ConnectorDrawingTool;\n}(ConnectTool));\nexport { ConnectorDrawingTool };\nvar TextDrawingTool = /** @class */ (function (_super) {\n __extends(TextDrawingTool, _super);\n function TextDrawingTool(commandHandler) {\n return _super.call(this, commandHandler, true) || this;\n }\n TextDrawingTool.prototype.mouseDown = function (args) {\n _super.prototype.mouseDown.call(this, args);\n this.commandHandler.clearSelection();\n var node = {\n shape: { type: 'Text' },\n offsetX: this.currentPosition.x, width: 50, height: 20,\n offsetY: this.currentPosition.y\n };\n if (!args.source) {\n this.drawingNode = this.commandHandler.drawObject(node);\n }\n };\n TextDrawingTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n if (!this.drawingNode) {\n var node = {\n shape: { type: 'Text' }, offsetX: this.currentPosition.x, width: 30, height: 30,\n style: { strokeDashArray: '2 2', fill: 'transparent' }, offsetY: this.currentPosition.y\n };\n this.drawingNode = this.commandHandler.drawObject(node);\n }\n else {\n this.drawingNode.style.strokeColor = 'black';\n this.drawingNode.style.strokeDashArray = '2 2';\n this.drawingNode.style.fill = 'transparent';\n }\n if (this.inAction && Point.equals(this.currentPosition, this.prevPosition) === false) {\n var rect = Rect.toBounds([this.prevPosition, this.currentPosition]);\n this.commandHandler.updateNodeDimension(this.drawingNode, rect);\n }\n return !this.blocked;\n };\n TextDrawingTool.prototype.mouseUp = function (args) {\n if (this.drawingNode) {\n this.drawingNode.style.strokeColor = 'none';\n this.drawingNode.style.fill = 'none';\n }\n else {\n this.drawingNode = args.source;\n }\n if (this.drawingNode && (this.drawingNode instanceof Node || this.drawingNode instanceof Connector)) {\n this.commandHandler.addText(this.drawingNode, this.currentPosition);\n }\n _super.prototype.mouseUp.call(this, args);\n this.inAction = false;\n };\n TextDrawingTool.prototype.endAction = function () {\n _super.prototype.endAction.call(this);\n };\n return TextDrawingTool;\n}(ToolBase));\nexport { TextDrawingTool };\n/**\n * Pans the diagram control on drag\n */\nvar ZoomPanTool = /** @class */ (function (_super) {\n __extends(ZoomPanTool, _super);\n function ZoomPanTool(commandHandler, zoom) {\n var _this = _super.call(this, commandHandler) || this;\n _this.zooming = zoom;\n return _this;\n }\n ZoomPanTool.prototype.mouseDown = function (args) {\n _super.prototype.mouseDown.call(this, args);\n this.inAction = true;\n };\n ZoomPanTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n if (this.inAction) {\n if (!this.zooming && Point.equals(this.currentPosition, this.prevPosition) === false) {\n var difX = this.currentPosition.x - this.prevPosition.x;\n var difY = this.currentPosition.y - this.prevPosition.y;\n this.commandHandler.scroll(difX, difY, this.currentPosition);\n }\n else if (args.moveTouches.length >= 2) {\n var startTouch0 = args.startTouches[0];\n var startTouch1 = args.startTouches[1];\n var moveTouch0 = args.moveTouches[0];\n var moveTouch1 = args.moveTouches[1];\n var scale = this.getDistance(moveTouch0, moveTouch1) / this.getDistance(startTouch0, startTouch1);\n var focusPoint = args.position;\n this.commandHandler.zoom(scale, 0, 0, focusPoint);\n this.updateTouch(startTouch0, moveTouch0);\n this.updateTouch(startTouch1, moveTouch1);\n }\n }\n return !this.blocked;\n };\n ZoomPanTool.prototype.mouseUp = function (args) {\n _super.prototype.mouseUp.call(this, args);\n this.inAction = false;\n };\n ZoomPanTool.prototype.endAction = function () {\n _super.prototype.endAction.call(this);\n };\n ZoomPanTool.prototype.getDistance = function (touch1, touch2) {\n var x = touch2.pageX - touch1.pageX;\n var y = touch2.pageY - touch1.pageY;\n return Math.sqrt((x * x) + (y * y));\n };\n ZoomPanTool.prototype.updateTouch = function (startTouch, moveTouch) {\n startTouch.pageX = moveTouch.pageX;\n startTouch.pageY = moveTouch.pageY;\n };\n return ZoomPanTool;\n}(ToolBase));\nexport { ZoomPanTool };\n/**\n * Animate the layout during expand and collapse\n */\nvar ExpandTool = /** @class */ (function (_super) {\n __extends(ExpandTool, _super);\n function ExpandTool(commandHandler) {\n return _super.call(this, commandHandler, true) || this;\n }\n ExpandTool.prototype.mouseUp = function (args) {\n this.commandHandler.initExpand(args);\n _super.prototype.mouseUp.call(this, args);\n };\n return ExpandTool;\n}(ToolBase));\nexport { ExpandTool };\n/**\n * Opens the annotation hypeLink at mouse up\n */\nvar LabelTool = /** @class */ (function (_super) {\n __extends(LabelTool, _super);\n function LabelTool(commandHandler) {\n return _super.call(this, commandHandler, true) || this;\n }\n LabelTool.prototype.mouseUp = function (args) {\n var win = window.open(args.sourceWrapper.hyperlink.link, '_blank');\n win.focus();\n _super.prototype.mouseUp.call(this, args);\n };\n return LabelTool;\n}(ToolBase));\nexport { LabelTool };\n/**\n * Draws a Polygon shape node dynamically using polygon Tool\n */\nvar PolygonDrawingTool = /** @class */ (function (_super) {\n __extends(PolygonDrawingTool, _super);\n function PolygonDrawingTool(commandHandler) {\n return _super.call(this, commandHandler, true) || this;\n }\n PolygonDrawingTool.prototype.mouseDown = function (args) {\n _super.prototype.mouseDown.call(this, args);\n this.inAction = true;\n if (!this.drawingObject) {\n this.startPoint = { x: this.startPosition.x, y: this.startPosition.y };\n var node = {\n offsetX: this.currentPosition.x,\n offsetY: this.currentPosition.y,\n width: 5, height: 5,\n style: { strokeColor: 'black', strokeWidth: 1 },\n shape: {\n type: 'Basic',\n shape: 'Polygon',\n points: [{ x: this.startPoint.x, y: this.startPoint.y }, { x: this.currentPosition.x, y: this.currentPosition.y }]\n }\n };\n this.drawingObject = this.commandHandler.drawObject(node);\n }\n else {\n var pt = void 0;\n var obj = this.drawingObject.shape;\n pt = obj.points[obj.points.length - 1];\n pt = { x: pt.x, y: pt.y };\n this.drawingObject.shape.points.push(pt);\n }\n };\n PolygonDrawingTool.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n if (this.inAction) {\n var obj = this.drawingObject.shape;\n if (this.drawingObject && this.currentPosition) {\n obj.points[obj.points.length - 1].x = this.currentPosition.x;\n obj.points[obj.points.length - 1].y = this.currentPosition.y;\n this.drawingObject.wrapper.children[0].data = getPolygonPath(this.drawingObject.shape.points);\n if (this.inAction && Point.equals(this.currentPosition, this.prevPosition) === false) {\n var region = Rect.toBounds(this.drawingObject.shape.points);\n this.commandHandler.updateNodeDimension(this.drawingObject, region);\n }\n }\n }\n return true;\n };\n PolygonDrawingTool.prototype.mouseUp = function (args, dblClickArgs) {\n _super.prototype.mouseMove.call(this, args);\n if (this.inAction) {\n this.inAction = false;\n if (this.drawingObject) {\n this.commandHandler.addObjectToDiagram(this.drawingObject);\n }\n }\n this.endAction();\n };\n PolygonDrawingTool.prototype.mouseWheel = function (args) {\n _super.prototype.mouseWheel.call(this, args);\n this.mouseMove(args);\n };\n PolygonDrawingTool.prototype.endAction = function () {\n this.inAction = false;\n this.drawingObject = null;\n };\n return PolygonDrawingTool;\n}(ToolBase));\nexport { PolygonDrawingTool };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Point } from '../primitives/point';\nimport { Rect } from '../primitives/rect';\nimport { intersect3 } from '../utility/diagram-util';\nimport { cloneObject } from '../utility/base-util';\nimport { contains } from './actions';\nimport { getOppositeDirection } from '../utility/connector';\nimport { StraightSegment, OrthogonalSegment } from '../objects/connector';\nimport { ToolBase } from './tool';\n/**\n * Multiple segments editing for Connector\n */\nvar ConnectorEditing = /** @class */ (function (_super) {\n __extends(ConnectorEditing, _super);\n function ConnectorEditing(commandHandler, endPoint) {\n var _this = _super.call(this, commandHandler, true) || this;\n _this.endPoint = endPoint;\n return _this;\n }\n ConnectorEditing.prototype.mouseDown = function (args) {\n this.inAction = true;\n this.undoElement = cloneObject(args.source);\n _super.prototype.mouseDown.call(this, args);\n var connectors;\n if (args.source && args.source.connectors) {\n connectors = args.source.connectors[0];\n }\n // Sets the selected segment \n for (var i = 0; i < connectors.segments.length; i++) {\n var segment = connectors.segments[i];\n if (this.endPoint === 'OrthoThumb') {\n for (var j = 0; j < segment.points.length - 1; j++) {\n var segPoint = { x: 0, y: 0 };\n segPoint.x = ((segment.points[j].x + segment.points[j + 1].x) / 2);\n segPoint.y = ((segment.points[j].y + segment.points[j + 1].y) / 2);\n if (contains(this.currentPosition, segPoint, 30)) {\n this.selectedSegment = segment;\n this.segmentIndex = j;\n }\n }\n }\n else {\n if (contains(this.currentPosition, segment.point, 10)) {\n this.selectedSegment = segment;\n }\n }\n }\n };\n ConnectorEditing.prototype.mouseMove = function (args) {\n _super.prototype.mouseMove.call(this, args);\n this.currentPosition = args.position;\n if (this.currentPosition && this.prevPosition) {\n var diffY = this.currentPosition.y - this.prevPosition.y;\n var diffX = this.currentPosition.x - this.prevPosition.x;\n this.currentPosition = this.commandHandler.snapConnectorEnd(this.currentPosition);\n var connector = void 0;\n if (args.source && args.source.connectors) {\n connector = args.source.connectors[0];\n }\n if (this.inAction && this.endPoint !== undefined && diffX !== 0 || diffY !== 0) {\n if (this.endPoint === 'OrthoThumb') {\n this.blocked = !this.dragOrthogonalSegment(connector, this.selectedSegment, this.currentPosition, this.segmentIndex);\n }\n else {\n var tx = this.currentPosition.x - this.selectedSegment.point.x;\n var ty = this.currentPosition.y - this.selectedSegment.point.y;\n var index = connector.segments.indexOf(this.selectedSegment);\n this.blocked = !this.commandHandler.dragControlPoint(connector, tx, ty, false, index);\n }\n this.commandHandler.updateSelector();\n }\n }\n this.prevPosition = this.currentPosition;\n return !this.blocked;\n };\n ConnectorEditing.prototype.mouseUp = function (args) {\n var connector;\n if (args.source && args.source.connectors) {\n connector = args.source.connectors[0];\n }\n if (args && args.source && args.info && args.info.ctrlKey && args.info.shiftKey && connector.type === 'Straight') {\n this.addOrRemoveSegment(connector, this.currentPosition);\n }\n else {\n if (this.endPoint === 'OrthoThumb' && this.selectedSegment) {\n var index = connector.segments.indexOf(this.selectedSegment);\n var prev = connector.segments[index - 1];\n var next = connector.segments[index + 1];\n if (index === connector.segments.length - 2\n && this.updateLastSegment(connector, this.selectedSegment)) {\n connector.segments.splice(connector.segments.length - 2, 1);\n }\n else {\n if (prev && Math.abs(prev.length) < 5) {\n if (index !== 1) {\n this.removePrevSegment(connector, index);\n }\n }\n else if (next) {\n var len = Point.distancePoints(next.points[0], next.points[1]);\n var length_1 = ((next.length || next.length === 0) ? next.length : len);\n if ((Math.abs(length_1) <= 5)) {\n this.removeNextSegment(connector, index);\n }\n }\n }\n this.commandHandler.updateEndPoint(connector);\n }\n }\n if (this.undoElement) {\n var obj = void 0;\n obj = cloneObject(args.source);\n var entry = {\n type: 'SegmentChanged', redoObject: obj, undoObject: this.undoElement, category: 'Internal'\n };\n this.commandHandler.addHistoryEntry(entry);\n }\n _super.prototype.mouseUp.call(this, args);\n };\n ConnectorEditing.prototype.removePrevSegment = function (connector, index) {\n var first = connector.segments[index - 2];\n var next = connector.segments[index + 1];\n var length = (next.length || next.length === 0) ? next.length : Point.distancePoints(next.points[0], next.points[1]);\n if (!(length <= 5)) {\n var last = connector.segments[index + 1];\n connector.segments.splice(index - 1, 2);\n var segment = this.selectedSegment;\n if (segment.direction === 'Left' || segment.direction === 'Right') {\n first.points[first.points.length - 1].x = last.points[0].x;\n last.points[0].y = first.points[first.points.length - 1].y;\n }\n else {\n first.points[first.points.length - 1].y = last.points[0].y;\n last.points[0].x = first.points[first.points.length - 1].x;\n }\n if (segment.length || segment.length === 0) {\n this.findSegmentDirection(first);\n }\n this.findSegmentDirection(last);\n }\n };\n ConnectorEditing.prototype.findSegmentDirection = function (segment) {\n if (segment.direction && (segment.length || segment.length === 0)) {\n segment.length = Point.distancePoints(segment.points[0], segment.points[segment.points.length - 1]);\n segment.direction = Point.direction(segment.points[0], segment.points[segment.points.length - 1]);\n }\n };\n ConnectorEditing.prototype.removeNextSegment = function (connector, index) {\n var segment = this.selectedSegment;\n var first = connector.segments[index - 1];\n var last = connector.segments[index + 2];\n var next = connector.segments[index + 1];\n if (next.length || next.length === 0) {\n connector.segments.splice(index, 2);\n if (segment.direction === 'Top' || segment.direction === 'Bottom') {\n last.points[0].y = segment.points[0].y;\n first.points[first.points.length - 1].x = last.points[0].x;\n }\n else {\n last.points[0].x = segment.points[0].x;\n first.points[first.points.length - 1].y = last.points[0].y;\n }\n }\n else {\n connector.segments.splice(index + 1, 1);\n if (segment.direction === 'Top' || segment.direction === 'Bottom') {\n first.points[first.points.length - 1].x = next.points[next.points.length - 1].x;\n }\n else {\n first.points[first.points.length - 1].y = next.points[next.points.length - 1].y;\n }\n this.findSegmentDirection(first);\n segment.length = segment.direction = null;\n }\n if (first && last) {\n first.length = Point.distancePoints(first.points[0], last.points[0]);\n first.direction = Point.direction(first.points[0], last.points[0]);\n if (last.length || last.length === 0) {\n last.length = Point.distancePoints(first.points[first.points.length - 1], last.points[last.points.length - 1]);\n var point1 = first.points;\n var point2 = last.points;\n last.direction = Point.direction(point1[point1.length - 1], point2[point2.length - 1]);\n }\n }\n };\n ConnectorEditing.prototype.addOrRemoveSegment = function (connector, point) {\n var updateSeg;\n var segmentIndex;\n for (var i = 0; i < connector.segments.length; i++) {\n var segment = (connector.segments)[i];\n if (contains(point, segment.point, connector.hitPadding)) {\n segmentIndex = i;\n updateSeg = true;\n }\n }\n if (updateSeg && segmentIndex !== undefined) {\n if (connector.segments && connector.segments[segmentIndex] && connector.segments[segmentIndex].type === 'Straight') {\n var segment = connector.segments[segmentIndex];\n var previous = connector.segments[segmentIndex + 1];\n if (previous) {\n connector.segments.splice(segmentIndex, 1);\n previous.points[0] = segment.points[0];\n }\n }\n }\n else {\n var index = this.findIndex(connector, point);\n if (connector.segments && connector.segments[index] && connector.segments[index].type === 'Straight') {\n var segment = connector.segments[index];\n var newseg = new StraightSegment(connector, 'segments', { type: 'Straight', point: point }, true);\n newseg.points[0] = segment.points[0];\n newseg.points[1] = point;\n segment.points[0] = point;\n connector.segments.splice(index, 0, newseg);\n updateSeg = true;\n }\n }\n if (updateSeg) {\n this.commandHandler.updateEndPoint(connector);\n }\n };\n ConnectorEditing.prototype.findIndex = function (connector, point) {\n var intersectingSegs = [];\n for (var i = 0; i < connector.segments.length; i++) {\n var segment = connector.segments[i];\n var rect = Rect.toBounds([segment.points[0], segment.points[1]]);\n rect.Inflate(connector.hitPadding);\n if (rect.containsPoint(point)) {\n intersectingSegs.push(segment);\n }\n }\n if (intersectingSegs.length === 1) {\n return connector.segments.indexOf(intersectingSegs[0]);\n }\n else {\n var ratio = void 0;\n var min = void 0;\n var index = void 0;\n var seg = void 0;\n var v = void 0;\n var h = void 0;\n for (var i = 0; i < intersectingSegs.length; i++) {\n seg = intersectingSegs[i];\n v = (point.y - seg.points[0].y) / (seg.points[1].y - point.y);\n h = (point.x - seg.points[0].x) / (seg.points[1].x - point.x);\n ratio = Math.abs(v - h);\n if (i === 0) {\n min = ratio;\n index = 0;\n }\n if (ratio < min) {\n min = ratio;\n index = i;\n }\n }\n return connector.segments.indexOf(intersectingSegs[index]);\n }\n };\n ConnectorEditing.prototype.dragOrthogonalSegment = function (obj, segment, point, segmentIndex) {\n var segmentPoint = { x: 0, y: 0 };\n segmentPoint.x = ((segment.points[segmentIndex].x + segment.points[segmentIndex + 1].x) / 2);\n segmentPoint.y = ((segment.points[segmentIndex].y + segment.points[segmentIndex + 1].y) / 2);\n var ty = point.y - segmentPoint.y;\n var tx = point.x - segmentPoint.x;\n var index = obj.segments.indexOf(segment);\n var update = false;\n var orientation = (segment.points[0].y.toFixed(2) === segment.points[1].y.toFixed(2)) ? 'horizontal' : 'vertical';\n var prevSegment;\n var nextSegment;\n if (index !== -1) {\n if (index === 0 && obj.segments.length === 1 && segment.points.length === 2) {\n index = this.addSegments(obj, segment, tx, ty, index);\n update = true;\n }\n else if (index === obj.segments.length - 1 && (segment.direction === null || segment.length === null)) {\n index = this.addTerminalSegment(obj, segment, tx, ty, segmentIndex);\n update = true;\n }\n else if (index === 0) {\n index = this.insertFirstSegment(obj, segment, tx, ty, index);\n update = true;\n }\n if (update) {\n this.selectedSegment = segment = obj.segments[index];\n this.segmentIndex = 0;\n }\n this.updateAdjacentSegments(obj, index, tx, ty);\n this.commandHandler.updateEndPoint(obj);\n }\n return true;\n };\n ConnectorEditing.prototype.addSegments = function (obj, segment, tx, ty, coll) {\n var index;\n var direction;\n var segments = [];\n var len;\n var length = Point.distancePoints(segment.points[0], segment.points[1]);\n var segmentDirection = Point.direction(segment.points[0], segment.points[1]);\n segments.push(new OrthogonalSegment(obj, 'segments', { type: 'Orthogonal', direction: segmentDirection, length: length / 4 }, true));\n direction = (segment.points[0].y === segment.points[1].y) ? ((ty > 0) ? 'Bottom' : 'Top') : ((tx > 0) ? 'Right' : 'Left');\n len = (segment.points[0].x === segment.points[1].x) ? ty : tx;\n segments.push(new OrthogonalSegment(obj, 'segments', { type: 'Orthogonal', direction: direction, length: len }, true));\n segments.push(new OrthogonalSegment(obj, 'segments', { type: 'Orthogonal', direction: segmentDirection, length: length / 2 }, true));\n obj.segments = segments.concat(obj.segments);\n index = coll + 2;\n return index;\n };\n ConnectorEditing.prototype.insertFirstSegment = function (obj, segment, tx, ty, coll) {\n var direction;\n var length;\n var segments = [];\n var segValues;\n var index;\n var insertseg;\n if (obj.sourcePortID && segment.length && obj.segments[0].points.length > 2) {\n obj.segments.splice(0, 1);\n var prev = void 0;\n for (var i = 0; i < segment.points.length - 1; i++) {\n var len = Point.distancePoints(segment.points[i], segment.points[i + 1]);\n var dir = Point.direction(segment.points[i], segment.points[i + 1]);\n insertseg = new OrthogonalSegment(obj, 'segments', { type: 'Orthogonal', direction: dir, length: len }, true);\n if (insertseg.length === 0) {\n if (prev && (prev.direction === 'Top' || prev.direction === 'Bottom')) {\n insertseg.direction = tx > 0 ? 'Right' : 'Left';\n }\n else {\n insertseg.direction = ty > 0 ? 'Bottom' : 'Top';\n }\n }\n prev = insertseg;\n segments.push(insertseg);\n }\n obj.segments = segments.concat(obj.segments);\n index = 1;\n }\n else {\n segValues = { type: 'Orthogonal', direction: segment.direction, length: segment.length / 3 };\n segments.push(new OrthogonalSegment(obj, 'segments', segValues, true));\n if (segment.direction === 'Bottom' || segment.direction === 'Top') {\n length = Math.abs(tx);\n direction = tx > 0 ? 'Right' : 'Left';\n }\n else {\n length = Math.abs(ty);\n direction = ty > 0 ? 'Bottom' : 'Top';\n }\n insertseg = new OrthogonalSegment(obj, 'segments', { type: 'Orthogonal', direction: direction, length: length }, true);\n segments.push(insertseg);\n var nextseg = obj.segments[1];\n if (nextseg && nextseg.length) {\n nextseg.length = (direction !== nextseg.direction) ? nextseg.length + length : nextseg.length - length;\n }\n index = 2;\n segment.length = 2 * segment.length / 3;\n obj.segments = segments.concat(obj.segments);\n }\n return index;\n };\n ConnectorEditing.prototype.updateAdjacentSegments = function (obj, index, tx, ty) {\n var current = obj.segments[index];\n var endPoint = current.points[current.points.length - 1];\n var startPoint = current.points[0];\n var isNextUpdate = true;\n if (current.type === 'Orthogonal') {\n current.points[0] = startPoint;\n current.points[current.points.length - 1] = endPoint;\n var prev = obj.segments[index - 1];\n if (prev) {\n isNextUpdate = this.updatePreviousSegment(tx, ty, obj, index);\n }\n if (obj.segments.length - 1 > index && isNextUpdate) {\n var nextSegment = obj.segments[index + 1];\n this.updateNextSegment(obj, current, nextSegment, tx, ty);\n }\n }\n };\n ConnectorEditing.prototype.addTerminalSegment = function (connector, segment, tx, ty, segmentIndex) {\n var index = connector.segments.indexOf(segment);\n var first;\n var insertseg;\n var len;\n var dir;\n connector.segments.pop();\n var last = connector.segments[connector.segments.length - 1];\n first = (last && last.type === 'Orthogonal') ? last : null;\n for (var i = 0; i < segment.points.length - 2; i++) {\n len = Point.distancePoints(segment.points[i], segment.points[i + 1]);\n dir = Point.direction(segment.points[i], segment.points[i + 1]);\n insertseg = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal', length: len, direction: dir }, true);\n connector.segments.push(insertseg);\n first = insertseg;\n }\n var sec = segmentIndex;\n if (segment.points.length === 2 || sec === segment.points.length - 2) {\n if (first) {\n first.length += 5;\n }\n if (sec !== undefined) {\n var newseg = void 0;\n len = 2 * Point.distancePoints(segment.points[segment.points.length - 2], segment.points[segment.points.length - 1]) / 3;\n dir = Point.direction(segment.points[segment.points.length - 2], segment.points[segment.points.length - 1]);\n newseg = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal', length: len, direction: dir });\n connector.segments.push(newseg);\n }\n }\n var lastseg = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n connector.segments.push(lastseg);\n this.commandHandler.updateEndPoint(connector);\n index = index + segmentIndex;\n return index;\n };\n ConnectorEditing.prototype.updatePortSegment = function (prev, connector, index, tx, ty) {\n if (index === 1 && prev.points.length === 2 && prev.length < 0) {\n var source = connector.sourceWrapper.corners;\n var current = connector.segments[index];\n var next = connector.segments[index + 1];\n var newseg = void 0;\n var segment = [];\n newseg = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal', length: 13, direction: prev.direction });\n segment.push(newseg);\n var len = void 0;\n if (current.direction === 'Left') {\n len = (current.points[0].x - (source.middleLeft.x - 20));\n }\n else if (current.direction === 'Right') {\n len = ((source.middleRight.x + 20) - current.points[0].x);\n }\n else if (current.direction === 'Bottom') {\n len = ((source.bottomCenter.y + 20) - current.points[0].y);\n }\n else {\n len = (current.points[0].y - (source.topCenter.y - 20));\n }\n var dir = current.direction;\n newseg = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal', length: len, direction: current.direction });\n segment.push(newseg);\n current.length = current.length - len;\n if (next && next.length && next.direction) {\n if (next.direction === prev.direction) {\n next.length -= 13;\n }\n else if (next.direction === getOppositeDirection(prev.direction)) {\n next.length += 13;\n }\n }\n connector.segments = segment.concat(connector.segments);\n this.selectedSegment = connector.segments[3];\n }\n };\n ConnectorEditing.prototype.updatePreviousSegment = function (tx, ty, connector, index) {\n var current = connector.segments[index];\n var prev = connector.segments[index - 1];\n var firstSegment = (index === 1) ? true : false;\n prev.points[prev.points.length - 1] = current.points[0];\n var isSourceNode = (connector.sourceID && connector.sourcePortID === '') ? false : true;\n var isNextUpdate = true;\n if (prev.type === 'Orthogonal') {\n if (prev.direction === 'Bottom') {\n prev.length += ty;\n }\n else if (prev.direction === 'Top') {\n prev.length -= ty;\n }\n else if (prev.direction === 'Right') {\n prev.length += tx;\n }\n else {\n prev.length -= tx;\n }\n if (connector.sourcePortID !== '' && prev.length < 0) {\n this.updatePortSegment(prev, connector, index, tx, ty);\n }\n else if (connector.sourceID && connector.sourcePortID === '' && prev.length < 0 && index === 1) {\n isNextUpdate = false;\n this.updateFirstSegment(connector, current);\n }\n if (isSourceNode) {\n this.changeSegmentDirection(prev);\n }\n }\n return isNextUpdate;\n };\n ConnectorEditing.prototype.changeSegmentDirection = function (segment) {\n if (segment.length < 0) {\n segment.direction = getOppositeDirection(segment.direction);\n segment.length *= -1;\n }\n };\n ConnectorEditing.prototype.updateNextSegment = function (obj, current, next, tx, ty) {\n var pt = current.points[current.points.length - 1];\n next.points[0] = current.points[current.points.length - 1];\n if (next && next.type === 'Orthogonal') {\n if (next.length || next.length === 0) {\n if (next.direction === 'Left' || next.direction === 'Right') {\n if (tx !== 0) {\n next.length = (next.direction === 'Right') ? next.length - tx : next.length + tx;\n if (next.length || next.length === 0) {\n this.changeSegmentDirection(next);\n }\n }\n }\n else {\n if (ty !== 0) {\n next.length = (next.direction === 'Bottom') ? next.length - ty : next.length + ty;\n if (next.length || next.length === 0) {\n this.changeSegmentDirection(next);\n }\n }\n }\n }\n }\n };\n ConnectorEditing.prototype.updateFirstSegment = function (connector, selectedSegment) {\n var index = connector.segments.indexOf(selectedSegment);\n var insertfirst = false;\n var current = connector.segments[index];\n var prev = connector.segments[index - 1];\n var con = connector;\n var sourcePoint;\n if (prev.length < 0 && connector.sourceID) {\n var sourceNode = connector.sourceWrapper.corners;\n var segments = [];\n var segValues = void 0;\n var removeCurrentPrev = false;\n this.changeSegmentDirection(current);\n var next = connector.segments[index + 1];\n var nextNext = connector.segments[index + 2];\n if (next) {\n this.changeSegmentDirection(next);\n }\n if (nextNext) {\n this.changeSegmentDirection(nextNext);\n }\n switch (prev.direction) {\n case 'Top':\n case 'Bottom':\n sourcePoint = (current.length > 0 && current.direction === 'Left') ? sourceNode.middleLeft : sourceNode.middleRight;\n if (current.length > sourceNode.width / 2) {\n if (Math.abs(prev.length) < sourceNode.height / 2) {\n prev.length = Point.distancePoints(sourceNode.center, prev.points[prev.points.length - 1]);\n current.points[0].x = sourcePoint.x;\n current.length = Point.distancePoints(current.points[0], current.points[current.points.length - 1]);\n current.length -= 20;\n insertfirst = true;\n }\n }\n else {\n if (next && next.direction && next.length) {\n next.points[0].y = sourcePoint.y;\n next.points[0].x = next.points[next.points.length - 1].x = (current.direction === 'Right') ?\n sourcePoint.x + 20 : sourcePoint.x - 20;\n }\n insertfirst = true;\n removeCurrentPrev = true;\n }\n break;\n case 'Left':\n case 'Right':\n sourcePoint = (current.length > 0 && current.direction === 'Top') ? sourceNode.topCenter : sourceNode.bottomCenter;\n if (current.length > sourceNode.height / 2) {\n if (Math.abs(prev.length) < sourceNode.width / 2) {\n prev.length = Point.distancePoints(sourceNode.center, prev.points[prev.points.length - 1]);\n current.points[0].y = sourcePoint.y;\n current.length = Point.distancePoints(current.points[0], current.points[current.points.length - 1]);\n current.length -= 20;\n insertfirst = true;\n }\n }\n else {\n if (next && next.direction && next.length) {\n next.points[0].x = sourcePoint.x;\n next.points[0].y = next.points[next.points.length - 1].y = (current.direction === 'Bottom') ?\n sourcePoint.y + 20 : sourcePoint.y - 20;\n }\n insertfirst = true;\n removeCurrentPrev = true;\n }\n break;\n }\n this.changeSegmentDirection(prev);\n this.changeSegmentDirection(current);\n if (insertfirst) {\n segValues = { type: 'Orthogonal', direction: current.direction, length: 20 };\n segments.push(new OrthogonalSegment(connector, 'segments', segValues, true));\n if (removeCurrentPrev) {\n if (next && next.direction && next.length) {\n next.length = Point.distancePoints(next.points[0], next.points[next.points.length - 1]);\n }\n if (nextNext && nextNext.direction && nextNext.length) {\n nextNext.length = Point.distancePoints(next.points[next.points.length - 1], nextNext.points[nextNext.points.length - 1]);\n }\n connector.segments.splice(index - 1, 2);\n }\n connector.segments = segments.concat(connector.segments);\n }\n this.selectedSegment = ((removeCurrentPrev) ? connector.segments[index - 1] :\n connector.segments[index + 1]);\n this.commandHandler.updateEndPoint(connector);\n }\n };\n ConnectorEditing.prototype.updateLastSegment = function (connector, selectedSegment) {\n if (connector.targetID && connector.targetPortID === '') {\n var line1Start = void 0;\n var line1End = void 0;\n var line2Start = void 0;\n var line2End = void 0;\n var corners = connector.targetWrapper.corners;\n var firstSegPoint = selectedSegment.points[0];\n var lastSegPoint = selectedSegment.points[selectedSegment.points.length - 1];\n if (selectedSegment.direction === 'Right' || selectedSegment.direction === 'Left') {\n line1Start = { x: firstSegPoint.x, y: firstSegPoint.y };\n line1End = {\n x: (selectedSegment.direction === 'Left') ? lastSegPoint.x - corners.width / 2 : lastSegPoint.x + corners.width / 2,\n y: lastSegPoint.y\n };\n line2Start = { x: corners.center.x, y: corners.center.y - corners.height };\n line2End = { x: corners.center.x, y: corners.center.y + corners.height };\n }\n else {\n line1Start = { x: firstSegPoint.x, y: firstSegPoint.y };\n line1End = {\n x: lastSegPoint.x,\n y: (selectedSegment.direction === 'Bottom') ? lastSegPoint.y + corners.height / 2 : lastSegPoint.y - corners.height / 2\n };\n line2Start = { x: corners.center.x - corners.width, y: corners.center.y };\n line2End = { x: corners.center.x + corners.width, y: corners.center.y };\n }\n var line1 = { X1: line1Start.x, Y1: line1Start.y, X2: line1End.x, Y2: line1End.y };\n var line2 = { X1: line2Start.x, Y1: line2Start.y, X2: line2End.x, Y2: line2End.y };\n return (intersect3(line1, line2).enabled);\n }\n return false;\n };\n /**\n * To destroy the connector editing module\n * @return {void}\n * @private\n */\n ConnectorEditing.prototype.destroy = function () {\n /**\n * Destroys the connector editing module\n */\n };\n /**\n * Get module name.\n */\n ConnectorEditing.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'ConnectorEditingTool';\n };\n return ConnectorEditing;\n}(ToolBase));\nexport { ConnectorEditing };\n","import { Point } from '../primitives/point';\nimport { Container } from '../core/containers/container';\nimport { Connector } from '../objects/connector';\nimport { NodeDrawingTool, ConnectorDrawingTool, TextDrawingTool, PolygonDrawingTool } from './tool';\nimport { Node } from '../objects/node';\nimport { SelectTool, MoveTool, ResizeTool, RotateTool, ConnectTool, ExpandTool, LabelTool, ZoomPanTool } from './tool';\nimport { ConnectorEditing } from './connector-editing';\nimport { Selector } from './selector';\nimport { findToolToActivate, isSelected, getCursor, contains } from './actions';\nimport { DiagramAction, KeyModifiers, Keys, DiagramEvent, DiagramTools } from '../enum/enum';\nimport { isPointOverConnector, findObjectType, insertObject, getObjectFromCollection, getTooltipOffset } from '../utility/diagram-util';\nimport { getObjectType } from '../utility/diagram-util';\nimport { canZoomPan, canDraw, canDrag } from './../utility/constraints-util';\nimport { canMove, canEnablePointerEvents, canSelect, canEnableToolTip } from './../utility/constraints-util';\nimport { canOutConnect, canInConnect, canAllowDrop, canUserInteract, defaultTool } from './../utility/constraints-util';\nimport { updateTooltip } from '../objects/tooltip';\nimport { PortVisibility, NodeConstraints, ConnectorConstraints } from '../enum/enum';\nimport { addTouchPointer, measureHtmlText } from '../utility/dom-util';\nimport { TextElement } from '../core/elements/text-element';\nimport { Size } from '../primitives/size';\nimport { Rect } from '../primitives/rect';\nimport { identityMatrix, rotateMatrix, transformPointByMatrix } from './../primitives/matrix';\nimport { removeRulerMarkers, drawRulerMarkers, getRulerSize, updateRuler } from '../ruler/ruler';\nimport { canContinuousDraw, canDrawOnce } from '../utility/constraints-util';\nimport { getFunction } from '../utility/base-util';\n/**\n * This module handles the mouse and touch events\n */\nvar DiagramEventHandler = /** @class */ (function () {\n /** @private */\n function DiagramEventHandler(diagram, commandHandler) {\n this.currentAction = 'None';\n this.focus = false;\n this.isBlocked = false;\n this.isMouseDown = false;\n this.inAction = false;\n this.doingAutoScroll = false;\n this.diagram = null;\n this.objectFinder = null;\n this.tool = null;\n this.eventArgs = null;\n this.diagram = diagram;\n this.objectFinder = new ObjectFinder();\n this.commandHandler = commandHandler;\n }\n Object.defineProperty(DiagramEventHandler.prototype, \"action\", {\n get: function () {\n return this.currentAction;\n },\n set: function (action) {\n if (action !== this.currentAction) {\n if (this.currentAction === 'PortDraw') {\n this.diagram.tool &= ~DiagramTools.DrawOnce;\n if (this.tool) {\n this.tool.mouseUp({ position: this.currentPosition });\n }\n this.tool = null;\n }\n this.currentAction = action;\n if (this.currentAction !== 'None' && this.currentAction !== 'Select' &&\n !(this.diagram.diagramActions & DiagramAction.TextEdit)) {\n this.diagram.diagramActions = this.diagram.diagramActions | DiagramAction.ToolAction;\n }\n else {\n this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.ToolAction;\n }\n this.diagram.setCursor(this.diagram.getCursor(action, this.inAction));\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DiagramEventHandler.prototype, \"blocked\", {\n get: function () {\n return this.isBlocked;\n },\n set: function (blocked) {\n this.isBlocked = blocked;\n if (this.blocked) {\n this.diagram.setCursor('not-allowed');\n }\n else {\n this.diagram.setCursor(this.diagram.getCursor(this.action, this.inAction));\n }\n },\n enumerable: true,\n configurable: true\n });\n /** @private */\n DiagramEventHandler.prototype.getMousePosition = function (e) {\n var touchArg;\n var offsetX;\n var offsetY;\n if (e.type.indexOf('touch') !== -1) {\n touchArg = e;\n offsetX = touchArg.changedTouches[0].clientX;\n offsetY = touchArg.changedTouches[0].clientY;\n }\n else {\n offsetX = e.clientX;\n offsetY = e.clientY;\n }\n var position = new Size();\n position = getRulerSize(this.diagram);\n var boundingRect = this.diagram.element.getBoundingClientRect();\n offsetX = offsetX + this.diagram.diagramCanvas.scrollLeft - boundingRect.left - position.width;\n offsetY = offsetY + this.diagram.diagramCanvas.scrollTop - boundingRect.top - position.height;\n offsetX /= this.diagram.scroller.transform.scale;\n offsetY /= this.diagram.scroller.transform.scale;\n offsetX -= this.diagram.scroller.transform.tx;\n offsetY -= this.diagram.scroller.transform.ty;\n return { x: offsetX, y: offsetY };\n };\n /**\n * @private\n */\n DiagramEventHandler.prototype.windowResize = function (evt) {\n var _this = this;\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n this.resizeTo = setTimeout(function () {\n _this.updateViewPortSize(_this.diagram.element);\n }, 300);\n return false;\n };\n /**\n * @private\n */\n DiagramEventHandler.prototype.updateViewPortSize = function (element) {\n var container = document.getElementById(element.id);\n if (container) {\n var bounds = container.getBoundingClientRect();\n this.diagram.scroller.setViewPortSize(bounds.width, bounds.height);\n var position = new Size();\n position = getRulerSize(this.diagram);\n var width = this.diagram.getSizeValue(this.diagram.width, position.width);\n var height = this.diagram.getSizeValue(this.diagram.height, position.height);\n this.diagram.diagramCanvas.style.width = width;\n this.diagram.diagramCanvas.style.height = height;\n this.diagram.scroller.setSize();\n if (this.diagram.rulerSettings.showRulers) {\n updateRuler(this.diagram);\n }\n }\n };\n /** @private */\n DiagramEventHandler.prototype.canHideResizers = function () {\n return ((this.tool instanceof MoveTool || this.tool instanceof RotateTool) && this.isMouseDown);\n };\n /** @private */\n DiagramEventHandler.prototype.updateCursor = function () {\n if ((this.diagram.selectedItems.nodes.length === 1 || this.diagram.selectedItems.connectors.length === 1)) {\n var list = [];\n list = list.concat(this.diagram.selectedItems.nodes, this.diagram.selectedItems.connectors);\n this.blocked = (this.isMouseDown && list.length === 1 && this.tool instanceof SelectTool && !canMove(list[0]));\n }\n };\n DiagramEventHandler.prototype.isForeignObject = function (target, isTextBox) {\n var foreignobject = target;\n if (foreignobject) {\n while (foreignobject.parentNode !== null) {\n if (typeof foreignobject.className === 'string' &&\n ((!isTextBox && foreignobject.className.indexOf('foreign-object') !== -1) ||\n (isTextBox && foreignobject.className.indexOf('e-diagram-text-edit') !== -1))) {\n return foreignobject;\n }\n else {\n foreignobject = foreignobject.parentNode;\n }\n }\n }\n return null;\n };\n DiagramEventHandler.prototype.isMetaKey = function (evt) {\n return navigator.platform.match('Mac') ? evt.metaKey : evt.ctrlKey;\n };\n DiagramEventHandler.prototype.isDeleteKey = function (key, value) {\n return (navigator.platform.match('Mac') && key === 'Backspace' && value === 'delete');\n };\n DiagramEventHandler.prototype.mouseDown = function (evt) {\n this.focus = true;\n var touches;\n touches = evt.touches;\n if (!this.checkEditBoxAsTarget(evt) && (canUserInteract(this.diagram)) ||\n (canZoomPan(this.diagram) && !defaultTool(this.diagram))) {\n if (this.action === 'Select' || this.action === 'Drag') {\n this.diagram.updatePortVisibility(this.hoverElement, PortVisibility.Hover, true);\n }\n if (this.tool instanceof PolygonDrawingTool && (evt.button === 2 || evt.buttons === 2)) {\n var arg = {\n element: this.diagram, position: this.currentPosition, count: evt.buttons, actualObject: this.eventArgs.actualObject\n };\n this.inAction = false;\n this.tool.mouseUp(this.eventArgs, arg);\n }\n else if ((this.inAction === true) && this.isMouseDown === true && this.tool instanceof PolygonDrawingTool) {\n this.isMouseDown = true;\n this.eventArgs = {};\n this.getMouseEventArgs(this.currentPosition, this.eventArgs);\n this.eventArgs.position = this.currentPosition;\n this.tool.mouseDown(this.eventArgs);\n }\n else {\n this.isMouseDown = true;\n this.currentPosition = this.prevPosition = this.getMousePosition(evt);\n this.eventArgs = {};\n this.diagram.endEdit();\n var target = void 0;\n var objects = this.objectFinder.findObjectsUnderMouse(this.currentPosition, this.diagram, this.eventArgs, null, this.action);\n var obj = this.objectFinder.findObjectUnderMouse(this.diagram, objects, this.action, this.inAction, this.eventArgs, evt);\n var sourceElement = null;\n if (obj !== null) {\n sourceElement = this.diagram.findElementUnderMouse(obj, this.currentPosition);\n if (sourceElement) {\n target = this.commandHandler.findTarget(sourceElement, obj);\n }\n }\n this.action = this.diagram.findActionToBeDone(obj, sourceElement, this.currentPosition, target);\n //work around - correct it\n var ctrlKey = this.isMetaKey(evt);\n if (ctrlKey && evt.shiftKey && this.diagram.connectorEditingToolModule) {\n this.action = 'SegmentEnd';\n }\n else if ((ctrlKey || evt.shiftKey) && (!canZoomPan(this.diagram))) {\n this.action = 'Select';\n }\n this.tool = this.diagram.getTool(this.action);\n if (!this.tool) {\n this.action = 'Select';\n this.tool = this.diagram.getTool(this.action);\n }\n this.getMouseEventArgs(this.currentPosition, this.eventArgs);\n if (ctrlKey || evt.shiftKey) {\n var info = (ctrlKey && evt.shiftKey) ? { ctrlKey: ctrlKey, shiftKey: evt.shiftKey } : { ctrlKey: true };\n this.eventArgs.info = info;\n }\n this.eventArgs.position = this.currentPosition;\n this.tool.mouseDown(this.eventArgs);\n this.initialEventArgs = { source: this.eventArgs.source, sourceWrapper: this.eventArgs.sourceWrapper };\n this.initialEventArgs.position = this.currentPosition;\n this.initialEventArgs.info = this.eventArgs.info;\n this.inAction = false;\n if (evt.type === 'touchstart') {\n if (touches && touches.length >= 2) {\n this.touchStartList = addTouchPointer(this.touchStartList, evt, touches);\n }\n if (!touches) {\n evt.preventDefault();\n }\n }\n }\n }\n if (!this.isForeignObject(evt.target) && !this.isForeignObject(evt.target, true) && (!touches)) {\n evt.preventDefault();\n }\n };\n DiagramEventHandler.prototype.mouseMoveExtend = function (e, obj) {\n if (this.tool instanceof PolygonDrawingTool) {\n this.tool.mouseMove(this.eventArgs);\n }\n if (this.diagram.scrollSettings.canAutoScroll) {\n this.checkAutoScroll(e);\n }\n else {\n if (!this.blocked) {\n (this.tool.mouseMove(this.eventArgs));\n }\n }\n if (this.eventArgs.target) {\n this.hoverElement = this.eventArgs.target;\n }\n var isNode = this.eventArgs.target instanceof Node && obj instanceof Node ? false : true;\n if (this.tool instanceof ConnectTool) {\n this.diagram.updatePortVisibility(this.hoverElement instanceof Node ? this.hoverElement : this.hoverNode, PortVisibility.Connect | PortVisibility.Hover, isNode);\n }\n if (this.hoverElement instanceof Node\n && this.hoverNode instanceof Node && this.hoverNode && this.hoverNode.id !== this.hoverElement.id) {\n this.diagram.updatePortVisibility(this.hoverNode, PortVisibility.Connect | PortVisibility.Hover, true);\n }\n this.hoverElement = isNode ? null : obj;\n this.hoverNode = isNode ? null : obj;\n };\n /** @private */\n DiagramEventHandler.prototype.mouseMove = function (e, touches) {\n this.focus = true;\n if (canUserInteract(this.diagram) || (canZoomPan(this.diagram) && !defaultTool(this.diagram))) {\n this.currentPosition = this.getMousePosition(e);\n var objects = this.diagram.findObjectsUnderMouse(this.currentPosition);\n var obj = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction);\n drawRulerMarkers(this.diagram, this.currentPosition);\n var force = false;\n var target = void 0;\n if (e.type === 'touchmove') {\n touches = e.touches;\n if (touches && touches.length > 1) {\n this.touchMoveList = addTouchPointer(this.touchMoveList, e, touches);\n if (this.action !== 'PinchZoom') {\n force = true;\n }\n }\n }\n if (Point.equals(this.currentPosition, this.prevPosition) === false || this.inAction) {\n if (this.isMouseDown === false || force) {\n this.eventArgs = {};\n var sourceElement = null;\n if (obj !== null) {\n sourceElement = this.diagram.findElementUnderMouse(obj, this.currentPosition);\n if (obj !== this.hoverElement) {\n if (this.hoverElement) {\n this.elementLeave();\n this.diagram.updatePortVisibility(this.hoverElement, PortVisibility.Hover, true);\n }\n if (obj instanceof Node) {\n this.hoverNode = obj;\n }\n this.hoverElement = obj;\n this.elementEnter(this.currentPosition, false);\n }\n else if (!this.hoverElement && this.hoverElement === obj) {\n this.elementEnter(this.currentPosition, true);\n }\n if (sourceElement) {\n target = this.commandHandler.findTarget(sourceElement, obj);\n }\n }\n this.action = this.diagram.findActionToBeDone(obj, sourceElement, this.currentPosition, target);\n this.getMouseEventArgs(this.currentPosition, this.eventArgs);\n this.tool = this.getTool(this.action);\n this.mouseEvents();\n if (this.tool instanceof ConnectorDrawingTool) {\n this.tool.mouseMove(this.eventArgs);\n }\n else if (this.tool instanceof PolygonDrawingTool) {\n this.tool.mouseMove(this.eventArgs);\n }\n else if (touches && this.tool instanceof ZoomPanTool) {\n this.tool.mouseDown(this.eventArgs);\n }\n this.updateCursor();\n var isNode = false;\n if (!(this.hoverElement && (!(this.tool instanceof ZoomPanTool)) && obj instanceof Node &&\n (this.diagram.selectedItems.nodes.length === 0 || !isSelected(this.diagram, this.hoverElement)))) {\n isNode = true;\n }\n this.diagram.updatePortVisibility(this.hoverElement, PortVisibility.Hover, isNode);\n if (obj === null && this.hoverElement) {\n this.hoverElement = null;\n this.elementLeave();\n }\n force = false;\n }\n else {\n this.eventArgs.position = this.currentPosition;\n if (this.action === 'Drag' && !isSelected(this.diagram, this.eventArgs.source, false) &&\n this.eventArgs.source instanceof Selector) {\n this.getMouseEventArgs(this.currentPosition, this.eventArgs);\n }\n this.mouseEvents();\n if (e.ctrlKey || e.shiftKey) {\n var info = (e.ctrlKey && e.shiftKey) ? { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey } : { ctrlKey: true };\n this.eventArgs.info = info;\n }\n if (canMove(obj) && canSelect(obj) && this.initialEventArgs &&\n this.initialEventArgs.source && this.action === 'Select') {\n if (!isSelected(this.diagram, this.eventArgs.source, false) &&\n this.eventArgs.source instanceof Selector) {\n this.getMouseEventArgs(this.currentPosition, this.eventArgs);\n }\n if (!(obj instanceof Connector) || (obj instanceof Connector &&\n !(contains(this.currentPosition, obj.sourcePoint, obj.hitPadding) ||\n contains(this.currentPosition, obj.targetPoint, obj.hitPadding)))) {\n this.action = 'Drag';\n }\n this.tool = this.getTool(this.action);\n this.tool.mouseDown(this.initialEventArgs);\n }\n this.getMouseEventArgs(this.currentPosition, this.eventArgs, this.eventArgs.source);\n this.updateCursor();\n this.inAction = true;\n this.initialEventArgs = null;\n this.mouseMoveExtend(e, obj);\n }\n this.prevPosition = this.currentPosition;\n if (!this.isForeignObject(e.target, true)) {\n e.preventDefault();\n }\n }\n }\n };\n DiagramEventHandler.prototype.checkAutoScroll = function (e) {\n var autoScrollPosition = this.startAutoScroll(e);\n if (!autoScrollPosition && this.doingAutoScroll) {\n this.doingAutoScroll = false;\n clearInterval(this.timeOutValue);\n }\n else if (autoScrollPosition) {\n if ((this.tool instanceof MoveTool || this.tool instanceof ResizeTool\n || this.tool instanceof SelectTool) && this.inAction) {\n var diagram_1 = this;\n var delay_1 = 100;\n if (this.diagram.scrollSettings.canAutoScroll && autoScrollPosition && !this.doingAutoScroll) {\n this.doingAutoScroll = true;\n this.timeOutValue = setInterval(function (args) {\n diagram_1.doAutoScroll(autoScrollPosition, e, delay_1);\n }, delay_1);\n }\n }\n }\n else {\n this.blocked = !(this.tool.mouseMove(this.eventArgs));\n }\n };\n /** @private */\n DiagramEventHandler.prototype.mouseUp = function (evt) {\n var touches;\n touches = evt.touches;\n if (!this.checkEditBoxAsTarget(evt) && (canUserInteract(this.diagram))\n || (canZoomPan(this.diagram) && !defaultTool(this.diagram))) {\n if (this.tool && (!(this.tool instanceof PolygonDrawingTool) ||\n ((this.tool instanceof PolygonDrawingTool) && evt.detail === 2))) {\n this.diagram.endEdit();\n document.getElementById(this.diagram.element.id + 'content').focus();\n if (!this.inAction && evt.which !== 3) {\n if (this.action === 'Drag') {\n this.action = 'Select';\n var objects = this.diagram.findObjectsUnderMouse(this.currentPosition);\n var obj = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction);\n var isMultipleSelect = true;\n if ((!evt.ctrlKey && this.isMouseDown\n && (this.diagram.selectedItems.nodes.length + this.diagram.selectedItems.connectors.length) > 1)\n && evt.which === 1) {\n isMultipleSelect = false;\n this.commandHandler.clearSelection();\n }\n if (!isSelected(this.diagram, obj) || (!isMultipleSelect)) {\n this.commandHandler.selectObjects([obj]);\n }\n }\n }\n this.inAction = false;\n this.isMouseDown = false;\n this.currentPosition = this.getMousePosition(evt);\n if (this.tool && (this.tool.prevPosition || this.tool instanceof LabelTool)) {\n this.eventArgs.position = this.currentPosition;\n this.getMouseEventArgs(this.currentPosition, this.eventArgs, this.eventArgs.source);\n var ctrlKey = this.isMetaKey(evt);\n if (ctrlKey || evt.shiftKey) {\n var info = (ctrlKey && evt.shiftKey) ? { ctrlKey: ctrlKey, shiftKey: evt.shiftKey } :\n { ctrlKey: true };\n this.eventArgs.info = info;\n }\n this.eventArgs.clickCount = evt.detail;\n this.tool.mouseUp(this.eventArgs);\n }\n this.blocked = false;\n if (this.hoverElement) {\n var portVisibility = PortVisibility.Connect;\n if (isSelected(this.diagram, this.hoverElement)) {\n portVisibility |= PortVisibility.Hover;\n }\n this.diagram.updatePortVisibility(this.hoverElement, portVisibility, true);\n this.hoverElement = null;\n }\n this.touchStartList = null;\n this.touchMoveList = null;\n if (!(this.tool instanceof TextDrawingTool)) {\n this.tool = null;\n }\n }\n if (!touches) {\n evt.preventDefault();\n }\n this.diagram.currentDrawingObject = undefined;\n var selector = this.diagram.selectedItems;\n if (!this.inAction && selector.wrapper && selector.userHandles.length > 0) {\n this.diagram.renderSelector(true);\n }\n if (!this.inAction && !this.diagram.currentSymbol) {\n var arg = {\n element: this.eventArgs.source || this.diagram, position: this.eventArgs.position, count: evt.detail,\n actualObject: this.eventArgs.actualObject\n };\n this.diagram.triggerEvent(DiagramEvent.click, arg);\n }\n this.eventArgs = {};\n }\n //end the corresponding tool\n };\n /** @private */\n DiagramEventHandler.prototype.mouseLeave = function (evt) {\n //Define what has to happen on mouse leave\n if (this.tool && this.inAction) {\n this.tool.mouseLeave(this.eventArgs);\n }\n if (this.eventArgs && this.eventArgs.source) {\n this.diagram.updatePortVisibility(this.eventArgs.source, PortVisibility.Hover, true);\n this.hoverElement = null;\n }\n if (this.tool instanceof ConnectTool && this.eventArgs && this.eventArgs.target && this.eventArgs.target instanceof Node) {\n this.diagram.updatePortVisibility(this.eventArgs.target, PortVisibility.Hover | PortVisibility.Connect, true);\n this.hoverElement = null;\n }\n var selector = this.diagram.selectedItems;\n if (selector && selector.wrapper) {\n this.diagram.renderSelector(true);\n }\n this.isMouseDown = false;\n this.focus = false;\n this.touchStartList = null;\n this.touchMoveList = null;\n this.commandHandler.removeSnap();\n this.inAction = false;\n this.eventArgs = {};\n this.tool = null;\n removeRulerMarkers();\n evt.preventDefault();\n };\n /** @private */\n DiagramEventHandler.prototype.mouseWheel = function (evt) {\n var up = (evt.wheelDelta > 0 || -40 * evt.detail > 0) ? true : false;\n var mousePosition = this.getMousePosition(evt);\n this.diagram.endEdit();\n this.diagram.tooltipObject.close();\n var ctrlKey = this.isMetaKey(evt);\n if (ctrlKey) {\n this.diagram.zoom(up ? (1.2) : 1 / (1.2), mousePosition);\n evt.preventDefault();\n }\n else {\n var horizontalOffset = this.diagram.scroller.horizontalOffset;\n var verticalOffset = this.diagram.scroller.verticalOffset;\n var change = up ? 20 : -20;\n if (this.tool && this.tool instanceof PolygonDrawingTool) {\n this.eventArgs = {};\n this.getMouseEventArgs(mousePosition, this.eventArgs);\n this.eventArgs.position = mousePosition;\n this.tool.mouseWheel(this.eventArgs);\n }\n if (evt.shiftKey) {\n this.diagram.scroller.zoom(1, change, 0, mousePosition);\n }\n else {\n this.diagram.scroller.zoom(1, 0, change, mousePosition);\n }\n if (horizontalOffset !== this.diagram.scroller.horizontalOffset\n || verticalOffset !== this.diagram.scroller.verticalOffset) {\n evt.preventDefault();\n }\n }\n };\n /** @private */\n DiagramEventHandler.prototype.keyDown = function (evt) {\n if (!(this.diagram.diagramActions & DiagramAction.TextEdit) &&\n !(this.checkEditBoxAsTarget(evt)) || (evt.key === 'Escape' || evt.keyCode === 27)) {\n var i = void 0;\n var command = void 0;\n var keycode = evt.keyCode ? evt.keyCode : evt.which;\n var key = evt.key;\n var ctrlKey = this.isMetaKey(evt);\n if (this.diagram.commandManager && this.diagram.commands) {\n var commands = this.diagram.commands;\n for (var _i = 0, _a = Object.keys(commands); _i < _a.length; _i++) {\n var i_1 = _a[_i];\n command = this.diagram.commands[i_1];\n if (command && (command.gesture.keyModifiers || command.gesture.key)) {\n if ((keycode === command.gesture.key || (key === Keys[command.gesture.key])\n || this.isDeleteKey(key, i_1))\n && (((!command.gesture.keyModifiers) && (!evt.altKey) && (!evt.shiftKey) && (!ctrlKey)) ||\n (command.gesture.keyModifiers && (ctrlKey || evt.altKey || evt.shiftKey) &&\n (this.altKeyPressed(command.gesture.keyModifiers) && evt.altKey) ||\n (this.shiftKeyPressed(command.gesture.keyModifiers) && evt.shiftKey) ||\n (this.ctrlKeyPressed(command.gesture.keyModifiers) && ctrlKey)))) {\n var canExecute = getFunction(command.canExecute);\n if (canExecute && canExecute({\n 'keyDownEventArgs': KeyboardEvent,\n parameter: command.parameter\n })) {\n evt.preventDefault();\n if (evt.key === 'Escape' && (this.checkEditBoxAsTarget(evt))) {\n document.getElementById(this.diagram.diagramCanvas.id).focus();\n }\n if (command.execute) {\n // if (i === 'nudgeUp' || i === \"nudgeRight\" || i === \"nudgeDown\" || i === 'nudgeLeft') {\n // command.execute()\n // } else {\n var execute = getFunction(command.execute);\n execute({ 'keyDownEventArgs': KeyboardEvent, parameter: command.parameter });\n // }\n }\n break;\n }\n }\n }\n }\n }\n }\n };\n DiagramEventHandler.prototype.startAutoScroll = function (e) {\n var position = this.getMousePosition(e);\n position.x *= this.diagram.scroller.currentZoom;\n position.y *= this.diagram.scroller.currentZoom;\n var movingPosition;\n var autoScrollBorder = this.diagram.scrollSettings.autoScrollBorder;\n if (this.diagram.scrollSettings.canAutoScroll) {\n if (position.x + this.diagram.scroller.horizontalOffset + autoScrollBorder.right > this.diagram.scroller.viewPortWidth - 18) {\n movingPosition = 'right';\n }\n else if (position.x + this.diagram.scroller.horizontalOffset < autoScrollBorder.left) {\n movingPosition = 'left';\n }\n else if (position.y + this.diagram.scroller.verticalOffset + autoScrollBorder.bottom >\n this.diagram.scroller.viewPortHeight - 18) {\n movingPosition = 'bottom';\n }\n else if (position.y + this.diagram.scroller.verticalOffset < autoScrollBorder.top) {\n movingPosition = 'top';\n }\n }\n return movingPosition;\n };\n DiagramEventHandler.prototype.doAutoScroll = function (option, e, delay, autoScroll) {\n var position = option;\n if ((this.tool instanceof MoveTool || this.tool instanceof ResizeTool\n || this.tool instanceof SelectTool) && this.inAction) {\n var diagram = this;\n this.eventArgs.position = { x: this.tool.prevPosition.x, y: this.tool.prevPosition.y };\n var pos = this.getMousePosition(e);\n var autoScrollBorder = this.diagram.scrollSettings.autoScrollBorder;\n var newDelay = delay ? delay : 100;\n var left = 0;\n var top_1 = 0;\n switch (position) {\n case 'right':\n this.eventArgs.position.x += 10;\n left = 10;\n break;\n case 'left':\n this.eventArgs.position.x -= 10;\n left = -10;\n break;\n case 'bottom':\n this.eventArgs.position.y += 10;\n top_1 = 10;\n break;\n case 'top':\n this.eventArgs.position.y -= 10;\n top_1 = -10;\n break;\n }\n this.tool.mouseMove(this.eventArgs);\n this.diagram.scroller.zoom(1, -left, -top_1, pos);\n }\n };\n DiagramEventHandler.prototype.mouseEvents = function () {\n var target = this.diagram.findObjectsUnderMouse(this.currentPosition);\n for (var i = 0; i < target.length; i++) {\n if (this.eventArgs.actualObject === target[i]) {\n target.splice(i, 1);\n }\n }\n var arg = {\n targets: target,\n element: (this.eventArgs.source === this.eventArgs.actualObject) ? undefined : this.eventArgs.source,\n actualObject: this.eventArgs.actualObject\n };\n if (this.lastObjectUnderMouse && (!this.eventArgs.actualObject || (this.lastObjectUnderMouse !== this.eventArgs.actualObject))) {\n arg.element = this.lastObjectUnderMouse;\n arg.targets = arg.actualObject = undefined;\n this.diagram.triggerEvent(DiagramEvent.mouseLeave, arg);\n this.lastObjectUnderMouse = null;\n }\n if (!this.lastObjectUnderMouse && this.eventArgs.source || (this.lastObjectUnderMouse !== this.eventArgs.actualObject)) {\n this.lastObjectUnderMouse = this.eventArgs.actualObject;\n this.diagram.triggerEvent(DiagramEvent.mouseEnter, arg);\n }\n if (this.eventArgs.actualObject) {\n this.diagram.triggerEvent(DiagramEvent.mouseOver, arg);\n }\n };\n DiagramEventHandler.prototype.elementEnter = function (mousePosition, elementOver) {\n if (!elementOver) {\n var isPrivateTooltip = ((this.hoverElement instanceof Node) &&\n this.hoverElement.constraints & NodeConstraints.Tooltip) ||\n ((this.hoverElement instanceof Connector) && this.hoverElement.constraints & ConnectorConstraints.Tooltip);\n updateTooltip(this.diagram, isPrivateTooltip ? this.hoverElement : undefined);\n var offset = getTooltipOffset(this.diagram, mousePosition, this.hoverElement);\n this.diagram.tooltipObject.close();\n this.diagram.tooltipObject.offsetX = offset.x;\n this.diagram.tooltipObject.offsetY = offset.y;\n this.diagram.tooltipObject.dataBind();\n if (canEnableToolTip(this.hoverElement, this.diagram)) {\n this.diagram.tooltipObject.open(this.diagram.element);\n }\n }\n };\n DiagramEventHandler.prototype.elementLeave = function () {\n this.diagram.tooltipObject.close();\n };\n DiagramEventHandler.prototype.altKeyPressed = function (keyModifier) {\n if (keyModifier & KeyModifiers.Alt) {\n return true;\n }\n return false;\n };\n DiagramEventHandler.prototype.ctrlKeyPressed = function (keyModifier) {\n if (keyModifier & KeyModifiers.Control) {\n return true;\n }\n return false;\n };\n DiagramEventHandler.prototype.shiftKeyPressed = function (keyModifier) {\n if (keyModifier & KeyModifiers.Shift) {\n return true;\n }\n return false;\n };\n /** @private */\n DiagramEventHandler.prototype.scrolled = function (evt) {\n this.diagram.updateScrollOffset();\n };\n /** @private */\n DiagramEventHandler.prototype.doubleClick = function (evt) {\n if (canUserInteract(this.diagram)) {\n var annotation = void 0;\n var objects = this.diagram.findObjectsUnderMouse(this.currentPosition);\n var obj = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction);\n if (obj !== null && canUserInteract(this.diagram)) {\n var node = obj;\n annotation = this.diagram.findElementUnderMouse(obj, this.currentPosition);\n if (this.tool && this.tool instanceof PolygonDrawingTool) {\n var arg_1 = {\n source: obj || this.diagram, position: this.currentPosition, count: evt.detail\n };\n this.tool.mouseUp(this.eventArgs, arg_1);\n this.isMouseDown = false;\n this.eventArgs = {};\n this.tool = null;\n evt.preventDefault();\n }\n else {\n var layer = this.diagram.commandHandler.getObjectLayer(obj.id);\n if (layer && !layer.lock && layer.visible) {\n if (!(this.diagram.diagramActions & DiagramAction.TextEdit)) {\n var id = '';\n if (obj.shape.shape === 'TextAnnotation') {\n id = obj.id.split('_textannotation_')[1];\n }\n this.diagram.startTextEdit(obj, id || (annotation instanceof TextElement ?\n (annotation.id).split(obj.id + '_')[1] : undefined));\n }\n }\n }\n }\n var arg = {\n source: obj || this.diagram, position: this.currentPosition, count: evt.detail\n };\n this.diagram.triggerEvent(DiagramEvent.doubleClick, arg);\n }\n };\n /**\n * @private\n */\n DiagramEventHandler.prototype.inputChange = function (evt) {\n var minWidth = 90;\n var maxWidth;\n var minHeight = 12;\n var fontsize;\n var textWrapper;\n var node;\n var height;\n var width;\n var textBounds;\n var textBoxWidth;\n var transforms;\n var editTextBox = document.getElementById(this.diagram.element.id + '_editBox');\n var editTextBoxDiv = document.getElementById(this.diagram.element.id + '_editTextBoxDiv');\n var text = (editTextBox.value);\n var line = text.split('\\n');\n node = (this.diagram.selectedItems.nodes[0]) ? this.diagram.selectedItems.nodes[0] : this.diagram.selectedItems.connectors[0];\n if (!node && this.tool instanceof TextDrawingTool) {\n node = this.diagram.nameTable[this.diagram.activeLabel.parentId];\n }\n if (node && ((node.shape.type !== 'Text' && node.annotations.length > 0) || (node.shape.type === 'Text'))) {\n textWrapper = this.diagram.getWrapper(node.wrapper, this.diagram.activeLabel.id);\n maxWidth = node.wrapper.bounds.width > textWrapper.bounds.width ? node.wrapper.bounds.width : textWrapper.bounds.width;\n maxWidth = maxWidth > minWidth ? maxWidth : minWidth;\n textBounds = measureHtmlText(textWrapper.style, text, undefined, undefined, maxWidth);\n fontsize = Number((editTextBox.style.fontSize).split('px')[0]);\n if (line.length > 1 && line[line.length - 1] === '') {\n textBounds.height = textBounds.height + fontsize;\n }\n width = textBounds.width;\n width = (minWidth > width) ? minWidth : width;\n height = (minHeight > textBounds.height) ? minHeight : textBounds.height;\n transforms = this.diagram.scroller.transform;\n editTextBoxDiv.style.left = ((((textWrapper.bounds.center.x + transforms.tx) * transforms.scale) - width / 2) - 2.5) + 'px';\n editTextBoxDiv.style.top = ((((textWrapper.bounds.center.y + transforms.ty) * transforms.scale) - height / 2) - 3) + 'px';\n editTextBoxDiv.style.width = width + 'px';\n editTextBoxDiv.style.height = height + 'px';\n editTextBox.style.minHeight = minHeight + 'px';\n editTextBox.style.minWidth = minWidth + 'px';\n editTextBox.style.width = width + 'px';\n editTextBox.style.height = height + 'px';\n }\n };\n /**\n * @private\n */\n DiagramEventHandler.prototype.isAddTextNode = function (node, focusOut) {\n if (this.tool instanceof TextDrawingTool || focusOut) {\n this.tool = null;\n if (node && (!(canContinuousDraw(this.diagram)))) {\n this.diagram.drawingObject = undefined;\n this.diagram.currentDrawingObject = undefined;\n }\n if (getObjectFromCollection(this.diagram.nodes, node.id) || getObjectFromCollection(this.diagram.connectors, node.id)) {\n return false;\n }\n return true;\n }\n return false;\n };\n DiagramEventHandler.prototype.checkEditBoxAsTarget = function (evt) {\n if ((evt.target && evt.target.id === this.diagram.element.id + '_editBox')) {\n return true;\n }\n return false;\n };\n DiagramEventHandler.prototype.getMouseEventArgs = function (position, args, source) {\n args.position = position;\n var obj;\n var objects;\n if (!source) {\n if (this.action === 'Drag' || this.action === 'ConnectorSourceEnd' || this.action === 'SegmentEnd' ||\n this.action === 'OrthoThumb' || this.action === 'BezierSourceThumb' || this.action === 'BezierTargetThumb' ||\n this.action === 'ConnectorTargetEnd' || this.action === 'Rotate' || this.action.indexOf('Resize') !== -1) {\n obj = this.diagram.selectedItems;\n }\n else {\n objects = this.diagram.findObjectsUnderMouse(this.currentPosition);\n obj = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction);\n }\n }\n else {\n objects = this.diagram.findObjectsUnderMouse(this.currentPosition, source);\n obj = this.diagram.findTargetObjectUnderMouse(objects, this.action, this.inAction, args.position, source);\n }\n var wrapper;\n if (obj) {\n wrapper = this.diagram.findElementUnderMouse(obj, this.currentPosition);\n }\n if (!source) {\n args.source = obj;\n args.sourceWrapper = wrapper;\n }\n else {\n args.target = obj;\n args.targetWrapper = wrapper;\n }\n args.actualObject = this.eventArgs.actualObject;\n args.startTouches = this.touchStartList;\n args.moveTouches = this.touchMoveList;\n return args;\n };\n /** @private */\n DiagramEventHandler.prototype.resetTool = function () {\n this.action = 'Select';\n this.hoverElement = null;\n this.hoverNode = null;\n this.tool = this.diagram.getTool(this.action);\n this.updateCursor();\n };\n /** @private */\n DiagramEventHandler.prototype.getTool = function (action) {\n switch (action) {\n case 'Select':\n return new SelectTool(this.commandHandler, true);\n case 'Drag':\n return new MoveTool(this.commandHandler);\n case 'Rotate':\n return new RotateTool(this.commandHandler);\n case 'LayoutAnimation':\n return new ExpandTool(this.commandHandler);\n case 'Hyperlink':\n return new LabelTool(this.commandHandler);\n case 'ResizeSouthEast':\n case 'ResizeSouthWest':\n case 'ResizeNorthEast':\n case 'ResizeNorthWest':\n case 'ResizeSouth':\n case 'ResizeNorth':\n case 'ResizeWest':\n case 'ResizeEast':\n return new ResizeTool(this.commandHandler, action);\n case 'ConnectorSourceEnd':\n case 'ConnectorTargetEnd':\n case 'BezierSourceThumb':\n case 'BezierTargetThumb':\n return new ConnectTool(this.commandHandler, action);\n case 'SegmentEnd':\n case 'OrthoThumb':\n return new ConnectorEditing(this.commandHandler, action);\n case 'Draw':\n var shape = 'shape';\n var type = findObjectType(this.diagram.drawingObject);\n if (type === 'Node' && this.diagram.drawingObject.shape.type === 'Text') {\n return new TextDrawingTool(this.commandHandler);\n }\n else if (type === 'Node' && this.diagram.drawingObject.shape[shape] === 'Polygon' &&\n !(this.diagram.drawingObject.shape.points)) {\n return new PolygonDrawingTool(this.commandHandler);\n }\n else if (type === 'Node' ||\n (type === 'Node' && this.diagram.drawingObject.shape[shape] === 'Polygon' &&\n (this.diagram.drawingObject.shape.points))) {\n return new NodeDrawingTool(this.commandHandler, this.diagram.drawingObject);\n }\n else if (type === 'Connector') {\n return new ConnectorDrawingTool(this.commandHandler, 'ConnectorSourceEnd', this.diagram.drawingObject);\n }\n break;\n case 'Pan':\n return new ZoomPanTool(this.commandHandler, false);\n case 'PinchZoom':\n return new ZoomPanTool(this.commandHandler, true);\n case 'PortDrag':\n return new MoveTool(this.commandHandler, 'Port');\n case 'PortDraw':\n return new ConnectorDrawingTool(this.commandHandler, 'ConnectorSourceEnd', this.diagram.drawingObject);\n }\n return null;\n };\n /** @private */\n DiagramEventHandler.prototype.getCursor = function (action) {\n return getCursor(action, this.diagram.selectedItems.rotateAngle);\n };\n //start region - interface betweend diagram and interaction\n /** @private */\n DiagramEventHandler.prototype.findElementUnderMouse = function (obj, position) {\n return this.objectFinder.findElementUnderSelectedItem(obj, position);\n };\n /** @private */\n DiagramEventHandler.prototype.findObjectsUnderMouse = function (position, source) {\n return this.objectFinder.findObjectsUnderMouse(position, this.diagram, this.eventArgs, source);\n };\n /** @private */\n DiagramEventHandler.prototype.findObjectUnderMouse = function (objects, action, inAction) {\n return this.objectFinder.findObjectUnderMouse(this.diagram, objects, action, inAction, this.eventArgs, this.currentPosition);\n };\n /** @private */\n DiagramEventHandler.prototype.findTargetUnderMouse = function (objects, action, inAction, position, source) {\n return this.objectFinder.findObjectUnderMouse(this.diagram, objects, action, inAction, this.eventArgs, position, source);\n };\n /** @private */\n DiagramEventHandler.prototype.findActionToBeDone = function (obj, wrapper, position, target) {\n return findToolToActivate(obj, wrapper, this.currentPosition, this.diagram, this.touchStartList, this.touchMoveList, target);\n };\n return DiagramEventHandler;\n}());\nexport { DiagramEventHandler };\n/** @private */\nvar ObjectFinder = /** @class */ (function () {\n function ObjectFinder() {\n }\n /** @private */\n ObjectFinder.prototype.findObjectsUnderMouse = function (pt, diagram, eventArgs, source, actions) {\n // finds the collection of the object that is under the mouse;\n var actualTarget = [];\n if (source && source instanceof Selector) {\n if (source.nodes.length + source.connectors.length === 1) {\n source = (source.nodes[0] || source.connectors[0]);\n if (source.children && source.children.length === 0) {\n eventArgs.actualObject = source;\n }\n }\n }\n var container;\n var bounds;\n var child;\n var matrix;\n var objArray = diagram.spatialSearch.findObjects(new Rect(pt.x - 50, pt.y - 50, 100, 100));\n var layerObjTable = {};\n var layerTarger;\n for (var _i = 0, objArray_1 = objArray; _i < objArray_1.length; _i++) {\n var obj = objArray_1[_i];\n var point = pt;\n bounds = obj.wrapper.outerBounds;\n if ((obj !== source || diagram.currentDrawingObject instanceof Connector) &&\n (obj instanceof Connector) ? obj !== diagram.currentDrawingObject : true && obj.wrapper.visible) {\n var layer = diagram.commandHandler.getObjectLayer(obj.id);\n if (layer && !layer.lock && layer.visible) {\n layerTarger = layerObjTable[layer.zIndex] = layerObjTable[layer.zIndex] || [];\n if (obj.rotateAngle) {\n container = obj.wrapper;\n matrix = identityMatrix();\n rotateMatrix(matrix, -(container.rotateAngle + container.parentTransform), obj.offsetX, obj.offsetY);\n point = transformPointByMatrix(matrix, pt);\n bounds = container.corners;\n for (var _a = 0, _b = container.children; _a < _b.length; _a++) {\n child = _b[_a];\n bounds.uniteRect(child.corners);\n }\n }\n if (!source || (isSelected(diagram, obj) === false)) {\n if (canEnablePointerEvents(obj, diagram)) {\n if ((obj instanceof Connector) ? isPointOverConnector(obj, pt) : bounds.containsPoint(point)) {\n var padding = (obj instanceof Connector) ? obj.hitPadding || 0 : 0;\n var element = void 0;\n element = this.findElementUnderMouse(obj, pt, padding);\n if (element) {\n if (obj instanceof Connector && diagram.bpmnModule) {\n obj = diagram.bpmnModule.findInteractableObject(obj, diagram);\n }\n insertObject(obj, 'zIndex', layerTarger);\n }\n }\n }\n }\n }\n }\n }\n for (var _c = 0, _d = diagram.layers; _c < _d.length; _c++) {\n var layer = _d[_c];\n actualTarget = actualTarget.concat(layerObjTable[layer.zIndex] || []);\n for (var _e = 0, actualTarget_1 = actualTarget; _e < actualTarget_1.length; _e++) {\n var obj = actualTarget_1[_e];\n var eventHandler = 'eventHandler';\n if (obj.shape.type === 'Bpmn' && obj.processId && (!(diagram[eventHandler].tool instanceof MoveTool) ||\n (diagram[eventHandler].tool instanceof MoveTool) && canAllowDrop(obj))) {\n var index = actualTarget.indexOf(diagram.nameTable[obj.processId]);\n if (index > -1) {\n actualTarget.splice(index, 1);\n }\n }\n }\n }\n for (var i = 0; i < actualTarget.length; i++) {\n var parentObj = diagram.nameTable[actualTarget[i].parentId];\n if (parentObj) {\n var portElement = this.findElementUnderMouse(parentObj, pt);\n for (var j = 0; j < parentObj.ports.length; j++) {\n if (portElement.id.match('_' + parentObj.ports[j].id + '$')) {\n var port = parentObj.ports[j];\n if (canDrag(port, diagram) || canDraw(port, diagram)) {\n return actualTarget;\n }\n }\n }\n }\n while (parentObj) {\n var index = actualTarget.indexOf(parentObj);\n if (index !== -1) {\n actualTarget.splice(index, 1);\n }\n else {\n break;\n }\n parentObj = diagram.nameTable[parentObj.parentId];\n }\n }\n return actualTarget;\n };\n /** @private */\n ObjectFinder.prototype.isTarget = function (actualTarget, diagram, action) {\n var connector = diagram.selectedItems.connectors[0];\n var node;\n node = action === 'ConnectorSourceEnd' ? diagram.nameTable[connector.targetID] :\n node = diagram.nameTable[connector.sourceID];\n if (node && (!node.processId && !actualTarget.processId || node.processId !== actualTarget.processId)) {\n if (node.processId !== actualTarget.processId) {\n actualTarget = null;\n }\n }\n return actualTarget;\n };\n /* tslint:disable */\n /** @private */\n ObjectFinder.prototype.findObjectUnderMouse = function (diagram, objects, action, inAction, eventArg, position, source) {\n //we will get the wrapper object here\n //we have to choose the object to be interacted with from the given wrapper\n //Find the object that is under mouse\n var eventHandler = 'eventHandler';\n var actualTarget = null;\n if (objects.length !== 0) {\n if (source && source instanceof Selector) {\n if (source.nodes.length + source.connectors.length === 1) {\n source = (source.nodes[0] || source.connectors[0]);\n }\n }\n if ((action === 'ConnectorSourceEnd' && source || action === 'PortDraw') ||\n ((canDrawOnce(diagram) || canContinuousDraw(diagram)) && getObjectType(diagram.drawingObject) === Connector)) {\n var connector = diagram.selectedItems.connectors[0];\n for (var i = objects.length - 1; i >= 0; i--) {\n if (objects[i] instanceof Node && canOutConnect(objects[i])) {\n actualTarget = objects[i];\n if (connector) {\n actualTarget = this.isTarget(actualTarget, diagram, action);\n }\n eventArg.actualObject = actualTarget;\n return actualTarget;\n }\n }\n }\n else if (action === 'ConnectorTargetEnd' && source) {\n for (var i = objects.length - 1; i >= 0; i--) {\n if (objects[i] instanceof Node && canInConnect(objects[i])) {\n actualTarget = objects[i];\n actualTarget = this.isTarget(actualTarget, diagram, action);\n eventArg.actualObject = actualTarget;\n return actualTarget;\n }\n }\n }\n else if (source && (action === 'Drag' || (diagram[eventHandler].tool instanceof MoveTool))) {\n var index = 0;\n for (var i = 0; i < objects.length; i++) {\n var temp = objects[i];\n if (source !== temp && (temp instanceof Connector ||\n !position || temp.wrapper.bounds.containsPoint(position))) {\n if (canAllowDrop(temp)) {\n if (!actualTarget) {\n actualTarget = temp;\n index = actualTarget.zIndex;\n }\n else {\n actualTarget = index >= temp.zIndex ? actualTarget : temp;\n index = Math.max(index, temp.zIndex);\n }\n }\n }\n }\n if (actualTarget && actualTarget.shape.type === 'Bpmn') {\n if (diagram.selectedItems.nodes.length > 0 && diagram.selectedItems.nodes[0].shape.type === 'Bpmn') {\n actualTarget = actualTarget;\n }\n else {\n actualTarget = null;\n }\n }\n if (actualTarget) {\n eventArg.actualObject = actualTarget;\n }\n return actualTarget;\n }\n else if (action === 'Select' && diagram[eventHandler].tool) {\n for (var i = objects.length - 1; i >= 0; i--) {\n if (objects[i] instanceof Connector) {\n if (objects[i - 1] instanceof Node && objects[i - 1].ports) {\n var portElement = this.findTargetElement(objects[i - 1].wrapper, position, undefined);\n if ((portElement && (portElement.id.match('_icon_content_shape$') || portElement.id.match('_icon_content_rect$')))) {\n return objects[i - 1];\n }\n for (var j = 0; j < objects[i - 1].ports.length; j++) {\n if (portElement && portElement.id.match('_' + objects[i - 1].ports[j].id + '$')) {\n if (canDraw(objects[i - 1].ports[j], diagram)) {\n return objects[i - 1];\n }\n }\n }\n }\n }\n }\n actualTarget = objects[objects.length - 1];\n eventArg.actualObject = actualTarget;\n if (actualTarget.parentId) {\n var obj = actualTarget;\n var selected = isSelected(diagram, obj);\n while (obj) {\n if (isSelected(diagram, obj) && !selected) {\n break;\n }\n actualTarget = obj;\n obj = diagram.nameTable[obj.parentId];\n }\n }\n }\n else if (action === 'Pan' || action === 'LayoutAnimation') {\n for (var i = objects.length - 1; i >= 0; i--) {\n if (objects[i] instanceof Node) {\n var portElement = this.findTargetElement(objects[i].wrapper, position, undefined);\n if ((action === 'LayoutAnimation' || action === 'Pan') || ((portElement && (portElement.id.match('_icon_content_shape$') || portElement.id.match('_icon_content_rect$'))))) {\n return objects[i];\n }\n }\n }\n }\n else {\n actualTarget = objects[objects.length - 1];\n if (eventArg && actualTarget) {\n eventArg.actualObject = actualTarget;\n }\n }\n }\n return actualTarget;\n };\n /* tslint:enable */\n /** @private */\n ObjectFinder.prototype.findElementUnderSelectedItem = function (obj, position) {\n //rewrite this for multiple selection\n if (obj instanceof Selector) {\n if (obj.nodes.length === 1 && (!obj.connectors || !obj.connectors.length)) {\n return this.findElementUnderMouse(obj.nodes[0], position);\n }\n else if ((!obj.nodes || obj.nodes.length) && obj.connectors.length === 1) {\n return this.findElementUnderMouse(obj.connectors[0], position);\n }\n }\n else {\n return this.findElementUnderMouse(obj, position);\n }\n return null;\n };\n ObjectFinder.prototype.findElementUnderMouse = function (obj, position, padding) {\n return this.findTargetElement(obj.wrapper, position, padding);\n };\n /** @private */\n ObjectFinder.prototype.findTargetElement = function (container, position, padding) {\n for (var i = container.children.length - 1; i >= 0; i--) {\n var element = container.children[i];\n if (element && element.outerBounds.containsPoint(position)) {\n if (element instanceof Container) {\n var target = this.findTargetElement(element, position);\n if (target) {\n return target;\n }\n }\n if (element.bounds.containsPoint(position)) {\n return element;\n }\n }\n }\n if (container.bounds.containsPoint(position, padding) && container.style.fill !== 'none') {\n return container;\n }\n return null;\n };\n return ObjectFinder;\n}());\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty } from '@syncfusion/ej2-base';\n/**\n * Defines the BackgroundImage of diagram\n */\nvar Layer = /** @class */ (function (_super) {\n __extends(Layer, _super);\n // tslint:disable-next-line:no-any\n function Layer(parent, propName, defaultValue, isArray) {\n var _this = _super.call(this, parent, propName, defaultValue, isArray) || this;\n /** @private */\n _this.objectZIndex = -1;\n /** @private */\n _this.zIndexTable = {};\n _this.objects = [];\n return _this;\n }\n __decorate([\n Property('')\n ], Layer.prototype, \"id\", void 0);\n __decorate([\n Property(true)\n ], Layer.prototype, \"visible\", void 0);\n __decorate([\n Property(false)\n ], Layer.prototype, \"lock\", void 0);\n __decorate([\n Property()\n ], Layer.prototype, \"objects\", void 0);\n __decorate([\n Property()\n ], Layer.prototype, \"addInfo\", void 0);\n __decorate([\n Property(-1)\n ], Layer.prototype, \"zIndex\", void 0);\n return Layer;\n}(ChildProperty));\nexport { Layer };\n","import { Connector, getBezierPoints, isEmptyVector } from '../objects/connector';\nimport { Node, BpmnSubEvent } from '../objects/node';\nimport { PathElement } from '../core/elements/path-element';\nimport { TextElement } from '../core/elements/text-element';\nimport { OrthogonalSegment } from '../objects/connector';\nimport { Rect } from '../primitives/rect';\nimport { identityMatrix, rotateMatrix, transformPointByMatrix, scaleMatrix } from './../primitives/matrix';\nimport { cloneObject as clone, cloneObject, getBounds, rotatePoint } from './../utility/base-util';\nimport { completeRegion, getTooltipOffset, sort, findPortIndex } from './../utility/diagram-util';\nimport { randomId } from './../utility/base-util';\nimport { Selector } from './selector';\nimport { hasSelection, isSelected, hasSingleConnection } from './actions';\nimport { DiagramEvent } from '../enum/enum';\nimport { canSelect, canMove, canRotate, canDragSourceEnd, canDragTargetEnd, canSingleSelect, canDrag } from './../utility/constraints-util';\nimport { canMultiSelect, canContinuousDraw } from './../utility/constraints-util';\nimport { canPanX, canPanY, canPageEditable } from './../utility/constraints-util';\nimport { SnapConstraints, DiagramTools, DiagramAction } from '../enum/enum';\nimport { getDiagramElement, getAdornerLayerSvg, getHTMLLayer, getAdornerLayer } from '../utility/dom-util';\nimport { Point } from '../primitives/point';\nimport { Size } from '../primitives/size';\nimport { getObjectType } from './../utility/diagram-util';\nimport { Layer } from '../diagram/layer';\nimport { SelectorConstraints } from '../enum/enum';\nimport { remove } from '@syncfusion/ej2-base';\nimport { getOppositeDirection, getPortDirection } from './../utility/connector';\n/**\n * Defines the behavior of commands\n */\nvar CommandHandler = /** @class */ (function () {\n function CommandHandler(diagram) {\n this.clipboardData = {};\n this.connectorsTable = [];\n this.processTable = {};\n this.childTable = {};\n this.parentTable = {};\n this.diagram = diagram;\n }\n Object.defineProperty(CommandHandler.prototype, \"snappingModule\", {\n get: function () {\n return this.diagram.snappingModule;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CommandHandler.prototype, \"layoutAnimateModule\", {\n get: function () {\n return this.diagram.layoutAnimateModule;\n },\n enumerable: true,\n configurable: true\n });\n /** @private */\n CommandHandler.prototype.startTransaction = function (protectChange) {\n this.state = { element: this.diagram.selectedItems, backup: null };\n if (protectChange) {\n this.diagram.protectPropertyChange(true);\n }\n getAdornerLayer(this.diagram.element.id).style.pointerEvents = 'none';\n };\n /** @private */\n CommandHandler.prototype.endTransaction = function (protectChange) {\n this.state = null;\n if (protectChange) {\n this.diagram.protectPropertyChange(false);\n }\n getAdornerLayer(this.diagram.element.id).style.pointerEvents = 'all';\n };\n /**\n * @private\n */\n CommandHandler.prototype.showTooltip = function (node, position, content, toolName, isTooltipVisible) {\n var _this = this;\n if (isTooltipVisible) {\n this.diagram.tooltipObject.position = 'BottomCenter';\n this.diagram.tooltipObject.animation = { open: { delay: 0, duration: 0 } };\n this.diagram.tooltip.relativeMode = toolName === 'ConnectTool' ? 'Mouse' : 'Object';\n this.diagram.tooltipObject.openDelay = 0;\n this.diagram.tooltipObject.closeDelay = 0;\n }\n this.diagram.tooltipObject.content = content;\n var tooltipOffset = getTooltipOffset(this.diagram, { x: position.x, y: position.y }, node);\n this.diagram.tooltipObject.offsetX = tooltipOffset.x + (toolName === 'ConnectTool' ? 10 : 0);\n this.diagram.tooltipObject.offsetY = tooltipOffset.y + 10;\n this.diagram.tooltipObject.dataBind();\n if (isTooltipVisible) {\n setTimeout(function () {\n _this.diagram.tooltipObject.open(_this.diagram.element);\n }, 1);\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.closeTooltip = function () {\n this.diagram.tooltipObject.close();\n };\n /**\n * @private\n */\n CommandHandler.prototype.canEnableDefaultTooltip = function () {\n if (this.diagram.selectedItems.constraints & SelectorConstraints.ToolTip) {\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.updateSelector = function () {\n this.diagram.updateSelector();\n };\n /**\n * @private\n */\n CommandHandler.prototype.triggerEvent = function (event, args) {\n if (event === DiagramEvent.drop || event === DiagramEvent.positionChange ||\n event === DiagramEvent.connectionChange) {\n if (this.diagram.currentSymbol) {\n return;\n }\n if (event === DiagramEvent.drop) {\n args.source = this.diagram;\n }\n if (this.diagram.currentDrawingObject) {\n return;\n }\n }\n this.diagram.triggerEvent(event, args);\n };\n /**\n * @private\n */\n CommandHandler.prototype.dragOverElement = function (args, currentPosition) {\n if (this.diagram.currentSymbol) {\n var dragOverArg = {\n element: args.source, target: args.target, mousePosition: currentPosition, diagram: this.diagram\n };\n this.triggerEvent(DiagramEvent.dragOver, dragOverArg);\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.disConnect = function (obj, endPoint) {\n var oldChanges = {};\n var newChanges = {};\n var selectorModel;\n var connector;\n if (obj instanceof Selector) {\n selectorModel = obj;\n connector = selectorModel.connectors[0];\n }\n else if (obj instanceof Connector && this.diagram.currentDrawingObject) {\n connector = this.diagram.currentDrawingObject;\n }\n if (obj && connector && (hasSingleConnection(this.diagram) || this.diagram.currentDrawingObject)) {\n if (endPoint && (endPoint === 'ConnectorSourceEnd' || endPoint === 'ConnectorTargetEnd')) {\n var nodeEndId = endPoint === 'ConnectorSourceEnd' ? 'sourceID' : 'targetID';\n var portEndId = endPoint === 'ConnectorSourceEnd' ? 'sourcePortID' : 'targetPortID';\n if (connector[nodeEndId]) {\n oldChanges[nodeEndId] = connector[nodeEndId];\n connector[nodeEndId] = '';\n newChanges[nodeEndId] = connector[nodeEndId];\n if (connector.sourcePortID || connector.targetPortID) {\n oldChanges[portEndId] = connector[portEndId];\n connector[portEndId] = '';\n newChanges[portEndId] = connector[portEndId];\n }\n this.connectionEventChange(connector, oldChanges, newChanges, endPoint);\n }\n }\n else if ((endPoint !== 'OrthoThumb' && endPoint !== 'SegmentEnd') && (connector.sourceID || connector.targetID)) {\n oldChanges = {\n sourceID: connector.sourceID, sourcePortID: connector.sourcePortID,\n targetID: connector.targetID, targetPortID: connector.targetPortID\n };\n connector.sourceID = '';\n connector.sourcePortID = '';\n connector.targetID = '';\n connector.targetPortID = '';\n newChanges = {\n sourceID: connector.sourceID, sourcePortID: connector.sourcePortID,\n targetID: connector.targetID, targetPortID: connector.targetPortID\n };\n var arg = {\n connector: connector, oldValue: oldChanges,\n newValue: newChanges, cancel: false, state: 'Changing', connectorEnd: endPoint\n };\n this.triggerEvent(DiagramEvent.connectionChange, arg);\n if (arg.cancel) {\n connector.sourceID = oldChanges.sourceID;\n connector.sourcePortID = oldChanges.sourcePortID;\n connector.targetID = oldChanges.targetID;\n connector.targetPortID = oldChanges.targetPortID;\n }\n else {\n this.diagram.connectorPropertyChange(connector, oldChanges, newChanges);\n this.diagram.updateDiagramObject(connector);\n arg = {\n connector: connector, oldValue: oldChanges,\n newValue: newChanges, cancel: false, state: 'Changed', connectorEnd: endPoint\n };\n this.triggerEvent(DiagramEvent.connectionChange, arg);\n }\n }\n }\n };\n CommandHandler.prototype.connectionEventChange = function (connector, oldChanges, newChanges, endPoint) {\n var nodeEndId = endPoint === 'ConnectorSourceEnd' ? 'sourceID' : 'targetID';\n var portEndId = endPoint === 'ConnectorSourceEnd' ? 'sourcePortID' : 'targetPortID';\n var arg = {\n connector: connector, oldValue: { nodeId: oldChanges[nodeEndId], portId: oldChanges[portEndId] },\n newValue: { nodeId: newChanges[nodeEndId], portId: newChanges[portEndId] },\n cancel: false, state: 'Changing', connectorEnd: endPoint\n };\n this.triggerEvent(DiagramEvent.connectionChange, arg);\n if (arg.cancel) {\n connector[nodeEndId] = oldChanges[nodeEndId];\n connector[portEndId] = oldChanges[portEndId];\n newChanges = oldChanges;\n }\n else {\n this.diagram.connectorPropertyChange(connector, oldChanges, newChanges);\n this.diagram.updateDiagramObject(connector);\n arg = {\n connector: connector, oldValue: { nodeId: oldChanges[nodeEndId], portId: oldChanges[portEndId] },\n newValue: { nodeId: newChanges[nodeEndId], portId: newChanges[portEndId] },\n cancel: false, state: 'Changed', connectorEnd: endPoint\n };\n this.triggerEvent(DiagramEvent.connectionChange, arg);\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.findTarget = function (element, argsTarget, source) {\n var target;\n if (argsTarget instanceof Node) {\n if (element && element.id === argsTarget.id + '_content') {\n return argsTarget;\n }\n if (source && argsTarget.shape.type === 'Bpmn' && argsTarget.shape.shape === 'Activity') {\n if (argsTarget.shape.activity.subProcess.type === 'Transaction') {\n var transaction = argsTarget.shape.activity.subProcess.transaction;\n if (transaction.success.visible && element.id.indexOf(argsTarget.id + '_success') === 0) {\n return transaction.success;\n }\n if (transaction.cancel.visible && element.id.indexOf(argsTarget.id + '_cancel') === 0) {\n return transaction.cancel;\n }\n if (transaction.failure.visible && element.id.indexOf(argsTarget.id + '_failure') === 0) {\n return transaction.failure;\n }\n }\n }\n if (element instanceof PathElement) {\n for (var i = 0; i < argsTarget.ports.length; i++) {\n var port = argsTarget.ports[i];\n if (element.id === argsTarget.id + '_' + port.id) {\n return port;\n }\n }\n }\n }\n return argsTarget;\n };\n /**\n * @private\n */\n CommandHandler.prototype.canDisconnect = function (endPoint, args, targetPortId, targetNodeId) {\n var selector;\n var connect;\n if (args.source instanceof Selector) {\n selector = args.source;\n connect = selector.connectors[0];\n }\n else if (args.source instanceof Connector && this.diagram.currentDrawingObject) {\n connect = this.diagram.currentDrawingObject;\n }\n var targetObject = this.findTarget(args.targetWrapper, args.target, endPoint === 'ConnectorSourceEnd');\n var nodeEnd = endPoint === 'ConnectorSourceEnd' ? 'sourceID' : 'targetID';\n var portEnd = endPoint === 'ConnectorSourceEnd' ? 'sourcePortID' : 'targetPortID';\n if (connect[nodeEnd] !== targetNodeId || connect[portEnd] !== targetPortId) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n CommandHandler.prototype.connect = function (endPoint, args) {\n var newChanges = {};\n var oldChanges = {};\n var oldNodeId;\n var oldPortId;\n var selectorModel;\n var connector;\n if (args.source instanceof Selector) {\n selectorModel = args.source;\n connector = selectorModel.connectors[0];\n }\n else if (args.source instanceof Connector && this.diagram.currentDrawingObject) {\n connector = this.diagram.currentDrawingObject;\n }\n var target = this.findTarget(args.targetWrapper, args.target, endPoint === 'ConnectorSourceEnd');\n var nodeEndId = endPoint === 'ConnectorSourceEnd' ? 'sourceID' : 'targetID';\n var portEndId = endPoint === 'ConnectorSourceEnd' ? 'sourcePortID' : 'targetPortID';\n if (target instanceof Node) {\n oldChanges[nodeEndId] = connector[nodeEndId];\n connector[nodeEndId] = target.id;\n newChanges[nodeEndId] = connector[nodeEndId];\n oldChanges[portEndId] = connector[portEndId];\n this.connectionEventChange(connector, oldChanges, newChanges, endPoint);\n }\n else {\n oldNodeId = connector[nodeEndId];\n oldPortId = connector[portEndId];\n connector[portEndId] = target.id;\n connector[nodeEndId] = args.target.id;\n newChanges[nodeEndId] = connector[nodeEndId];\n newChanges[portEndId] = connector[portEndId];\n var arg = {\n connector: connector, oldValue: { nodeId: oldNodeId, portId: oldPortId },\n newValue: { nodeId: newChanges[nodeEndId], portId: newChanges[portEndId] },\n cancel: false, state: 'Changing', connectorEnd: endPoint\n };\n this.triggerEvent(DiagramEvent.connectionChange, arg);\n if (arg.cancel) {\n connector[nodeEndId] = oldNodeId;\n connector[portEndId] = oldPortId;\n newChanges[nodeEndId] = oldNodeId;\n newChanges[portEndId] = oldPortId;\n }\n else {\n this.diagram.connectorPropertyChange(connector, {}, newChanges);\n this.diagram.updateDiagramObject(connector);\n arg = {\n connector: connector, oldValue: { nodeId: oldNodeId, portId: oldPortId },\n newValue: { nodeId: newChanges[nodeEndId], portId: newChanges[portEndId] }, cancel: false,\n state: 'Changed', connectorEnd: endPoint\n };\n this.triggerEvent(DiagramEvent.connectionChange, arg);\n }\n }\n this.renderHighlighter(args, undefined, endPoint === 'ConnectorSourceEnd');\n };\n /** @private */\n CommandHandler.prototype.cut = function () {\n var index;\n this.clipboardData.pasteIndex = 0;\n if (this.diagram.undoRedoModule) {\n this.diagram.historyList.startGroupAction();\n }\n this.clipboardData.clipObject = this.copyObjects();\n if (this.diagram.undoRedoModule) {\n this.diagram.historyList.endGroupAction();\n }\n if (this.diagram.mode !== 'SVG') {\n this.diagram.refreshDiagramLayer();\n }\n };\n /** @private */\n CommandHandler.prototype.addLayer = function (layer, objects) {\n layer.id = layer.id || randomId();\n layer.zIndex = this.diagram.layers.length;\n layer = new Layer(this.diagram, 'layers', layer, true);\n layer.objectZIndex = -1;\n layer.zIndexTable = {};\n this.diagram.layers.push(layer);\n this.diagram.layerZIndexTable[layer.zIndex] = layer.id;\n this.diagram.activeLayer = layer;\n var layers = layer.objects;\n if (objects) {\n for (var i = 0; i < objects.length; i++) {\n this.diagram.add(objects[i]);\n }\n }\n };\n /** @private */\n CommandHandler.prototype.getObjectLayer = function (objectName) {\n var layers = this.diagram.layers;\n for (var i = 0; i < layers.length; i++) {\n var objIndex = layers[i].objects.indexOf(objectName);\n if (objIndex > -1) {\n return layers[i];\n }\n }\n return this.diagram.activeLayer;\n };\n /** @private */\n CommandHandler.prototype.getLayer = function (layerName) {\n var layers = this.diagram.layers;\n for (var i = 0; i < layers.length; i++) {\n if (layers[i].id === layerName) {\n return layers[i];\n }\n }\n return undefined;\n };\n /** @private */\n CommandHandler.prototype.removeLayer = function (layerId) {\n var layers = this.getLayer(layerId);\n if (layers) {\n var index = this.diagram.layers.indexOf(layers);\n var layerObject = layers.objects;\n for (var i = layerObject.length - 1; i >= 0; i--) {\n this.diagram.unSelect(this.diagram.nameTable[layerObject[i]]);\n this.diagram.remove(this.diagram.nameTable[layerObject[i]]);\n if (layers.id !== 'default_layer') {\n if (this.diagram.activeLayer.id === layerId) {\n this.diagram.activeLayer = this.diagram.layers[this.diagram.layers.length - 1];\n }\n }\n }\n delete this.diagram.layerZIndexTable[layers.zIndex];\n this.diagram.layers.splice(index, 1);\n if (this.diagram.mode !== 'SVG') {\n this.diagram.refreshDiagramLayer();\n }\n }\n };\n /** @private */\n CommandHandler.prototype.moveObjects = function (objects, targetLayer) {\n var layer = this.getLayer(targetLayer) || this.diagram.activeLayer;\n this.diagram.setActiveLayer(layer.id);\n var targerNodes;\n for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {\n var i = objects_1[_i];\n var layer_1 = this.getObjectLayer(i);\n var index = layer_1.objects.indexOf(i);\n if (index > -1) {\n targerNodes = this.diagram.nameTable[i];\n this.diagram.unSelect(targerNodes);\n this.diagram.remove(this.diagram.nameTable[i]);\n this.diagram.add(targerNodes);\n }\n }\n };\n /** @private */\n CommandHandler.prototype.cloneLayer = function (layerName) {\n var layers = this.diagram.layers;\n var layer = this.getLayer(layerName);\n if (layer) {\n var cloneObject_1 = [];\n var newlayer = {\n id: layerName + '_' + randomId(), objects: [], visible: true, lock: false\n };\n this.addLayer(newlayer);\n newlayer.zIndex = this.diagram.layers.length - 1;\n var multiSelect = cloneObject_1.length !== 1;\n for (var _i = 0, _a = layer.objects; _i < _a.length; _i++) {\n var obj = _a[_i];\n cloneObject_1.push(this.diagram.nameTable[obj]);\n }\n this.paste(cloneObject_1);\n }\n };\n /** @private */\n CommandHandler.prototype.copy = function () {\n this.clipboardData.pasteIndex = 1;\n this.clipboardData.clipObject = this.copyObjects();\n return this.clipboardData.clipObject;\n };\n /** @private */\n CommandHandler.prototype.copyObjects = function () {\n var selectedItems = [];\n var obj = [];\n this.clipboardData.childTable = {};\n if (this.diagram.selectedItems.connectors.length > 0) {\n selectedItems = this.diagram.selectedItems.connectors;\n for (var j = 0; j < selectedItems.length; j++) {\n var element = clone((selectedItems[j]));\n obj.push(element);\n }\n }\n if (this.diagram.selectedItems.nodes.length > 0) {\n selectedItems = selectedItems.concat(this.diagram.selectedItems.nodes);\n for (var j = 0; j < this.diagram.selectedItems.nodes.length; j++) {\n var node = clone(this.diagram.selectedItems.nodes[j]);\n var processTable = {};\n this.copyProcesses(node);\n obj.push(clone(node));\n var matrix = identityMatrix();\n rotateMatrix(matrix, -node.rotateAngle, node.offsetX, node.offsetY);\n if (node.children) {\n var childTable = this.clipboardData.childTable;\n var tempNode = void 0;\n var elements = [];\n var nodes = this.getAllDescendants(node, elements, true);\n for (var i = 0; i < nodes.length; i++) {\n tempNode = this.diagram.nameTable[nodes[i].id];\n var clonedObject = childTable[tempNode.id] = clone(tempNode);\n var newOffset = transformPointByMatrix(matrix, { x: clonedObject.wrapper.offsetX, y: clonedObject.wrapper.offsetY });\n if (tempNode instanceof Node) {\n clonedObject.offsetX = newOffset.x;\n clonedObject.offsetY = newOffset.y;\n clonedObject.rotateAngle -= node.rotateAngle;\n }\n }\n this.clipboardData.childTable = childTable;\n }\n }\n }\n if (this.clipboardData.pasteIndex === 0) {\n this.startGroupAction();\n for (var _i = 0, selectedItems_1 = selectedItems; _i < selectedItems_1.length; _i++) {\n var item = selectedItems_1[_i];\n if (this.diagram.nameTable[item.id]) {\n this.diagram.remove(item);\n }\n }\n this.endGroupAction();\n }\n this.sortByZIndex(obj, 'zIndex');\n return obj;\n };\n CommandHandler.prototype.copyProcesses = function (node) {\n if (node.shape.type === 'Bpmn' && node.shape.activity &&\n node.shape.activity.subProcess.processes &&\n node.shape.activity.subProcess.processes.length > 0) {\n var processes = node.shape.activity.subProcess.processes;\n for (var _i = 0, processes_1 = processes; _i < processes_1.length; _i++) {\n var i = processes_1[_i];\n this.processTable[i] = (clone(this.diagram.nameTable[i]));\n if (this.processTable[i].shape.activity.subProcess.processes &&\n this.processTable[i].shape.activity.subProcess.processes.length > 0) {\n this.copyProcesses(this.processTable[i]);\n }\n }\n this.clipboardData.processTable = this.processTable;\n }\n };\n /** @private */\n CommandHandler.prototype.group = function () {\n var propName = 'isProtectedOnChange';\n var protectedChange = this.diagram[propName];\n this.diagram.protectPropertyChange(true);\n this.diagram.diagramActions = this.diagram.diagramActions | DiagramAction.Group;\n var selectedItems = [];\n var obj = {};\n obj.id = 'group' + randomId();\n obj = new Node(this.diagram, 'nodes', obj, true);\n obj.children = [];\n selectedItems = this.diagram.selectedItems.nodes;\n selectedItems = selectedItems.concat(this.diagram.selectedItems.connectors);\n for (var i = 0; i < selectedItems.length; i++) {\n if (!selectedItems[i].parentId) {\n obj.children.push(selectedItems[i].id);\n }\n }\n this.diagram.add(obj);\n var entry = { type: 'Group', undoObject: obj, redoObject: obj, category: 'Internal' };\n this.addHistoryEntry(entry);\n this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.Group;\n this.diagram.protectPropertyChange(protectedChange);\n };\n /** @private */\n CommandHandler.prototype.unGroup = function (obj) {\n var propName = 'isProtectedOnChange';\n var protectedChange = this.diagram[propName];\n this.diagram.protectPropertyChange(true);\n this.diagram.diagramActions = this.diagram.diagramActions | DiagramAction.Group;\n var selectedItems = [];\n if (obj) {\n selectedItems.push(obj);\n }\n else {\n selectedItems = this.diagram.selectedItems.nodes;\n }\n for (var i = 0; i < selectedItems.length; i++) {\n var node = selectedItems[i];\n var entry = {\n type: 'UnGroup', undoObject: cloneObject(node),\n redoObject: cloneObject(node), category: 'Internal'\n };\n if (!(this.diagram.diagramActions & DiagramAction.UndoRedo)) {\n this.addHistoryEntry(entry);\n }\n if (node.children) {\n var parentNode = this.diagram.nameTable[node.parentId];\n for (var j = node.children.length - 1; j >= 0; j--) {\n (this.diagram.nameTable[node.children[0]]).parentId = '';\n this.diagram.deleteChild(this.diagram.nameTable[node.children[0]], node);\n if (node.parentId && node.children[0]) {\n this.diagram.addChild(parentNode, node.children[0]);\n }\n }\n if (node.parentId) {\n this.diagram.deleteChild(node, parentNode);\n }\n }\n this.diagram.removeNode(node);\n this.clearSelection();\n }\n this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.Group;\n this.diagram.protectPropertyChange(protectedChange);\n };\n /** @private */\n CommandHandler.prototype.paste = function (obj) {\n if (obj || this.clipboardData.clipObject) {\n this.diagram.protectPropertyChange(true);\n var copiedItems = obj ? this.getNewObject(obj) :\n this.clipboardData.clipObject;\n if (copiedItems) {\n var multiSelect = copiedItems.length !== 1;\n var groupAction = false;\n var objectTable = {};\n var keyTable = {};\n if (this.clipboardData.pasteIndex !== 0) {\n this.clearSelection();\n }\n if (this.diagram.undoRedoModule) {\n groupAction = true;\n this.diagram.historyList.startGroupAction();\n }\n for (var _i = 0, copiedItems_1 = copiedItems; _i < copiedItems_1.length; _i++) {\n var copy = copiedItems_1[_i];\n objectTable[copy.id] = copy;\n }\n for (var j = 0; j < copiedItems.length; j++) {\n var copy = copiedItems[j];\n if (getObjectType(copy) === Connector) {\n var clonedObj = clone(copy);\n var nodeId = clonedObj.sourceID;\n clonedObj.sourceID = '';\n if (objectTable[nodeId] && keyTable[nodeId]) {\n clonedObj.sourceID = keyTable[nodeId];\n }\n nodeId = clonedObj.targetID;\n clonedObj.targetID = '';\n if (objectTable[nodeId] && keyTable[nodeId]) {\n clonedObj.targetID = keyTable[nodeId];\n }\n var newObj = this.cloneConnector(clonedObj, multiSelect);\n keyTable[copy.id] = newObj.id;\n }\n else {\n var newNode = this.cloneNode(copy, multiSelect);\n //bpmn text annotations will not be pasted\n if (newNode) {\n keyTable[copy.id] = newNode.id;\n var edges = copy.inEdges;\n if (edges) {\n for (var _a = 0, edges_1 = edges; _a < edges_1.length; _a++) {\n var edge = edges_1[_a];\n if (objectTable[edge] && keyTable[edge]) {\n var newConnector = this.diagram.nameTable[keyTable[edge]];\n newConnector.targetID = keyTable[copy.id];\n this.diagram.connectorPropertyChange(newConnector, { targetID: '' }, { targetID: newConnector.targetID });\n }\n }\n }\n edges = copy.outEdges;\n if (edges) {\n for (var _b = 0, edges_2 = edges; _b < edges_2.length; _b++) {\n var edge = edges_2[_b];\n if (objectTable[edge] && keyTable[edge]) {\n var newConnector = this.diagram.nameTable[keyTable[edge]];\n newConnector.sourceID = keyTable[copy.id];\n this.diagram.connectorPropertyChange(newConnector, { sourceID: '' }, { sourceID: newConnector.sourceID });\n }\n }\n }\n }\n }\n }\n if (groupAction === true) {\n this.diagram.historyList.endGroupAction();\n groupAction = false;\n }\n if (this.diagram.mode !== 'SVG') {\n this.diagram.refreshDiagramLayer();\n }\n this.clipboardData.pasteIndex++;\n this.diagram.protectPropertyChange(false);\n }\n }\n };\n CommandHandler.prototype.getNewObject = function (obj) {\n var newObj;\n var newobjs = [];\n this.clipboardData.pasteIndex = 1;\n for (var i = 0; i < obj.length; i++) {\n newObj = cloneObject(obj[i]);\n newobjs.push(newObj);\n }\n return newobjs;\n };\n CommandHandler.prototype.cloneConnector = function (connector, multiSelect) {\n var newConnector;\n var cloneObject = clone(connector);\n this.translateObject(cloneObject);\n cloneObject.zIndex = -1;\n newConnector = this.diagram.add(cloneObject);\n this.selectObjects([newConnector], multiSelect);\n return newConnector;\n };\n CommandHandler.prototype.cloneNode = function (node, multiSelect, children) {\n var newNode;\n var connectorsTable = {};\n var cloneObject = clone(node);\n var process;\n if (node.shape && node.shape.type === 'Bpmn' && node.shape.activity &&\n node.shape.activity.subProcess.processes\n && node.shape.activity.subProcess.processes.length) {\n process = cloneObject.shape.activity.subProcess.processes;\n cloneObject.zIndex = -1;\n cloneObject.shape.activity.subProcess.processes = [];\n }\n if (node.children && node.children.length && (!children || !children.length)) {\n newNode = this.cloneGroup(node, multiSelect);\n }\n else {\n this.translateObject(cloneObject);\n cloneObject.zIndex = -1;\n if (children) {\n cloneObject.children = children;\n }\n newNode = this.diagram.add(cloneObject);\n }\n for (var _i = 0, _a = Object.keys(connectorsTable); _i < _a.length; _i++) {\n var i = _a[_i];\n this.diagram.add(connectorsTable[i]);\n }\n if (process && process.length) {\n newNode.shape.activity.subProcess.processes = process;\n this.cloneSubProcesses(newNode);\n }\n if (newNode) {\n this.selectObjects([newNode], multiSelect);\n }\n return newNode;\n };\n CommandHandler.prototype.cloneSubProcesses = function (node) {\n var connector = [];\n var temp = {};\n if (node.shape.type === 'Bpmn' && node.shape.activity &&\n node.shape.activity.subProcess.processes\n && node.shape.activity.subProcess.processes.length) {\n var process = node.shape.activity.subProcess.processes;\n for (var g = 0; g < process.length; g++) {\n var child = this.diagram.nameTable[process[g]] || this.clipboardData.processTable[process[g]];\n for (var _i = 0, _a = child.outEdges; _i < _a.length; _i++) {\n var j = _a[_i];\n if (connector.indexOf(j) < 0) {\n connector.push(j);\n }\n }\n for (var _b = 0, _c = child.inEdges; _b < _c.length; _b++) {\n var j = _c[_b];\n if (connector.indexOf(j) < 0) {\n connector.push(j);\n }\n }\n var innerChild = cloneObject(this.clipboardData.processTable[process[g]]);\n innerChild.processId = node.id;\n var newNode = this.cloneNode(innerChild, false);\n temp[process[g]] = newNode.id;\n process[g] = newNode.id;\n this.diagram.addProcess(newNode, node.id);\n for (var _d = 0, connector_1 = connector; _d < connector_1.length; _d++) {\n var i = connector_1[_d];\n var node_1 = this.diagram.nameTable[i] || this.diagram.connectorTable[i];\n var clonedNode = cloneObject(node_1);\n if (temp[clonedNode.sourceID] && temp[clonedNode.targetID]) {\n clonedNode.zIndex = -1;\n clonedNode.id += randomId();\n clonedNode.sourceID = temp[clonedNode.sourceID];\n clonedNode.targetID = temp[clonedNode.targetID];\n connector.splice(connector.indexOf(i), 1);\n this.diagram.add(clonedNode);\n }\n }\n }\n }\n };\n CommandHandler.prototype.cloneGroup = function (obj, multiSelect) {\n var value;\n var newChildren = [];\n var children = [];\n children = children.concat(obj.children);\n if (this.clipboardData.childTable) {\n for (var i = 0; i < children.length; i++) {\n var childObj = this.clipboardData.childTable[children[i]];\n if (childObj) {\n var newObj = void 0;\n if (getObjectType(childObj) === Connector) {\n newObj = this.cloneConnector(childObj, multiSelect);\n }\n else {\n newObj = this.cloneNode(childObj, multiSelect);\n }\n newChildren.push(newObj.id);\n }\n }\n }\n var parentObj = this.cloneNode(obj, multiSelect, newChildren);\n return parentObj;\n };\n /** @private */\n CommandHandler.prototype.translateObject = function (obj) {\n obj.id += randomId();\n var diff = this.clipboardData.pasteIndex * 10;\n if (getObjectType(obj) === Connector) {\n obj.sourcePoint = {\n x: obj.sourcePoint.x + diff, y: obj.sourcePoint.y + diff\n };\n obj.targetPoint = {\n x: obj.targetPoint.x + diff, y: obj.targetPoint.y + diff\n };\n if (obj.type === 'Bezier') {\n var segments = obj.segments;\n for (var i = 0; i < segments.length; i++) {\n if (!Point.isEmptyPoint(segments[i].point1)) {\n segments[i].point1 = {\n x: segments[i].point1.x + diff, y: segments[i].point1.y + diff\n };\n }\n if (!Point.isEmptyPoint(segments[i].point2)) {\n segments[i].point2 = {\n x: segments[i].point2.x + diff, y: segments[i].point2.y + diff\n };\n }\n }\n }\n if (obj.type === 'Straight' || obj.type === 'Bezier') {\n if (obj.segments && obj.segments.length > 0) {\n var segments = obj.segments;\n for (var i = 0; i < segments.length - 1; i++) {\n segments[i].point.x += diff;\n segments[i].point.y += diff;\n }\n }\n }\n }\n else {\n obj.offsetX += diff;\n obj.offsetY += diff;\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.drawObject = function (obj) {\n var newObj;\n var cloneObject;\n cloneObject = clone(this.diagram.drawingObject);\n for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {\n var prop = _a[_i];\n cloneObject[prop] = obj[prop];\n }\n if (getObjectType(this.diagram.drawingObject) === Node) {\n newObj = new Node(this.diagram, 'nodes', cloneObject, true);\n newObj.id = (this.diagram.drawingObject.id || 'node') + randomId();\n this.diagram.initObject(newObj);\n }\n else {\n newObj = new Connector(this.diagram, 'connectors', cloneObject, true);\n newObj.id = (this.diagram.drawingObject.id || 'connector') + randomId();\n this.diagram.initObject(newObj);\n }\n this.diagram.updateDiagramObject(newObj);\n this.diagram.currentDrawingObject = newObj;\n return newObj;\n };\n /**\n * @private\n */\n CommandHandler.prototype.addObjectToDiagram = function (obj) {\n var newObj;\n this.diagram.removeFromAQuad(obj);\n this.diagram.removeObjectsFromLayer(this.diagram.nameTable[obj.id]);\n delete this.diagram.nameTable[obj.id];\n newObj = this.diagram.add(obj);\n if (this.diagram.mode !== 'SVG') {\n this.diagram.refreshDiagramLayer();\n }\n this.selectObjects([newObj]);\n if (obj && (!(canContinuousDraw(this.diagram)))) {\n this.diagram.tool &= ~DiagramTools.DrawOnce;\n this.diagram.currentDrawingObject = undefined;\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.addText = function (obj, currentPosition) {\n var annotation = this.diagram.findElementUnderMouse(obj, currentPosition);\n this.diagram.startTextEdit(obj, annotation instanceof TextElement ? (annotation.id).split('_')[1] : undefined);\n };\n /** @private */\n CommandHandler.prototype.selectObjects = function (obj, multipleSelection, oldValue) {\n var arg = {\n oldValue: oldValue ? oldValue : [], newValue: obj, cause: this.diagram.diagramActions,\n state: 'Changing', type: 'Addition', cancel: false\n };\n var select = true;\n this.diagram.triggerEvent(DiagramEvent.selectionChange, arg);\n var canDoMultipleSelection = canMultiSelect(this.diagram);\n var canDoSingleSelection = canSingleSelect(this.diagram);\n if (canDoSingleSelection || canDoMultipleSelection) {\n if (!canDoMultipleSelection && ((obj.length > 1) || (multipleSelection && obj.length === 1))) {\n if (obj.length === 1) {\n this.clearSelection();\n }\n else {\n return;\n }\n }\n if (!canDoSingleSelection && obj.length === 1 && (!multipleSelection || !hasSelection(this.diagram))) {\n this.clearSelection();\n return;\n }\n }\n if (!arg.cancel) {\n for (var i = 0; i < obj.length; i++) {\n var newObj = obj[i];\n select = true;\n if (!hasSelection(this.diagram)) {\n this.select(newObj, i > 0 || multipleSelection, true);\n }\n else {\n if ((i > 0 || multipleSelection) && newObj.children && !newObj.parentId) {\n for (var i_1 = 0; i_1 < this.diagram.selectedItems.nodes.length; i_1++) {\n var parentNode = this.diagram.nameTable[this.diagram.selectedItems.nodes[i_1].parentId];\n if (parentNode) {\n parentNode = this.findParent(parentNode);\n if (parentNode) {\n if (newObj.id === parentNode.id) {\n this.selectGroup(newObj);\n }\n }\n }\n }\n }\n this.selectProcesses(newObj);\n select = this.selectBpmnSubProcesses(newObj);\n if (select) {\n this.select(newObj, i > 0 || multipleSelection, true);\n }\n }\n }\n arg = {\n oldValue: oldValue ? oldValue : [], newValue: obj, cause: this.diagram.diagramActions,\n state: 'Changed', type: 'Addition', cancel: false\n };\n this.diagram.triggerEvent(DiagramEvent.selectionChange, arg);\n this.diagram.renderSelector(multipleSelection || (obj && obj.length > 1));\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.findParent = function (node) {\n if (node.parentId) {\n node = this.diagram.nameTable[node.parentId];\n this.findParent(node);\n }\n return node;\n };\n CommandHandler.prototype.selectProcesses = function (newObj) {\n if (this.hasProcesses(newObj)) {\n var processes = (newObj).shape.activity.subProcess.processes;\n for (var i = 0; i < processes.length; i++) {\n var innerChild = this.diagram.nameTable[processes[i]];\n if (this.hasProcesses(innerChild)) {\n this.selectObjects([innerChild], true);\n }\n this.unSelect(innerChild);\n }\n }\n };\n CommandHandler.prototype.selectGroup = function (newObj) {\n for (var j = 0; j < newObj.children.length; j++) {\n var innerChild = this.diagram.nameTable[newObj.children[j]];\n if (innerChild.children) {\n this.selectGroup(innerChild);\n }\n this.unSelect(this.diagram.nameTable[newObj.children[j]]);\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.selectBpmnSubProcesses = function (node) {\n var select = true;\n var parent;\n if (node.processId) {\n if (isSelected(this.diagram, this.diagram.nameTable[node.processId])) {\n select = false;\n }\n else {\n select = this.selectBpmnSubProcesses(this.diagram.nameTable[node.processId]);\n }\n }\n else if (node instanceof Connector) {\n if (node.sourceID && this.diagram.nameTable[node.sourceID] &&\n this.diagram.nameTable[node.sourceID].processId) {\n parent = this.diagram.nameTable[node.sourceID].processId;\n }\n if (node.targetID && this.diagram.nameTable[node.targetID] &&\n this.diagram.nameTable[node.targetID].processId) {\n parent = this.diagram.nameTable[node.targetID].processId;\n }\n if (parent) {\n if (isSelected(this.diagram, this.diagram.nameTable[parent])) {\n return false;\n }\n else {\n select = this.selectBpmnSubProcesses(this.diagram.nameTable[parent]);\n }\n }\n }\n return select;\n };\n /**\n * @private\n */\n CommandHandler.prototype.hasProcesses = function (node) {\n if (node) {\n if ((node.shape.type === 'Bpmn') && node.shape.activity &&\n node.shape.activity.subProcess.processes &&\n node.shape.activity.subProcess.processes.length > 0) {\n return true;\n }\n }\n return false;\n };\n /** @private */\n CommandHandler.prototype.select = function (obj, multipleSelection, preventUpdate) {\n var hasLayer = this.getObjectLayer(obj.id);\n if ((canSelect(obj) && !(obj instanceof Selector) && !isSelected(this.diagram, obj))\n && (hasLayer && !hasLayer.lock && hasLayer.visible) && obj.wrapper.visible) {\n multipleSelection = hasSelection(this.diagram) ? multipleSelection : false;\n if (!multipleSelection) {\n this.clearSelection();\n }\n var selectorModel = this.diagram.selectedItems;\n var convert = obj;\n if (convert instanceof Node) {\n selectorModel.nodes.push(obj);\n }\n else {\n selectorModel.connectors.push(obj);\n }\n if (!multipleSelection) {\n selectorModel.init(this.diagram);\n if (selectorModel.nodes.length === 1 && selectorModel.connectors.length === 0) {\n selectorModel.rotateAngle = selectorModel.nodes[0].rotateAngle;\n selectorModel.wrapper.rotateAngle = selectorModel.nodes[0].rotateAngle;\n selectorModel.wrapper.pivot = selectorModel.nodes[0].pivot;\n }\n }\n else {\n selectorModel.wrapper.rotateAngle = selectorModel.rotateAngle = 0;\n selectorModel.wrapper.children.push(obj.wrapper);\n }\n if (!preventUpdate) {\n this.diagram.renderSelector(multipleSelection);\n }\n }\n };\n /** @private */\n CommandHandler.prototype.unSelect = function (obj) {\n var objArray = [];\n objArray.push(obj);\n var arg = {\n oldValue: objArray, newValue: [], cause: this.diagram.diagramActions,\n state: 'Changing', type: 'Removal', cancel: false\n };\n if (!this.diagram.currentSymbol) {\n this.diagram.triggerEvent(DiagramEvent.selectionChange, arg);\n }\n if (isSelected(this.diagram, obj)) {\n var selectormodel = this.diagram.selectedItems;\n var index = void 0;\n if (obj instanceof Node) {\n index = selectormodel.nodes.indexOf(obj, 0);\n selectormodel.nodes.splice(index, 1);\n }\n else {\n index = selectormodel.connectors.indexOf(obj, 0);\n selectormodel.connectors.splice(index, 1);\n }\n arg = {\n oldValue: objArray, newValue: [], cause: this.diagram.diagramActions,\n state: 'Changed', type: 'Removal', cancel: false\n };\n if (!arg.cancel) {\n index = selectormodel.wrapper.children.indexOf(obj.wrapper, 0);\n selectormodel.wrapper.children.splice(index, 1);\n this.diagram.updateSelector();\n if (!this.diagram.currentSymbol) {\n this.diagram.triggerEvent(DiagramEvent.selectionChange, arg);\n }\n }\n }\n };\n /** @private */\n CommandHandler.prototype.getChildElements = function (child) {\n var children = [];\n for (var i = 0; i < child.length; i++) {\n var childNode = child[i];\n if (childNode.children && childNode.children.length > 0) {\n children.concat(this.getChildElements(childNode.children));\n }\n else {\n children.push(childNode.id);\n if (childNode instanceof TextElement) {\n children.push(childNode.id + '_text');\n }\n }\n }\n return children;\n };\n CommandHandler.prototype.moveSvgNode = function (nodeId, targetID) {\n var diagramDiv = getDiagramElement(targetID + '_groupElement');\n var backNode = getDiagramElement(nodeId + '_groupElement');\n diagramDiv.parentNode.insertBefore(backNode, diagramDiv);\n };\n /** @private */\n CommandHandler.prototype.sendLayerBackward = function (layerName) {\n var layer = this.getLayer(layerName);\n if (layer && layer.zIndex !== 0) {\n var index = layer.zIndex;\n if (this.diagram.mode === 'SVG') {\n var currentLayerObject = layer.objects;\n var targetObject = this.getLayer(this.diagram.layerZIndexTable[index - 1]).objects[0];\n if (targetObject) {\n for (var _i = 0, currentLayerObject_1 = currentLayerObject; _i < currentLayerObject_1.length; _i++) {\n var obj = currentLayerObject_1[_i];\n this.moveSvgNode(obj, targetObject);\n }\n }\n }\n var targetLayer = this.getLayer(this.diagram.layerZIndexTable[index - 1]);\n targetLayer.zIndex = targetLayer.zIndex + 1;\n layer.zIndex = layer.zIndex - 1;\n var temp = this.diagram.layerZIndexTable[index];\n this.diagram.layerZIndexTable[index] = this.diagram.layerZIndexTable[index - 1];\n this.diagram.layerZIndexTable[index - 1] = temp;\n if (this.diagram.mode === 'Canvas') {\n this.diagram.refreshDiagramLayer();\n }\n }\n };\n /** @private */\n CommandHandler.prototype.bringLayerForward = function (layerName) {\n var layer = this.getLayer(layerName);\n if (layer && layer.zIndex < this.diagram.layers.length - 1) {\n var index = layer.zIndex;\n if (this.diagram.mode === 'SVG') {\n var targetObject = this.getLayer(this.diagram.layerZIndexTable[index + 1]).objects[0];\n var currentLayerObject = layer.objects;\n for (var _i = 0, currentLayerObject_2 = currentLayerObject; _i < currentLayerObject_2.length; _i++) {\n var obj = currentLayerObject_2[_i];\n if (targetObject) {\n this.moveSvgNode(targetObject, obj);\n }\n }\n }\n var targetLayer = this.getLayer(this.diagram.layerZIndexTable[index + 1]);\n targetLayer.zIndex = targetLayer.zIndex - 1;\n layer.zIndex = layer.zIndex + 1;\n var temp = this.diagram.layerZIndexTable[index];\n this.diagram.layerZIndexTable[index] = this.diagram.layerZIndexTable[index + 1];\n this.diagram.layerZIndexTable[index + 1] = temp;\n if (this.diagram.mode === 'Canvas') {\n this.diagram.refreshDiagramLayer();\n }\n }\n };\n /** @private */\n CommandHandler.prototype.sendToBack = function () {\n if (hasSelection(this.diagram)) {\n var objectId = this.diagram.selectedItems.nodes.length ? this.diagram.selectedItems.nodes[0].id\n : this.diagram.selectedItems.connectors[0].id;\n var index = this.diagram.nameTable[objectId].zIndex;\n var layerNum = this.diagram.layers.indexOf(this.getObjectLayer(objectId));\n var zIndexTable = this.diagram.layers[layerNum].zIndexTable;\n for (var i = index; i > 0; i--) {\n if (zIndexTable[i]) {\n //When there are empty records in the zindex table\n if (!zIndexTable[i - 1]) {\n zIndexTable[i - 1] = zIndexTable[i];\n this.diagram.nameTable[zIndexTable[i - 1]].zIndex = i;\n delete zIndexTable[i];\n }\n else {\n //bringing the objects forward\n zIndexTable[i] = zIndexTable[i - 1];\n this.diagram.nameTable[zIndexTable[i]].zIndex = i;\n }\n }\n }\n zIndexTable[0] = this.diagram.nameTable[objectId].id;\n this.diagram.nameTable[objectId].zIndex = 0;\n if (this.diagram.mode === 'SVG') {\n var i = 1;\n var target = zIndexTable[i];\n while (!target && i < index) {\n target = zIndexTable[++i];\n }\n this.moveSvgNode(objectId, target);\n }\n else {\n this.diagram.refreshCanvasLayers();\n }\n }\n };\n /** @private */\n CommandHandler.prototype.bringToFront = function () {\n if (hasSelection(this.diagram)) {\n var objectName = this.diagram.selectedItems.nodes.length ? this.diagram.selectedItems.nodes[0].id\n : this.diagram.selectedItems.connectors[0].id;\n var layerNum = this.diagram.layers.indexOf(this.getObjectLayer(objectName));\n var zIndexTable = this.diagram.layers[layerNum].zIndexTable;\n //find the maximum zIndex of the tabel\n var tabelLength = Number(Object.keys(zIndexTable).sort(function (a, b) { return Number(a) - Number(b); }).reverse()[0]);\n var index = this.diagram.nameTable[objectName].zIndex;\n for (var i = index; i < tabelLength; i++) {\n //When there are empty records in the zindex table\n if (zIndexTable[i]) {\n if (!zIndexTable[i + 1]) {\n zIndexTable[i + 1] = zIndexTable[i];\n this.diagram.nameTable[zIndexTable[i + 1]].zIndex = i;\n delete zIndexTable[i];\n }\n else {\n //bringing the objects backward\n zIndexTable[i] = zIndexTable[i + 1];\n this.diagram.nameTable[zIndexTable[i]].zIndex = i;\n }\n }\n }\n zIndexTable[tabelLength] = this.diagram.nameTable[objectName].id;\n this.diagram.nameTable[objectName].zIndex = tabelLength;\n if (this.diagram.mode === 'SVG') {\n var diagramLayer = this.diagram.diagramLayer;\n var child = this.getChildElements(this.diagram.nameTable[objectName].wrapper.children);\n var targerNodes = [];\n var element = getDiagramElement(objectName + '_groupElement');\n element.parentNode.removeChild(element);\n var htmlLayer = getHTMLLayer(this.diagram.element.id);\n this.diagram.diagramRenderer.renderElement(this.diagram.nameTable[objectName].wrapper, diagramLayer, htmlLayer);\n }\n else {\n this.diagram.refreshCanvasLayers();\n }\n }\n };\n /** @private */\n CommandHandler.prototype.sortByZIndex = function (nodeArray, sortID) {\n var id = sortID ? sortID : 'zIndex';\n nodeArray = nodeArray.sort(function (a, b) {\n return a[id] - b[id];\n });\n return nodeArray;\n };\n /** @private */\n CommandHandler.prototype.sendForward = function () {\n if (hasSelection(this.diagram)) {\n var nodeId = this.diagram.selectedItems.nodes.length ? this.diagram.selectedItems.nodes[0].id\n : this.diagram.selectedItems.connectors[0].id;\n var layerIndex = this.diagram.layers.indexOf(this.getObjectLayer(nodeId));\n var zIndexTable = this.diagram.layers[layerIndex].zIndexTable;\n var tabelLength = Object.keys(zIndexTable).length;\n var index = this.diagram.nameTable[nodeId];\n var intersectArray = [];\n var temp = this.diagram.spatialSearch.findObjects(index.wrapper.bounds);\n if (temp.length > 2) {\n temp = this.sortByZIndex(temp);\n }\n for (var _i = 0, temp_1 = temp; _i < temp_1.length; _i++) {\n var i = temp_1[_i];\n if (index.id !== i.id) {\n var currentLayer = this.getObjectLayer(i.id).zIndex;\n if (layerIndex === currentLayer && (Number(this.diagram.nameTable[nodeId].zIndex) < Number(i.zIndex)) &&\n index.wrapper.bounds.intersects(i.wrapper.bounds)) {\n intersectArray.push(i);\n break;\n }\n }\n }\n if (intersectArray.length > 0) {\n var overlapObject = intersectArray[0].zIndex;\n var currentObject = index.zIndex;\n var temp_2 = zIndexTable[overlapObject];\n //swap the nodes\n this.diagram.layers[0].zIndexTable[overlapObject] = index.id;\n this.diagram.nameTable[zIndexTable[overlapObject]].zIndex = overlapObject;\n this.diagram.layers[0].zIndexTable[currentObject] = intersectArray[0].id;\n this.diagram.nameTable[zIndexTable[currentObject]].zIndex = currentObject;\n if (this.diagram.mode === 'SVG') {\n this.moveSvgNode(zIndexTable[Number(intersectArray[0].zIndex)], nodeId);\n }\n else {\n this.diagram.refreshCanvasLayers();\n }\n }\n }\n };\n /** @private */\n CommandHandler.prototype.sendBackward = function () {\n if (hasSelection(this.diagram)) {\n var objectId = this.diagram.selectedItems.nodes.length ? this.diagram.selectedItems.nodes[0].id\n : this.diagram.selectedItems.connectors[0].id;\n var layerNum = this.diagram.layers.indexOf(this.getObjectLayer(objectId));\n var zIndexTable = this.diagram.layers[layerNum].zIndexTable;\n var tabelLength = Object.keys(zIndexTable).length;\n var node = this.diagram.nameTable[objectId];\n var intersectArray = [];\n var temp = this.diagram.spatialSearch.findObjects(node.wrapper.bounds);\n if (temp.length > 2) {\n temp = this.sortByZIndex(temp);\n }\n for (var _i = 0, temp_3 = temp; _i < temp_3.length; _i++) {\n var i = temp_3[_i];\n if (node.id !== i.id) {\n var currentLayer = this.getObjectLayer(i.id).zIndex;\n if (layerNum === currentLayer && (Number(this.diagram.nameTable[objectId].zIndex) > Number(i.zIndex)) &&\n node.wrapper.bounds.intersects(i.wrapper.bounds)) {\n intersectArray.push(i);\n }\n }\n }\n if (intersectArray.length > 0) {\n var overlapObject = intersectArray[intersectArray.length - 1].zIndex;\n var currentObject = node.zIndex;\n var temp_4 = zIndexTable[overlapObject];\n //swap the nodes\n zIndexTable[overlapObject] = node.id;\n this.diagram.nameTable[zIndexTable[overlapObject]].zIndex = overlapObject;\n zIndexTable[currentObject] = intersectArray[intersectArray.length - 1].id;\n this.diagram.nameTable[zIndexTable[currentObject]].zIndex = currentObject;\n if (this.diagram.mode === 'SVG') {\n this.moveSvgNode(objectId, zIndexTable[intersectArray[intersectArray.length - 1].zIndex]);\n }\n else {\n this.diagram.refreshCanvasLayers();\n }\n }\n }\n };\n CommandHandler.prototype.initSelectorWrapper = function () {\n var selectorModel = this.diagram.selectedItems;\n selectorModel.init(this.diagram);\n if (selectorModel.nodes.length === 1 && selectorModel.connectors.length === 0) {\n selectorModel.rotateAngle = selectorModel.nodes[0].rotateAngle;\n selectorModel.wrapper.rotateAngle = selectorModel.nodes[0].rotateAngle;\n selectorModel.wrapper.pivot = selectorModel.nodes[0].pivot;\n }\n };\n /** @private */\n CommandHandler.prototype.doRubberBandSelection = function (region) {\n this.clearSelectionRectangle();\n this.clearSelection();\n var selArray = [];\n var rubberArray = [];\n selArray = this.diagram.getNodesConnectors(selArray);\n if (this.diagram.selectedItems.rubberBandSelectionMode === 'CompleteIntersect') {\n rubberArray = completeRegion(region, selArray);\n }\n else {\n rubberArray = this.diagram.spatialSearch.findObjects(region);\n }\n if (rubberArray.length) {\n this.selectObjects(rubberArray, true);\n }\n };\n CommandHandler.prototype.clearSelectionRectangle = function () {\n var adornerSvg = getAdornerLayerSvg(this.diagram.element.id);\n var element = adornerSvg.getElementById(this.diagram.element.id + '_diagramAdorner_selected_region');\n if (element) {\n remove(element);\n }\n };\n /** @private */\n CommandHandler.prototype.dragConnectorEnds = function (endPoint, obj, point, segment, target, targetPortId) {\n var selectorModel;\n var connector;\n var node;\n var tx;\n var segmentPoint;\n var ty;\n var index;\n var checkBezierThumb = false;\n if (obj instanceof Selector) {\n selectorModel = obj;\n connector = selectorModel.connectors[0];\n }\n else if (obj instanceof Connector && this.diagram.currentDrawingObject) {\n this.clearSelection();\n connector = this.diagram.currentDrawingObject;\n }\n if (endPoint === 'BezierSourceThumb' || endPoint === 'BezierTargetThumb') {\n checkBezierThumb = true;\n }\n if (endPoint === 'ConnectorSourceEnd' || endPoint === 'BezierSourceThumb') {\n tx = point.x - (checkBezierThumb ? segment.bezierPoint1.x : connector.sourcePoint.x);\n ty = point.y - (checkBezierThumb ? segment.bezierPoint1.y : connector.sourcePoint.y);\n return this.dragSourceEnd(connector, tx, ty, null, point, endPoint, undefined, target, targetPortId, undefined, segment);\n }\n else {\n tx = point.x - (checkBezierThumb ? segment.bezierPoint2.x : connector.targetPoint.x);\n ty = point.y - (checkBezierThumb ? segment.bezierPoint2.y : connector.targetPoint.y);\n return this.dragTargetEnd(connector, tx, ty, null, point, endPoint, undefined, segment);\n }\n };\n CommandHandler.prototype.getSelectedObject = function () {\n var selectormodel = this.diagram.selectedItems;\n return (selectormodel.nodes).concat(selectormodel.connectors);\n };\n /** @private */\n CommandHandler.prototype.clearSelection = function (triggerAction) {\n if (hasSelection(this.diagram)) {\n var selectormodel = this.diagram.selectedItems;\n var arrayNodes = this.getSelectedObject();\n var arg = {\n oldValue: arrayNodes, newValue: [], cause: this.diagram.diagramActions,\n state: 'Changing', type: 'Removal', cancel: false\n };\n if (triggerAction) {\n this.diagram.triggerEvent(DiagramEvent.selectionChange, arg);\n }\n if (!arg.cancel) {\n selectormodel.offsetX = 0;\n selectormodel.offsetY = 0;\n selectormodel.width = 0;\n selectormodel.height = 0;\n selectormodel.rotateAngle = 0;\n selectormodel.nodes = [];\n selectormodel.connectors = [];\n selectormodel.wrapper = null;\n this.diagram.clearSelectorLayer();\n if (triggerAction) {\n arg = {\n oldValue: arrayNodes, newValue: [], cause: this.diagram.diagramActions,\n state: 'Changed', type: 'Removal', cancel: false\n };\n this.diagram.triggerEvent(DiagramEvent.selectionChange, arg);\n }\n }\n }\n };\n /** @private */\n CommandHandler.prototype.drag = function (obj, tx, ty) {\n var tempNode;\n var elements = [];\n if (canMove(obj) && this.checkBoundaryConstraints(tx, ty, obj.wrapper.bounds) && canPageEditable(this.diagram)) {\n if (obj instanceof Node) {\n var oldValues = { offsetX: obj.offsetX, offsetY: obj.offsetY };\n obj.offsetX += tx;\n obj.offsetY += ty;\n if (obj.children) {\n var nodes = this.getAllDescendants(obj, elements);\n for (var i = 0; i < nodes.length; i++) {\n tempNode = (this.diagram.nameTable[nodes[i].id]);\n this.drag(tempNode, tx, ty);\n }\n }\n this.diagram.nodePropertyChange(obj, oldValues, { offsetX: obj.offsetX, offsetY: obj.offsetY });\n }\n else {\n var connector = obj;\n var update = connector.type === 'Bezier' ? true : false;\n var hasEnds = false;\n if (!connector.sourceWrapper) {\n this.dragSourceEnd(connector, tx, ty, true, null, '', update);\n }\n else {\n hasEnds = true;\n }\n if (!connector.targetWrapper) {\n this.dragTargetEnd(connector, tx, ty, true, null, '', update);\n }\n else {\n hasEnds = true;\n }\n if (!hasEnds) {\n this.dragControlPoint(connector, tx, ty, true);\n var conn = { sourcePoint: connector.sourcePoint, targetPoint: connector.targetPoint };\n this.diagram.connectorPropertyChange(connector, {}, conn);\n }\n }\n }\n };\n /** @private */\n CommandHandler.prototype.updateEndPoint = function (connector) {\n var conn = {\n sourcePoint: connector.sourcePoint, targetPoint: connector.targetPoint,\n sourceID: connector.sourceID ? connector.sourceID : undefined,\n targetID: connector.targetID ? connector.targetID : undefined,\n sourcePortID: connector.sourcePortID ? connector.sourcePortID : undefined,\n targetPortID: connector.targetPortID ? connector.targetPortID : undefined,\n segments: connector.segments ? connector.segments : undefined\n };\n this.diagram.connectorPropertyChange(connector, {}, conn);\n // this.diagram.refreshDiagramLayer();\n this.diagram.updateSelector();\n };\n /** @private */\n CommandHandler.prototype.dragSourceEnd = function (obj, tx, ty, preventUpdate, point, endPoint, update, target, targetPortId, isDragSource, segment) {\n var connector = this.diagram.nameTable[obj.id];\n var checkBoundaryConstraints = this.checkBoundaryConstraints(tx, ty, connector.wrapper.bounds);\n if (canDragSourceEnd(connector) && checkBoundaryConstraints\n && (endPoint !== 'BezierSourceThumb') && canPageEditable(this.diagram)) {\n connector.sourcePoint.x += tx;\n connector.sourcePoint.y += ty;\n if (endPoint === 'ConnectorSourceEnd' && connector.type === 'Orthogonal') {\n this.changeSegmentLength(connector, target, targetPortId, isDragSource);\n }\n }\n if (connector.type === 'Bezier') {\n if (segment) {\n this.translateBezierPoints(obj, (endPoint === '') ? 'ConnectorSourceEnd' : endPoint, tx, ty, segment, point, !update);\n }\n else {\n for (var i = 0; i < obj.segments.length; i++) {\n this.translateBezierPoints(obj, (endPoint === '') ? 'ConnectorSourceEnd' : endPoint, tx, ty, obj.segments[i], point, !update);\n }\n }\n }\n if (!preventUpdate) {\n this.updateEndPoint(connector);\n }\n return checkBoundaryConstraints;\n };\n /**\n * Upadte the connector segments when change the source node\n */\n CommandHandler.prototype.changeSegmentLength = function (connector, target, targetPortId, isDragSource) {\n if (connector.segments && connector.segments[0].direction !== null\n && ((!target && connector.sourceID === '') || isDragSource)) {\n var first = connector.segments[0];\n var second = connector.segments[1];\n var node = this.diagram.nameTable[connector.sourceID];\n var secPoint = void 0;\n first.points[0] = connector.sourcePoint;\n if (first.direction === 'Top' || first.direction === 'Bottom') {\n first.points[first.points.length - 1].x = connector.sourcePoint.x;\n second.points[0].y = first.points[first.points.length - 1].y;\n }\n else {\n first.points[first.points.length - 1].y = connector.sourcePoint.y;\n second.points[0].x = first.points[first.points.length - 1].x;\n }\n if (first.direction && (first.length || first.length === 0)) {\n first.length = Point.distancePoints(first.points[0], first.points[first.points.length - 1]);\n }\n if (second.direction && (second.length || second.length === 0)) {\n second.length = Point.distancePoints(first.points[first.points.length - 1], second.points[second.points.length - 1]);\n second.direction = Point.direction(first.points[first.points.length - 1], second.points[second.points.length - 1]);\n }\n if (connector.sourcePortID !== '' && first.length < 10) {\n if (connector.segments.length > 2) {\n var next = connector.segments[2];\n var nextDirection = Point.direction(next.points[0], next.points[1]);\n if (first.direction === getOppositeDirection(nextDirection)) {\n if (first.direction === 'Right') {\n next.points[0].x = first.points[first.points.length - 1].x = node.wrapper.corners.middleRight.x + 20;\n }\n else if (first.direction === 'Left') {\n next.points[0].x = first.points[first.points.length - 1].x = node.wrapper.corners.middleLeft.x - 20;\n }\n else if (first.direction === 'Top') {\n next.points[0].y = first.points[first.points.length - 1].y = node.wrapper.corners.topCenter.y - 20;\n }\n else {\n next.points[0].y = first.points[first.points.length - 1].y = node.wrapper.corners.bottomCenter.y + 20;\n }\n if (next.direction && next.length) {\n next.length = Point.distancePoints(next.points[0], next.points[next.points.length - 1]);\n }\n first.length = Point.distancePoints(first.points[0], first.points[first.points.length - 1]);\n }\n else if (first.direction === nextDirection && next.direction && next.length) {\n if (first.direction === 'Top' || first.direction === 'Bottom') {\n next.points[0] = first.points[0];\n next.points[next.points.length - 1].x = next.points[0].x;\n }\n else {\n next.points[0] = first.points[0];\n next.points[next.points.length - 1].y = next.points[0].y;\n }\n next.length = Point.distancePoints(next.points[0], next.points[next.points.length - 1]);\n connector.segments.splice(0, 2);\n }\n else {\n first.length = 20;\n }\n }\n else {\n first.length = 20;\n }\n }\n else if (first.length < 1) {\n if (connector.sourceID !== '') {\n if (second.direction === 'Right') {\n secPoint = node.wrapper.corners.middleRight;\n second.points[second.points.length - 1].y = secPoint.y;\n }\n else if (second.direction === 'Left') {\n secPoint = node.wrapper.corners.middleLeft;\n second.points[second.points.length - 1].y = secPoint.y;\n }\n else if (second.direction === 'Top') {\n secPoint = node.wrapper.corners.topCenter;\n second.points[second.points.length - 1].x = secPoint.x;\n }\n else {\n secPoint = node.wrapper.corners.bottomCenter;\n second.points[second.points.length - 1].x = secPoint.x;\n }\n second.length = Point.distancePoints(secPoint, second.points[second.points.length - 1]);\n if (connector.segments.length > 2) {\n var next = connector.segments[2];\n if (next.direction && next.length) {\n next.length = Point.distancePoints(second.points[second.points.length - 1], next.points[next.points.length - 1]);\n }\n }\n connector.segments.splice(0, 1);\n }\n else {\n connector.segments.splice(0, 1);\n }\n }\n }\n else {\n if (target && targetPortId && connector.sourcePortID !== targetPortId &&\n connector.segments && connector.segments[0].direction !== null && target && target instanceof Node) {\n this.changeSourceEndToPort(connector, target, targetPortId);\n }\n else if (target && (connector.sourceID !== target.id || connector.sourcePortID === '') &&\n connector.segments && connector.segments[0].direction !== null && target && target instanceof Node) {\n this.changeSourceEndToNode(connector, target);\n }\n }\n };\n /**\n * Change the connector endPoint to port\n */\n CommandHandler.prototype.changeSourceEndToPort = function (connector, target, targetPortId) {\n var port = this.diagram.getWrapper(target.wrapper, targetPortId);\n var point = { x: port.offsetX, y: port.offsetY };\n var direction = getPortDirection(point, target.wrapper.corners, target.wrapper.bounds, false);\n var firstSegment = connector.segments[0];\n var secondSegment = connector.segments[1];\n if (firstSegment.direction !== direction) {\n var segments = [];\n var segValues = {};\n if (firstSegment.direction === getOppositeDirection(direction)) {\n segValues = {};\n var segValues1 = void 0;\n if (direction === 'Top' || direction === 'Bottom') {\n segValues1 = (direction === 'Top') ? {\n type: 'Orthogonal', isTerminal: true, direction: direction,\n length: Math.abs(firstSegment.points[0].y - point.y)\n } :\n {\n type: 'Orthogonal', isTerminal: true, direction: direction,\n length: Math.abs(point.y - firstSegment.points[0].y)\n };\n segValues = (firstSegment.points[0].x > point.x) ?\n { type: 'Orthogonal', isTerminal: true, direction: 'Right', length: (firstSegment.points[0].x - point.x) } :\n { type: 'Orthogonal', isTerminal: true, direction: 'Left', length: (point.x - firstSegment.points[0].x) };\n }\n else {\n segValues1 = (direction === 'Right') ? {\n type: 'Orthogonal', isTerminal: true, direction: direction,\n length: Math.abs(firstSegment.points[0].x - point.x)\n } :\n {\n type: 'Orthogonal', isTerminal: true, direction: direction,\n length: Math.abs(point.x - firstSegment.points[0].x)\n };\n segValues = (firstSegment.points[0].y > point.y) ?\n { type: 'Orthogonal', direction: 'Top', isTerminal: true, length: (firstSegment.points[0].y - point.y) } :\n { type: 'Orthogonal', direction: 'Bottom', isTerminal: true, length: (point.y - firstSegment.points[0].y) };\n }\n segments.push(new OrthogonalSegment(connector, 'segments', segValues1, true));\n segments.push(new OrthogonalSegment(connector, 'segments', segValues, true));\n }\n else {\n segValues = { type: 'Orthogonal', direction: direction, length: 20, isTerminal: true };\n segments.push(new OrthogonalSegment(connector, 'segments', segValues, true));\n }\n if (firstSegment.direction !== getOppositeDirection(direction)) {\n if (direction === 'Top' || direction === 'Bottom') {\n firstSegment.points[0].x = point.x;\n firstSegment.points[0].y = firstSegment.points[firstSegment.points.length - 1].y = (direction === 'Top') ?\n point.y - 20 : point.y + 20;\n }\n else {\n firstSegment.points[0].y = point.y;\n firstSegment.points[0].x = firstSegment.points[firstSegment.points.length - 1].x = (direction === 'Right') ?\n point.x + 20 : point.x - 20;\n }\n firstSegment.length = Point.distancePoints(firstSegment.points[0], firstSegment.points[firstSegment.points.length - 1]);\n secondSegment.length = Point.distancePoints(firstSegment.points[firstSegment.points.length - 1], secondSegment.points[secondSegment.points.length - 1]);\n }\n connector.segments = segments.concat(connector.segments);\n }\n else {\n firstSegment.points[0] = point;\n if (direction === 'Top' || direction === 'Bottom') {\n firstSegment.points[firstSegment.points.length - 1].x = point.x;\n }\n else {\n firstSegment.points[firstSegment.points.length - 1].y = point.y;\n }\n firstSegment.length = Point.distancePoints(firstSegment.points[0], firstSegment.points[firstSegment.points.length - 1]);\n secondSegment.length = Point.distancePoints(firstSegment.points[firstSegment.points.length - 1], secondSegment.points[secondSegment.points.length - 1]);\n }\n };\n /**\n * @private\n * Remove terinal segment in initial\n */\n CommandHandler.prototype.removeTerminalSegment = function (connector, changeTerminal) {\n for (var i = 0; i < connector.segments.length - 2; i++) {\n var segment = connector.segments[0];\n if (segment.isTerminal) {\n if (changeTerminal) {\n segment.isTerminal = false;\n }\n else {\n connector.segments.splice(i, 1);\n i--;\n }\n }\n }\n };\n /**\n * Change the connector endPoint from point to node\n */\n CommandHandler.prototype.changeSourceEndToNode = function (connector, target) {\n this.removeTerminalSegment(connector);\n var sourceWrapper = target.wrapper.children[0].corners;\n var sourcePoint;\n var sourcePoint2;\n var firstSegment = connector.segments[0];\n var nextSegment = connector.segments[1];\n var segments = [];\n if (firstSegment.direction === 'Right' || firstSegment.direction === 'Left') {\n sourcePoint = (firstSegment.direction === 'Left') ? sourceWrapper.middleLeft : sourceWrapper.middleRight;\n if (firstSegment.length > sourceWrapper.width || ((firstSegment.direction === 'Left' &&\n sourcePoint.x >= firstSegment.points[0].x) || (firstSegment.direction === 'Right' &&\n sourcePoint.x <= firstSegment.points[0].x))) {\n firstSegment.points[0].y = firstSegment.points[firstSegment.points.length - 1].y = sourcePoint.y;\n firstSegment.points[0].x = sourcePoint.x;\n firstSegment.length = Point.distancePoints(firstSegment.points[0], firstSegment.points[firstSegment.points.length - 1]);\n nextSegment.length = Point.distancePoints(firstSegment.points[firstSegment.points.length - 1], nextSegment.points[nextSegment.points.length - 1]);\n }\n else {\n var direction = void 0;\n if (nextSegment.direction) {\n direction = nextSegment.direction;\n }\n else {\n direction = Point.direction(nextSegment.points[0], nextSegment.points[nextSegment.points.length - 1]);\n }\n sourcePoint2 = (direction === 'Bottom') ? sourceWrapper.bottomCenter : sourceWrapper.topCenter;\n if (nextSegment.length && nextSegment.direction) {\n nextSegment.length =\n (direction === 'Top') ? firstSegment.points[firstSegment.points.length - 1].y - (sourcePoint2.y + 20) :\n (sourcePoint2.y + 20) - firstSegment.points[firstSegment.points.length - 1].y;\n }\n firstSegment.length = firstSegment.points[firstSegment.points.length - 1].x - sourcePoint2.x;\n firstSegment.direction = (firstSegment.length > 0) ? 'Right' : 'Left';\n var segValues = { type: 'Orthogonal', direction: direction, length: 20 };\n segments.push(new OrthogonalSegment(connector, 'segments', segValues, true));\n connector.segments = segments.concat(connector.segments);\n }\n }\n else {\n sourcePoint = (firstSegment.direction === 'Bottom') ? sourceWrapper.bottomCenter : sourceWrapper.topCenter;\n if (firstSegment.length > sourceWrapper.height || ((firstSegment.direction === 'Top' &&\n sourcePoint.y >= firstSegment.points[0].y) ||\n (firstSegment.direction === 'Bottom' && sourcePoint.y <= firstSegment.points[0].y))) {\n firstSegment.points[0].x = firstSegment.points[firstSegment.points.length - 1].x = sourcePoint.x;\n firstSegment.points[0].y = sourcePoint.y;\n firstSegment.length = Point.distancePoints(firstSegment.points[0], firstSegment.points[firstSegment.points.length - 1]);\n nextSegment.length = Point.distancePoints(firstSegment.points[firstSegment.points.length - 1], nextSegment.points[nextSegment.points.length - 1]);\n }\n else {\n sourcePoint2 = (nextSegment.direction === 'Left') ? sourceWrapper.middleLeft : sourceWrapper.middleRight;\n var direction = void 0;\n if (nextSegment.direction) {\n direction = nextSegment.direction;\n }\n else {\n direction = Point.direction(nextSegment.points[0], nextSegment.points[nextSegment.points.length - 1]);\n }\n if (nextSegment.length && nextSegment.direction) {\n nextSegment.length =\n (direction === 'Left') ? firstSegment.points[firstSegment.points.length - 1].x - (sourcePoint2.x + 20) :\n (sourcePoint2.x + 20) - firstSegment.points[firstSegment.points.length - 1].x;\n }\n firstSegment.length = firstSegment.points[firstSegment.points.length - 1].y - sourcePoint2.y;\n firstSegment.direction = (firstSegment.length > 0) ? 'Bottom' : 'Top';\n var segValues = { type: 'Orthogonal', direction: direction, length: 20 };\n segments.push(new OrthogonalSegment(connector, 'segments', segValues, true));\n connector.segments = segments.concat(connector.segments);\n }\n }\n };\n /**\n * Translate the bezier points during the interaction\n */\n CommandHandler.prototype.translateBezierPoints = function (connector, value, tx, ty, seg, point, update) {\n var index = (connector.segments.indexOf(seg));\n var segment = connector.segments[index];\n if (segment) {\n if (value === 'BezierSourceThumb' && (segment.vector1.angle || segment.vector1.distance)) {\n segment.vector1 = {\n distance: connector.distance(connector.sourcePoint, point),\n angle: Point.findAngle(connector.sourcePoint, point),\n };\n }\n else if (value === 'BezierTargetThumb' && (segment.vector2.angle || segment.vector2.distance)) {\n segment.vector2 = {\n distance: connector.distance(connector.targetPoint, point),\n angle: Point.findAngle(connector.targetPoint, point),\n };\n }\n else if ((value === 'ConnectorSourceEnd' && !connector.sourceID || value === 'ConnectorTargetEnd' && !connector.targetID)\n && update && isEmptyVector(segment.vector1) && isEmptyVector(segment.vector2)) {\n if (Point.isEmptyPoint(segment.point1)) {\n segment.bezierPoint1 = getBezierPoints(connector.sourcePoint, connector.targetPoint);\n }\n if (Point.isEmptyPoint(segment.point2)) {\n segment.bezierPoint2 = getBezierPoints(connector.targetPoint, connector.sourcePoint);\n }\n }\n else if (value === 'BezierSourceThumb' || (value === 'ConnectorSourceEnd' && !update && isEmptyVector(segment.vector1))) {\n segment.bezierPoint1.x += tx;\n segment.bezierPoint1.y += ty;\n if ((!Point.isEmptyPoint(segment.point1)) || (update)) {\n segment.point1 = { x: segment.bezierPoint1.x, y: segment.bezierPoint1.y };\n }\n }\n else if (value === 'BezierTargetThumb' || (value === 'ConnectorTargetEnd' && !update && isEmptyVector(segment.vector2))) {\n segment.bezierPoint2.x += tx;\n segment.bezierPoint2.y += ty;\n if ((!Point.isEmptyPoint(segment.point2)) || (update)) {\n segment.point2 = { x: segment.bezierPoint2.x, y: segment.bezierPoint2.y };\n }\n }\n }\n };\n /** @private */\n CommandHandler.prototype.dragTargetEnd = function (obj, tx, ty, preventUpdate, point, endPoint, update, segment) {\n var connector = this.diagram.nameTable[obj.id];\n var boundaryConstraints = this.checkBoundaryConstraints(tx, ty, connector.wrapper.bounds);\n if (canDragTargetEnd(connector) && endPoint !== 'BezierTargetThumb'\n && boundaryConstraints && canPageEditable(this.diagram)) {\n connector.targetPoint.x += tx;\n connector.targetPoint.y += ty;\n if (endPoint === 'ConnectorTargetEnd' && connector.type === 'Orthogonal' &&\n connector.segments && connector.segments.length > 0) {\n var prev = connector.segments[connector.segments.length - 2];\n if (prev && connector.segments[connector.segments.length - 1].points.length === 2) {\n if (prev.direction === 'Left' || prev.direction === 'Right') {\n prev.points[prev.points.length - 1].x = connector.targetPoint.x;\n }\n else {\n prev.points[prev.points.length - 1].y = connector.targetPoint.y;\n }\n prev.length = Point.distancePoints(prev.points[0], prev.points[prev.points.length - 1]);\n prev.direction = Point.direction(prev.points[0], prev.points[prev.points.length - 1]);\n }\n }\n }\n if (connector.type === 'Bezier') {\n if (segment) {\n this.translateBezierPoints(obj, (endPoint === '') ? 'ConnectorTargetEnd' : endPoint, tx, ty, segment, point, !update);\n }\n else {\n for (var i = 0; i < obj.segments.length; i++) {\n this.translateBezierPoints(obj, (endPoint === '') ? 'ConnectorTargetEnd' : endPoint, tx, ty, obj.segments[i], point, !update);\n }\n }\n }\n if (!preventUpdate) {\n this.updateEndPoint(connector);\n }\n return boundaryConstraints;\n };\n /** @private */\n CommandHandler.prototype.dragControlPoint = function (obj, tx, ty, preventUpdate, segmentNumber) {\n var connector = this.diagram.nameTable[obj.id];\n if ((connector.type === 'Straight' || connector.type === 'Bezier') && connector.segments.length > 0) {\n if (segmentNumber !== undefined && connector.segments[segmentNumber]) {\n connector.segments[segmentNumber].point.x += tx;\n connector.segments[segmentNumber].point.y += ty;\n }\n else {\n for (var i = 0; i < connector.segments.length - 1; i++) {\n connector.segments[i].point.x += tx;\n connector.segments[i].point.y += ty;\n }\n }\n if (!preventUpdate) {\n this.updateEndPoint(connector);\n }\n }\n return true;\n };\n /** @private */\n CommandHandler.prototype.rotateObjects = function (parent, objects, angle, pivot, includeParent) {\n pivot = pivot || {};\n var matrix = identityMatrix();\n rotateMatrix(matrix, angle, pivot.x, pivot.y);\n for (var _i = 0, objects_2 = objects; _i < objects_2.length; _i++) {\n var obj = objects_2[_i];\n if (obj instanceof Node) {\n if (canRotate(obj) && canPageEditable(this.diagram)) {\n if (includeParent !== false || parent !== obj) {\n obj.rotateAngle += angle;\n obj.rotateAngle = (obj.rotateAngle + 360) % 360;\n var newOffset = transformPointByMatrix(matrix, { x: obj.offsetX, y: obj.offsetY });\n obj.offsetX = newOffset.x;\n obj.offsetY = newOffset.y;\n this.diagram.nodePropertyChange(obj, {}, { offsetX: obj.offsetX, offsetY: obj.offsetY, rotateAngle: obj.rotateAngle });\n }\n if (obj.processId) {\n var parent_1 = this.diagram.nameTable[obj.processId];\n var bound = this.diagram.bpmnModule.getChildrenBound(parent_1, obj.id, this.diagram);\n this.diagram.bpmnModule.updateSubProcessess(bound, obj, this.diagram);\n }\n if (obj.children && obj.children.length) {\n this.getChildren(obj, objects);\n }\n }\n }\n else {\n this.rotatePoints(obj, angle, pivot || { x: obj.wrapper.offsetX, y: obj.wrapper.offsetY });\n }\n this.diagram.updateDiagramObject(obj);\n }\n this.diagram.updateSelector();\n };\n /** @private */\n CommandHandler.prototype.snapConnectorEnd = function (currentPosition) {\n if ((this.diagram.snapSettings.constraints & SnapConstraints.SnapToLines)\n && this.snappingModule) {\n this.diagram.snappingModule.snapConnectorEnd(currentPosition);\n }\n return currentPosition;\n };\n CommandHandler.prototype.snapAngle = function (angle) {\n if ((this.diagram.snapSettings.constraints & SnapConstraints.SnapToLines)\n && this.snappingModule) {\n return this.snappingModule.snapAngle(this.diagram, angle);\n }\n else {\n return 0;\n }\n };\n CommandHandler.prototype.rotatePoints = function (conn, angle, pivot) {\n if (!conn.sourceWrapper || !conn.targetWrapper) {\n var matrix = identityMatrix();\n rotateMatrix(matrix, angle, pivot.x, pivot.y);\n conn.sourcePoint = transformPointByMatrix(matrix, conn.sourcePoint);\n conn.targetPoint = transformPointByMatrix(matrix, conn.targetPoint);\n var newProp = { sourcePoint: conn.sourcePoint, targetPoint: conn.targetPoint };\n this.diagram.connectorPropertyChange(conn, {}, newProp);\n }\n };\n /** @private */\n CommandHandler.prototype.scale = function (obj, sw, sh, pivot, refObject) {\n var node = this.diagram.nameTable[obj.id];\n var tempNode = node;\n var elements = [];\n var element = node.wrapper;\n if (element.actualSize.width !== undefined && element.actualSize.height !== undefined && canPageEditable(this.diagram)) {\n if (tempNode.children) {\n var nodes = this.getAllDescendants(tempNode, elements);\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var temp = nodes_1[_i];\n this.scaleObject(sw, sh, pivot, temp, element, refObject);\n }\n obj.wrapper.measure(new Size());\n obj.wrapper.arrange(obj.wrapper.desiredSize);\n this.diagram.updateGroupOffset(node);\n }\n else {\n this.scaleObject(sw, sh, pivot, node, element, refObject);\n }\n var bounds = getBounds(obj.wrapper);\n var checkBoundaryConstraints = this.checkBoundaryConstraints(undefined, undefined, bounds);\n if (!checkBoundaryConstraints) {\n this.scale(obj, 1 / sw, 1 / sh, pivot);\n return false;\n }\n this.diagram.updateDiagramObject(obj);\n }\n return true;\n };\n /** @private */\n CommandHandler.prototype.getAllDescendants = function (node, nodes, includeParent) {\n var temp = node;\n for (var i = 0; i < temp.children.length; i++) {\n node = (this.diagram.nameTable[temp.children[i]]);\n if (!node.children) {\n nodes.push(node);\n }\n else {\n if (includeParent) {\n nodes.push(node);\n }\n nodes = this.getAllDescendants(node, nodes);\n }\n }\n return nodes;\n };\n CommandHandler.prototype.getChildren = function (node, nodes) {\n var temp = node;\n if (node.children) {\n for (var i = 0; i < temp.children.length; i++) {\n node = (this.diagram.nameTable[temp.children[i]]);\n nodes.push(node);\n }\n }\n return nodes;\n };\n /** @private */\n CommandHandler.prototype.cloneChild = function (id) {\n var node = this.diagram.nameTable[id];\n return node;\n };\n /** @private */\n CommandHandler.prototype.scaleObject = function (sw, sh, pivot, obj, element, refObject) {\n sw = sw < 0 ? 1 : sw;\n sh = sh < 0 ? 1 : sh;\n var process;\n var oldValues = {\n offsetX: obj.wrapper.offsetX, offsetY: obj.wrapper.offsetY,\n width: obj.wrapper.actualSize.width, height: obj.wrapper.actualSize.height\n };\n if (sw !== 1 || sh !== 1) {\n var width = void 0;\n var height = void 0;\n if (obj instanceof Node) {\n var node = obj;\n var isResize = void 0;\n var bound = void 0;\n if (node.shape.type === 'Bpmn' && node.shape.activity.subProcess.processes\n && node.shape.activity.subProcess.processes.length > 0) {\n bound = this.diagram.bpmnModule.getChildrenBound(node, node.id, this.diagram);\n isResize = node.wrapper.bounds.containsRect(bound);\n }\n width = node.wrapper.actualSize.width * sw;\n height = node.wrapper.actualSize.height * sh;\n if (node.maxWidth !== undefined && node.maxWidth !== 0) {\n width = Math.min(node.maxWidth, width);\n }\n if (node.minWidth !== undefined && node.minWidth !== 0) {\n width = Math.max(node.minWidth, width);\n }\n if (node.maxHeight !== undefined && node.maxHeight !== 0) {\n height = Math.min(node.maxHeight, height);\n }\n if (node.minHeight !== undefined && node.minHeight !== 0) {\n height = Math.max(node.minHeight, height);\n }\n if (isResize) {\n width = Math.max(width, (bound.right - node.wrapper.bounds.x));\n height = Math.max(height, (bound.bottom - node.wrapper.bounds.y));\n }\n sw = width / node.actualSize.width;\n sh = height / node.actualSize.height;\n }\n var matrix = identityMatrix();\n var refWrapper = void 0;\n if (!refObject) {\n refObject = obj;\n }\n refWrapper = refObject.wrapper;\n var x = refWrapper.offsetX - refWrapper.actualSize.width * refWrapper.pivot.x;\n var y = refWrapper.offsetY - refWrapper.actualSize.height * refWrapper.pivot.y;\n var refPoint = { x: x + refWrapper.actualSize.width * pivot.x, y: y + refWrapper.actualSize.height * pivot.y };\n refPoint = rotatePoint(refWrapper.rotateAngle, refWrapper.offsetX, refWrapper.offsetY, refPoint);\n rotateMatrix(matrix, -refWrapper.rotateAngle, refPoint.x, refPoint.y);\n scaleMatrix(matrix, sw, sh, refPoint.x, refPoint.y);\n rotateMatrix(matrix, refWrapper.rotateAngle, refPoint.x, refPoint.y);\n if (obj instanceof Node) {\n var node = obj;\n var left = void 0;\n var top_1;\n var newPosition = transformPointByMatrix(matrix, { x: node.wrapper.offsetX, y: node.wrapper.offsetY });\n var oldleft = node.wrapper.offsetX - node.wrapper.actualSize.width * node.pivot.x;\n var oldtop = node.wrapper.offsetY - node.wrapper.actualSize.height * node.pivot.y;\n if (width > 0) {\n if (node.processId) {\n var parent_2 = this.diagram.nameTable[node.processId];\n if (!parent_2.maxWidth || ((node.margin.left + width) < parent_2.maxWidth)) {\n node.width = width;\n node.offsetX = newPosition.x;\n }\n }\n else {\n node.width = width;\n node.offsetX = newPosition.x;\n }\n }\n if (height > 0) {\n if (node.processId) {\n var parent_3 = this.diagram.nameTable[node.processId];\n if (!parent_3.maxHeight || ((node.margin.top + height) < parent_3.maxHeight)) {\n node.height = height;\n node.offsetY = newPosition.y;\n }\n }\n else {\n node.height = height;\n node.offsetY = newPosition.y;\n }\n }\n left = node.wrapper.offsetX - node.wrapper.actualSize.width * node.pivot.x;\n top_1 = node.wrapper.offsetY - node.wrapper.actualSize.height * node.pivot.y;\n var parent_4 = this.diagram.nameTable[node.processId];\n if (parent_4 && ((node.margin.top + (top_1 - oldtop)) <= 0 ||\n (node.margin.left + (left - oldleft) <= 0))) {\n this.diagram.nodePropertyChange(obj, {}, {\n margin: { top: node.margin.top, left: node.margin.left }\n });\n }\n else {\n this.diagram.nodePropertyChange(obj, {}, {\n width: node.width, height: node.height, offsetX: node.offsetX,\n offsetY: node.offsetY, margin: { top: node.margin.top + (top_1 - oldtop), left: node.margin.left + (left - oldleft) }\n });\n }\n }\n else {\n var connector = obj;\n if (!connector.sourceWrapper || !connector.targetWrapper) {\n connector.sourcePoint = transformPointByMatrix(matrix, connector.sourcePoint);\n connector.targetPoint = transformPointByMatrix(matrix, connector.targetPoint);\n var newProp = { sourcePoint: connector.sourcePoint, targetPoint: connector.targetPoint };\n this.diagram.connectorPropertyChange(connector, {}, newProp);\n }\n }\n var parentNode = this.diagram.nameTable[obj.processId];\n if (parentNode) {\n var parent_5 = parentNode.wrapper.bounds;\n var child = obj.wrapper.bounds;\n var bound = this.diagram.bpmnModule.getChildrenBound(parentNode, obj.id, this.diagram);\n this.diagram.bpmnModule.updateSubProcessess(bound, obj, this.diagram);\n }\n }\n };\n /** @private */\n CommandHandler.prototype.portDrag = function (obj, portElement, tx, ty) {\n var oldValues;\n var changedvalues;\n var port = this.findTarget(portElement, obj);\n var bounds = getBounds(obj.wrapper);\n var index = findPortIndex(obj, port.id);\n var ports = {};\n ports[index] = { offset: { x: port.offset.x, y: port.offset.y } };\n if (port && canDrag(port, this.diagram)) {\n oldValues = { ports: ports };\n port.offset.x += (tx / bounds.width);\n port.offset.y += (ty / bounds.height);\n ports = {};\n ports[index] = { offset: { x: port.offset.x, y: port.offset.y } };\n changedvalues = { ports: ports };\n this.diagram.nodePropertyChange(obj, oldValues, changedvalues);\n this.diagram.updateDiagramObject(obj);\n }\n };\n /** @private */\n CommandHandler.prototype.getSubProcess = function (source) {\n var selector = { nodes: [], connectors: [] };\n var process;\n if (source instanceof Node) {\n process = source.processId;\n }\n else if (source && source.nodes && (source.nodes.length)\n && source.nodes[0].processId) {\n process = source.nodes[0].processId;\n }\n if (process) {\n selector.nodes.push(clone(this.diagram.nameTable[process]));\n return selector;\n }\n return selector;\n };\n CommandHandler.prototype.checkBoundaryConstraints = function (tx, ty, nodeBounds) {\n var pageSettings = this.diagram.pageSettings;\n var boundaryConstraints = this.diagram.pageSettings.boundaryConstraints;\n var scroller = this.diagram.scroller;\n if (boundaryConstraints === 'Page' || boundaryConstraints === 'Diagram') {\n var selectorBounds = !nodeBounds ? this.diagram.selectedItems.wrapper.bounds : undefined;\n var width = boundaryConstraints === 'Page' ? pageSettings.width : scroller.viewPortWidth;\n var height = boundaryConstraints === 'Page' ? pageSettings.height : scroller.viewPortHeight;\n var bounds = nodeBounds;\n var right = (nodeBounds ? bounds.right : selectorBounds.right) + (tx || 0);\n var left = (nodeBounds ? bounds.left : selectorBounds.left) + (tx || 0);\n var top_2 = (nodeBounds ? bounds.top : selectorBounds.top) + (ty || 0);\n var bottom = (nodeBounds ? bounds.bottom : selectorBounds.bottom) + (ty || 0);\n if (right <= width && left >= 0\n && bottom <= height && top_2 >= 0) {\n return true;\n }\n return false;\n }\n return true;\n };\n //interfaces\n /** @private */\n CommandHandler.prototype.dragSelectedObjects = function (tx, ty) {\n var obj = this.diagram.selectedItems;\n if (this.state && !this.state.backup) {\n this.state.backup = {};\n this.state.backup.offsetX = obj.offsetX;\n this.state.backup.offsetY = obj.offsetY;\n }\n if (this.checkBoundaryConstraints(tx, ty)) {\n this.diagram.drag(obj, tx, ty);\n return true;\n }\n return false;\n };\n /** @private */\n CommandHandler.prototype.scaleSelectedItems = function (sx, sy, pivot) {\n var obj = this.diagram.selectedItems;\n if (this.state && !this.state.backup) {\n this.state.backup = {};\n this.state.backup.offsetX = obj.offsetX;\n this.state.backup.offsetY = obj.offsetY;\n this.state.backup.width = obj.width;\n this.state.backup.height = obj.height;\n this.state.backup.pivot = pivot;\n }\n return this.diagram.scale(obj, sx, sy, pivot);\n };\n /** @private */\n CommandHandler.prototype.rotateSelectedItems = function (angle) {\n var obj = this.diagram.selectedItems;\n if (this.state && !this.state.backup) {\n this.state.backup = {};\n this.state.backup.angle = obj.rotateAngle;\n }\n return this.diagram.rotate(obj, angle);\n };\n /** @private */\n CommandHandler.prototype.hasSelection = function () {\n return hasSelection(this.diagram);\n };\n /** @private */\n CommandHandler.prototype.isSelected = function (element) {\n return isSelected(this.diagram, element);\n };\n /**\n * initExpand is used for layout expand and collapse interaction\n */\n CommandHandler.prototype.initExpand = function (args) {\n var node = (args.target || args.source);\n this.expandNode(node, false, this.diagram);\n };\n /** @private */\n CommandHandler.prototype.expandNode = function (node, propChange, diagram) {\n var animation;\n var objects;\n var expand = propChange ? node.isExpanded : !node.isExpanded;\n this.expandCollapse(node, expand, this.diagram);\n node.isExpanded = expand;\n this.diagram.layout.fixedNode = node.id;\n if (!propChange) {\n this.diagram.updateIcon(node);\n }\n if (this.diagram.layoutAnimateModule && this.diagram.layout.enableAnimation) {\n this.diagram.organizationalChartModule.isAnimation = true;\n }\n objects = this.diagram.doLayout();\n if (this.diagram.layoutAnimateModule && this.diagram.layout.enableAnimation) {\n this.layoutAnimateModule.expand(this.diagram.organizationalChartModule.isAnimation, objects, node, this.diagram);\n }\n return objects;\n };\n /**\n * Setinterval and Clear interval for layout animation\n */\n /** @private */\n CommandHandler.prototype.expandCollapse = function (source, visibility, diagram) {\n for (var i = 0; i < source.outEdges.length; i++) {\n var connector = diagram.nameTable[source.outEdges[i]];\n var target = diagram.nameTable[connector.targetID];\n connector.visible = visibility;\n if (target.isExpanded) {\n this.expandCollapse(target, visibility, diagram);\n }\n var oldValues = {\n visible: target.visible\n };\n target.visible = visibility;\n var newValues = {\n visible: target.visible\n };\n diagram.nodePropertyChange(target, oldValues, newValues);\n diagram.connectorPropertyChange(connector, oldValues, newValues);\n }\n };\n /**\n * @private\n */\n CommandHandler.prototype.updateNodeDimension = function (obj, rect) {\n if (obj instanceof Node) {\n obj.offsetX = rect.x + rect.width / 2;\n obj.offsetY = rect.y + rect.height / 2;\n obj.width = rect.width;\n obj.height = rect.height;\n this.diagram.nodePropertyChange(obj, {}, {\n width: rect.width, height: rect.height, offsetX: obj.offsetX,\n offsetY: obj.offsetY\n });\n if (this.diagram.mode !== 'SVG') {\n this.diagram.refreshDiagramLayer();\n }\n }\n };\n /** @private */\n CommandHandler.prototype.drawSelectionRectangle = function (x, y, width, height) {\n this.diagram.drawSelectionRectangle(x, y, width, height);\n };\n /** @private */\n CommandHandler.prototype.startGroupAction = function () {\n this.diagram.startGroupAction();\n };\n /** @private */\n CommandHandler.prototype.endGroupAction = function () {\n this.diagram.endGroupAction();\n };\n /** @private */\n CommandHandler.prototype.removeChildFromBPmn = function (child, newTarget, oldTarget) {\n var obj = this.diagram.nameTable[child.id] || child.nodes[0];\n if (oldTarget) {\n if ((obj) && obj.processId && obj.processId === oldTarget.wrapper.id) {\n var node = clone(obj);\n node.processId = obj.processId;\n this.diagram.startGroupAction();\n var edges = [];\n edges = edges.concat(obj.outEdges, obj.inEdges);\n for (var i = edges.length - 1; i >= 0; i--) {\n var connector = this.diagram.nameTable[edges[i]];\n if (connector) {\n this.diagram.remove(connector);\n }\n }\n var nodeCollection = void 0;\n nodeCollection = (this.diagram.nameTable[obj.processId].shape.activity.subProcess.processes) || [];\n nodeCollection.splice(nodeCollection.indexOf((obj).id), 1);\n this.diagram.bpmnModule.removeChildFromBPMN(this.diagram.nameTable[obj.processId].wrapper, (obj).id);\n this.diagram.nameTable[(obj).id].processId = '';\n obj.offsetX = obj.wrapper.offsetX;\n obj.offsetY = obj.wrapper.offsetY;\n var undoElement = clone(obj);\n var entry = {\n type: 'PositionChanged', redoObject: { nodes: [undoElement] }, undoObject: { nodes: [node] }, category: 'Internal'\n };\n this.addHistoryEntry(entry);\n this.diagram.endGroupAction();\n }\n }\n };\n /** @private */\n CommandHandler.prototype.isDroppable = function (source, targetNodes) {\n var node = this.diagram.nameTable[source.id] || source.nodes[0];\n if (node && node.shape.type === 'Bpmn') {\n if ((node.processId === targetNodes.id) || (node.id === targetNodes.processId) ||\n targetNodes.shape.activity.subProcess.collapsed) {\n return false;\n }\n }\n return true;\n };\n /**\n * @private\n */\n CommandHandler.prototype.renderHighlighter = function (args, connectHighlighter, source) {\n var bounds = new Rect();\n if (args.target instanceof Node || (connectHighlighter && args.source instanceof Node)) {\n var tgt = connectHighlighter ? args.source : args.target;\n var tgtWrap = connectHighlighter ? args.sourceWrapper : args.targetWrapper;\n var target = this.findTarget(tgtWrap, tgt, source);\n var element = void 0;\n if (target instanceof BpmnSubEvent) {\n var portId = target.id;\n var node = args.target;\n var parent_6 = node.wrapper.children[0].children[0].children[2];\n for (var _i = 0, _a = parent_6.children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (child.id === node.id + '_' + portId) {\n element = child.children[0];\n break;\n }\n }\n }\n else {\n element = target instanceof Node ?\n target.wrapper : connectHighlighter ? args.sourceWrapper : args.targetWrapper;\n }\n this.diagram.renderHighlighter(element);\n }\n };\n //additional events\n /** @private */\n CommandHandler.prototype.mouseOver = function (source, target, position) {\n //mouse over\n //returns whether the source can move over the target or not\n return true;\n };\n /**\n * @private\n */\n CommandHandler.prototype.snapPoint = function (startPoint, endPoint, tx, ty) {\n var obj = this.diagram.selectedItems;\n var point;\n var towardsLeft = endPoint.x < startPoint.x;\n var towardsTop = endPoint.y < startPoint.y;\n point = { x: tx, y: ty };\n var snappedPoint = point;\n if (this.snappingModule) {\n snappedPoint = this.diagram.snappingModule.snapPoint(this.diagram, obj, towardsLeft, towardsTop, point, startPoint, endPoint);\n }\n return snappedPoint;\n };\n /**\n * @private\n */\n CommandHandler.prototype.removeSnap = function () {\n if ((this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject) && this.snappingModule) {\n this.snappingModule.removeGuidelines(this.diagram);\n }\n };\n /** @private */\n CommandHandler.prototype.drop = function (source, target, position) {\n //drop\n if (this.diagram.bpmnModule) {\n this.diagram.bpmnModule.dropBPMNchild(target, (source instanceof Node) ? source : source.nodes[0], this.diagram);\n this.diagram.refreshDiagramLayer();\n }\n };\n /** @private */\n CommandHandler.prototype.addHistoryEntry = function (entry) {\n this.diagram.addHistoryEntry(entry);\n };\n /** @private */\n CommandHandler.prototype.align = function (objects, option) {\n if (objects.length > 0) {\n var i = 0;\n var j = 0;\n var bounds = getBounds(objects[0].wrapper);\n var undoObj = { nodes: [], connectors: [] };\n var redoObj = { nodes: [], connectors: [] };\n for (i = 1; i < objects.length; i++) {\n var tx = 0;\n var ty = 0;\n if (option === 'Left') {\n if (objects[i] instanceof Node) {\n tx = bounds.topLeft.x +\n objects[i].width / 2 - objects[i].offsetX;\n }\n else {\n tx = bounds.topLeft.x - objects[i].sourcePoint.x;\n }\n }\n else if (option === 'Right') {\n if (objects[i] instanceof Node) {\n tx = bounds.topRight.x -\n objects[i].width / 2 - objects[i].offsetX;\n }\n else {\n tx = bounds.topRight.x - objects[i].wrapper.bounds.width -\n objects[i].sourcePoint.x;\n }\n }\n else if (option === 'Top') {\n if (objects[i] instanceof Node) {\n ty = bounds.top + objects[i].height / 2 - objects[i].offsetY;\n }\n else {\n ty = bounds.top - objects[i].sourcePoint.y;\n }\n }\n else if (option === 'Bottom') {\n if (objects[i] instanceof Node) {\n ty = bounds.bottom - objects[i].height / 2 - objects[i].offsetY;\n }\n else {\n ty = bounds.bottom - objects[i].sourcePoint.y;\n }\n }\n else if (option === 'Center') {\n if (objects[i] instanceof Node) {\n tx = bounds.center.x - objects[i].offsetX;\n }\n else {\n j = Math.abs(bounds.width -\n objects[i].wrapper.bounds.width);\n tx = bounds.bottomLeft.x - j / 2 - objects[i].sourcePoint.x;\n }\n }\n else if (option === 'Middle') {\n if (objects[i] instanceof Node) {\n ty = bounds.center.y - objects[i].offsetY;\n }\n else {\n ty = bounds.center.y - objects[i].sourcePoint.y;\n }\n }\n undoObj = this.storeObject(undoObj, objects[i]);\n this.drag(objects[i], tx, ty);\n this.diagram.updateSelector();\n redoObj = this.storeObject(redoObj, objects[i]);\n }\n undoObj = clone(undoObj);\n redoObj = clone(redoObj);\n var entry = {\n type: 'Align', category: 'Internal',\n undoObject: cloneObject(undoObj), redoObject: cloneObject(redoObj)\n };\n this.addHistoryEntry(entry);\n }\n };\n /** @private */\n CommandHandler.prototype.distribute = function (objects, option) {\n if (objects.length > 0) {\n var i = 0;\n var j = 0;\n var rect = new Rect();\n var b = [];\n var temp = void 0;\n var right = 0;\n var left = 0;\n var top_3 = 0;\n var bottom = 0;\n var center = 0;\n var middle = 0;\n var btt = 0;\n var sum = 0;\n var undoSelectorObj = { nodes: [], connectors: [] };\n var redoSelectorObj = { nodes: [], connectors: [] };\n objects = sort(objects);\n for (i = 1; i < objects.length; i++) {\n right = right + objects[i].wrapper.bounds.topRight.x - objects[i - 1].wrapper.bounds.topRight.x;\n left = left + objects[i].wrapper.bounds.topLeft.x - objects[i - 1].wrapper.bounds.topLeft.x;\n top_3 = top_3 + objects[i].wrapper.bounds.topRight.y - objects[i - 1].wrapper.bounds.topRight.y;\n bottom = bottom + objects[i].wrapper.bounds.bottomRight.y - objects[i - 1].wrapper.bounds.bottomRight.y;\n center = center + objects[i].wrapper.bounds.center.x - objects[i - 1].wrapper.bounds.center.x;\n middle = middle + objects[i].wrapper.bounds.center.y - objects[i - 1].wrapper.bounds.center.y;\n btt = btt + objects[i].wrapper.bounds.topRight.y - objects[i - 1].wrapper.bounds.bottomRight.y;\n }\n for (i = 1; i < objects.length - 1; i++) {\n var tx = 0;\n var ty = 0;\n var prev = getBounds(objects[i - 1].wrapper);\n var current = getBounds(objects[i].wrapper);\n if (option === 'RightToLeft' || option === 'Center') {\n tx = prev.center.x - current.center.x + (center / (objects.length - 1));\n }\n else if (option === 'Right') {\n tx = prev.topRight.x - current.topRight.x + (right / (objects.length - 1));\n }\n else if (option === 'Left') {\n tx = prev.topLeft.x - current.topLeft.x + (left / (objects.length - 1));\n }\n else if (option === 'Middle') {\n ty = prev.center.y - current.center.y + (middle / (objects.length - 1));\n }\n else if (option === 'Top') {\n ty = prev.topRight.y - current.topRight.y + (top_3 / (objects.length - 1));\n }\n else if (option === 'Bottom') {\n ty = prev.bottomRight.y - current.bottomRight.y + (bottom / (objects.length - 1));\n }\n else if (option === 'BottomToTop') {\n ty = prev.bottomRight.y - current.topRight.y + (btt / (objects.length - 1));\n }\n undoSelectorObj = this.storeObject(undoSelectorObj, objects[i]);\n this.drag(objects[i], tx, ty);\n this.diagram.updateSelector();\n redoSelectorObj = this.storeObject(redoSelectorObj, objects[i]);\n }\n undoSelectorObj = clone(undoSelectorObj);\n redoSelectorObj = clone(redoSelectorObj);\n var entry = {\n type: 'Distribute', category: 'Internal',\n undoObject: cloneObject(undoSelectorObj), redoObject: cloneObject(redoSelectorObj)\n };\n this.addHistoryEntry(entry);\n }\n };\n /** @private */\n CommandHandler.prototype.sameSize = function (objects, option) {\n if (objects.length > 0) {\n var i = 0;\n var pivot = void 0;\n pivot = { x: 0.5, y: 0.5 };\n var bounds = getBounds(objects[0].wrapper);\n var undoObject = { nodes: [], connectors: [] };\n var redoObject = { nodes: [], connectors: [] };\n for (i = 1; i < objects.length; i++) {\n var rect = getBounds(objects[i].wrapper);\n var sw = 1;\n var sh = 1;\n if (option === 'Width') {\n sw = bounds.width / rect.width;\n }\n else if (option === 'Height') {\n sh = bounds.height / rect.height;\n }\n else if (option === 'Size') {\n sw = bounds.width / rect.width;\n sh = bounds.height / rect.height;\n }\n undoObject = this.storeObject(undoObject, objects[i]);\n this.scale(objects[i], sw, sh, pivot);\n redoObject = this.storeObject(redoObject, objects[i]);\n }\n this.diagram.updateSelector();\n undoObject = clone(undoObject);\n redoObject = clone(redoObject);\n var entry = {\n type: 'Sizing', category: 'Internal',\n undoObject: cloneObject(undoObject), redoObject: cloneObject(redoObject)\n };\n this.addHistoryEntry(entry);\n }\n };\n CommandHandler.prototype.storeObject = function (selectorObject, obj) {\n if (obj instanceof Node) {\n selectorObject.nodes.push(clone(obj));\n }\n else {\n selectorObject.connectors.push(clone(obj));\n }\n return selectorObject;\n };\n /** @private */\n CommandHandler.prototype.scroll = function (scrollX, scrollY, focusPoint) {\n var panx = canPanX(this.diagram);\n var pany = canPanY(this.diagram);\n this.diagram.pan((scrollX = panx ? scrollX : 0) * this.diagram.scroller.currentZoom, (scrollY = pany ? scrollY : 0) * this.diagram.scroller.currentZoom, focusPoint);\n };\n /**\n * @private\n */\n CommandHandler.prototype.drawHighlighter = function (element) {\n this.diagram.renderHighlighter(element.wrapper);\n };\n /**\n * @private\n */\n CommandHandler.prototype.removeHighlighter = function () {\n this.diagram.clearHighlighter();\n };\n /** @private */\n CommandHandler.prototype.zoom = function (scale, scrollX, scrollY, focusPoint) {\n this.diagram.scroller.zoom(scale, scrollX * this.diagram.scroller.currentZoom, scrollY * this.diagram.scroller.currentZoom, focusPoint);\n };\n return CommandHandler;\n}());\nexport { CommandHandler };\n","import { Rect } from '../primitives/rect';\nimport { identityMatrix, scaleMatrix, translateMatrix, transformPointByMatrix, multiplyMatrix } from '../primitives/matrix';\nimport { updateRuler } from '../ruler/ruler';\nimport { canZoom, canPan } from './../utility/constraints-util';\n/**\n */\nvar DiagramScroller = /** @class */ (function () {\n function DiagramScroller(diagram) {\n /** @private */\n this.transform = { tx: 0, ty: 0, scale: 1 };\n this.vPortWidth = 0;\n this.vPortHeight = 0;\n this.currentZoomFActor = 1;\n this.hOffset = 0;\n this.vOffset = 0;\n this.scrolled = false;\n this.hScrollSize = 0;\n this.vScrollSize = 0;\n this.diagram = diagram;\n this.objects = [];\n }\n Object.defineProperty(DiagramScroller.prototype, \"viewPortHeight\", {\n /** @private */\n get: function () {\n return this.vPortHeight;\n },\n /** @private */\n set: function (offset) {\n this.vPortHeight = offset;\n this.diagram.scrollSettings.viewPortHeight = offset;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DiagramScroller.prototype, \"currentZoom\", {\n /** @private */\n get: function () {\n return this.currentZoomFActor;\n },\n /** @private */\n set: function (offset) {\n this.currentZoomFActor = offset;\n this.diagram.scrollSettings.currentZoom = offset;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DiagramScroller.prototype, \"viewPortWidth\", {\n /** @private */\n get: function () {\n return this.vPortWidth;\n },\n /** @private */\n set: function (offset) {\n this.vPortWidth = offset;\n this.diagram.scrollSettings.viewPortWidth = offset;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DiagramScroller.prototype, \"horizontalOffset\", {\n /** @private */\n get: function () {\n return this.hOffset;\n },\n /** @private */\n set: function (offset) {\n this.hOffset = offset;\n if (Math.abs(this.hOffset - this.diagram.scrollSettings.horizontalOffset) > 1) {\n this.scrolled = true;\n }\n this.diagram.scrollSettings.horizontalOffset = offset;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DiagramScroller.prototype, \"verticalOffset\", {\n /** @private */\n get: function () {\n return this.vOffset;\n },\n /** @private */\n set: function (offset) {\n this.vOffset = offset;\n if (Math.abs(this.vOffset - this.diagram.scrollSettings.verticalOffset) > 1) {\n this.scrolled = true;\n }\n this.diagram.scrollSettings.verticalOffset = offset;\n },\n enumerable: true,\n configurable: true\n });\n /** @private */\n DiagramScroller.prototype.updateScrollOffsets = function (hOffset, vOffset) {\n var offsetX = 0;\n var offsetY = 0;\n var pageBounds = this.getPageBounds();\n pageBounds.x *= this.currentZoom;\n pageBounds.y *= this.currentZoom;\n pageBounds.width *= this.currentZoom;\n pageBounds.height *= this.currentZoom;\n offsetX = Math.max(0, hOffset - pageBounds.left);\n offsetY = Math.max(0, vOffset - pageBounds.top);\n if (hOffset !== undefined && vOffset !== undefined) {\n this.horizontalOffset = offsetX;\n this.verticalOffset = offsetY;\n this.diagram.setOffset(offsetX, offsetY);\n }\n else {\n this.diagram.setOffset(-this.horizontalOffset - pageBounds.x, -this.verticalOffset - pageBounds.y);\n }\n this.transform = {\n tx: Math.max(this.horizontalOffset, -pageBounds.left) / this.currentZoom, ty: Math.max(this.verticalOffset, -pageBounds.top) / this.currentZoom,\n scale: this.currentZoom\n };\n };\n /** @private */\n DiagramScroller.prototype.setScrollOffset = function (hOffset, vOffset) {\n this.scrolled = false;\n var pageBounds = this.getPageBounds();\n pageBounds.x *= this.currentZoom;\n pageBounds.y *= this.currentZoom;\n pageBounds.width *= this.currentZoom;\n pageBounds.height *= this.currentZoom;\n var x = -pageBounds.left;\n var y = -pageBounds.top;\n var set = false;\n var viewWidth = this.viewPortWidth * this.currentZoom;\n var viewHeight = this.viewPortHeight * this.currentZoom;\n var newX = x - hOffset;\n if (newX !== this.horizontalOffset) {\n if (x < this.horizontalOffset) {\n if (this.horizontalOffset > newX) {\n this.horizontalOffset -= hOffset;\n }\n else {\n this.horizontalOffset = newX;\n }\n set = true;\n }\n var right = Math.max(pageBounds.right + this.vScrollSize, viewWidth);\n if (!set && right < -newX + this.viewPortWidth) {\n var actualRight = -newX + viewWidth - this.vScrollSize;\n var currentRight = -this.horizontalOffset + viewWidth - this.vScrollSize;\n if (actualRight < currentRight) {\n //define\n this.horizontalOffset = newX;\n }\n else {\n if (actualRight - pageBounds.right > actualRight - currentRight) {\n this.horizontalOffset = newX;\n }\n else {\n this.horizontalOffset = -(pageBounds.right + this.vScrollSize - viewWidth);\n }\n }\n set = true;\n }\n if (!set) {\n this.horizontalOffset = x - hOffset;\n }\n }\n set = false;\n //vertical offset\n var newY = y - vOffset;\n if (newY !== this.verticalOffset) {\n if (y < this.verticalOffset) {\n if (this.verticalOffset > newY) {\n this.verticalOffset -= vOffset;\n }\n else {\n this.verticalOffset = newY;\n }\n set = true;\n }\n var bottom = Math.max(pageBounds.bottom + this.hScrollSize, viewHeight);\n if (!set && bottom < -newY + viewHeight) {\n var actualBottom = -newY + viewHeight - this.hScrollSize;\n var currentBottom = -this.verticalOffset + viewHeight - this.hScrollSize;\n if (actualBottom < currentBottom) {\n //define\n this.verticalOffset = newY;\n }\n else {\n if (actualBottom - pageBounds.bottom > actualBottom - currentBottom) {\n this.verticalOffset = newY;\n }\n else {\n this.verticalOffset = -(pageBounds.bottom + this.hScrollSize - viewHeight);\n }\n }\n set = true;\n }\n if (!set) {\n this.verticalOffset = y - vOffset;\n }\n }\n this.transform = {\n tx: Math.max(this.horizontalOffset, -pageBounds.left) / this.currentZoom, ty: Math.max(this.verticalOffset, -pageBounds.top) / this.currentZoom,\n scale: this.currentZoom\n };\n this.setSize();\n if (this.scrolled) {\n this.diagram.endEdit();\n }\n };\n /** @private */\n DiagramScroller.prototype.setSize = function () {\n var pageBounds = this.getPageBounds();\n pageBounds.x *= this.currentZoom;\n pageBounds.y *= this.currentZoom;\n pageBounds.width *= this.currentZoom;\n pageBounds.height *= this.currentZoom;\n var x = Math.min(pageBounds.x, -this.horizontalOffset);\n var y = Math.min(pageBounds.y, -this.verticalOffset);\n var difX = -this.horizontalOffset + this.viewPortWidth - pageBounds.right;\n var difY = -this.verticalOffset + this.viewPortHeight - pageBounds.bottom;\n var hScrollSize = this.scrollerWidth;\n var vScrollSize = this.scrollerWidth;\n if (-this.verticalOffset <= pageBounds.y && -this.verticalOffset + this.viewPortHeight >= pageBounds.bottom) {\n vScrollSize = 0;\n }\n if (-this.horizontalOffset <= pageBounds.x && -this.horizontalOffset + this.viewPortWidth >= pageBounds.right) {\n hScrollSize = 0;\n }\n this.hScrollSize = hScrollSize;\n this.vScrollSize = vScrollSize;\n this.diagramWidth = Math.max(pageBounds.right, -this.horizontalOffset + this.viewPortWidth - vScrollSize) - x;\n this.diagramHeight = Math.max(pageBounds.bottom, -this.verticalOffset + this.viewPortHeight - hScrollSize) - y;\n this.diagram.setSize(this.diagramWidth, this.diagramHeight);\n this.diagram.element.style.overflow = 'hidden';\n };\n /** @private */\n DiagramScroller.prototype.setViewPortSize = function (width, height) {\n this.viewPortWidth = width;\n this.viewPortHeight = height;\n };\n /**\n * To get page pageBounds\n * @private\n */\n DiagramScroller.prototype.getPageBounds = function (boundingRect, region) {\n var rect = new Rect();\n var temp = 0;\n if (region !== 'Content' && this.diagram.pageSettings.width !== null && this.diagram.pageSettings.height !== null) {\n var width = this.diagram.pageSettings.width;\n var height = this.diagram.pageSettings.height;\n var negwidth = 0;\n var negheight = 0;\n if (this.diagram.pageSettings.multiplePage) {\n rect = this.diagram.spatialSearch.getPageBounds(0, 0);\n if (rect.right > width) {\n var x = Math.ceil(rect.right / width);\n width = width * x;\n }\n if (rect.bottom > height) {\n var x = Math.ceil(rect.bottom / height);\n height = height * x;\n }\n if (rect.left < 0 && Math.abs(rect.left) > negwidth) {\n var x = Math.ceil(Math.abs(rect.left) / this.diagram.pageSettings.width);\n negwidth = this.diagram.pageSettings.width * x;\n }\n if (rect.top < 0 && Math.abs(rect.top) > negheight) {\n var x = Math.ceil(Math.abs(rect.top) / this.diagram.pageSettings.height);\n negheight = this.diagram.pageSettings.height * x;\n }\n }\n return new Rect((-negwidth), (-negheight), width + negwidth, height + negheight);\n }\n else {\n var origin = boundingRect ? undefined : 0;\n return this.diagram.spatialSearch.getPageBounds(origin, origin);\n }\n };\n /**\n * To get page break when PageBreak is set as true\n * @private\n */\n DiagramScroller.prototype.getPageBreak = function (pageBounds) {\n var i = 0;\n var j = 0;\n var v = -1;\n var collection = [];\n var x1 = 0;\n var x2 = 0;\n var y1 = 0;\n var y2 = 0;\n var left = this.diagram.pageSettings.margin.left;\n var right = this.diagram.pageSettings.margin.right;\n var top = this.diagram.pageSettings.margin.top;\n var bottom = this.diagram.pageSettings.margin.bottom;\n var widthCount = 1;\n var heightCount = 1;\n var segment = { x1: x1, y1: y1, x2: x2, y2: y2 };\n while (pageBounds.width > i) {\n i = i + (this.diagram.pageSettings.width ? this.diagram.pageSettings.width : pageBounds.width);\n if (i === this.diagram.pageSettings.width) {\n segment = {\n x1: pageBounds.left + left, y1: pageBounds.top + top,\n x2: pageBounds.left + left, y2: pageBounds.bottom - bottom\n };\n collection[++v] = segment;\n }\n if (i < pageBounds.width) {\n x1 = pageBounds.topLeft.x + this.diagram.pageSettings.width * widthCount;\n y1 = pageBounds.topLeft.y + top;\n x2 = pageBounds.bottomLeft.x + this.diagram.pageSettings.width * widthCount;\n y2 = pageBounds.bottomLeft.y - bottom;\n segment = { x1: x1, y1: y1, x2: x2, y2: y2 };\n collection[++v] = segment;\n widthCount++;\n }\n if (pageBounds.width === i) {\n segment = {\n x1: pageBounds.right - right, y1: pageBounds.top + top,\n x2: pageBounds.right - right, y2: pageBounds.bottom - bottom\n };\n collection[++v] = segment;\n }\n }\n while (pageBounds.height > j) {\n j = j + (this.diagram.pageSettings.height ? this.diagram.pageSettings.height : pageBounds.height);\n if (j === this.diagram.pageSettings.height) {\n segment = {\n x1: pageBounds.left + left, y1: pageBounds.top + top,\n x2: pageBounds.right - right, y2: pageBounds.top + top\n };\n collection[++v] = segment;\n }\n if (j < pageBounds.height) {\n x1 = pageBounds.topLeft.x + left;\n y1 = pageBounds.topLeft.y + this.diagram.pageSettings.height * heightCount;\n x2 = pageBounds.topRight.x - right;\n y2 = pageBounds.topRight.y + this.diagram.pageSettings.height * heightCount;\n segment = { x1: x1, y1: y1, x2: x2, y2: y2 };\n collection[++v] = segment;\n heightCount++;\n }\n if (pageBounds.height === j) {\n segment = {\n x1: pageBounds.left + left, y1: pageBounds.bottom - bottom,\n x2: pageBounds.right - right, y2: pageBounds.bottom - bottom\n };\n collection[++v] = segment;\n }\n }\n return collection;\n };\n /** @private */\n DiagramScroller.prototype.zoom = function (factor, deltaX, deltaY, focusPoint) {\n if (canZoom(this.diagram) && factor !== 1 || (canPan(this.diagram) && factor === 1)) {\n var matrix = identityMatrix();\n scaleMatrix(matrix, this.currentZoom, this.currentZoom);\n translateMatrix(matrix, this.horizontalOffset, this.verticalOffset);\n focusPoint = focusPoint || { x: this.viewPortWidth / 2, y: this.viewPortHeight / 2 };\n focusPoint = transformPointByMatrix(matrix, focusPoint);\n if ((this.currentZoom * factor) >= this.diagram.scrollSettings.minZoom &&\n (this.currentZoom * factor) <= this.diagram.scrollSettings.maxZoom) {\n this.currentZoom *= factor;\n var pageBounds = this.getPageBounds();\n pageBounds.x *= this.currentZoom;\n pageBounds.y *= this.currentZoom;\n //target Matrix\n var targetMatrix = identityMatrix();\n scaleMatrix(targetMatrix, factor, factor, focusPoint.x, focusPoint.y);\n translateMatrix(targetMatrix, deltaX || 0, deltaY || 0);\n multiplyMatrix(matrix, targetMatrix);\n var newOffset = transformPointByMatrix(matrix, { x: 0, y: 0 });\n if (factor === 1) {\n newOffset = this.applyScrollLimit(newOffset.x, newOffset.y);\n }\n this.transform = {\n tx: Math.max(newOffset.x, -pageBounds.left) / this.currentZoom,\n ty: Math.max(newOffset.y, -pageBounds.top) / this.currentZoom,\n scale: this.currentZoom\n };\n this.horizontalOffset = newOffset.x;\n this.verticalOffset = newOffset.y;\n this.setSize();\n if (this.diagram.mode !== 'SVG') {\n this.diagram.refreshDiagramLayer();\n }\n this.diagram.setOffset(-this.horizontalOffset - pageBounds.x, -this.verticalOffset - pageBounds.y);\n updateRuler(this.diagram);\n }\n }\n };\n /** @private */\n DiagramScroller.prototype.fitToPage = function (options) {\n options = options || {};\n var mode = options.mode;\n var region = options.region;\n var margin = options.margin || {};\n var canZoomIn = options.canZoomIn;\n var customBounds = options.customBounds;\n margin.bottom = margin.bottom || 25;\n margin.top = margin.top || 25;\n margin.left = margin.left || 25;\n margin.right = margin.right || 25;\n var bounds = customBounds;\n var factor;\n var deltaX = -this.horizontalOffset;\n var deltaY = -this.verticalOffset;\n region = region ? region : 'PageSettings';\n //fit mode\n if ((region === 'PageSettings' && this.diagram.pageSettings.width && this.diagram.pageSettings.height)\n || (this.diagram.nodes.length > 0 || this.diagram.connectors.length > 0)) {\n mode = mode ? mode : 'Page';\n if (region !== 'CustomBounds') {\n bounds = this.getPageBounds(true, region);\n }\n var scale = { x: 0, y: 0 };\n scale.x = (this.viewPortWidth - (margin.left + margin.right)) / (bounds.width);\n scale.y = (this.viewPortHeight - (margin.top + margin.bottom)) / (bounds.height);\n if (!canZoomIn && ((bounds.width - this.horizontalOffset) < this.viewPortWidth) &&\n (bounds.height - this.verticalOffset) < this.viewPortHeight) {\n scale.x = Math.min(1, scale.x);\n scale.y = Math.min(1, scale.y);\n }\n var zoomFactor = void 0;\n var centerX = void 0;\n var centerY = void 0;\n switch (mode) {\n case 'Width':\n zoomFactor = scale.x;\n factor = zoomFactor / this.currentZoom;\n centerX = (this.viewPortWidth - (bounds.width) * zoomFactor) / 2 - bounds.x * zoomFactor;\n deltaX += centerX + (margin.left - margin.right) / 2 * zoomFactor;\n deltaY -= -this.verticalOffset * factor;\n deltaY = region !== 'CustomBounds' ? deltaY : deltaY - this.verticalOffset * factor;\n break;\n case 'Height':\n zoomFactor = scale.y;\n factor = (zoomFactor / this.currentZoom);\n centerX = ((this.viewPortWidth - (bounds.width) * zoomFactor) / 2) - bounds.x * zoomFactor;\n centerY = ((this.viewPortHeight - (bounds.height) * zoomFactor) / 2) - bounds.y * zoomFactor;\n deltaX += centerX + (margin.left - margin.right) / 2 * zoomFactor;\n deltaY += centerY + (margin.top - margin.bottom) / 2 * zoomFactor;\n break;\n case 'Page':\n zoomFactor = Math.min(scale.x, scale.y);\n factor = (zoomFactor / this.currentZoom);\n centerX = (this.viewPortWidth - (bounds.width) * zoomFactor) / 2 - bounds.x * zoomFactor;\n centerY = (this.viewPortHeight - (bounds.height) * zoomFactor) / 2 - bounds.y * zoomFactor;\n deltaX += centerX + (margin.left - margin.right) / 2 * zoomFactor;\n deltaY += centerY + (margin.top - margin.bottom) / 2 * zoomFactor;\n break;\n }\n this.zoom(factor, deltaX, deltaY, { x: 0, y: 0 });\n }\n else {\n factor = 1 / this.currentZoom;\n this.zoom(factor, deltaX, deltaY, { x: 0, y: 0 });\n }\n };\n /** @private */\n DiagramScroller.prototype.bringIntoView = function (rect) {\n var x = 0;\n var y = 0;\n var scale = this.currentZoom;\n var bounds = rect;\n var hoffset = -this.horizontalOffset;\n var voffset = -this.verticalOffset;\n bounds = new Rect(bounds.x * scale, bounds.y * scale, bounds.width * scale, bounds.height * scale);\n var view = new Rect(hoffset, voffset, this.viewPortWidth, this.viewPortHeight);\n if (!(view.containsRect(bounds))) {\n if (bounds.right > (-hoffset + this.viewPortWidth)) {\n x = bounds.right - this.viewPortWidth;\n }\n if (bounds.x < -hoffset) {\n x = bounds.x;\n }\n if (bounds.bottom > (-voffset + this.viewPortHeight)) {\n y = bounds.bottom - this.viewPortHeight;\n }\n if (bounds.y < -voffset) {\n y = bounds.y;\n }\n this.zoom(1, -this.horizontalOffset - x, -this.verticalOffset - y, null);\n }\n };\n /** @private */\n DiagramScroller.prototype.bringToCenter = function (bounds) {\n var scale = this.currentZoom;\n var actualbounds = new Rect(bounds.x * scale, bounds.y * scale, bounds.width * scale, bounds.height * scale);\n var hoffset = actualbounds.x + actualbounds.width / 2 - this.viewPortWidth / 2;\n var voffset = actualbounds.y + actualbounds.height / 2 - this.viewPortHeight / 2;\n this.zoom(1, -this.horizontalOffset - hoffset, -this.verticalOffset - voffset, null);\n };\n DiagramScroller.prototype.applyScrollLimit = function (hOffset, vOffset) {\n if (this.diagram.scrollSettings.scrollLimit !== 'Infinity') {\n var bounds = void 0;\n if (this.diagram.scrollSettings.scrollLimit === 'Limited') {\n bounds = this.diagram.scrollSettings.scrollableArea;\n }\n bounds = bounds || this.getPageBounds(true);\n bounds.x *= this.currentZoom;\n bounds.y *= this.currentZoom;\n bounds.width *= this.currentZoom;\n bounds.height *= this.currentZoom;\n hOffset *= -1;\n vOffset *= -1;\n var allowedRight = Math.max(bounds.right, this.viewPortWidth);\n if (!(hOffset <= bounds.x && (hOffset + this.viewPortWidth >= bounds.right ||\n hOffset >= bounds.right - this.viewPortWidth)\n || hOffset >= bounds.x && (hOffset + this.viewPortWidth <= allowedRight))) {\n //not allowed case\n if (hOffset >= bounds.x) {\n hOffset = Math.max(bounds.x, Math.min(hOffset, hOffset - (hOffset + this.viewPortWidth - this.vScrollSize - allowedRight)));\n }\n else {\n var allowed = bounds.right - this.viewPortWidth;\n hOffset = Math.min(allowed, bounds.x);\n }\n }\n var allowedBottom = Math.max(bounds.bottom, this.viewPortHeight);\n if (!(vOffset <= bounds.y && vOffset + this.viewPortHeight >= bounds.bottom\n || vOffset >= bounds.y && vOffset + this.viewPortHeight <= allowedBottom)) {\n //not allowed case\n if (vOffset >= bounds.y) {\n vOffset = Math.max(bounds.y, Math.min(vOffset, vOffset - (vOffset + this.viewPortHeight - this.hScrollSize - allowedBottom)));\n }\n else {\n var allowed = bounds.bottom - this.viewPortHeight;\n vOffset = Math.min(bounds.y, allowed);\n }\n }\n hOffset *= -1;\n vOffset *= -1;\n }\n return { x: hOffset, y: vOffset };\n };\n return DiagramScroller;\n}());\nexport { DiagramScroller };\n","/**\n * Quad helps to maintain a set of objects that are contained within the particular region\n */\n/** @private */\nvar Quad = /** @class */ (function () {\n /** @private */\n function Quad(left, top, width, height, spatialSearching) {\n this.objects = [];\n this.left = left;\n this.top = top;\n this.width = width;\n this.height = height;\n this.spatialSearch = spatialSearching;\n }\n /** @private */\n Quad.prototype.findQuads = function (currentViewPort, quads) {\n if (this.first != null && this.first.isIntersect(currentViewPort)) {\n this.first.findQuads(currentViewPort, quads);\n }\n if (this.second != null && this.second.isIntersect(currentViewPort)) {\n this.second.findQuads(currentViewPort, quads);\n }\n if (this.third != null && this.third.isIntersect(currentViewPort)) {\n this.third.findQuads(currentViewPort, quads);\n }\n if (this.fourth != null && this.fourth.isIntersect(currentViewPort)) {\n this.fourth.findQuads(currentViewPort, quads);\n }\n if (this.objects.length > 0) {\n quads.push(this);\n }\n };\n Quad.prototype.isIntersect = function (t) {\n if (this.left + this.width < t.left || this.top + this.height < t.top || this.left > t.right || this.top > t.bottom) {\n return false;\n }\n return true;\n };\n /** @private */\n Quad.prototype.selectQuad = function () {\n var target = null;\n var current = this;\n var quadSet;\n while (current != null) {\n quadSet = current.getQuad(target);\n current = quadSet.source;\n target = quadSet.target || target;\n }\n return target;\n };\n Quad.prototype.getQuad = function (target) {\n target = null;\n var halfWidth = this.width / 2;\n var halfHeight = this.height / 2;\n if (halfWidth >= 1000 && halfHeight >= 1000) {\n var xCenter = this.left + halfWidth;\n var yCenter = this.top + halfHeight;\n if (this.spatialSearch.childRight <= xCenter) {\n if (this.spatialSearch.childBottom <= yCenter) {\n if (!this.first) {\n var newQuad = new Quad(this.left, this.top, halfWidth, halfHeight, this.spatialSearch);\n newQuad.parent = this;\n this.first = newQuad;\n }\n return { source: this.first };\n }\n if (this.spatialSearch.childTop >= yCenter) {\n if (!this.third) {\n var newQuad = new Quad(this.left, yCenter, halfWidth, halfHeight, this.spatialSearch);\n newQuad.parent = this;\n this.third = newQuad;\n }\n return { source: this.third };\n }\n }\n else if (this.spatialSearch.childLeft >= xCenter) {\n if (this.spatialSearch.childBottom <= yCenter) {\n if (!this.second) {\n var newQuad = new Quad(xCenter, this.top, halfWidth, halfHeight, this.spatialSearch);\n newQuad.parent = this;\n this.second = newQuad;\n }\n return { source: this.second };\n }\n if (this.spatialSearch.childTop >= yCenter) {\n if (!this.fourth) {\n var newQuad = new Quad(xCenter, yCenter, halfWidth, halfHeight, this.spatialSearch);\n newQuad.parent = this;\n this.fourth = newQuad;\n }\n return { source: this.fourth };\n }\n }\n }\n target = this;\n this.objects.push(this.spatialSearch.childNode);\n return { target: this };\n };\n /** @private */\n Quad.prototype.isContained = function () {\n if (this.spatialSearch.childLeft >= this.left && this.spatialSearch.childRight <= this.left + this.width &&\n this.spatialSearch.childTop >= this.top && this.spatialSearch.childBottom <= this.top + this.height) {\n return true;\n }\n return false;\n };\n /** @private */\n Quad.prototype.addIntoAQuad = function (node) {\n var quadAddition = {};\n this.spatialSearch.setCurrentNode(node);\n var quad = null;\n while (!quadAddition.isAdded) {\n quadAddition = this.spatialSearch.parentQuad.add(quad);\n quad = quadAddition.quad;\n }\n return quad;\n };\n Quad.prototype.add = function (quad) {\n quad = null;\n if (this.isContained()) {\n quad = this.selectQuad();\n return { isAdded: true, quad: quad };\n }\n else {\n var newParent = void 0;\n var isempty = this.objects.length === 0 && !this.first && !this.second && !this.third &&\n !this.fourth;\n var newWidth = this.width * 2;\n var newHeight = this.height * 2;\n if (this.spatialSearch.childLeft < this.left) {\n if (this.spatialSearch.childTop < this.top) {\n newParent = new Quad(this.left - this.width, this.top - this.height, newWidth, newHeight, this.spatialSearch);\n if (!isempty) {\n newParent.fourth = this;\n }\n }\n else {\n newParent = new Quad(this.left - this.width, this.top, newWidth, newHeight, this.spatialSearch);\n if (!isempty) {\n newParent.second = this;\n }\n }\n }\n else if (this.spatialSearch.childTop < this.top) {\n newParent = new Quad(this.left, this.top - this.height, newWidth, newHeight, this.spatialSearch);\n if (!isempty) {\n newParent.third = this;\n }\n }\n else {\n newParent = new Quad(this.left, this.top, newWidth, newHeight, this.spatialSearch);\n if (!isempty) {\n newParent.first = this;\n }\n }\n this.parent = newParent;\n this.spatialSearch.parentQuad = newParent;\n return { isAdded: false, quad: quad };\n //newParent.AddIntoaQuad(node);\n }\n };\n return Quad;\n}());\nexport { Quad };\n","import { Rect } from '../../primitives/rect';\nimport { Quad } from './quad';\n/**\n * Spatial search module helps to effectively find the objects over diagram\n */\nvar SpatialSearch = /** @class */ (function () {\n /** @private */\n function SpatialSearch(objectTable) {\n this.quadSize = 500;\n this.objectTable = objectTable;\n this.parentQuad = new Quad(0, 0, this.quadSize * 2, this.quadSize * 2, this);\n this.pageLeft = Number.MAX_VALUE;\n this.pageRight = -Number.MAX_VALUE;\n this.pageTop = Number.MAX_VALUE;\n this.pageBottom = -Number.MAX_VALUE;\n this.quadTable = {};\n }\n /** @private */\n SpatialSearch.prototype.removeFromAQuad = function (node) {\n if (this.quadTable[node.id]) {\n var quad = this.quadTable[node.id];\n var index = quad.objects.indexOf(node);\n if (index !== -1) {\n quad.objects.splice(index, 1);\n this.update(quad);\n delete this.quadTable[node.id];\n }\n }\n };\n SpatialSearch.prototype.update = function (quad) {\n if (quad.parent && quad.objects.length === 0 && quad.first && quad.second && quad.third && quad.fourth) {\n var parent_1 = quad.parent;\n if (parent_1.first === quad) {\n parent_1.first = null;\n }\n else if (parent_1.second === quad) {\n parent_1.second = null;\n }\n else if (parent_1.third === quad) {\n parent_1.third = null;\n }\n else if (parent_1.fourth === quad) {\n parent_1.fourth = null;\n }\n this.update(quad.parent);\n }\n else {\n if (quad === this.parentQuad && !quad.first && !quad.second && !quad.third && !quad.fourth) {\n quad.left = 0;\n quad.width = 1000;\n quad.top = 0;\n quad.height = 1000;\n }\n return;\n }\n };\n SpatialSearch.prototype.addIntoAQuad = function (node) {\n var quad = this.parentQuad.addIntoAQuad(node);\n this.quadTable[node.id] = quad;\n };\n SpatialSearch.prototype.updateQuad = function (node) {\n this.setCurrentNode(node);\n var nodBounds = node.outerBounds;\n if (!(!isNaN(nodBounds.x) && !isNaN(nodBounds.y) &&\n !isNaN(nodBounds.width) && !isNaN(nodBounds.height))) {\n return false;\n }\n //nodBounds = new Rect(nodBounds.X.Valid(), nodBounds.Y.Valid(), nodBounds.Width.Valid(), nodBounds.Height.Valid());\n if (this.quadTable[node.id]) {\n var quad = this.quadTable[node.id];\n if (!quad.isContained()) {\n this.removeFromAQuad(node);\n this.addIntoAQuad(node);\n }\n }\n else {\n this.addIntoAQuad(node);\n }\n if (this.isWithinPageBounds(nodBounds) &&\n this.leftElement !== node &&\n this.topElement !== node &&\n this.rightElement !== node &&\n this.bottomElement !== node) {\n //contained - no change\n }\n else {\n var modified = false;\n if (this.pageLeft !== this.childLeft || node !== this.leftElement) {\n if (this.pageLeft >= this.childLeft) {\n this.pageLeft = this.childLeft;\n this.leftElement = node;\n modified = true;\n }\n else if (node === this.leftElement) {\n this.pageLeft = Number.MAX_VALUE;\n this.findLeft(this.parentQuad);\n modified = true;\n }\n }\n if (this.pageTop !== this.childTop || node !== this.topElement) {\n if (this.pageTop >= this.childTop) {\n this.pageTop = this.childTop;\n this.topElement = node;\n modified = true;\n }\n else if (node === this.topElement) {\n this.pageTop = Number.MAX_VALUE;\n this.findTop(this.parentQuad);\n modified = true;\n }\n }\n if (this.pageBottom !== this.childBottom || node !== this.bottomElement) {\n if (this.pageBottom <= this.childBottom) {\n modified = true;\n this.pageBottom = this.childBottom;\n this.bottomElement = node;\n }\n else if (node === this.bottomElement) {\n this.pageBottom = -Number.MAX_VALUE;\n this.findBottom(this.parentQuad);\n modified = true;\n }\n }\n if (this.pageRight !== this.childRight || node !== this.rightElement) {\n if (this.pageRight <= this.childRight) {\n this.pageRight = this.childRight;\n this.rightElement = node;\n modified = true;\n }\n else if (node === this.rightElement) {\n this.pageRight = -Number.MAX_VALUE;\n this.findRight(this.parentQuad);\n modified = true;\n }\n }\n return modified;\n }\n this.setCurrentNode(null);\n return false;\n };\n SpatialSearch.prototype.isWithinPageBounds = function (node) {\n if (node.left >= this.pageLeft && node.right <= this.pageRight && node.top >= this.pageTop\n && node.bottom <= this.pageBottom) {\n return true;\n }\n else {\n return false;\n }\n };\n /** @private */\n SpatialSearch.prototype.findQuads = function (region) {\n var quads = [];\n this.parentQuad.findQuads(region, quads);\n return quads;\n };\n /** @private */\n SpatialSearch.prototype.findObjects = function (region) {\n var quads = this.findQuads(region);\n var objects = [];\n for (var _i = 0, quads_1 = quads; _i < quads_1.length; _i++) {\n var quad = quads_1[_i];\n for (var _a = 0, _b = quad.objects; _a < _b.length; _a++) {\n var obj = _b[_a];\n if (obj.outerBounds.intersects(region)) {\n objects.push(this.objectTable[obj.id]);\n }\n }\n }\n return objects;\n };\n /** @private */\n SpatialSearch.prototype.updateBounds = function (node) {\n var modified = false;\n if (node === this.topElement) {\n this.pageTop = Number.MAX_VALUE;\n this.topElement = null;\n this.findTop(this.parentQuad);\n modified = true;\n }\n if (node === this.leftElement) {\n this.pageLeft = Number.MAX_VALUE;\n this.leftElement = null;\n this.findLeft(this.parentQuad);\n modified = true;\n }\n if (node === this.rightElement) {\n this.pageRight = -Number.MAX_VALUE;\n this.rightElement = null;\n this.findRight(this.parentQuad);\n modified = true;\n }\n if (node === this.bottomElement) {\n this.pageBottom = -Number.MAX_VALUE;\n this.bottomElement = null;\n this.findBottom(this.parentQuad);\n modified = true;\n }\n return modified;\n };\n SpatialSearch.prototype.findBottom = function (quad) {\n //if (quad.Quads.Count === 4)\n {\n if (quad.third || quad.fourth) {\n if (quad.third) {\n this.findBottom(quad.third);\n }\n if (quad.fourth) {\n this.findBottom(quad.fourth);\n }\n }\n else {\n if (quad.second) {\n this.findBottom(quad.second);\n }\n if (quad.first) {\n this.findBottom(quad.first);\n }\n }\n }\n for (var _i = 0, _a = quad.objects; _i < _a.length; _i++) {\n var node = _a[_i];\n if (this.pageBottom <= node.outerBounds.bottom) {\n this.pageBottom = node.outerBounds.bottom;\n this.bottomElement = node;\n }\n }\n };\n SpatialSearch.prototype.findRight = function (quad) {\n //if (quad.Quads.Count === 4)\n {\n if (quad.second || quad.fourth) {\n if (quad.second) {\n this.findRight(quad.second);\n }\n if (quad.fourth) {\n this.findRight(quad.fourth);\n }\n }\n else {\n if (quad.first) {\n this.findRight(quad.first);\n }\n if (quad.third) {\n this.findRight(quad.third);\n }\n }\n }\n for (var _i = 0, _a = quad.objects; _i < _a.length; _i++) {\n var node = _a[_i];\n if (this.pageRight <= node.outerBounds.right) {\n this.pageRight = node.outerBounds.right;\n this.rightElement = node;\n }\n }\n };\n SpatialSearch.prototype.findLeft = function (quad) {\n //if (quad.Quads.Count === 4)\n {\n if (quad.first || quad.third) {\n if (quad.first) {\n this.findLeft(quad.first);\n }\n if (quad.third) {\n this.findLeft(quad.third);\n }\n }\n else {\n if (quad.second) {\n this.findLeft(quad.second);\n }\n if (quad.fourth) {\n this.findLeft(quad.fourth);\n }\n }\n }\n for (var _i = 0, _a = quad.objects; _i < _a.length; _i++) {\n var node = _a[_i];\n if (this.pageLeft >= node.outerBounds.left) {\n this.pageLeft = node.outerBounds.left;\n this.leftElement = node;\n }\n }\n };\n SpatialSearch.prototype.findTop = function (quad) {\n //if (quad.Quads.Count === 4)\n {\n if (quad.first || quad.second) {\n if (quad.first) {\n this.findTop(quad.first);\n }\n if (quad.second) {\n this.findTop(quad.second);\n }\n }\n else {\n if (quad.third) {\n this.findTop(quad.third);\n }\n if (quad.fourth) {\n this.findTop(quad.fourth);\n }\n }\n }\n for (var _i = 0, _a = quad.objects; _i < _a.length; _i++) {\n var node = _a[_i];\n if (this.pageTop >= node.outerBounds.top) {\n this.pageTop = node.outerBounds.top;\n this.topElement = node;\n }\n }\n };\n /** @private */\n SpatialSearch.prototype.setCurrentNode = function (node) {\n this.childNode = node;\n if (node) {\n var r = node.outerBounds;\n this.childLeft = Number(r.left);\n this.childTop = Number(r.top);\n this.childRight = Number(r.right);\n this.childBottom = Number(r.bottom);\n }\n else {\n this.childLeft = Number.MAX_VALUE;\n this.childTop = Number.MAX_VALUE;\n this.childRight = -Number.MAX_VALUE;\n this.childBottom = -Number.MAX_VALUE;\n }\n };\n /** @private */\n SpatialSearch.prototype.getPageBounds = function (originX, originY) {\n if (this.pageLeft === Number.MAX_VALUE) {\n return new Rect(0, 0, 0, 0);\n }\n var left = originX !== undefined ? Math.min(this.pageLeft, 0) : this.pageLeft;\n var top = originY !== undefined ? Math.min(this.pageTop, 0) : this.pageTop;\n return new Rect(Math.round(left), Math.round(top), Math.round(this.pageRight - left), Math.round(this.pageBottom - top));\n };\n /** @private */\n SpatialSearch.prototype.getQuad = function (node) {\n return this.quadTable[node.id];\n };\n return SpatialSearch;\n}());\nexport { SpatialSearch };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, Complex, ChildProperty, Collection } from '@syncfusion/ej2-base';\n/**\n * Defines keyboard commands\n */\nvar KeyGesture = /** @class */ (function (_super) {\n __extends(KeyGesture, _super);\n function KeyGesture() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], KeyGesture.prototype, \"key\", void 0);\n __decorate([\n Property()\n ], KeyGesture.prototype, \"keyModifiers\", void 0);\n return KeyGesture;\n}(ChildProperty));\nexport { KeyGesture };\nvar Command = /** @class */ (function (_super) {\n __extends(Command, _super);\n function Command() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Command.prototype, \"name\", void 0);\n __decorate([\n Property()\n ], Command.prototype, \"canExecute\", void 0);\n __decorate([\n Property()\n ], Command.prototype, \"execute\", void 0);\n __decorate([\n Complex({}, KeyGesture)\n ], Command.prototype, \"gesture\", void 0);\n __decorate([\n Property('')\n ], Command.prototype, \"parameter\", void 0);\n return Command;\n}(ChildProperty));\nexport { Command };\nvar CommandManager = /** @class */ (function (_super) {\n __extends(CommandManager, _super);\n function CommandManager() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Collection([], Command)\n ], CommandManager.prototype, \"commands\", void 0);\n return CommandManager;\n}(ChildProperty));\nexport { CommandManager };\n/**\n * Defines the behavior of the context menu items\n */\nvar ContextMenuSettings = /** @class */ (function (_super) {\n __extends(ContextMenuSettings, _super);\n function ContextMenuSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], ContextMenuSettings.prototype, \"show\", void 0);\n __decorate([\n Property()\n ], ContextMenuSettings.prototype, \"showCustomMenuOnly\", void 0);\n __decorate([\n Property()\n ], ContextMenuSettings.prototype, \"items\", void 0);\n return ContextMenuSettings;\n}(ChildProperty));\nexport { ContextMenuSettings };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, Complex, Collection, EventHandler, L10n, Droppable, remove } from '@syncfusion/ej2-base';\nimport { Browser, Event } from '@syncfusion/ej2-base';\nimport { CanvasRenderer } from './rendering/canvas-renderer';\nimport { SvgRenderer } from './rendering/svg-renderer';\nimport { DiagramRenderer } from './rendering/renderer';\nimport { PageSettings, ScrollSettings } from './diagram/page-settings';\nimport { ServiceLocator } from './objects/service';\nimport { Container } from './core/containers/container';\nimport { Node, BpmnShape } from './objects/node';\nimport { Connector } from './objects/connector';\nimport { SnapSettings } from './diagram/grid-lines';\nimport { RulerSettings } from './diagram/ruler-settings';\nimport { removeRulerElements, updateRuler, getRulerSize } from './ruler/ruler';\nimport { renderRuler, renderOverlapElement } from './ruler/ruler';\nimport { Size } from './primitives/size';\nimport { Keys, KeyModifiers, DiagramTools } from './enum/enum';\nimport { DiagramConstraints, SelectorConstraints, PortVisibility, DiagramEvent } from './enum/enum';\nimport { DiagramAction, ThumbsConstraints } from './enum/enum';\nimport { PathElement } from './core/elements/path-element';\nimport { TextElement } from './core/elements/text-element';\nimport { updateStyle, removeItem, updateConnector, updateShape } from './utility/diagram-util';\nimport { checkPortRestriction, serialize, deserialize, updateHyperlink, getObjectType } from './utility/diagram-util';\nimport { Rect } from './primitives/rect';\nimport { getPortShape } from './objects/dictionary/common';\nimport { ShapeAnnotation, PathAnnotation } from './objects/annotation';\nimport { Canvas } from './core/containers/canvas';\nimport { DataSource } from './diagram/data-source';\nimport { Layout } from './layout/layout-base';\nimport { Selector } from './interaction/selector';\nimport { DiagramEventHandler } from './interaction/event-handlers';\nimport { CommandHandler } from './interaction/command-manager';\nimport { DiagramScroller } from './interaction/scroller';\nimport { isSelected } from './interaction/actions';\nimport { SpatialSearch } from './interaction/spatial-search/spatial-search';\nimport { setAttributeSvg, setAttributeHtml, measureHtmlText, removeElement, createMeasureElements } from './utility/dom-util';\nimport { getDiagramElement, getScrollerWidth, getHTMLLayer } from './utility/dom-util';\nimport { getBackgroundLayer, createHtmlElement, createSvgElement, getNativeLayerSvg } from './utility/dom-util';\nimport { getPortLayerSvg, getDiagramLayerSvg } from './utility/dom-util';\nimport { getAdornerLayerSvg, getSelectorElement, getGridLayerSvg, getBackgroundLayerSvg } from './utility/dom-util';\nimport { CommandManager, ContextMenuSettings } from './diagram/keyboard-commands';\nimport { canDelete, canInConnect, canOutConnect, canRotate, canResize, canSingleSelect, canZoomPan } from './utility/constraints-util';\nimport { canDragSourceEnd, canDragTargetEnd, canDragSegmentThumb, enableReadOnly, canMove } from './utility/constraints-util';\nimport { findAnnotation } from './utility/diagram-util';\nimport { randomId, cloneObject, extendObject, getFunction, getBounds } from './utility/base-util';\nimport { DiagramTooltip, initTooltip } from './objects/tooltip';\nimport { PointPort } from './objects/port';\nimport { canShadow } from './utility/constraints-util';\nimport { Layer } from './diagram/layer';\nimport { DiagramNativeElement } from './core/elements/native-element';\nimport { DiagramHtmlElement } from './core/elements/html-element';\n/**\n * Diagram control\n * ```\n *
\n * \n * ```\n */\nvar Diagram = /** @class */ (function (_super) {\n __extends(Diagram, _super);\n /**\n * Constructor for creating the widget\n */\n function Diagram(options, element) {\n var _this = _super.call(this, options, element) || this;\n /** @private */\n _this.connectorTable = {};\n /** @private */\n _this.groupTable = {};\n /** @private */\n _this.activeLabel = { id: '', parentId: '', isGroup: false };\n _this.renderTimer = null;\n return _this;\n }\n Diagram.prototype.clearCollection = function (isConnector) {\n var collection = [];\n var obj;\n for (var _i = 0, _a = Object.keys(this.nameTable); _i < _a.length; _i++) {\n var key = _a[_i];\n obj = this.nameTable[key];\n if (obj && ((isConnector && obj instanceof Connector) || (!isConnector && obj instanceof Node))) {\n collection.push(obj);\n }\n }\n this.clearObjects(collection);\n };\n /**\n * Updates the diagram control when the objects are changed\n * @param newProp Lists the new values of the changed properties\n * @param oldProp Lists the old values of the changed properties\n */\n /* tslint:disable */\n Diagram.prototype.onPropertyChanged = function (newProp, oldProp) {\n // Model Changed\n var objectArray = [];\n var refreshLayout = false;\n var refereshColelction = false;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'width':\n case 'height':\n this.element.style.width = this.getSizeValue(this.width);\n this.element.style.height = this.getSizeValue(this.height);\n this.eventHandler.updateViewPortSize(this.element);\n for (var _b = 0, _c = this.views; _b < _c.length; _b++) {\n var view = _c[_b];\n var temp = this.views[view];\n if (!(temp instanceof Diagram)) {\n temp.updateView(temp);\n }\n }\n break;\n case 'nodes':\n if (newProp.nodes.length > 0 && oldProp.nodes.length === 0) {\n this.clearCollection();\n refereshColelction = true;\n }\n else {\n for (var _d = 0, _e = Object.keys(newProp.nodes); _d < _e.length; _d++) {\n var key = _e[_d];\n var index = Number(key);\n var actualObject = this.nodes[index];\n var changedProp = newProp.nodes[index];\n refreshLayout = refreshLayout || changedProp.excludeFromLayout !== undefined;\n this.nodePropertyChange(actualObject, oldProp.nodes[index], changedProp);\n objectArray.push(actualObject);\n }\n if (this.mode === 'Canvas') {\n this.refreshDiagramLayer();\n }\n }\n break;\n case 'connectors':\n var oldObject = void 0;\n if (newProp.connectors.length > 0 && oldProp.connectors.length === 0) {\n this.clearCollection(true);\n refereshColelction = true;\n }\n else {\n for (var _f = 0, _g = Object.keys(newProp.connectors); _f < _g.length; _f++) {\n var key = _g[_f];\n var index = Number(key);\n var actualObject = this.connectors[index];\n var changedProp = newProp.connectors[index];\n this.connectorPropertyChange(actualObject, oldProp.connectors[index], changedProp, true);\n objectArray.push(actualObject);\n }\n this.updateBridging();\n if (this.mode === 'Canvas') {\n this.refreshDiagramLayer();\n }\n }\n break;\n case 'bridgeDirection':\n this.updateBridging();\n if (this.mode === 'Canvas') {\n this.refreshDiagramLayer();\n }\n break;\n case 'backgroundColor':\n this.intOffPageBackground();\n break;\n case 'pageSettings':\n this.validatePageSize();\n this.updatePage();\n break;\n case 'selectedItems':\n if (newProp.selectedItems.userHandles && this.selectedItems.wrapper && this.selectedItems.userHandles) {\n if (this.selectedItems.userHandles.length > 0) {\n this.renderSelector(true);\n break;\n }\n }\n if (newProp.selectedItems.constraints) {\n this.renderSelector(true);\n break;\n }\n break;\n case 'snapSettings':\n this.updateSnapSettings(newProp);\n break;\n case 'commandManager':\n this.initCommands();\n break;\n case 'layout':\n refreshLayout = true;\n break;\n case 'dataSourceSettings':\n this.clear();\n this.initObjects();\n refreshLayout = true;\n break;\n case 'tooltip':\n initTooltip(this);\n break;\n case 'rulerSettings':\n this.updateRulerSettings(newProp);\n break;\n case 'layers':\n this.updateLayer(newProp);\n break;\n case 'scrollSettings':\n this.updateScrollSettings(newProp);\n break;\n }\n }\n if (refreshLayout) {\n this.doLayout();\n }\n var args = { element: objectArray, cause: this.diagramActions, oldValue: oldProp, newValue: newProp };\n this.triggerEvent(DiagramEvent.propertyChange, args);\n if (!refereshColelction && (this.canLogChange()) && (this.modelChanged(newProp, oldProp))) {\n var entry = { type: 'PropertyChanged', undoObject: oldProp, redoObject: newProp, category: 'Internal' };\n this.addHistoryEntry(entry);\n }\n this.resetDiagramActions();\n if (refereshColelction) {\n this.initObjects(true);\n this.refreshDiagramLayer();\n }\n };\n /* tslint:enable */\n Diagram.prototype.updateSnapSettings = function (newProp) {\n if (newProp.snapSettings.constraints || newProp.snapSettings.horizontalGridlines ||\n newProp.snapSettings.verticalGridlines) {\n this.diagramRenderer.updateGrid(this.snapSettings, getGridLayerSvg(this.element.id), this.scroller.transform, this.rulerSettings, this.hRuler, this.vRuler);\n }\n };\n Diagram.prototype.updateRulerSettings = function (newProp) {\n if (newProp.rulerSettings.dynamicGrid !== undefined) {\n this.diagramRenderer.updateGrid(this.snapSettings, getGridLayerSvg(this.element.id), this.scroller.transform, this.rulerSettings, this.hRuler, this.vRuler);\n }\n if (newProp.rulerSettings.showRulers !== undefined) {\n this.intOffPageBackground();\n this.scroller.setSize();\n this.renderRulers();\n }\n else if (newProp.rulerSettings.horizontalRuler !== undefined ||\n newProp.rulerSettings.verticalRuler !== undefined) {\n if (newProp.rulerSettings.horizontalRuler.thickness !== undefined ||\n newProp.rulerSettings.verticalRuler.thickness !== undefined) {\n removeRulerElements(this);\n this.intOffPageBackground();\n this.scroller.setSize();\n this.renderRulers();\n }\n else {\n updateRuler(this);\n }\n }\n this.diagramRenderer.updateGrid(this.snapSettings, getGridLayerSvg(this.element.id), this.scroller.transform, this.rulerSettings, this.hRuler, this.vRuler);\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @return {string}\n */\n Diagram.prototype.getPersistData = function () {\n var keyEntity = ['loaded'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Initialize nodes, connectors and renderer\n */\n Diagram.prototype.preRender = function () {\n this.initializePrivateVariables();\n this.isProtectedOnChange = true;\n this.serviceLocator = new ServiceLocator;\n this.initializeServices();\n this.initDiagram();\n this.initViews();\n this.unWireEvents();\n this.wireEvents();\n this.element.classList.add('e-diagram');\n };\n Diagram.prototype.initializePrivateVariables = function () {\n this.defaultLocale = {\n Copy: 'Copy',\n Cut: 'Cut',\n Paste: 'Paste',\n Undo: 'Undo',\n Redo: 'Redo',\n SelectAll: 'Select All',\n Grouping: 'Grouping',\n Group: 'Group',\n UnGroup: 'Un Group',\n Order: 'Order',\n BringToFront: 'Bring To Front',\n MoveForward: 'Move Forward',\n SendToBack: 'Send To Back',\n SendBackward: 'Send Backward'\n };\n this.layerZIndex = -1;\n this.layerZIndexTable = {};\n this.nameTable = {};\n this.groupTable = {};\n this.commands = {};\n if (!this.isLoading) {\n this.views = [];\n }\n this.commandHandler = new CommandHandler(this);\n this.eventHandler = new DiagramEventHandler(this, this.commandHandler);\n this.spatialSearch = new SpatialSearch(this.nameTable);\n this.scroller = new DiagramScroller(this);\n };\n Diagram.prototype.initializeServices = function () {\n this.serviceLocator.register('localization', this.localeObj = new L10n(this.getModuleName(), this.defaultLocale, this.locale));\n };\n /**\n * Renders the diagram control with nodes and connectors\n */\n Diagram.prototype.render = function () {\n this.initHistory();\n this.diagramRenderer = new DiagramRenderer(this.element.id, new SvgRenderer(), this.mode === 'SVG');\n this.initLayers();\n this.initializeDiagramLayers();\n this.diagramRenderer.setLayers();\n this.initObjects(true);\n this.doLayout();\n this.validatePageSize();\n this.renderPageBreaks();\n this.diagramRenderer.renderSvgGridlines(this.snapSettings, getGridLayerSvg(this.element.id), this.scroller.transform, this.rulerSettings, this.hRuler, this.vRuler);\n this.commandHandler.initSelectorWrapper();\n /**\n * Used to render context menu\n */\n this.notify('initial-load', {});\n /**\n * Used to load context menu\n */\n this.trigger('load');\n this.scroller.setSize();\n this.scroller.updateScrollOffsets();\n this.refreshDiagramLayer();\n /**\n * Used to end the context menu rendering\n */\n this.notify('initial-end', {});\n this.isProtectedOnChange = false;\n this.tooltipObject = initTooltip(this);\n this.diagramActions = DiagramAction.Render;\n this.initCommands();\n this.isLoading = false;\n };\n /**\n * Returns the module name of the diagram\n */\n Diagram.prototype.getModuleName = function () {\n return 'diagram';\n };\n /**\n * To provide the array of modules needed for control rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n Diagram.prototype.requiredModules = function () {\n var modules = [];\n modules.push({\n member: 'Bpmn',\n args: []\n });\n modules.push({\n member: 'Bridging',\n args: []\n });\n modules.push({\n member: 'ConnectorEditingTool',\n args: []\n });\n if (this.constraints & DiagramConstraints.UndoRedo) {\n modules.push({\n member: 'UndoRedo',\n args: []\n });\n }\n if (this.layout.type === 'OrganizationalChart' || this.layout.type === 'HierarchicalTree' ||\n this.layout.enableAnimation) {\n modules.push({\n member: 'LayoutAnimate',\n args: []\n });\n }\n if (this.snapSettings.constraints) {\n modules.push({\n member: 'Snapping',\n args: [this]\n });\n }\n modules.push({\n member: 'PrintandExport',\n args: [this]\n });\n if (this.contextMenuSettings.show) {\n modules.push({\n member: 'contextMenu',\n args: [this, this.serviceLocator]\n });\n }\n if (this.layout.type === 'OrganizationalChart' || this.layout.type === 'HierarchicalTree') {\n modules.push({\n member: 'OrganizationalChart',\n args: []\n });\n }\n if (this.layout.type === 'ComplexHierarchicalTree') {\n modules.push({\n member: 'ComplexHierarchicalTree',\n args: []\n });\n }\n if (this.layout.type === 'MindMap') {\n modules.push({\n member: 'MindMapChart',\n args: []\n });\n }\n if (this.layout.type === 'RadialTree') {\n modules.push({\n member: 'RadialTree',\n args: []\n });\n }\n if (this.layout.type === 'SymmetricalLayout') {\n modules.push({\n member: 'SymmetricalLayout',\n args: []\n });\n }\n if (this.dataSourceSettings.dataManager || this.dataSourceSettings.data) {\n modules.push({\n member: 'DataBinding',\n args: []\n });\n }\n return modules;\n };\n /**\n * Destroys the diagram control\n */\n Diagram.prototype.destroy = function () {\n clearInterval(this.renderTimer);\n this.renderTimer = null;\n if (this.hRuler && this.vRuler) {\n this.hRuler.destroy();\n this.vRuler.destroy();\n }\n this.tooltipObject.destroy();\n this.droppable.destroy();\n this.unWireEvents();\n this.notify('destroy', {});\n _super.prototype.destroy.call(this);\n if (document.getElementById(this.element.id)) {\n this.element.classList.remove('e-diagram');\n var tooltipelement = document.getElementsByClassName('e-tooltip-wrap');\n while (tooltipelement.length > 0) {\n tooltipelement[0].parentNode.removeChild(tooltipelement[0]);\n }\n var content = document.getElementById(this.element.id + 'content');\n if (content) {\n this.element.removeChild(content);\n }\n var measureElement = 'measureElement';\n if (window[measureElement]) {\n window[measureElement].usageCount -= 1;\n if (window[measureElement].usageCount === 0) {\n window[measureElement].parentNode.removeChild(window[measureElement]);\n window[measureElement] = null;\n }\n }\n }\n };\n /**\n * Wires the mouse events with diagram control\n */\n Diagram.prototype.wireEvents = function () {\n var startEvent = Browser.touchStartEvent;\n var stopEvent = Browser.touchEndEvent;\n var moveEvent = Browser.touchMoveEvent;\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n var isIE11Pointer = Browser.isPointer;\n var wheelEvent = Browser.info.name === 'mozilla' ?\n (isIE11Pointer ? 'mousewheel' : 'DOMMouseScroll') : 'mousewheel';\n EventHandler.add(this.diagramCanvas, startEvent, this.eventHandler.mouseDown, this.eventHandler);\n EventHandler.add(this.diagramCanvas, moveEvent, this.eventHandler.mouseMove, this.eventHandler);\n EventHandler.add(this.diagramCanvas, stopEvent, this.eventHandler.mouseUp, this.eventHandler);\n EventHandler.add(this.diagramCanvas, cancelEvent, this.eventHandler.mouseLeave, this.eventHandler);\n EventHandler.add(this.diagramCanvas, 'keydown', this.eventHandler.keyDown, this.eventHandler);\n EventHandler.add(this.diagramCanvas, 'dblclick', this.eventHandler.doubleClick, this.eventHandler);\n EventHandler.add(this.diagramCanvas, 'scroll', this.eventHandler.scrolled, this.eventHandler);\n EventHandler.add(this.diagramCanvas, wheelEvent, this.eventHandler.mouseWheel, this.eventHandler);\n EventHandler.add(window, 'resize', this.eventHandler.windowResize, this.eventHandler);\n this.initDroppables();\n };\n /**\n * Unwires the mouse events from diagram control\n */\n Diagram.prototype.unWireEvents = function () {\n var startEvent = Browser.touchStartEvent;\n var moveEvent = Browser.touchMoveEvent;\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n var isIE11Pointer = Browser.isPointer;\n var wheelEvent = Browser.info.name === 'mozilla' ?\n (isIE11Pointer ? 'mousewheel' : 'DOMMouseScroll') : 'mousewheel';\n var stopEvent = Browser.touchEndEvent;\n EventHandler.remove(this.diagramCanvas, startEvent, this.eventHandler.mouseDown);\n EventHandler.remove(this.diagramCanvas, moveEvent, this.eventHandler.mouseMove);\n EventHandler.remove(this.diagramCanvas, stopEvent, this.eventHandler.mouseUp);\n EventHandler.remove(this.diagramCanvas, cancelEvent, this.eventHandler.mouseLeave);\n EventHandler.remove(this.diagramCanvas, 'keydown', this.eventHandler.keyDown);\n EventHandler.remove(this.diagramCanvas, 'dblclick', this.eventHandler.doubleClick);\n EventHandler.remove(this.diagramCanvas, 'scroll', this.eventHandler.scrolled);\n EventHandler.remove(this.diagramCanvas, wheelEvent, this.eventHandler.mouseWheel);\n EventHandler.remove(window, 'resize', this.eventHandler.windowResize);\n };\n //public methods - start region\n /**\n * Selects the given collection of objects\n * @param objects Defines the collection of nodes and connectors to be selected\n * @param multipleSelection Defines whether the existing selection has to be cleared or not\n */\n Diagram.prototype.select = function (objects, multipleSelection) {\n if (objects != null) {\n this.commandHandler.selectObjects(objects, multipleSelection);\n }\n };\n /**\n * Selects the all the objects.\n */\n Diagram.prototype.selectAll = function () {\n var selectedItems = [];\n selectedItems = this.getObjectsOfLayer(this.activeLayer.objects);\n this.select(selectedItems);\n };\n /**\n * Removes the given object from selection list\n * @param obj Defines the object to be unselected\n */\n Diagram.prototype.unSelect = function (obj) {\n if (obj && isSelected(this, obj)) {\n this.commandHandler.unSelect(obj);\n }\n };\n /**\n * Removes all elements from the selection list\n */\n Diagram.prototype.clearSelection = function () {\n this.commandHandler.clearSelection(true);\n };\n /**\n * Update the diagram clipboard dimension\n */\n Diagram.prototype.updateViewPort = function () {\n this.eventHandler.updateViewPortSize(this.element);\n };\n Diagram.prototype.cutCommand = function () {\n this.cut();\n };\n /**\n * Removes the selected nodes and connectors from diagram and moves them to diagram clipboard\n */\n Diagram.prototype.cut = function () {\n this.commandHandler.cut();\n };\n /**\n * Add a process into the sub-process\n */\n Diagram.prototype.addProcess = function (process, parentId) {\n if (this.bpmnModule) {\n this.bpmnModule.addProcess(process, parentId, this);\n }\n };\n /**\n * Remove a process from the sub-process\n */\n Diagram.prototype.removeProcess = function (id) {\n if (this.bpmnModule) {\n this.bpmnModule.removeProcess(id, this);\n }\n };\n Diagram.prototype.pasteCommand = function () {\n this.paste();\n };\n /**\n * Adds the given objects/ the objects in the diagram clipboard to diagram control\n * @param obj Defines the objects to be added to diagram\n */\n Diagram.prototype.paste = function (obj) {\n this.commandHandler.paste(obj);\n };\n /**\n * fit the diagram to the page with respect to mode and region\n */\n Diagram.prototype.fitToPage = function (options) {\n this.scroller.fitToPage(options);\n };\n /**\n * bring the specified bounds into the viewport\n */\n Diagram.prototype.bringIntoView = function (bound) {\n this.scroller.bringIntoView(bound);\n };\n /**\n * bring the specified bounds to the center of the viewport\n */\n Diagram.prototype.bringToCenter = function (bound) {\n this.scroller.bringToCenter(bound);\n };\n Diagram.prototype.copyCommand = function () {\n this.copy();\n };\n /**\n * Copies the selected nodes and connectors to diagram clipboard\n */\n Diagram.prototype.copy = function () {\n var obj = this.commandHandler.copy();\n return obj;\n };\n /**\n * Group the selected nodes and connectors in diagram\n */\n Diagram.prototype.group = function () {\n this.commandHandler.group();\n };\n /**\n * UnGroup the selected nodes and connectors in diagram\n */\n Diagram.prototype.unGroup = function () {\n this.commandHandler.unGroup();\n };\n /**\n * send the selected nodes or connectors back\n */\n Diagram.prototype.sendToBack = function () {\n this.commandHandler.sendToBack();\n };\n /**\n * set the active layer\n * @param layerName defines the name of the layer which is to be active layer\n */\n Diagram.prototype.setActiveLayer = function (layerName) {\n var layer = this.commandHandler.getLayer(layerName);\n this.activeLayer = layer;\n };\n /**\n * add the layer into diagram\n * @param layer defines the layer model which is to be added\n * @param layerObject defines the object of the layer\n */\n Diagram.prototype.addLayer = function (layer, layerObject) {\n this.commandHandler.addLayer(layer, layerObject);\n };\n /**\n * remove the layer from diagram\n * @param layerId define the id of the layer\n */\n Diagram.prototype.removeLayer = function (layerId) {\n this.commandHandler.removeLayer(layerId);\n };\n /**\n * move objects from the layer to another layer from diagram\n * @param objects define the objects id of string array\n */\n Diagram.prototype.moveObjects = function (objects, targetLayer) {\n this.commandHandler.moveObjects(objects, targetLayer);\n };\n /**\n * move the layer backward\n * @param layerName define the name of the layer\n */\n Diagram.prototype.sendLayerBackward = function (layerName) {\n this.commandHandler.sendLayerBackward(layerName);\n };\n /**\n * move the layer forward\n * @param layerName define the name of the layer\n */\n Diagram.prototype.bringLayerForward = function (layerName) {\n this.commandHandler.bringLayerForward(layerName);\n };\n /**\n * clone a layer with its object\n * @param layerName define the name of the layer\n */\n Diagram.prototype.cloneLayer = function (layerName) {\n this.commandHandler.cloneLayer(layerName);\n };\n /**\n * bring the selected nodes or connectors to front\n */\n Diagram.prototype.bringToFront = function () {\n this.commandHandler.bringToFront();\n };\n /**\n * send the selected nodes or connectors forward\n */\n Diagram.prototype.moveForward = function () {\n this.commandHandler.sendForward();\n };\n /**\n * send the selected nodes or connectors back\n */\n Diagram.prototype.sendBackward = function () {\n this.commandHandler.sendBackward();\n };\n /**\n * gets the node or connector having the given name\n */\n Diagram.prototype.getObject = function (name) {\n return this.nameTable[name];\n };\n /**\n * gets the active layer back\n */\n Diagram.prototype.getActiveLayer = function () {\n return this.activeLayer;\n };\n Diagram.prototype.nudgeCommand = function (direction, x, y) {\n if (typeof direction !== 'object') {\n this.nudge(direction);\n }\n };\n /**\n * Moves the selected objects towards the given direction\n * @param direction Defines the direction by which the objects have to be moved\n * @param x Defines the distance by which the selected objects have to be horizontally moved\n * @param y Defines the distance by which the selected objects have to be vertically moved\n */\n Diagram.prototype.nudge = function (direction, x, y) {\n var tx = 0;\n var ty = 0;\n var negativeDirection;\n if (direction === 'Left' || direction === 'Right') {\n negativeDirection = (direction === 'Left');\n tx = (negativeDirection ? -1 : 1) * (x ? x : 1);\n }\n else {\n negativeDirection = (direction === 'Up');\n ty = (negativeDirection ? -1 : 1) * (y ? y : 1);\n }\n var obj = this.selectedItems;\n this.drag(obj, tx, ty);\n };\n /**\n * Drags the given object by the specified pixels\n * @param obj Defines the nodes/connectors to be dragged\n * @param tx Defines the distance by which the given objects have to be horizontally moved\n * @param ty Defines the distance by which the given objects have to be vertically moved\n */\n Diagram.prototype.drag = function (obj, tx, ty) {\n if (this.bpmnModule && (obj instanceof Node)) {\n var updated = this.bpmnModule.updateAnnotationDrag(obj, this, tx, ty);\n if (updated) {\n return;\n }\n }\n if (obj instanceof Selector) {\n if (obj.nodes && obj.nodes.length) {\n for (var _i = 0, _a = obj.nodes; _i < _a.length; _i++) {\n var node = _a[_i];\n this.drag(node, tx, ty);\n }\n }\n if (obj.connectors && obj.connectors.length) {\n for (var _b = 0, _c = obj.connectors; _b < _c.length; _b++) {\n var conn = _c[_b];\n this.drag(conn, tx, ty);\n }\n }\n this.updateSelector();\n }\n else {\n if (obj instanceof Node) {\n if (this.bpmnModule) {\n this.bpmnModule.updateAnnotationDrag(obj, this, tx, ty);\n }\n }\n this.commandHandler.drag(obj, tx, ty);\n }\n };\n /**\n * Scales the given objects by the given ratio\n * @param obj Defines the objects to be resized\n * @param sx Defines the ratio by which the objects have to be horizontally scaled\n * @param sy Defines the ratio by which the objects have to be vertically scaled\n * @param pivot Defines the reference point with respect to which the objects will be resized\n */\n Diagram.prototype.scale = function (obj, sx, sy, pivot) {\n var checkBoundaryConstraints = true;\n if (obj instanceof Selector) {\n if (obj.nodes && obj.nodes.length) {\n for (var _i = 0, _a = obj.nodes; _i < _a.length; _i++) {\n var node = _a[_i];\n checkBoundaryConstraints = this.commandHandler.scale(node, sx, sy, pivot, obj);\n }\n }\n if (obj.connectors && obj.connectors.length) {\n for (var _b = 0, _c = obj.connectors; _b < _c.length; _b++) {\n var conn = _c[_b];\n this.commandHandler.scale(conn, sx, sy, pivot, obj);\n }\n }\n this.updateSelector();\n }\n else {\n this.commandHandler.scale(obj, sx, sy, pivot);\n }\n return checkBoundaryConstraints;\n };\n /**\n * Rotates the given nodes/connectors by the given angle\n * @param obj Defines the objects to be rotated\n * @param angle Defines the angle by which the objects have to be rotated\n * @param pivot Defines the reference point with reference to which the objects have to be rotated\n */\n Diagram.prototype.rotate = function (obj, angle, pivot) {\n var checkBoundaryConstraints;\n if (obj) {\n pivot = pivot || { x: obj.wrapper.offsetX, y: obj.wrapper.offsetY };\n if (obj instanceof Selector) {\n obj.rotateAngle += angle;\n obj.wrapper.rotateAngle += angle;\n var bounds = getBounds(obj.wrapper);\n checkBoundaryConstraints = this.commandHandler.checkBoundaryConstraints(undefined, undefined, bounds);\n if (!checkBoundaryConstraints) {\n obj.rotateAngle -= angle;\n obj.wrapper.rotateAngle -= angle;\n return checkBoundaryConstraints;\n }\n var objects = [];\n objects = objects.concat(obj.nodes);\n objects = objects.concat(obj.connectors);\n this.commandHandler.rotateObjects(obj, objects, angle, pivot);\n }\n else {\n this.commandHandler.rotateObjects(obj, [obj], angle, pivot);\n }\n }\n return checkBoundaryConstraints;\n };\n /**\n * Moves the source point of the given connector\n * @param obj Defines the connector, the end points of which has to be moved\n * @param tx Defines the distance by which the end point has to be horizontally moved\n * @param ty Defines the distance by which the end point has to be vertically moved\n */\n Diagram.prototype.dragSourceEnd = function (obj, tx, ty) {\n this.commandHandler.dragSourceEnd(obj, tx, ty);\n };\n /**\n * Moves the target point of the given connector\n * @param obj Defines the connector, the end points of which has to be moved\n * @param tx Defines the distance by which the end point has to be horizontally moved\n * @param ty Defines the distance by which the end point has to be vertically moved\n */\n Diagram.prototype.dragTargetEnd = function (obj, tx, ty) {\n this.commandHandler.dragTargetEnd(obj, tx, ty);\n };\n /**\n * Finds all the objects that is under the given mouse position\n * @param position Defines the position, the objects under which has to be found\n * @param source Defines the object, the objects under which has to be found\n */\n Diagram.prototype.findObjectsUnderMouse = function (position, source) {\n return this.eventHandler.findObjectsUnderMouse(position, source);\n };\n /**\n * Finds the object that is under the given mouse position\n * @param objects Defines the collection of objects, from which the object has to be found.\n * @param action Defines the action, using which the relevant object has to be found.\n * @param inAction Defines the active state of the action.\n */\n Diagram.prototype.findObjectUnderMouse = function (objects, action, inAction) {\n return this.eventHandler.findObjectUnderMouse(objects, action, inAction);\n };\n /**\n * Finds the object that is under the given active object (Source)\n * @param objects Defines the collection of objects, from which the object has to be found.\n * @param action Defines the action, using which the relevant object has to be found.\n * @param inAction Defines the active state of the action.\n */\n Diagram.prototype.findTargetObjectUnderMouse = function (objects, action, inAction, position, source) {\n return this.eventHandler.findTargetUnderMouse(objects, action, inAction, position, source);\n };\n /**\n * Finds the child element of the given object at the given position\n * @param obj Defines the object, the child element of which has to be found\n * @param position Defines the position, the child element under which has to be found\n */\n Diagram.prototype.findElementUnderMouse = function (obj, position) {\n return this.eventHandler.findElementUnderMouse(obj, position);\n };\n /**\n * Defines the action to be done, when the mouse hovers the given element of the given object\n * @param obj Defines the object under mouse\n * @param wrapper Defines the target element of the object under mouse\n * @param position Defines the current mouse position\n */\n Diagram.prototype.findActionToBeDone = function (obj, wrapper, position, target) {\n return this.eventHandler.findActionToBeDone(obj, wrapper, position, target);\n };\n /**\n * Returns the tool that handles the given action\n * @param action Defines the action that is going to be performed\n */\n Diagram.prototype.getTool = function (action) {\n var tool;\n var getCustomTool = getFunction(this.getCustomTool);\n if (getCustomTool) {\n tool = getCustomTool(action);\n if (tool) {\n return tool;\n }\n }\n return this.eventHandler.getTool(action);\n };\n /**\n * Defines the cursor that corresponds to the given action\n * @param action Defines the action that is going to be performed\n */\n Diagram.prototype.getCursor = function (action, active) {\n var cursor;\n var getCustomCursor = getFunction(this.getCustomCursor);\n if (getCustomCursor) {\n cursor = getCustomCursor(action, active);\n if (cursor) {\n return cursor;\n }\n }\n return this.eventHandler.getCursor(action);\n };\n /**\n * Initializes the undo redo actions\n * @private\n */\n Diagram.prototype.initHistory = function () {\n if (this.undoRedoModule) {\n this.undoRedoModule.initHistory(this);\n }\n };\n /**\n * Adds the given change in the diagram control to the track\n * @param entry Defines the entry/information about a change in diagram\n */\n Diagram.prototype.addHistoryEntry = function (entry) {\n if (this.undoRedoModule && (this.constraints & DiagramConstraints.UndoRedo) && !this.currentSymbol) {\n this.undoRedoModule.addHistoryEntry(entry, this);\n if (entry.type !== 'StartGroup' && entry.type !== 'EndGroup') {\n this.historyChangeTrigger(entry);\n }\n }\n };\n /** @private */\n Diagram.prototype.historyChangeTrigger = function (entry) {\n var change = {};\n var oldValue = 'oldValue';\n var newValue = 'newValue';\n var type = 'type';\n var source = [];\n if (entry && entry.redoObject && ((entry.redoObject.nodes) instanceof Array) &&\n ((entry.redoObject.connectors) instanceof Array)) {\n source = entry.redoObject.nodes.concat(entry.redoObject.connectors);\n }\n else {\n if (entry.redoObject) {\n source.push(entry.redoObject);\n }\n }\n change[type] = entry.type;\n switch (entry.type) {\n case 'PositionChanged':\n change[oldValue] = { offsetX: entry.undoObject.offsetX, offsetY: entry.undoObject.offsetY };\n change[newValue] = { offsetX: entry.redoObject.offsetX, offsetY: entry.redoObject.offsetY };\n break;\n case 'RotationChanged':\n change[oldValue] = { rotateAngle: entry.undoObject.rotateAngle };\n change[newValue] = { rotateAngle: entry.redoObject.rotateAngle };\n break;\n case 'SizeChanged':\n change[oldValue] = {\n offsetX: entry.undoObject.offsetX, offsetY: entry.undoObject.offsetY,\n width: entry.undoObject.width, height: entry.undoObject.height\n };\n change[newValue] = {\n offsetX: entry.redoObject.offsetX, offsetY: entry.redoObject.offsetY,\n width: entry.redoObject.width, height: entry.redoObject.height\n };\n break;\n case 'CollectionChanged':\n change[entry.changeType] = source;\n break;\n case 'ConnectionChanged':\n change[oldValue] = { offsetX: entry.undoObject.offsetX, offsetY: entry.undoObject.offsetY };\n change[newValue] = { offsetX: entry.redoObject.offsetX, offsetY: entry.redoObject.offsetY };\n break;\n }\n var arg = {\n cause: entry.category, source: source, change: change\n };\n if (source.length) {\n this.triggerEvent(DiagramEvent.historyChange, arg);\n }\n };\n /**\n * Starts grouping the actions that will be undone/restored as a whole\n */\n Diagram.prototype.startGroupAction = function () {\n var entry = { type: 'StartGroup', category: 'Internal' };\n this.addHistoryEntry(entry);\n };\n /**\n * Closes grouping the actions that will be undone/restored as a whole\n */\n Diagram.prototype.endGroupAction = function () {\n var entry = { type: 'EndGroup', category: 'Internal' };\n this.addHistoryEntry(entry);\n };\n /**\n * Restores the last action that is performed\n */\n Diagram.prototype.undo = function () {\n if (this.undoRedoModule && (this.constraints & DiagramConstraints.UndoRedo)) {\n this.undoRedoModule.undo(this);\n }\n };\n /**\n * Restores the last undone action\n */\n Diagram.prototype.redo = function () {\n if (this.undoRedoModule && (this.constraints & DiagramConstraints.UndoRedo)) {\n this.undoRedoModule.redo(this);\n }\n };\n /**\n * Aligns the group of objects to with reference to the first object in the group\n * @param objects Defines the objects that have to be aligned\n * @param option Defines the factor, by which the objects have to be aligned\n */\n Diagram.prototype.align = function (option, objects) {\n if (!objects) {\n objects = [];\n objects = objects.concat(this.selectedItems.nodes, this.selectedItems.connectors);\n }\n this.diagramActions = this.diagramActions | DiagramAction.PublicMethod;\n this.commandHandler.align(objects, option);\n };\n /**\n * Arranges the group of objects with equal intervals, but within the group of objects\n * @param objects Defines the objects that have to be equally spaced\n * @param option Defines the factor to distribute the shapes\n */\n Diagram.prototype.distribute = function (option, objects) {\n if (!objects) {\n objects = [];\n objects = objects.concat(this.selectedItems.nodes, this.selectedItems.connectors);\n }\n this.diagramActions = this.diagramActions | DiagramAction.PublicMethod;\n this.commandHandler.distribute(objects, option);\n };\n /**\n * Scales the given objects to the size of the first object in the group\n * @param objects Defines the collection of objects that have to be scaled\n * @param option Defines whether the node has to be horizontally scaled, vertically scaled or both\n */\n Diagram.prototype.sameSize = function (option, objects) {\n if (!objects) {\n objects = [];\n objects = objects.concat(this.selectedItems.nodes, this.selectedItems.connectors);\n }\n this.diagramActions = this.diagramActions | DiagramAction.PublicMethod;\n this.commandHandler.sameSize(objects, option);\n };\n /**\n * Scales the diagram control by the given factor\n * @param factor Defines the factor by which the diagram is zoomed\n * @param focusedPoint Defines the point with respect to which the diagram has to be zoomed\n */\n Diagram.prototype.zoom = function (factor, focusedPoint) {\n this.scroller.zoom(factor, 0, 0, focusedPoint);\n };\n /**\n * Scales the diagram control by the given factor\n * @param options used to define the zoom factor, focus point and zoom type.\n *\n */\n Diagram.prototype.zoomTo = function (options) {\n var factor = options.zoomFactor ? options.zoomFactor : 0.2;\n factor = options.type === 'ZoomOut' ? 1 / (1 + factor) : (1 + factor);\n this.scroller.zoom(factor, 0, 0, options.focusPoint);\n };\n /**\n * Pans the diagram control to the given horizontal and vertical offsets\n * @param horizontalOffset Defines the horizontal distance to which the diagram has to be scrolled\n * @param verticalOffset Defines the vertical distance to which the diagram has to be scrolled\n */\n Diagram.prototype.pan = function (horizontalOffset, verticalOffset, focusedPoint) {\n this.scroller.zoom(1, horizontalOffset, verticalOffset, focusedPoint);\n };\n /**\n * Resets the zoom and scroller offsets to default values\n */\n Diagram.prototype.reset = function () {\n this.scroller.zoom(1 / this.scroller.currentZoom, -this.scroller.horizontalOffset, -this.scroller.verticalOffset, { x: 0, y: 0 });\n };\n /** @private */\n Diagram.prototype.triggerEvent = function (eventName, args) {\n if (args) {\n this.updateEventValue(args);\n }\n this.trigger(DiagramEvent[eventName], args);\n };\n Diagram.prototype.updateEventValue = function (args) {\n var element = args.element;\n if (args.element && element instanceof Selector && (element.nodes.length + element.connectors.length === 1)) {\n args.element = (element.nodes.length === 1) ? element.nodes[0] : element.connectors[0];\n }\n };\n /**\n * Adds the given object to diagram control\n * @param obj Defines the object that has to be added to diagram\n */\n Diagram.prototype.add = function (obj) {\n var newObj;\n if (obj) {\n obj = cloneObject(obj);\n if (this.bpmnModule) {\n if (!this.bpmnModule.canAdd(obj)) {\n return null;\n }\n }\n var args = {\n element: obj, cause: this.diagramActions, state: 'Changing', type: 'Addition', cancel: false\n };\n this.triggerEvent(DiagramEvent.collectionChange, args);\n var activeLayer = void 0;\n obj.id = obj.id || randomId();\n var layers = this.activeLayer;\n if (!args.cancel && !layers.lock) {\n if (layers.objects.indexOf(obj.id) < 0 && !layers.lock) {\n if (!layers.visible) {\n layers.visible = true;\n this.dataBind();\n }\n layers.objects.push(obj.id);\n }\n if (getObjectType(obj) === Connector) {\n newObj = new Connector(this, 'connectors', obj, true);\n this.connectors.push(newObj);\n this.initObject(newObj);\n if (obj.visible === false) {\n this.updateElementVisibility(newObj.wrapper, newObj, obj.visible);\n }\n this.updateEdges(newObj);\n }\n else {\n newObj = new Node(this, 'nodes', obj, true);\n // newObj.processId = (obj as Node).processId;\n this.nodes.push(newObj);\n this.initObject(newObj, layers);\n if (this.bpmnModule) {\n if (newObj.shape.annotations && newObj.shape.annotations.length !== 0) {\n for (var _i = 0, _a = this.bpmnModule.getTextAnnotationConn(newObj); _i < _a.length; _i++) {\n var obj_1 = _a[_i];\n this.initConnectors(obj_1, layers, false);\n }\n }\n if (newObj.shape.activity && newObj.shape.activity.subProcess.processes &&\n newObj.shape.activity.subProcess.processes.length) {\n this.bpmnModule.updateDocks(newObj, this);\n }\n }\n }\n args = {\n element: newObj, cause: this.diagramActions, state: 'Changed', type: 'Addition', cancel: false\n };\n this.triggerEvent(DiagramEvent.collectionChange, args);\n if (!(this.diagramActions & DiagramAction.UndoRedo) && !(this.diagramActions & DiagramAction.Group)) {\n var entry = {\n type: 'CollectionChanged', changeType: 'Insert', undoObject: cloneObject(obj),\n redoObject: cloneObject(obj), category: 'Internal'\n };\n this.addHistoryEntry(entry);\n }\n this.diagramActions = this.diagramActions | DiagramAction.PublicMethod;\n if (this.mode === 'SVG') {\n this.updateSvgNodes(newObj);\n this.updateDiagramObject(newObj);\n if (newObj.shape.activity && newObj.shape.activity.subProcess.processes &&\n newObj.shape.activity.subProcess.processes.length) {\n this.updateProcesses(newObj);\n }\n }\n }\n }\n this.resetDiagramActions(DiagramAction.PublicMethod);\n return newObj;\n };\n Diagram.prototype.updateSvgNodes = function (node) {\n if (node.children) {\n for (var _i = 0, _a = node.children; _i < _a.length; _i++) {\n var j = _a[_i];\n if (this.nameTable[j] && this.nameTable[j].parentId) {\n var child = getDiagramElement(j + '_groupElement');\n child.parentNode.removeChild(child);\n }\n }\n }\n };\n /** @private */\n Diagram.prototype.updateProcesses = function (node) {\n if (this.bpmnModule && node && node.shape && node.shape.activity &&\n node.shape.activity.subProcess.processes &&\n node.shape.activity.subProcess.processes.length) {\n var processes = node.shape.activity.subProcess.processes;\n this.moveSvgNode(node.id);\n for (var _i = 0, processes_1 = processes; _i < processes_1.length; _i++) {\n var j = processes_1[_i];\n this.moveSvgNode(j);\n var edges = [];\n edges = edges.concat(this.nameTable[j].outEdges, this.nameTable[j].inEdges);\n for (var i = edges.length - 1; i >= 0; i--) {\n this.moveSvgNode(edges[i]);\n }\n }\n for (var _a = 0, processes_2 = processes; _a < processes_2.length; _a++) {\n var j = processes_2[_a];\n if (this.nameTable[j].shape.activity.subProcess.processes &&\n this.nameTable[j].shape.activity.subProcess.processes.length) {\n this.updateProcesses(this.nameTable[j]);\n }\n }\n }\n else {\n this.moveSvgNode(node.id);\n }\n };\n /** @private */\n Diagram.prototype.moveSvgNode = function (nodeId) {\n var child = getDiagramElement(nodeId + '_groupElement');\n var parent = child.parentElement;\n child.parentNode.removeChild(child);\n parent.appendChild(child);\n };\n /**\n * Adds the given annotation to the given node\n * @param annotation Defines the annotation to be added\n * @param node Defines the node to which the annotation has to be added\n */\n Diagram.prototype.addTextAnnotation = function (annotation, node) {\n if (this.bpmnModule) {\n var connector = this.bpmnModule.addAnnotation(node, annotation, this);\n this.initConnectors(connector, this.commandHandler.getObjectLayer(node.id), false);\n this.updateDiagramObject(node);\n }\n };\n /**\n * Splice the InEdge and OutEdge of the for the node with respect to corresponding connectors that is deleting\n */\n Diagram.prototype.spliceConnectorEdges = function (connector, isSource) {\n var node;\n var edges = [];\n node = isSource ? this.nameTable[connector.sourceID] : this.nameTable[connector.targetID];\n if (node) {\n edges = isSource ? node.outEdges : node.inEdges;\n for (var i = edges.length - 1; i >= 0; i--) {\n if (edges[i] === connector.id) {\n edges.splice(i, 1);\n }\n }\n }\n };\n /**\n * Remove the dependent connectors if the node is deleted\n * @private\n */\n Diagram.prototype.removeDependentConnector = function (node) {\n var connector;\n var edges = [];\n edges = edges.concat(node.outEdges, node.inEdges);\n for (var i = edges.length - 1; i >= 0; i--) {\n connector = this.nameTable[edges[i]];\n if (connector) {\n this.connectorTable[connector.id] = cloneObject(connector);\n this.remove(connector);\n }\n }\n };\n Diagram.prototype.removeObjectsFromLayer = function (obj) {\n var layer = this.layers.indexOf(this.commandHandler.getObjectLayer(obj.id));\n var objects = this.layers[layer].objects;\n var objIndex = objects.indexOf(obj.id);\n if (objIndex > -1) {\n if (isSelected(this, obj)) {\n this.unSelect(obj);\n }\n this.layers[layer].objects.splice(objIndex, 1);\n delete this.layers[layer].zIndexTable[this.nameTable[obj.id].zIndex];\n }\n };\n Diagram.prototype.removeElements = function (currentObj) {\n if (this.mode === 'SVG' || (this.mode === 'Canvas' && currentObj.shape.type === 'Native')) {\n var removeElement_1 = getDiagramElement(currentObj.id + '_groupElement');\n if (removeElement_1) {\n removeElement_1.parentNode.removeChild(removeElement_1);\n }\n }\n this.refreshCanvasLayers();\n var children = currentObj.wrapper.children;\n var element;\n var view;\n for (var i = 0; i < children.length; i++) {\n if (children[i] instanceof DiagramNativeElement || ((children[i].id) && (children[i].id).indexOf('icon_content') > 0)) {\n if ((children[i].id).indexOf('icon_content') > 0) {\n element = getDiagramElement(children[i].id + '_shape_groupElement');\n element.parentNode.removeChild(element);\n element = getDiagramElement(children[i].id + '_rect_groupElement');\n element.parentNode.removeChild(element);\n }\n for (var _i = 0, _a = this.views; _i < _a.length; _i++) {\n var elementId = _a[_i];\n removeElement(children[i].id + '_groupElement', elementId);\n }\n }\n else if (children[i] instanceof DiagramHtmlElement) {\n for (var _b = 0, _c = this.views; _b < _c.length; _b++) {\n var elementId = _c[_b];\n removeElement(children[i].id + '_html_element', elementId);\n }\n }\n }\n };\n Diagram.prototype.removeCommand = function () {\n this.remove();\n };\n /**\n * Removes the given object from diagram\n * @param obj Defines the object that has to be removed from diagram\n */\n /* tslint:disable */\n Diagram.prototype.remove = function (obj) {\n var selectedItems = [];\n selectedItems = selectedItems.concat(this.selectedItems.nodes, this.selectedItems.connectors);\n var args;\n var groupAction = false;\n if (obj) {\n obj = this.nameTable[obj.id];\n if (obj && (canDelete(obj) || (this.diagramActions & DiagramAction.Clear))) {\n if (this.bpmnModule) {\n if (this.bpmnModule.checkAndRemoveAnnotations(obj, this)) {\n this.refreshCanvasLayers();\n return;\n }\n }\n args = {\n element: obj, cause: this.diagramActions,\n state: 'Changing', type: 'Removal', cancel: false\n };\n if (!(this.diagramActions & DiagramAction.Clear)) {\n this.triggerEvent(DiagramEvent.collectionChange, args);\n }\n if (!args.cancel) {\n if ((!(this.diagramActions & DiagramAction.UndoRedo)) &&\n (obj instanceof Node || obj instanceof Connector)) {\n var entry = {\n type: 'CollectionChanged', changeType: 'Remove', undoObject: cloneObject(obj),\n redoObject: cloneObject(obj), category: 'Internal'\n };\n if (!(this.diagramActions & DiagramAction.Clear)) {\n if (selectedItems.length > 0 && this.undoRedoModule && !this.layout.type) {\n this.historyList.startGroupAction();\n groupAction = true;\n }\n }\n if (obj instanceof Node) {\n this.removeDependentConnector(obj);\n }\n if (!(this.diagramActions & DiagramAction.Clear)) {\n this.addHistoryEntry(entry);\n }\n }\n if (obj.children) {\n this.deleteGroup(obj);\n }\n if (obj.parentId) {\n this.deleteChild(obj);\n }\n var index = void 0;\n this.diagramActions = this.diagramActions | DiagramAction.PublicMethod;\n var currentObj = this.nameTable[obj.id];\n if (currentObj instanceof Node) {\n if (currentObj.shape.type === 'Bpmn' && this.bpmnModule) {\n this.bpmnModule.removeBpmnProcesses(currentObj, this);\n }\n index = this.nodes.indexOf(currentObj);\n if (index !== -1) {\n this.nodes.splice(index, 1);\n this.updateNodeEdges(currentObj);\n }\n }\n else {\n index = this.connectors.indexOf(currentObj);\n if (index !== -1) {\n this.connectors.splice(index, 1);\n }\n this.updateEdges(currentObj);\n this.spliceConnectorEdges(obj, true);\n this.spliceConnectorEdges(obj, false);\n }\n if (groupAction) {\n this.historyList.endGroupAction();\n }\n if (isSelected(this, currentObj)) {\n this.unSelect(currentObj);\n }\n this.removeObjectsFromLayer(obj);\n if (this.currentDrawingObject) {\n this.currentDrawingObject.wrapper = undefined;\n }\n delete this.nameTable[obj.id];\n this.removeElements(currentObj);\n if (this.mode !== 'SVG') {\n this.refreshDiagramLayer();\n }\n if (!(this.diagramActions & DiagramAction.Clear)) {\n this.removeFromAQuad(currentObj);\n args = {\n element: obj, cause: this.diagramActions,\n state: 'Changed', type: 'Removal', cancel: false\n };\n this.triggerEvent(DiagramEvent.collectionChange, args);\n this.resetTool();\n }\n }\n }\n }\n else if (selectedItems.length > 0) {\n if (this.undoRedoModule) {\n this.historyList.startGroupAction();\n groupAction = true;\n }\n for (var i = 0; i < selectedItems.length; i++) {\n var node = selectedItems[i];\n if (this.nameTable[selectedItems[i].id]) {\n this.remove(selectedItems[i]);\n }\n }\n if (groupAction) {\n this.historyList.endGroupAction();\n }\n this.clearSelection();\n }\n };\n /* tslint:enable */\n /** @private */\n Diagram.prototype.deleteChild = function (node, parentNode) {\n var id;\n parentNode = parentNode ? this.nameTable[parentNode.id] : this.nameTable[node.parentId];\n if (typeof node === 'string') {\n id = node;\n }\n else {\n id = node.id;\n }\n if (parentNode && parentNode.children) {\n for (var i = 0; i < parentNode.children.length; i++) {\n if (parentNode.children[i] === id) {\n parentNode.children.splice(i, 1);\n parentNode.wrapper.children.splice(i, 1);\n }\n }\n parentNode.wrapper.measure(new Size());\n parentNode.wrapper.arrange(parentNode.wrapper.desiredSize);\n }\n };\n /** @private */\n Diagram.prototype.addChild = function (node, child) {\n var id;\n var parentNode = this.nameTable[node.id];\n if (parentNode.children) {\n if (typeof child === 'string') {\n if (this.nameTable[child]) {\n id = child;\n }\n }\n else {\n id = child.id = child.id || randomId();\n this.add(child);\n }\n if (id) {\n var childNode = this.nameTable[id];\n childNode.parentId = parentNode.id;\n parentNode.children.push(id);\n parentNode.wrapper.children.push(this.nameTable[id].wrapper);\n parentNode.wrapper.measure(new Size());\n parentNode.wrapper.arrange(parentNode.wrapper.desiredSize);\n }\n }\n };\n /**\n * Clears all nodes and objects in the diagram\n */\n Diagram.prototype.clear = function () {\n this.clearObjects();\n };\n Diagram.prototype.clearObjects = function (collection) {\n var objects = [];\n if (!collection) {\n objects = objects.concat(this.nodes);\n objects = objects.concat(this.connectors);\n }\n else {\n objects = collection;\n }\n this.diagramActions = this.diagramActions | DiagramAction.Clear;\n for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {\n var obj = objects_1[_i];\n if (this.nameTable[obj.id]) {\n this.remove(obj);\n }\n }\n this.diagramActions = this.diagramActions & ~DiagramAction.Clear;\n this.spatialSearch = new SpatialSearch(this.nameTable);\n this.initHistory();\n };\n Diagram.prototype.startEditCommad = function () {\n this.startTextEdit();\n };\n /**\n * Specified annotation to edit mode\n * @param node Defines node/connector that contains the annotation to be edited\n * @param id Defines annotation id to be edited in the node\n */\n Diagram.prototype.startTextEdit = function (node, id) {\n if (!canZoomPan(this) || canSingleSelect(this)) {\n var minWidth = 90;\n var text = void 0;\n var bounds = void 0;\n var attributes = void 0;\n var x = void 0;\n var y = void 0;\n var textWrapper = void 0;\n var transform = this.scroller.transform;\n if (!node) {\n node = (this.selectedItems.nodes[0]) ? this.selectedItems.nodes[0] : this.selectedItems.connectors[0];\n }\n if (node) {\n var bpmnAnnotation = false;\n if (this.bpmnModule) {\n textWrapper = this.bpmnModule.getTextAnnotationWrapper(node, id);\n if (textWrapper) {\n node = this.nameTable[node.id.split('_textannotation_')[0]];\n }\n }\n if (!textWrapper) {\n if (node.shape.type !== 'Text' && node.annotations.length === 0) {\n this.activeLabel.isGroup = true;\n this.startGroupAction();\n this.addLabels(node, [{ id: randomId(), content: '' }]);\n }\n if (!id && ((node.shape.type !== 'Text' && node.annotations.length > 0) || (node.shape.type === 'Text'))) {\n id = (node.shape.type === 'Text') ? (node.wrapper.children[0].id).split('_')[1] : node.annotations[0].id;\n }\n if (id) {\n textWrapper = this.getWrapper(node.wrapper, id);\n }\n }\n else {\n bpmnAnnotation = true;\n }\n if (node && textWrapper &&\n (!enableReadOnly(textWrapper, node) || bpmnAnnotation)) {\n var style = (textWrapper.style);\n var maxWidth = void 0;\n maxWidth = textWrapper.bounds.width < node.wrapper.bounds.width ? textWrapper.bounds.width : node.wrapper.bounds.width;\n maxWidth = minWidth > maxWidth ? minWidth : maxWidth;\n var textEditing = document.createElement('div');\n var textarea = document.createElement('textarea');\n textEditing.appendChild(textarea);\n text = textWrapper.content;\n bounds = measureHtmlText(textWrapper.style, text, undefined, undefined, maxWidth);\n if (bounds.isEmpty()) {\n if (node.shape.type !== 'Text') {\n bounds = new Size(findAnnotation(node, (textWrapper.id).split(node.id + '_')[1]).width || 50, textWrapper.style.fontSize);\n }\n else {\n bounds = new Size((node.width > 50) ? 50 : node.width, textWrapper.style.fontSize);\n }\n }\n bounds.width = Math.max(bounds.width, 50);\n x = ((((textWrapper.bounds.center.x + transform.tx) * transform.scale) - bounds.width / 2) - 2.5);\n y = ((((textWrapper.bounds.center.y + transform.ty) * transform.scale) - bounds.height / 2) - 3);\n attributes = {\n 'id': this.element.id + '_editTextBoxDiv',\n 'style': 'position: absolute' + ';left:' + x + 'px;top:' + y + 'px;width:' + (bounds.width + 1) +\n 'px;height:' + bounds.height + 'px; containerName:' + node.id + ';'\n };\n setAttributeHtml(textEditing, attributes);\n attributes = {\n 'id': this.element.id + '_editBox',\n 'style': 'width:' + (bounds.width + 1) + 'px;height:' + bounds.height +\n 'px;resize: none;outline: none;overflow: hidden;' +\n 'font-family:' + style.fontFamily + ';font-size:' + style.fontSize + 'px;text-align:' +\n (textWrapper.style.textAlign.toLocaleLowerCase()) + ';',\n 'class': 'e-diagram-text-edit'\n };\n setAttributeHtml(textarea, attributes);\n textarea.style.fontWeight = (style.bold) ? 'bold' : '';\n textarea.style.fontStyle = (style.italic) ? 'italic' : '';\n textarea.style.textDecoration = (style.textDecoration) ? style.textDecoration : '';\n textarea.appendChild(document.createTextNode(text));\n this.activeLabel.parentId = node.id;\n this.activeLabel.id = id;\n textWrapper.visible = false;\n this.updateDiagramObject(node);\n this.diagramActions = this.diagramActions | DiagramAction.TextEdit;\n this.diagramCanvas.appendChild(textEditing);\n EventHandler.add(textarea, 'input', this.eventHandler.inputChange, this.eventHandler);\n EventHandler.add(textarea, 'focusout', this.focusOutEdit, this);\n textarea.focus();\n textarea.select();\n }\n }\n }\n };\n /**\n * Automatically updates the diagram objects based on the type of the layout\n */\n Diagram.prototype.doLayout = function () {\n var update = false;\n var layout;\n var propChange = this.isProtectedOnChange;\n this.protectPropertyChange(true);\n var viewPort = { x: this.scroller.viewPortWidth, y: this.scroller.viewPortHeight };\n if (this.organizationalChartModule) {\n layout = this.organizationalChartModule.updateLayout(this.nodes, this.nameTable, this.layout, viewPort, this.dataSourceSettings.id);\n update = true;\n }\n else if (this.mindMapChartModule) {\n this.mindMapChartModule.updateLayout(this.nodes, this.nameTable, this.layout, viewPort, this.dataSourceSettings.id, this.dataSourceSettings.root);\n update = true;\n }\n else if (this.radialTreeModule) {\n this.radialTreeModule.updateLayout(this.nodes, this.nameTable, this.layout, viewPort);\n update = true;\n }\n else if (this.symmetricalLayoutModule) {\n this.symmetricalLayoutModule.maxIteration = this.layout.maxIteration;\n this.symmetricalLayoutModule.springLength = this.layout.springLength;\n this.symmetricalLayoutModule.springFactor = this.layout.springFactor;\n this.symmetricalLayoutModule.updateLayout(this.nodes, this.connectors, this.symmetricalLayoutModule, this.nameTable, this.layout, viewPort);\n update = true;\n }\n else if (this.complexHierarchicalTreeModule) {\n this.complexHierarchicalTreeModule.doLayout(this.nodes, this.nameTable, this.layout, viewPort);\n update = true;\n }\n if (update) {\n this.preventUpdate = true;\n var connectors = {};\n for (var _i = 0, _a = this.nodes; _i < _a.length; _i++) {\n var obj = _a[_i];\n var node = obj;\n this.updateIcon(node);\n this.updateDefaultLayoutIcons(node);\n this.nodePropertyChange(node, {}, { offsetX: node.offsetX, offsetY: node.offsetY }, true);\n node.wrapper.measure(new Size(node.wrapper.width, node.wrapper.height));\n node.wrapper.arrange(node.wrapper.desiredSize);\n if (node.inEdges.length > 0) {\n for (var j = 0; j < node.inEdges.length; j++) {\n var connector = this.nameTable[node.inEdges[j]];\n connectors[connector.id] = connector;\n }\n }\n if (node.outEdges.length > 0) {\n for (var k = 0; k < node.outEdges.length; k++) {\n var connection = this.nameTable[node.outEdges[k]];\n connectors[connection.id] = connection;\n }\n }\n }\n for (var _b = 0, _c = Object.keys(connectors); _b < _c.length; _b++) {\n var conn = _c[_b];\n var connector = connectors[conn];\n var points = this.getPoints(connector);\n updateConnector(connector, points);\n connector.wrapper.measure(new Size(undefined, undefined));\n connector.wrapper.arrange(connector.wrapper.desiredSize);\n this.updateQuad(connector);\n }\n this.preventUpdate = false;\n this.updatePage();\n this.refreshDiagramLayer();\n }\n if (!propChange) {\n this.protectPropertyChange(propChange);\n }\n return layout;\n };\n /**\n * Serializes the diagram control as a string\n */\n Diagram.prototype.saveDiagram = function () {\n return serialize(this);\n };\n /**\n * Converts the given string as a Diagram Control\n * @param data Defines the behavior of the diagram to be loaded\n */\n Diagram.prototype.loadDiagram = function (data) {\n return deserialize(data, this);\n };\n /**\n * To export Diagram\n * @param options defines the how the image to be exported.\n */\n Diagram.prototype.exportDiagram = function (options) {\n if (this.printandExportModule) {\n var data = this.printandExportModule.exportDiagram(options);\n return data;\n }\n return '';\n };\n /**\n * To print Diagram\n * @param optons defines how the image to be printed.\n */\n Diagram.prototype.print = function (options) {\n if (this.printandExportModule) {\n this.printandExportModule.print(options);\n }\n };\n /**\n * Add ports at the run time\n */\n Diagram.prototype.addPorts = function (obj, ports) {\n var newObj;\n if (ports.length > 1) {\n this.startGroupAction();\n }\n for (var i = 0; i < ports.length; i++) {\n newObj = new PointPort(obj, 'ports', ports[i], true);\n obj.ports.push(newObj);\n var canvas = obj.wrapper;\n canvas.children.push(obj.initPortWrapper(obj.ports[obj.ports.length - 1]));\n if (!(this.diagramActions & DiagramAction.UndoRedo) && !(this.diagramActions & DiagramAction.Group)) {\n var entry = {\n type: 'PortCollectionChanged', changeType: 'Insert', undoObject: cloneObject(newObj),\n redoObject: cloneObject(obj), category: 'Internal'\n };\n this.addHistoryEntry(entry);\n }\n }\n if (ports.length > 1) {\n this.endGroupAction();\n }\n obj.wrapper.measure(new Size(obj.width, obj.height));\n obj.wrapper.arrange(obj.wrapper.desiredSize);\n this.updateDiagramObject(obj);\n };\n /**\n * Add Labels at the run time\n */\n Diagram.prototype.addLabels = function (obj, labels) {\n var canvas = obj.wrapper;\n var newObj;\n if (labels.length > 1) {\n this.startGroupAction();\n }\n for (var i = 0; i < labels.length; i++) {\n if (obj instanceof Node) {\n newObj = new ShapeAnnotation(obj, 'annotations', labels[i], true);\n obj.annotations.push(newObj);\n if (obj.children) {\n var node = obj;\n for (var i_1 = 0; i_1 < node.wrapper.children.length; i_1++) {\n if (node.wrapper.children[i_1].id === 'group_container') {\n var container = node.wrapper.children[i_1];\n container.children.push(obj.initAnnotationWrapper(obj.annotations[obj.annotations.length - 1]));\n }\n }\n }\n else {\n canvas.children.push(obj.initAnnotationWrapper(obj.annotations[obj.annotations.length - 1]));\n }\n }\n else if (obj instanceof Connector) {\n newObj = new PathAnnotation(obj, 'annotations', labels[i], true);\n obj.annotations.push(newObj);\n var segment = canvas.children[0];\n var bounds = new Rect(segment.offsetX - segment.width / 2, segment.offsetY - segment.height / 2, segment.width, segment.height);\n canvas.children.push(obj.getAnnotationElement(obj.annotations[obj.annotations.length - 1], obj.intermediatePoints, bounds, this.getDescription));\n }\n if (!(this.diagramActions & DiagramAction.UndoRedo) && !(this.diagramActions & DiagramAction.Group)) {\n var entry = {\n type: 'LabelCollectionChanged', changeType: 'Insert', undoObject: cloneObject(newObj),\n redoObject: cloneObject(obj), category: 'Internal'\n };\n this.addHistoryEntry(entry);\n }\n }\n if (labels.length > 1) {\n this.endGroupAction();\n }\n obj.wrapper.measure(new Size(canvas.width, canvas.height));\n obj.wrapper.arrange(canvas.desiredSize);\n this.updateDiagramObject(obj);\n };\n /**\n * Remove Labels at the run time\n */\n Diagram.prototype.removeLabels = function (obj, labels) {\n if (labels.length > 1) {\n this.startGroupAction();\n }\n for (var j = labels.length - 1; j >= 0; j--) {\n for (var i = 0; i < obj.wrapper.children.length; i++) {\n var canvas = obj.wrapper.children[i];\n if (canvas instanceof TextElement) {\n if (canvas.id.match('_' + labels[j].id + '$')) {\n for (var k = 0; k < obj.annotations.length; k++) {\n if (canvas.id.match('_' + obj.annotations[k].id + '$')) {\n if (!(this.diagramActions & DiagramAction.UndoRedo)) {\n var entry = {\n type: 'LabelCollectionChanged', changeType: 'Remove', undoObject: cloneObject(obj.annotations[k]),\n redoObject: cloneObject(obj), category: 'Internal'\n };\n this.addHistoryEntry(entry);\n }\n obj.annotations.splice(k, 1);\n }\n }\n obj.wrapper.children.splice(i, 1);\n if (this.mode === 'SVG') {\n var element = getDiagramElement(canvas.id);\n if (element) {\n var element_1 = getDiagramElement(canvas.id);\n element_1.parentNode.removeChild(element_1);\n }\n var textElement = getDiagramElement(canvas.id + '_text');\n if (textElement) {\n element = getDiagramElement(canvas.id + '_text');\n element.parentNode.removeChild(element);\n }\n }\n else {\n this.refreshCanvasLayers();\n }\n }\n }\n }\n }\n if (labels.length > 1) {\n this.endGroupAction();\n }\n };\n /**\n * Remove Ports at the run time\n */\n Diagram.prototype.removePorts = function (obj, ports) {\n if (ports.length > 1) {\n this.startGroupAction();\n }\n for (var j = 0; j < ports.length; j++) {\n for (var i = 0; i < obj.wrapper.children.length; i++) {\n var canvas = obj.wrapper.children[i];\n if (canvas instanceof PathElement) {\n if (canvas.id.match('_' + ports[j].id + '$')) {\n for (var k = 0; k < obj.ports.length; k++) {\n if (canvas.id.match('_' + obj.ports[k].id + '$')) {\n if (!(this.diagramActions & DiagramAction.UndoRedo)) {\n var entry = {\n type: 'PortCollectionChanged', changeType: 'Remove', undoObject: cloneObject(obj.ports[k]),\n redoObject: cloneObject(obj), category: 'Internal'\n };\n this.addHistoryEntry(entry);\n }\n obj.ports.splice(k, 1);\n }\n }\n obj.wrapper.children.splice(i, 1);\n if (this.mode === 'SVG') {\n var element = getDiagramElement(canvas.id);\n element.parentNode.removeChild(element);\n }\n else {\n this.refreshCanvasLayers();\n }\n }\n }\n }\n }\n if (ports.length > 1) {\n this.endGroupAction();\n }\n };\n //public methods - end region\n //helper methods - start region\n /**\n * @private\n * @param real\n * @param rulerSize\n */\n Diagram.prototype.getSizeValue = function (real, rulerSize) {\n var value;\n if (real.toString().indexOf('px') > 0) {\n value = real.toString();\n }\n else if (real.toString().indexOf('%') > 0) {\n value = rulerSize !== undefined ? '100%' : real.toString();\n }\n else {\n value = real.toString() + 'px';\n }\n if (rulerSize) {\n var position = getRulerSize(this);\n value = 'calc(' + value + ' - ' + rulerSize + 'px)';\n }\n return value;\n };\n Diagram.prototype.renderRulers = function () {\n if (this.rulerSettings.showRulers) {\n renderOverlapElement(this);\n renderRuler(this, true);\n renderRuler(this, false);\n }\n else {\n removeRulerElements(this);\n }\n };\n Diagram.prototype.intOffPageBackground = function () {\n var position = new Size();\n position = getRulerSize(this);\n var element = document.getElementById(this.element.id + 'content');\n var width = this.getSizeValue(this.width, position.width);\n var height = this.getSizeValue(this.height, position.height);\n var style = this.rulerSettings.showRulers ?\n 'width:' + width + '; height:' + height + ';' +\n 'top:' + position.height + 'px;left:' + position.width + 'px;' +\n 'overflow: scroll;position:absolute;overflow:auto;' :\n 'width:' + width + '; height:' + height + ';position:absolute;' +\n ' left:0px; top:0px;overflow: auto;';\n var attr = {\n 'id': this.element.id + 'content',\n 'tabindex': '0',\n 'style': style\n };\n if (!element) {\n this.diagramCanvas = createHtmlElement('div', attr);\n this.element.appendChild(this.diagramCanvas);\n }\n else {\n this.diagramCanvas = element;\n this.diagramCanvas.setAttribute('style', style);\n }\n this.diagramCanvas.style.background = this.backgroundColor;\n };\n Diagram.prototype.initDiagram = function () {\n this.intOffPageBackground();\n setAttributeHtml(this.element, {\n style: 'width:' + this.getSizeValue(this.width) + '; height:'\n + this.getSizeValue(this.height) + ';position:relative;overflow:hidden;'\n });\n };\n ;\n Diagram.prototype.renderBackgroundLayer = function (bounds, commonStyle) {\n var bgLayer = this.createSvg(this.element.id + '_backgroundLayer_svg', bounds.width, bounds.height);\n bgLayer.setAttribute('style', commonStyle);\n var backgroundImage = createSvgElement('g', {\n 'id': this.element.id + '_backgroundImageLayer',\n 'class': 'e-background-image-layer'\n });\n bgLayer.appendChild(backgroundImage);\n var attr = { 'id': this.element.id + '_backgroundLayer', 'class': 'e-background-layer' };\n var background = createSvgElement('g', attr);\n bgLayer.appendChild(background);\n this.diagramCanvas.appendChild(bgLayer);\n };\n Diagram.prototype.renderGridLayer = function (bounds, commonStyle) {\n var svgGridSvg = this.createSvg(this.element.id + '_gridline_svg', bounds.width, bounds.height);\n svgGridSvg.setAttribute('class', 'e-grid-layer');\n var svgGrid = createSvgElement('g', { 'id': this.element.id + '_gridline', 'width': '100%', 'height': '100%' });\n var rect = createSvgElement('rect', {\n 'id': this.element.id + '_grid_rect', 'x': '0', 'y': '0', 'width': '100%', 'height': '100%',\n 'fill': 'url(#' + this.element.id + '_pattern)'\n });\n svgGrid.appendChild(rect);\n svgGridSvg.appendChild(svgGrid);\n this.diagramCanvas.appendChild(svgGridSvg);\n setAttributeSvg(svgGridSvg, { 'style': commonStyle });\n };\n Diagram.prototype.renderDiagramLayer = function (bounds, commonStyle) {\n var attributes;\n this.diagramLayerDiv = document.createElement('div');\n attributes = {\n 'id': this.element.id + '_diagramLayer_div',\n 'style': 'width:' + bounds.width + 'px; height:' + bounds.height + 'px;' + commonStyle\n };\n setAttributeHtml(this.diagramLayerDiv, attributes);\n if (this.mode === 'SVG') {\n var diagramSvg = this.createSvg(this.element.id + '_diagramLayer_svg', bounds.width, bounds.height);\n diagramSvg.setAttribute('style', ' pointer-events: none; ');\n diagramSvg.setAttribute('class', 'e-diagram-layer');\n var diagramLayer = createSvgElement('g', { 'id': this.element.id + '_diagramLayer' });\n var transformationLayer = createSvgElement('g', {});\n this.diagramLayer = diagramLayer;\n diagramLayer.setAttribute('style', 'pointer-events: all;');\n transformationLayer.appendChild(diagramLayer);\n diagramSvg.appendChild(transformationLayer);\n this.diagramLayerDiv.appendChild(diagramSvg);\n }\n else {\n this.diagramLayer = CanvasRenderer.createCanvas(this.element.id + '_diagram', bounds.width, bounds.height);\n this.diagramLayer.setAttribute('style', 'position:absolute;left:0px;top:0px;');\n this.diagramLayerDiv.appendChild(this.diagramLayer);\n }\n this.diagramCanvas.appendChild(this.diagramLayerDiv);\n };\n Diagram.prototype.initLayers = function () {\n var commonStyle = 'position:absolute;top:0px;left:0px;overflow:hidden;pointer-events:none;';\n var container = document.getElementById(this.element.id);\n var bounds = container.getBoundingClientRect();\n var scrollerSize = getScrollerWidth();\n this.scroller.scrollerWidth = scrollerSize;\n this.scroller.setViewPortSize(bounds.width, bounds.height);\n this.renderRulers();\n createMeasureElements();\n // this.renderBackgroundImageLayer(bounds, commonStyle);\n this.renderBackgroundLayer(bounds, commonStyle);\n this.renderGridLayer(bounds, commonStyle);\n this.renderDiagramLayer(bounds, commonStyle);\n this.renderHTMLLayer(bounds, commonStyle);\n this.renderPortsExpandLayer(bounds, commonStyle);\n this.renderNativeLayer(bounds, commonStyle);\n this.renderAdornerLayer(bounds, commonStyle);\n };\n Diagram.prototype.renderAdornerLayer = function (bounds, commonStyle) {\n var divElement = createHtmlElement('div', {\n 'id': this.element.id + '_diagramAdornerLayer',\n 'style': 'width:' + bounds.width + 'px;height:' + bounds.height + 'px;' + commonStyle\n });\n var svgAdornerSvg = this.createSvg(this.element.id + '_diagramAdorner_svg', bounds.width, bounds.height);\n svgAdornerSvg.setAttribute('class', 'e-adorner-layer');\n svgAdornerSvg.setAttribute('style', 'pointer-events:none;');\n this.adornerLayer = createSvgElement('g', { 'id': this.element.id + '_diagramAdorner' });\n this.adornerLayer.setAttribute('style', ' pointer-events: all; ');\n svgAdornerSvg.appendChild(this.adornerLayer);\n divElement.appendChild(svgAdornerSvg);\n this.diagramCanvas.appendChild(divElement);\n var svgSelector = createSvgElement('g', { 'id': this.element.id + '_SelectorElement' });\n this.adornerLayer.appendChild(svgSelector);\n setAttributeSvg(svgAdornerSvg, { style: 'pointer-events:none;' });\n };\n Diagram.prototype.renderPortsExpandLayer = function (bounds, commonStyle) {\n var svgPortsSvg = this.createSvg(this.element.id + '_diagramPorts_svg', bounds.width, bounds.height);\n svgPortsSvg.setAttribute('class', 'e-ports-expand-layer');\n var svgPortsLayer = createSvgElement('g', {\n 'id': this.element.id + '_diagramPorts',\n 'class': 'e-ports-layer',\n 'style': 'pointer-events: all;'\n });\n svgPortsSvg.appendChild(svgPortsLayer);\n var svgExpandLayer = createSvgElement('g', {\n 'id': this.element.id + '_diagramExpander',\n 'class': 'e-expand-layer',\n 'style': 'pointer-events: all;'\n });\n svgPortsSvg.appendChild(svgExpandLayer);\n this.diagramCanvas.appendChild(svgPortsSvg);\n setAttributeSvg(svgPortsSvg, { 'style': commonStyle });\n };\n Diagram.prototype.renderHTMLLayer = function (bounds, commonStyle) {\n this.htmlLayer = createHtmlElement('div', {\n 'id': this.element.id + '_htmlLayer',\n 'style': 'width:' + bounds.width + 'px; height:' + bounds.height + 'px;position:absolute;top:0px;' +\n 'left:0px;overflow:hidden;pointer-events:none;',\n 'class': 'e-html-layer'\n });\n var htmlLayerDiv = createHtmlElement('div', {\n 'id': this.element.id + '_htmlLayer_div',\n 'style': 'position:absolute;top:0px;left:0px;pointer-events:all;'\n });\n this.htmlLayer.appendChild(htmlLayerDiv);\n this.diagramCanvas.appendChild(this.htmlLayer);\n };\n Diagram.prototype.renderNativeLayer = function (bounds, commonStyle) {\n var nativeLayerSvg = this.createSvg(this.element.id + '_nativeLayer_svg', bounds.width, bounds.height);\n var nativeLayer = createSvgElement('g', { 'id': this.element.id + '_nativeLayer', 'style': 'pointer-events:all;' });\n nativeLayerSvg.appendChild(nativeLayer);\n this.diagramLayerDiv.appendChild(nativeLayerSvg);\n setAttributeSvg(nativeLayerSvg, { 'class': 'e-native-layer', 'style': commonStyle });\n };\n Diagram.prototype.createSvg = function (id, width, height) {\n var svgObj = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n setAttributeSvg(svgObj, { 'id': id, 'width': width, 'height': height });\n return svgObj;\n };\n Diagram.prototype.initObjects = function (isLoad) {\n if (!this.isLoading) {\n this.initData();\n }\n this.initLayerObjects();\n this.updateBridging(isLoad);\n };\n Diagram.prototype.initLayerObjects = function () {\n var hasLayers = this.layers.length > 1;\n var set = false;\n var connectors = [];\n var tempTabel = {};\n var bpmnTable = {};\n var tempNode = [];\n var groups = [];\n var i = 0;\n for (var _i = 0, _a = this.nodes; _i < _a.length; _i++) {\n var obj = _a[_i];\n obj.id = obj.id || randomId();\n this.addToLayer(obj, hasLayers);\n tempTabel[obj.id] = obj;\n }\n for (var _b = 0, _c = this.connectors; _b < _c.length; _b++) {\n var obj = _c[_b];\n obj.id = obj.id || randomId();\n this.addToLayer(obj, hasLayers);\n tempTabel[obj.id] = obj;\n }\n for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {\n var layer = _e[_d];\n for (var _f = 0, _g = layer.objects; _f < _g.length; _f++) {\n var obj = _g[_f];\n if (tempTabel[obj]) {\n if (!(tempTabel[obj] instanceof Connector)) {\n if (tempTabel[obj].children) {\n groups.push(obj);\n }\n else if ((tempTabel[obj].shape instanceof BpmnShape) &&\n tempTabel[obj].shape.activity.subProcess.processes &&\n tempTabel[obj].shape.activity.subProcess.processes.length > 0) {\n bpmnTable[tempTabel[obj].id] = obj;\n }\n else {\n this.initNodes(tempTabel[obj], layer);\n }\n }\n else {\n var connector = tempTabel[obj];\n if (connector.sourceID && connector.targetID) {\n var sourceNode = tempTabel[connector.sourceID];\n var targetNode = tempTabel[connector.targetID];\n if (sourceNode && sourceNode.wrapper && targetNode && targetNode.wrapper) {\n this.initConnectors(tempTabel[obj], layer);\n }\n else {\n connectors.push(tempTabel[obj]);\n }\n }\n else {\n this.initConnectors(tempTabel[obj], layer);\n }\n }\n }\n }\n if (this.bpmnModule) {\n for (var _h = 0, _j = this.bpmnModule.textAnnotationConnectors; _h < _j.length; _h++) {\n var obj = _j[_h];\n this.initConnectors(obj, layer, false);\n }\n }\n }\n for (var _k = 0, _l = Object.keys(bpmnTable); _k < _l.length; _k++) {\n var obj = _l[_k];\n this.initObject(tempTabel[obj]);\n this.bpmnModule.updateDocks(tempTabel[obj], this);\n }\n for (var _m = 0, groups_1 = groups; _m < groups_1.length; _m++) {\n var obj = groups_1[_m];\n var layer = this.commandHandler.getObjectLayer(obj);\n this.initNodes(tempTabel[obj], layer);\n }\n for (var _o = 0, connectors_1 = connectors; _o < connectors_1.length; _o++) {\n var connector = connectors_1[_o];\n var layer = this.commandHandler.getObjectLayer(connector.id);\n this.initConnectors(connector, layer);\n }\n };\n Diagram.prototype.addToLayer = function (obj, hasLayers) {\n var layer;\n if (hasLayers) {\n layer = this.commandHandler.getObjectLayer(obj.id);\n }\n if (!hasLayers || !layer) {\n if (this.activeLayer.objects.indexOf(obj.id) === -1) {\n this.activeLayer.objects.push(obj.id);\n }\n }\n this.setZIndex(layer || this.activeLayer, obj);\n };\n Diagram.prototype.updateLayer = function (newProp) {\n for (var _i = 0, _a = Object.keys(newProp.layers); _i < _a.length; _i++) {\n var key = _a[_i];\n var layerObject = this.layers[key].objects;\n for (var _b = 0, layerObject_1 = layerObject; _b < layerObject_1.length; _b++) {\n var obj = layerObject_1[_b];\n var node = this.nameTable[obj];\n if (newProp.layers[key].visible !== undefined) {\n this.updateElementVisibility(node.wrapper, node, newProp.layers[key].visible);\n }\n else if (newProp.layers[key].lock === true) {\n this.unSelect(node);\n }\n }\n if (newProp.layers[key].lock !== undefined) {\n this.layers[key].lock = newProp.layers[key].lock;\n }\n }\n if (this.mode !== 'SVG') {\n this.refreshDiagramLayer();\n }\n };\n Diagram.prototype.updateScrollSettings = function (newProp) {\n var hPan = (-this.scroller.horizontalOffset + newProp.scrollSettings.horizontalOffset || 0);\n var vPan = (this.scroller.verticalOffset - newProp.scrollSettings.verticalOffset || 0);\n var oldValue = {\n VerticalOffset: this.scrollSettings.verticalOffset, HorizontalOffset: this.scrollSettings.horizontalOffset,\n ViewportHeight: this.scrollSettings.viewPortHeight, ViewportWidth: this.scrollSettings.viewPortWidth,\n CurrentZoom: this.scroller.currentZoom\n };\n if (hPan !== 0 || vPan !== 0) {\n this.pan(hPan, vPan);\n }\n var newValue = {\n VerticalOffset: this.scrollSettings.verticalOffset, HorizontalOffset: this.scrollSettings.horizontalOffset,\n ViewportHeight: this.scrollSettings.viewPortHeight, ViewportWidth: this.scrollSettings.viewPortWidth,\n CurrentZoom: this.scroller.currentZoom\n };\n var arg = {\n oldValue: oldValue, newValue: newValue, source: this\n };\n this.triggerEvent(DiagramEvent.scrollChange, arg);\n };\n Diagram.prototype.initData = function () {\n if (this.dataBindingModule) {\n if (this.dataSourceSettings.dataManager && this.dataSourceSettings.dataManager.dataSource &&\n this.dataSourceSettings.dataManager.dataSource.url !== undefined) {\n this.dataBindingModule.initSource(this.dataSourceSettings, this);\n }\n else {\n this.dataBindingModule.initData(this.dataSourceSettings, this);\n }\n }\n };\n Diagram.prototype.initNodes = function (obj, layer) {\n this.preventUpdate = true;\n this.initObject(obj, layer);\n this.preventUpdate = false;\n };\n Diagram.prototype.initConnectors = function (obj, layer, independentObj) {\n this.preventUpdate = true;\n this.initObject(obj, layer, independentObj);\n this.updateEdges(obj);\n this.preventUpdate = false;\n };\n Diagram.prototype.setZIndex = function (layer, obj) {\n //should be changed\n var currentLayer = layer;\n if ((obj).zIndex === -1) {\n while (currentLayer.zIndexTable[currentLayer.objectZIndex + 1]) {\n layer.objectZIndex++;\n }\n obj.zIndex = ++currentLayer.objectZIndex;\n }\n else {\n var index = obj.zIndex;\n if (currentLayer.zIndexTable[index]) {\n var tabelLength = Object.keys(currentLayer.zIndexTable).length;\n var j = 0;\n for (var i = 0; i < tabelLength; i++) {\n if (i === index) {\n for (var j_1 = tabelLength; j_1 > index; j_1--) {\n currentLayer.zIndexTable[j_1] = currentLayer.zIndexTable[j_1 - 1];\n if (this.nameTable[currentLayer.zIndexTable[j_1]]) {\n this.nameTable[currentLayer.zIndexTable[j_1]].zIndex = j_1;\n }\n }\n currentLayer.zIndexTable[i] = obj.id;\n }\n j++;\n }\n }\n }\n };\n Diagram.prototype.initializeDiagramLayers = function () {\n for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {\n var layer = _a[_i];\n layer.zIndex = this.layers.indexOf(layer);\n this.layerZIndexTable[layer.zIndex] = layer.id;\n }\n if (this.layers.length === 0) {\n var defaultLayer = {\n id: 'default_layer', visible: true, lock: false, objects: [], zIndex: 0,\n objectZIndex: -1, zIndexTable: {}\n };\n this.commandHandler.addLayer(defaultLayer);\n }\n this.setActiveLayer(this.layers[this.layers.length - 1].id);\n };\n /** @private */\n Diagram.prototype.resetTool = function () {\n this.eventHandler.resetTool();\n };\n /** @private */\n Diagram.prototype.initObject = function (obj, layer, independentObj) {\n if (independentObj === void 0) { independentObj = true; }\n if (obj !== undefined) {\n if (independentObj) {\n if (!layer) {\n this.addToLayer(obj, false);\n layer = this.activeLayer;\n }\n //Move the common properties like zindex and id to an abstract class\n if (obj instanceof Node || obj instanceof Connector) {\n this.setZIndex(layer, obj);\n }\n }\n if (obj instanceof Node) {\n if (independentObj) {\n var getDefaults = getFunction(this.getNodeDefaults);\n if (getDefaults) {\n var defaults = getDefaults(obj, this);\n if (defaults && defaults !== obj) {\n extendObject(defaults, obj);\n }\n }\n this.initNode(obj, this.element.id);\n }\n }\n else if (obj instanceof Connector) {\n var getDefaults = getFunction(this.getConnectorDefaults);\n if (getDefaults) {\n var defaults = getDefaults(obj, this);\n if (defaults && defaults !== obj) {\n extendObject(defaults, obj);\n }\n if (obj.segments.length) {\n if (obj.type !== obj.segments[0].type) {\n obj.segments = [];\n }\n }\n }\n var sourceNode = this.nameTable[obj.sourceID];\n var targetNode = this.nameTable[obj.targetID];\n if (sourceNode !== undefined && canOutConnect(sourceNode)) {\n obj.sourceWrapper = this.getEndNodeWrapper(sourceNode, obj, true);\n if (obj.sourcePortID) {\n obj.sourcePortWrapper = this.getWrapper(sourceNode.wrapper, obj.sourcePortID);\n }\n }\n if (targetNode !== undefined && canInConnect(targetNode)) {\n obj.targetWrapper = this.getEndNodeWrapper(targetNode, obj, false);\n if (obj.targetPortID) {\n obj.targetPortWrapper = this.getWrapper(targetNode.wrapper, obj.targetPortID);\n }\n }\n if (!independentObj) {\n var points = obj.getConnectorPoints(obj.type);\n updateConnector(obj, points);\n }\n if (independentObj) {\n obj.init(this);\n }\n obj.wrapper.measure(new Size(undefined, undefined));\n obj.wrapper.arrange(obj.wrapper.desiredSize);\n }\n if (this.bpmnModule && obj instanceof Node\n && obj.shape.type === 'Bpmn' && obj.shape.annotations.length > 0) {\n this.bpmnModule.updateQuad(obj, this);\n }\n if (independentObj) {\n var checkBoundaryConstraints = this.commandHandler.checkBoundaryConstraints(undefined, undefined, obj.wrapper.bounds);\n if (!checkBoundaryConstraints) {\n var node = obj instanceof Node ? this.nodes : this.connectors;\n for (var i = 0; i <= node.length; i++) {\n if (node[i] && obj.id === node[i].id) {\n node.splice(i, 1);\n }\n }\n }\n layer.zIndexTable[obj.zIndex] = obj.id;\n }\n this.nameTable[obj.id] = obj;\n if (obj instanceof Node && obj.children) {\n this.updateGroupOffset(obj);\n this.groupTable[obj.id] = obj.children;\n for (var i = 0; i < obj.children.length; i++) {\n var node = (this.nameTable[obj.children[i]]);\n node.parentId = obj.id;\n }\n if (!this.isLoading && obj.rotateAngle) {\n this.commandHandler.rotateObjects(obj, [obj], obj.rotateAngle, { x: obj.offsetX, y: obj.offsetY }, false);\n }\n }\n this.updateQuad(obj);\n }\n if (obj.visible === false) {\n this.updateElementVisibility(obj.wrapper, obj, false);\n }\n };\n Diagram.prototype.updateDefaultLayoutIcons = function (node) {\n if (this.layout.type === 'OrganizationalChart' || this.layout.type === 'HierarchicalTree' ||\n this.layout.type === 'ComplexHierarchicalTree') {\n {\n this.updateDefaultLayoutIcon(node, node.expandIcon);\n this.updateDefaultLayoutIcon(node, node.collapseIcon);\n }\n }\n };\n Diagram.prototype.updateDefaultLayoutIcon = function (node, icon) {\n if (icon.shape !== 'None') {\n if (icon.horizontalAlignment === 'Auto' && icon.verticalAlignment === 'Auto' &&\n icon.offset.x === .5 && icon.offset.y === 1) {\n var iconWrapper = this.getWrapper(node.wrapper, 'icon_content');\n var offsetX = void 0;\n var offsetY = void 0;\n if (this.layout.orientation === 'TopToBottom' || this.layout.orientation === 'BottomToTop') {\n offsetX = .5;\n offsetY = this.layout.orientation === 'TopToBottom' ? 1 : 0;\n }\n else if (this.layout.orientation === 'RightToLeft' || this.layout.orientation === 'LeftToRight') {\n offsetX = this.layout.orientation === 'LeftToRight' ? 1 : 0;\n offsetY = .5;\n }\n iconWrapper.setOffsetWithRespectToBounds(offsetX, offsetY, 'Fraction');\n iconWrapper.horizontalAlignment = 'Center';\n iconWrapper.verticalAlignment = 'Center';\n node.wrapper.measure(new Size(node.wrapper.width, node.wrapper.height));\n node.wrapper.arrange(node.wrapper.desiredSize);\n }\n }\n };\n /**\n * @private\n */\n Diagram.prototype.updateGroupOffset = function (node) {\n if ((node.children && node.children.length > 0) || (node.processId)) {\n this.nameTable[node.id].offsetX = node.wrapper.offsetX;\n this.nameTable[node.id].offsetY = node.wrapper.offsetY;\n if ((node.children && node.children.length > 0)) {\n this.nameTable[node.id].width = node.wrapper.actualSize.width;\n this.nameTable[node.id].height = node.wrapper.actualSize.height;\n }\n }\n };\n Diagram.prototype.initNode = function (obj, diagramId) {\n var canvas = obj.initContainer();\n var portContainer = new Canvas();\n var content;\n if (!canvas.children) {\n canvas.children = [];\n }\n if (obj.children) {\n canvas.measureChildren = false;\n for (var i = 0; i < obj.children.length; i++) {\n if (this.nameTable[obj.children[i]]) {\n canvas.children.push(this.nameTable[obj.children[i]].wrapper);\n }\n }\n portContainer.id = 'group_container';\n portContainer.style.fill = 'none';\n portContainer.style.strokeColor = 'none';\n portContainer.horizontalAlignment = 'Stretch';\n portContainer.verticalAlignment = 'Stretch';\n portContainer.children = [];\n canvas.children.push(portContainer);\n }\n else {\n var setNodeTemplate = getFunction(this.setNodeTemplate);\n if (setNodeTemplate) {\n content = setNodeTemplate(obj, this);\n }\n if (!content) {\n content = obj.init(this);\n }\n canvas.children.push(content);\n }\n // tslint:disable-next-line:no-any\n var wrapperContent;\n wrapperContent = getFunction(this.getDescription);\n if (wrapperContent) {\n (obj.children ? canvas : content).description = wrapperContent;\n }\n else {\n (obj.children ? canvas : content).description = obj.annotations.length ? obj.annotations[0].content : obj.id;\n }\n var container = obj.children ? portContainer : canvas;\n obj.initAnnotations(this.getDescription, container);\n obj.initPorts(this.getDescription, container);\n obj.initIcons(this.getDescription, this.layout, container, diagramId);\n canvas.measure(new Size(obj.width, obj.height));\n canvas.arrange(canvas.desiredSize);\n };\n Diagram.prototype.canExecute = function () {\n return true;\n };\n Diagram.prototype.initViews = function () {\n if (!this.isLoading) {\n this.views.push(this.element.id);\n this.views[this.element.id] = this;\n }\n };\n Diagram.prototype.initCommands = function () {\n var i;\n var newCommands = this.commandManager.commands;\n var commands = {\n 'copy': {\n execute: this.copyCommand.bind(this), canExecute: this.canExecute.bind(this),\n gesture: { key: Keys.C, keyModifiers: KeyModifiers.Control }\n },\n 'paste': {\n execute: this.pasteCommand.bind(this), canExecute: this.canExecute.bind(this),\n gesture: { key: Keys.V, keyModifiers: KeyModifiers.Control }\n },\n 'cut': {\n execute: this.cutCommand.bind(this), canExecute: this.canExecute.bind(this),\n gesture: { key: Keys.X, keyModifiers: KeyModifiers.Control }\n },\n 'delete': {\n execute: this.removeCommand.bind(this), canExecute: this.canExecute.bind(this),\n gesture: { key: Keys.Delete }\n },\n 'selectAll': {\n execute: this.selectAll.bind(this), canExecute: this.canExecute.bind(this),\n gesture: { key: Keys.A, keyModifiers: KeyModifiers.Control }\n },\n 'undo': {\n execute: this.undo.bind(this), canExecute: this.canExecute.bind(this),\n gesture: { key: Keys.Z, keyModifiers: KeyModifiers.Control }\n },\n 'redo': {\n execute: this.redo.bind(this), canExecute: this.canExecute.bind(this),\n gesture: { key: Keys.Y, keyModifiers: KeyModifiers.Control }\n },\n 'nudgeUp': {\n execute: this.nudgeCommand.bind(this, 'Up'),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Up },\n parameter: 'up'\n },\n 'nudgeRight': {\n execute: this.nudgeCommand.bind(this, 'Right'),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Right },\n parameter: 'right'\n },\n 'nudgeDown': {\n execute: this.nudgeCommand.bind(this, 'Down'),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Down },\n parameter: 'down'\n },\n 'nudgeLeft': {\n execute: this.nudgeCommand.bind(this, 'Left'),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Left },\n parameter: 'left'\n },\n 'startEdit': {\n execute: this.startEditCommad.bind(this),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.F2 }\n },\n 'endEdit': {\n execute: this.endEditCommand.bind(this),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Escape }\n },\n 'focusToNextItem': {\n // execute: this.focusToItem.bind(this),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Tab }\n },\n 'focusToPreviousItem': {\n // execute: this.focusToItem.bind(this),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Tab, keyModifiers: KeyModifiers.Control }\n },\n 'selectFocusedItem': {\n execute: this.startEditCommad.bind(this),\n canExecute: this.canExecute.bind(this), gesture: { key: Keys.Enter }\n },\n };\n this.initCommandManager(newCommands, commands);\n };\n Diagram.prototype.overrideCommands = function (newCommand, commands) {\n var command;\n for (var _i = 0, _a = Object.keys(commands); _i < _a.length; _i++) {\n var key = _a[_i];\n command = commands[key];\n if (newCommand.gesture.key === command.gesture.key && newCommand.gesture.keyModifiers === command.gesture.keyModifiers) {\n delete commands[key];\n break;\n }\n }\n };\n Diagram.prototype.initCommandManager = function (newCommands, commands) {\n var i = 0;\n if (newCommands) {\n for (i = 0; i < newCommands.length; i++) {\n if (commands[newCommands[i].name] && newCommands[i]) {\n if (newCommands[i].canExecute) {\n commands[newCommands[i].name].canExecute = newCommands[i].canExecute;\n }\n if (newCommands[i].execute) {\n commands[newCommands[i].name].execute = newCommands[i].execute;\n }\n if (newCommands[i].gesture.key || newCommands[i].gesture.keyModifiers) {\n commands[newCommands[i].name].gesture = newCommands[i].gesture;\n }\n if (newCommands[i].parameter !== '') {\n commands[newCommands[i].name].parameter = newCommands[i].parameter;\n }\n }\n else {\n this.overrideCommands(newCommands[i], commands);\n commands[newCommands[i].name] = {\n execute: newCommands[i].execute, canExecute: newCommands[i].canExecute, gesture: newCommands[i].gesture,\n parameter: newCommands[i].parameter\n };\n }\n }\n }\n this.commands = commands;\n };\n /** @private */\n Diagram.prototype.updateNodeEdges = function (node) {\n for (var _i = 0, _a = node.inEdges; _i < _a.length; _i++) {\n var edge = _a[_i];\n if (this.nameTable[edge]) {\n this.nameTable[edge].targetID = '';\n }\n }\n for (var _b = 0, _c = node.outEdges; _b < _c.length; _b++) {\n var edge = _c[_b];\n if (this.nameTable[edge]) {\n this.nameTable[edge].sourceID = '';\n }\n }\n node.inEdges = [];\n node.outEdges = [];\n };\n /** @private */\n Diagram.prototype.updateIconVisibility = function (node, visibility) {\n for (var i = 0; i < node.wrapper.children.length; i++) {\n var child = node.wrapper.children[i];\n var id = child.id.split(node.id)[1];\n if (child.id && id && id.match('^_icon')) {\n child.visible = visibility;\n this.updateDiagramContainerVisibility(child, visibility);\n }\n }\n };\n /** @private */\n Diagram.prototype.updateEdges = function (obj) {\n if (obj.sourceID !== undefined && obj.sourceID !== '') {\n var node = this.nameTable[obj.sourceID];\n if (node && node.outEdges && node.outEdges.length === 0) {\n node.outEdges = [];\n }\n if (node && node.outEdges && node.outEdges.indexOf(obj.id) === -1) {\n node.outEdges.push(obj.id);\n }\n }\n if (obj.targetID !== undefined && obj.targetID !== '') {\n var node = this.nameTable[obj.targetID];\n if (node && node.inEdges && node.inEdges.length === 0) {\n node.inEdges = [];\n }\n if (node && node.inEdges && node.inEdges.indexOf(obj.id) === -1) {\n node.inEdges.push(obj.id);\n }\n if (node && node.visible && node.outEdges) {\n var value = node.outEdges.length === 0 ? false : true;\n this.updateIconVisibility(node, value);\n }\n }\n };\n /** @private */\n Diagram.prototype.refreshDiagram = function () {\n this.initLayerObjects();\n this.doLayout();\n this.updateBridging();\n this.scroller.setSize();\n };\n /** @private */\n Diagram.prototype.updateDiagramObject = function (obj) {\n var view;\n for (var _i = 0, _a = this.views; _i < _a.length; _i++) {\n var temp = _a[_i];\n view = this.views[temp];\n if (view.mode === 'SVG' && this.diagramActions) {\n var htmlLayer = getHTMLLayer(this.element.id);\n var diagramElementsLayer = document.getElementById(view.element.id + '_diagramLayer');\n this.diagramRenderer.updateNode(obj.wrapper, diagramElementsLayer, htmlLayer, undefined);\n }\n else {\n this.refreshCanvasDiagramLayer(view);\n }\n }\n };\n /** @private */\n Diagram.prototype.getObjectsOfLayer = function (objectArray) {\n var nodeArray = [];\n for (var _i = 0, objectArray_1 = objectArray; _i < objectArray_1.length; _i++) {\n var obj = objectArray_1[_i];\n if (this.nameTable[obj]) {\n nodeArray.push(this.nameTable[obj]);\n }\n }\n return nodeArray;\n };\n /** @private */\n Diagram.prototype.refreshDiagramLayer = function () {\n var view;\n for (var _i = 0, _a = this.views; _i < _a.length; _i++) {\n var temp = _a[_i];\n view = this.views[temp];\n switch (view.mode) {\n case 'SVG':\n this.refreshSvgDiagramLayer(view);\n break;\n case 'Canvas':\n this.refreshCanvasLayers();\n break;\n }\n }\n };\n /** @private */\n Diagram.prototype.refreshCanvasLayers = function () {\n for (var _i = 0, _a = this.views; _i < _a.length; _i++) {\n var temp = _a[_i];\n var view = this.views[temp];\n this.refreshCanvasDiagramLayer(view);\n }\n };\n Diagram.prototype.renderBasicElement = function (view) {\n var htmlLayer = getHTMLLayer(view.element.id);\n for (var i = 0; i < this.basicElements.length; i++) {\n var element = this.basicElements[i];\n if (element instanceof Container) {\n element.prevRotateAngle = 0;\n }\n element.measure(new Size(element.width, element.height));\n element.arrange(element.desiredSize);\n view.diagramRenderer.renderElement(element, view.diagramLayer, htmlLayer);\n }\n };\n Diagram.prototype.refreshElements = function (view) {\n if (!this.isDestroyed) {\n this.clearCanvas(view);\n if (view instanceof Diagram) {\n view.diagramLayer.getContext('2d').setTransform(view.scroller.currentZoom, 0, 0, view.scroller.currentZoom, 0, 0);\n view.diagramLayer.getContext('2d').scale(1.5, 1.5);\n }\n var htmlLayer = getHTMLLayer(view.element.id);\n var bounds = this.spatialSearch.getPageBounds();\n this.renderDiagramElements(view.diagramLayer, view.diagramRenderer, htmlLayer);\n if (view instanceof Diagram) {\n view.diagramLayer.style.transform = 'scale(' + (2 / 3) + ')';\n view.diagramLayer.style.transformOrigin = '0 0';\n }\n this.renderTimer = null;\n }\n };\n /** @private */\n Diagram.prototype.refreshCanvasDiagramLayer = function (view) {\n var _this = this;\n if (view.mode !== 'SVG' && !this.isDestroyed) {\n if (this.basicElements.length > 0) {\n this.renderBasicElement(view);\n }\n if (!this.diagramActions || (this.diagramActions & DiagramAction.Render) === 0) {\n this.refreshElements(view);\n }\n else if (!this.renderTimer) {\n this.renderTimer = setTimeout(function () {\n _this.refreshElements(view);\n }, 40);\n }\n }\n };\n /** @private */\n Diagram.prototype.updatePortVisibility = function (node, portVisibility, inverse) {\n var portElement;\n var drawingObject = !(this.drawingObject && this.drawingObject.shape) ? true : false;\n if (node instanceof Node && drawingObject && canMove(node)) {\n var ports = node.ports;\n var changed = false;\n for (var i = 0; i < ports.length; i++) {\n portElement = this.getWrapper(node.wrapper, ports[i].id);\n if (portVisibility & PortVisibility.Hover || portVisibility & PortVisibility.Connect) {\n if (checkPortRestriction(ports[i], portVisibility)) {\n portElement.visible = !inverse;\n changed = true;\n }\n }\n }\n if (changed) {\n this.updateDiagramObject(node);\n }\n }\n };\n /** @private */\n Diagram.prototype.refreshSvgDiagramLayer = function (view) {\n var container = document.getElementById(view.element.id);\n var bounds = container.getBoundingClientRect();\n var node;\n var element;\n var connector;\n var diagramElementsLayer = document.getElementById(view.element.id + '_diagramLayer');\n var htmlLayer = getHTMLLayer(view.element.id);\n for (var i = 0; i < this.basicElements.length; i++) {\n element = this.basicElements[i];\n element.measure(new Size(element.width, element.height));\n element.arrange(element.desiredSize);\n this.diagramRenderer.renderElement(element, diagramElementsLayer, htmlLayer);\n }\n this.renderDiagramElements(diagramElementsLayer, this.diagramRenderer, htmlLayer);\n };\n /** @private */\n Diagram.prototype.renderDiagramElements = function (canvas, renderer, htmlLayer, transform) {\n if (transform === void 0) { transform = true; }\n for (var _i = 0, _a = Object.keys(this.layerZIndexTable); _i < _a.length; _i++) {\n var layerId = _a[_i];\n var layer = this.commandHandler.getLayer(this.layerZIndexTable[layerId]);\n for (var _b = 0, _c = Object.keys(layer.zIndexTable); _b < _c.length; _b++) {\n var node = _c[_b];\n var element = this.nameTable[layer.zIndexTable[node]].wrapper;\n if (!(this.nameTable[layer.zIndexTable[node]].parentId)\n && !(this.nameTable[layer.zIndexTable[node]].processId)) {\n renderer.renderElement(element, canvas, htmlLayer, (!renderer.isSvgMode && transform) ? this.scroller.transform : undefined);\n }\n }\n }\n };\n /** @private */\n Diagram.prototype.updateBridging = function (isLoad) {\n if (this.bridgingModule) {\n for (var i = 0; i < this.connectors.length; i++) {\n var connector = this.connectors[i];\n this.bridgingModule.updateBridging(connector, this);\n var canvas = this.connectors[i].wrapper;\n if (canvas) {\n var pathSegment = canvas.children[0];\n var data = pathSegment.data;\n connector.getSegmentElement(connector, pathSegment);\n if (pathSegment.data !== data) {\n canvas.measure(new Size());\n canvas.arrange(canvas.desiredSize);\n if (this.mode === 'SVG' && !isLoad) {\n this.updateDiagramObject(connector);\n }\n }\n }\n }\n }\n };\n /** @private */\n Diagram.prototype.setCursor = function (cursor) {\n this.diagramRenderer.setCursor(this.diagramCanvas, cursor);\n };\n /** @private */\n Diagram.prototype.clearCanvas = function (view) {\n var width;\n var height;\n width = view.contentWidth || view.diagramLayer.width;\n height = view.contentHeight || view.diagramLayer.height;\n if (view.mode !== 'SVG') {\n var ctx = CanvasRenderer.getContext(view.diagramLayer);\n ctx.clearRect(0, 0, width, height);\n }\n };\n /** @private */\n Diagram.prototype.updateScrollOffset = function () {\n this.scroller.setScrollOffset(this.diagramCanvas.scrollLeft, this.diagramCanvas.scrollTop);\n updateRuler(this);\n };\n /** @private */\n Diagram.prototype.setOffset = function (offsetX, offsetY) {\n var container = document.getElementById(this.element.id + 'content');\n if (container) {\n container.scrollLeft = offsetX;\n container.scrollTop = offsetY;\n }\n };\n /** @private */\n Diagram.prototype.setSize = function (width, height) {\n if (this.diagramLayer && !this.preventUpdate) {\n var position = getRulerSize(this);\n width -= position.width;\n height -= position.height;\n var bounds = this.spatialSearch.getPageBounds();\n bounds.x *= this.scroller.currentZoom;\n bounds.y *= this.scroller.currentZoom;\n bounds.width *= this.scroller.currentZoom;\n bounds.height *= this.scroller.currentZoom;\n var factor = this.mode === 'SVG' ? 1 : 1.5;\n var diagramLayer = this.mode === 'SVG' ?\n getDiagramLayerSvg(this.element.id) : this.diagramLayer;\n diagramLayer.setAttribute('width', (factor * width).toString());\n diagramLayer.setAttribute('height', (factor * height).toString());\n var attr = { 'width': width.toString(), 'height': height.toString() };\n this.diagramLayerDiv.style.width = width + 'px';\n this.diagramLayerDiv.style.height = height + 'px';\n setAttributeSvg(getNativeLayerSvg(this.element.id), attr);\n setAttributeSvg(getPortLayerSvg(this.element.id), attr);\n var adornerSVG = getAdornerLayerSvg(this.element.id);\n setAttributeSvg(adornerSVG, attr);\n adornerSVG.parentNode.style.width = width + 'px';\n adornerSVG.parentNode.style.height = height + 'px';\n var gridLayer = getGridLayerSvg(this.element.id);\n setAttributeSvg(gridLayer, attr);\n this.diagramRenderer.updateGrid(this.snapSettings, gridLayer, this.scroller.transform, this.rulerSettings, this.hRuler, this.vRuler);\n setAttributeSvg(getBackgroundLayerSvg(this.element.id), attr);\n this.htmlLayer.style.width = width + 'px';\n this.htmlLayer.style.height = height + 'px';\n this.diagramRenderer.transformLayers(this.scroller.transform, this.mode === 'SVG');\n if (this.mode !== 'SVG') {\n this.refreshDiagramLayer();\n }\n this.updateSelector();\n this.renderPageBreaks(bounds);\n }\n };\n /**\n * Defines how to remove the Page breaks\n * @private\n */\n Diagram.prototype.removePageBreaks = function () {\n if (this.diagramLayer) {\n var line = getBackgroundLayer(this.element.id);\n if (line && line.childNodes) {\n var length_1 = line.childNodes.length;\n for (var i = 0; i < length_1; i++) {\n line.removeChild(line.childNodes[0]);\n }\n }\n }\n };\n /**\n * Defines how the page breaks has been rendered\n * @private\n */\n Diagram.prototype.renderPageBreaks = function (bounds) {\n this.removePageBreaks();\n var backgroundLayer = getBackgroundLayer(this.element.id);\n if (backgroundLayer) {\n var i = 0;\n bounds = this.scroller.getPageBounds(true);\n var x = (this.scroller.transform.tx + bounds.x) * this.scroller.currentZoom;\n var y = (this.scroller.transform.ty + bounds.y) * this.scroller.currentZoom;\n var height = bounds.height * this.scroller.currentZoom;\n var width = bounds.width * this.scroller.currentZoom;\n DiagramRenderer.renderSvgBackGroundImage(this.pageSettings.background, this.element, x, y, width, height);\n var options = {\n id: backgroundLayer.id + 'rect', x: x,\n y: y,\n height: height,\n width: width, angle: 0, stroke: '', strokeWidth: 1,\n fill: this.pageSettings.background.color, opacity: 1,\n pivotX: 0, pivotY: 0, visible: true, dashArray: '0',\n };\n this.diagramRenderer.drawRect(backgroundLayer, options);\n if (this.pageSettings.showPageBreaks) {\n var collection = this.scroller.getPageBreak(bounds);\n for (i = 0; i < collection.length; i++) {\n this.diagramRenderer.drawLine(backgroundLayer, {\n class: 'e-diagram-page-break',\n fill: 'none', stroke: '#aaaaaa', strokeWidth: 1, dashArray: '10 10',\n opacity: 2, x: 0, y: 0, width: 0, height: 0, angle: 0, pivotX: 0, pivotY: 0, visible: true,\n startPoint: {\n x: (collection[i].x1 + this.scroller.transform.tx) * this.scroller.currentZoom,\n y: (collection[i].y1 + this.scroller.transform.ty) * this.scroller.currentZoom\n },\n endPoint: {\n x: (collection[i].x2 + this.scroller.transform.tx) * this.scroller.currentZoom,\n y: (collection[i].y2 + this.scroller.transform.ty) * this.scroller.currentZoom\n }, id: collection[i].y1 === collection[i].y2 ? 'HorizontalLines' : 'VerticalLines'\n });\n }\n }\n }\n };\n Diagram.prototype.validatePageSize = function () {\n var temp = 0;\n if (this.pageSettings.orientation === 'Portrait') {\n if (this.pageSettings.width > this.pageSettings.height) {\n temp = this.pageSettings.height;\n this.pageSettings.height = this.pageSettings.width;\n this.pageSettings.width = temp;\n }\n }\n else {\n if (this.pageSettings.height > this.pageSettings.width) {\n temp = this.pageSettings.width;\n this.pageSettings.width = this.pageSettings.height;\n this.pageSettings.height = temp;\n }\n }\n };\n /**\n * @private\n */\n Diagram.prototype.setOverview = function (overview, id) {\n if (overview) {\n if (overview) {\n this.views.push(overview.id);\n this.views[overview.id] = overview;\n overview.renderDocument(overview);\n overview.diagramRenderer.setLayers();\n overview.updateView(overview);\n this.renderNodes(overview);\n }\n }\n else {\n for (var i = 0; i < this.views.length; i++) {\n if (this.views[i] === id) {\n overview = (this.views[id]);\n }\n }\n this.views[id] = undefined;\n var index = this.views.indexOf(id);\n this.views.splice(index, 1);\n }\n };\n Diagram.prototype.renderNodes = function (overview) {\n if (overview) {\n var renderer = new DiagramRenderer(overview.id, new SvgRenderer(), false);\n var g = document.getElementById(overview.element.id + '_diagramLayer');\n var htmlLayer = getHTMLLayer(overview.element.id);\n this.renderDiagramElements(g, overview.diagramRenderer || renderer, htmlLayer);\n }\n };\n Diagram.prototype.updateThumbConstraints = function (node, selectorModel) {\n var state = 0;\n var length = node.length;\n for (var i = 0; i < length; i++) {\n var obj = node[i];\n var hideRotate = false;\n var hideResize = false;\n var thumbConstraints = selectorModel.thumbsConstraints;\n if (obj instanceof Node) {\n hideRotate = (obj.shape.type === 'Bpmn' && (obj.shape.shape === 'Activity' &&\n (obj.shape.activity.subProcess.collapsed === false)) ||\n obj.shape.shape === 'TextAnnotation');\n hideResize = (obj.shape.type === 'Bpmn' && obj.shape.shape === 'TextAnnotation');\n if (!canRotate(obj) || !(thumbConstraints & ThumbsConstraints.Rotate) || hideRotate) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.Rotate;\n }\n if (!canResize(obj, 'SouthEast') || !(thumbConstraints & ThumbsConstraints.ResizeSouthEast) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeSouthEast;\n }\n if (!canResize(obj, 'NorthWest') || !(thumbConstraints & ThumbsConstraints.ResizeNorthWest) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeNorthWest;\n }\n if (!canResize(obj, 'East') || !(thumbConstraints & ThumbsConstraints.ResizeEast) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeEast;\n }\n if (!canResize(obj, 'West') || !(thumbConstraints & ThumbsConstraints.ResizeWest) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeWest;\n }\n if (!canResize(obj, 'North') || !(thumbConstraints & ThumbsConstraints.ResizeNorth) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeNorth;\n }\n if (!canResize(obj, 'South') || !(thumbConstraints & ThumbsConstraints.ResizeSouth) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeSouth;\n }\n if (!canResize(obj, 'NorthEast') || !(thumbConstraints & ThumbsConstraints.ResizeNorthEast) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeNorthEast;\n }\n if (!canResize(obj, 'SouthWest') || !(thumbConstraints & ThumbsConstraints.ResizeSouthWest) || hideResize) {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ResizeSouthWest;\n }\n }\n else {\n thumbConstraints = thumbConstraints | ThumbsConstraints.Default;\n if (canDragSourceEnd(obj)) {\n thumbConstraints = thumbConstraints | ThumbsConstraints.ConnectorSource;\n }\n else {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ConnectorSource;\n }\n if (canDragTargetEnd(obj)) {\n thumbConstraints = thumbConstraints | ThumbsConstraints.ConnectorTarget;\n }\n else {\n thumbConstraints = thumbConstraints & ~ThumbsConstraints.ConnectorTarget;\n }\n }\n selectorModel.thumbsConstraints = thumbConstraints;\n }\n };\n /** @private */\n Diagram.prototype.renderSelector = function (multipleSelection) {\n var size = new Size();\n var selectorModel = this.selectedItems;\n var selectorConstraints = selectorModel.constraints;\n this.clearSelectorLayer();\n if (this.commandHandler.hasSelection()) {\n if (selectorModel.nodes.length === 1 && selectorModel.connectors.length === 0) {\n selectorModel.rotateAngle = selectorModel.nodes[0].rotateAngle;\n selectorModel.pivot = selectorModel.nodes[0].pivot;\n }\n selectorModel.wrapper.measure(size);\n selectorModel.wrapper.arrange(selectorModel.wrapper.desiredSize);\n selectorModel.width = selectorModel.wrapper.actualSize.width;\n selectorModel.height = selectorModel.wrapper.actualSize.height;\n selectorModel.offsetX = selectorModel.wrapper.offsetX;\n selectorModel.offsetY = selectorModel.wrapper.offsetY;\n if (selectorModel.rotateAngle !== 0) {\n for (var _i = 0, _a = selectorModel.nodes; _i < _a.length; _i++) {\n var obj = _a[_i];\n obj.offsetX = obj.wrapper.offsetX;\n obj.offsetY = obj.wrapper.offsetY;\n }\n for (var _b = 0, _c = selectorModel.connectors; _b < _c.length; _b++) {\n var conn = _c[_b];\n //update connections\n }\n }\n var bounds = this.spatialSearch.getPageBounds();\n var selectorElement = void 0;\n selectorElement = getSelectorElement(this.element.id);\n selectorModel.thumbsConstraints = ThumbsConstraints.Default;\n this.updateThumbConstraints(selectorModel.nodes, selectorModel);\n this.updateThumbConstraints(selectorModel.connectors, selectorModel);\n if (selectorModel.nodes.length + selectorModel.connectors.length === 1) {\n if (selectorModel.nodes[0] instanceof Node) {\n this.diagramRenderer.renderResizeHandle(selectorModel.nodes[0].wrapper, selectorElement, selectorModel.thumbsConstraints, this.scroller.currentZoom, selectorModel.constraints, this.scroller.transform, undefined, canMove(selectorModel.nodes[0]));\n }\n else if (selectorModel.connectors[0] instanceof Connector) {\n var connector = selectorModel.connectors[0];\n this.diagramRenderer.renderEndPointHandle(connector, selectorElement, selectorModel.thumbsConstraints, selectorModel.constraints, this.scroller.transform, connector.sourceWrapper !== undefined, connector.targetWrapper !== undefined, (this.connectorEditingToolModule && canDragSegmentThumb(connector)) ? true : false);\n }\n }\n else {\n this.diagramRenderer.renderResizeHandle(selectorModel.wrapper, selectorElement, selectorModel.thumbsConstraints, this.scroller.currentZoom, selectorModel.constraints, this.scroller.transform, undefined, canMove(selectorModel));\n }\n this.diagramRenderer.renderUserHandler(selectorModel, selectorElement, this.scroller.transform);\n }\n };\n /** @private */\n Diagram.prototype.updateSelector = function () {\n var bounds = this.spatialSearch.getPageBounds();\n var size = new Size();\n var selectorModel = this.selectedItems;\n var selectorConstraints = selectorModel.constraints;\n if (!(this.diagramActions & DiagramAction.ToolAction) && this.selectedItems.nodes.length === 1) {\n this.selectedItems.rotateAngle = this.selectedItems.nodes[0].rotateAngle;\n this.selectedItems.wrapper.rotateAngle = this.selectedItems.nodes[0].rotateAngle;\n }\n if (this.selectedItems !== undefined) {\n this.clearSelectorLayer();\n if (selectorModel.wrapper !== null && selectorModel.wrapper.children.length) {\n selectorModel.wrapper.measure(size);\n selectorModel.wrapper.arrange(selectorModel.wrapper.desiredSize);\n if (selectorModel.rotateAngle !== 0 || selectorModel.rotateAngle !== selectorModel.wrapper.prevRotateAngle) {\n for (var _i = 0, _a = selectorModel.nodes; _i < _a.length; _i++) {\n var obj = _a[_i];\n obj.offsetX = obj.wrapper.offsetX;\n obj.offsetY = obj.wrapper.offsetY;\n }\n }\n selectorModel.width = selectorModel.wrapper.actualSize.width;\n selectorModel.height = selectorModel.wrapper.actualSize.height;\n selectorModel.offsetX = selectorModel.wrapper.offsetX;\n selectorModel.offsetY = selectorModel.wrapper.offsetY;\n var selectorElement = void 0;\n selectorElement = getSelectorElement(this.element.id);\n var canHideResizers = this.eventHandler.canHideResizers();\n selectorModel.thumbsConstraints = ThumbsConstraints.Default;\n this.updateThumbConstraints(selectorModel.nodes, selectorModel);\n this.updateThumbConstraints(selectorModel.connectors, selectorModel);\n if (this.selectedItems.constraints & SelectorConstraints.UserHandle) {\n this.diagramRenderer.renderUserHandler(selectorModel, selectorElement, this.scroller.transform);\n }\n if (selectorModel.nodes.length + selectorModel.connectors.length === 1) {\n if (selectorModel.connectors[0] instanceof Connector) {\n var connector = selectorModel.connectors[0];\n this.diagramRenderer.renderEndPointHandle(connector, selectorElement, selectorModel.thumbsConstraints, selectorConstraints, this.scroller.transform, connector.sourceWrapper !== undefined, connector.targetWrapper !== undefined, (this.connectorEditingToolModule && canDragSegmentThumb(connector)) ? true : false);\n }\n else if (selectorModel.nodes[0] instanceof Node) {\n this.diagramRenderer.renderResizeHandle(selectorModel.nodes[0].wrapper, selectorElement, selectorModel.thumbsConstraints, this.scroller.currentZoom, selectorModel.constraints, this.scroller.transform, canHideResizers, canMove(selectorModel.nodes[0]));\n }\n }\n else {\n this.diagramRenderer.renderResizeHandle(selectorModel.wrapper, selectorElement, selectorModel.thumbsConstraints, this.scroller.currentZoom, selectorModel.constraints, this.scroller.transform, canHideResizers, canMove(selectorModel));\n }\n }\n }\n };\n /** @private */\n Diagram.prototype.drawSelectionRectangle = function (x, y, width, height) {\n this.clearSelectorLayer();\n this.diagramRenderer.drawSelectionRectangle(x, y, width, height, this.adornerLayer, this.scroller.transform);\n };\n /**\n * @private\n */\n Diagram.prototype.renderHighlighter = function (element) {\n var adornerSvg = getAdornerLayerSvg(this.element.id);\n this.diagramRenderer.renderHighlighter(element, adornerSvg, this.scroller.transform);\n };\n /**\n * @private\n */\n Diagram.prototype.clearHighlighter = function () {\n var adornerSvg = getAdornerLayerSvg(this.element.id);\n var highlighter = adornerSvg.getElementById(adornerSvg.id + '_highlighter');\n if (highlighter) {\n highlighter.parentNode.removeChild(highlighter);\n }\n };\n /** @private */\n Diagram.prototype.getNodesConnectors = function (selectedItems) {\n for (var i = 0; i < this.nodes.length; i++) {\n var node = this.nodes[i];\n selectedItems.push(node);\n }\n for (var i = 0; i < this.connectors.length; i++) {\n var conn = this.connectors[i];\n selectedItems.push(conn);\n }\n return selectedItems;\n };\n /** @private */\n Diagram.prototype.clearSelectorLayer = function () {\n var adornerSvg = getAdornerLayerSvg(this.element.id);\n var highlighter = adornerSvg.getElementById(adornerSvg.id + '_highlighter');\n var selectionRect = adornerSvg.getElementById(this.adornerLayer.id + '_selected_region');\n if (selectionRect) {\n selectionRect.parentNode.removeChild(selectionRect);\n }\n this.clearHighlighter();\n var childNodes = getSelectorElement(this.element.id).childNodes;\n var child;\n for (var i = childNodes.length; i > 0; i--) {\n child = childNodes[i - 1];\n child.parentNode.removeChild(child);\n }\n };\n /** @private */\n Diagram.prototype.getWrapper = function (nodes, id) {\n var wrapper;\n id = nodes.id + '_' + id;\n var container = nodes instanceof Canvas ? nodes : this.getPortContainer(this.nameTable[nodes.id]);\n for (var i = 0; i < container.children.length; i++) {\n if (id === container.children[i].id) {\n wrapper = container.children[i];\n }\n }\n return wrapper;\n };\n Diagram.prototype.getEndNodeWrapper = function (node, connector, source) {\n if (node.shape.type === 'Bpmn' && node.wrapper.children[0] instanceof Canvas) {\n if (node.shape.shape === 'Activity') {\n if (source && node.shape.activity.subProcess.type === 'Transaction'\n && connector.sourcePortID) {\n var portId = connector.sourcePortID;\n var parent_1 = node.wrapper.children[0].children[0].children[2];\n if (parent_1.children) {\n for (var _i = 0, _a = parent_1.children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (child.visible && child.id === node.id + '_' + portId) {\n return child.children[0];\n }\n }\n }\n }\n return node.wrapper.children[0].children[0].children[0];\n }\n return node.wrapper.children[0].children[0];\n }\n if (!this.containsMargin(node.wrapper.children[0])) {\n if (!node.children) {\n return node.wrapper.children[0];\n }\n }\n return node.wrapper;\n };\n Diagram.prototype.containsMargin = function (node) {\n return node.margin && (node.margin.left !== 0 || node.margin.top !== 0 || node.margin.right !== 0 || node.margin.bottom !== 0);\n };\n Diagram.prototype.focusOutEdit = function () {\n this.endEdit(true);\n };\n Diagram.prototype.endEditCommand = function () {\n this.endEdit();\n };\n /**\n * @private\n */\n Diagram.prototype.endEdit = function (focusOut) {\n if (this.diagramActions & DiagramAction.TextEdit) {\n var textarea = document.getElementById(this.element.id + '_editBox');\n var text = textarea.value;\n EventHandler.remove(textarea, 'input', this.eventHandler.inputChange);\n EventHandler.remove(textarea, 'focusout', this.focusOutEdit);\n var element = document.getElementById(this.element.id + '_editTextBoxDiv');\n var args = { oldValue: element.textContent, newValue: text, cancel: false };\n var bpmnAnnotation = false;\n var node = void 0;\n element.parentNode.removeChild(element);\n var textWrapper = void 0;\n if (this.bpmnModule) {\n node = this.bpmnModule.isBpmnTextAnnotation(this.activeLabel, this);\n textWrapper = this.bpmnModule.getTextAnnotationWrapper(node, this.activeLabel.id);\n bpmnAnnotation = node ? true : false;\n if (bpmnAnnotation) {\n if (element.textContent !== text) {\n this.triggerEvent(DiagramEvent.textEdit, args);\n if (!args.cancel) {\n this.bpmnModule.updateTextAnnotationContent(node, this.activeLabel, text, this);\n }\n }\n }\n }\n if (!bpmnAnnotation) {\n node = this.nameTable[this.activeLabel.parentId];\n var deleteNode = this.eventHandler.isAddTextNode(node, true);\n if (!deleteNode && element.textContent !== text) {\n this.triggerEvent(DiagramEvent.textEdit, args);\n }\n if (!textWrapper) {\n textWrapper = this.getWrapper(node.wrapper, this.activeLabel.id);\n }\n var annotation = findAnnotation(node, this.activeLabel.id);\n if (annotation.content !== text && !args.cancel) {\n annotation.content = text;\n this.dataBind();\n this.updateSelector();\n }\n if (deleteNode) {\n this.removeObjectsFromLayer(node);\n this.removeFromAQuad(node);\n delete this.nameTable[this.activeLabel.parentId];\n if (text !== '') {\n this.clearSelection();\n var clonedObject = cloneObject(node);\n node = this.add(clonedObject);\n this.updateDiagramObject(node);\n this.commandHandler.select(this.nameTable[node.id]);\n }\n }\n }\n textWrapper.visible = true;\n this.updateDiagramObject(node);\n this.diagramActions = this.diagramActions & ~DiagramAction.TextEdit;\n if (this.activeLabel.isGroup) {\n this.endGroupAction();\n }\n this.activeLabel = { id: '', parentId: '', isGroup: false };\n }\n };\n /** @private */\n Diagram.prototype.canLogChange = function () {\n if ((this.diagramActions & DiagramAction.Render) && (!(this.diagramActions & DiagramAction.ToolAction)) &&\n (!(this.diagramActions & DiagramAction.UndoRedo)) && (!(this.diagramActions & DiagramAction.PublicMethod))) {\n return true;\n }\n else {\n return false;\n }\n };\n Diagram.prototype.modelChanged = function (newProp, oldProp) {\n if (newProp.connectors || oldProp.connectors || newProp.nodes || oldProp.connectors\n || newProp.pageSettings || oldProp.pageSettings || newProp.bridgeDirection || oldProp.bridgeDirection) {\n return true;\n }\n return false;\n };\n Diagram.prototype.resetDiagramActions = function (action) {\n var isAction = action ? true : false;\n if (this.diagramActions & DiagramAction.UndoRedo && (!isAction || (action === DiagramAction.UndoRedo))) {\n this.diagramActions = this.diagramActions & ~DiagramAction.UndoRedo;\n }\n if (this.diagramActions & DiagramAction.PublicMethod && (!isAction || action === DiagramAction.PublicMethod)) {\n this.diagramActions = this.diagramActions & ~DiagramAction.PublicMethod;\n }\n };\n /** @private */\n Diagram.prototype.removeNode = function (node) {\n this.removeObjectsFromLayer(node);\n this.removeFromAQuad(this.nameTable[node.id]);\n delete this.nameTable[node.id];\n if (node.children) {\n delete this.groupTable[node.id];\n }\n this.nodes.splice(this.nodes.indexOf(node), 1);\n };\n /** @private */\n Diagram.prototype.deleteGroup = function (node) {\n var elements = [];\n var tempNode = [];\n if (node.children) {\n tempNode = this.commandHandler.getChildren(node, elements);\n }\n for (var _i = 0, tempNode_1 = tempNode; _i < tempNode_1.length; _i++) {\n var nodes = tempNode_1[_i];\n if (this.nameTable[nodes.id]) {\n this.remove(nodes);\n }\n }\n };\n //helper methods - end region\n //property changes - start region\n /** @private */\n Diagram.prototype.updateObject = function (actualObject, oldObject, changedProp) {\n if (!(this.diagramActions & DiagramAction.ToolAction)) {\n var bound = actualObject.wrapper.children[0].bounds;\n var checkBoundaryConstraints = this.commandHandler.checkBoundaryConstraints(undefined, undefined, bound);\n if (!checkBoundaryConstraints) {\n if (actualObject instanceof Node) {\n var oldNode = oldObject;\n for (var _i = 0, _a = Object.keys(changedProp); _i < _a.length; _i++) {\n var key = _a[_i];\n switch (key) {\n case 'width':\n actualObject.width = oldNode.width;\n break;\n case 'height':\n actualObject.height = oldNode.height;\n break;\n case 'offsetX':\n actualObject.offsetX = oldNode.offsetX;\n break;\n case 'offsetY':\n actualObject.offsetY = oldNode.offsetY;\n break;\n case 'rotateAngle':\n actualObject.rotateAngle = oldNode.rotateAngle;\n break;\n }\n }\n this.nodePropertyChange(actualObject, changedProp, oldObject);\n }\n else {\n for (var _b = 0, _c = Object.keys(changedProp); _b < _c.length; _b++) {\n var key = _c[_b];\n var oldConnector = oldObject;\n var actualSourcePoint = actualObject.sourcePoint;\n var actualTargetPoint = actualObject.targetPoint;\n switch (key) {\n case 'sourcePoint':\n actualSourcePoint.x = oldConnector.sourcePoint.x || actualSourcePoint.x;\n actualSourcePoint.y = oldConnector.sourcePoint.y || actualSourcePoint.y;\n break;\n case 'targetPoint':\n actualTargetPoint.x = oldConnector.targetPoint.x || actualTargetPoint.x;\n actualTargetPoint.y = oldConnector.targetPoint.y || actualTargetPoint.y;\n }\n }\n this.connectorPropertyChange(actualObject, changedProp, oldObject);\n }\n }\n }\n };\n Diagram.prototype.nodePropertyChangeExtend = function (actualObject, oldObject, node, update) {\n if (node.style !== undefined && actualObject.shape.type !== 'Bpmn') {\n updateStyle(node.style, actualObject.wrapper.children[0]);\n update = true;\n }\n if (node.constraints !== undefined) {\n this.updateThumbConstraints(this.selectedItems.nodes, this.selectedItems);\n this.updateSelector();\n update = true;\n }\n return update;\n };\n Diagram.prototype.connectorSegmentChange = function (actualObject, existingInnerBounds) {\n var tx;\n var ty;\n var segmentChange = true;\n if (existingInnerBounds.equals(existingInnerBounds, actualObject.wrapper.bounds) === false) {\n if (actualObject.outEdges.length > 0) {\n for (var k = 0; k < actualObject.outEdges.length; k++) {\n var connector = this.nameTable[actualObject.outEdges[k]];\n if (connector.targetID !== '') {\n segmentChange = this.commandHandler.isSelected(this.nameTable[connector.targetID]) ? false : true;\n }\n else {\n segmentChange = this.commandHandler.isSelected(this.nameTable[connector.id]) ? false : true;\n }\n if (connector.type === 'Orthogonal' && connector.segments && connector.segments.length > 1 && segmentChange) {\n switch (connector.segments[0].direction) {\n case 'Bottom':\n tx = actualObject.wrapper.bounds.bottomCenter.x - existingInnerBounds.bottomCenter.x;\n ty = actualObject.wrapper.bounds.bottomCenter.y - existingInnerBounds.bottomCenter.y;\n break;\n case 'Top':\n tx = actualObject.wrapper.bounds.topCenter.x - existingInnerBounds.topCenter.x;\n ty = actualObject.wrapper.bounds.topCenter.y - existingInnerBounds.topCenter.y;\n break;\n case 'Left':\n tx = actualObject.wrapper.bounds.middleLeft.x - existingInnerBounds.middleLeft.x;\n ty = actualObject.wrapper.bounds.middleLeft.y - existingInnerBounds.middleLeft.y;\n break;\n case 'Right':\n tx = actualObject.wrapper.bounds.middleRight.x - existingInnerBounds.middleRight.x;\n ty = actualObject.wrapper.bounds.middleRight.y - existingInnerBounds.middleRight.y;\n break;\n }\n this.commandHandler.dragSourceEnd(connector, tx, ty, true, null, 'ConnectorSourceEnd', undefined, undefined, undefined, true);\n }\n }\n }\n }\n };\n /* tslint:disable */\n /** @private */\n Diagram.prototype.nodePropertyChange = function (actualObject, oldObject, node, isLayout) {\n var existingBounds = actualObject.wrapper.outerBounds;\n var existingInnerBounds = actualObject.wrapper.bounds;\n var updateConnector = false;\n var i;\n var j;\n var offsetX;\n var offsetY;\n var update;\n var tx;\n var ty;\n if (node.width !== undefined && !actualObject.children) {\n actualObject.wrapper.children[0].width = node.width;\n update = true;\n updateConnector = true;\n }\n if (node.height !== undefined && !actualObject.children) {\n actualObject.wrapper.children[0].height = node.height;\n update = true;\n updateConnector = true;\n }\n update = this.nodePropertyChangeExtend(actualObject, oldObject, node, update);\n if (node.constraints !== undefined && canShadow(oldObject) !== canShadow(node)) {\n actualObject.wrapper.children[0].shadow = canShadow(actualObject) ? actualObject.shadow : null;\n }\n if (node.offsetX !== undefined) {\n actualObject.wrapper.offsetX = node.offsetX;\n update = true;\n updateConnector = true;\n }\n if (node.offsetY !== undefined) {\n actualObject.wrapper.offsetY = node.offsetY;\n update = true;\n updateConnector = true;\n }\n if (node.pivot !== undefined) {\n actualObject.wrapper.pivot = node.pivot;\n update = true;\n }\n if (node.minWidth !== undefined) {\n actualObject.wrapper.minWidth = node.minWidth;\n update = true;\n updateConnector = true;\n }\n if (node.minHeight !== undefined) {\n actualObject.wrapper.minHeight = node.minHeight;\n update = true;\n updateConnector = true;\n }\n if (node.maxWidth !== undefined) {\n actualObject.wrapper.maxWidth = node.maxWidth;\n update = true;\n updateConnector = true;\n }\n if (node.maxHeight !== undefined) {\n actualObject.wrapper.maxHeight = node.maxHeight;\n update = true;\n updateConnector = true;\n }\n if (node.rotateAngle !== undefined) {\n actualObject.wrapper.rotateAngle = node.rotateAngle;\n update = true;\n updateConnector = true;\n }\n if (node.backgroundColor !== undefined) {\n actualObject.wrapper.style.fill = node.backgroundColor;\n }\n if (node.visible !== undefined) {\n this.updateElementVisibility(actualObject.wrapper, actualObject, actualObject.visible);\n }\n if (node.shape !== undefined && actualObject.shape.type !== 'Bpmn') {\n update = true;\n updateShape(node, actualObject, oldObject, this);\n updateConnector = true;\n }\n if (node.margin) {\n update = true;\n this.updateMargin(actualObject, node);\n updateConnector = true;\n }\n if (((node.shape !== undefined && node.shape.type === undefined) || node.width !== undefined\n || node.height !== undefined || node.style !== undefined) && actualObject.shape.type === 'Bpmn' && this.bpmnModule) {\n update = true;\n updateConnector = true;\n this.bpmnModule.updateBPMN(node, oldObject, actualObject, this);\n }\n if (node.ports !== undefined) {\n for (var _i = 0, _a = Object.keys(node.ports); _i < _a.length; _i++) {\n var key = _a[_i];\n var index = Number(key);\n update = true;\n var changedObject = node.ports[key];\n var actualPort = actualObject.ports[index];\n this.updatePort(changedObject, actualPort, actualObject.wrapper);\n }\n }\n if (node.annotations !== undefined || node.width !== undefined) {\n for (var _b = 0, _c = Object.keys(node.annotations || actualObject.annotations); _b < _c.length; _b++) {\n var key = _c[_b];\n var index = Number(key);\n update = true;\n var changedObject = node.annotations ? node.annotations[key] : actualObject.annotations;\n var actualAnnotation = actualObject.annotations[index];\n if (actualAnnotation) {\n var updateSize = actualObject.width ? true : false;\n this.updateAnnotation(changedObject, actualAnnotation, actualObject.wrapper, actualObject, updateSize);\n }\n }\n }\n if (node.expandIcon !== undefined || node.collapseIcon !== undefined || node.isExpanded !== undefined) {\n this.updateIcon(actualObject);\n this.updateDefaultLayoutIcons(actualObject);\n if (node.isExpanded !== undefined) {\n this.commandHandler.expandNode(actualObject, true, this);\n }\n update = true;\n }\n if (node.tooltip !== undefined) {\n this.updateTooltip(actualObject, node);\n }\n if (update) {\n if (!(this.diagramActions & DiagramAction.ToolAction)) {\n if (this.checkSelectedItem(actualObject)) {\n this.updateSelector();\n }\n }\n if (this.bpmnModule !== undefined) {\n this.bpmnModule.updateTextAnnotationProp(actualObject, { offsetX: (oldObject.offsetX || actualObject.offsetX), offsetY: (oldObject.offsetY || actualObject.offsetY) }, this);\n }\n actualObject.wrapper.measure(new Size(actualObject.wrapper.bounds.width, actualObject.wrapper.bounds.height));\n actualObject.wrapper.arrange(actualObject.wrapper.desiredSize);\n this.updateObject(actualObject, oldObject, node);\n if (!isLayout) {\n this.connectorSegmentChange(actualObject, existingInnerBounds);\n if (updateConnector) {\n this.updateConnectorEdges(actualObject);\n }\n }\n else {\n if (actualObject && actualObject.visible && actualObject.outEdges) {\n this.updateIconVisibility(actualObject, (actualObject.outEdges.length === 0 ? false : true));\n }\n }\n if (this.bpmnModule !== undefined) {\n this.bpmnModule.updateDocks(actualObject, this);\n }\n this.updateGroupOffset(actualObject);\n if (existingBounds.equals(existingBounds, actualObject.wrapper.outerBounds) === false) {\n this.updateQuad(actualObject);\n }\n if (existingInnerBounds.equals(existingInnerBounds, actualObject.wrapper.bounds) === false) {\n this.updateGroupSize(actualObject);\n if (actualObject.children) {\n this.updateGroupOffset(actualObject);\n }\n }\n if (this.mode === 'SVG') {\n this.updateDiagramObject(actualObject);\n }\n }\n };\n Diagram.prototype.updateConnectorEdges = function (actualObject) {\n if (actualObject.inEdges.length > 0) {\n for (var j = 0; j < actualObject.inEdges.length; j++) {\n var connector = this.nameTable[actualObject.inEdges[j]];\n var conn = {\n sourcePoint: connector.sourcePoint, targetPoint: connector.targetPoint, sourceID: connector.sourceID,\n targetID: connector.targetID, sourcePortID: connector.sourcePortID, targetPortID: connector.targetPortID\n };\n this.connectorPropertyChange(connector, {}, conn);\n }\n }\n if (actualObject.outEdges.length > 0) {\n for (var k = 0; k < actualObject.outEdges.length; k++) {\n var connection = this.nameTable[actualObject.outEdges[k]];\n var conn = {\n sourcePoint: connection.sourcePoint, targetPoint: connection.targetPoint, sourceID: connection.sourceID,\n targetID: connection.targetID, sourcePortID: connection.sourcePortID, targetPortID: connection.targetPortID\n };\n this.connectorPropertyChange(connection, {}, conn);\n }\n }\n if (actualObject.parentId) {\n this.updateConnectorEdges(this.nameTable[actualObject.parentId]);\n }\n };\n /* tslint:enable */\n Diagram.prototype.connectorProprtyChangeExtend = function (actualObject, oldProp, newProp, updateSelector) {\n if (newProp.type !== undefined && newProp.type !== oldProp.type) {\n if (actualObject.segments.length > 0 && newProp.segments === undefined) {\n actualObject.segments = [];\n }\n }\n if ((newProp.shape !== undefined) && actualObject.shape !== undefined &&\n actualObject.shape && actualObject.shape.type === 'Bpmn' && this.bpmnModule) {\n this.bpmnModule.updateBPMNConnector(actualObject, oldProp, newProp, this);\n }\n if (actualObject.constraints !== undefined) {\n this.updateThumbConstraints(this.selectedItems.connectors, this.selectedItems);\n return updateSelector = true;\n }\n return updateSelector;\n };\n /** @private */\n Diagram.prototype.connectorPropertyChange = function (actualObject, oldProp, newProp, disableBridging) {\n var existingBounds = actualObject.wrapper.bounds;\n var updateSelector = false;\n var points = [];\n updateSelector = this.connectorProprtyChangeExtend(actualObject, oldProp, newProp, updateSelector);\n if (newProp.visible !== undefined) {\n this.updateElementVisibility(actualObject.wrapper, newProp, actualObject.visible);\n }\n if (newProp.sourcePoint !== undefined || newProp.targetPoint !== undefined\n || newProp.sourceID !== undefined || newProp.targetID !== undefined ||\n newProp.sourcePortID !== undefined || newProp.targetPortID !== undefined ||\n newProp.type !== undefined || newProp.segments !== undefined) {\n if ((newProp.sourceID !== undefined && newProp.sourceID !== oldProp.sourceID) || newProp.sourcePortID) {\n var sourceNode = this.nameTable[actualObject.sourceID];\n if (!sourceNode || canOutConnect(sourceNode)) {\n actualObject.sourceWrapper = sourceNode ? this.getEndNodeWrapper(sourceNode, actualObject, true) : undefined;\n }\n if (newProp.sourceID !== undefined && oldProp.sourceID !== undefined && oldProp.sourceID !== '') {\n var oldSource = this.nameTable[oldProp.sourceID];\n if (oldSource !== undefined && oldSource.outEdges && oldSource.outEdges.indexOf(actualObject.id) !== -1) {\n removeItem(oldSource.outEdges, actualObject.id);\n }\n }\n this.updateEdges(actualObject);\n }\n if (newProp.targetID !== undefined && newProp.targetID !== oldProp.targetID) {\n var targetNode = this.nameTable[newProp.targetID];\n if (!targetNode || canInConnect(targetNode)) {\n actualObject.targetWrapper = targetNode ? this.getEndNodeWrapper(targetNode, actualObject, false) : undefined;\n }\n if (oldProp !== undefined && oldProp.targetID !== undefined && oldProp.targetID !== '') {\n var oldTarget = this.nameTable[oldProp.targetID];\n if (oldTarget !== undefined && oldTarget.inEdges && oldTarget.inEdges.indexOf(actualObject.id) !== -1) {\n removeItem(oldTarget.inEdges, actualObject.id);\n }\n }\n this.updateEdges(actualObject);\n }\n if (newProp.sourcePortID !== undefined && newProp.sourcePortID !== oldProp.sourcePortID) {\n var source = void 0;\n if (actualObject.sourceID && this.nameTable[actualObject.sourceID]) {\n source = this.nameTable[actualObject.sourceID].wrapper;\n }\n actualObject.sourcePortWrapper = source ?\n this.getWrapper(source, newProp.sourcePortID) : undefined;\n }\n if (newProp.targetPortID !== undefined && newProp.targetPortID !== oldProp.targetPortID) {\n var target = void 0;\n if (actualObject.targetID && this.nameTable[actualObject.targetID]) {\n target = this.nameTable[actualObject.targetID].wrapper;\n }\n actualObject.targetPortWrapper = target ?\n this.getWrapper(target, newProp.targetPortID) : undefined;\n }\n points = this.getPoints(actualObject);\n }\n //Add prop change for zindex, alignments and margin\n if (newProp.style !== undefined) {\n updateStyle(newProp.style, actualObject.wrapper.children[0]);\n }\n if (points.length > 0 || newProp.sourceDecorator !== undefined || newProp.targetDecorator !== undefined ||\n newProp.cornerRadius !== undefined) {\n updateConnector(actualObject, points.length > 0 ? points : actualObject.intermediatePoints);\n if (newProp.type !== undefined) {\n updateSelector = true;\n }\n if (points.length > 0) {\n actualObject.wrapper.measure(new Size(actualObject.wrapper.width, actualObject.wrapper.height));\n actualObject.wrapper.arrange(actualObject.wrapper.desiredSize);\n if (actualObject.annotations.length) {\n for (var _i = 0, _a = actualObject.annotations; _i < _a.length; _i++) {\n var annotation = _a[_i];\n var annotationWrapper = void 0;\n annotationWrapper = this.getWrapper(actualObject.wrapper, annotation.id);\n actualObject.updateAnnotation(annotation, actualObject.intermediatePoints, actualObject.wrapper.bounds, annotationWrapper);\n }\n }\n actualObject.wrapper.measure(new Size(actualObject.wrapper.width, actualObject.wrapper.height));\n actualObject.wrapper.arrange(actualObject.wrapper.desiredSize);\n this.updateObject(actualObject, oldProp, newProp);\n } //work-around to update intersected connector bridging\n }\n if ((newProp.sourcePoint || newProp.targetPoint || newProp.segments)\n && this.diagramActions === DiagramAction.Render) {\n updateSelector = true;\n }\n if (!disableBridging) {\n this.updateBridging();\n }\n this.updateAnnotations(newProp, actualObject);\n actualObject.wrapper.measure(new Size(actualObject.wrapper.width, actualObject.wrapper.height));\n actualObject.wrapper.arrange(actualObject.wrapper.desiredSize);\n if (existingBounds.equals(existingBounds, actualObject.wrapper.bounds) === false) {\n this.updateQuad(actualObject);\n this.updateGroupSize(actualObject);\n }\n if (updateSelector === true && this.checkSelectedItem(actualObject)) {\n this.updateSelector();\n }\n if (this.mode === 'SVG') {\n this.updateDiagramObject(actualObject);\n }\n };\n Diagram.prototype.getPoints = function (actualObject, points) {\n var pts;\n pts = actualObject.getConnectorPoints(actualObject.type, points, this.layout.type === 'ComplexHierarchicalTree' || this.layout.type === 'HierarchicalTree' ?\n this.layout.orientation : undefined);\n return pts;\n };\n /**\n * update the opacity and visibility for the node once the layout animation starts\n */\n /** @private */\n Diagram.prototype.updateNodeProperty = function (element, visible, opacity) {\n if (visible === undefined) {\n this.updateElementVisibility(element, this.nameTable[element.id], visible);\n }\n else {\n element.style.opacity = opacity;\n for (var i = 0; i < element.children.length; i++) {\n if (element.children[i] instanceof Container) {\n this.updateNodeProperty(element.children[i], undefined, opacity);\n }\n element.children[i].style.opacity = opacity;\n }\n }\n };\n /**\n * checkSelected Item for Connector\n * @private\n */\n Diagram.prototype.checkSelectedItem = function (actualObject) {\n var selectorModel = this.selectedItems;\n var isSelected = false;\n var selItems = [];\n selItems = selItems.concat(selectorModel.nodes, selectorModel.connectors);\n if (selItems.length > 0) {\n if (actualObject.id === selItems[selItems.length - 1].id) {\n isSelected = true;\n }\n }\n return isSelected;\n };\n /**\n * Updates the visibility of the diagram container\n * @private\n */\n Diagram.prototype.updateDiagramContainerVisibility = function (element, visible) {\n if (element instanceof Container) {\n for (var i = 0; i < element.children.length; i++) {\n this.updateDiagramContainerVisibility(element.children[i], visible);\n }\n }\n element.visible = visible;\n };\n /**\n * Updates the visibility of the node/connector\n * @private\n */\n Diagram.prototype.updateElementVisibility = function (element, obj, visible) {\n if (visible !== undefined) {\n element.visible = visible;\n if (obj instanceof Node) {\n //content\n if (!obj.children) {\n element.children[0].visible = visible;\n this.updateDiagramContainerVisibility(element.children[0], visible);\n if (obj.shape.type === 'Bpmn' && this.bpmnModule) {\n this.bpmnModule.updateElementVisibility(obj, visible, this);\n }\n }\n else {\n for (var _i = 0, _a = obj.children; _i < _a.length; _i++) {\n var child = _a[_i];\n this.updateElementVisibility(this.nameTable[child].wrapper, this.nameTable[child], visible);\n }\n }\n //ports\n if (obj.ports) {\n for (var _b = 0, _c = obj.ports; _b < _c.length; _b++) {\n var port = _c[_b];\n if (port.visibility & PortVisibility.Visible) {\n var wrapper = this.getWrapper(element, port.id);\n wrapper.visible = visible;\n }\n }\n }\n if (obj.annotations) {\n for (var _d = 0, _e = obj.annotations; _d < _e.length; _d++) {\n var annotation = _e[_d];\n var wrapper = this.getWrapper(element, annotation.id);\n wrapper.visible = visible;\n }\n }\n }\n else {\n //path and decorators\n for (var i = 0; i < 3; i++) {\n element.children[i].visible = visible;\n }\n }\n if (obj.annotations) {\n //annotations\n for (var _f = 0, _g = obj.annotations; _f < _g.length; _f++) {\n var annotation = _g[_f];\n var wrapper = this.getWrapper(element, annotation.id);\n wrapper.visible = visible;\n }\n }\n if (obj.expandIcon || obj.collapseIcon) {\n var wrapper = this.getWrapper(element, 'icon_content');\n if (wrapper) {\n for (var i = 0; i < wrapper.children.length; i++) {\n wrapper.children[i].visible = visible;\n }\n wrapper.visible = visible;\n }\n }\n if (visible === false) {\n this.unSelect(this.nameTable[element.id]);\n }\n this.updateDiagramObject(this.nameTable[element.id]);\n }\n };\n Diagram.prototype.updateAnnotations = function (newProp, actualObject) {\n if (newProp.annotations !== undefined) {\n for (var _i = 0, _a = Object.keys(newProp.annotations); _i < _a.length; _i++) {\n var key = _a[_i];\n var index = Number(key);\n var changedObject = newProp.annotations[key];\n var actualAnnotation = actualObject.annotations[index];\n this.updateAnnotation(changedObject, actualAnnotation, actualObject.wrapper, actualObject);\n }\n }\n };\n /** @private */\n Diagram.prototype.updateAnnotation = function (changedObject, actualAnnotation, nodes, actualObject, canUpdateSize) {\n var annotationWrapper;\n var isMeasure = false;\n annotationWrapper = this.getWrapper(nodes, actualAnnotation.id);\n if (annotationWrapper !== undefined) {\n if (changedObject.width !== undefined && changedObject.height !== undefined) {\n annotationWrapper.width = changedObject.width;\n annotationWrapper.height = changedObject.height;\n isMeasure = true;\n }\n if (canUpdateSize) {\n annotationWrapper.refreshTextElement();\n }\n if (actualAnnotation instanceof ShapeAnnotation &&\n changedObject.offset !== undefined) {\n var offset = changedObject.offset;\n isMeasure = true;\n var offsetX = offset.x !== undefined ? offset.x :\n actualAnnotation.offset.x;\n var offsetY = offset.y !== undefined ? offset.y :\n actualAnnotation.offset.y;\n annotationWrapper.setOffsetWithRespectToBounds(offsetX, offsetY, 'Fraction');\n annotationWrapper.relativeMode = 'Point';\n }\n else if (actualAnnotation instanceof PathAnnotation &&\n changedObject.offset !== undefined) {\n actualObject.updateAnnotation(actualAnnotation, actualObject.intermediatePoints, actualObject.wrapper.bounds, annotationWrapper);\n }\n if ((actualAnnotation instanceof PathAnnotation) && changedObject.displacement) {\n if (changedObject.displacement.x !== undefined ||\n changedObject.displacement.y !== undefined) {\n isMeasure = true;\n }\n }\n if (changedObject.margin !== undefined) {\n isMeasure = true;\n if (changedObject.margin.bottom !== undefined) {\n annotationWrapper.margin.bottom = changedObject.margin.bottom;\n }\n if (changedObject.margin.top !== undefined) {\n annotationWrapper.margin.top = changedObject.margin.top;\n }\n if (changedObject.margin.left !== undefined) {\n annotationWrapper.margin.left = changedObject.margin.left;\n }\n if (changedObject.margin.right !== undefined) {\n annotationWrapper.margin.right = changedObject.margin.right;\n }\n }\n if (isMeasure || canUpdateSize) {\n annotationWrapper.width = (actualAnnotation.width || actualObject.width)\n - annotationWrapper.margin.left - annotationWrapper.margin.right;\n }\n if (changedObject.horizontalAlignment !== undefined) {\n annotationWrapper.horizontalAlignment = changedObject.horizontalAlignment;\n isMeasure = true;\n }\n if (changedObject.verticalAlignment !== undefined) {\n annotationWrapper.verticalAlignment = changedObject.verticalAlignment;\n isMeasure = true;\n }\n if (changedObject.visibility !== undefined) {\n annotationWrapper.visible = (nodes.visible && changedObject.visibility) ? true : false;\n }\n if (changedObject.constraints !== undefined) {\n annotationWrapper.constraints = changedObject.constraints;\n }\n if (changedObject.style !== undefined) {\n updateStyle(changedObject.style, annotationWrapper);\n }\n if (changedObject.hyperlink !== undefined) {\n updateHyperlink(changedObject.hyperlink, annotationWrapper, actualAnnotation);\n }\n if (changedObject.content !== undefined) {\n if (annotationWrapper) {\n isMeasure = true;\n annotationWrapper.content = changedObject.content;\n }\n }\n if (isMeasure === true) {\n annotationWrapper.measure(new Size(annotationWrapper.width, annotationWrapper.height));\n annotationWrapper.arrange(annotationWrapper.desiredSize);\n }\n annotationWrapper.refreshTextElement();\n // this.refresh(); this.refreshDiagramLayer();\n }\n };\n /** @private */\n Diagram.prototype.updatePort = function (changedObject, actualPort, nodes) {\n var portWrapper;\n var isMeasure = false;\n portWrapper = this.getWrapper(nodes, actualPort.id);\n if (portWrapper !== undefined) {\n if (changedObject.offset !== undefined) {\n isMeasure = true;\n var offsetX = changedObject.offset.x !== undefined ? changedObject.offset.x :\n actualPort.offset.x;\n var offsetY = changedObject.offset.y !== undefined ? changedObject.offset.y :\n actualPort.offset.y;\n portWrapper.setOffsetWithRespectToBounds(offsetX, offsetY, 'Fraction');\n portWrapper.relativeMode = 'Point';\n }\n if (changedObject.width !== undefined) {\n isMeasure = true;\n portWrapper.width = changedObject.width;\n }\n if (changedObject.height !== undefined) {\n isMeasure = true;\n portWrapper.height = changedObject.height;\n }\n if (changedObject.visibility !== undefined) {\n portWrapper.visible = (nodes.visible && checkPortRestriction(actualPort, PortVisibility.Visible)) ? true : false;\n }\n if (changedObject.margin !== undefined) {\n isMeasure = true;\n if (changedObject.margin.bottom !== undefined) {\n portWrapper.margin.bottom = changedObject.margin.bottom;\n }\n if (changedObject.margin.top !== undefined) {\n portWrapper.margin.top = changedObject.margin.top;\n }\n if (changedObject.margin.right !== undefined) {\n portWrapper.margin.right = changedObject.margin.right;\n }\n if (changedObject.margin.right !== undefined) {\n portWrapper.margin.left = changedObject.margin.left;\n }\n }\n if (changedObject.horizontalAlignment !== undefined) {\n isMeasure = true;\n portWrapper.horizontalAlignment = changedObject.horizontalAlignment;\n }\n if (changedObject.verticalAlignment !== undefined) {\n isMeasure = true;\n portWrapper.verticalAlignment = changedObject.verticalAlignment;\n }\n if (changedObject.style !== undefined) {\n if (changedObject.style.fill !== undefined) {\n portWrapper.style.fill = changedObject.style.fill;\n }\n if (changedObject.style.opacity !== undefined) {\n portWrapper.style.opacity = changedObject.style.opacity;\n }\n if (changedObject.style.strokeColor !== undefined) {\n portWrapper.style.strokeColor = changedObject.style.strokeColor;\n }\n if (changedObject.style.strokeWidth !== undefined) {\n portWrapper.style.strokeWidth = changedObject.style.strokeWidth;\n }\n if (changedObject.style.strokeDashArray !== undefined) {\n portWrapper.style.strokeDashArray = changedObject.style.strokeDashArray;\n }\n }\n if (changedObject.shape !== undefined) {\n if (portWrapper) {\n if (changedObject.shape === 'Custom' && changedObject.pathData) {\n portWrapper.data = String(changedObject.pathData);\n isMeasure = true;\n }\n else {\n var pathdata = getPortShape(changedObject.shape);\n portWrapper.data = pathdata;\n }\n }\n }\n if (isMeasure === true) {\n portWrapper.measure(new Size(portWrapper.width, portWrapper.height));\n portWrapper.arrange(portWrapper.desiredSize);\n }\n //this.refresh(); this.refreshDiagramLayer();\n }\n };\n /** @private */\n Diagram.prototype.updateIcon = function (actualObject) {\n var iconContainer = this.getWrapper(actualObject.wrapper, 'icon_content');\n if (iconContainer) {\n if (this.mode === 'SVG') {\n var icon = getDiagramElement(actualObject.wrapper.id + '_icon_content');\n if (icon) {\n var iconRect = getDiagramElement(icon.id + '_rect');\n var iconShape = getDiagramElement(icon.id + '_shape');\n var nativeContent = getDiagramElement(iconShape.id + '_native_element');\n if (nativeContent) {\n nativeContent.parentNode.removeChild(nativeContent);\n }\n iconShape.parentNode.removeChild(iconShape);\n iconRect.parentNode.removeChild(iconRect);\n icon.parentNode.removeChild(icon);\n }\n }\n var index = actualObject.wrapper.children.indexOf(iconContainer);\n actualObject.wrapper.children.splice(index, 1);\n }\n var portContainer = this.getPortContainer(actualObject);\n actualObject.initIcons(this.getDescription, this.layout, portContainer, this.element.id);\n };\n Diagram.prototype.getPortContainer = function (actualObject) {\n if (actualObject.children) {\n for (var i = 0; i < actualObject.wrapper.children.length; i++) {\n if (actualObject.wrapper.children[i].id === 'group_container') {\n return actualObject.wrapper.children[i];\n }\n }\n }\n return actualObject.wrapper;\n };\n Diagram.prototype.updateTooltip = function (actualObject, node) {\n if (node.tooltip.content !== undefined) {\n actualObject.tooltip.content = node.tooltip.content;\n }\n if (node.tooltip.position !== undefined) {\n actualObject.tooltip.position = node.tooltip.position;\n }\n if (node.tooltip.height !== undefined) {\n actualObject.tooltip.height = node.tooltip.height;\n }\n if (node.tooltip.width !== undefined) {\n actualObject.tooltip.width = node.tooltip.width;\n }\n if (node.tooltip.showTipPointer !== undefined) {\n actualObject.tooltip.showTipPointer = node.tooltip.showTipPointer;\n }\n };\n /** @private */\n Diagram.prototype.updateQuad = function (obj) {\n var modified = this.spatialSearch.updateQuad(obj.wrapper);\n if (modified && !this.preventUpdate) {\n this.updatePage();\n }\n };\n /** @private */\n Diagram.prototype.removeFromAQuad = function (obj) {\n this.spatialSearch.removeFromAQuad(obj.wrapper);\n var modified = this.spatialSearch.updateBounds(obj.wrapper);\n if (modified && !this.preventUpdate) {\n this.updatePage();\n }\n };\n /** @private */\n Diagram.prototype.updateGroupSize = function (node) {\n var tempNode;\n if (node.parentId) {\n tempNode = this.nameTable[node.parentId];\n if (tempNode.parentId) {\n this.updateGroupSize(tempNode);\n }\n else {\n tempNode.wrapper.measure(new Size());\n tempNode.wrapper.arrange(tempNode.wrapper.desiredSize);\n this.updateGroupOffset(tempNode);\n this.updateDiagramObject(tempNode);\n }\n }\n };\n Diagram.prototype.updatePage = function () {\n if (this.diagramActions & DiagramAction.Render) {\n this.scroller.setSize();\n this.scroller.updateScrollOffsets();\n //updating overview\n for (var _i = 0, _a = this.views; _i < _a.length; _i++) {\n var temp = _a[_i];\n var view = this.views[temp];\n if (!(view instanceof Diagram)) {\n view.updateView(view);\n }\n }\n }\n };\n /** @private */\n Diagram.prototype.protectPropertyChange = function (enable) {\n this.isProtectedOnChange = enable;\n };\n /** @private */\n Diagram.prototype.updateMargin = function (node, changes) {\n if (changes.margin.top !== undefined) {\n node.margin.top = changes.margin.top;\n }\n if (changes.margin.bottom !== undefined) {\n node.margin.bottom = changes.margin.bottom;\n }\n if (changes.margin.left !== undefined) {\n node.margin.left = changes.margin.left;\n }\n if (changes.margin.right !== undefined) {\n node.margin.right = changes.margin.right;\n }\n };\n //property changes - end region\n /* tslint:disable */\n Diagram.prototype.initDroppables = function () {\n var _this = this;\n // initiates droppable event\n this.droppable = new Droppable(this.element);\n this.droppable.accept = '.e-dragclone';\n // tslint:disable-next-line:no-any\n this.droppable.over = function (args) {\n if (!_this.currentSymbol) {\n if (args.dragData) {\n var newObj = void 0;\n var position = _this.eventHandler.getMousePosition(args.event);\n var clonedObject = void 0;\n var selectedSymbol = args.dragData.helper;\n var paletteId = selectedSymbol.getAttribute('paletteId');\n if (paletteId) {\n var sourceElement = document.getElementById(paletteId).ej2_instances[0];\n var source = 'sourceElement';\n _this.droppable[source] = sourceElement;\n var selectedSymbols = 'selectedSymbols';\n if (sourceElement) {\n var obj = sourceElement[selectedSymbols];\n clonedObject = cloneObject(sourceElement[selectedSymbols]);\n var wrapper = obj.wrapper.children[0].children[0];\n if (sourceElement[selectedSymbols] instanceof Node) {\n clonedObject.offsetX = position.x + 5 + (clonedObject.width || wrapper.actualSize.width) / 2;\n clonedObject.offsetY = position.y + (clonedObject.height || wrapper.actualSize.height) / 2;\n var newNode = new Node(_this, 'nodes', clonedObject, true);\n if (newNode.shape.type === 'Bpmn' && newNode.shape.activity.subProcess.processes\n && newNode.shape.activity.subProcess.processes.length) {\n newNode.shape.activity.subProcess.processes = [];\n }\n newObj = newNode;\n }\n else if (sourceElement[selectedSymbols] instanceof Connector) {\n newObj = new Connector(_this, 'connectors', clonedObject, true);\n var bounds = Rect.toBounds([newObj.sourcePoint, newObj.targetPoint]);\n var tx = position.x - bounds.center.x;\n var ty = position.y - bounds.center.y;\n newObj.sourcePoint.x += tx;\n newObj.sourcePoint.y += ty;\n newObj.targetPoint.x += tx;\n newObj.targetPoint.y += ty;\n }\n newObj.id += randomId();\n var arg = {\n source: sourceElement, element: newObj, cancel: false,\n diagram: _this\n };\n _this.triggerEvent(DiagramEvent.dragEnter, arg);\n if (!_this.activeLayer.lock && !arg.cancel) {\n _this['enterObject'] = newObj;\n _this.preventUpdate = true;\n _this.initObject(newObj);\n _this.currentSymbol = newObj;\n if (_this.mode !== 'SVG') {\n _this.refreshDiagramLayer();\n }\n delete _this['enterObject'];\n _this.commandHandler.select(newObj);\n _this.eventHandler.mouseDown(args.event);\n _this.eventHandler.mouseMove(args.event, args);\n _this.preventUpdate = false;\n _this.updatePage();\n selectedSymbol.style.opacity = '0';\n }\n }\n _this.droppable[selectedSymbols] = selectedSymbol;\n }\n }\n }\n else {\n if (args.event.touches && args.event.touches.length) {\n _this.eventHandler.mouseMove(args.event, args.event.touches);\n }\n }\n };\n // tslint:disable-next-line:no-any\n this.droppable.drop = function (args) {\n if (_this.currentSymbol) {\n if (args.event.touches) {\n _this.eventHandler.mouseUp(args.event);\n }\n var newObj = void 0;\n var node = void 0;\n var conn = void 0;\n var source = 'sourceElement';\n var arg = {\n source: _this.droppable[source],\n element: _this.currentSymbol, target: _this, cancel: false,\n position: { x: _this.currentSymbol.wrapper.offsetX, y: _this.currentSymbol.wrapper.offsetY }\n };\n _this.triggerEvent(DiagramEvent.drop, arg);\n var clonedObject = void 0;\n var id = 'id';\n clonedObject = cloneObject(_this.currentSymbol);\n _this.removeFromAQuad(_this.currentSymbol);\n _this.removeObjectsFromLayer(_this.nameTable[_this.currentSymbol.id]);\n _this.removeElements(_this.currentSymbol);\n delete _this.nameTable[_this.currentSymbol.id];\n _this.currentSymbol = null;\n _this.protectPropertyChange(true);\n if (!arg.cancel) {\n _this.startGroupAction();\n _this.add(clonedObject);\n if (canSingleSelect(_this)) {\n _this.select([_this.nameTable[clonedObject[id]]]);\n }\n }\n _this.protectPropertyChange(false);\n newObj = _this.nameTable[clonedObject[id]];\n if (_this.bpmnModule && newObj instanceof Node && clonedObject.processId) {\n newObj.processId = clonedObject.processId;\n _this.bpmnModule.dropBPMNchild(_this.nameTable[newObj.processId], newObj, _this);\n }\n _this.endGroupAction();\n if (_this.mode !== 'SVG') {\n _this.refreshDiagramLayer();\n }\n delete _this.droppable[source];\n }\n var selectedSymbols = 'selectedSymbols';\n remove(_this.droppable[selectedSymbols]);\n };\n this.droppable.out = function (args) {\n if (_this.currentSymbol && !_this.eventHandler.focus) {\n _this.unSelect(_this.currentSymbol);\n _this.removeFromAQuad(_this.currentSymbol);\n if (_this.mode !== 'SVG' && _this.currentSymbol.shape.type === 'Native') {\n _this.removeElements(_this.currentSymbol);\n }\n _this.removeObjectsFromLayer(_this.nameTable[_this.currentSymbol.id]);\n delete _this.nameTable[_this.currentSymbol.id];\n _this.triggerEvent(DiagramEvent.dragLeave, { element: _this.currentSymbol, diagram: _this });\n if (_this.mode !== 'SVG') {\n _this.refreshDiagramLayer();\n }\n else {\n _this.removeElements(_this.currentSymbol);\n }\n _this.currentSymbol = null;\n var selectedSymbols = 'selectedSymbols';\n _this.droppable[selectedSymbols].style.opacity = '1';\n var source = 'sourceElement';\n delete _this.droppable[source];\n }\n };\n };\n __decorate([\n Property('100%')\n ], Diagram.prototype, \"width\", void 0);\n __decorate([\n Property('SVG')\n ], Diagram.prototype, \"mode\", void 0);\n __decorate([\n Property('100%')\n ], Diagram.prototype, \"height\", void 0);\n __decorate([\n Complex({}, ContextMenuSettings)\n ], Diagram.prototype, \"contextMenuSettings\", void 0);\n __decorate([\n Property(DiagramConstraints.Default)\n ], Diagram.prototype, \"constraints\", void 0);\n __decorate([\n Property(DiagramTools.Default)\n ], Diagram.prototype, \"tool\", void 0);\n __decorate([\n Property('Top')\n ], Diagram.prototype, \"bridgeDirection\", void 0);\n __decorate([\n Property('transparent')\n ], Diagram.prototype, \"backgroundColor\", void 0);\n __decorate([\n Complex({}, SnapSettings)\n ], Diagram.prototype, \"snapSettings\", void 0);\n __decorate([\n Complex({}, RulerSettings)\n ], Diagram.prototype, \"rulerSettings\", void 0);\n __decorate([\n Complex({}, PageSettings)\n ], Diagram.prototype, \"pageSettings\", void 0);\n __decorate([\n Collection([], Node)\n ], Diagram.prototype, \"nodes\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"drawingObject\", void 0);\n __decorate([\n Collection([], Connector)\n ], Diagram.prototype, \"connectors\", void 0);\n __decorate([\n Property([])\n ], Diagram.prototype, \"basicElements\", void 0);\n __decorate([\n Complex({}, DiagramTooltip)\n ], Diagram.prototype, \"tooltip\", void 0);\n __decorate([\n Complex({}, DataSource)\n ], Diagram.prototype, \"dataSourceSettings\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"addInfo\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"getNodeDefaults\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"getConnectorDefaults\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"setNodeTemplate\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"getDescription\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"getCustomProperty\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"getCustomTool\", void 0);\n __decorate([\n Property()\n ], Diagram.prototype, \"getCustomCursor\", void 0);\n __decorate([\n Complex({}, Selector)\n ], Diagram.prototype, \"selectedItems\", void 0);\n __decorate([\n Complex({}, ScrollSettings)\n ], Diagram.prototype, \"scrollSettings\", void 0);\n __decorate([\n Complex({}, Layout)\n ], Diagram.prototype, \"layout\", void 0);\n __decorate([\n Complex({}, CommandManager)\n ], Diagram.prototype, \"commandManager\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"dataLoaded\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"dragEnter\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"dragLeave\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"dragOver\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"click\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"historyChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"doubleClick\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"textEdit\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"scrollChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"selectionChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"sizeChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"connectionChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"sourcePointChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"targetPointChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"propertyChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"positionChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"animationComplete\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"rotateChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"collectionChange\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"mouseEnter\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"mouseLeave\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"mouseOver\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"contextMenuOpen\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"contextMenuClick\", void 0);\n __decorate([\n Collection([], Layer)\n ], Diagram.prototype, \"layers\", void 0);\n __decorate([\n Event()\n ], Diagram.prototype, \"drop\", void 0);\n return Diagram;\n}(Component));\nexport { Diagram };\n","import { Browser } from '@syncfusion/ej2-base';\nimport { CanvasRenderer } from './rendering/canvas-renderer';\nimport { DiagramRenderer } from './rendering/renderer';\nimport { Size } from './primitives/size';\nimport { setAttributeHtml, setAttributeSvg } from './utility/dom-util';\nimport { Rect } from './primitives/rect';\nimport { createSvgElement, getHTMLLayer } from './utility/dom-util';\nimport { getDiagramLayerSvg } from './utility/dom-util';\nimport { DiagramHtmlElement } from './core/elements/html-element';\nimport { DiagramNativeElement } from './core/elements/native-element';\n/**\n * Print and Export Settings\n */\nvar PrintAndExport = /** @class */ (function () {\n function PrintAndExport(diagram) {\n this.diagram = diagram;\n }\n /**\n * To Export the diagram\n * @private\n */\n PrintAndExport.prototype.exportDiagram = function (options) {\n var fileType;\n var customBounds;\n var content;\n var content1 = '';\n var data = 'data';\n var mode;\n var buffers = [];\n var margin = options.margin || {};\n var region = options && options.region ? options.region : 'Content';\n mode = options && options.mode ? options.mode : 'Download';\n var bounds = this.getDiagramBounds(region, options);\n if (options.bounds) {\n customBounds = true;\n bounds.x = options.bounds.x ? options.bounds.x : bounds.x;\n bounds.y = options.bounds.y ? options.bounds.y : bounds.y;\n bounds.width = options.bounds.width || bounds.width;\n bounds.height = options.bounds.height || bounds.height;\n }\n margin = {\n top: margin.top !== undefined ? margin.top : 25,\n bottom: margin.bottom !== undefined ? margin.bottom : 25,\n right: margin.right !== undefined ? margin.right : 25,\n left: margin.left !== undefined ? margin.left : 25\n };\n var nodes = this.diagram.nodes;\n if (region !== 'PageSettings') {\n bounds.x -= margin.left;\n bounds.y -= margin.top;\n bounds.width += margin.left + margin.right;\n bounds.height += margin.top + margin.bottom;\n }\n var fileName = options.fileName || 'diagram';\n if (options.format !== 'SVG') {\n data = this.setCanvas(options, bounds, margin, mode, customBounds, region, fileName);\n if (data !== null) {\n return data;\n }\n }\n else {\n fileType = options.format;\n options.bounds = bounds;\n options.margin = margin;\n var svg = content = this.diagramAsSvg(options, margin);\n if (mode === 'Data') {\n return content;\n }\n var buffer = new XMLSerializer().serializeToString(svg);\n buffers.push(buffer);\n }\n if (mode === 'Download' && data !== null) {\n var browserInfo = void 0;\n // Ensure this for Safari\n // if (Browser.info.name === 'msie' && Number(Browser.info.version) < 10 || Browser.info.name === 'webkit') {\n // let info: string = Browser.info.name === 'webkit' ? 'Safari' : 'IE-9';\n // alert('Downloading option is not supported in ' + info + ', Please use the returned data');\n // return content;\n // } else {\n for (var b = 0; b < buffers.length; b++) {\n var blob = new Blob([buffers[b]], { type: 'application/octet-stream' });\n if (Browser.info.name === 'msie') {\n window.navigator.msSaveOrOpenBlob(blob, fileName + '.' + fileType);\n }\n else {\n var pom = document.createElement('a');\n var url = URL.createObjectURL(blob);\n pom.href = url;\n pom.setAttribute('download', fileName + '.' + fileType);\n var e = document.createEvent('MouseEvents');\n e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n pom.dispatchEvent(e);\n }\n }\n }\n return null;\n };\n PrintAndExport.prototype.setCanvas = function (options, bounds, margin, mode, customBounds, region, fileName) {\n var _this = this;\n var fileType;\n var content;\n options.bounds = bounds;\n options.region = region;\n var scaleX = 'scaleX';\n var scaleY = 'scaleY';\n var images = [];\n this.setScaleValueforCanvas(options, bounds);\n var canvas = this.diagramAsCanvas({\n bounds: bounds, margin: margin, region: region, scaleX: options[scaleX],\n scaleY: options[scaleY]\n }, customBounds);\n fileType = options.format || 'JPG';\n var image = content = canvas.toDataURL();\n if (mode === 'Data') {\n return content;\n }\n if (options.multiplePage) {\n options.pageHeight = options.pageHeight ? options.pageHeight : this.diagram.pageSettings.height;\n options.pageWidth = options.pageWidth ? options.pageWidth : this.diagram.pageSettings.width;\n options.pageHeight = options.pageHeight ? options.pageHeight : canvas.width;\n options.pageWidth = options.pageWidth ? options.pageWidth : canvas.height;\n margin = options.margin || {};\n if (options.pageOrientation) {\n if ((options.pageOrientation === 'Landscape' && options.pageHeight > options.pageWidth) ||\n options.pageOrientation === 'Portrait' && options.pageWidth > options.pageHeight) {\n var temp = options.pageWidth;\n options.pageWidth = options.pageHeight;\n options.pageHeight = temp;\n }\n }\n options.margin = {\n top: !isNaN(margin.top) ? margin.top : 0,\n bottom: !isNaN(margin.bottom) ? margin.bottom : 0,\n left: !isNaN(margin.left) ? margin.left : 0,\n right: !isNaN(margin.right) ? margin.right : 0\n };\n var img_1 = document.createElement('img');\n var attr = {\n 'id': this.diagram.element.id + '_printImage',\n 'src': image,\n };\n img_1.setAttribute('id', this.diagram.element.id + '_printImage');\n setAttributeHtml(img_1, attr);\n img_1.onload = function () {\n images = _this.getMultipleImage(img_1, options, true);\n _this.exportImage(images, fileName, fileType, image);\n };\n }\n else {\n images = [image];\n this.exportImage(images, fileName, fileType, image);\n }\n return null;\n };\n PrintAndExport.prototype.exportImage = function (images, fileName, fileType, image) {\n var buffers = [];\n var length = (!(images instanceof HTMLElement)) ? images.length : 0;\n for (var g = 0; g < length; g++) {\n image = images[g];\n image = image.replace(/^data:[a-z]*;,/, '');\n var image1 = image.split(',');\n var byteString = atob(image1[1]);\n var buffer = new ArrayBuffer(byteString.length);\n var intArray = new Uint8Array(buffer);\n for (var i = 0; i < byteString.length; i++) {\n intArray[i] = byteString.charCodeAt(i);\n }\n buffers.push(buffer);\n }\n var _loop_1 = function (j) {\n var b = new Blob([buffers[j]], { type: 'application/octet-stream' });\n if (Browser.info.name === 'msie') {\n window.navigator.msSaveOrOpenBlob(b, fileName + '.' + fileType);\n }\n else {\n var htmlElement_1 = document.createElement('a');\n var urlLink = URL.createObjectURL(b);\n htmlElement_1.href = urlLink;\n htmlElement_1.setAttribute('download', fileName + '.' + fileType);\n var mouseEvent_1 = document.createEvent('MouseEvents');\n mouseEvent_1.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n setTimeout(function () {\n htmlElement_1.dispatchEvent(mouseEvent_1);\n }, ((j + 1) * 5));\n }\n };\n // Ensure this for safari\n // if (Browser.info.name === 'msie' && Number(Browser.info.version) < 10 || Browser.info.name === 'webkit') {\n // let browserInfo: string = Browser.info.name === 'webkit' ? 'Safari' : 'IE-9';\n // alert('Downloading option is not supported in ' + browserInfo + ', Please use the returned data');\n // return content;\n // } else {\n for (var j = 0; j < buffers.length; j++) {\n _loop_1(j);\n }\n };\n PrintAndExport.prototype.getObjectsBound = function (options) {\n var nodes = this.diagram.nodes;\n var nodebounds;\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var node = nodes_1[_i];\n if (node.visible) {\n if (((options.format !== 'SVG' && !(node instanceof DiagramNativeElement) && !(node instanceof DiagramHtmlElement))\n || (options.format === 'SVG' && !(node instanceof DiagramHtmlElement)))) {\n if (!nodebounds) {\n nodebounds = node.wrapper.outerBounds;\n }\n else {\n nodebounds = nodebounds.uniteRect(node.wrapper.outerBounds);\n }\n }\n }\n }\n var connectors = this.diagram.connectors;\n for (var _a = 0, connectors_1 = connectors; _a < connectors_1.length; _a++) {\n var connector = connectors_1[_a];\n if (connector.visible) {\n if (!nodebounds) {\n nodebounds = connector.wrapper.outerBounds;\n }\n else {\n nodebounds = nodebounds.uniteRect(connector.wrapper.outerBounds);\n }\n }\n }\n return nodebounds || new Rect(0, 0, 0, 0);\n };\n PrintAndExport.prototype.getDiagramBounds = function (mode, options) {\n var rect = this.getObjectsBound(options);\n var left = rect.left;\n var top = rect.top;\n var right = rect.right - rect.left;\n var bottom = rect.bottom - rect.top;\n if (mode !== 'Content') {\n if (this.diagram.pageSettings && this.diagram.pageSettings.multiplePage) {\n left = rect.left;\n top = rect.top;\n if (this.diagram.pageSettings.width) {\n left = Math.floor(left / this.diagram.pageSettings.width) * this.diagram.pageSettings.width;\n right = Math.ceil(rect.right / this.diagram.pageSettings.width) * this.diagram.pageSettings.width - left;\n }\n if (this.diagram.pageSettings.height) {\n top = Math.floor(top / this.diagram.pageSettings.height) * this.diagram.pageSettings.height;\n bottom = Math.ceil(rect.bottom / this.diagram.pageSettings.height) * this.diagram.pageSettings.height - top;\n }\n if ((rect.width === 0) && this.diagram.pageSettings.width !== null) {\n right = this.diagram.pageSettings.width;\n }\n if ((rect.height === 0) && this.diagram.pageSettings.height !== null) {\n bottom = this.diagram.pageSettings.height;\n }\n }\n else {\n if (this.diagram.pageSettings.width) {\n left = 0;\n right = this.diagram.pageSettings.width;\n }\n if (this.diagram.pageSettings.height) {\n top = 0;\n bottom = this.diagram.pageSettings.height;\n }\n }\n }\n var svgBounds = new Rect();\n svgBounds.x = left;\n svgBounds.y = top;\n svgBounds.width = right;\n svgBounds.height = bottom;\n return svgBounds;\n };\n PrintAndExport.prototype.setScaleValueforCanvas = function (options, bounds) {\n var scaleX = 'scaleX';\n var scaleY = 'scaleY';\n options[scaleX] = 1;\n options[scaleY] = 1;\n options.pageHeight = options.pageHeight || this.diagram.pageSettings.height;\n options.pageWidth = options.pageWidth || this.diagram.pageSettings.width;\n var height = options.pageHeight || bounds.height;\n var width = options.pageWidth || bounds.width;\n if (options.stretch === 'Stretch' || options.stretch === 'Meet' || options.stretch === 'Slice') {\n options[scaleX] = width / bounds.width;\n options[scaleY] = height / bounds.height;\n if (options.stretch === 'Meet') {\n options[scaleX] = options[scaleY] = Math.min(options[scaleX], options[scaleY]);\n }\n else if (options.stretch === 'Slice') {\n options[scaleX] = options[scaleY] = Math.max(options[scaleX], options[scaleY]);\n }\n bounds.width = width;\n bounds.height = height;\n }\n bounds.x *= options[scaleX];\n bounds.y *= options[scaleY];\n };\n PrintAndExport.prototype.diagramAsSvg = function (options, margin) {\n var svg = this.diagram.createSvg(this.diagram.element.id + '_diagram_svg', options.bounds.width, options.bounds.height);\n document.body.appendChild(svg);\n var g = createSvgElement('g', { 'id': this.diagram.element.id + '_pageBackground' });\n var region = options && options.region ? options.region : 'Content';\n var bounds = this.getDiagramBounds(region, options);\n var left = bounds.x;\n var top = bounds.y;\n var width = bounds.width;\n var height = bounds.height;\n svg.appendChild(g);\n var attr = {\n 'transform': 'translate(' + (-options.bounds.x + margin.left) + ', ' + (-options.bounds.y + margin.top) + ')',\n 'x': String(left),\n 'y': String(top), 'width': String(width), 'height': String(height)\n };\n setAttributeSvg(g, attr);\n var backRect = document.getElementById(this.diagram.element.id + '_backgroundLayerrect').cloneNode(true);\n attr = {\n 'x': 0,\n 'y': 0, 'width': String(width + margin.left + margin.right), 'height': String(height + margin.top + margin.bottom)\n };\n setAttributeSvg(backRect, attr);\n svg.appendChild(backRect);\n if (this.diagram.mode === 'SVG') {\n var diagramLayerSVG = getDiagramLayerSvg(this.diagram.element.id);\n svg.appendChild(diagramLayerSVG.getElementById(this.diagram.diagramLayer.id).cloneNode(true));\n for (var i = 0; i < svg.childNodes.length; i++) {\n var element = svg.childNodes[i];\n if (element.id === 'diagram_diagramLayer') {\n element.setAttribute('transform', 'translate(' + (-bounds.x + margin.left) + ', ' +\n (-bounds.y + margin.top) + ')');\n }\n }\n }\n else {\n g = createSvgElement('g', { 'id': this.diagram.element.id + '_diagramLayer' });\n svg.appendChild(g);\n g.setAttribute('transform', 'translate(' + (-options.bounds.x + margin.left) + ', ' +\n (-options.bounds.y + margin.top) + ')');\n var nodes = this.diagram.nodes;\n //renderLabels\n var renderer = new DiagramRenderer('', null, true);\n var htmlLayer = getHTMLLayer(this.diagram.element.id);\n this.diagram.renderDiagramElements(svg, renderer, htmlLayer, false);\n }\n document.body.removeChild(svg);\n return svg;\n };\n PrintAndExport.prototype.diagramAsCanvas = function (options, customBounds) {\n var scaleX = 'scaleX';\n var scaleY = 'scaleY';\n var element;\n var elements = [];\n var region = options.bounds;\n var margin = options.margin;\n var mode = options && options.region ? options.region : 'Content';\n var pageBounds = this.getDiagramBounds(mode, options);\n var bgColor = this.diagram.pageSettings.background.color;\n var canvas = CanvasRenderer.createCanvas(this.diagram.element.id + '_diagram', options.bounds.width, options.bounds.height);\n //canvas.setAttribute('style', 'position:absolute;top:135px;left:160px;');\n var context = canvas.getContext('2d');\n context.translate(-region.x, -region.y);\n context.save();\n context.fillStyle = this.diagram.pageSettings.background.color;\n region = mode === 'Content' ? pageBounds : region;\n context.fillRect(region.x, region.y, region.width, region.height);\n var bgImg = this.diagram.pageSettings.background;\n if (bgImg && bgImg.source) {\n pageBounds = this.getDiagramBounds(mode, options);\n var image = new Image();\n image.src = bgImg.source;\n var proportionX = pageBounds.width / image.width;\n var proportionY = pageBounds.height / image.height;\n var x = pageBounds.x;\n var y = pageBounds.y;\n var width = pageBounds.width;\n var height = pageBounds.height;\n var exportable = this.isImageExportable(bgImg);\n if (bgImg.scale !== 'None' && bgImg.align !== 'None') {\n var proportion = bgImg.scale === 'Meet' ? Math.min(proportionX, proportionY) : Math.max(proportionX, proportionY);\n width = proportion * image.width;\n height = proportion * image.height;\n if (bgImg.align.indexOf('xmid') > -1) {\n x += (pageBounds.width - width) / 2;\n }\n else if (bgImg.align.indexOf('xmax') > -1) {\n x = x + pageBounds.width - width;\n }\n if (bgImg.align.indexOf('ymid') > -1) {\n y += (pageBounds.height - height) / 2;\n }\n else if (bgImg.align.indexOf('ymax') > -1) {\n y = y + pageBounds.height - height;\n }\n if (this.diagram.pageSettings.background.color === 'none' || this.diagram.pageSettings.background.color === 'transparent') {\n context.fillStyle = 'white';\n context.fillRect(pageBounds.x * options[scaleX], pageBounds.y * options[scaleY], pageBounds.width * options[scaleX], pageBounds.height * options[scaleY]);\n }\n if (exportable) {\n context.drawImage(image, x, y, proportion * image.width, proportion * image.height);\n }\n }\n else if (exportable) {\n context.drawImage(image, x, y, pageBounds.width, pageBounds.height);\n }\n }\n else {\n context.fillStyle = bgColor === 'transparent' ? 'white' : bgColor;\n context.fillRect((pageBounds.x * options[scaleX]) - margin.left, (pageBounds.y * options[scaleY]) - margin.top, (pageBounds.width * options[scaleX]) + margin.left + margin.right, (options[scaleY] * pageBounds.height) + margin.top + margin.bottom);\n }\n var brColor = this.diagram.pageSettings.background.color;\n var brWidth = this.diagram.pageSettings.width;\n if (brWidth) {\n context.strokeStyle = brColor === 'none' ? 'transparent' : brColor;\n context.lineWidth = brWidth;\n context.strokeRect(pageBounds.x * options[scaleX], pageBounds.y * options[scaleY], pageBounds.width * options[scaleX], pageBounds.height * options[scaleY]);\n }\n context.restore();\n var htmlLayer = getHTMLLayer(this.diagram.element.id);\n var renderer = new DiagramRenderer('', null, false);\n this.diagram.renderDiagramElements(canvas, renderer, htmlLayer, false);\n return canvas;\n };\n PrintAndExport.prototype.isImageExportable = function (backgroundImage) {\n var state = true;\n var content;\n var canvas;\n if (backgroundImage.source) {\n try {\n canvas = CanvasRenderer.createCanvas(this.diagram.element.id + 'temp_canvas', 100, 100);\n var ctx = canvas.getContext('2d');\n ctx.save();\n var image = new Image();\n image.src = backgroundImage.source;\n ctx.drawImage(image, 0, 0, 100, 100);\n ctx.restore();\n content = canvas.toDataURL();\n }\n catch (e) {\n state = false;\n }\n }\n return state;\n };\n PrintAndExport.prototype.getPrintCanvasStyle = function (img, options) {\n var width = 0;\n var height = 0;\n var size = new Size();\n width = img.width;\n height = img.height;\n if (options.pageHeight || options.pageWidth) {\n height = options.pageHeight ? options.pageHeight : height;\n width = options.pageWidth ? options.pageWidth : width;\n }\n if (options.pageOrientation) {\n if ((options.pageOrientation === 'Landscape' && height > width) || options.pageOrientation === 'Portrait' && width > height) {\n var temp = width;\n width = height;\n height = temp;\n }\n }\n size.height = height;\n size.width = width;\n return size;\n };\n PrintAndExport.prototype.getMultipleImage = function (img, options, isExport) {\n var imageArray = [];\n var div = document.createElement('div');\n var pageSize = this.getPrintCanvasStyle(img, options);\n var pageWidth;\n var pageHeight;\n var margin = options.margin;\n var mLeft = margin.left;\n var mTop = margin.top;\n var mRight = margin.right;\n var mBottom = margin.bottom;\n var x = 0;\n var y = 0;\n pageWidth = pageSize.width + x;\n pageHeight = pageSize.height + y;\n var drawnX = 0;\n var drawnY = 0;\n if (options && options.multiplePage && !(options.region === 'Content')) {\n div.style.height = 'auto';\n div.style.width = 'auto';\n var imgHeight = img.height;\n var imgWidth = img.width;\n //if (img) {\n var i = 0;\n var j = 0;\n var url = void 0;\n var clipWidth = 0;\n var clipHeight = 0;\n var ctx = void 0;\n var canvas = void 0;\n do {\n do {\n clipWidth = pageSize.width;\n clipHeight = pageSize.height;\n if ((drawnX + pageSize.width) >= imgWidth) {\n clipWidth = (imgWidth - drawnX);\n }\n if ((drawnY + pageSize.height) >= imgHeight) {\n clipHeight = (imgHeight - drawnY);\n }\n canvas = CanvasRenderer.createCanvas(this.diagram.element.id + '_multiplePrint', pageSize.width, pageSize.height);\n ctx = canvas.getContext('2d');\n ctx.drawImage(img, x + drawnX + mLeft, y + drawnY + mTop, clipWidth - mRight - mLeft, clipHeight - mBottom - mTop, 0 + mLeft, 0 + mTop, clipWidth - mRight - mLeft, clipHeight - mBottom - mTop);\n if ((drawnX + pageSize.width) >= imgWidth) {\n drawnX -= (drawnX - imgWidth);\n }\n url = canvas.toDataURL();\n ctx.restore();\n drawnX += pageWidth;\n if (isExport) {\n imageArray.push(url);\n }\n else {\n this.printImage(div, url, i + '' + j, pageWidth + 'px;', pageHeight + 'px;');\n }\n i++;\n } while (drawnX < imgWidth);\n j++;\n i = x = drawnX = 0;\n if ((drawnY + pageSize.height) >= imgHeight) {\n drawnY -= (drawnY - imgHeight);\n }\n drawnY += pageHeight;\n } while (drawnY < imgHeight);\n //}\n }\n else {\n var x_1 = 0;\n var y_1 = 0;\n var pageSize_1 = this.getPrintCanvasStyle(img, options);\n var pageWidth_1;\n var pageHeight_1;\n pageWidth_1 = pageSize_1.width;\n pageHeight_1 = pageSize_1.height;\n var ctx = void 0;\n var canvas = void 0;\n var url = void 0;\n canvas = CanvasRenderer.createCanvas(this.diagram.element.id + '_diagram', pageWidth_1, pageHeight_1);\n ctx = canvas.getContext('2d');\n ctx.drawImage(img, x_1 + mLeft, y_1 + mTop, img.width - (mRight + mLeft), img.height - (mTop + mBottom), 0 + mLeft, 0 + mTop, pageWidth_1 - (mRight + mLeft), pageHeight_1 - (mTop + mBottom));\n url = canvas.toDataURL();\n ctx.restore();\n this.printImage(div, url, 0);\n }\n if (isExport) {\n return imageArray;\n }\n else {\n return div;\n }\n };\n PrintAndExport.prototype.printImage = function (div, url, i, pageWidth, pageHeight) {\n var img = document.createElement('img');\n var attr;\n var innerDiv = document.createElement('div');\n attr = { 'class': 'e-diagram-print-page', 'style': 'width:' + pageWidth + 'height:' + pageHeight };\n setAttributeHtml(img, attr);\n setAttributeHtml(innerDiv, attr);\n attr = { 'id': this.diagram.element.id + '_multiplePrint_img' + i, 'style': 'float:left', 'src': url };\n setAttributeHtml(img, attr);\n innerDiv.appendChild(img);\n div.appendChild(innerDiv);\n };\n /**\n * To print the image\n * @private\n */\n PrintAndExport.prototype.print = function (options) {\n var _this = this;\n options.mode = 'Data';\n options.margin = { top: 0, bottom: 0, right: 0, left: 0 };\n var url = this.exportDiagram(options);\n var img = document.createElement('img');\n var attr = {\n 'id': this.diagram.element.id + '_printImage',\n 'src': url,\n };\n setAttributeHtml(img, attr);\n img.onload = function () {\n var div = _this.getMultipleImage(img, options);\n // specify window parameters\n var printWind = window.open('');\n if (printWind != null) {\n if ((div instanceof HTMLElement)) {\n printWind.document.write('
');\n printWind.document.write('');\n printWind.document.write('
' + div.innerHTML + ' ');\n printWind.document.close();\n }\n }\n };\n };\n /**\n * To destroy the Print and Export module\n * @return {void}\n * @private\n */\n PrintAndExport.prototype.destroy = function () {\n /**\n * Destroys the Print and Export module\n */\n };\n /**\n * Get module name.\n */\n PrintAndExport.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'PrintandExport';\n };\n return PrintAndExport;\n}());\nexport { PrintAndExport };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Container } from './container';\nimport { rotateSize } from '../../utility/base-util';\n/**\n * StackPanel module is used to arrange its children in a line\n */\nvar StackPanel = /** @class */ (function (_super) {\n __extends(StackPanel, _super);\n function StackPanel() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /**\n * Gets/Sets the orientation of the stack panel\n */\n _this.orientation = 'Vertical';\n /**\n * Not applicable for canvas\n * @private\n */\n _this.measureChildren = undefined;\n return _this;\n }\n /**\n * Measures the minimum space that the panel needs\n * @param availableSize\n */\n StackPanel.prototype.measure = function (availableSize) {\n var updateSize = this.orientation === 'Horizontal' ? this.updateHorizontalStack : this.updateVerticalStack;\n this.desiredSize = this.measureStackPanel(availableSize, updateSize);\n return this.desiredSize;\n };\n /**\n * Arranges the child elements of the stack panel\n * @param desiredSize\n */\n StackPanel.prototype.arrange = function (desiredSize) {\n var updateSize = this.orientation === 'Horizontal' ? this.arrangeHorizontalStack : this.arrangeVerticalStack;\n this.actualSize = this.arrangeStackPanel(desiredSize, updateSize);\n this.updateBounds();\n return this.actualSize;\n };\n /**\n * Measures the minimum space that the panel needs\n * @param availableSize\n */\n StackPanel.prototype.measureStackPanel = function (availableSize, updateSize) {\n var desired = undefined;\n if (this.children !== undefined && this.children.length > 0) {\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n child.parentTransform = this.rotateAngle + this.parentTransform;\n //Measure children\n child.measure(availableSize);\n var childSize = child.desiredSize.clone();\n //Consider Child's margin\n this.applyChildMargin(child, childSize);\n //Consider children's rotation\n if (child.rotateAngle !== 0) {\n childSize = rotateSize(childSize, child.rotateAngle);\n }\n //Measure stack panel\n if (desired === undefined) {\n desired = childSize;\n }\n else {\n updateSize(childSize, desired);\n }\n }\n }\n desired = _super.prototype.validateDesiredSize.call(this, desired, availableSize);\n this.stretchChildren(desired);\n //Considering padding values\n this.applyPadding(desired);\n return desired;\n };\n StackPanel.prototype.arrangeStackPanel = function (desiredSize, updatePosition) {\n if (this.children !== undefined && this.children.length > 0) {\n var x = void 0;\n var y = void 0;\n x = this.offsetX - desiredSize.width * this.pivot.x + this.padding.left;\n y = this.offsetY - desiredSize.height * this.pivot.y + this.padding.top;\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n var childSize = child.desiredSize.clone();\n var rotatedSize = childSize;\n if (this.orientation === 'Vertical') {\n y += child.margin.top;\n }\n else {\n x += child.margin.left;\n }\n if (child.rotateAngle !== 0) {\n rotatedSize = rotateSize(childSize, child.rotateAngle);\n }\n var center = updatePosition(x, y, child, this, desiredSize, rotatedSize);\n _super.prototype.findChildOffsetFromCenter.call(this, child, center);\n child.arrange(childSize);\n if (this.orientation === 'Vertical') {\n y += rotatedSize.height + child.margin.bottom;\n }\n else {\n x += rotatedSize.width + child.margin.right;\n }\n }\n }\n return desiredSize;\n };\n StackPanel.prototype.updateHorizontalStack = function (child, parent) {\n parent.height = Math.max(child.height, parent.height);\n parent.width += child.width;\n };\n StackPanel.prototype.updateVerticalStack = function (child, parent) {\n parent.width = Math.max(child.width, parent.width);\n parent.height += child.height;\n };\n StackPanel.prototype.arrangeHorizontalStack = function (x, y, child, parent, parenBounds, childBounds) {\n var centerY = 0;\n if (child.verticalAlignment === 'Top') {\n centerY = y + child.margin.top + childBounds.height / 2;\n }\n else if (child.verticalAlignment === 'Bottom') {\n var parentBottom = parent.offsetY + parenBounds.height * (1 - parent.pivot.y);\n centerY = parentBottom - parent.padding.bottom - child.margin.bottom - childBounds.height / 2;\n }\n else {\n centerY = parent.offsetY - parenBounds.height * parent.pivot.y + parenBounds.height / 2;\n }\n return { x: x + childBounds.width / 2, y: centerY };\n };\n StackPanel.prototype.arrangeVerticalStack = function (x, y, child, parent, parentSize, childSize) {\n var centerX = 0;\n if (child.horizontalAlignment === 'Left') {\n centerX = x + child.margin.left + childSize.width / 2;\n }\n else if (child.horizontalAlignment === 'Right') {\n var parentRight = parent.offsetX + parentSize.width * (1 - parent.pivot.x);\n centerX = parentRight - parent.padding.right - child.margin.right - childSize.width / 2;\n }\n else {\n centerX = parent.offsetX - parentSize.width * parent.pivot.x + parentSize.width / 2;\n }\n return { x: centerX, y: y + childSize.height / 2 };\n };\n StackPanel.prototype.stretchChildren = function (size) {\n if (this.children !== undefined && this.children.length > 0) {\n for (var _i = 0, _a = this.children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (this.orientation === 'Vertical') {\n if (child.horizontalAlignment === 'Stretch') {\n child.desiredSize.width = size.width;\n }\n }\n else {\n if (child.verticalAlignment === 'Stretch') {\n child.desiredSize.height = size.height;\n }\n }\n }\n }\n };\n StackPanel.prototype.applyChildMargin = function (child, size) {\n size.height += child.margin.top + child.margin.bottom;\n size.width += child.margin.left + child.margin.right;\n };\n return StackPanel;\n}(Container));\nexport { StackPanel };\n","import { Node } from '../objects/node';\nimport { Connector } from '../objects/connector';\nimport { DataManager } from '@syncfusion/ej2-data';\nimport { randomId, getFunction } from '../utility/base-util';\n/**\n * data source defines the basic unit of diagram\n */\nvar DataBinding = /** @class */ (function () {\n /**\n * Constructor for the data binding module.\n * @private\n */\n function DataBinding() {\n this.dataTable = {};\n //constructs the data binding module\n }\n /**\n * To destroy the data binding module\n * @return {void}\n * @private\n */\n DataBinding.prototype.destroy = function () {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name.\n */\n DataBinding.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'DataBinding';\n };\n /**\n * Initialize nodes and connectors when we have a data as JSON\n * @param data\n * @param diagram\n * @private\n */\n DataBinding.prototype.initData = function (data, diagram) {\n var dataSource;\n var dataProp = 'data';\n var jsonProp = 'json';\n var dataManager = data.dataManager || {};\n dataSource = data.data || dataManager[dataProp] || dataManager[jsonProp] ||\n (dataManager.dataSource ? dataManager.dataSource.json : undefined);\n if (dataSource && dataSource.length) {\n this.applyDataSource(data, dataSource, diagram);\n }\n };\n /**\n * Initialize nodes and connector when we have a data as remote url\n * @param data\n * @param diagram\n * @private\n */\n DataBinding.prototype.initSource = function (data, diagram) {\n var _this = this;\n var dataSource = data;\n var result;\n var mapper = data;\n if (dataSource.dataManager instanceof DataManager) {\n var query = mapper.dataManager.defaultQuery;\n data.dataManager.executeQuery(query).then(function (e) {\n var prop = 'result';\n result = e[prop];\n if (!diagram.isDestroyed) {\n _this.applyDataSource(data, result, diagram);\n diagram.refreshDiagram();\n diagram.trigger('dataLoaded', { diagram: diagram });\n }\n });\n }\n };\n DataBinding.prototype.applyDataSource = function (mapper, data, diagram) {\n this.dataTable = {};\n var obj;\n var firstNode;\n var rootNodes = [];\n var firstLevel = [];\n var item;\n var nextLevel;\n if (data !== undefined) {\n for (var r = 0; r < data.length; r++) {\n obj = data[r];\n if (obj[mapper.parentId] === undefined || obj[mapper.parentId] === null ||\n typeof obj[mapper.parentId] !== 'object') {\n if (rootNodes[obj[mapper.parentId]] !== undefined) {\n rootNodes[obj[mapper.parentId]].items.push(obj);\n }\n else {\n rootNodes[obj[mapper.parentId]] = { items: [obj] };\n }\n }\n else {\n rootNodes = this.updateMultipleRootNodes(obj, rootNodes, mapper, data);\n }\n if (mapper.root === obj[mapper.id]) {\n firstNode = { items: [obj] };\n }\n }\n if (firstNode) {\n firstLevel.push(firstNode);\n }\n else {\n for (var _i = 0, _a = Object.keys(rootNodes); _i < _a.length; _i++) {\n var n = _a[_i];\n if (!n || n === 'undefined' || n === '\\'\\'' || n === 'null') {\n firstLevel.push(rootNodes[n]);\n }\n }\n }\n for (var i = 0; i < firstLevel.length; i++) {\n for (var j = 0; j < firstLevel[i].items.length; j++) {\n item = firstLevel[i].items[j];\n var node = this.applyNodeTemplate(mapper, item, diagram);\n diagram.nodes.push(node);\n this.dataTable[item[mapper.id]] = node;\n nextLevel = rootNodes[node.data[mapper.id]];\n if (nextLevel !== undefined) {\n this.renderChildNodes(mapper, nextLevel, node.id, rootNodes, diagram);\n }\n }\n }\n }\n this.dataTable = null;\n };\n /**\n * updateMultipleRootNodes method is used to update the multiple Root Nodes\n * @param object\n * @param rootnodes\n * @param mapper\n * @param data\n */\n DataBinding.prototype.updateMultipleRootNodes = function (obj, rootNodes, mapper, data) {\n var parents = obj[mapper.parentId];\n var parent;\n for (var i = 0; i < parents.length; i++) {\n parent = parents[i];\n if (rootNodes[parent]) {\n rootNodes[parent].items.push(obj);\n }\n else {\n rootNodes[parent] = { items: [obj] };\n }\n }\n return rootNodes;\n };\n /**\n * Get the node values\n * @param mapper\n * @param item\n * @param diagram\n */\n DataBinding.prototype.applyNodeTemplate = function (mapper, item, diagram) {\n var root = item;\n var id = randomId();\n var nodeModel = { id: id, data: item };\n var doBinding = getFunction(mapper.doBinding);\n if (doBinding) {\n doBinding(nodeModel, item, diagram);\n }\n var obj = new Node(diagram, 'nodes', nodeModel, true);\n if (!this.collectionContains(obj, diagram, mapper.id, mapper.parentId)) {\n return obj;\n }\n else {\n return this.dataTable[item[mapper.id]];\n }\n };\n DataBinding.prototype.renderChildNodes = function (mapper, parent, value, rtNodes, diagram) {\n var child;\n var nextLevel;\n var node;\n for (var j = 0; j < parent.items.length; j++) {\n child = parent.items[j];\n node = this.applyNodeTemplate(mapper, child, diagram);\n var canBreak = false;\n if (!this.collectionContains(node, diagram, mapper.id, mapper.parentId)) {\n this.dataTable[child[mapper.id]] = node;\n diagram.nodes.push(node);\n }\n else {\n canBreak = true;\n }\n if (!this.containsConnector(diagram, value, node.id)) {\n diagram.connectors.push(this.applyConnectorTemplate(value, node.id, diagram));\n }\n if (!canBreak) {\n nextLevel = rtNodes[node.data[mapper.id]];\n if (nextLevel !== undefined) {\n this.renderChildNodes(mapper, nextLevel, node.id, rtNodes, diagram);\n }\n }\n }\n };\n DataBinding.prototype.containsConnector = function (diagram, sourceNode, targetNode) {\n if (sourceNode !== '' && targetNode !== '') {\n for (var i = 0; i < diagram.connectors.length; i++) {\n var connector = diagram.connectors[i];\n if (connector !== undefined && (connector.sourceID === sourceNode && connector.targetID === targetNode)) {\n return true;\n }\n }\n }\n return false;\n };\n /**\n * collectionContains method is used to check wthear the node is already present in collection or not\n * @param node\n * @param diagram\n * @param id\n * @param parentId\n */\n DataBinding.prototype.collectionContains = function (node, diagram, id, parentId) {\n var obj = this.dataTable[node.data[id]];\n if (obj !== undefined && obj.data[id] === node.data[id] && obj.data[parentId] === node.data[parentId]) {\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Get the Connector values\n * @param sourceNode\n * @param targetNode\n * @param diagram\n */\n DataBinding.prototype.applyConnectorTemplate = function (sNode, tNode, diagram) {\n var connModel = {\n id: randomId(), sourceID: sNode, targetID: tNode\n };\n var obj = new Connector(diagram, 'connectors', connModel, true);\n return obj;\n };\n return DataBinding;\n}());\nexport { DataBinding };\n","import { createElement, remove } from '@syncfusion/ej2-base';\nimport { ContextMenu as Menu } from '@syncfusion/ej2-navigations';\nimport { contextMenuClick, contextMenuOpen } from '../enum/enum';\n/**\n * @private\n */\nexport var menuClass = {\n content: '.e-diagramcontent',\n copy: 'e-copy',\n paste: 'e-paste',\n undo: 'e-undo',\n redo: 'e-redo',\n cut: 'e-cut',\n selectAll: 'e-selectall',\n grouping: 'e-grouping',\n group: 'e-group',\n unGroup: 'e-ungroup',\n bringToFront: 'e-bringfront',\n sendToBack: 'e-sendback',\n moveForward: 'e-bringforward',\n sendBackward: 'e-sendbackward',\n order: 'e-order'\n};\n/**\n * 'ContextMenu module used to handle context menu actions.'\n * @private\n */\nvar DiagramContextMenu = /** @class */ (function () {\n function DiagramContextMenu(parent, service) {\n this.defaultItems = {};\n /**\n * @private\n */\n this.disableItems = [];\n /**\n * @private\n */\n this.hiddenItems = [];\n this.localeText = this.setLocaleKey();\n this.parent = parent;\n this.serviceLocator = service;\n this.addEventListener();\n }\n /**\n * @hidden\n * @private\n */\n DiagramContextMenu.prototype.addEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on('initial-load', this.render, this);\n };\n /**\n * @hidden\n * @private\n */\n DiagramContextMenu.prototype.removeEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off('initial-load', this.render);\n };\n DiagramContextMenu.prototype.render = function () {\n this.l10n = this.serviceLocator.getService('localization');\n this.element = createElement('ul', { id: this.parent.element.id + '_contextMenu' });\n this.parent.element.appendChild(this.element);\n var target = '#' + this.parent.element.id;\n this.contextMenu = new Menu({\n items: this.getMenuItems(),\n enableRtl: this.parent.enableRtl,\n enablePersistence: this.parent.enablePersistence,\n locale: this.parent.locale,\n target: target,\n select: this.contextMenuItemClick.bind(this),\n beforeOpen: this.contextMenuBeforeOpen.bind(this),\n onOpen: this.contextMenuOpen.bind(this),\n onClose: this.contextMenuOnClose.bind(this),\n cssClass: 'e-diagram-menu'\n });\n this.contextMenu.appendTo(this.element);\n };\n DiagramContextMenu.prototype.getMenuItems = function () {\n var menuItems = [];\n var orderItems = [];\n var groupItems = [];\n if (!this.parent.contextMenuSettings.showCustomMenuOnly) {\n for (var _i = 0, _a = this.getDefaultItems(); _i < _a.length; _i++) {\n var item = _a[_i];\n if (item.toLocaleLowerCase().indexOf('group') !== -1) {\n if (item.toLocaleLowerCase() !== 'grouping') {\n groupItems.push(this.buildDefaultItems(item));\n }\n }\n else if (item.toLocaleLowerCase().indexOf('order') !== -1) {\n if (item.toLocaleLowerCase() !== 'order') {\n orderItems.push(this.buildDefaultItems(item));\n }\n }\n else {\n menuItems.push(this.buildDefaultItems(item));\n }\n }\n if (groupItems.length > 0) {\n var orderGroup = this.buildDefaultItems('grouping');\n orderGroup.items = groupItems;\n menuItems.push(orderGroup);\n }\n if (orderItems.length > 0) {\n var orderGroup = this.buildDefaultItems('order');\n orderGroup.items = orderItems;\n menuItems.push(orderGroup);\n }\n }\n if (this.parent.contextMenuSettings.items) {\n for (var _b = 0, _c = this.parent.contextMenuSettings.items; _b < _c.length; _b++) {\n var customItem = _c[_b];\n menuItems.push(customItem);\n }\n }\n return menuItems;\n };\n DiagramContextMenu.prototype.contextMenuOpen = function () {\n this.isOpen = true;\n };\n DiagramContextMenu.prototype.contextMenuItemClick = function (args) {\n var item = this.getKeyFromId(args.item.id);\n switch (item) {\n case 'cut':\n this.parent.cut();\n break;\n case 'copy':\n this.parent.copy();\n break;\n case 'undo':\n this.parent.undo();\n break;\n case 'redo':\n this.parent.redo();\n break;\n case 'paste':\n this.parent.paste();\n break;\n case 'selectAll':\n this.parent.selectAll();\n break;\n case 'group':\n this.parent.group();\n break;\n case 'unGroup':\n this.parent.unGroup();\n break;\n case 'bringToFrontOrder':\n this.parent.bringToFront();\n break;\n case 'moveForwardOrder':\n this.parent.moveForward();\n break;\n case 'sendToBackOrder':\n this.parent.sendToBack();\n break;\n case 'sendBackwardOrder':\n this.parent.sendBackward();\n break;\n }\n document.getElementById(this.parent.element.id + 'content').focus();\n this.parent.trigger(contextMenuClick, args);\n };\n DiagramContextMenu.prototype.contextMenuOnClose = function (args) {\n var parent = 'parentObj';\n if (args.items.length > 0 && args.items[0][parent] instanceof Menu) {\n this.updateItemStatus();\n }\n };\n DiagramContextMenu.prototype.getLocaleText = function (item) {\n return this.l10n.getConstant(this.localeText[item]);\n };\n DiagramContextMenu.prototype.updateItemStatus = function () {\n this.contextMenu.showItems(this.hiddenItems, true);\n this.contextMenu.enableItems(this.disableItems, false, true);\n this.hiddenItems = [];\n this.disableItems = [];\n this.isOpen = false;\n };\n DiagramContextMenu.prototype.ensureItems = function (item, event) {\n var key = this.getKeyFromId(item.id);\n var dItem = this.defaultItems[key];\n if (this.getDefaultItems().indexOf(key) !== -1) {\n if (item.target && event &&\n !this.ensureTarget(item)) {\n this.hiddenItems.push(item.id);\n }\n }\n };\n DiagramContextMenu.prototype.contextMenuBeforeOpen = function (args) {\n var diagramArgs = args;\n diagramArgs.hiddenItems = [];\n for (var _i = 0, _a = args.items; _i < _a.length; _i++) {\n var item = _a[_i];\n this.ensureItems(item, args.event);\n if (item.items.length) {\n for (var _b = 0, _c = item.items; _b < _c.length; _b++) {\n var newItem = _c[_b];\n this.ensureItems(newItem, args.event);\n }\n }\n }\n this.eventArgs = args.event;\n this.parent.trigger(contextMenuOpen, diagramArgs);\n if (diagramArgs.items.length === diagramArgs.hiddenItems.length) {\n diagramArgs.cancel = true;\n diagramArgs.hiddenItems = [];\n }\n else {\n this.hiddenItems = this.hiddenItems.concat(diagramArgs.hiddenItems);\n this.contextMenu.enableItems(this.disableItems, false, true);\n this.contextMenu.hideItems(this.hiddenItems, true);\n }\n };\n DiagramContextMenu.prototype.ensureTarget = function (item) {\n var selectedLength = this.parent.selectedItems.nodes.length +\n this.parent.selectedItems.connectors.length;\n var itemText = this.getKeyFromId(item.id);\n var target = false;\n switch (itemText) {\n case 'undo':\n target = this.parent.historyList && this.parent.historyList.canUndo ? true : false;\n break;\n case 'redo':\n target = this.parent.historyList && this.parent.historyList.canRedo ? true : false;\n break;\n case 'paste':\n target = this.parent.commandHandler.clipboardData.clipObject ? true : false;\n break;\n case 'selectAll':\n target = this.parent.nodes.length + this.parent.connectors.length ? true : false;\n break;\n case 'grouping':\n target = ((selectedLength > 1) || (this.parent.selectedItems.nodes[0] && this.parent.selectedItems.nodes[0].children\n && this.parent.selectedItems.nodes[0].children.length > 1)) ? true : false;\n break;\n case 'group':\n target = selectedLength > 1;\n break;\n case 'unGroup':\n target = ((this.parent.selectedItems.nodes[0] && this.parent.selectedItems.nodes[0].children\n && this.parent.selectedItems.nodes[0].children.length > 1)) ? true : false;\n break;\n case 'cut':\n case 'copy':\n case 'order':\n case 'bringToFrontOrder':\n case 'moveForwardOrder':\n case 'sendToBackOrder':\n case 'sendBackwardOrder':\n target = selectedLength ? true : false;\n break;\n }\n return target;\n };\n /**\n * To destroy the Context menu.\n * @method destroy\n * @return {void}\n * @private\n */\n DiagramContextMenu.prototype.destroy = function () {\n this.contextMenu.destroy();\n remove(this.element);\n this.removeEventListener();\n };\n DiagramContextMenu.prototype.getModuleName = function () {\n return 'contextMenu';\n };\n DiagramContextMenu.prototype.generateID = function (item) {\n return this.parent.element.id + '_contextMenu_' + item;\n };\n DiagramContextMenu.prototype.getKeyFromId = function (id) {\n return id.replace(this.parent.element.id + '_contextMenu_', '');\n };\n DiagramContextMenu.prototype.buildDefaultItems = function (item) {\n var menuItem;\n switch (item) {\n case 'copy':\n menuItem = { target: menuClass.content, iconCss: menuClass.copy };\n break;\n case 'cut':\n menuItem = { target: menuClass.content, iconCss: menuClass.cut };\n break;\n case 'paste':\n menuItem = { target: menuClass.content, iconCss: menuClass.paste };\n break;\n case 'undo':\n menuItem = { target: menuClass.content, iconCss: menuClass.undo };\n break;\n case 'redo':\n menuItem = { target: menuClass.content, iconCss: menuClass.redo };\n break;\n case 'grouping':\n menuItem = { target: menuClass.content };\n break;\n case 'group':\n menuItem = { target: menuClass.content, iconCss: menuClass.group };\n break;\n case 'unGroup':\n menuItem = { target: menuClass.content, iconCss: menuClass.unGroup };\n break;\n case 'order':\n menuItem = { target: menuClass.content, iconCss: menuClass.order };\n break;\n case 'bringToFrontOrder':\n menuItem = { target: menuClass.content, iconCss: menuClass.bringToFront };\n break;\n case 'moveForwardOrder':\n menuItem = { target: menuClass.content, iconCss: menuClass.moveForward };\n break;\n case 'sendToBackOrder':\n menuItem = { target: menuClass.content, iconCss: menuClass.sendToBack };\n break;\n case 'sendBackwardOrder':\n menuItem = { target: menuClass.content, iconCss: menuClass.sendBackward };\n break;\n case 'selectAll':\n menuItem = { target: menuClass.content };\n break;\n }\n this.defaultItems[item] = {\n text: this.getLocaleText(item), id: this.generateID(item),\n target: menuItem.target, iconCss: menuItem.iconCss ? 'e-icons ' + menuItem.iconCss : ''\n };\n return this.defaultItems[item];\n };\n DiagramContextMenu.prototype.getDefaultItems = function () {\n return [\n 'copy',\n 'cut', 'paste', 'undo', 'redo', 'selectAll', 'grouping', 'group', 'unGroup', 'order',\n 'bringToFrontOrder', 'moveForwardOrder', 'sendToBackOrder', 'sendBackwardOrder'\n ];\n };\n DiagramContextMenu.prototype.setLocaleKey = function () {\n return {\n 'copy': 'Copy',\n 'cut': 'Cut',\n 'paste': 'Paste',\n 'undo': 'Undo',\n 'redo': 'Redo',\n 'selectAll': 'SelectAll',\n 'grouping': 'Grouping',\n 'group': 'Group',\n 'unGroup': 'UnGroup',\n 'order': 'Order',\n 'bringToFrontOrder': 'BringToFront',\n 'moveForwardOrder': 'MoveForward',\n 'sendToBackOrder': 'SendToBack',\n 'sendBackwardOrder': 'SendBackward'\n };\n };\n return DiagramContextMenu;\n}());\nexport { DiagramContextMenu };\n","import { Point } from '../primitives/point';\nimport { Rect } from '../primitives/rect';\nimport { intersect3 } from '../utility/diagram-util';\nimport { canBridge } from '../utility/constraints-util';\n/**\n * ConnectorBridging defines the bridging behavior\n */\n/** @private */\nvar ConnectorBridging = /** @class */ (function () {\n /**\n * Constructor for the bridging module\n * @private\n */\n function ConnectorBridging() {\n //constructs the bridging module\n }\n /** @private */\n ConnectorBridging.prototype.updateBridging = function (conn, diagram) {\n var lastBridge = [];\n var bounds;\n conn.bridges = [];\n if (canBridge(conn, diagram)) {\n // if (this.canBridge(conn, diagram)) {\n var points1 = this.getPoints(conn);\n bounds = Rect.toBounds(points1);\n var bridgeSpacing = conn.bridgeSpace;\n var bgedir = diagram.bridgeDirection;\n var count = -1;\n var quads = diagram.connectors;\n for (var q = 0; q < quads.length; q++) {\n var connector1 = quads[q];\n if (conn && connector1 && conn.id !== connector1.id) {\n var points2 = this.getPoints(connector1);\n var bounds1 = Rect.toBounds(points2);\n if (this.intersectsRect(bounds, bounds1)) {\n var intersectPts = this.intersect(points1, points2, false, bgedir, true);\n if (intersectPts.length > 0) {\n for (var i = 0; i < intersectPts.length; i++) {\n var fullLength = 0;\n var length_1 = 0;\n var segmentIndex = 0;\n var pointIndex = 0;\n var obj = this.getLengthAtFractionPoint(conn, intersectPts[i]);\n if (obj.pointIndex !== -1) {\n length_1 = obj.lengthFractionIndex;\n fullLength = obj.fullLength;\n segmentIndex = obj.segmentIndex;\n pointIndex = obj.pointIndex;\n var stBridge = this.getPointAtLength((length_1 - (bridgeSpacing / 2)), points1);\n var enBridge = this.getPointAtLength((length_1 + (bridgeSpacing / 2)), points1);\n var fractLength = (length_1 - (bridgeSpacing / 2)) / fullLength;\n fractLength = (length_1 + (bridgeSpacing / 2)) / fullLength;\n if (this.isEmptyPoint(enBridge)) {\n enBridge = stBridge;\n }\n var start = void 0;\n var end = void 0;\n start = conn.sourcePoint;\n if (conn.type === 'Straight') {\n end = conn.targetPoint;\n }\n else {\n end = conn.intermediatePoints[pointIndex];\n }\n var angle = this.angleCalculation(start, end);\n if (lastBridge.length) {\n var fixedPoint = void 0;\n fixedPoint = conn.sourcePoint;\n var fix = Math.abs(this.lengthCalculation(fixedPoint, enBridge));\n var var1 = 0;\n var insertAt = -1;\n count = -1;\n for (var k = 0; k < lastBridge[segmentIndex].bridges.length; k++) {\n count++;\n var arcSeg = lastBridge[segmentIndex].bridges[k];\n var1 = Math.abs(this.lengthCalculation(fixedPoint, arcSeg.endPoint));\n if (fix < var1) {\n insertAt = count;\n break;\n }\n }\n if (insertAt >= 0) {\n var paths = void 0;\n paths = this.createSegment(stBridge, enBridge, angle, bgedir, pointIndex, conn, diagram);\n paths.target = connector1.id;\n lastBridge[segmentIndex].bridges.splice(insertAt, 0, paths);\n lastBridge[segmentIndex].bridges.join();\n lastBridge[segmentIndex].bridgeStartPoint.splice(insertAt, 0, stBridge);\n lastBridge[segmentIndex].bridgeStartPoint.join();\n lastBridge[segmentIndex].segmentIndex = segmentIndex;\n }\n else {\n var paths = void 0;\n paths = this.createSegment(stBridge, enBridge, angle, bgedir, pointIndex, conn, diagram);\n paths.target = connector1.id;\n lastBridge[segmentIndex].bridges.push(paths);\n lastBridge[segmentIndex].bridgeStartPoint.push(stBridge);\n lastBridge[segmentIndex].segmentIndex = segmentIndex;\n }\n }\n else {\n if (!isNaN(stBridge.x) && !isNaN(stBridge.y) && !this.isEmptyPoint(enBridge)) {\n var arcs = void 0;\n var bges = [];\n var bgept = [];\n arcs = this.createSegment(stBridge, enBridge, angle, bgedir, pointIndex, conn, diagram);\n var bgseg = {\n bridges: bges, bridgeStartPoint: bgept, segmentIndex: segmentIndex\n };\n arcs.target = connector1.id;\n var stPoints = [];\n var edPoints = [];\n stPoints.push(stBridge);\n edPoints.push(enBridge);\n lastBridge[segmentIndex] = bgseg;\n lastBridge[segmentIndex].bridges.push(arcs);\n lastBridge[segmentIndex].bridgeStartPoint = stPoints;\n lastBridge[segmentIndex].segmentIndex = segmentIndex;\n }\n }\n }\n }\n }\n }\n }\n }\n if (lastBridge.length !== 0) {\n this.firstBridge(lastBridge, conn, bridgeSpacing);\n }\n }\n };\n /** @private */\n ConnectorBridging.prototype.firstBridge = function (bridgeList, connector, bridgeSpacing) {\n for (var i = 0; i < bridgeList.length; i++) {\n var bridge = bridgeList[i];\n for (var k = 1; k < bridge.bridges.length; k++) {\n if (Point.findLength(bridge.bridges[k].endPoint, bridge.bridges[k - 1].endPoint) < bridgeSpacing) {\n bridge.bridges[k - 1].endPoint = bridge.bridges[k].endPoint;\n var subBridge = bridge.bridges[k - 1];\n var arc = this.createBridgeSegment(subBridge.startPoint, subBridge.endPoint, subBridge.angle, bridgeSpacing, subBridge.sweep);\n bridge.bridges[k - 1].path = arc;\n bridge.bridges.splice(k, 1);\n bridge.bridgeStartPoint.splice(k, 1);\n k--;\n }\n }\n var pre = connector.sourcePoint;\n for (var j = 0; j < bridge.bridges.length; j++) {\n var subBridge = bridge.bridges[j];\n var preventChecking = true;\n pre = subBridge.endPoint;\n connector.bridges.push(subBridge);\n }\n }\n };\n /** @private */\n ConnectorBridging.prototype.createSegment = function (st, end, angle, direction, index, conn, diagram) {\n var arc;\n var sweep;\n var path = {\n angle: 0, endPoint: { x: 0, y: 0 }, target: '', path: '',\n segmentPointIndex: -1, startPoint: { x: 0, y: 0 }, sweep: 1, rendered: false\n };\n sweep = this.sweepDirection(angle, direction, conn, diagram);\n arc = this.createBridgeSegment(st, end, angle, conn.bridgeSpace, sweep);\n path.path = arc;\n path.startPoint = st;\n path.endPoint = end;\n path.angle = angle;\n path.segmentPointIndex = index;\n path.sweep = sweep;\n return path;\n };\n /** @private */\n ConnectorBridging.prototype.createBridgeSegment = function (startPt, endPt, angle, bridgeSpace, sweep) {\n var path = 'A ' + bridgeSpace / 2 + ' ' + bridgeSpace / 2 + ' ' + angle + ' , 1 ' + sweep + ' ' + endPt.x + ',' + endPt.y;\n return path;\n };\n /** @private */\n ConnectorBridging.prototype.sweepDirection = function (angle, bridgeDirection, connector, diagram) {\n var angle1 = Math.abs(angle);\n var sweep;\n switch (bridgeDirection) {\n case 'Top':\n case 'Bottom':\n sweep = 1;\n if (angle1 >= 0 && angle1 <= 90) {\n sweep = 0;\n }\n break;\n case 'Left':\n case 'Right':\n sweep = 1;\n if (angle < 0 && angle >= -180) {\n sweep = 0;\n }\n break;\n }\n if (bridgeDirection === 'Right' || bridgeDirection === 'Bottom') {\n if (sweep === 0) {\n sweep = 1;\n }\n else {\n sweep = 0;\n }\n }\n return sweep;\n };\n /** @private */\n ConnectorBridging.prototype.getPointAtLength = function (length, pts) {\n var run = 0;\n var pre;\n var found = { x: 0, y: 0 };\n for (var i = 0; i < pts.length; i++) {\n var pt = pts[i];\n if (!pre) {\n pre = pt;\n continue;\n }\n else {\n var l = this.lengthCalculation(pre, pt);\n if (run + l > length) {\n var r = length - run;\n var deg = Point.findAngle(pre, pt);\n var x = r * Math.cos(deg * Math.PI / 180);\n var y = r * Math.sin(deg * Math.PI / 180);\n found = { x: pre.x + x, y: pre.y + y };\n break;\n }\n else {\n run += l;\n }\n }\n pre = pt;\n }\n return found;\n };\n /** @private */\n ConnectorBridging.prototype.getPoints = function (connector) {\n var points = [];\n if (connector.intermediatePoints && (connector.type === 'Straight' || connector.type === 'Orthogonal')) {\n for (var j = 0; j < connector.intermediatePoints.length; j++) {\n points.push(connector.intermediatePoints[j]);\n }\n }\n return points;\n };\n ConnectorBridging.prototype.intersectsRect = function (rect1, rect2) {\n return ((((rect2.x < (rect1.x + rect1.width)) && (rect1.x < (rect2.x + rect2.width)))\n && (rect2.y < (rect1.y + rect1.height))) && (rect1.y < (rect2.y + rect2.height)));\n };\n /** @private */\n ConnectorBridging.prototype.intersect = function (points1, points2, self, bridgeDirection, zOrder) {\n if (self && points2.length >= 2) {\n points2.splice(0, 1);\n points2.splice(0, 1);\n }\n var points = [];\n for (var i = 0; i < points1.length - 1; i++) {\n var pt = this.inter1(points1[i], points1[i + 1], points2, zOrder, bridgeDirection);\n if (pt.length > 0) {\n for (var k = 0; k < pt.length; k++) {\n points.push(pt[k]);\n }\n }\n if (self && points2.length >= 1) {\n points2.splice(0, 1);\n }\n }\n return points;\n };\n /** @private */\n ConnectorBridging.prototype.inter1 = function (startPt, endPt, pts, zOrder, bridgeDirection) {\n var points1 = [];\n for (var i = 0; i < pts.length - 1; i++) {\n var point = this.intersect2(startPt, endPt, pts[i], pts[i + 1]);\n if (!this.isEmptyPoint(point)) {\n var angle = this.angleCalculation(startPt, endPt);\n var angle1 = this.angleCalculation(pts[i], pts[i + 1]);\n angle = this.checkForHorizontalLine(angle);\n angle1 = this.checkForHorizontalLine(angle1);\n switch (bridgeDirection) {\n case 'Left':\n case 'Right':\n if (angle > angle1) {\n points1.push(point);\n }\n break;\n case 'Top':\n case 'Bottom':\n if (angle < angle1) {\n points1.push(point);\n }\n break;\n }\n if (angle === angle1 && zOrder) {\n points1.push(point);\n }\n }\n }\n return points1;\n };\n ConnectorBridging.prototype.checkForHorizontalLine = function (angle) {\n var temp = 0;\n var roundedAngle = Math.abs(angle);\n if (roundedAngle > 90) {\n temp = 180 - roundedAngle;\n }\n else {\n temp = roundedAngle;\n }\n return temp;\n };\n ConnectorBridging.prototype.intersect2 = function (start1, end1, start2, end2) {\n var point = { x: 0, y: 0 };\n var lineUtil1 = this.getLineSegment(start1.x, start1.y, end1.x, end1.y);\n var lineUtil2 = this.getLineSegment(start2.x, start2.y, end2.x, end2.y);\n var line3 = intersect3(lineUtil1, lineUtil2);\n if (line3.enabled) {\n return line3.intersectPt;\n }\n else {\n return point;\n }\n };\n /** @private */\n ConnectorBridging.prototype.getLineSegment = function (x1, y1, x2, y2) {\n return { 'X1': Number(x1) || 0, 'Y1': Number(y1) || 0, 'X2': Number(x2) || 0, 'Y2': Number(y2) || 0 };\n };\n ConnectorBridging.prototype.isEmptyPoint = function (point) {\n return point.x === 0 && point.y === 0;\n };\n ConnectorBridging.prototype.getLengthAtFractionPoint = function (connector, pointAt) {\n var lengthFraction;\n var confirm = 100;\n var pointIndex = -1;\n var fullLength = 0;\n var segmentIndex = -1;\n var count = 0;\n var lengthAtFractionPt = 0;\n var pt1 = connector.sourcePoint;\n var previouspt2 = pt1;\n var points = [];\n for (var i = 0; i < connector.intermediatePoints.length; i++) {\n var point2 = connector.intermediatePoints[i];\n points.push(point2);\n }\n for (var j = 0; j < points.length; j++) {\n var pt2 = points[j];\n var suspect = this.getSlope(pt2, pt1, pointAt, connector);\n if (suspect < confirm) {\n confirm = suspect;\n lengthAtFractionPt = fullLength + this.lengthCalculation(pointAt, previouspt2);\n segmentIndex = count;\n pointIndex = j;\n }\n fullLength += Point.findLength(pt2, pt1);\n pt1 = pt2;\n previouspt2 = pt2;\n }\n count++;\n lengthFraction = {\n lengthFractionIndex: lengthAtFractionPt, fullLength: fullLength,\n segmentIndex: segmentIndex, pointIndex: pointIndex\n };\n return lengthFraction;\n };\n ConnectorBridging.prototype.getSlope = function (startPt, endPt, point, connector) {\n var three = 3.0;\n var delX = Math.abs(startPt.x - endPt.x);\n var delY = Math.abs(startPt.y - endPt.y);\n var lhs = ((point.y - startPt.y) / (endPt.y - startPt.y));\n var rhs = ((point.x - startPt.x) / (endPt.x - startPt.x));\n if (!isFinite(lhs) || !isFinite(rhs) || isNaN(lhs) || isNaN(rhs)) {\n if (startPt.x === endPt.x) {\n if (startPt.y === endPt.y) {\n return 10000;\n }\n else if (((startPt.y > point.y) && (point.y > endPt.y)) || ((startPt.y < point.y) && (point.y < endPt.y))) {\n return Math.abs(startPt.x - point.x);\n }\n }\n else if (startPt.y === endPt.y) {\n if (((startPt.x > point.x) && (point.x > endPt.x)) || ((startPt.x < point.x) && (point.x < endPt.x))) {\n return Math.abs(startPt.y - point.y);\n }\n }\n }\n else {\n if ((startPt.x >= point.x && point.x >= endPt.x) || (startPt.x <= point.x && point.x <= endPt.x) || delX < three) {\n if ((startPt.y >= point.y && point.y >= endPt.y) || (startPt.y <= point.y && point.y <= endPt.y) || delY < three) {\n return Math.abs(lhs - rhs);\n }\n }\n }\n return 10000;\n };\n /** @private */\n ConnectorBridging.prototype.angleCalculation = function (startPt, endPt) {\n var xDiff = startPt.x - endPt.x;\n var yDiff = startPt.y - endPt.y;\n return Math.atan2(yDiff, xDiff) * (180 / Math.PI);\n };\n ConnectorBridging.prototype.lengthCalculation = function (startPt, endPt) {\n //removed a try catch from here\n var len = Math.sqrt(((startPt.x - endPt.x) * (startPt.x - endPt.x)) + ((startPt.y - endPt.y) * (startPt.y - endPt.y)));\n return len;\n };\n /**\n * To destroy the bridging module\n * @return {void}\n * @private\n */\n ConnectorBridging.prototype.destroy = function () {\n /**\n * Destroys the bridging module\n */\n };\n /**\n * Get module name.\n */\n ConnectorBridging.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'Bridging';\n };\n return ConnectorBridging;\n}());\nexport { ConnectorBridging };\n","import { Rect } from '../primitives/rect';\nimport { PathElement } from '../core/elements/path-element';\nimport { SnapConstraints } from '../enum/enum';\nimport { Connector } from './connector';\nimport { Selector } from '../interaction/selector';\nimport { getBounds } from './../utility/base-util';\nimport { randomId } from './../utility/base-util';\nimport { getAdornerLayerSvg } from './../utility/dom-util';\nimport { isSelected } from '../interaction/actions';\n/**\n * Snapping\n */\nvar Snapping = /** @class */ (function () {\n function Snapping(diagram) {\n this.line = [];\n this.diagram = diagram;\n }\n /** @private */\n Snapping.prototype.canSnap = function () {\n return (this.diagram.snapSettings.constraints\n & (SnapConstraints.SnapToObject | SnapConstraints.SnapToLines)) !== 0;\n };\n /**\n * Snap to object\n * @private\n */\n Snapping.prototype.snapPoint = function (diagram, selectedObject, towardsLeft, towardsTop, delta, startPoint, endPoint) {\n var snapSettings = this.diagram.snapSettings;\n var zoomFactor = 1;\n var offset = { x: 0, y: 0 };\n var bounds = getBounds(selectedObject.wrapper);\n var horizontallysnapped = { snapped: false, offset: 0 };\n var verticallysnapped = { snapped: false, offset: 0 };\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject) {\n var snapLine = void 0;\n snapLine = document.createElementNS('http://www.w3.org/2000/svg', 'g');\n snapLine.setAttribute('id', '_SnappingLines');\n snapLine.setAttribute('shapeRendering', 'crispEdges');\n getAdornerLayerSvg(this.diagram.element.id).appendChild(snapLine);\n this.snapObject(diagram, selectedObject, snapLine, horizontallysnapped, verticallysnapped, delta, startPoint === endPoint);\n }\n //original position\n var left = bounds.x + delta.x;\n var top = bounds.y + delta.y;\n var right = bounds.x + bounds.width + delta.x;\n var bottom = bounds.y + bounds.height + delta.y;\n var scaledIntervals = snapSettings.verticalGridlines.scaledIntervals;\n //snapped positions\n var roundedRight = this.round(right, scaledIntervals, zoomFactor);\n var roundedLeft = this.round(left, scaledIntervals, zoomFactor);\n scaledIntervals = snapSettings.horizontalGridlines.scaledIntervals;\n var roundedTop = this.round(top, scaledIntervals, zoomFactor);\n var roundedBottom = this.round(bottom, scaledIntervals, zoomFactor);\n //currentposition\n var currentright = bounds.x + bounds.width;\n var currentbottom = bounds.y + bounds.height;\n if (!horizontallysnapped.snapped) {\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToVerticalLines) {\n if (Math.abs(delta.x) >= 1) {\n if (towardsLeft) {\n if (Math.abs(roundedRight - currentright) > Math.abs(roundedLeft - bounds.x)) {\n offset.x += roundedLeft - bounds.x;\n }\n else {\n offset.x += roundedRight - currentright;\n }\n }\n else {\n if (Math.abs(roundedRight - currentright) < Math.abs(roundedLeft - bounds.x)) {\n offset.x += roundedRight - currentright;\n }\n else {\n offset.x += roundedLeft - bounds.x;\n }\n }\n }\n }\n else {\n offset.x = endPoint.x - startPoint.x;\n }\n }\n else {\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject) {\n offset.x = horizontallysnapped.offset;\n }\n else {\n offset.x = endPoint.x - startPoint.x;\n }\n }\n if (!verticallysnapped.snapped) {\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToHorizontalLines) {\n if (Math.abs(delta.y) >= 1) {\n if (towardsTop) {\n if (Math.abs(roundedBottom - currentbottom) > Math.abs(roundedTop - bounds.y)) {\n offset.y += roundedTop - bounds.y;\n }\n else {\n offset.y += roundedBottom - currentbottom;\n }\n }\n else {\n if (Math.abs(roundedBottom - currentbottom) < Math.abs(roundedTop - bounds.y)) {\n offset.y += roundedBottom - currentbottom;\n }\n else {\n offset.y += roundedTop - bounds.y;\n }\n }\n }\n }\n else {\n offset.y = endPoint.y - startPoint.y;\n }\n }\n else {\n offset.y = verticallysnapped.offset;\n }\n return offset;\n };\n /**\n * @private\n */\n Snapping.prototype.round = function (value, snapIntervals, scale) {\n if (scale > 1) {\n scale = Math.pow(2, Math.floor(Math.log(scale) / Math.log(2)));\n }\n else {\n scale = Math.pow(2, Math.ceil(Math.log(scale) / Math.log(2)));\n }\n var cutoff = 0;\n var i = 0;\n for (i = 0; i < snapIntervals.length; i++) {\n cutoff += snapIntervals[i];\n }\n cutoff /= scale;\n var quotient = Math.floor(Math.abs(value) / cutoff);\n var bal = value % cutoff;\n var prev = quotient * cutoff;\n if (prev !== value) {\n if (value >= 0) {\n for (i = 0; i < snapIntervals.length; i++) {\n if (bal <= snapIntervals[i] / scale) {\n return prev + (bal < (snapIntervals[i] / (2 * scale)) ? 0 : snapIntervals[i] / scale);\n }\n else {\n prev += snapIntervals[i] / scale;\n bal -= snapIntervals[i] / scale;\n }\n }\n }\n else {\n prev = prev * -1;\n for (i = snapIntervals.length - 1; i >= 0; i--) {\n if (Math.abs(bal) <= snapIntervals[i] / scale) {\n return prev - (Math.abs(bal) < (snapIntervals[i] / (2 * scale)) ? 0 : snapIntervals[i] / scale);\n }\n else {\n prev -= snapIntervals[i] / scale;\n bal += snapIntervals[i] / scale;\n }\n }\n }\n }\n return value;\n };\n /**\n * Snap to Object\n */\n Snapping.prototype.snapObject = function (diagram, selectedObject, g, horizontalSnap, verticalSnap, delta, ended) {\n var lengthX = null;\n var lengthY;\n var hTarget;\n var vTarget;\n var scroller = this.diagram.scroller;\n var snapSettings = this.diagram.snapSettings;\n var objectsAtLeft = [];\n var objectsAtRight = [];\n var objectsAtTop = [];\n var objectsAtBottom = [];\n var bounds = getBounds(selectedObject.wrapper);\n var scale = diagram.scroller.currentZoom;\n var hoffset = -scroller.horizontalOffset;\n var voffset = -scroller.verticalOffset;\n var snapObjDistance = snapSettings.snapObjectDistance / scale;\n var viewPort = new Rect(0, 0, scroller.viewPortWidth, scroller.viewPortHeight);\n var hIntersectRect = new Rect(hoffset / scale, (bounds.y - snapObjDistance - 5), viewPort.width / scale, (bounds.height + 2 * snapObjDistance + 10));\n var vIntersectRect = new Rect((bounds.x - snapObjDistance - 5), voffset / scale, (bounds.width + 2 * snapObjDistance + 10), viewPort.height / scale);\n viewPort = new Rect(hoffset / scale, voffset / scale, viewPort.width / scale, viewPort.height / scale);\n var nodes = this.findNodes(diagram.spatialSearch, selectedObject, vIntersectRect, viewPort);\n var i;\n var target;\n var targetBounds;\n var nameTable = diagram.nameTable;\n for (i = 0; i < nodes.length; i++) {\n target = nodes[i];\n if (this.canBeTarget(diagram, target)) {\n if (!(this.diagram.nameTable[target.id] instanceof Connector) && this.canConsider(nameTable, selectedObject, target)) {\n targetBounds = target.bounds;\n if (targetBounds.height + targetBounds.y < delta.y + bounds.y) {\n objectsAtTop.push({\n obj: target, distance: Math.abs(bounds.y + delta.y - targetBounds.y - targetBounds.height)\n });\n }\n else if (targetBounds.y > bounds.y + delta.y + bounds.height) {\n objectsAtBottom.push({ obj: target, distance: Math.abs(bounds.y + delta.y + bounds.height - targetBounds.y) });\n }\n if (lengthX == null || lengthX > Math.abs(targetBounds.y - bounds.y - delta.y)) {\n if (Math.abs(targetBounds.x + targetBounds.width / 2 - (bounds.x + bounds.width / 2 + delta.x)) <=\n snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'centerX');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n else if (Math.abs(targetBounds.x + targetBounds.width - (bounds.x + bounds.width + delta.x)) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'right');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n else if (Math.abs(targetBounds.x - (bounds.x + delta.x)) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'left');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n else if (Math.abs(targetBounds.x - (bounds.x + bounds.width + delta.x)) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'rightLeft');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n else if (Math.abs(targetBounds.x + targetBounds.width - (bounds.x + delta.x)) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'leftRight');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n }\n }\n }\n }\n nodes = this.findNodes(diagram.spatialSearch, selectedObject, hIntersectRect, viewPort);\n for (var j = 0; j < nodes.length; j++) {\n target = nodes[j];\n if (this.canBeTarget(diagram, target)) {\n if (!(this.diagram.nameTable[target.id] instanceof Connector) && this.canConsider(nameTable, selectedObject, target)) {\n targetBounds = target.bounds;\n if (targetBounds.x + targetBounds.width < bounds.x + delta.x) {\n objectsAtLeft[objectsAtLeft.length] = {\n obj: target, distance: Math.abs((bounds.x + delta.x) - targetBounds.x - targetBounds.width)\n };\n }\n if (targetBounds.x > bounds.x + delta.x + bounds.width) {\n objectsAtRight[objectsAtRight.length] = {\n obj: target, distance: Math.abs(bounds.x + delta.x + bounds.width - targetBounds.x)\n };\n }\n if (lengthY == null || lengthY > Math.abs(targetBounds.x - bounds.x - delta.x)) {\n if (Math.abs(targetBounds.y + targetBounds.height / 2 - (bounds.y + bounds.height / 2 + delta.y))\n <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds, bounds, 'centerY');\n lengthY = Math.abs(targetBounds.x - bounds.x);\n }\n else if (Math.abs(targetBounds.y - bounds.y - delta.y) <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds, bounds, 'top');\n lengthY = Math.abs(targetBounds.x - bounds.x);\n }\n else if (Math.abs(targetBounds.y + targetBounds.height - (bounds.y + bounds.height + delta.y)) <=\n snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds, bounds, 'bottom');\n lengthY = Math.abs(targetBounds.x - bounds.x);\n }\n else if (Math.abs(targetBounds.y + targetBounds.height - bounds.y - delta.y) <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds, bounds, 'topBottom');\n lengthY = Math.abs(targetBounds.x - bounds.x);\n }\n else if (Math.abs(targetBounds.y - (bounds.y + bounds.height + delta.y)) <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds, bounds, 'bottomTop');\n lengthY = Math.abs(targetBounds.x - bounds.x);\n }\n }\n }\n }\n }\n this.createGuidelines(diagram, hTarget, vTarget, g, horizontalSnap, verticalSnap, ended);\n if (!horizontalSnap.snapped) {\n this.createHSpacingLines(diagram, g, selectedObject, objectsAtLeft, objectsAtRight, horizontalSnap, verticalSnap, ended, delta, snapObjDistance);\n }\n if (!verticalSnap.snapped) {\n this.createVSpacingLines(diagram, g, selectedObject, objectsAtTop, objectsAtBottom, horizontalSnap, verticalSnap, ended, delta, snapObjDistance);\n }\n };\n /**\n * @private\n */\n Snapping.prototype.snapConnectorEnd = function (point) {\n var snapSettings = this.diagram.snapSettings;\n var zoomFactor = 1;\n if (snapSettings.constraints & SnapConstraints.SnapToLines) {\n point.x = this.round(point.x, snapSettings.verticalGridlines.scaledIntervals, zoomFactor);\n point.y = this.round(point.y, snapSettings.horizontalGridlines.scaledIntervals, zoomFactor);\n }\n return point;\n };\n Snapping.prototype.canBeTarget = function (diagram, node) {\n node = this.diagram.nameTable[node.id];\n return !(isSelected(this.diagram, node, false));\n };\n Snapping.prototype.snapSize = function (diagram, horizontalSnap, verticalSnap, snapLine, deltaX, deltaY, selectedObject, ended) {\n var lengthX;\n var lengthY;\n var snapSettings = this.diagram.snapSettings;\n var scroller = this.diagram.scroller;\n var hTarget;\n var vTarget;\n var bounds = getBounds(selectedObject.wrapper);\n var nameTable = diagram.nameTable;\n var sameWidth = [];\n var sameHeight = [];\n var scale = diagram.scroller.currentZoom;\n var hoffset = -scroller.horizontalOffset;\n var voffset = -scroller.verticalOffset;\n var snapObjDistance = snapSettings.snapObjectDistance / scale;\n var viewPort = new Rect(0, 0, scroller.viewPortWidth, scroller.viewPortHeight);\n var hintersectedrect = new Rect(hoffset / scale, (bounds.y - 5) / scale, viewPort.width / scale, (bounds.height + 10) / scale);\n var vintersectedrect = new Rect((bounds.x - 5) / scale, voffset / scale, (bounds.width + 10) / scale, viewPort.height / scale);\n viewPort = new Rect(hoffset / scale, voffset / scale, viewPort.width / scale, viewPort.height / scale);\n var nodesInView = [];\n var nodes = this.findNodes(diagram.spatialSearch, selectedObject, vintersectedrect, viewPort, nodesInView);\n var i;\n var target;\n var targetBounds;\n for (i = 0; i < nodes.length; i++) {\n target = nodes[i];\n if (this.canConsider(nameTable, selectedObject, target) && !(this.diagram.nameTable[target.id] instanceof Connector)) {\n targetBounds = target.bounds;\n if (lengthX == null || lengthX > Math.abs(targetBounds.y - bounds.y)) {\n if (horizontalSnap.left) {\n if (Math.abs(bounds.x + deltaX - targetBounds.x) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'left');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n else if (Math.abs(bounds.x + deltaX - targetBounds.x - targetBounds.width) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'leftRight');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n }\n else if (horizontalSnap.right) {\n if (Math.abs(bounds.x + deltaX + bounds.width - targetBounds.x - targetBounds.width) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'right');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n else if (Math.abs(bounds.x + deltaX + bounds.width - targetBounds.x) <= snapObjDistance) {\n hTarget = this.createSnapObject(targetBounds, bounds, 'rightLeft');\n lengthX = Math.abs(targetBounds.y - bounds.y);\n }\n }\n }\n }\n }\n nodes = this.findNodes(diagram.spatialSearch, selectedObject, hintersectedrect, viewPort);\n for (var i_1 = 0; i_1 < nodes.length; i_1++) {\n var target_1 = nodes[i_1];\n if (this.canConsider(nameTable, selectedObject, target_1) && !(this.diagram.nameTable[target_1.id] instanceof Connector)) {\n var targetBounds_1 = target_1.bounds;\n if (lengthY == null || lengthY > Math.abs(targetBounds_1.x - bounds.x)) {\n if (verticalSnap.top) {\n if (Math.abs(bounds.y + deltaY - targetBounds_1.y) <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds_1, bounds, 'top');\n lengthY = Math.abs(targetBounds_1.x - bounds.x);\n }\n else if (Math.abs(bounds.y + deltaY - targetBounds_1.y - targetBounds_1.height) <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds_1, bounds, 'topBottom');\n lengthY = Math.abs(targetBounds_1.x - bounds.x);\n }\n }\n else if (verticalSnap.bottom) {\n if (Math.abs(bounds.y + bounds.height + deltaY - targetBounds_1.y - targetBounds_1.height) <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds_1, bounds, 'bottom');\n lengthY = Math.abs(targetBounds_1.x - bounds.x);\n }\n else if (Math.abs(bounds.y + bounds.height + deltaY - targetBounds_1.y) <= snapObjDistance) {\n vTarget = this.createSnapObject(targetBounds_1, bounds, 'bottomTop');\n lengthY = Math.abs(targetBounds_1.x - bounds.x);\n }\n }\n }\n }\n }\n for (i = 0; i < nodesInView.length; i++) {\n target = nodesInView[i];\n if (this.canConsider(nameTable, selectedObject, target)) {\n var targetBounds_2 = target.bounds;\n var delta = horizontalSnap.left ? -deltaX : deltaX;\n var difference = Math.abs(bounds.width + delta - targetBounds_2.width);\n var actualDiff = void 0;\n if (difference <= snapObjDistance) {\n actualDiff = horizontalSnap.left ? -targetBounds_2.width + bounds.width : targetBounds_2.width - bounds.width;\n sameWidth[sameWidth.length] = { source: target, difference: difference, offset: actualDiff };\n }\n delta = verticalSnap.top ? -deltaY : deltaY;\n var dify = Math.abs(bounds.height + delta - targetBounds_2.height);\n if (dify <= snapObjDistance) {\n actualDiff = verticalSnap.top ? -targetBounds_2.height + bounds.height : targetBounds_2.height - bounds.height;\n sameHeight[sameHeight.length] = { source: target, difference: dify, offset: actualDiff };\n }\n }\n }\n var g;\n if (!diagram.getTool) {\n var g_1 = this.createGuidelines(diagram, hTarget, vTarget, snapLine, horizontalSnap, verticalSnap, ended);\n }\n if (!horizontalSnap.snapped && sameWidth.length > 0 && (horizontalSnap.left || horizontalSnap.right)) {\n this.addSameWidthLines(diagram, snapLine, sameWidth, horizontalSnap, ended, selectedObject);\n }\n if (!verticalSnap.snapped && sameHeight.length > 0 && (verticalSnap.top || verticalSnap.bottom)) {\n this.addSameHeightLines(diagram, snapLine, sameHeight, verticalSnap, ended, selectedObject);\n }\n };\n /**\n * Snap to object on top\n * @private\n */\n Snapping.prototype.snapTop = function (horizontalSnap, verticalSnap, snapLine, deltaX, deltaY, shape, ended, initialBoundsT) {\n var dify = deltaY;\n verticalSnap.top = true;\n var y;\n horizontalSnap.left = horizontalSnap.right = false;\n var zoomFactor = 1;\n //let initialBoundsT: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height);\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) {\n //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) {\n y = initialBoundsT.y - initialBoundsT.height * shape.pivot.y + deltaY - (shape.offsetY - shape.height * shape.pivot.y);\n this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, deltaX, y, this.diagram.selectedItems, ended);\n }\n if (!verticalSnap.snapped) {\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToHorizontalLines) {\n var top_1 = initialBoundsT.y - initialBoundsT.height * shape.pivot.y;\n var actualTop = top_1 + deltaY;\n var roundedTop = this.round(actualTop, this.diagram.snapSettings.horizontalGridlines.scaledIntervals, zoomFactor);\n dify = roundedTop - top_1;\n }\n }\n else {\n dify = (deltaY - y) + verticalSnap.offset;\n }\n return dify;\n };\n /**\n * Snap to object on right\n * @private\n */\n Snapping.prototype.snapRight = function (horizontalSnap, verticalSnap, snapLine, deltaX, deltaY, shape, ended, initialBound) {\n var difx = deltaX;\n var x;\n horizontalSnap.right = true;\n verticalSnap.top = verticalSnap.bottom = false;\n var zoomFactor = 1;\n //let initialBound: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height);\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) {\n //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) {\n x = initialBound.x + initialBound.width * (1 - shape.pivot.x) + deltaX - (shape.offsetX + shape.width * (1 - shape.pivot.x));\n this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, x, deltaY, this.diagram.selectedItems, ended);\n }\n if (!horizontalSnap.snapped) {\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToVerticalLines) {\n var right = initialBound.x + initialBound.width * (1 - shape.pivot.x);\n var actualRight = right + deltaX;\n var roundedRight = this.round(actualRight, this.diagram.snapSettings.verticalGridlines.scaledIntervals, zoomFactor);\n difx = roundedRight - right;\n }\n }\n else {\n difx = (deltaX - x) + horizontalSnap.offset;\n }\n return difx;\n };\n /**\n * Snap to object on left\n * @private\n */\n Snapping.prototype.snapLeft = function (horizontalSnap, verticalSnap, snapLine, deltaX, deltaY, shape, ended, initialBoundsB) {\n var difx = deltaX;\n var x = 0;\n horizontalSnap.left = true;\n verticalSnap.top = verticalSnap.bottom = false;\n var zoomFactor = 1;\n //let initialBoundsB: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height);\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) {\n //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) {\n x = initialBoundsB.x - initialBoundsB.width * shape.pivot.x + deltaX - (shape.offsetX - shape.width * shape.pivot.x);\n this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, x, deltaY, this.diagram.selectedItems, ended);\n }\n if (!horizontalSnap.snapped) {\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToVerticalLines) {\n var left = initialBoundsB.x - initialBoundsB.width * shape.pivot.x;\n var actualLeft = left + deltaX;\n var roundedLeft = this.round(actualLeft, this.diagram.snapSettings.horizontalGridlines.scaledIntervals, zoomFactor);\n difx = roundedLeft - left;\n }\n }\n else {\n difx = (deltaX - x) + horizontalSnap.offset;\n }\n return difx;\n };\n /**\n * Snap to object on bottom\n * @private\n */\n Snapping.prototype.snapBottom = function (horizontalSnap, verticalSnap, snapLine, deltaX, deltaY, shape, ended, initialRect) {\n var dify = deltaY;\n verticalSnap.bottom = true;\n horizontalSnap.left = horizontalSnap.right = false;\n var zoomFactor = 1;\n var y = 0;\n //let initialRect: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height);\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) {\n //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) {\n y = initialRect.y + initialRect.height * (1 - shape.pivot.y) + deltaY - (shape.offsetY + shape.height * (1 - shape.pivot.y));\n this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, deltaX, y, this.diagram.selectedItems, ended);\n }\n var bounds = getBounds(shape.wrapper);\n if (!verticalSnap.snapped) {\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToHorizontalLines) {\n var bottom = initialRect.y + initialRect.height * (1 - shape.pivot.y);\n var actualBottom = bottom + deltaY;\n var roundedBottom = this.round(actualBottom, this.diagram.snapSettings.horizontalGridlines.scaledIntervals, zoomFactor);\n dify = roundedBottom - bottom;\n }\n }\n else {\n dify = (deltaY - y) + verticalSnap.offset;\n }\n return dify;\n };\n /**\n * To create the same width and same size lines\n */\n Snapping.prototype.createGuidelines = function (diagram, hTarget, vTarget, snapLine, horizontalSnap, verticalSnap, ended) {\n if (hTarget) {\n horizontalSnap.offset = hTarget.offsetX;\n horizontalSnap.snapped = true;\n if (!ended) {\n if (hTarget.type === 'sideAlign') {\n this.renderAlignmentLines(hTarget.start, hTarget.end, snapLine, diagram.scroller.transform);\n }\n else {\n this.renderAlignmentLines(hTarget.start, hTarget.end, snapLine, diagram.scroller.transform);\n }\n }\n }\n if (vTarget) {\n verticalSnap.offset = vTarget.offsetY;\n verticalSnap.snapped = true;\n if (!ended) {\n if (vTarget.type === 'sideAlign') {\n this.renderAlignmentLines(vTarget.start, vTarget.end, snapLine, diagram.scroller.transform);\n }\n else {\n this.renderAlignmentLines(vTarget.start, vTarget.end, snapLine, diagram.scroller.transform);\n }\n }\n }\n return snapLine;\n };\n /**\n * To create the alignment lines\n */\n Snapping.prototype.renderAlignmentLines = function (start, end, svg, transform) {\n start = {\n x: (start.x + transform.tx) * transform.scale,\n y: (start.y + transform.ty) * transform.scale\n };\n end = {\n x: (end.x + transform.tx) * transform.scale,\n y: (end.y + transform.ty) * transform.scale\n };\n var line1 = {\n stroke: '#07EDE1', strokeWidth: 1, startPoint: { x: start.x, y: start.y },\n endPoint: { x: end.x, y: end.y }, fill: '#07EDE1', dashArray: '', width: 1,\n x: 0, y: 0, height: 0, angle: 0, pivotX: 0,\n pivotY: 0, visible: true, opacity: 1, id: randomId()\n };\n var i = 0;\n this.line.push(line1);\n for (i = 0; i < this.line.length; i++) {\n this.diagram.diagramRenderer.drawLine(svg, this.line.pop());\n }\n };\n /**\n * To create Horizontal spacing lines\n */\n Snapping.prototype.createHSpacingLines = function (diagram, g, shape, objectsAtLeft, objectsAtRight, horizontalSnap, verticalSnap, ended, delta, snapObjDistance) {\n var top = 0;\n this.sortByDistance(objectsAtLeft, 'distance', true);\n this.sortByDistance(objectsAtRight, 'distance', true);\n var equallySpaced = [];\n var bounds = getBounds(shape.wrapper);\n var nearestleft;\n var nearestright;\n var targetBounds;\n var equaldistance;\n if (objectsAtLeft.length > 0) {\n equallySpaced[equallySpaced.length] = objectsAtLeft[0];\n nearestleft = ((objectsAtLeft[0].obj).bounds);\n top = nearestleft.y;\n if (objectsAtLeft.length > 1) {\n targetBounds = ((objectsAtLeft[1].obj).bounds);\n equaldistance = nearestleft.x - targetBounds.x - targetBounds.width;\n if (Math.abs(equaldistance - objectsAtLeft[0].distance) <= snapObjDistance) {\n top = this.findEquallySpacedNodesAtLeft(objectsAtLeft, equaldistance, top, equallySpaced);\n }\n else {\n equaldistance = objectsAtLeft[0].distance;\n }\n }\n else {\n equaldistance = objectsAtLeft[0].distance;\n }\n }\n this.sortByDistance(equallySpaced, 'distance');\n equallySpaced[equallySpaced.length] = { obj: shape, distance: 0 };\n top = bounds.y < top || !top ? bounds.y : top;\n if (objectsAtRight.length > 0) {\n var dist = void 0;\n nearestright = ((objectsAtRight[0].obj).bounds);\n top = nearestright.y < top ? nearestright.y : top;\n if (objectsAtRight.length > 1) {\n targetBounds = ((objectsAtRight[1].obj).bounds);\n dist = targetBounds.x - nearestright.x - nearestright.width;\n }\n if (objectsAtLeft.length > 0) {\n if (Math.abs(objectsAtRight[0].distance - objectsAtLeft[0].distance) <= snapObjDistance) {\n var adjustablevalue = Math.abs(objectsAtRight[0].distance - objectsAtLeft[0].distance) / 2;\n (objectsAtRight[0].distance < objectsAtLeft[0].distance) ?\n equaldistance -= adjustablevalue : equaldistance += adjustablevalue;\n equallySpaced[equallySpaced.length] = objectsAtRight[0];\n }\n else if (objectsAtLeft.length === 1) {\n nearestleft = undefined;\n equallySpaced.splice(0, 1);\n equallySpaced[equallySpaced.length] = objectsAtRight[0];\n equaldistance = dist;\n }\n }\n else {\n equaldistance = dist;\n equallySpaced[equallySpaced.length] = objectsAtRight[0];\n }\n if (objectsAtRight.length > 1 && nearestright.x + nearestright.width < targetBounds.x) {\n top = this.findEquallySpacedNodesAtRight(objectsAtRight, dist, top, equallySpaced, snapObjDistance);\n }\n }\n if (equallySpaced.length > 2) {\n this.addHSpacingLines(diagram, g, equallySpaced, ended, top);\n var deltaHorizontal = 0;\n if (ended) {\n deltaHorizontal = delta.x;\n }\n if (nearestleft) {\n horizontalSnap.offset = equaldistance - Math.abs(bounds.x + deltaHorizontal - nearestleft.x - nearestleft.width)\n + deltaHorizontal;\n }\n else if (nearestright) {\n horizontalSnap.offset = Math.abs(bounds.x + bounds.width + deltaHorizontal - nearestright.x)\n - equaldistance + deltaHorizontal;\n }\n horizontalSnap.snapped = true;\n }\n };\n /**\n * To create vertical spacing lines\n */\n Snapping.prototype.createVSpacingLines = function (diagram, g, shape, objectsAtTop, objectsAtBottom, horizontalSnap, verticalSnap, ended, delta, snapObjDistance) {\n var right = 0;\n this.sortByDistance(objectsAtTop, 'distance', true);\n this.sortByDistance(objectsAtBottom, 'distance', true);\n var equallySpaced = [];\n var bounds = getBounds(shape.wrapper);\n var nearesttop;\n var nearestbottom;\n var targetBounds;\n var equaldistance;\n if (objectsAtTop.length > 0) {\n equallySpaced[equallySpaced.length] = objectsAtTop[0];\n nearesttop = ((objectsAtTop[0].obj).bounds);\n right = nearesttop.x + nearesttop.width;\n if (objectsAtTop.length > 1) {\n targetBounds = ((objectsAtTop[1].obj).bounds);\n equaldistance = nearesttop.y - targetBounds.y - targetBounds.height;\n if (Math.abs(equaldistance - objectsAtTop[0].distance) <= snapObjDistance) {\n right = this.findEquallySpacedNodesAtTop(objectsAtTop, equaldistance, right, equallySpaced);\n }\n else {\n equaldistance = objectsAtTop[0].distance;\n }\n }\n else {\n equaldistance = objectsAtTop[0].distance;\n }\n }\n this.sortByDistance(equallySpaced, 'distance');\n equallySpaced[equallySpaced.length] = { obj: shape, distance: 0 };\n right = bounds.x + bounds.width > right || !right ? bounds.x + bounds.width : right;\n var dist;\n if (objectsAtBottom.length > 0) {\n nearestbottom = ((objectsAtBottom[0].obj).bounds);\n right = nearestbottom.x + nearestbottom.width > right ? nearestbottom.x + nearestbottom.width : right;\n if (objectsAtBottom.length > 1) {\n targetBounds = ((objectsAtBottom[1].obj).bounds);\n dist = targetBounds.y - nearestbottom.y - nearestbottom.height;\n }\n if (objectsAtTop.length > 0) {\n if (Math.abs(objectsAtBottom[0].distance - objectsAtTop[0].distance) <= snapObjDistance) {\n var adjustablevalue = Math.abs(objectsAtBottom[0].distance - objectsAtTop[0].distance) / 2;\n (objectsAtBottom[0].distance < objectsAtTop[0].distance) ?\n equaldistance -= adjustablevalue : equaldistance += adjustablevalue;\n equallySpaced[equallySpaced.length] = objectsAtBottom[0];\n }\n else if (objectsAtTop.length === 1) {\n nearesttop = undefined;\n equallySpaced.splice(0, 1);\n equallySpaced[equallySpaced.length] = objectsAtBottom[0];\n equaldistance = dist;\n }\n }\n else {\n equaldistance = dist;\n equallySpaced[equallySpaced.length] = objectsAtBottom[0];\n }\n if (objectsAtBottom.length > 1 && targetBounds.y > nearestbottom.y + nearestbottom.height) {\n right = this.findEquallySpacedNodesAtBottom(objectsAtBottom, dist, right, equallySpaced, snapObjDistance);\n }\n }\n if (equallySpaced.length > 2) {\n this.addVSpacingLines(diagram, g, equallySpaced, ended, right);\n var deltaVertical = 0;\n if (ended) {\n deltaVertical = delta.y;\n }\n if (nearesttop) {\n verticalSnap.offset = equaldistance - Math.abs(bounds.y + deltaVertical - nearesttop.y - nearesttop.height) + deltaVertical;\n }\n else if (nearestbottom) {\n verticalSnap.offset = Math.abs(bounds.y + bounds.height + deltaVertical - nearestbottom.y) - equaldistance + deltaVertical;\n }\n verticalSnap.snapped = true;\n }\n };\n /**\n * Add the Horizontal spacing lines\n */\n Snapping.prototype.addHSpacingLines = function (diagram, g, equallySpaced, ended, top) {\n var i;\n var start;\n var end;\n if (!ended) {\n for (i = 0; i < equallySpaced.length - 1; i++) {\n var crnt = equallySpaced[i].obj instanceof Selector ?\n getBounds((equallySpaced[i].obj).wrapper) : ((equallySpaced[i].obj).bounds);\n var next = equallySpaced[i + 1].obj instanceof Selector ?\n getBounds((equallySpaced[i + 1].obj).wrapper) : ((equallySpaced[i + 1].obj).bounds);\n start = { x: crnt.x + crnt.width, y: top - 15 };\n end = { x: next.x, y: top - 15 };\n this.renderSpacingLines(start, end, g, getAdornerLayerSvg(this.diagram.element.id), diagram.scroller.transform);\n }\n }\n };\n /**\n * Add the vertical spacing lines\n */\n Snapping.prototype.addVSpacingLines = function (diagram, g, equallySpacedObjects, ended, right) {\n var start;\n var end;\n if (!ended) {\n for (var i = 0; i < equallySpacedObjects.length - 1; i++) {\n var crnt = equallySpacedObjects[i].obj instanceof Selector ?\n getBounds((equallySpacedObjects[i].obj).wrapper) : ((equallySpacedObjects[i].obj).bounds);\n var next = equallySpacedObjects[i + 1].obj instanceof Selector ?\n getBounds((equallySpacedObjects[i + 1].obj).wrapper) :\n ((equallySpacedObjects[i + 1].obj).bounds);\n start = { x: right + 15, y: crnt.y + crnt.height };\n end = { x: right + 15, y: next.y };\n this.renderSpacingLines(start, end, g, getAdornerLayerSvg(this.diagram.element.id), diagram.scroller.transform);\n }\n }\n };\n /**\n * To add same width lines\n */\n Snapping.prototype.addSameWidthLines = function (diagram, snapLine, sameWidths, horizontalSnap, ended, shape) {\n this.sortByDistance(sameWidths, 'offset');\n var bounds = getBounds(shape.wrapper);\n var target = sameWidths[0];\n var startPt;\n var endPt;\n var targetBounds = (target.source).bounds;\n var sameSizes = [];\n sameSizes.push(sameWidths[0]);\n var i;\n var crntbounds;\n for (i = 1; i < sameWidths.length; i++) {\n crntbounds = (sameWidths[i].source).bounds;\n if (crntbounds.width === targetBounds.width) {\n sameSizes.push(sameWidths[i]);\n }\n }\n if (!ended) {\n startPt = { x: bounds.x + target.offset, y: bounds.y - 15 };\n endPt = { x: bounds.x + bounds.width + target.offset, y: bounds.y - 15 };\n this.renderSpacingLines(startPt, endPt, snapLine, getAdornerLayerSvg(this.diagram.element.id), diagram.scroller.transform);\n for (i = 0; i < sameSizes.length; i++) {\n bounds = (sameSizes[i].source).bounds;\n startPt = { x: bounds.x, y: bounds.y - 15 };\n endPt = { x: bounds.x + bounds.width, y: bounds.y - 15 };\n this.renderSpacingLines(startPt, endPt, snapLine, getAdornerLayerSvg(this.diagram.element.id), diagram.scroller.transform);\n }\n }\n horizontalSnap.offset = target.offset;\n horizontalSnap.snapped = true;\n };\n /**\n * To add same height lines\n */\n Snapping.prototype.addSameHeightLines = function (diagram, snapLine, sameHeights, verticalSnap, ended, shape) {\n this.sortByDistance(sameHeights, 'offset');\n var bounds = getBounds(shape.wrapper);\n var target = sameHeights[0];\n var targetBounds = (target.source).bounds;\n var start;\n var end;\n var sameSizes = [];\n sameSizes.push(sameHeights[0]);\n var i;\n var crntbounds;\n for (i = 0; i < sameHeights.length; i++) {\n crntbounds = (sameHeights[i].source).bounds;\n if (crntbounds.height === targetBounds.height) {\n sameSizes.push(sameHeights[i]);\n }\n }\n if (!ended) {\n start = { x: bounds.x + bounds.width + 15, y: bounds.y + target.offset };\n end = { x: bounds.x + bounds.width + 15, y: bounds.y + target.offset + bounds.height };\n this.renderSpacingLines(start, end, snapLine, getAdornerLayerSvg(this.diagram.element.id), diagram.scroller.transform);\n for (i = 0; i < sameSizes.length; i++) {\n bounds = (sameSizes[i].source).bounds;\n start = { x: bounds.x + bounds.width + 15, y: bounds.y };\n end = { x: bounds.x + bounds.width + 15, y: bounds.y + bounds.height };\n this.renderSpacingLines(start, end, snapLine, getAdornerLayerSvg(this.diagram.element.id), diagram.scroller.transform);\n }\n }\n verticalSnap.offset = target.offset;\n verticalSnap.snapped = true;\n };\n /**\n * Render spacing lines\n */\n Snapping.prototype.renderSpacingLines = function (start, end, snapLine, svg, transform) {\n var d;\n var d1;\n var line1;\n var element = new PathElement();\n var options = {};\n start = {\n x: (start.x + transform.tx) * transform.scale,\n y: (start.y + transform.ty) * transform.scale\n };\n end = {\n x: (end.x + transform.tx) * transform.scale,\n y: (end.y + transform.ty) * transform.scale\n };\n if (start.x === end.x) {\n d = 'M' + (start.x - 5) + ' ' + (start.y + 5) + 'L' + start.x + ' ' + start.y +\n 'L' + (start.x + 5) + ' ' + (start.y + 5) + 'z' + 'M' + (end.x - 5) + ' ' +\n (end.y - 5) + ' L' + end.x + ' ' + end.y + ' L' +\n (end.x + 5) + ' ' + (end.y - 5) + 'z';\n line1 = {\n startPoint: { x: start.x - 8, y: start.y - 1 },\n endPoint: { x: start.x + 8, y: start.y - 1 },\n stroke: '#07EDE1',\n strokeWidth: 1, fill: '#07EDE1', dashArray: '', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0,\n pivotY: 0, visible: true, opacity: 1, id: randomId()\n };\n element.data = d;\n options.data = element.data;\n options.angle = 0;\n options.pivotX = 0;\n options.pivotY = 0;\n options.x = 0;\n options.y = 0;\n options.height = 0;\n options.width = 1;\n options.id = randomId();\n this.diagram.diagramRenderer.drawPath(snapLine, options);\n this.line.push(line1);\n this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop());\n line1 = {\n startPoint: { x: end.x - 8, y: end.y + 1 },\n endPoint: { x: end.x + 8, y: end.y + 1 },\n stroke: '#07EDE1',\n strokeWidth: 1, fill: '#07EDE1', dashArray: '', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0,\n pivotY: 0, visible: true, opacity: 1, id: getAdornerLayerSvg(this.diagram.element.id).id + 'spacing'\n };\n this.line.push(line1);\n this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop());\n }\n else {\n d = 'M' + (start.x + 5) + ' ' + (start.y + 5) + ' L' + start.x + ' ' + start.y +\n ' L' + (start.x + 5) + ' ' + (start.y - 5) + 'z' + 'M' + (end.x - 5) + ' ' +\n (end.y - 5) + ' L' + end.x + ' ' + end.y +\n ' L' + (end.x - 5) + ' ' + (end.y + 5) + 'z';\n element.data = d;\n options.data = d;\n options.angle = 0;\n options.pivotX = 0;\n options.pivotY = 0;\n options.x = 0;\n options.y = 0;\n options.height = 0;\n options.width = 1;\n options.id = randomId();\n this.diagram.diagramRenderer.drawPath(snapLine, options);\n line1 = {\n visible: true, opacity: 1, id: randomId(),\n startPoint: { x: start.x - 1, y: start.y - 8 },\n endPoint: { x: start.x - 1, y: start.y + 8 },\n stroke: '#07EDE1',\n strokeWidth: 1, fill: '#07EDE1', dashArray: '0', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0,\n pivotY: 0\n };\n this.line.push(line1);\n this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop());\n line1 = {\n width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0,\n pivotY: 0, visible: true, opacity: 1, id: randomId(),\n startPoint: { x: end.x + 1, y: end.y - 8 },\n endPoint: { x: end.x + 1, y: end.y + 8 },\n stroke: '#07EDE1',\n strokeWidth: 1, fill: '#07EDE1', dashArray: '0'\n };\n this.line.push(line1);\n this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop());\n }\n line1 = {\n startPoint: { x: start.x, y: start.y },\n endPoint: { x: end.x, y: end.y }, stroke: '#07EDE1', strokeWidth: 1, fill: '#07EDE1',\n dashArray: '0', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0,\n pivotY: 0, visible: true, opacity: 1, id: randomId()\n };\n this.line.push(line1);\n this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop());\n };\n /**\n * To Create Snap object with position, initial bounds, and final bounds\n * @private\n */\n Snapping.prototype.createSnapObject = function (targetBounds, bounds, snap) {\n var snapObject;\n switch (snap) {\n case 'left':\n snapObject = {\n start: { x: (targetBounds.x), y: Math.min(targetBounds.y, bounds.y) },\n end: { x: (targetBounds.x), y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height) },\n offsetX: targetBounds.x - bounds.x, offsetY: 0, type: 'sideAlign'\n };\n break;\n case 'right':\n snapObject = {\n type: 'sideAlign',\n start: { x: (targetBounds.x + targetBounds.width), y: Math.min(targetBounds.y, bounds.y) },\n offsetX: targetBounds.x + targetBounds.width - bounds.x - bounds.width,\n offsetY: 0,\n end: {\n x: (targetBounds.x + targetBounds.width),\n y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height)\n },\n };\n break;\n case 'top':\n snapObject = {\n offsetY: targetBounds.y - bounds.y, offsetX: 0, type: 'sideAlign',\n start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y },\n end: { x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)), y: targetBounds.y },\n };\n break;\n case 'bottom':\n snapObject = {\n type: 'sideAlign', offsetY: targetBounds.y + targetBounds.height - bounds.y - bounds.height, offsetX: 0,\n end: {\n x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)),\n y: targetBounds.y + targetBounds.height\n },\n start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y + targetBounds.height },\n };\n break;\n case 'topBottom':\n snapObject = {\n start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y + targetBounds.height },\n end: {\n x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)),\n y: targetBounds.y + targetBounds.height\n },\n offsetY: targetBounds.y + targetBounds.height - bounds.y, offsetX: 0, type: 'sideAlign'\n };\n break;\n case 'bottomTop':\n snapObject = {\n start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y },\n end: { x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)), y: targetBounds.y },\n offsetY: targetBounds.y - bounds.y - bounds.height, offsetX: 0, type: 'sideAlign'\n };\n break;\n case 'leftRight':\n snapObject = {\n start: { x: (targetBounds.x + targetBounds.width), y: Math.min(targetBounds.y, bounds.y) },\n end: {\n x: (targetBounds.x + targetBounds.width),\n y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height)\n },\n offsetX: targetBounds.x + targetBounds.width - bounds.x, offsetY: 0, type: 'sideAlign'\n };\n break;\n case 'rightLeft':\n snapObject = {\n start: { x: (targetBounds.x), y: (Math.min(targetBounds.y, bounds.y)) },\n end: { x: (targetBounds.x), y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height) },\n offsetX: targetBounds.x - bounds.x - bounds.width, offsetY: 0, type: 'sideAlign'\n };\n break;\n case 'centerX':\n snapObject = {\n start: { x: (targetBounds.x + targetBounds.width / 2), y: (Math.min(targetBounds.y, bounds.y)) },\n end: {\n x: (targetBounds.x + targetBounds.width / 2),\n y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height)\n },\n offsetX: targetBounds.x + targetBounds.width / 2 - (bounds.x + bounds.width / 2), offsetY: 0, type: 'centerAlign'\n };\n break;\n case 'centerY':\n snapObject = {\n start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y + targetBounds.height / 2 },\n end: {\n x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)),\n y: targetBounds.y + targetBounds.height / 2\n },\n offsetY: targetBounds.y + targetBounds.height / 2 - (bounds.y + bounds.height / 2), offsetX: 0, type: 'centerAlign'\n };\n break;\n }\n return snapObject;\n };\n /**\n * Calculate the snap angle\n * @private\n */\n Snapping.prototype.snapAngle = function (diagram, angle) {\n var snapSettings = this.diagram.snapSettings;\n var snapAngle = snapSettings.snapAngle;\n var width = angle % (snapAngle || 0);\n if (width >= (snapAngle / 2)) {\n return angle + snapAngle - width;\n }\n else {\n return angle - width;\n }\n };\n /**\n * Check whether the node to be snapped or not.\n */\n Snapping.prototype.canConsider = function (nameTable, selectedObject, target) {\n var consider = false;\n if (this.diagram.selectedItems.nodes.length && this.diagram.selectedItems.nodes[0].id === target.id) {\n return false;\n }\n else {\n return true;\n }\n };\n /**\n * Find the total number of nodes in diagram using SpatialSearch\n */\n Snapping.prototype.findNodes = function (spatialSearch, node, child, viewPort, nodesInView) {\n var nodes = [];\n var nd;\n var bounds;\n var quads = spatialSearch.findQuads(nodesInView ? viewPort : child);\n for (var i = 0; i < quads.length; i++) {\n var quad = quads[i];\n if (quad.objects.length > 0) {\n for (var j = 0; j < quad.objects.length; j++) {\n nd = quad.objects[j];\n if (!(this.diagram.nameTable[nd.id] instanceof Connector) && nd.visible) {\n bounds = getBounds(nd);\n if (nodes.indexOf(nd) === -1 && this.intersectsRect(child, bounds)) {\n nodes.push(nd);\n }\n if (nodesInView && nodesInView.indexOf(nd) && this.intersectsRect(viewPort, bounds)) {\n nodesInView.push(nd);\n }\n }\n }\n }\n }\n return nodes;\n };\n Snapping.prototype.intersectsRect = function (child, bounds) {\n return ((((bounds.x < (child.x + child.width)) && (child.x < (bounds.x + bounds.width)))\n && (bounds.y < (child.y + child.height))) && (child.y < (bounds.y + bounds.height)));\n };\n /**\n * To remove grid lines on mouse move and mouse up\n * @private\n */\n Snapping.prototype.removeGuidelines = function (diagram) {\n var selectionRect = getAdornerLayerSvg(this.diagram.element.id).getElementById('_SnappingLines');\n var line = getAdornerLayerSvg(this.diagram.element.id).getElementById('pivotLine');\n if (selectionRect) {\n selectionRect.parentNode.removeChild(selectionRect);\n }\n if (line) {\n line.parentNode.removeChild(line);\n }\n };\n /**\n * Sort the objects by its distance\n */\n Snapping.prototype.sortByDistance = function (obj, value, ascending) {\n var i;\n var j;\n var temp;\n if (ascending) {\n for (i = 0; i < obj.length; i++) {\n for (j = i + 1; j < obj.length; j++) {\n if (obj[i][value] > obj[j][value]) {\n temp = obj[i];\n obj[i] = obj[j];\n obj[j] = temp;\n }\n }\n }\n }\n else {\n for (i = 0; i < obj.length; i++) {\n for (j = i + 1; j < obj.length; j++) {\n if (obj[i][value] < obj[j][value]) {\n temp = obj[i];\n obj[i] = obj[j];\n obj[j] = temp;\n }\n }\n }\n }\n };\n /**\n * To find nodes that are equally placed at left of the selected node\n */\n Snapping.prototype.findEquallySpacedNodesAtLeft = function (objectsAtLeft, equalDistance, top, equallySpaced) {\n var prevBounds;\n var targetBounds;\n var dist;\n var i;\n for (i = 1; i < objectsAtLeft.length; i++) {\n prevBounds = ((objectsAtLeft[i - 1].obj).bounds);\n targetBounds = ((objectsAtLeft[i].obj).bounds);\n dist = prevBounds.x - targetBounds.x - targetBounds.width;\n if (Math.abs(dist - equalDistance) <= 1) {\n equallySpaced[equallySpaced.length] = objectsAtLeft[i];\n if (targetBounds.y < top) {\n top = targetBounds.y;\n }\n }\n else {\n break;\n }\n }\n return top;\n };\n /**\n * To find nodes that are equally placed at right of the selected node\n */\n Snapping.prototype.findEquallySpacedNodesAtRight = function (objectsAtRight, equalDistance, top, equallySpaced, snapObjDistance) {\n var actualDistance = objectsAtRight[0].distance;\n var target;\n var targetBounds;\n var prevBounds;\n var dist;\n if (Math.abs(equalDistance - actualDistance) <= snapObjDistance) {\n for (var i = 0; i < objectsAtRight.length - 1; i++) {\n target = objectsAtRight[i].obj;\n targetBounds = ((objectsAtRight[i + 1].obj).bounds);\n prevBounds = (target.bounds);\n dist = targetBounds.x - prevBounds.x - prevBounds.width;\n if (Math.abs(dist - equalDistance) <= 1) {\n equallySpaced[equallySpaced.length] = objectsAtRight[i + 1];\n if (prevBounds.y < top) {\n top = prevBounds.y;\n }\n }\n else {\n break;\n }\n }\n }\n return top;\n };\n Snapping.prototype.findEquallySpacedNodesAtTop = function (objectsAtTop, equalDistance, right, equallySpaced) {\n var prevBounds;\n var targetBounds;\n var dist;\n for (var i = 1; i < objectsAtTop.length; i++) {\n prevBounds = ((objectsAtTop[i - 1].obj).bounds);\n targetBounds = ((objectsAtTop[i].obj).bounds);\n dist = prevBounds.y - targetBounds.y - targetBounds.height;\n if (Math.abs(dist - equalDistance) <= 1) {\n equallySpaced[equallySpaced.length] = objectsAtTop[i];\n if (targetBounds.x + targetBounds.width > right) {\n right = targetBounds.x + targetBounds.width;\n }\n }\n else {\n break;\n }\n }\n return right;\n };\n /**\n * To find nodes that are equally placed at bottom of the selected node\n */\n Snapping.prototype.findEquallySpacedNodesAtBottom = function (objectsAtBottom, equalDistance, right, equallySpaced, snapObjDistance) {\n var actualDistance = objectsAtBottom[0].distance;\n var target;\n var targetBounds;\n var prevBounds;\n var dist;\n if (Math.abs(equalDistance - actualDistance) <= snapObjDistance) {\n for (var i = 0; i < objectsAtBottom.length - 1; i++) {\n target = objectsAtBottom[i].obj;\n targetBounds = ((objectsAtBottom[i + 1].obj).bounds);\n prevBounds = (target.bounds);\n dist = targetBounds.y - prevBounds.y - prevBounds.height;\n if (Math.abs(dist - equalDistance) <= 1) {\n equallySpaced[equallySpaced.length] = objectsAtBottom[i + 1];\n if (prevBounds.x + prevBounds.width > right) {\n right = prevBounds.x + prevBounds.width;\n }\n }\n else {\n break;\n }\n }\n }\n return right;\n };\n /**\n * To get Adoner layer to draw snapLine\n * @private\n */\n Snapping.prototype.getLayer = function () {\n var snapLine;\n if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject) {\n snapLine = document.createElementNS('http://www.w3.org/2000/svg', 'g');\n snapLine.setAttribute('id', '_SnappingLines');\n snapLine.setAttribute('shapeRendering', 'crispEdges');\n getAdornerLayerSvg(this.diagram.element.id).appendChild(snapLine);\n }\n return snapLine;\n };\n /**\n * Constructor for the snapping module\n * @private\n */\n // constructor() {\n // //constructs the snapping module\n // }\n /**\n * To destroy the snapping module\n * @return {void}\n * @private\n */\n Snapping.prototype.destroy = function () {\n /**\n * Destroys the snapping module\n */\n };\n /**\n * Get module name.\n */\n Snapping.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'Snapping';\n };\n return Snapping;\n}());\nexport { Snapping };\n","import { Node } from './node';\nimport { DiagramAction } from '../enum/enum';\nimport { removeItem, getObjectType } from '../utility/diagram-util';\nimport { cloneObject } from '../utility/base-util';\n/**\n * Undo redo function used for revert and restore the changes\n */\nvar UndoRedo = /** @class */ (function () {\n /**\n * Constructor for the undo redo module\n * @private\n */\n function UndoRedo() {\n this.groupUndo = false;\n this.childTable = [];\n //constructs the undo redo module\n }\n /** @private */\n UndoRedo.prototype.initHistory = function (diagram) {\n diagram.historyList = {\n canRedo: false, canUndo: false, currentEntry: null,\n push: diagram.addHistoryEntry.bind(diagram), undo: Function, redo: Function,\n startGroupAction: diagram.startGroupAction.bind(diagram), endGroupAction: diagram.endGroupAction.bind(diagram),\n canLog: null, undoStack: [], redoStack: []\n };\n };\n /** @private */\n UndoRedo.prototype.addHistoryEntry = function (entry, diagram) {\n var entryObject = null;\n var nextEntry = null;\n if (diagram.historyList.canLog) {\n var hEntry = diagram.historyList.canLog(entry);\n if (hEntry.cancel === true) {\n return;\n }\n }\n if (diagram.historyList && diagram.historyList.canUndo && diagram.historyList.currentEntry) {\n entryObject = diagram.historyList.currentEntry;\n if (entryObject.next) {\n if (entryObject.previous) {\n nextEntry = entryObject.next;\n nextEntry.previous = null;\n entryObject.next = entry;\n entry.previous = entryObject;\n }\n }\n else {\n entryObject.next = entry;\n entry.previous = entryObject;\n }\n }\n diagram.historyList.currentEntry = entry;\n this.getHistoryList(diagram);\n diagram.historyList.canUndo = true;\n diagram.historyList.canRedo = false;\n };\n /** @private */\n UndoRedo.prototype.undo = function (diagram) {\n var entry = this.getUndoEntry(diagram);\n var endGroupActionCount = 0;\n if (entry) {\n if (entry.category === 'Internal') {\n if (entry.type === 'EndGroup') {\n endGroupActionCount++;\n this.groupUndo = true;\n }\n else {\n this.undoEntry(entry, diagram);\n }\n if (this.groupUndo) {\n this.undoGroupAction(entry, diagram, endGroupActionCount);\n this.groupUndo = false;\n }\n }\n else {\n diagram.historyList.undo(entry);\n }\n }\n };\n UndoRedo.prototype.getHistoryList = function (diagram) {\n var undoStack = [];\n var redoStack = [];\n var currEntry = diagram.historyList.currentEntry;\n var undoObj;\n var redoObj;\n currEntry = diagram.historyList.currentEntry;\n if (diagram.historyList.canUndo || diagram.historyList.undoStack.length === 0) {\n this.getHistroyObject(undoStack, currEntry);\n }\n else {\n this.getHistroyObject(redoStack, currEntry);\n }\n while (currEntry && currEntry.previous) {\n undoObj = currEntry.previous;\n this.getHistroyObject(undoStack, undoObj);\n currEntry = currEntry.previous;\n }\n currEntry = diagram.historyList.currentEntry;\n while (currEntry && currEntry.next) {\n redoObj = currEntry.next;\n this.getHistroyObject(redoStack, redoObj);\n currEntry = currEntry.next;\n }\n diagram.historyList.undoStack = undoStack;\n diagram.historyList.redoStack = redoStack;\n };\n UndoRedo.prototype.getHistroyObject = function (list, obj) {\n if (obj && obj.type !== 'StartGroup' && obj.type !== 'EndGroup') {\n list.push({\n redoObject: obj.redoObject ? obj.redoObject : null,\n undoObject: obj.undoObject ? obj.undoObject : null,\n type: obj.type ? obj.type : null,\n category: obj.category ? obj.category : null\n });\n }\n };\n UndoRedo.prototype.undoGroupAction = function (entry, diagram, endGroupActionCount) {\n while (endGroupActionCount !== 0) {\n this.undoEntry(entry, diagram);\n entry = this.getUndoEntry(diagram);\n if (entry.type === 'StartGroup') {\n endGroupActionCount--;\n }\n else if (entry.type === 'EndGroup') {\n endGroupActionCount++;\n }\n }\n endGroupActionCount = 0;\n };\n UndoRedo.prototype.undoEntry = function (entry, diagram) {\n var obj;\n if (entry.type !== 'PropertyChanged' && entry.type !== 'CollectionChanged' && entry.type !== 'LabelCollectionChanged') {\n obj = (entry.undoObject);\n }\n if (entry.type !== 'StartGroup' && entry.type !== 'EndGroup') {\n if (diagram.historyList.undoStack.length > 0) {\n var addObject = diagram.historyList.undoStack.splice(0, 1);\n diagram.historyList.redoStack.splice(0, 0, addObject[0]);\n }\n }\n diagram.protectPropertyChange(true);\n diagram.diagramActions |= DiagramAction.UndoRedo;\n switch (entry.type) {\n case 'PositionChanged':\n case 'Align':\n case 'Distribute':\n this.recordPositionChanged(obj, diagram);\n break;\n case 'SizeChanged':\n case 'Sizing':\n this.recordSizeChanged(obj, diagram, entry);\n break;\n case 'RotationChanged':\n this.recordRotationChanged(obj, diagram, entry);\n break;\n case 'ConnectionChanged':\n this.recordConnectionChanged(obj, diagram);\n break;\n case 'PropertyChanged':\n this.recordPropertyChanged(entry, diagram, false);\n break;\n case 'CollectionChanged':\n entry.isUndo = true;\n this.recordCollectionChanged(entry, diagram);\n entry.isUndo = false;\n break;\n case 'LabelCollectionChanged':\n entry.isUndo = true;\n this.recordLabelCollectionChanged(entry, diagram);\n entry.isUndo = false;\n break;\n case 'PortCollectionChanged':\n entry.isUndo = true;\n this.recordPortCollectionChanged(entry, diagram);\n entry.isUndo = false;\n break;\n case 'Group':\n this.unGroup(entry, diagram);\n break;\n case 'UnGroup':\n this.group(entry, diagram);\n break;\n case 'SegmentChanged':\n this.recordSegmentChanged(obj, diagram);\n break;\n }\n diagram.diagramActions &= ~DiagramAction.UndoRedo;\n diagram.protectPropertyChange(false);\n diagram.historyChangeTrigger(entry);\n };\n UndoRedo.prototype.group = function (historyEntry, diagram) {\n diagram.add(historyEntry.undoObject);\n };\n UndoRedo.prototype.unGroup = function (entry, diagram) {\n var i = 0;\n entry.redoObject = cloneObject(entry.undoObject);\n var node = entry.undoObject;\n diagram.commandHandler.unGroup(node);\n };\n UndoRedo.prototype.ignoreProperty = function (key) {\n if (key === 'zIndex' || key === 'wrapper') {\n return true;\n }\n return false;\n };\n UndoRedo.prototype.getProperty = function (collection, property) {\n for (var _i = 0, _a = Object.keys(property); _i < _a.length; _i++) {\n var key = _a[_i];\n if (!this.ignoreProperty(key)) {\n if (property[key] instanceof Object) {\n this.getProperty(collection[key], property[key]);\n }\n else {\n collection[key] = property[key];\n }\n }\n }\n };\n UndoRedo.prototype.recordPropertyChanged = function (entry, diagram, isRedo) {\n var redoObject = entry.redoObject;\n var undoObject = entry.undoObject;\n this.getProperty(diagram, (isRedo ? redoObject : undoObject));\n isRedo ? diagram.onPropertyChanged(redoObject, undoObject) : diagram.onPropertyChanged(undoObject, redoObject);\n diagram.diagramActions = diagram.diagramActions | DiagramAction.UndoRedo;\n };\n UndoRedo.prototype.recordSegmentChanged = function (obj, diagram) {\n var i = 0;\n var node;\n var connector;\n if (obj.connectors && obj.connectors.length > 0) {\n for (i = 0; i < obj.connectors.length; i++) {\n connector = obj.connectors[i];\n this.segmentChanged(connector, diagram);\n }\n }\n };\n UndoRedo.prototype.segmentChanged = function (connector, diagram) {\n var conn = diagram.nameTable[connector.id];\n conn.segments = connector.segments;\n diagram.commandHandler.updateEndPoint(conn);\n };\n UndoRedo.prototype.recordPositionChanged = function (obj, diagram) {\n var i = 0;\n var node;\n var connector;\n if (obj.nodes && obj.nodes.length > 0) {\n for (i = 0; i < obj.nodes.length; i++) {\n node = obj.nodes[i];\n this.positionChanged(node, diagram);\n }\n }\n if (obj.connectors && obj.connectors.length > 0) {\n for (i = 0; i < obj.connectors.length; i++) {\n connector = obj.connectors[i];\n this.connectionChanged(connector, diagram);\n }\n }\n };\n UndoRedo.prototype.positionChanged = function (obj, diagram, entry) {\n var node = diagram.nameTable[obj.id];\n if (obj.processId && !node.processId) {\n diagram.addProcess(obj, obj.processId);\n }\n if (!obj.processId && node.processId) {\n diagram.removeProcess(obj.id);\n }\n if (node.processId) {\n var tx = obj.margin.left - node.margin.left;\n var ty = obj.margin.top - node.margin.top;\n diagram.drag(node, tx, ty);\n }\n else {\n var tx = obj.offsetX - node.wrapper.offsetX;\n var ty = obj.offsetY - node.wrapper.offsetY;\n diagram.drag(node, tx, ty);\n }\n if (diagram.bpmnModule) {\n diagram.bpmnModule.updateDocks(node, diagram);\n }\n };\n UndoRedo.prototype.recordSizeChanged = function (obj, diagram, entry) {\n var i = 0;\n var connector;\n var node;\n if (obj && obj.nodes && obj.nodes.length > 0) {\n for (i = 0; i < obj.nodes.length; i++) {\n node = obj.nodes[i];\n if (node.children) {\n var elements = [];\n var nodes = diagram.commandHandler.getAllDescendants(node, elements);\n for (var i_1 = 0; i_1 < nodes.length; i_1++) {\n var tempNode = entry.childTable[nodes[i_1].id];\n if ((getObjectType(tempNode) === Node)) {\n this.sizeChanged(tempNode, diagram, entry);\n this.positionChanged(tempNode, diagram, entry);\n }\n else {\n this.connectionChanged(tempNode, diagram, entry);\n }\n }\n }\n else {\n this.sizeChanged(node, diagram);\n this.positionChanged(node, diagram);\n }\n }\n }\n if (obj && obj.connectors && obj.connectors.length > 0) {\n var connectors = obj.connectors;\n for (i = 0; i < connectors.length; i++) {\n connector = connectors[i];\n this.connectionChanged(connector, diagram);\n }\n }\n };\n UndoRedo.prototype.sizeChanged = function (obj, diagram, entry) {\n var node = diagram.nameTable[obj.id];\n var scaleWidth = obj.wrapper.actualSize.width / node.wrapper.actualSize.width;\n var scaleHeight = obj.wrapper.actualSize.height / node.wrapper.actualSize.height;\n if (entry && entry.childTable) {\n entry.childTable[obj.id] = cloneObject(node);\n }\n diagram.scale(node, scaleWidth, scaleHeight, {\n x: obj.wrapper.offsetX / node.wrapper.offsetX,\n y: obj.wrapper.offsetY / node.wrapper.offsetY\n });\n };\n UndoRedo.prototype.recordRotationChanged = function (obj, diagram, entry) {\n var i = 0;\n var node;\n var connector;\n var selectorObj = diagram.selectedItems;\n selectorObj.rotateAngle = obj.rotateAngle;\n if (selectorObj && selectorObj.wrapper) {\n selectorObj.wrapper.rotateAngle = obj.rotateAngle;\n }\n if (obj && obj.nodes && obj.nodes.length > 0) {\n for (i = 0; i < obj.nodes.length; i++) {\n node = obj.nodes[i];\n this.rotationChanged(node, diagram);\n this.positionChanged(node, diagram);\n }\n }\n if (obj && obj.connectors && obj.connectors.length > 0) {\n for (i = 0; i < obj.connectors.length; i++) {\n connector = obj.connectors[i];\n this.connectionChanged(connector, diagram);\n }\n }\n };\n UndoRedo.prototype.rotationChanged = function (obj, diagram) {\n var node = diagram.nameTable[obj.id];\n diagram.rotate(node, obj.rotateAngle - node.rotateAngle);\n };\n UndoRedo.prototype.recordConnectionChanged = function (obj, diagram) {\n var connector = obj.connectors[0];\n this.connectionChanged(connector, diagram);\n };\n UndoRedo.prototype.connectionChanged = function (obj, diagram, entry) {\n var connector = diagram.nameTable[obj.id];\n var node;\n if (obj.sourcePortID !== connector.sourcePortID) {\n connector.sourcePortID = obj.sourcePortID;\n diagram.connectorPropertyChange(connector, {}, { sourcePortID: obj.sourcePortID });\n }\n if (obj.targetPortID !== connector.targetPortID) {\n connector.targetPortID = obj.targetPortID;\n diagram.connectorPropertyChange(connector, {}, { targetPortID: obj.targetPortID });\n }\n if (obj.sourceID !== connector.sourceID) {\n if (obj.sourceID === '') {\n node = diagram.nameTable[connector.sourceID];\n removeItem(node.outEdges, obj.id);\n }\n else {\n node = diagram.nameTable[obj.sourceID];\n node.outEdges.push(obj.id);\n }\n connector.sourceID = obj.sourceID;\n diagram.connectorPropertyChange(connector, {}, { sourceID: obj.sourceID });\n }\n if (obj.targetID !== connector.targetID) {\n if (obj.targetID === '') {\n node = diagram.nameTable[connector.targetID];\n removeItem(node.inEdges, obj.id);\n }\n else {\n node = diagram.nameTable[obj.targetID];\n node.inEdges.push(obj.id);\n }\n connector.targetID = obj.targetID;\n diagram.connectorPropertyChange(connector, {}, { targetID: obj.targetID });\n }\n if (entry && entry.childTable) {\n entry.childTable[obj.id] = cloneObject(connector);\n }\n var sx = obj.sourcePoint.x - connector.sourcePoint.x;\n var sy = obj.sourcePoint.y - connector.sourcePoint.y;\n if (sx !== 0 || sy !== 0) {\n diagram.dragSourceEnd(connector, sx, sy);\n }\n var tx = obj.targetPoint.x - connector.targetPoint.x;\n var ty = obj.targetPoint.y - connector.targetPoint.y;\n if (tx !== 0 || ty !== 0) {\n diagram.dragTargetEnd(connector, tx, ty);\n }\n diagram.updateSelector();\n if (diagram.mode !== 'SVG') {\n diagram.refreshDiagramLayer();\n }\n };\n UndoRedo.prototype.recordCollectionChanged = function (entry, diagram) {\n var obj = entry.undoObject;\n if (entry && entry.changeType) {\n var changeType = void 0;\n if (entry.isUndo) {\n if (entry.changeType === 'Insert') {\n changeType = 'Remove';\n }\n else {\n changeType = 'Insert';\n }\n }\n else {\n changeType = entry.changeType;\n }\n if (changeType === 'Remove') {\n diagram.remove(obj);\n diagram.clearSelectorLayer();\n }\n else {\n diagram.clearSelectorLayer();\n if (obj.parentId) {\n var parentNode = diagram.nameTable[obj.parentId];\n if (parentNode) {\n diagram.addChild(parentNode, obj);\n }\n else {\n diagram.add(obj);\n }\n }\n else {\n diagram.add(obj);\n }\n if (obj.processId && diagram.nameTable[obj.processId]) {\n diagram.addProcess(obj, obj.processId);\n }\n }\n if (diagram.mode !== 'SVG') {\n diagram.refreshDiagramLayer();\n }\n }\n };\n UndoRedo.prototype.recordLabelCollectionChanged = function (entry, diagram) {\n var label = entry.undoObject;\n var obj = entry.redoObject;\n var node = diagram.nameTable[obj.id];\n if (entry && entry.changeType) {\n var changeType = void 0;\n if (entry.isUndo) {\n changeType = (entry.changeType === 'Insert') ? 'Remove' : 'Insert';\n }\n else {\n changeType = entry.changeType;\n }\n if (changeType === 'Remove') {\n diagram.removeLabels(node, [label]);\n diagram.clearSelectorLayer();\n }\n else {\n diagram.clearSelectorLayer();\n diagram.addLabels(node, [label]);\n }\n if (diagram.mode !== 'SVG') {\n diagram.refreshDiagramLayer();\n }\n }\n };\n UndoRedo.prototype.recordPortCollectionChanged = function (entry, diagram) {\n var port = entry.undoObject;\n var obj = entry.redoObject;\n var node = diagram.nameTable[obj.id];\n if (entry && entry.changeType) {\n var changeType = void 0;\n if (entry.isUndo) {\n changeType = (entry.changeType === 'Insert') ? 'Remove' : 'Insert';\n }\n else {\n changeType = entry.changeType;\n }\n if (changeType === 'Remove') {\n diagram.removePorts(node, [port]);\n diagram.clearSelectorLayer();\n }\n else {\n diagram.clearSelectorLayer();\n diagram.addPorts(node, [port]);\n }\n if (diagram.mode !== 'SVG') {\n diagram.refreshDiagramLayer();\n }\n }\n };\n /** @private */\n UndoRedo.prototype.redo = function (diagram) {\n var entry = this.getRedoEntry(diagram);\n var startGroupActionCount = 0;\n if (entry) {\n if (entry.category === 'Internal') {\n if (entry.type === 'StartGroup') {\n startGroupActionCount++;\n this.groupUndo = true;\n }\n else {\n this.redoEntry(entry, diagram);\n }\n if (this.groupUndo) {\n this.redoGroupAction(entry, diagram, startGroupActionCount);\n this.groupUndo = false;\n }\n }\n else {\n diagram.historyList.redo(entry);\n }\n }\n };\n UndoRedo.prototype.redoGroupAction = function (entry, diagram, startGroupActionCount) {\n while (startGroupActionCount !== 0) {\n this.redoEntry(entry, diagram);\n entry = this.getRedoEntry(diagram);\n if (entry.type === 'EndGroup') {\n startGroupActionCount--;\n }\n else if (entry.type === 'StartGroup') {\n startGroupActionCount++;\n }\n }\n startGroupActionCount = 0;\n };\n UndoRedo.prototype.redoEntry = function (historyEntry, diagram) {\n var redoObject;\n if (historyEntry.type !== 'PropertyChanged' && historyEntry.type !== 'CollectionChanged') {\n redoObject = (historyEntry.redoObject);\n }\n diagram.diagramActions |= DiagramAction.UndoRedo;\n if (historyEntry.type !== 'StartGroup' && historyEntry.type !== 'EndGroup') {\n if (diagram.historyList.redoStack.length > 0) {\n var addObject = diagram.historyList.redoStack.splice(0, 1);\n diagram.historyList.undoStack.splice(0, 0, addObject[0]);\n }\n }\n diagram.protectPropertyChange(true);\n switch (historyEntry.type) {\n case 'PositionChanged':\n case 'Align':\n case 'Distribute':\n this.recordPositionChanged(redoObject, diagram);\n break;\n case 'SizeChanged':\n case 'Sizing':\n this.recordSizeChanged(redoObject, diagram, historyEntry);\n break;\n case 'RotationChanged':\n this.recordRotationChanged(redoObject, diagram, historyEntry);\n break;\n case 'ConnectionChanged':\n this.recordConnectionChanged(redoObject, diagram);\n break;\n case 'PropertyChanged':\n this.recordPropertyChanged(historyEntry, diagram, true);\n break;\n case 'CollectionChanged':\n this.recordCollectionChanged(historyEntry, diagram);\n break;\n case 'LabelCollectionChanged':\n this.recordLabelCollectionChanged(historyEntry, diagram);\n break;\n case 'PortCollectionChanged':\n this.recordPortCollectionChanged(historyEntry, diagram);\n break;\n case 'Group':\n this.group(historyEntry, diagram);\n break;\n case 'UnGroup':\n this.unGroup(historyEntry, diagram);\n break;\n case 'SegmentChanged':\n this.recordSegmentChanged(redoObject, diagram);\n break;\n }\n diagram.protectPropertyChange(false);\n diagram.diagramActions &= ~DiagramAction.UndoRedo;\n diagram.historyChangeTrigger(historyEntry);\n };\n UndoRedo.prototype.getUndoEntry = function (diagram) {\n var undoEntry = null;\n var currentObject;\n var hList = diagram.historyList;\n if (hList.canUndo) {\n undoEntry = hList.currentEntry;\n currentObject = hList.currentEntry.previous;\n if (currentObject) {\n hList.currentEntry = currentObject;\n if (!hList.canRedo) {\n hList.canRedo = true;\n }\n }\n else {\n hList.canRedo = true;\n hList.canUndo = false;\n }\n }\n return undoEntry;\n };\n UndoRedo.prototype.getRedoEntry = function (diagram) {\n var redoEntry = null;\n var entryCurrent;\n var hList = diagram.historyList;\n if (hList.canRedo) {\n if (!hList.currentEntry.previous && !hList.canUndo) {\n entryCurrent = hList.currentEntry;\n }\n else {\n entryCurrent = hList.currentEntry.next;\n }\n if (entryCurrent) {\n hList.currentEntry = entryCurrent;\n if (!hList.canUndo) {\n hList.canUndo = true;\n }\n if (!entryCurrent.next) {\n hList.canRedo = false;\n hList.canUndo = true;\n }\n }\n redoEntry = hList.currentEntry;\n }\n return redoEntry;\n };\n /**\n * To destroy the undo redo module\n * @return {void}\n * @private\n */\n UndoRedo.prototype.destroy = function () {\n /**\n * Destroys the undo redo module\n */\n };\n /**\n * Get module name.\n */\n UndoRedo.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'UndoRedo';\n };\n return UndoRedo;\n}());\nexport { UndoRedo };\n","import { Container } from '../core/containers/container';\nimport { DiagramEvent } from '../enum/enum';\n/**\n * Layout Animation function to enable or disable layout animation\n */\nvar LayoutAnimation = /** @class */ (function () {\n function LayoutAnimation() {\n this.protectChange = false;\n }\n /**\n * Layout expand function for animation of expand and collapse\n */\n LayoutAnimation.prototype.expand = function (animation, objects, node, diagram) {\n var _this = this;\n var setIntervalObject = {};\n var i = 0;\n var j = 0;\n setIntervalObject[i] = setInterval(function () {\n j++;\n return _this.layoutAnimation(objects, setIntervalObject, j === 6, diagram);\n }, 20);\n if (node.isExpanded) {\n var opacity_1 = .2;\n var protect = 'isProtectedOnChange';\n this.protectChange = diagram[protect];\n diagram.protectPropertyChange(false);\n //let objects: ILayout = diagram.doLayout();\n var setIntervalObjects_1 = {};\n var x = 0;\n this.updateOpacity(node, opacity_1, diagram);\n var current = this;\n setIntervalObjects_1[x] = setInterval(function () {\n opacity_1 <= 1 ? _this.updateOpacity(node, opacity_1, diagram) : clearInterval(setIntervalObjects_1[0]);\n opacity_1 += .2;\n }, 20);\n }\n };\n /**\n * Setinterval and Clear interval for layout animation\n */\n /** @private */\n LayoutAnimation.prototype.layoutAnimation = function (objValue, layoutTimer, stop, diagram) {\n if (!stop) {\n for (var k = 0; k < objValue.objects.length; k++) {\n var node = diagram.nameTable[objValue.objects[k].id];\n node.offsetX += objValue.objects[k].differenceX / 5;\n node.offsetY += objValue.objects[k].differenceY / 5;\n }\n }\n if (stop) {\n clearInterval(layoutTimer[0]);\n diagram.protectPropertyChange(this.protectChange);\n diagram.triggerEvent(DiagramEvent.animationComplete, undefined);\n this.protectChange = false;\n diagram.organizationalChartModule.isAnimation = false;\n diagram.layout.fixedNode = '';\n diagram.protectPropertyChange(this.protectChange);\n }\n };\n /**\n * update the node opacity for the node and connector once the layout animation starts\n */\n LayoutAnimation.prototype.updateOpacity = function (source, value, diagram) {\n for (var i = 0; i < source.outEdges.length; i++) {\n var connector = diagram.nameTable[source.outEdges[i]];\n var target = diagram.nameTable[connector.targetID];\n connector.style.opacity = value;\n diagram.updateDiagramObject(source);\n for (var j = 0; j < connector.wrapper.children.length; j++) {\n connector.wrapper.children[j].style.opacity = value;\n target.style.opacity = value;\n if (target.wrapper instanceof Container) {\n diagram.updateNodeProperty(target.wrapper, undefined, value);\n }\n }\n this.updateOpacity(target, value, diagram);\n }\n };\n /**\n * To destroy the LayoutAnimate module\n * @return {void}\n * @private\n */\n LayoutAnimation.prototype.destroy = function () {\n /**\n * Destroys the LayoutAnimate module\n */\n };\n /**\n * Get module name.\n */\n LayoutAnimation.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'LayoutAnimate';\n };\n return LayoutAnimation;\n}());\nexport { LayoutAnimation };\n","import { Rect } from '../primitives/rect';\nimport { OrthogonalSegment } from '../objects/connector';\nimport { getFunction } from '../utility/base-util';\nimport { Point } from '../primitives/point';\n/**\n * Hierarchical Tree and Organizational Chart\n */\nvar HierarchicalTree = /** @class */ (function () {\n /**\n * Constructor for the organizational chart module.\n * @private\n */\n function HierarchicalTree() {\n /**\n * Defines the layout animation\n *\n */\n this.isAnimation = false;\n //constructs the layout module\n }\n /**\n * To destroy the organizational chart\n * @return {void}\n * @private\n */\n HierarchicalTree.prototype.destroy = function () {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name.\n */\n HierarchicalTree.prototype.getModuleName = function () {\n /**\n * Returns the module name of the layout\n */\n return 'OrganizationalChart';\n };\n HierarchicalTree.prototype.updateLayout = function (nodes, nameTable, layoutProp, viewport, uniqueId) {\n var layout = {\n type: layoutProp.type,\n nameTable: nameTable, anchorX: 0, anchorY: 0,\n firstLevelNodes: [], centerNode: null, levels: [], maxLevel: 0, graphNodes: {},\n orientation: layoutProp.orientation,\n horizontalSpacing: layoutProp.horizontalSpacing, verticalSpacing: layoutProp.verticalSpacing,\n verticalAlignment: layoutProp.verticalAlignment, horizontalAlignment: layoutProp.horizontalAlignment,\n fixedNode: layoutProp.fixedNode, getLayoutInfo: getFunction(layoutProp.getLayoutInfo), margin: layoutProp.margin,\n bounds: layoutProp.bounds, objects: [], root: layoutProp.root\n };\n this.doLayout(layout, nodes, viewport, uniqueId);\n return layout;\n };\n HierarchicalTree.prototype.doLayout = function (layout, nodes, viewport, uniqueId) {\n var node;\n var i;\n var layoutInfo = {};\n var shape;\n var rootNodes = [];\n if (layout.nameTable[layout.root]) {\n layout.firstLevelNodes.push(layout.nameTable[layout.root]);\n }\n for (i = 0; i < nodes.length; i++) {\n node = nodes[i];\n if (!node.excludeFromLayout) {\n layoutInfo = layout.graphNodes[node.id] = this.setUpLayoutInfo(layout, node);\n layoutInfo.tree.hasSubTree = false;\n if (!layout.nameTable[layout.root]) {\n if (!node.inEdges || !node.inEdges.length) {\n rootNodes.push(node);\n if (node.data && String(node.data[uniqueId]) === layout.root) {\n layout.firstLevelNodes.push(node);\n }\n }\n }\n }\n }\n if (layout.firstLevelNodes.length === 0) {\n layout.firstLevelNodes = rootNodes;\n }\n //Update relationship(parent and children)\n for (i = 0; i < layout.firstLevelNodes.length; i++) {\n node = layout.firstLevelNodes[i];\n this.updateEdges(layout, node, 1);\n }\n if (layout.firstLevelNodes.length > 0) {\n layout.rootNode = layout.firstLevelNodes[0];\n var x = 0;\n var y = 0;\n var minX = void 0;\n var maxY = void 0;\n var maxX = void 0;\n var minY = void 0;\n var j = void 0;\n var bounds = void 0;\n for (i = 0; i < layout.firstLevelNodes.length; i++) {\n bounds = this.updateTree(layout, x, y, layout.firstLevelNodes[i], 0, layout.firstLevelNodes[i - 1]);\n var rootInfo = layout.graphNodes[layout.firstLevelNodes[i].id];\n bounds.y = Math.min(bounds.y, rootInfo.y);\n bounds.x = Math.min(bounds.x, rootInfo.x);\n if (layout.orientation.indexOf('Left') !== -1) {\n y = bounds.right + layout.horizontalSpacing;\n }\n else {\n x = bounds.right + layout.horizontalSpacing;\n }\n if (i === 0) {\n minX = bounds.x;\n minY = bounds.y;\n maxX = bounds.right;\n maxY = bounds.bottom;\n }\n else {\n minX = Math.min(minX, bounds.x);\n minY = Math.min(minY, bounds.y);\n maxX = Math.max(maxX, bounds.right);\n maxY = Math.max(maxY, bounds.bottom);\n }\n }\n this.updateAnchor(layout, { x: minX, y: minY, right: maxX, bottom: maxY }, viewport);\n for (i = 0; i < layout.firstLevelNodes.length; i++) {\n this.updateNodes(layout, layout.firstLevelNodes[i], 0);\n }\n for (i = 0; i < layout.firstLevelNodes.length; i++) {\n this.updateConnectors(layout, layout.firstLevelNodes[i], 1);\n }\n }\n };\n HierarchicalTree.prototype.getBounds = function (node) {\n var x = node.offsetX - node.actualSize.width * node.pivot.x;\n var y = node.offsetY - node.actualSize.height * node.pivot.y;\n return new Rect(x, y, node.actualSize.width, node.actualSize.height);\n };\n HierarchicalTree.prototype.updateTree = function (layout, x, y, shape, level, prev, dontupdate) {\n var dimensions;\n var info = {};\n var lev;\n var obj;\n var hasChild;\n dimensions = this.getDimensions(layout, shape, x, y, level);\n info = layout.graphNodes[shape.id];\n var firstChild;\n //Set maximum level of layout\n layout.maxLevel = Math.max(layout.maxLevel, level);\n lev = level;\n hasChild = this.hasChild(layout, shape);\n if (!hasChild && !info.tree.assistants.length) {\n //update leaf nodes\n shape.treeBounds = this.updateLeafNode(layout, shape, prev, dimensions, level, dontupdate);\n return shape.treeBounds;\n }\n else {\n var treeBounds = void 0;\n var shapeBounds = void 0;\n var levelBounds = void 0;\n var d = void 0;\n var asstBounds = void 0;\n var space = void 0;\n var bottom = void 0;\n bottom = dimensions.y + dimensions.height + layout.verticalSpacing;\n if (info.tree.assistants.length) {\n //Vertically place assistants\n obj = this.setDepthSpaceForAssitants(layout, shape, bottom, dimensions.height, level, layout.verticalSpacing);\n lev = obj.level;\n bottom = obj.bottom;\n }\n if (!info.tree.assistants.length && info.tree.orientation !== 'Horizontal') {\n bottom = dimensions.y + dimensions.height + layout.verticalSpacing / 2;\n }\n if (info.tree.children.length) {\n if (info.tree.orientation === 'Horizontal' && (info.tree.type !== 'Balanced' || info.tree.children.length === 1)) {\n treeBounds = this.updateHorizontalTree(layout, shape, prev, dimensions.x, bottom, lev);\n }\n else if (info.tree.type === 'Balanced') {\n treeBounds = this.updateHorizontalTreeWithMultipleRows(layout, shape, prev, dimensions.x, bottom, lev);\n }\n else {\n treeBounds = this.updateVerticalTree(layout, shape, dimensions.x, bottom, lev, dontupdate);\n }\n }\n if (!(info.y && info.y > dimensions.y)) {\n info.y = dimensions.y;\n }\n if (!(x && x > info.mid)) {\n x = info.mid;\n }\n if (info.tree.assistants.length) {\n //Set breadth space for assistants\n space = x !== undefined ? x : dimensions.x;\n asstBounds = this.setBreadthSpaceForAssistants(layout, shape, dimensions, space, bottom, level);\n if (!hasChild) {\n levelBounds = treeBounds = asstBounds;\n x = (levelBounds.x + levelBounds.right) / 2 - dimensions.width / 2;\n treeBounds = levelBounds;\n }\n d = asstBounds ? asstBounds.canMoveBy : undefined;\n }\n info.x = x;\n if (!info.translate) {\n info.treeWidth = treeBounds.right - treeBounds.x;\n }\n {\n shapeBounds = { x: x, y: dimensions.y, right: x + dimensions.width, bottom: dimensions.y + dimensions.height };\n }\n var translateInfo = {\n layout: layout, shape: shape, shapeBounds: shapeBounds, treeBounds: treeBounds,\n dim: dimensions, level: level\n };\n this.translateSubTree(translateInfo, d, prev !== undefined, dontupdate);\n if (info.firstChild && typeof info.firstChild !== 'string') {\n info.firstChild.x += info.subTreeTranslation;\n }\n shape.treeBounds = treeBounds;\n return treeBounds;\n }\n };\n HierarchicalTree.prototype.updateLeafNode = function (layout, shape, prev, dimensions, level, dontupdate) {\n var bounds;\n var info = layout.graphNodes[shape.id];\n info.x = dimensions.x;\n if (!(info.y && info.y > dimensions.y)) {\n info.y = dimensions.y;\n info.maxLevel = Math.max(level, info.maxLevel || 0);\n }\n bounds = { x: dimensions.x, y: dimensions.y, right: dimensions.x + dimensions.width, bottom: dimensions.y + dimensions.height };\n info.maxLevel = Math.max(info.maxLevel || 0, level);\n var translateInfo = {\n layout: layout, shape: shape, shapeBounds: bounds, treeBounds: bounds,\n dim: dimensions, level: level\n };\n this.translateSubTree(translateInfo, undefined, prev !== undefined, dontupdate);\n return { x: info.x, y: info.y, right: info.x + dimensions.width, bottom: info.y + dimensions.height };\n };\n HierarchicalTree.prototype.setUpLayoutInfo = function (layout, item) {\n var info = {};\n info.subTreeTranslation = 0;\n if (layout.type === 'OrganizationalChart') {\n info.tree = { orientation: 'Vertical', type: 'Alternate', offset: 20, enableRouting: true };\n }\n else {\n info.tree = { orientation: 'Horizontal', type: 'Center', enableRouting: true };\n }\n info.tree.children = [];\n info.tree.assistants = [];\n info.tree.level = 0;\n info.translate = true;\n return info;\n };\n HierarchicalTree.prototype.translateSubTree = function (translateInfo, asstDif, translate, dontupdate) {\n var layout = translateInfo.layout;\n var shape = translateInfo.shape;\n var shapeBounds = translateInfo.shapeBounds;\n var treeBounds = translateInfo.treeBounds;\n var level = translateInfo.level;\n var dim = translateInfo.dim;\n var info = layout.graphNodes[shape.id];\n var firstChild = layout.nameTable[info.firstChild ? info.firstChild.child : info.tree.children[0]];\n var firstChildInfo = firstChild ? layout.graphNodes[firstChild.id] : null;\n var hasChild = this.hasChild(layout, shape);\n var intersect = this.findIntersectingLevels(layout, shapeBounds, level, info.actualLevel);\n var treeIntersect = this.findIntersectingLevels(layout, treeBounds, level, info.actualLevel);\n var levelBounds = [];\n var diff;\n if (intersect.length && info.translate) {\n info.intersect = intersect;\n this.spaceLeftFromPrevSubTree(layout, shape, shapeBounds);\n info.canMoveBy = info.diff;\n if (asstDif !== undefined) {\n info.canMoveBy = Math.min(asstDif, info.canMoveBy);\n }\n if (firstChild && firstChildInfo.canMoveBy !== undefined) {\n if (firstChildInfo.canMoveBy >= info.canMoveBy) {\n info.translated = true;\n }\n info.canMoveBy = Math.min(info.canMoveBy, firstChildInfo.canMoveBy);\n }\n if (translate) {\n info.x -= info.canMoveBy;\n info.subTreeTranslation -= info.canMoveBy;\n if (hasChild) {\n this.shiftSubordinates(layout, treeIntersect, info.canMoveBy);\n treeBounds.x = Math.min(treeBounds.x, info.x);\n treeBounds.right = Math.max(treeBounds.right, info.x + dim.width);\n treeBounds.bottom = Math.max(treeBounds.bottom, info.y + dim.height);\n treeBounds.x -= info.canMoveBy;\n treeBounds.right -= info.canMoveBy;\n }\n if (firstChild && firstChildInfo.canMoveBy > info.canMoveBy) {\n info.canMoveBy = firstChildInfo.canMoveBy - info.canMoveBy;\n }\n else if (firstChild && info.canMoveBy !== undefined) {\n info.canMoveBy = 0;\n }\n }\n }\n else {\n if (hasChild) {\n treeBounds.x = Math.min(treeBounds.x, shapeBounds.x);\n treeBounds.right = Math.max(treeBounds.right, shapeBounds.x + dim.width);\n treeBounds.bottom = Math.max(treeBounds.bottom, info.y + dim.height);\n }\n if (!info.translate) {\n info.canMoveBy = 0;\n info.subTreeTranslation = 0;\n }\n }\n if (!dontupdate) {\n shapeBounds = { x: info.x, y: dim.y, right: info.x + dim.width, bottom: dim.y + dim.height };\n levelBounds.push({ rBounds: shapeBounds });\n this.updateRearBounds(layout, shape, levelBounds, level);\n }\n };\n HierarchicalTree.prototype.updateRearBounds = function (layout, shape, levelBounds, level, intersect) {\n var bnds;\n var index;\n var isLastLeaf = true;\n var i;\n var info = {};\n var firstLevel;\n var lastLevel;\n var bottom;\n if (shape) {\n info = layout.graphNodes[shape.id];\n intersect = info.intersect;\n isLastLeaf = !info.tree.children.length && !info.tree.assistants.length;\n }\n firstLevel = levelBounds[0].rBounds;\n lastLevel = levelBounds[levelBounds.length - 1].rBounds;\n if (intersect && intersect.length) {\n bnds = layout.levels[intersect[0]].rBounds;\n bottom = bnds.bottom;\n if (bnds.y < firstLevel.y) {\n bnds.bottom = firstLevel.y;\n levelBounds.splice(0, 0, { rBounds: bnds });\n }\n if (bottom > lastLevel.bottom) {\n levelBounds.push({ rBounds: { x: bnds.x, right: bnds.right, y: firstLevel.bottom, bottom: bottom } });\n }\n else {\n bnds = layout.levels[intersect[intersect.length - 1]].rBounds;\n if (isLastLeaf && bnds.bottom > lastLevel.bottom) {\n bnds.y = lastLevel.bottom;\n levelBounds.push({ rBounds: bnds });\n }\n }\n index = intersect[0];\n for (i = levelBounds.length - 1; i >= 0; i--) {\n layout.levels.splice(index, 0, levelBounds[i]);\n }\n index += levelBounds.length;\n layout.levels.splice(index, intersect.length);\n }\n else {\n index = this.findLevel(layout, levelBounds[levelBounds.length - 1].rBounds, level);\n for (i = levelBounds.length - 1; i >= 0; i--) {\n layout.levels.splice(index, 0, levelBounds[i]);\n }\n }\n };\n HierarchicalTree.prototype.shiftSubordinates = function (layout, intersect, diff) {\n var i;\n //Shift the sublevels by the distance diff\n if (diff !== 0) {\n for (i = 0; i < intersect.length; i++) {\n if (layout.levels[intersect[i]].rBounds) {\n layout.levels[intersect[i]].rBounds.x -= diff;\n layout.levels[intersect[i]].rBounds.right -= diff;\n }\n }\n }\n };\n HierarchicalTree.prototype.setDepthSpaceForAssitants = function (layout, shape, bottom, height, lev, vSpace) {\n var info = layout.graphNodes[shape.id];\n var asst = {};\n var asstHeight;\n var i;\n var asstElement;\n var max;\n max = bottom;\n //Vertically place the assistants as alternate layout(alternatively at both right and left sides of parent)\n for (i = 0; i < info.tree.assistants.length; i++) {\n asst = layout.graphNodes[info.tree.assistants[i]];\n if (asst) {\n asst.tree.children = asst.tree.assistants = [];\n asst.y = bottom;\n asstElement = layout.nameTable[info.tree.assistants[i]];\n asstHeight = asstElement.actualSize.height;\n if (layout.orientation.indexOf('Left') !== -1) {\n asstHeight = asstElement.actualSize.width;\n }\n max = bottom + asstHeight + vSpace / 2;\n layout.maxLevel = lev + 1;\n if (i % 2 === 1 && i !== info.tree.assistants.length - 1) {\n bottom = max;\n lev++;\n }\n }\n }\n return { level: layout.maxLevel, bottom: bottom + asstHeight + vSpace };\n };\n HierarchicalTree.prototype.setBreadthSpaceForAssistants = function (layout, shape, dim, space, bottom, level) {\n var asst = {};\n var asstWidth;\n var prevBounds;\n var bounds;\n var asstElement;\n var i;\n var info = layout.graphNodes[shape.id];\n var max = bottom;\n var lev = level;\n var left;\n var diff;\n var intersect;\n var levelBounds;\n for (i = 0; i < info.tree.assistants.length; i++) {\n asst = layout.graphNodes[info.tree.assistants[i]];\n //Arrange assistants at both left and right sides of parent(like alternate layout)\n //Check - By default, distance to be left between parent and child nodes is assumed as 20.\n //It can be modified/customized later.\n if (asst) {\n asstElement = layout.nameTable[info.tree.assistants[i]];\n asstWidth = asstElement.actualSize.width;\n if (layout.orientation.indexOf('Left') !== -1) {\n asstWidth = asstElement.actualSize.height;\n }\n if (i % 2 === 0) {\n left = space + dim.width / 2 - 20 - asstWidth;\n }\n else {\n left = space + dim.width / 2 + 20;\n }\n //Check - What will happen if update leaf node is called? Since assistants don't have children\n bounds = this.updateTree(layout, left, asst.y, layout.nameTable[info.tree.assistants[i]], lev + 1);\n if (!this.hasChild(layout, shape)) {\n if (i === 0) {\n levelBounds = bounds;\n }\n else {\n this.uniteRects(levelBounds, bounds);\n }\n }\n if (i % 2 === 0 && asst.prevBounds) {\n if (diff === undefined) {\n diff = asst.canMoveBy;\n }\n else {\n diff = Math.min(diff, asst.canMoveBy);\n }\n }\n if (i % 2 === 1 || i === info.tree.assistants.length - 1) {\n intersect = this.findIntersectingLevels(layout, bounds, lev + 1);\n //Update rightmost positions of known layout levels\n this.updateRearBounds(layout, null, [{ rBounds: bounds }], lev + 1, intersect);\n lev++;\n }\n }\n }\n if (levelBounds) {\n levelBounds.canMoveBy = diff;\n }\n return levelBounds;\n };\n HierarchicalTree.prototype.getDimensions = function (layout, shape, x, y, level) {\n var width;\n width = shape.actualSize.width;\n var height;\n height = shape.actualSize.height;\n if (layout.orientation.indexOf('Left') !== -1) {\n if (!level) {\n var temp = void 0;\n temp = x;\n x = y;\n y = temp;\n }\n height = shape.actualSize.width;\n width = shape.actualSize.height;\n }\n return { x: x, y: y, width: width, height: height };\n };\n HierarchicalTree.prototype.hasChild = function (layout, shape) {\n //Check whether the node has children \n var shape1 = layout.graphNodes[shape.id];\n return shape1.tree.children && shape1.tree.children.length;\n };\n HierarchicalTree.prototype.updateHorizontalTree = function (layout, shape, prev, x, y, level) {\n //Get dimensions with respect to layout orientations \n var dimensions;\n dimensions = this.getDimensions(layout, shape, x, y, level);\n var info = {};\n info = layout.graphNodes[shape.id];\n var side = info.tree.type;\n var lev;\n lev = level;\n var right = 0;\n right = x;\n var bottom;\n bottom = y;\n var width;\n var height;\n var child;\n var childBounds;\n var childWidth;\n var childHeight;\n var prevBounds;\n var bounds;\n var actBounds;\n var maxLevel;\n var translateSibilingsBy;\n var canMoveBy;\n var oldActBounds;\n var i;\n var childInfo;\n var prevLayoutLevels;\n var firstChildInfo;\n prevLayoutLevels = layout.levels.slice(0, layout.levels.length);\n if (this.hasChild(layout, shape)) {\n var h = void 0;\n h = layout.orientation.indexOf('Left') !== -1 ? true : false;\n for (i = 0; i < info.tree.children.length; i++) {\n child = layout.nameTable[info.tree.children[i]];\n width = child.actualSize.width;\n height = child.actualSize.height;\n childWidth = h ? height : width;\n childHeight = h ? width : height;\n prevBounds = layout.levels[lev + 1] ? layout.levels[lev + 1].rBounds : null;\n //Update sub tree\n childBounds = this.updateTree(layout, right, bottom, child, lev + 1, layout.nameTable[info.tree.children[i - 1]]);\n childInfo = layout.graphNodes[child.id];\n info.maxLevel = Math.max(info.maxLevel || 0, childInfo.maxLevel || 0);\n actBounds = { x: childInfo.x, y: childInfo.y, right: childInfo.x + childWidth, bottom: childInfo.y + childHeight };\n if (i === 0) {\n //Compare with previous(right most) subtree\n bounds = {\n x: Math.min(childInfo.x, childBounds.x), y: Math.min(childInfo.y, childBounds.y),\n right: childBounds.right, bottom: childBounds.bottom\n };\n firstChildInfo = childInfo;\n }\n if (!oldActBounds) {\n oldActBounds = actBounds;\n }\n else {\n oldActBounds.x = actBounds.x;\n oldActBounds.y = actBounds.y;\n if (actBounds.right > oldActBounds.right) {\n oldActBounds.right = actBounds.right;\n }\n oldActBounds.bottom = actBounds.bottom;\n //oldActBounds = actBounds;\n }\n //Compare with previous subtree if level of the child is greater than the level of previous sub tree\n //Check - what will happen if level of second child is greater than current child\n if (i === 0) {\n info.firstChild = { x: childInfo.x, canMoveBy: childInfo.canMoveBy, child: child.id };\n }\n if (this.hasChild(layout, child)) {\n if (!info.firstChild || info.firstChild.x >= childInfo.firstChild.x) {\n if (childInfo.firstChild && info.firstChild.canMoveBy < childInfo.canMoveBy) {\n info.firstChild.canMoveBy = canMoveBy;\n childInfo.canMoveBy = canMoveBy;\n canMoveBy = info.firstChild.canMoveBy;\n layout.graphNodes[info.firstChild.child].canMoveBy = canMoveBy;\n }\n var canMoveValue = canMoveBy !== undefined ? canMoveBy : childInfo.canMoveBy;\n info.firstChild = { x: childInfo.firstChild.x, canMoveBy: canMoveValue, child: child.id };\n }\n else if (childInfo.firstChild && childInfo.translated && info.firstChild.canMoveBy > childInfo.canMoveBy) {\n info.firstChild.canMoveBy = layout.graphNodes[info.firstChild.child].canMoveBy = childInfo.canMoveBy;\n }\n }\n maxLevel = maxLevel ? Math.max(childInfo.maxLevel, maxLevel) : childInfo.maxLevel;\n this.uniteRects(bounds, childBounds);\n if (i !== 0 && !this.hasChild(layout, child) && childInfo.subTreeTranslation < 0) {\n right = childBounds.right - childInfo.subTreeTranslation + layout.horizontalSpacing;\n }\n else {\n right = childBounds.right + layout.horizontalSpacing;\n }\n }\n if (!isNaN(translateSibilingsBy)) {\n firstChildInfo.canMoveBy = translateSibilingsBy;\n }\n info.mid = (firstChildInfo.x + oldActBounds.right) / 2 - dimensions.width / 2;\n //Set parent based on the chart type\n if (side === 'Left') {\n info.mid = actBounds.right - dimensions.width;\n }\n else if (side === 'Right') {\n info.mid = x;\n }\n }\n return bounds;\n };\n HierarchicalTree.prototype.updateHorizontalTreeWithMultipleRows = function (layout, shape, prev, x, y, level) {\n //declarations\n var child;\n var childInfo;\n var childBounds;\n var childWidth;\n var childHeight;\n var firstChildInfo;\n var maxLevel;\n var bounds;\n var rowBounds;\n var width;\n var height;\n var diff;\n var translateSibilingsBy;\n var fchild;\n var maxRowWidth;\n var j;\n var i;\n var k;\n var max;\n var leftCenter;\n var rightCenter;\n //Get dimensions with respect to layout orientations\n var dimensions = this.getDimensions(layout, shape, x, y, level);\n var info = layout.graphNodes[shape.id];\n var side = info.tree.type;\n var lev = level;\n var right = x;\n var bottom = y;\n var prevLayoutLevels = layout.levels.slice(0, layout.levels.length);\n var minTranslation = 0;\n if (this.hasChild(layout, shape)) {\n var h = layout.orientation.indexOf('Left') !== -1 ? true : false;\n var align = void 0;\n var rows = this.splitChildrenInRows(layout, shape);\n var unique = info.tree.children.length === 5 && rows[0].length === 3;\n var leftTree = [];\n var rightTree = [];\n if (!unique) {\n this.splitRows(rows, leftTree, rightTree);\n }\n else {\n rightTree = rows;\n }\n var treeInfo = { leftTree: leftTree, rows: rows, rightTree: rightTree, dimensions: dimensions };\n var rightMost = this.updateLeftTree(layout, treeInfo, shape, x, bottom, lev);\n bounds = treeInfo.bounds;\n var rightX = void 0;\n var center = (rightMost || 0) + (rightMost !== undefined ? (layout.horizontalSpacing / 2) : 0);\n if (rightMost !== undefined) {\n info.mid = center - dimensions.width / 2;\n rightX = rightMost + layout.horizontalSpacing;\n }\n bottom = y;\n var rightBounds = void 0;\n rightBounds = [];\n for (i = 0; i < rightTree.length; i++) {\n if (rows[i].length % 2 === 1 && i === rightTree.length - 1 || unique) {\n right = x;\n }\n else {\n right = rightX || x;\n }\n if (i !== 0) {\n bottom = rightBounds[i - 1].bottom + layout.verticalSpacing;\n }\n for (j = 0; j < rightTree[i].length; j++) {\n child = layout.nameTable[rightTree[i][j]];\n width = child.actualSize.width;\n height = child.actualSize.height;\n childWidth = h ? height : width;\n childHeight = h ? width : height;\n //Update sub tree\n childInfo = layout.graphNodes[child.id];\n childInfo.actualLevel = lev + 1 + i;\n if (j === 0 && leftTree[i] && leftTree[i].length) {\n childInfo.translate = false;\n }\n if (unique && i === 1) {\n if (j === 0 && leftCenter + childWidth + layout.horizontalSpacing <= rightCenter) {\n align = true;\n right = leftCenter - childWidth / 2;\n }\n if (align && j === 1) {\n right = rightCenter - childWidth / 2;\n }\n }\n childBounds = this.updateTree(layout, right, bottom, child, lev + 1, layout.nameTable[rightTree[i][j - 1]]);\n if (unique && j <= 2 && i === 0) {\n if (j === 1) {\n leftCenter = childBounds.x - layout.horizontalSpacing / 2;\n rightCenter = childBounds.x + childWidth + layout.horizontalSpacing / 2;\n }\n }\n if (j === 0) {\n rightBounds[i] = { x: childBounds.x, y: childBounds.y, right: childBounds.right, bottom: childBounds.bottom };\n }\n else {\n this.uniteRects(rightBounds[i], childBounds);\n }\n if (!bounds) {\n bounds = {\n x: rightBounds[i].x, y: rightBounds[i].y, right: rightBounds[i].right,\n bottom: rightBounds[i].bottom\n };\n }\n this.uniteRects(bounds, rightBounds[i]);\n right = childBounds.right + layout.horizontalSpacing;\n if (!info.firstChild || ((i === rightTree.length - 1 && rows[i].length % 2 === 1) || unique)\n && j === 0 && childInfo.canMoveBy !== undefined && minTranslation > childInfo.canMoveBy) {\n minTranslation = Math.min(minTranslation, childInfo.canMoveBy || 0);\n info.firstChild = { x: childInfo.x, child: child.id, canMoveBy: childInfo.canMoveBy };\n }\n treeInfo.leftCenter = leftCenter;\n treeInfo.rightCenter = rightCenter;\n treeInfo.align = align;\n treeInfo.level = lev;\n treeInfo.rightBounds = rightBounds;\n this.alignRowsToCenter(layout, i, shape, treeInfo, rightX);\n }\n }\n }\n return bounds;\n };\n HierarchicalTree.prototype.updateLeftTree = function (layout, treeInfo, shape, x, bottom, lev) {\n var leftTree = treeInfo.leftTree;\n var info = layout.graphNodes[shape.id];\n var right;\n var leftBounds = [];\n var minTranslation;\n var rightMost;\n var childBounds;\n var bounds;\n var h = layout.orientation.indexOf('Left') !== -1 ? true : false;\n //Arrange left side\n for (var i = 0; i < leftTree.length && leftTree[i].length; i++) {\n right = x;\n if (leftBounds[i - 1]) {\n bottom = leftBounds[i - 1].bottom + layout.verticalSpacing;\n }\n for (var j = 0; j < leftTree[i].length; j++) {\n var child = layout.nameTable[leftTree[i][j]];\n var childWidth = h ? child.actualSize.height : child.actualSize.width;\n var childHeight = h ? child.actualSize.width : child.actualSize.height;\n //Update sub tree\n var childInfo = layout.graphNodes[child.id];\n childInfo.actualLevel = lev + 1 + i;\n childBounds = this.updateTree(layout, right, bottom, child, lev + 1, layout.nameTable[leftTree[i][j - 1]]);\n if (j === 0) {\n leftBounds[i] = { x: childBounds.x, y: childBounds.y, right: childBounds.right, bottom: childBounds.bottom };\n }\n else {\n this.uniteRects(leftBounds[i], childBounds);\n }\n if (i === 0 && j === 0) {\n minTranslation = childInfo.canMoveBy;\n info.firstChild = { x: childInfo.x, child: child.id, canMoveBy: childInfo.canMoveBy };\n }\n else if (j === 0 && childInfo.canMoveBy !== undefined && minTranslation > childInfo.canMoveBy) {\n minTranslation = Math.min(minTranslation, childInfo.canMoveBy || 0);\n info.firstChild = { x: childInfo.x, child: child.id, canMoveBy: childInfo.canMoveBy };\n }\n right = childBounds.right + layout.horizontalSpacing;\n }\n if (i === 0) {\n rightMost = leftBounds[i].right;\n }\n else {\n rightMost = Math.max(rightMost, leftBounds[i].right);\n }\n }\n //Translate to same positions\n for (var i = 0; i < leftTree.length && leftTree[i].length; i++) {\n if (rightMost !== leftBounds[i].right) {\n var diff = rightMost - leftBounds[i].right;\n for (var j = 0; j < leftTree[i].length; j++) {\n var element = layout.nameTable[leftTree[i][j]];\n var elementInfo = layout.graphNodes[leftTree[i][j]];\n elementInfo.x += diff;\n }\n //leftBounds[i].x += diff;\n //leftBounds[i].right += diff;\n }\n if (i === 0) {\n bounds = { x: leftBounds[0].x, y: leftBounds[0].y, right: leftBounds[0].right, bottom: leftBounds[0].bottom };\n }\n else {\n this.uniteRects(bounds, leftBounds[i]);\n }\n }\n treeInfo.bounds = bounds;\n return rightMost;\n };\n HierarchicalTree.prototype.alignRowsToCenter = function (layout, i, shape, treeInfo, rightX) {\n var max;\n var centered;\n var diff;\n var info = layout.graphNodes[shape.id];\n var rows = treeInfo.rows;\n var rightTree = treeInfo.rightTree;\n var leftCenter = treeInfo.leftCenter;\n var rightCenter = treeInfo.rightCenter;\n var align = treeInfo.align;\n var rightBounds = treeInfo.rightBounds;\n var dimensions = treeInfo.dimensions;\n var lev = treeInfo.level;\n var unique = info.tree.children.length === 5 && rows[0].length === 3;\n if (unique && i === 1) {\n max = (rightBounds[0].right - rightBounds[0].x) >= (rightBounds[1].right - rightBounds[1].x) ? 0 : 1;\n }\n if (i === rows.length - 1) {\n if (rows[i].length % 2 === 1 || unique && i === 1) {\n centered = rightTree[i][Math.floor(rightTree[i].length / 2)];\n var centerObjct = void 0;\n centerObjct = layout.nameTable[centered];\n var childDimension = void 0;\n var centeredX = layout.graphNodes[centered].x;\n var centeredY = layout.graphNodes[centered].y;\n childDimension = this.getDimensions(layout, centerObjct, centeredX, centeredY, lev + 1);\n diff = undefined;\n if (!align && unique) {\n if (max === 1) {\n i = 0;\n }\n diff = (rightBounds[max].x + rightBounds[max].right) / 2 - (rightBounds[i].x + rightBounds[i].right) / 2;\n if (i === 0) {\n info.mid += diff;\n }\n }\n else if (!unique && rightX !== undefined) {\n diff = rightX - layout.horizontalSpacing / 2 - (centeredX + childDimension.width / 2);\n }\n if (diff !== undefined) {\n this.updateRearBoundsOfTree(layout, rightTree[i], diff, dimensions);\n }\n if (unique) {\n info.mid = (rightCenter + leftCenter) / 2 + (i === 0 ? diff : 0) - dimensions.width / 2;\n }\n if (info.mid === undefined && layout.graphNodes[centered]) {\n info.mid = centeredX;\n }\n align = false;\n i++;\n }\n }\n };\n HierarchicalTree.prototype.updateRearBoundsOfTree = function (layout, rightTree, diff, dimensions) {\n for (var j = 0; j < rightTree.length; j++) {\n var childInfo = layout.graphNodes[rightTree[j]];\n var child = layout.nameTable[rightTree[j]];\n childInfo.x += diff;\n childInfo.canMoveBy += diff;\n if (j === rightTree.length - 1) {\n //removed child dimensions call calculation, since that is not used\n var childBnds = {\n x: childInfo.x, y: childInfo.y, right: childInfo.x +\n dimensions.width, bottom: childInfo.y + dimensions.height\n };\n var intersect = this.findIntersectingLevels(layout, childBnds, childInfo.actualLevel);\n this.updateRearBounds(layout, null, [{ rBounds: childBnds }], childInfo.actualLevel, intersect);\n }\n }\n };\n HierarchicalTree.prototype.splitRows = function (rows, leftTree, rightTree) {\n for (var i = 0; i < rows.length; i++) {\n leftTree[i] = [];\n rightTree[i] = [];\n var half = void 0;\n half = rows[i].length;\n if (rows[i].length % 2 !== 1) {\n half = Math.ceil(rows[i].length / 2);\n for (var k = 0; k < half; k++) {\n leftTree[i].push(rows[i][k]);\n }\n }\n for (var j = leftTree[i].length; j < rows[i].length; j++) {\n rightTree[i].push(rows[i][j]);\n }\n }\n };\n HierarchicalTree.prototype.updateVerticalTree = function (layout, shape, x, y, level, dontUpdate) {\n //declarations\n var child;\n var childInfo;\n var childBounds;\n var childWidth;\n var childHeight;\n var prevBounds;\n var bounds;\n var actBounds;\n var oddBounds;\n var evenBounds;\n var dimensions = this.getDimensions(layout, shape, x, y, level);\n var info = layout.graphNodes[shape.id];\n var firstChild = layout.nameTable[info.tree.children[0]];\n var h = layout.orientation.indexOf('Left') !== -1 ? true : false;\n var factor = info.tree.type === 'Left' ? -1 : 0;\n var right = x;\n var bottom = y;\n var lev;\n lev = level;\n var i;\n var intersect;\n var type;\n var levels = [];\n var oddLevels = [];\n var canMoveBy;\n var diff;\n for (i = 0; i < info.tree.children.length; i++) {\n if (info.tree.type === 'Alternate') {\n //arrange at both left and right\n type = (i % 2 === 0 && info.tree.children.length > 2) ? 'Left' : 'Right';\n factor = (i % 2 === 0 && info.tree.children.length > 2) ? -1 : 0;\n }\n right = x + this.findOffset(layout, shape, info, type);\n child = layout.nameTable[info.tree.children[i]];\n childWidth = h ? child.actualSize.height : child.actualSize.width;\n childHeight = h ? child.actualSize.width : child.actualSize.height;\n //Update sub tree\n childBounds = this.updateTree(layout, right + factor * childWidth, bottom, child, level + 1, undefined, true);\n childInfo = layout.graphNodes[child.id];\n actBounds = { x: childInfo.x, y: childInfo.y, right: childInfo.x + childWidth, bottom: childInfo.y + childHeight };\n if (i === 0) {\n this.uniteRects(childBounds, actBounds);\n bounds = childBounds;\n }\n else {\n this.uniteRects(bounds, childBounds);\n }\n //Check and adjust the space left from previous subtree/sibling\n if (childInfo.prevBounds && !(info.tree.type === 'Alternate' && i % 2 === 1 && info.tree.children.length > 2)) {\n canMoveBy = canMoveBy !== undefined ? Math.min(childInfo.canMoveBy, canMoveBy) : childInfo.canMoveBy;\n }\n //Max level of the subtree node\n info.maxLevel = Math.max(info.maxLevel || 0, childInfo.maxLevel || 0);\n if (!(info.tree.type === 'Alternate' && info.tree.children.length > 2 && i % 2 === 0)) {\n if (info.tree.type === 'Alternate' && info.tree.children.length > 2) {\n //alternate - arrange children with even index(0,2,4,6,..) at the next level\n bottom = Math.max(childBounds.bottom, prevBounds.bottom) + layout.verticalSpacing / 2;\n }\n else {\n // left/right - arrange next child at the nect level(bottom)\n bottom = childBounds.bottom + layout.verticalSpacing / 2;\n }\n level = info.maxLevel;\n levels.push({ rBounds: actBounds });\n if (!evenBounds) {\n evenBounds = {\n x: childInfo.x, y: childInfo.y, right: childInfo.x + childWidth,\n bottom: childInfo.y + childHeight\n };\n }\n else {\n this.uniteRects(evenBounds, actBounds);\n }\n if (childInfo.levelBounds) {\n levels = levels.concat(childInfo.levelBounds);\n }\n }\n else {\n if (i !== 0) {\n bottom = prevBounds.bottom + layout.verticalSpacing / 2;\n }\n oddLevels.push({ rBounds: actBounds });\n if (childInfo.levelBounds) {\n oddLevels = oddLevels.concat(childInfo.levelBounds);\n }\n }\n if (i === 0) {\n info.firstChild = { x: childInfo.x, canMoveBy: childInfo.canMoveBy, child: child.id };\n }\n if (this.hasChild(layout, child)) {\n if (!info.firstChild || info.firstChild.x >= childInfo.firstChild.x) {\n if (childInfo.firstChild && info.firstChild.canMoveBy < childInfo.canMoveBy) {\n var canMoveBy_1 = info.firstChild.canMoveBy;\n childInfo.canMoveBy = canMoveBy_1;\n layout.graphNodes[info.firstChild.child].canMoveBy = canMoveBy_1;\n info.firstChild.canMoveBy = canMoveBy_1;\n }\n info.firstChild = {\n x: childInfo.firstChild.x, canMoveBy: canMoveBy !== undefined ? canMoveBy : childInfo.canMoveBy,\n child: child.id\n };\n }\n else if (childInfo.firstChild && childInfo.translated && info.firstChild.canMoveBy > childInfo.canMoveBy) {\n info.firstChild.canMoveBy = layout.graphNodes[info.firstChild.child].canMoveBy = childInfo.canMoveBy;\n }\n }\n prevBounds = actBounds;\n }\n //To set level bounds(right most position of levels)\n if (!dontUpdate) {\n if (info.tree.type === 'Alternate' && info.tree.children.length > 2) {\n oddBounds = {\n x: oddLevels[0].rBounds.x, y: oddLevels[0].rBounds.y,\n right: oddLevels[oddLevels.length - 1].rBounds.right, bottom: oddLevels[oddLevels.length - 1].rBounds.bottom\n };\n intersect = this.findIntersectingLevels(layout, oddBounds, lev + 1);\n this.updateRearBounds(layout, null, oddLevels, lev + 1, intersect);\n }\n intersect = this.findIntersectingLevels(layout, evenBounds || bounds, lev + 1);\n this.updateRearBounds(layout, null, evenBounds ? levels : [{ rBounds: bounds }], lev + 1, intersect);\n }\n else {\n info.levelBounds = levels;\n }\n if (!isNaN(canMoveBy)) {\n layout.graphNodes[firstChild.id].canMoveBy = canMoveBy;\n }\n info.childBounds = bounds;\n info.mid = x;\n return bounds;\n };\n HierarchicalTree.prototype.splitChildrenInRows = function (layout, shape) {\n var info;\n info = layout.graphNodes[shape.id];\n var column;\n column = 4;\n var rows = [];\n var childNodes;\n childNodes = info.tree.children.length;\n var children = this.extend(info.tree.children);\n if (info.tree.rows) {\n var count = void 0;\n count = info.tree.children.length;\n var columns = void 0;\n columns = Math.ceil(count / info.tree.rows);\n if (columns % 2 === 0) {\n column = columns;\n }\n else {\n column = columns + 1;\n }\n }\n else if (info.tree.children.length === 3 || info.tree.children.length === 4) {\n column = 2;\n }\n else if (info.tree.children.length === 5) {\n column = 3;\n }\n while (childNodes > 0) {\n rows[rows.length] = children.splice(0, column);\n childNodes -= column;\n if (childNodes < column) {\n column = childNodes;\n }\n }\n return rows;\n };\n HierarchicalTree.prototype.extend = function (temp) {\n var i;\n var dummy = [];\n for (i = 0; i < temp.length; i++) {\n dummy[i] = temp[i];\n }\n return dummy;\n };\n HierarchicalTree.prototype.findOffset = function (layout, shape, info, type) {\n var offset = 0;\n var space = (layout.orientation.indexOf('Left') !== -1) ? shape.actualSize.height :\n shape.actualSize.width;\n var treeType = type ? type : info.tree.type;\n offset = info.tree.offset || 20;\n if (info.tree.type === 'Alternate') {\n if (offset >= layout.horizontalSpacing) {\n offset = layout.horizontalSpacing / 2;\n }\n }\n switch (treeType) {\n case 'Left':\n offset = space / 2 - offset;\n break;\n case 'Right':\n offset = offset + space / 2;\n break;\n }\n return offset;\n };\n HierarchicalTree.prototype.uniteRects = function (rect1, rect2) {\n //Unite two rects\n rect1.x = Math.min(rect1.x, rect2.x);\n rect1.right = Math.max(rect1.right, rect2.right);\n rect1.bottom = Math.max(rect1.bottom, rect2.bottom);\n };\n HierarchicalTree.prototype.spaceLeftFromPrevSubTree = function (layout, shape, bounds) {\n var info;\n info = layout.graphNodes[shape.id];\n var dif;\n var prevBounds;\n var intersect;\n var k;\n var space;\n space = layout.horizontalSpacing;\n //Find the minimum distance to move towards previous sub tree\n for (k = 0; k < info.intersect.length; k++) {\n prevBounds = layout.levels[info.intersect[k]].rBounds;\n dif = bounds.x - (prevBounds.right + space);\n if (info.diff === undefined || dif < info.diff) {\n info.diff = dif;\n info.prevBounds = layout.levels[info.intersect[k]].rBounds;\n }\n }\n };\n HierarchicalTree.prototype.findIntersectingLevels = function (layout, bounds, level, actualLevel) {\n //intersecting with exact Level\n var bnds;\n bnds = { x: bounds.x, y: bounds.y, right: bounds.right, bottom: bounds.bottom };\n bnds.y -= layout.verticalSpacing / 2;\n bnds.bottom += layout.verticalSpacing / 2;\n var intersectingLevels;\n intersectingLevels = [];\n var rBounds;\n var l;\n l = actualLevel !== undefined ? actualLevel : level;\n rBounds = layout.levels[l] ? layout.levels[l].rBounds : null;\n //Performance - We can consider only the intersecting levels\n do {\n if (rBounds && ((bnds.y < rBounds.y && bnds.bottom > rBounds.y)\n || (bnds.y < rBounds.bottom && rBounds.bottom < bnds.bottom) ||\n bnds.y >= rBounds.y &&\n bnds.bottom <= rBounds.bottom || bnds.y < rBounds.y && bnds.bottom > rBounds.bottom)) {\n var index = 0;\n intersectingLevels.splice(index, 0, l);\n }\n else if (rBounds && rBounds.bottom < bnds.y) {\n break;\n }\n l--;\n rBounds = layout.levels[l] ? layout.levels[l].rBounds : null;\n } while (l >= 0);\n l = (actualLevel !== undefined ? actualLevel : level) + 1;\n rBounds = layout.levels[l] ? layout.levels[l].rBounds : null;\n do {\n if (rBounds && ((bnds.y < rBounds.y && bnds.bottom > rBounds.y) ||\n (bnds.y < rBounds.bottom && rBounds.bottom < bnds.bottom) ||\n bnds.y >= rBounds.y && bnds.bottom <= rBounds.bottom || bnds.y < rBounds.y && bnds.bottom > rBounds.bottom)) {\n intersectingLevels.push(l);\n }\n else if (rBounds && rBounds.y > bnds.bottom) {\n break;\n }\n l++;\n rBounds = layout.levels[l] ? layout.levels[l].rBounds : null;\n } while (l <= layout.levels.length);\n return intersectingLevels;\n };\n HierarchicalTree.prototype.findLevel = function (layout, bounds, level) {\n var bnds;\n bnds = bounds;\n var l;\n l = 0;\n var rBounds;\n rBounds = layout.levels[l] ? layout.levels[l].rBounds : null;\n while (l < layout.levels.length) {\n if (rBounds && bnds.bottom < rBounds.y) {\n return l;\n }\n else {\n l++;\n }\n rBounds = layout.levels[l] ? layout.levels[l].rBounds : null;\n }\n return l;\n };\n HierarchicalTree.prototype.getParentNode = function (layout, node) {\n //Return the first parent node\n return layout.nameTable[layout.nameTable[node.inEdges[0]].sourceID];\n };\n HierarchicalTree.prototype.updateEdges = function (layout, node, depth) {\n var layoutInfo;\n layoutInfo = layout.graphNodes[node.id];\n var j;\n if (node.outEdges && node.outEdges.length && node.isExpanded) {\n for (j = 0; j < node.outEdges.length; j++) {\n var edge = void 0;\n edge = layout.nameTable[layout.nameTable[node.outEdges[j]].targetID];\n if (!edge.excludeFromLayout) {\n if (layoutInfo.tree.children.indexOf(edge.id) === -1) {\n layoutInfo.tree.children.push(edge.id);\n }\n if (edge.outEdges && edge.outEdges.length && edge.isExpanded) {\n layoutInfo.tree.hasSubTree = true;\n }\n this.updateEdges(layout, edge, depth + 1);\n }\n }\n }\n //set level info\n layoutInfo.tree.level = depth;\n //By default, orientation is horizontal for nested trees\n if (layoutInfo.tree.hasSubTree) {\n layoutInfo.tree.orientation = 'Horizontal';\n layoutInfo.tree.type = 'Center';\n }\n //Customizing assistants and children collection\n //Performance-Instead of reading the method everytime, we can set once and can reuse that\n if (layout.getLayoutInfo && layout.type === 'OrganizationalChart') {\n layout.getLayoutInfo(node, layoutInfo.tree);\n if (layoutInfo.tree.type === 'Balanced' && layoutInfo.tree.hasSubTree) {\n layoutInfo.tree.type = 'Center';\n layoutInfo.tree.orientation = 'Horizontal';\n }\n }\n if (layout.level && layoutInfo.tree.type !== 'Alternate' && depth >= layout.level) {\n layoutInfo.tree.hasSubTree = false;\n }\n };\n HierarchicalTree.prototype.updateAnchor = function (layout, bounds, viewPort) {\n var node;\n var fixedNode;\n var width = 0;\n var height = 0;\n var mod = 0;\n var viewPortBounds = new Rect(0, 0, viewPort.x, viewPort.y);\n var layoutBounds;\n layoutBounds = layout.bounds ? layout.bounds : viewPortBounds;\n var orientation = layout.orientation;\n //Anchor based on fixed nodes\n if (layout.fixedNode) {\n fixedNode = layout.nameTable[layout.fixedNode];\n width = fixedNode.actualSize.width;\n height = fixedNode.actualSize.height;\n layout.anchorX = fixedNode.offsetX;\n layout.anchorY = fixedNode.offsetY;\n var pivot = fixedNode.pivot;\n layout.anchorX += layout.orientation === 'RightToLeft' ? width * pivot.x : -width * pivot.x;\n layout.anchorY += layout.orientation === 'BottomToTop' ? height * pivot.y : -height * pivot.y;\n node = fixedNode;\n mod = 0;\n while (node.inEdges.length) {\n node = this.getParentNode(layout, node);\n mod += layout.graphNodes[node.id].subTreeTranslation || 0;\n }\n if (layout.orientation.indexOf('Left') !== -1) {\n layout.anchorX -= layout.graphNodes[fixedNode.id].y;\n layout.anchorY -= layout.graphNodes[fixedNode.id].x + mod;\n }\n else {\n layout.anchorX -= layout.graphNodes[fixedNode.id].x + mod;\n layout.anchorY -= layout.graphNodes[fixedNode.id].y;\n }\n }\n else {\n if (orientation === 'TopToBottom' || orientation === 'BottomToTop') {\n switch (layout.horizontalAlignment) {\n case 'Left':\n layout.anchorX = (layoutBounds.x - bounds.x) + layout.margin.left;\n break;\n case 'Right':\n layout.anchorX = layoutBounds.x + layoutBounds.width - layout.margin.right - bounds.right;\n break;\n case 'Auto':\n case 'Center':\n layout.anchorX = layoutBounds.x + layoutBounds.width / 2 - (bounds.x + bounds.right) / 2;\n break;\n }\n switch (layout.verticalAlignment) {\n case 'Auto':\n case 'Top':\n var top_1;\n top_1 = layoutBounds.y + layout.margin.top;\n layout.anchorY = orientation === 'TopToBottom' ? top_1 : bounds.bottom + top_1;\n break;\n case 'Bottom':\n var bottom = void 0;\n bottom = layoutBounds.y + layoutBounds.height - layout.margin.bottom;\n layout.anchorY = orientation === 'TopToBottom' ? bottom - bounds.bottom : bottom;\n break;\n case 'Center':\n var center = void 0;\n center = layoutBounds.y + layoutBounds.height / 2;\n layout.anchorY = layout.orientation === 'TopToBottom' ?\n center - (bounds.y + bounds.bottom) / 2 : center + (bounds.y + bounds.bottom) / 2;\n break;\n }\n }\n else {\n switch (layout.horizontalAlignment) {\n case 'Auto':\n case 'Left':\n var left = void 0;\n left = layoutBounds.x + layout.margin.left;\n layout.anchorX = orientation === 'LeftToRight' ? left : bounds.bottom + left;\n break;\n case 'Right':\n var right = void 0;\n right = layoutBounds.x + layoutBounds.width - layout.margin.right;\n layout.anchorX = orientation === 'LeftToRight' ? right - bounds.bottom : right;\n break;\n case 'Center':\n var center = void 0;\n center = layoutBounds.width / 2 + layoutBounds.x;\n layout.anchorX = layout.orientation === 'LeftToRight' ?\n center - (bounds.y + bounds.bottom) / 2 : center + (bounds.y + bounds.bottom) / 2;\n break;\n }\n switch (layout.verticalAlignment) {\n case 'Top':\n layout.anchorY = layoutBounds.y + layout.margin.top - bounds.x;\n break;\n case 'Auto':\n case 'Center':\n layout.anchorY = layoutBounds.y + layoutBounds.height / 2 - (bounds.right + bounds.x) / 2;\n break;\n case 'Bottom':\n layout.anchorY = layoutBounds.y + layoutBounds.height - layout.margin.bottom - bounds.right;\n break;\n }\n }\n }\n };\n HierarchicalTree.prototype.updateConnectors = function (layout, node, level) {\n var i;\n var info;\n var nodeWidth;\n var nodeHeight;\n var targetWidth;\n var targetHeight;\n var length;\n var offsetLen;\n var points;\n var segments;\n var target;\n var conn;\n var relative;\n var center;\n var layoutProp;\n //Route out edges\n info = layout.graphNodes[node.id];\n var direction;\n if (node.outEdges.length) {\n for (i = 0; i < node.outEdges.length; i++) {\n conn = layout.nameTable[node.outEdges[i]];\n conn.points = [];\n target = layout.nameTable[conn.targetID];\n if (conn.visible) {\n conn.visited = true;\n if (layout.getConnectorSegments) {\n segments = layout.getConnectorSegments(conn);\n }\n else {\n if (info && info.tree.children.indexOf(conn.targetID) !== -1) {\n conn.segments = [];\n if (layout.type === 'OrganizationalChart' && conn.type === 'Orthogonal') {\n this.updateSegments(layout, conn, node, target, i);\n }\n }\n }\n if (target && (target.isExpanded || this.hasChild(layout, target))) {\n this.updateConnectors(layout, target, level + 1);\n }\n }\n }\n }\n if (info && info.tree.assistants.length) {\n //In-Edge routing of assistant nodes\n for (i = 0; i < info.tree.assistants.length; i++) {\n target = layout.nameTable[info.tree.assistants[i]];\n conn = layout.nameTable[target.inEdges[0]];\n this.get3Points(layout, node, target, conn);\n if (target.isExpanded || this.hasChild(layout, target)) {\n this.updateConnectors(layout, target, level + 1);\n }\n }\n }\n };\n HierarchicalTree.prototype.updateSegments = function (layout, conn, node, target, i) {\n var info = layout.graphNodes[node.id];\n //Connector routing - Horizontal layout orientation\n if (info.tree.assistants.length) {\n //Route in-edge of child node, if the parent has assistant\n this.updateSegmentsForHorizontalOrientation(layout, node, target, conn);\n }\n else {\n //Route in-edge of child node\n if (info.tree.orientation === 'Horizontal' && info.tree.type === 'Balanced') {\n this.updateSegmentsForBalancedTree(layout, conn, node, target, i);\n }\n else {\n if (info.tree.orientation === 'Horizontal') {\n this.updateSegmentsForHorizontalOrientation(layout, node, target, conn);\n }\n else {\n if (info.tree.offset < 5) {\n this.get5Points(layout, node, target, conn);\n }\n else {\n this.get3Points(layout, node, target, conn);\n }\n }\n }\n }\n };\n HierarchicalTree.prototype.updateSegmentsForBalancedTree = function (layout, connector, node, target, i) {\n var info = layout.graphNodes[node.id];\n var center;\n var relative;\n if (info.tree.children.length === 5 && i > 2) {\n relative = info.tree.children[1];\n if (isNaN(layout.graphNodes[relative].treeWidth)) {\n layout.graphNodes[relative].treeWidth = layout.nameTable[relative].actualSize.width;\n }\n var factor = i !== 3 ? 1 : -1;\n if (layout.orientation.indexOf('Left') !== -1) {\n center = layout.nameTable[relative].offsetY - layout.graphNodes[relative].treeWidth / 2 -\n (layout.verticalSpacing * factor / 2);\n }\n else {\n center = layout.nameTable[relative].offsetX +\n layout.graphNodes[relative].treeWidth / 2 + (layout.horizontalSpacing * factor) / 2;\n }\n this.getSegmentsForMultipleRows(layout, node, target, connector);\n }\n else {\n if (info.tree.children.length > 5) {\n if (i < 4) {\n this.getSegmentsForMultipleRows(layout, node, target, connector);\n }\n else {\n this.updateSegmentsForHorizontalOrientation(layout, node, target, connector);\n }\n }\n else if (info.tree.children.length === 4) {\n if (i < 2) {\n this.getSegmentsForMultipleRows(layout, node, target, connector);\n }\n else {\n this.updateSegmentsForHorizontalOrientation(layout, node, target, connector);\n }\n }\n else {\n this.getSegmentsForMultipleRows(layout, node, target, connector);\n }\n }\n };\n HierarchicalTree.prototype.get3Points = function (layout, node, target, connector) {\n var points = [];\n var nodeBounds = this.getBounds(node);\n var targetBounds = this.getBounds(target);\n if (layout.orientation.indexOf('Top') !== -1) {\n var startingPoint = layout.orientation.indexOf('Top') === 0 ? nodeBounds.bottomCenter :\n nodeBounds.topCenter;\n var endPoint = node.offsetX > target.offsetX ? targetBounds.middleRight : targetBounds.middleLeft;\n points.push(startingPoint, { x: nodeBounds.bottomCenter.x, y: endPoint.y }, endPoint);\n }\n else {\n var startingPoint = layout.orientation.indexOf('Left') === 0 ? nodeBounds.middleRight :\n nodeBounds.middleLeft;\n var endPoint = node.offsetY > target.offsetY ? targetBounds.bottomCenter : targetBounds.topCenter;\n points.push(startingPoint, { x: targetBounds.bottomCenter.x, y: nodeBounds.middleRight.y }, endPoint);\n }\n this.getSegmentsFromPoints(points, connector);\n };\n HierarchicalTree.prototype.get5Points = function (layout, node, target, connector) {\n var points = [];\n var layoutprop;\n var nodeBounds = this.getBounds(node);\n var targetBounds = this.getBounds(target);\n var info = layout.graphNodes[node.id];\n if (node.offsetX > target.offsetX) {\n points.push(nodeBounds.bottomCenter, { x: nodeBounds.bottomCenter.x, y: (nodeBounds.bottomCenter.y + layout.verticalSpacing / 4) }, {\n x: (targetBounds.middleRight.x + layout.horizontalSpacing / 2),\n y: (nodeBounds.bottomCenter.y + layout.verticalSpacing / 4)\n }, { x: (targetBounds.middleRight.x + layout.horizontalSpacing / 2), y: targetBounds.middleRight.y }, targetBounds.middleRight);\n }\n else {\n points.push(nodeBounds.bottomCenter, { x: nodeBounds.bottomCenter.x, y: (nodeBounds.bottomCenter.y + layout.verticalSpacing / 4) }, {\n x: (targetBounds.middleLeft.x - layout.horizontalSpacing / 2),\n y: (nodeBounds.bottomCenter.y + layout.verticalSpacing / 4)\n }, { x: (targetBounds.middleLeft.x - layout.horizontalSpacing / 2), y: targetBounds.middleLeft.y }, targetBounds.middleLeft);\n }\n this.getSegmentsFromPoints(points, connector);\n };\n HierarchicalTree.prototype.getSegmentsFromPoints = function (points, connector) {\n var segments = [];\n var segment;\n for (var i = 0; i < points.length - 2; i++) {\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(points[i], points[i + 1]);\n segment.length = Point.distancePoints(points[i], points[i + 1]);\n segments.push(segment);\n }\n connector.segments = segments;\n };\n HierarchicalTree.prototype.getSegmentsForMultipleRows = function (layout, node, target, connector) {\n var points = [];\n var segments = [];\n var point;\n var segment;\n var targetBounds = this.getBounds(target);\n var nodeBounds = this.getBounds(node);\n switch (layout.orientation) {\n case 'TopToBottom':\n point = { x: nodeBounds.bottomCenter.x, y: (nodeBounds.bottomCenter.y + layout.verticalSpacing / 4) };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.bottomCenter, point);\n segment.length = Point.distancePoints(nodeBounds.bottomCenter, point);\n segments.push(segment);\n break;\n case 'BottomToTop':\n point = { x: nodeBounds.bottomCenter.x, y: (nodeBounds.topCenter.y - layout.verticalSpacing / 4) };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.topCenter, point);\n segment.length = Point.distancePoints(nodeBounds.topCenter, point);\n segments.push(segment);\n break;\n case 'LeftToRight':\n point = { x: (nodeBounds.middleRight.x + layout.verticalSpacing / 4), y: nodeBounds.middleRight.y, };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.middleRight, point);\n segment.length = Point.distancePoints(nodeBounds.middleRight, point);\n segments.push(segment);\n if (targetBounds.center.y !== nodeBounds.center.y) {\n var point3 = { x: (nodeBounds.middleRight.x + layout.verticalSpacing / 4), y: targetBounds.middleLeft.y };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(point, point3);\n segment.length = Point.distancePoints(point, point3);\n segments.push(segment);\n }\n break;\n case 'RightToLeft':\n point = { x: (nodeBounds.middleLeft.x - layout.verticalSpacing / 4), y: nodeBounds.middleRight.y };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.middleLeft, point);\n segment.length = Point.distancePoints(nodeBounds.middleLeft, point);\n segments.push(segment);\n if (targetBounds.center.y !== nodeBounds.center.y) {\n var point_1 = { x: (nodeBounds.middleLeft.x - layout.verticalSpacing / 4), y: targetBounds.middleLeft.y };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(point_1, point_1);\n segment.length = Point.distancePoints(point_1, point_1);\n segments.push(segment);\n }\n break;\n }\n connector.segments = segments;\n };\n HierarchicalTree.prototype.updateSegmentsForHorizontalOrientation = function (layout, node, target, connector) {\n var points = [];\n var point2;\n var segment;\n var segments = [];\n var nodeBounds = this.getBounds(node);\n var targetBounds = this.getBounds(target);\n switch (layout.orientation) {\n case 'TopToBottom':\n point2 = { x: nodeBounds.bottomCenter.x, y: (targetBounds.topCenter.y - layout.verticalSpacing / 2) };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.bottomCenter, point2);\n segment.length = Point.distancePoints(nodeBounds.bottomCenter, point2);\n segments.push(segment);\n break;\n case 'BottomToTop':\n point2 = { x: nodeBounds.topCenter.x, y: (targetBounds.bottomCenter.y + layout.verticalSpacing / 2) };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.topCenter, point2);\n segment.length = Point.distancePoints(nodeBounds.topCenter, point2);\n segments.push(segment);\n break;\n case 'LeftToRight':\n point2 = { x: (targetBounds.middleLeft.x - layout.verticalSpacing / 2), y: nodeBounds.middleRight.y };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.middleRight, point2);\n segment.length = Point.distancePoints(nodeBounds.middleRight, point2);\n segments.push(segment);\n if (targetBounds.center.y !== nodeBounds.center.y) {\n var point3 = { x: (targetBounds.middleLeft.x - layout.verticalSpacing / 2), y: targetBounds.middleLeft.y };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(point2, point3);\n segment.length = Point.distancePoints(point2, point3);\n segments.push(segment);\n }\n break;\n case 'RightToLeft':\n point2 = { x: (targetBounds.middleRight.x + layout.verticalSpacing / 2), y: nodeBounds.middleRight.y };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(nodeBounds.middleLeft, point2);\n segment.length = Point.distancePoints(nodeBounds.middleLeft, point2);\n segments.push(segment);\n if (targetBounds.center.y !== nodeBounds.center.y) {\n var point = { x: (targetBounds.middleRight.x + layout.verticalSpacing / 2), y: targetBounds.middleLeft.y };\n segment = new OrthogonalSegment(connector, 'segments', { type: 'Orthogonal' }, true);\n segment.direction = Point.direction(point2, point);\n segment.length = Point.distancePoints(point2, point);\n segments.push(segment);\n }\n break;\n }\n connector.segments = segments;\n return points;\n };\n HierarchicalTree.prototype.updateNodes = function (layout, node, mod, update, dx, dy) {\n var i;\n var child;\n var width;\n var height;\n var offsetX;\n var offsetY;\n width = node.actualSize.width;\n height = node.actualSize.height;\n if (!node.excludeFromLayout) {\n offsetX = layout.anchorX;\n offsetY = layout.anchorY;\n /*Performance - instead of checking conditions for every node, we can make the layout related\n conditions once and we can reuse them*/\n if (layout.orientation === 'LeftToRight') {\n offsetX += layout.graphNodes[node.id].y + width / 2;\n offsetY += layout.graphNodes[node.id].x + mod + height / 2;\n }\n else if (layout.orientation === 'RightToLeft') {\n offsetX -= layout.graphNodes[node.id].y + width / 2;\n offsetY += layout.graphNodes[node.id].x + mod + height / 2;\n }\n else if (layout.orientation === 'TopToBottom') {\n offsetX += layout.graphNodes[node.id].x + mod + width / 2;\n offsetY += layout.graphNodes[node.id].y + height / 2;\n }\n else {\n offsetX += layout.graphNodes[node.id].x + mod + width / 2;\n offsetY -= layout.graphNodes[node.id].y + height / 2;\n }\n if (layout.graphNodes) {\n dx = dx ? dx : 0;\n dy = dy ? dy : 0;\n offsetX += dx;\n offsetY += dy;\n if (!this.isAnimation) {\n node.offsetX = offsetX;\n node.offsetY = offsetY;\n }\n }\n var objects = { id: node.id, differenceX: offsetX - node.offsetX, differenceY: offsetY - node.offsetY };\n layout.objects.push(objects);\n var list = void 0;\n list = [];\n if (this.hasChild(layout, node)) {\n for (i = 0; i < layout.graphNodes[node.id].tree.children.length; i++) {\n child = layout.nameTable[layout.graphNodes[node.id].tree.children[i]];\n this.updateNodes(layout, child, mod + (layout.graphNodes[node.id].subTreeTranslation || 0), update, dx, dy);\n list.push(child);\n }\n }\n if (layout.graphNodes[node.id].tree.assistants.length) {\n for (i = 0; i < layout.graphNodes[node.id].tree.assistants.length; i++) {\n child = layout.nameTable[layout.graphNodes[node.id].tree.assistants[i]];\n this.updateNodes(layout, child, mod + (layout.graphNodes[node.id].subTreeTranslation || 0), null, dx, dy);\n }\n }\n }\n };\n return HierarchicalTree;\n}());\nexport { HierarchicalTree };\n","import { Rect } from '../primitives/rect';\nimport { getFunction } from '../utility/base-util';\nimport { HierarchicalTree } from './hierarchical-tree';\n/**\n * Layout for mind-map tree\n */\nvar MindMap = /** @class */ (function () {\n /**\n * Constructor for the organizational chart module.\n * @private\n */\n function MindMap() {\n /**\n * Defines the layout animation\n *\n */\n this.isAnimation = false;\n //constructs the layout module\n }\n /**\n * To destroy the organizational chart\n * @return {void}\n * @private\n */\n MindMap.prototype.destroy = function () {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name.\n */\n MindMap.prototype.getModuleName = function () {\n /**\n * Returns the module name of the layout\n */\n return 'MindMapChart';\n };\n MindMap.prototype.updateLayout = function (nodes, nameTable, layoutProp, viewPort, uniqueId, root) {\n var isRoot;\n isRoot = this.checkRoot(nodes, layoutProp, uniqueId, root, nameTable);\n if (isRoot) {\n layoutProp.fixedNode = isRoot;\n }\n else {\n for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {\n var node = nodes_1[_i];\n if (!node.excludeFromLayout) {\n if (!node.inEdges || !node.inEdges.length) {\n layoutProp.fixedNode = node.id;\n break;\n }\n }\n }\n }\n var rootNode = nameTable[layoutProp.fixedNode];\n var fistLevelNodes = this.findFirstLevelNodes(rootNode, layoutProp, nameTable);\n var leftNodes = [];\n var rightNodes = [];\n var getMindmapBranch = getFunction(layoutProp.getBranch);\n getMindmapBranch = getMindmapBranch || getFunction(this.getBranch);\n for (var _a = 0, fistLevelNodes_1 = fistLevelNodes; _a < fistLevelNodes_1.length; _a++) {\n var node = fistLevelNodes_1[_a];\n var align = getMindmapBranch(node, fistLevelNodes);\n (align === 'Left') ? leftNodes.push(node) : rightNodes.push(node);\n }\n var viewPortBounds = new Rect(0, 0, viewPort.x, viewPort.y);\n nameTable[layoutProp.fixedNode].offsetX = viewPortBounds.x + viewPortBounds.width / 2;\n nameTable[layoutProp.fixedNode].offsetY = viewPortBounds.y + viewPortBounds.height / 2;\n if (leftNodes.length) {\n this.updateMindMapBranch(nodes, rightNodes, nameTable, layoutProp, viewPort, uniqueId, 'Left');\n }\n if (rightNodes.length) {\n this.updateMindMapBranch(nodes, leftNodes, nameTable, layoutProp, viewPort, uniqueId, 'Right');\n }\n };\n MindMap.prototype.checkRoot = function (nodes, layoutProp, uniqueId, root, nameTable) {\n for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {\n var node = nodes_2[_i];\n if (!node.excludeFromLayout) {\n if (node.data && (node.data[uniqueId].toString() === root || node.data[uniqueId].toString()\n === layoutProp.root)) {\n return node.id;\n }\n else if (!node.data && node.id === layoutProp.root) {\n return node.id;\n }\n }\n }\n return '';\n };\n MindMap.prototype.updateMindMapBranch = function (nodes, excludeNodes, nameTable, layoutProp, viewPort, uniqueId, side) {\n var layout;\n layout = {\n type: 'HierarchicalTree',\n horizontalSpacing: layoutProp.verticalSpacing, verticalSpacing: layoutProp.horizontalSpacing,\n verticalAlignment: layoutProp.verticalAlignment, horizontalAlignment: layoutProp.horizontalAlignment,\n fixedNode: layoutProp.fixedNode, getLayoutInfo: getFunction(layoutProp.getLayoutInfo), margin: layoutProp.margin,\n root: layoutProp.fixedNode\n };\n layout.orientation = (side === 'Left') ? 'LeftToRight' : 'RightToLeft';\n this.excludeFromLayout(excludeNodes, nameTable, true);\n var mapLayout = new HierarchicalTree();\n mapLayout.updateLayout(nodes, nameTable, layout, viewPort, uniqueId);\n this.excludeFromLayout(excludeNodes, nameTable, false);\n };\n MindMap.prototype.getBranch = function (obj, firstLevelNodes) {\n var side;\n var i = firstLevelNodes.indexOf(obj);\n if (i % 2 === 0) {\n side = 'Left';\n }\n else {\n side = 'Right';\n }\n return side;\n };\n MindMap.prototype.excludeFromLayout = function (newCollection, nameTable, exclude) {\n for (var _i = 0, newCollection_1 = newCollection; _i < newCollection_1.length; _i++) {\n var newcol = newCollection_1[_i];\n var node = nameTable[newcol.id];\n node.excludeFromLayout = exclude;\n }\n };\n MindMap.prototype.findFirstLevelNodes = function (node, layout, nameTable) {\n var parentNode;\n var fistLevelNodes = [];\n if (node && node.outEdges.length) {\n for (var _i = 0, _a = node.outEdges; _i < _a.length; _i++) {\n var outEdge = _a[_i];\n fistLevelNodes.push(nameTable[nameTable[outEdge].targetID]);\n }\n }\n return fistLevelNodes;\n };\n return MindMap;\n}());\nexport { MindMap };\n","/**\n * Radial Tree\n */\nvar RadialTree = /** @class */ (function () {\n /**\n * Constructor for the organizational chart module.\n * @private\n */\n function RadialTree() {\n //constructs the layout module\n }\n /**\n * To destroy the organizational chart\n * @return {void}\n * @private\n */\n RadialTree.prototype.destroy = function () {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name.\n */\n RadialTree.prototype.getModuleName = function () {\n /**\n * Returns the module name of the layout\n */\n return 'RadialTree';\n };\n RadialTree.prototype.updateLayout = function (nodes, nameTable, layoutProp, viewport) {\n var layout = {\n type: layoutProp.type,\n nameTable: nameTable, anchorX: 0, anchorY: 0,\n firstLevelNodes: [], centerNode: null, levels: [], maxLevel: 0, graphNodes: {}, layoutNodes: [],\n orientation: layoutProp.orientation,\n horizontalSpacing: layoutProp.horizontalSpacing, verticalSpacing: layoutProp.verticalSpacing,\n verticalAlignment: layoutProp.verticalAlignment, horizontalAlignment: layoutProp.horizontalAlignment,\n fixedNode: layoutProp.fixedNode, margin: layoutProp.margin,\n bounds: layoutProp.bounds, objects: [], root: layoutProp.root\n };\n this.doLayout(layout, nodes, nameTable, viewport);\n };\n RadialTree.prototype.doLayout = function (layout, nodes, nameTable, viewport) {\n var node;\n for (var i = 0; i < nodes.length; i++) {\n node = nodes[i];\n if (!node.excludeFromLayout) {\n layout.graphNodes[node.id] = this.setUpLayoutInfo(layout, node);\n if (!node.inEdges || !node.inEdges.length) {\n layout.firstLevelNodes.push(node);\n }\n }\n }\n if (layout.root && nameTable[layout.root]) {\n layout.centerNode = nameTable[layout.root];\n }\n else if (layout.firstLevelNodes.length) {\n layout.centerNode = layout.firstLevelNodes[0];\n layout.root = layout.centerNode.id;\n }\n if (layout.centerNode) {\n this.updateEdges(layout, layout.centerNode, 0, nameTable);\n this.depthFirstAllignment(layout, layout.centerNode, 0, 0);\n this.populateLevels(layout);\n this.transformToCircleLayout(layout);\n this.updateAnchor(layout, viewport);\n this.updateNodes(layout, layout.centerNode, nameTable);\n }\n };\n RadialTree.prototype.updateEdges = function (layout, node, depth, nameTable) {\n var nodeInfo = layout.graphNodes[node.id];\n layout.layoutNodes.push(nodeInfo);\n nodeInfo.level = depth;\n nodeInfo.visited = true;\n layout.maxLevel = Math.max(layout.maxLevel, depth);\n for (var j = 0; j < node.outEdges.length; j++) {\n var edge = nameTable[nameTable[node.outEdges[j]].targetID];\n if (!edge.excludeFromLayout && !edge.visited) {\n nodeInfo.children.push(edge);\n this.updateEdges(layout, edge, depth + 1, nameTable);\n }\n }\n };\n RadialTree.prototype.depthFirstAllignment = function (layout, node, x, y) {\n var newValue;\n var nodeInfo = layout.graphNodes[node.id];\n if (nodeInfo.children.length) {\n y += 300;\n for (var i = 0; i < nodeInfo.children.length; i++) {\n newValue = this.depthFirstAllignment(layout, nodeInfo.children[i], x, y);\n x = newValue.x;\n y = newValue.y;\n }\n nodeInfo.children = nodeInfo.children.sort(function (obj1, obj2) {\n return layout.graphNodes[obj1.id].x - layout.graphNodes[obj2.id].x;\n });\n var min = layout.graphNodes[nodeInfo.children[0].id].min;\n var max = layout.graphNodes[nodeInfo.children[nodeInfo.children.length - 1].id].max;\n nodeInfo.x = min + (max - min) / 2;\n x = max + layout.horizontalSpacing;\n nodeInfo.segmentOffset = max + layout.horizontalSpacing;\n nodeInfo.x -= nodeInfo.width / 2;\n nodeInfo.y -= nodeInfo.height / 2;\n nodeInfo.min = min;\n nodeInfo.max = max;\n if (nodeInfo.x < min && nodeInfo.visited) {\n nodeInfo.x = min;\n x = nodeInfo.x + nodeInfo.width / 2 - (max - min) / 2;\n nodeInfo.visited = false;\n for (var i = 0; i < nodeInfo.children.length; i++) {\n newValue = this.depthFirstAllignment(layout, nodeInfo.children[i], x, y);\n }\n nodeInfo.visited = true;\n x = nodeInfo.x + nodeInfo.width + layout.horizontalSpacing;\n }\n max = layout.graphNodes[nodeInfo.children[nodeInfo.children.length - 1].id].segmentOffset;\n x = x < max ? max : x;\n y -= 300;\n nodeInfo.y = y;\n }\n else {\n nodeInfo.x = x;\n nodeInfo.y = y;\n nodeInfo.min = x;\n nodeInfo.max = x + nodeInfo.width;\n x += nodeInfo.width + layout.horizontalSpacing;\n }\n return { x: x, y: y };\n };\n RadialTree.prototype.populateLevels = function (layout) {\n var stages = [];\n var min = Math.min.apply(Math, layout.layoutNodes.map(function (nodeInfo) { return nodeInfo.x; }));\n var max = Math.max.apply(Math, layout.layoutNodes.map(function (nodeInfo) {\n return nodeInfo.x + nodeInfo.width + layout.horizontalSpacing;\n }));\n var full = max - min;\n layout.levels = [];\n var _loop_1 = function (i) {\n stages = layout.layoutNodes.filter(function (nodeInfo) {\n if (nodeInfo.level === i) {\n return nodeInfo;\n }\n else {\n return null;\n }\n });\n var newlevel = {};\n stages = stages.sort(function (nodeInfo1, nodeInfo2) { return nodeInfo1.x - nodeInfo2.x; });\n newlevel.min = stages[0].x;\n newlevel.max = stages[stages.length - 1].x + stages[stages.length - 1].width + layout.horizontalSpacing;\n newlevel.actualCircumference = 0;\n newlevel.height = 0;\n for (var k = 0; k < stages.length; k++) {\n if (stages[k].height > newlevel.height) {\n newlevel.height = stages[k].height;\n }\n newlevel.actualCircumference += Math.max(stages[k].width, stages[k].height);\n if (k !== stages.length - 1) {\n newlevel.actualCircumference += layout.horizontalSpacing;\n }\n }\n newlevel.circumference = newlevel.max - newlevel.min;\n if (newlevel.actualCircumference < newlevel.circumference) {\n newlevel.circumference = (newlevel.circumference + newlevel.actualCircumference) / 2;\n }\n newlevel.radius = newlevel.circumference / (2 * Math.PI) + newlevel.height;\n newlevel.nodes = [];\n if (i > 1) {\n if (layout.levels[i - 1].radius + layout.levels[i - 1].height >= newlevel.radius) {\n newlevel.radius = layout.levels[i - 1].radius + layout.levels[i - 1].height;\n }\n }\n for (var j = 0; j < stages.length; j++) {\n stages[j].ratio = Math.abs(stages[j].x + stages[j].width / 2 - min) / full;\n newlevel.nodes.push(stages[j]);\n }\n layout.levels.push(newlevel);\n };\n for (var i = 0; i <= layout.maxLevel; i++) {\n _loop_1(i);\n }\n };\n RadialTree.prototype.transformToCircleLayout = function (layout) {\n var root = layout.graphNodes[layout.centerNode.id];\n root.x = 0;\n root.y = 0;\n for (var i = 1; i < layout.levels.length; i++) {\n for (var j = 0; j < layout.levels[i].nodes.length; j++) {\n var nodeInfo = layout.levels[i].nodes[j];\n nodeInfo.x = Math.cos(nodeInfo.ratio * 360 * Math.PI / 180) * (layout.levels[i].radius + layout.verticalSpacing * i);\n nodeInfo.y = Math.sin(nodeInfo.ratio * 360 * Math.PI / 180) * (layout.levels[i].radius + layout.verticalSpacing * i);\n layout.anchorX = Math.min(layout.anchorX, nodeInfo.x);\n layout.anchorY = Math.min(layout.anchorY, nodeInfo.y);\n }\n }\n };\n RadialTree.prototype.updateAnchor = function (layout, viewPort) {\n layout.anchorX = layout.centerNode.offsetX || viewPort.x / 2;\n layout.anchorY = layout.centerNode.offsetY || viewPort.y / 2;\n };\n RadialTree.prototype.updateNodes = function (layout, node, nameTable) {\n var nodeInfo = layout.graphNodes[node.id];\n var offsetX = nodeInfo.x + layout.anchorX;\n var offsetY = nodeInfo.y + layout.anchorY;\n node.offsetX += offsetX;\n node.offsetY += offsetY;\n for (var i = 0; i < nodeInfo.children.length; i++) {\n var childInfo = nodeInfo.children[i];\n this.updateNodes(layout, nameTable[childInfo.id], nameTable);\n }\n };\n RadialTree.prototype.setUpLayoutInfo = function (layout, item) {\n var info = {};\n info.name = item.id;\n info.x = 0;\n info.y = 0;\n info.min = 0;\n info.max = 0;\n info.width = item.actualSize.width;\n info.height = item.actualSize.height;\n info.children = [];\n info.level = 0;\n info.ratio = 0;\n info.visited = false;\n return info;\n };\n return RadialTree;\n}());\nexport { RadialTree };\n","/**\n * Connects diagram objects with layout algorithm\n */\nvar ComplexHierarchicalTree = /** @class */ (function () {\n /**\n * Constructor for the hierarchical tree layout module\n * @private\n */\n function ComplexHierarchicalTree() {\n //constructs the layout module\n }\n /**\n * To destroy the hierarchical tree module\n * @return {void}\n * @private\n */\n ComplexHierarchicalTree.prototype.destroy = function () {\n /**\n * Destroy method performed here\n */\n };\n /**\n * Get module name.\n */\n ComplexHierarchicalTree.prototype.getModuleName = function () {\n /**\n * Returns the module name of the layout\n */\n return 'ComplexHierarchicalTree';\n };\n ComplexHierarchicalTree.prototype.doLayout = function (nodes, nameTable, layout, viewPort) {\n new HierarchicalLayoutUtil().doLayout(nodes, nameTable, layout, viewPort);\n };\n return ComplexHierarchicalTree;\n}());\nexport { ComplexHierarchicalTree };\n/**\n * Utility that arranges the nodes in hierarchical structure\n */\nvar HierarchicalLayoutUtil = /** @class */ (function () {\n function HierarchicalLayoutUtil() {\n this.nameTable = {};\n this.crossReduction = new CrossReduction();\n }\n /**\n * Defines a vertex that is equivalent to a node object\n */\n HierarchicalLayoutUtil.prototype.createVertex = function (node, value, x, y, width, height) {\n var geometry = { x: x, y: y, width: width, height: height };\n var vertex = {\n value: value, geometry: geometry, name: value, vertex: true,\n inEdges: node.inEdges.slice(), outEdges: node.outEdges.slice()\n };\n return vertex;\n };\n /**\n * Initializes the edges collection of the vertices\n * @private\n */\n HierarchicalLayoutUtil.prototype.getEdges = function (node) {\n var edges = [];\n if (node) {\n for (var i = 0; node.inEdges.length > 0 && i < node.inEdges.length; i++) {\n edges.push(this.nameTable[node.inEdges[i]]);\n }\n for (var i = 0; node.outEdges.length > 0 && i < node.outEdges.length; i++) {\n edges.push(this.nameTable[node.outEdges[i]]);\n }\n }\n return edges;\n };\n /**\n * Finds the root nodes of the layout\n */\n HierarchicalLayoutUtil.prototype.findRoots = function (vertices) {\n var roots = [];\n var best = null;\n var maxDiff = -100000;\n for (var _i = 0, _a = Object.keys(vertices); _i < _a.length; _i++) {\n var i = _a[_i];\n var cell = vertices[i];\n var conns = this.getEdges(cell);\n var outEdges = 0;\n var inEdges = 0;\n for (var k = 0; k < conns.length; k++) {\n var src = this.getVisibleTerminal(conns[k], true);\n if (src.name === cell.name) {\n outEdges++;\n }\n else {\n inEdges++;\n }\n }\n if (inEdges === 0 && outEdges > 0) {\n roots.push(cell);\n }\n var diff = outEdges - inEdges;\n if (diff > maxDiff) {\n maxDiff = diff;\n best = cell;\n }\n }\n if (roots.length === 0 && best != null) {\n roots.push(best);\n }\n return roots;\n };\n /**\n * Returns the source/target vertex of the given connector\n * @private\n */\n HierarchicalLayoutUtil.prototype.getVisibleTerminal = function (edge, source) {\n var terminalCache = this.nameTable[edge.targetID];\n if (source) {\n terminalCache = this.nameTable[edge.sourceID];\n }\n for (var i = 0; i < this.vertices.length; i++) {\n if (this.vertices[i].name === terminalCache.id) {\n return this.vertices[i];\n }\n }\n return null;\n };\n /**\n * Traverses each sub tree, ensures there is no cycle in traversing\n * @private\n */\n HierarchicalLayoutUtil.prototype.traverse = function (vertex, directed, edge, currentComp, hierarchyVertices, filledVertices) {\n if (vertex != null) {\n var vertexID = vertex.name;\n if ((filledVertices == null ? true : filledVertices[vertexID] != null)) {\n if (currentComp[vertexID] == null) {\n currentComp[vertexID] = vertex;\n }\n if (filledVertices != null) {\n delete filledVertices[vertexID];\n }\n var edges = this.getEdges(vertex);\n var edgeIsSource = [];\n for (var i = 0; i < edges.length; i++) {\n edgeIsSource[i] = this.getVisibleTerminal(edges[i], true) === vertex;\n }\n for (var i = 0; i < edges.length; i++) {\n if (!directed || edgeIsSource[i]) {\n var next = this.getVisibleTerminal(edges[i], !edgeIsSource[i]);\n var netCount = 1;\n for (var j = 0; j < edges.length; j++) {\n if (j === i) {\n continue;\n }\n else {\n var isSource2 = edgeIsSource[j];\n var otherTerm = this.getVisibleTerminal(edges[j], !isSource2);\n if (otherTerm === next) {\n if (isSource2) {\n netCount++;\n }\n else {\n netCount--;\n }\n }\n }\n }\n if (netCount >= 0) {\n currentComp = this.traverse(next, directed, edges[i], currentComp, hierarchyVertices, filledVertices);\n }\n }\n }\n }\n else {\n if (currentComp[vertexID] == null) {\n // We've seen this vertex before, but not in the current component This component and the one it's in need to be merged\n for (var i = 0; i < hierarchyVertices.length; i++) {\n var comp = hierarchyVertices[i];\n if (comp[vertexID] != null) {\n for (var _i = 0, _a = Object.keys(comp); _i < _a.length; _i++) {\n var key = _a[_i];\n currentComp[key] = comp[key];\n }\n // Remove the current component from the hierarchy set\n hierarchyVertices.splice(i, 1);\n return currentComp;\n }\n }\n }\n }\n }\n return currentComp;\n };\n /**\n * Returns the bounds of the given vertices\n */\n HierarchicalLayoutUtil.prototype.getModelBounds = function (nodes) {\n nodes = nodes.slice();\n var rect = null;\n var rect1 = null;\n for (var i = 0; i < nodes.length; i++) {\n rect = nodes[i].geometry;\n if (rect1) {\n var right = Math.max(rect1.x + rect1.width, rect.x + rect.width);\n var bottom = Math.max(rect1.y + rect1.height, rect.y + rect.height);\n rect1.x = Math.min(rect1.x, rect.x);\n rect1.y = Math.min(rect1.y, rect.y);\n rect1.width = right - rect1.x;\n rect1.height = bottom - rect1.y;\n }\n else {\n rect1 = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };\n }\n }\n return rect1;\n };\n /**\n * Initializes the layouting process\n * @private\n */\n HierarchicalLayoutUtil.prototype.doLayout = function (nodes, nameTable, layoutProp, viewPort) {\n this.nameTable = nameTable;\n var layout = {\n horizontalSpacing: layoutProp.horizontalSpacing, verticalSpacing: layoutProp.verticalSpacing,\n orientation: layoutProp.orientation, marginX: layoutProp.margin.left, marginY: layoutProp.margin.top\n };\n if (layout.orientation === 'BottomToTop') {\n layout.marginY = -layoutProp.margin.top;\n }\n else if (layout.orientation === 'RightToLeft') {\n layout.marginX = -layoutProp.margin.left;\n }\n this.vertices = [];\n var filledVertexSet = {};\n for (var i = 0; i < nodes.length; i++) {\n var node = this.createVertex(nodes[i], nodes[i].id, 0, 0, nodes[i].actualSize.width, nodes[i].actualSize.height);\n this.vertices.push(node);\n filledVertexSet[node.name] = node;\n }\n var hierarchyVertices = [];\n var candidateRoots;\n candidateRoots = this.findRoots(filledVertexSet);\n for (var i = 0; i < candidateRoots.length; i++) {\n var vertexSet = {};\n hierarchyVertices.push(vertexSet);\n this.traverse(candidateRoots[i], true, null, vertexSet, hierarchyVertices, filledVertexSet);\n }\n var limit = { marginX: 0, marginY: 0 };\n for (var i = 0; i < hierarchyVertices.length; i++) {\n var vertexSet = hierarchyVertices[i];\n var tmp = [];\n for (var _i = 0, _a = Object.keys(vertexSet); _i < _a.length; _i++) {\n var key = _a[_i];\n tmp.push(vertexSet[key]);\n }\n var model = new MultiParentModel(this, tmp, candidateRoots, layout);\n this.cycleStage(model);\n this.layeringStage(model);\n this.crossingStage(model);\n limit = this.placementStage(model, limit.marginX, limit.marginY);\n }\n var modelBounds = this.getModelBounds(this.vertices);\n var trnsX = (viewPort.x - modelBounds.width) / 2;\n for (var i = 0; i < this.vertices.length; i++) {\n var clnode = this.vertices[i];\n if (clnode) {\n var dnode = this.nameTable[clnode.name];\n dnode.offsetX = 0;\n dnode.offsetY = 0;\n //initialize layout\n var dx = (clnode.geometry.x - (dnode.offsetX - (dnode.actualSize.width / 2))) + layout.marginX;\n var dy = (clnode.geometry.y - (dnode.offsetY - (dnode.actualSize.height / 2))) + layout.marginY;\n var x = dx;\n var y = dy;\n if (layout.orientation === 'BottomToTop') {\n y = modelBounds.height - dy;\n }\n else if (layout.orientation === 'RightToLeft') {\n x = modelBounds.width - dx;\n }\n x += trnsX;\n dnode.offsetX += x - dnode.offsetX;\n dnode.offsetY += y - dnode.offsetY;\n }\n }\n };\n /**\n * Handles positioning the nodes\n */\n HierarchicalLayoutUtil.prototype.placementStage = function (model, marginX, marginY) {\n var placementStage = this.coordinateAssignment(marginX, marginY, parent, model);\n placementStage.model = model;\n placementStage.widestRankValue = null;\n this.placementStageExecute(placementStage);\n return {\n marginX: placementStage.marginX + model.layout.horizontalSpacing,\n marginY: placementStage.marginY + model.layout.verticalSpacing\n };\n };\n /**\n * Initializes the layout properties for positioning\n */\n HierarchicalLayoutUtil.prototype.coordinateAssignment = function (marginX, marginY, parent, model) {\n var plalementChange = {};\n if (model.layout.orientation === 'TopToBottom' || model.layout.orientation === 'BottomToTop') {\n plalementChange.horizontalSpacing = model.layout.horizontalSpacing;\n plalementChange.verticalSpacing = model.layout.verticalSpacing;\n }\n else {\n plalementChange.horizontalSpacing = model.layout.verticalSpacing;\n plalementChange.verticalSpacing = model.layout.horizontalSpacing;\n }\n plalementChange.orientation = 'north';\n //Removed the conditions here. So check here in case of any issue\n plalementChange.marginX = plalementChange.marginX = marginX;\n plalementChange.marginY = plalementChange.marginY = marginY;\n return plalementChange;\n };\n /**\n * Calculate the largest size of the node either height or width depends upon the layoutorientation\n */\n HierarchicalLayoutUtil.prototype.calculateWidestRank = function (plalementChange, graph, model) {\n var isHorizontal = false;\n if (plalementChange.model.layout.orientation === 'LeftToRight' || plalementChange.model.layout.orientation === 'RightToLeft') {\n isHorizontal = true;\n }\n var offset = -plalementChange.verticalSpacing;\n var lastRankMaxCellSize = 0.0;\n plalementChange.rankSizes = [];\n plalementChange.rankOffset = [];\n for (var rankValue = model.maxRank; rankValue >= 0; rankValue--) {\n var maxCellSize = 0.0;\n var rank = model.ranks[rankValue];\n var localOffset = isHorizontal ? plalementChange.marginY : plalementChange.marginX;\n for (var i = 0; i < rank.length; i++) {\n var node = rank[i];\n if (this.crossReduction.isVertex(node)) {\n var vertex = node;\n if (vertex.cell && (vertex.cell.inEdges || vertex.cell.outEdges)) {\n var obj = this.nameTable[vertex.cell.name];\n vertex.width = obj.actualSize.width;\n vertex.height = obj.actualSize.height;\n maxCellSize = Math.max(maxCellSize, (isHorizontal ? vertex.width : vertex.height));\n }\n }\n else {\n if (node) {\n var edge = node;\n var numEdges = 1;\n if (edge.edges != null) {\n numEdges = edge.edges.length;\n }\n node.width = (numEdges - 1) * 10;\n }\n }\n if (isHorizontal) {\n if (!node.height) {\n node.height = 0;\n }\n }\n // Set the initial x-value as being the best result so far\n localOffset += (isHorizontal ? node.height : node.width) / 2.0;\n this.setXY(node, rankValue, localOffset, isHorizontal ? true : false);\n this.setTempVariable(node, rankValue, localOffset);\n localOffset += ((isHorizontal ? node.height : node.width) / 2.0) + plalementChange.horizontalSpacing;\n if (localOffset > plalementChange.widestRankValue) {\n plalementChange.widestRankValue = localOffset;\n plalementChange.widestRank = rankValue;\n }\n plalementChange.rankSizes[rankValue] = localOffset;\n }\n plalementChange.rankOffset[rankValue] = offset;\n var distanceToNextRank = maxCellSize / 2.0 + lastRankMaxCellSize / 2.0 + plalementChange.verticalSpacing;\n lastRankMaxCellSize = maxCellSize;\n if (plalementChange.orientation === 'north' || plalementChange.orientation === 'west') {\n offset += distanceToNextRank;\n }\n else {\n offset -= distanceToNextRank;\n }\n for (var i = 0; i < rank.length; i++) {\n var cell = rank[i];\n this.setXY(cell, rankValue, offset, isHorizontal ? false : true);\n }\n }\n };\n /**\n * Sets the temp position of the node on the layer\n * @private\n */\n HierarchicalLayoutUtil.prototype.setTempVariable = function (node, layer, value) {\n if (this.crossReduction.isVertex(node)) {\n node.temp[0] = value;\n }\n else {\n node.temp[layer - node.minRank - 1] = value;\n }\n };\n /**\n * Sets the position of the vertex\n * @private\n */\n HierarchicalLayoutUtil.prototype.setXY = function (node, layer, value, isY) {\n if (node && node.cell) {\n if (node.cell.inEdges || node.cell.outEdges) {\n if (isY) {\n node.y[0] = value;\n }\n else {\n node.x[0] = value;\n }\n }\n else {\n if (isY) {\n node.y[layer - node.minRank - 1] = value;\n }\n else {\n node.x[layer - node.minRank - 1] = value;\n }\n }\n }\n };\n /**\n * Sets geometry position of the layout node on the layout model\n */\n HierarchicalLayoutUtil.prototype.rankCoordinates = function (stage, rankValue, graph, model) {\n var isHorizontal = false;\n if (stage.model.layout.orientation === 'LeftToRight' || stage.model.layout.orientation === 'RightToLeft') {\n isHorizontal = true;\n }\n var rank = model.ranks[rankValue];\n var maxOffset = 0.0;\n var localOffset = (isHorizontal ? stage.marginY : stage.marginX) + (stage.widestRankValue - stage.rankSizes[rankValue]) / 2;\n for (var i = 0; i < rank.length; i++) {\n var node = rank[i];\n if (this.crossReduction.isVertex(node)) {\n var obj = this.nameTable[node.cell.name];\n node.width = obj.actualSize.width;\n node.height = obj.actualSize.height;\n maxOffset = Math.max(maxOffset, node.height);\n }\n else {\n var edge = node;\n var numEdges = 1;\n if (edge.edges != null) {\n numEdges = edge.edges.length;\n }\n if (isHorizontal) {\n node.height = (numEdges - 1) * 10;\n }\n else {\n node.width = (numEdges - 1) * 10;\n }\n }\n var size = (isHorizontal ? node.height : node.width) / 2.0;\n localOffset += size;\n this.setXY(node, rankValue, localOffset, isHorizontal ? true : false);\n this.setTempVariable(node, rankValue, localOffset);\n localOffset += (size + stage.horizontalSpacing);\n }\n };\n /**\n * sets the layout in an initial positioning.it will arange all the ranks as much as possible\n */\n HierarchicalLayoutUtil.prototype.initialCoords = function (plalementChange, facade, model) {\n this.calculateWidestRank(plalementChange, facade, model);\n // Reverse sweep direction each time from widest rank \n for (var i = plalementChange.widestRank; i >= 0; i--) {\n if (i < model.maxRank) {\n this.rankCoordinates(plalementChange, i, facade, model);\n }\n }\n for (var i = plalementChange.widestRank + 1; i <= model.maxRank; i++) {\n if (i > 0) {\n this.rankCoordinates(plalementChange, i, facade, model);\n }\n }\n };\n /**\n * Checks whether the given node is an ancestor\n * @private\n */\n HierarchicalLayoutUtil.prototype.isAncestor = function (node, otherNode) {\n // Firstly, the hash code of this node needs to be shorter than the other node\n if (otherNode != null && node.hashCode != null && otherNode.hashCode != null\n && node.hashCode.length < otherNode.hashCode.length) {\n if (node.hashCode === otherNode.hashCode) {\n return true;\n }\n if (node.hashCode == null || node.hashCode == null) {\n return false;\n }\n for (var i = 0; i < node.hashCode.length; i++) {\n if (node.hashCode[i] !== otherNode.hashCode[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n };\n /**\n * initializes the sorter object\n */\n HierarchicalLayoutUtil.prototype.weightedCellSorter = function (cell, weightedValue) {\n var weightedCellSorter = {};\n weightedCellSorter.cell = cell ? cell : null;\n weightedCellSorter.weightedValue = weightedValue ? weightedValue : 0;\n weightedCellSorter.visited = false;\n weightedCellSorter.rankIndex = null;\n return weightedCellSorter;\n };\n /**\n * Performs one node positioning in both directions\n */\n HierarchicalLayoutUtil.prototype.minNode = function (plalementChange, model) {\n var nodeList = [];\n var map = { map: {} };\n var rank = [];\n for (var i = 0; i <= model.maxRank; i++) {\n rank[i] = model.ranks[i];\n for (var j = 0; j < rank[i].length; j++) {\n var node = rank[i][j];\n var nodeWrapper = this.weightedCellSorter(node, i);\n nodeWrapper.rankIndex = j;\n nodeWrapper.visited = true;\n nodeList.push(nodeWrapper);\n model.setDictionaryForSorter(map, node, nodeWrapper, true);\n }\n }\n var maxTries = nodeList.length * 10;\n var count = 0;\n var tolerance = 1;\n while (nodeList.length > 0 && count <= maxTries) {\n var cellWrapper = nodeList.shift();\n var cell = cellWrapper.cell;\n var rankValue = cellWrapper.weightedValue;\n var rankIndex = cellWrapper.rankIndex;\n var nextLayerConnectedCells = this.crossReduction.getConnectedCellsOnLayer(cell, rankValue);\n var previousLayerConnectedCells = this.crossReduction.getConnectedCellsOnLayer(cell, rankValue, true);\n var nextConnectedCount = nextLayerConnectedCells.length;\n var prevConnectedCount = previousLayerConnectedCells.length;\n var medianNextLevel = this.medianXValue(plalementChange, nextLayerConnectedCells, rankValue + 1);\n var medianPreviousLevel = this.medianXValue(plalementChange, previousLayerConnectedCells, rankValue - 1);\n var numConnectedNeighbours = nextConnectedCount + prevConnectedCount;\n var currentPosition = this.crossReduction.getTempVariable(cell, rankValue);\n var cellMedian = currentPosition;\n if (numConnectedNeighbours > 0) {\n cellMedian = (medianNextLevel * nextConnectedCount + medianPreviousLevel * prevConnectedCount) / numConnectedNeighbours;\n }\n var positionChanged = false;\n var tempValue = undefined;\n if (cellMedian < currentPosition - tolerance) {\n if (rankIndex === 0) {\n tempValue = cellMedian;\n positionChanged = true;\n }\n else {\n var leftCell = rank[rankValue][rankIndex - 1];\n var leftLimit = this.crossReduction.getTempVariable(leftCell, rankValue);\n leftLimit = leftLimit + leftCell.width / 2 + plalementChange.intraCellSpacing + cell.width / 2;\n if (leftLimit < cellMedian) {\n tempValue = cellMedian;\n positionChanged = true;\n }\n else if (leftLimit < this.crossReduction.getTempVariable(cell, rankValue) - tolerance) {\n tempValue = leftLimit;\n positionChanged = true;\n }\n }\n }\n else if (cellMedian > currentPosition + tolerance) {\n var rankSize = rank[rankValue].length;\n if (rankIndex === rankSize - 1) {\n tempValue = cellMedian;\n positionChanged = true;\n }\n else {\n var rightCell = rank[rankValue][rankIndex + 1];\n var rightLimit = this.crossReduction.getTempVariable(rightCell, rankValue);\n rightLimit = rightLimit - rightCell.width / 2 - plalementChange.intraCellSpacing - cell.width / 2;\n if (rightLimit > cellMedian) {\n tempValue = cellMedian;\n positionChanged = true;\n }\n else if (rightLimit > this.crossReduction.getTempVariable(cell, rankValue) + tolerance) {\n tempValue = rightLimit;\n positionChanged = true;\n }\n }\n }\n if (positionChanged) {\n this.setTempVariable(cell, rankValue, tempValue);\n // Add connected nodes to map and list\n this.updateNodeList(nodeList, map, nextLayerConnectedCells, model);\n this.updateNodeList(nodeList, map, previousLayerConnectedCells, model);\n }\n if (this.crossReduction.isVertex(cellWrapper.cell)) {\n cellWrapper.visited = false;\n }\n count++;\n }\n };\n /**\n * Updates the ndoes collection\n */\n HierarchicalLayoutUtil.prototype.updateNodeList = function (nodeList, map, collection, model) {\n for (var i = 0; i < collection.length; i++) {\n var connectedCell = collection[i];\n var connectedCellWrapper = model.getDictionaryForSorter(map, connectedCell);\n if (connectedCellWrapper != null) {\n if (connectedCellWrapper.visited === false) {\n connectedCellWrapper.visited = true;\n nodeList.push(connectedCellWrapper);\n }\n }\n }\n };\n /**\n * Calculates the node position of the connected cell on the specified rank\n */\n HierarchicalLayoutUtil.prototype.medianXValue = function (plalementChange, connectedCells, rankValue) {\n if (connectedCells.length === 0) {\n return 0;\n }\n var medianValues = [];\n for (var i = 0; i < connectedCells.length; i++) {\n medianValues[i] = this.crossReduction.getTempVariable(connectedCells[i], rankValue);\n }\n medianValues.sort(function (a, b) {\n return a - b;\n });\n if (connectedCells.length % 2 === 1) {\n return medianValues[Math.floor(connectedCells.length / 2)];\n }\n else {\n var medianPoint = connectedCells.length / 2;\n var leftMedian = medianValues[medianPoint - 1];\n var rightMedian = medianValues[medianPoint];\n return ((leftMedian + rightMedian) / 2);\n }\n };\n /**\n * Updates the geometry of the vertices\n */\n HierarchicalLayoutUtil.prototype.placementStageExecute = function (plalementChange) {\n var isHorizontal = false;\n if (plalementChange.model.layout.orientation === 'LeftToRight' || plalementChange.model.layout.orientation === 'RightToLeft') {\n isHorizontal = true;\n }\n plalementChange.jettyPositions = {};\n var model = plalementChange.model;\n isHorizontal ? plalementChange.currentYDelta = 0.0 : plalementChange.currentXDelta = 0.0;\n this.initialCoords(plalementChange, { model: model }, model);\n this.minNode(plalementChange, model);\n var bestOffsetDelta = 100000000.0;\n if (!plalementChange.maxIterations) {\n plalementChange.maxIterations = 8;\n }\n for (var i = 0; i < plalementChange.maxIterations; i++) {\n // if the total offset is less for the current positioning, \n //there are less heavily angled edges and so the current positioning is used\n if ((isHorizontal ? plalementChange.currentYDelta : plalementChange.currentXDelta) < bestOffsetDelta) {\n for (var j = 0; j < model.ranks.length; j++) {\n var rank = model.ranks[j];\n for (var k = 0; k < rank.length; k++) {\n var cell = rank[k];\n this.setXY(cell, j, this.crossReduction.getTempVariable(cell, j), isHorizontal ? true : false);\n }\n }\n bestOffsetDelta = isHorizontal ? plalementChange.currentYDelta : plalementChange.currentXDelta;\n }\n isHorizontal ? plalementChange.currentYDelta = 0 : plalementChange.currentXDelta = 0;\n }\n this.setCellLocations(plalementChange, model);\n };\n /**\n * sets the cell position in the after the layout operation\n */\n HierarchicalLayoutUtil.prototype.setCellLocations = function (plalementChange, model) {\n var vertices = this.getValues(model.vertexMapper);\n for (var i = 0; i < vertices.length; i++) {\n this.setVertexLocation(plalementChange, vertices[i]);\n }\n };\n /**\n * used to specify the geometrical position of the layout model cell\n */\n HierarchicalLayoutUtil.prototype.garphModelsetVertexLocation = function (plalementChange, cell, x, y) {\n var model = plalementChange.model;\n var geometry = cell.geometry;\n var result = null;\n if (geometry != null) {\n result = { x: x, y: y, width: geometry.width, height: geometry.height };\n if (geometry.x !== x || geometry.y !== y) {\n cell.geometry = result;\n }\n }\n return result;\n };\n /**\n * set the position of the specified node\n */\n HierarchicalLayoutUtil.prototype.setVertexLocation = function (plalementChange, cell) {\n var isHorizontal = false;\n if (plalementChange.model.layout.orientation === 'LeftToRight' || plalementChange.model.layout.orientation === 'RightToLeft') {\n isHorizontal = true;\n }\n var realCell = cell.cell;\n var positionX = cell.x[0] - cell.width / 2;\n var positionY = cell.y[0] - cell.height / 2;\n this.garphModelsetVertexLocation(plalementChange, realCell, positionX, positionY);\n if (isHorizontal) {\n if (!plalementChange.marginY) {\n plalementChange.marginY = 0;\n }\n plalementChange.marginY = Math.max(plalementChange.marginY, positionY + cell.height);\n }\n else {\n if (!plalementChange.marginX) {\n plalementChange.marginX = 0;\n }\n plalementChange.marginX = Math.max(plalementChange.marginX, positionX + cell.width);\n }\n };\n /**\n * get the specific value from the key value pair\n */\n HierarchicalLayoutUtil.prototype.getValues = function (mapper) {\n var list = [];\n if (mapper.map) {\n for (var _i = 0, _a = Object.keys(mapper.map); _i < _a.length; _i++) {\n var key = _a[_i];\n list.push(mapper.map[key]);\n }\n }\n return list;\n };\n /**\n * Checks and reduces the crosses in between line segments\n */\n HierarchicalLayoutUtil.prototype.crossingStage = function (model) {\n this.crossReduction.execute(model);\n };\n /**\n * Initializes the ranks of the vertices\n */\n HierarchicalLayoutUtil.prototype.layeringStage = function (model) {\n this.initialRank(model);\n this.fixRanks(model);\n };\n /**\n * determine the initial rank for the each vertex on the relevent direction\n */\n HierarchicalLayoutUtil.prototype.initialRank = function (model) {\n var startNodes = model.startNodes;\n var internalNodes = model.getDictionaryValues(model.vertexMapper);\n var startNodesCopy = startNodes.slice();\n while (startNodes.length > 0) {\n var internalNode = startNodes[0];\n var layerDeterminingEdges = internalNode.connectsAsTarget;\n var edgesToBeMarked = internalNode.connectsAsSource;\n var allEdgesScanned = true;\n var minimumLayer = 100000000;\n for (var i = 0; i < layerDeterminingEdges.length; i++) {\n var internalEdge = layerDeterminingEdges[i];\n if (internalEdge.temp[0] === 5270620) {\n // This edge has been scanned, get the layer of the node on the other end\n var otherNode = internalEdge.source;\n minimumLayer = Math.min(minimumLayer, otherNode.temp[0] - 1);\n }\n else {\n allEdgesScanned = false;\n break;\n }\n }\n // If all edge have been scanned, assign the layer, mark all edges in the other direction and remove from the nodes list\n if (allEdgesScanned) {\n internalNode.temp[0] = minimumLayer;\n if (!model.maxRank) {\n model.maxRank = 100000000;\n }\n model.maxRank = Math.min(model.maxRank, minimumLayer);\n if (edgesToBeMarked != null) {\n for (var i = 0; i < edgesToBeMarked.length; i++) {\n var internalEdge = edgesToBeMarked[i];\n internalEdge.temp[0] = 5270620;\n // Add node on other end of edge to LinkedList of nodes to be analysed\n var otherNode = internalEdge.target;\n // Only add node if it hasn't been assigned a layer\n if (otherNode.temp[0] === -1) {\n startNodes.push(otherNode);\n // Mark this other node as neither being unassigned nor assigned \n //so it isn't added to this list again, but it's layer isn't used in any calculation.\n otherNode.temp[0] = -2;\n }\n }\n }\n startNodes.shift();\n }\n else {\n // Not all the edges have been scanned, get to the back of the class and put the dunces cap on\n var removedCell = startNodes.shift();\n startNodes.push(internalNode);\n if (removedCell === internalNode && startNodes.length === 1) {\n // This is an error condition, we can't get out of this loop. \n //It could happen for more than one node but that's a lot harder to detect. Log the error\n break;\n }\n }\n }\n for (var i = 0; i < internalNodes.length; i++) {\n internalNodes[i].temp[0] -= model.maxRank;\n }\n for (var i = 0; i < startNodesCopy.length; i++) {\n var internalNode = startNodesCopy[i];\n var currentMaxLayer = 0;\n var layerDeterminingEdges = internalNode.connectsAsSource;\n for (var j = 0; j < layerDeterminingEdges.length; j++) {\n var internalEdge = layerDeterminingEdges[j];\n var otherNode = internalEdge.target;\n internalNode.temp[0] = Math.max(currentMaxLayer, otherNode.temp[0] + 1);\n currentMaxLayer = internalNode.temp[0];\n }\n }\n model.maxRank = 100000000 - model.maxRank;\n };\n /**\n * used to set the optimum value of each vertex on the layout\n */\n HierarchicalLayoutUtil.prototype.fixRanks = function (model) {\n model.fixRanks();\n };\n /**\n * used to determine any cyclic stage have been created on the layout model\n */\n HierarchicalLayoutUtil.prototype.cycleStage = function (model) {\n var seenNodes = {};\n model.startNodes = [];\n var unseenNodesArray = model.getDictionaryValues(model.vertexMapper);\n var unseenNodes = [];\n for (var i = 0; i < unseenNodesArray.length; i++) {\n unseenNodesArray[i].temp[0] = -1;\n unseenNodes[unseenNodesArray[i].id] = unseenNodesArray[i];\n }\n var rootsArray = null;\n if (model.roots != null) {\n var modelRoots = model.roots;\n rootsArray = [];\n for (var i = 0; i < modelRoots.length; i++) {\n rootsArray[i] = model.getDictionary(model.vertexMapper, modelRoots[i]);\n if (rootsArray[i] != null) {\n model.startNodes.push(rootsArray[i]);\n }\n }\n }\n model.visit('removeParentConnection', rootsArray, true, null, { seenNodes: seenNodes, unseenNodes: unseenNodes });\n var seenNodesCopy = model.clone(seenNodes, null, true);\n model.visit('removeNodeConnection', unseenNodes, true, seenNodesCopy, { seenNodes: seenNodes, unseenNodes: unseenNodes });\n };\n /**\n * removes the edge from the given collection\n * @private\n */\n HierarchicalLayoutUtil.prototype.remove = function (obj, array) {\n var index = array.indexOf(obj);\n if (index !== -1) {\n array.splice(index, 1);\n }\n return obj;\n };\n /**\n * Inverts the source and target of an edge\n * @private\n */\n HierarchicalLayoutUtil.prototype.invert = function (connectingEdge, layer) {\n var temp = connectingEdge.source;\n connectingEdge.source = connectingEdge.target;\n connectingEdge.target = temp;\n connectingEdge.isReversed = !connectingEdge.isReversed;\n };\n /**\n * used to get the edges between the given source and target\n * @private\n */\n HierarchicalLayoutUtil.prototype.getEdgesBetween = function (source, target, directed) {\n directed = (directed != null) ? directed : false;\n var edges = this.getEdges(source);\n var result = [];\n for (var i = 0; i < edges.length; i++) {\n var src = this.getVisibleTerminal(edges[i], true);\n var trg = this.getVisibleTerminal(edges[i], false);\n if ((src === source && trg === target) || (!directed && src === target && trg === source)) {\n result.push(edges[i]);\n }\n }\n return result;\n };\n return HierarchicalLayoutUtil;\n}());\n/**\n * Handles position the objects in a hierarchical tree structure\n */\nvar MultiParentModel = /** @class */ (function () {\n function MultiParentModel(layout, vertices, roots, dlayout) {\n this.multiObjectIdentityCounter = 0;\n //used to count the no of times the parent have been used\n this.dfsCount = 0;\n this.hierarchicalUtil = new HierarchicalLayoutUtil();\n this.roots = roots;\n this.vertexMapper = { map: {} };\n var internalVertices = [];\n this.layout = dlayout;\n this.maxRank = 100000000;\n this.hierarchicalLayout = layout;\n this.createInternalCells(layout, vertices, internalVertices);\n for (var i = 0; i < vertices.length; i++) {\n var edges = internalVertices[i].connectsAsSource;\n for (var j = 0; j < edges.length; j++) {\n var internalEdge = edges[j];\n var realEdges = internalEdge.edges;\n if (realEdges != null && realEdges.length > 0) {\n var realEdge = realEdges[0];\n var targetCell = layout.getVisibleTerminal(realEdge, false);\n var internalTargetCell = this.getDictionary(this.vertexMapper, targetCell);\n if (internalVertices[i] === internalTargetCell) {\n targetCell = layout.getVisibleTerminal(realEdge, true);\n internalTargetCell = this.getDictionary(this.vertexMapper, targetCell);\n }\n if (internalTargetCell != null && internalVertices[i] !== internalTargetCell) {\n internalEdge.target = internalTargetCell;\n if (internalTargetCell.connectsAsTarget.length === 0) {\n internalTargetCell.connectsAsTarget = [];\n }\n if (internalTargetCell.connectsAsTarget.indexOf(internalEdge) < 0) {\n internalTargetCell.connectsAsTarget.push(internalEdge);\n }\n }\n }\n }\n internalVertices[i].temp[0] = 1;\n }\n }\n /**\n * used to create the duplicate of the edges on the layout model\n */\n MultiParentModel.prototype.createInternalCells = function (layout, vertices, internalVertices) {\n for (var i = 0; i < vertices.length; i++) {\n internalVertices[i] = {\n x: [], y: [], temp: [], cell: vertices[i],\n id: vertices[i].name, connectsAsTarget: [], connectsAsSource: []\n };\n this.setDictionary(this.vertexMapper, vertices[i], internalVertices[i]);\n var conns = layout.getEdges(vertices[i]);\n internalVertices[i].connectsAsSource = [];\n for (var j = 0; j < conns.length; j++) {\n var cell = layout.getVisibleTerminal(conns[j], false);\n if (cell !== vertices[i]) {\n var undirectedEdges = layout.getEdgesBetween(vertices[i], cell, false);\n var directedEdges = layout.getEdgesBetween(vertices[i], cell, true);\n if (undirectedEdges != null && undirectedEdges.length > 0 && directedEdges.length * 2 >= undirectedEdges.length) {\n var internalEdge = { x: [], y: [], temp: [], edges: undirectedEdges, ids: [] };\n for (var m = 0; m < undirectedEdges.length; m++) {\n internalEdge.ids.push(undirectedEdges[m].id);\n }\n internalEdge.source = internalVertices[i];\n if (!internalVertices[i].connectsAsSource) {\n internalVertices[i].connectsAsSource = [];\n }\n if (internalVertices[i].connectsAsSource.indexOf(internalEdge) < 0) {\n internalVertices[i].connectsAsSource.push(internalEdge);\n }\n }\n }\n }\n internalVertices[i].temp[0] = 0;\n }\n };\n /**\n * used to set the optimum value of each vertex on the layout\n * @private\n */\n MultiParentModel.prototype.fixRanks = function () {\n var rankList = [];\n this.ranks = [];\n for (var i = 0; i < this.maxRank + 1; i++) {\n rankList[i] = [];\n this.ranks[i] = rankList[i];\n }\n var rootsArray = null;\n if (this.roots != null) {\n var oldRootsArray = this.roots;\n rootsArray = [];\n for (var i = 0; i < oldRootsArray.length; i++) {\n var cell = oldRootsArray[i];\n var internalNode = this.getDictionary(this.vertexMapper, cell);\n rootsArray[i] = internalNode;\n }\n }\n this.visit('updateMinMaxRank', rootsArray, false, null, { seenNodes: null, unseenNodes: null, rankList: rankList });\n };\n /**\n * Updates the min/max rank of the layer\n */\n MultiParentModel.prototype.updateMinMaxRank = function (layer, seen, data) {\n var seenNodes = data.seenNodes;\n var unseenNodes = data.unseenNodes;\n var parent = data.parent;\n var node = data.root;\n var edge = data.edge;\n var rankList = data.rankList;\n if (!node.maxRank && node.maxRank !== 0) {\n node.maxRank = -1;\n }\n if (!node.minRank && node.minRank !== 0) {\n node.minRank = -1;\n }\n if (seen === 0 && node.maxRank < 0 && node.minRank < 0) {\n rankList[node.temp[0]].push(node);\n node.maxRank = node.temp[0];\n node.minRank = node.temp[0];\n node.temp[0] = rankList[node.maxRank].length - 1;\n }\n if (parent != null && edge != null) {\n var parentToCellRankDifference = parent.maxRank - node.maxRank;\n if (parentToCellRankDifference > 1) {\n edge.maxRank = parent.maxRank;\n edge.minRank = node.maxRank;\n edge.temp = [];\n edge.x = [];\n edge.y = [];\n for (var i = edge.minRank + 1; i < edge.maxRank; i++) {\n rankList[i].push(edge);\n this.hierarchicalUtil.setTempVariable(edge, i, rankList[i].length - 1);\n }\n }\n }\n };\n /**\n * used to store the value of th given key on the object\n */\n MultiParentModel.prototype.setDictionary = function (dic, key, value) {\n var id = key.name;\n if (!id) {\n // id = this._getDictionary(dic, key);\n }\n var previous = dic.map[id];\n dic.map[id] = value;\n return previous;\n };\n /**\n * used to store the value of th given key on the object\n * @private\n */\n MultiParentModel.prototype.setDictionaryForSorter = function (dic, key, value, flag) {\n var id = key.id;\n if (!id) {\n //id = this._getDictionaryForSorter(dic, key);\n }\n var previous = dic.map[id];\n dic.map[id] = value;\n return previous;\n };\n /**\n * used to get the value of the given key\n * @private\n */\n MultiParentModel.prototype.getDictionary = function (dic, key) {\n if (!this.multiObjectIdentityCounter && this.multiObjectIdentityCounter !== 0) {\n this.multiObjectIdentityCounter = 0;\n }\n var id = key.name;\n if (!id) {\n if (!key.layoutObjectId) {\n key.layoutObjectId = 'graphHierarchyNode#' + this.multiObjectIdentityCounter++;\n return key.layoutObjectId;\n }\n else {\n return dic.map[key.layoutObjectId];\n }\n }\n return dic.map[id];\n };\n /**\n * used to get the value of the given key\n * @private\n */\n MultiParentModel.prototype.getDictionaryForSorter = function (dic, key) {\n if (!this.multiObjectIdentityCounter && this.multiObjectIdentityCounter !== 0) {\n this.multiObjectIdentityCounter = 0;\n }\n var id = key.id;\n if (!id) {\n if (!key.layoutObjectId) {\n key.layoutObjectId = 'graphHierarchyNode#' + this.multiObjectIdentityCounter++;\n return key.layoutObjectId;\n }\n else {\n return dic.map[key.layoutObjectId];\n }\n }\n return dic.map[id];\n };\n /**\n * used to get all the values of the dictionary object\n * @private\n */\n MultiParentModel.prototype.getDictionaryValues = function (dic) {\n var result = [];\n for (var _i = 0, _a = Object.keys(dic.map); _i < _a.length; _i++) {\n var key = _a[_i];\n result.push(dic.map[key]);\n }\n return result;\n };\n /**\n * used to visit all the entries on the given dictionary with given function\n * @private\n */\n MultiParentModel.prototype.visit = function (visitor, dfsRoots, trackAncestors, seenNodes, data) {\n var seenNodes1 = data.seenNodes;\n var unseenNodes1 = data.unseenNodes;\n var rankList = data.rankList;\n // Run depth first search through on all roots\n if (dfsRoots != null) {\n for (var i = 0; i < dfsRoots.length; i++) {\n var internalNode = dfsRoots[i];\n if (internalNode != null) {\n if (seenNodes == null) {\n seenNodes = new Object();\n }\n data.parent = null;\n data.root = internalNode;\n data.edge = null;\n if (trackAncestors) {\n // Set up hash code for root\n internalNode.hashCode = [];\n internalNode.hashCode[0] = this.dfsCount;\n internalNode.hashCode[1] = i;\n this.extendedDfs(visitor, seenNodes, i, 0, data);\n }\n else {\n this.depthFirstSearch(visitor, seenNodes, 0, data);\n }\n }\n }\n this.dfsCount++;\n }\n };\n /**\n * used to perform the depth fisrt search on the layout model\n */\n MultiParentModel.prototype.depthFirstSearch = function (visitor, seen, layer, data) {\n var seenNodes1 = data.seenNodes;\n var unseenNodes1 = data.unseenNodes;\n var rankList = data.rankList;\n var parent = data.parent;\n var root = data.root;\n var edge = data.edge;\n if (root != null) {\n var rootId = root.id;\n if (seen[rootId] == null) {\n seen[rootId] = root;\n this.updateConnectionRank(visitor, layer, 0, data);\n // Copy the connects as source list so that visitors can change the original for edge direction inversions\n var outgoingEdges = root.connectsAsSource.slice();\n for (var i = 0; i < outgoingEdges.length; i++) {\n var internalEdge = outgoingEdges[i];\n var targetNode = internalEdge.target;\n // Root check is O(|roots|)\n data.parent = root;\n data.root = targetNode;\n data.edge = internalEdge;\n this.depthFirstSearch(visitor, seen, layer + 1, data);\n }\n }\n else {\n this.updateConnectionRank(visitor, layer, 1, data);\n }\n }\n };\n /**\n * Updates the rank of the connection\n */\n MultiParentModel.prototype.updateConnectionRank = function (visitor, layer, seen, traversedList) {\n var parent = traversedList.parent;\n var root = traversedList.root;\n var edge = traversedList.edge;\n if (visitor === 'removeParentConnection' || visitor === 'removeNodeConnection') {\n var remove = visitor === 'removeNodeConnection' ? true : false;\n this.removeConnectionEdge(parent, root, edge, layer, traversedList, remove);\n }\n if (visitor === 'updateMinMaxRank') {\n this.updateMinMaxRank(layer, seen, traversedList);\n }\n };\n /**\n * Removes the edge from the collection\n */\n MultiParentModel.prototype.removeConnectionEdge = function (parent, node, edge, layer, data, remove) {\n var seenNodes = data.seenNodes;\n var unseenNodes = data.unseenNodes;\n var rankList = data.rankList;\n if (this.hierarchicalUtil.isAncestor(node, parent)) {\n this.hierarchicalUtil.invert(edge, 0);\n this.hierarchicalUtil.remove(edge, parent.connectsAsSource);\n if (remove) {\n node.connectsAsSource.push(edge);\n parent.connectsAsTarget.push(edge);\n this.hierarchicalUtil.remove(edge, node.connectsAsTarget);\n }\n else {\n parent.connectsAsTarget.push(edge);\n this.hierarchicalUtil.remove(edge, node.connectsAsTarget);\n node.connectsAsSource.push(edge);\n }\n }\n seenNodes[node.id] = node;\n delete unseenNodes[node.id];\n };\n /**\n * the dfs extends the default version by keeping track of cells ancestors, but it should be only used when necessary\n */\n MultiParentModel.prototype.extendedDfs = function (visitor, seen, cHash, layer, data) {\n var seenNodes = data.seenNodes;\n var unseenNodes = data.unseenNodes;\n var rankList = data.rankList;\n var parent = data.parent;\n var root = data.root;\n var edge = data.edge;\n if (root != null) {\n if (parent != null) {\n if (root.hashCode == null ||\n root.hashCode[0] !== parent.hashCode[0]) {\n var hashCodeLength = parent.hashCode.length + 1;\n root.hashCode = parent.hashCode.slice();\n root.hashCode[hashCodeLength - 1] = cHash;\n }\n }\n var rootId = root.id;\n if (seen[rootId] == null) {\n seen[rootId] = root;\n this.updateConnectionRank(visitor, layer, 0, data);\n var outgoingEdges = root.connectsAsSource.slice();\n for (var i = 0; i < outgoingEdges.length; i++) {\n var internalEdge = outgoingEdges[i];\n var targetNode = internalEdge.target;\n data.parent = root;\n data.root = targetNode;\n data.edge = internalEdge;\n this.extendedDfs(visitor, seen, i, layer + 1, data);\n }\n }\n else {\n this.updateConnectionRank(visitor, layer, 1, data);\n }\n }\n };\n /**\n * used to clone the specified object ignoring all fieldnames in the given array of transient fields\n * @private\n */\n MultiParentModel.prototype.clone = function (obj, transients, shallow) {\n shallow = (shallow != null) ? shallow : false;\n if (obj != null && typeof (obj.constructor) === 'function') {\n var clonedObj = obj.constructor();\n for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {\n var i = _a[_i];\n if (i !== 'layoutObjectId' && (transients == null || transients.indexOf(i) < 0)) {\n if (!shallow && typeof (obj[i]) === 'object') {\n //not used\n // _clone[i] = $.extend(true, {}, obj[i]);\n }\n else {\n clonedObj[i] = obj[i];\n }\n }\n }\n return clonedObj;\n }\n return null;\n };\n return MultiParentModel;\n}());\n/**\n * Defines how to reduce the crosses in between the line segments\n */\nvar CrossReduction = /** @class */ (function () {\n function CrossReduction() {\n }\n /**\n * used to calculate the number of edges crossing the layout model\n * @param model\n */\n CrossReduction.prototype.calculateCrossings = function (model) {\n var numRanks = model.ranks.length;\n var totalCrossings = 0;\n for (var i = 1; i < numRanks; i++) {\n totalCrossings += this.calculateRankCrossing(i, model);\n }\n return totalCrossings;\n };\n /**\n * used to get the temp value specified for the node or connector\n * @private\n */\n CrossReduction.prototype.getTempVariable = function (node, layer) {\n if (node) {\n if (this.isVertex(node)) {\n return node.temp[0];\n }\n else {\n return node.temp[layer - node.minRank - 1];\n }\n }\n return 0;\n };\n /**\n * used to specify the number of conenctors crossing between the specified rank and its below rank\n */\n CrossReduction.prototype.calculateRankCrossing = function (i, model) {\n var totalCrossings = 0;\n var rank = model.ranks[i];\n var previousRank = model.ranks[i - 1];\n var tmpIndices = [];\n // Iterate over the top rank and fill in the connection information\n for (var j = 0; j < rank.length; j++) {\n var node = rank[j];\n var rankPosition = this.getTempVariable(node, i);\n var connectedCells = this.getConnectedCellsOnLayer(node, i, true);\n ///#### \n var nodeIndices = [];\n for (var k = 0; k < connectedCells.length; k++) {\n var connectedNode = connectedCells[k];\n var otherCellRankPosition = this.getTempVariable(connectedNode, i - 1);\n nodeIndices.push(otherCellRankPosition);\n }\n nodeIndices.sort(function (x, y) { return x - y; });\n tmpIndices[rankPosition] = nodeIndices;\n }\n var indices = [];\n for (var j = 0; j < tmpIndices.length; j++) {\n indices = indices.concat(tmpIndices[j]);\n }\n var firstIndex = 1;\n while (firstIndex < previousRank.length) {\n firstIndex <<= 1;\n }\n var treeSize = 2 * firstIndex - 1;\n firstIndex -= 1;\n var tree = [];\n for (var j = 0; j < treeSize; ++j) {\n tree[j] = 0;\n }\n for (var j = 0; j < indices.length; j++) {\n var index = indices[j];\n var treeIndex = index + firstIndex;\n ++tree[treeIndex];\n while (treeIndex > 0) {\n if (treeIndex % 2) {\n totalCrossings += tree[treeIndex + 1];\n }\n treeIndex = (treeIndex - 1) >> 1;\n ++tree[treeIndex];\n }\n }\n return totalCrossings;\n };\n /**\n * Calculates and reduces the crosses between line segments\n * @private\n */\n CrossReduction.prototype.execute = function (model) {\n // Stores initial ordering \n this.nestedBestRanks = [];\n for (var i = 0; i < model.ranks.length; i++) {\n this.nestedBestRanks[i] = model.ranks[i].slice();\n }\n var iterationsWithoutImprovement = 0;\n var currentBestCrossings = this.calculateCrossings(model);\n for (var i = 0; i < 24 && iterationsWithoutImprovement < 2; i++) {\n this.weightedMedian(i, model);\n var candidateCrossings = this.calculateCrossings(model);\n if (candidateCrossings < currentBestCrossings) {\n currentBestCrossings = candidateCrossings;\n iterationsWithoutImprovement = 0;\n for (var j = 0; j < this.nestedBestRanks.length; j++) {\n var rank = model.ranks[j];\n for (var k = 0; k < rank.length; k++) {\n var cell = rank[k];\n this.nestedBestRanks[j][cell.temp[0]] = cell;\n }\n }\n }\n else {\n // Increase count of iterations \n iterationsWithoutImprovement++;\n // Restore the best values to the cells\n for (var j = 0; j < this.nestedBestRanks.length; j++) {\n var rank = model.ranks[j];\n for (var k = 0; k < rank.length; k++) {\n var cell = rank[k];\n this.setTempVariable(cell, j, k);\n }\n }\n }\n if (currentBestCrossings === 0) {\n break;\n }\n }\n // Store the best rankings but in the model\n var ranks = [];\n var rankList = [];\n for (var i = 0; i < model.maxRank + 1; i++) {\n rankList[i] = [];\n ranks[i] = rankList[i];\n }\n for (var i = 0; i < this.nestedBestRanks.length; i++) {\n for (var j = 0; j < this.nestedBestRanks[i].length; j++) {\n rankList[i].push(this.nestedBestRanks[i][j]);\n }\n }\n model.ranks = ranks;\n };\n /**\n * check whether the object is vertext or edge on the layout model.\n * @private\n */\n CrossReduction.prototype.isVertex = function (node) {\n if (node && node.cell && (node.cell.inEdges || node.cell.outEdges)) {\n return true;\n }\n return false;\n };\n /**\n * used to move up or move down the node position on the adjacent ranks\n */\n CrossReduction.prototype.weightedMedian = function (iteration, model) {\n // Reverse sweep direction each time through this method\n var downwardSweep = (iteration % 2 === 0);\n if (downwardSweep) {\n for (var j = model.maxRank - 1; j >= 0; j--) {\n this.medianRank(j, downwardSweep);\n }\n }\n else {\n for (var j = 1; j < model.maxRank; j++) {\n this.medianRank(j, downwardSweep);\n }\n }\n };\n /**\n * used to get the node next(up) connected to the specified node or connector\n * @private\n */\n CrossReduction.prototype.getConnectedCellsOnLayer = function (cell, layer, isPrevious) {\n if (isPrevious === void 0) { isPrevious = false; }\n var connectedlayer = 'nextLayerConnectedCells';\n var connectedAs = 'connectsAsTarget';\n if (isPrevious) {\n connectedlayer = 'previousLayerConnectedCells';\n connectedAs = 'connectsAsSource';\n }\n if (cell) {\n if (this.isVertex(cell)) {\n if (cell[connectedlayer] == null) {\n cell[connectedlayer] = [];\n cell[connectedlayer][0] = [];\n for (var i = 0; i < cell[connectedAs].length; i++) {\n var edge = cell[connectedAs][i];\n if (edge.maxRank === undefined) {\n edge.maxRank = -1;\n }\n if (edge.maxRank === -1 || (isPrevious ? (edge.minRank === layer - 1) : (edge.maxRank === layer + 1))) {\n // Either edge is not in any rank or no dummy nodes in edge, add node of other side of edge\n cell[connectedlayer][0].push(isPrevious ? edge.target : edge.source);\n }\n else {\n // Edge spans at least two layers, add edge\n cell[connectedlayer][0].push(edge);\n }\n }\n }\n return cell[connectedlayer][0];\n }\n else {\n if (cell[connectedlayer] == null) {\n cell[connectedlayer] = [];\n for (var i = 0; i < cell.temp.length; i++) {\n cell[connectedlayer][i] = [];\n if (i === (isPrevious ? 0 : (cell.temp.length - 1))) {\n cell[connectedlayer][i].push(isPrevious ? cell.target : cell.source);\n }\n else {\n cell[connectedlayer][i].push(cell);\n }\n }\n }\n return cell[connectedlayer][layer - cell.minRank - 1];\n }\n }\n return null;\n };\n /**\n * calculates the rank elements on the specified rank\n * @private\n */\n CrossReduction.prototype.medianValue = function (connectedCells, rankValue) {\n var medianValues = [];\n var arrayCount = 0;\n for (var i = 0; i < connectedCells.length; i++) {\n var cell = connectedCells[i];\n medianValues[arrayCount++] = this.getTempVariable(cell, rankValue);\n }\n // sorts numerical order sort\n medianValues.sort(function (a, b) { return a - b; });\n if (arrayCount % 2 === 1) {\n // For odd numbers of adjacent vertices return the median\n return medianValues[Math.floor(arrayCount / 2)];\n }\n else if (arrayCount === 2) {\n return ((medianValues[0] + medianValues[1]) / 2.0);\n }\n else {\n var medianPoint = arrayCount / 2;\n var leftMedian = medianValues[medianPoint - 1] - medianValues[0];\n var rightMedian = medianValues[arrayCount - 1]\n - medianValues[medianPoint];\n return (medianValues[medianPoint - 1] * rightMedian + medianValues[medianPoint] * leftMedian) / (leftMedian + rightMedian);\n }\n };\n /**\n * get the temp value of the specified layer\n * @private\n */\n CrossReduction.prototype.setTempVariable = function (cell, layer, value) {\n if (cell) {\n cell.temp[0] = value;\n }\n };\n /**\n * used to minimize the node position on this rank and one of its adjacent ranks\n */\n CrossReduction.prototype.medianRank = function (rankValue, downwardSweep) {\n var numCellsForRank = this.nestedBestRanks[rankValue].length;\n var medianValues = [];\n var reservedPositions = [];\n for (var i = 0; i < numCellsForRank; i++) {\n var cell = this.nestedBestRanks[rankValue][i];\n var sorterEntry = { medianValue: 0 };\n sorterEntry.cell = cell;\n // Flip whether or not equal medians are flipped on up and down sweeps \n //TODO re-implement some kind of nudge medianValues[i].nudge = !downwardSweep;\n var nextLevelConnectedCells = void 0;\n if (downwardSweep) {\n nextLevelConnectedCells = this.getConnectedCellsOnLayer(cell, rankValue);\n }\n else {\n nextLevelConnectedCells = this.getConnectedCellsOnLayer(cell, rankValue, true);\n }\n var nextRankValue = void 0;\n downwardSweep ? nextRankValue = rankValue + 1 : nextRankValue = rankValue - 1;\n if (nextLevelConnectedCells != null && nextLevelConnectedCells.length !== 0) {\n sorterEntry.medianValue = this.medianValue(nextLevelConnectedCells, nextRankValue);\n medianValues.push(sorterEntry);\n }\n else {\n // Nodes with no adjacent vertices are flagged in the reserved array to \n //indicate they should be left in their current position.\n reservedPositions[this.getTempVariable(cell, rankValue)] = true;\n }\n }\n medianValues.sort(this.compare);\n // Set the new position of each node within the rank using its temp variable\n for (var i = 0; i < numCellsForRank; i++) {\n if (reservedPositions[i] == null) {\n var cell = medianValues.shift().cell;\n this.setTempVariable(cell, rankValue, i);\n }\n }\n };\n /**\n * compares two values, it sends the values to the compare function,\n * and sorts the values according to the returned (negative, zero, positive) value\n */\n CrossReduction.prototype.compare = function (a, b) {\n if (a != null && b != null) {\n if (b.medianValue > a.medianValue) {\n return -1;\n }\n else if (b.medianValue < a.medianValue) {\n return 1;\n }\n }\n return 0;\n };\n return CrossReduction;\n}());\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, Complex, CollectionFactory, ChildProperty, Event } from '@syncfusion/ej2-base';\nimport { Browser, EventHandler, Draggable, Collection } from '@syncfusion/ej2-base';\nimport { remove, createElement } from '@syncfusion/ej2-base';\nimport { Accordion } from '@syncfusion/ej2-navigations';\nimport { Node, Connector, Shape, Size, Transform } from '../diagram/index';\nimport { DiagramRenderer, StackPanel, Margin } from '../diagram/index';\nimport { TextElement, Canvas, BpmnShape } from '../diagram/index';\nimport { SvgRenderer } from '../diagram/rendering/svg-renderer';\nimport { parentsUntil, createSvgElement, createHtmlElement, createMeasureElements } from '../diagram/utility/dom-util';\nimport { scaleElement } from '../diagram/utility/diagram-util';\nimport { getFunction } from '../diagram/utility/base-util';\nimport { getOuterBounds } from '../diagram/utility/connector';\nimport { Point } from '../diagram/primitives/point';\nimport { CanvasRenderer } from '../diagram/rendering/canvas-renderer';\nvar getObjectType = function (obj) {\n var conn = obj;\n if (conn.sourcePoint || conn.targetPoint || conn.sourceID || conn.targetID\n || conn.sourcePortID || conn.targetPortID || conn.sourceDecorator || conn.targetDecorator) {\n return Connector;\n }\n if (obj.shape && (obj.shape instanceof Shape || obj.shape.type)) {\n return Node;\n }\n return Node;\n};\n/**\n * Defines the behavior of a palette\n */\nvar Palette = /** @class */ (function (_super) {\n __extends(Palette, _super);\n function Palette() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('')\n ], Palette.prototype, \"id\", void 0);\n __decorate([\n Property()\n ], Palette.prototype, \"height\", void 0);\n __decorate([\n Property(true)\n ], Palette.prototype, \"expanded\", void 0);\n __decorate([\n Property('')\n ], Palette.prototype, \"iconCss\", void 0);\n __decorate([\n Property('')\n ], Palette.prototype, \"title\", void 0);\n __decorate([\n CollectionFactory(getObjectType)\n ], Palette.prototype, \"symbols\", void 0);\n return Palette;\n}(ChildProperty));\nexport { Palette };\n/**\n * Defines the size and position of the symbol palette\n */\nvar SymbolPreview = /** @class */ (function (_super) {\n __extends(SymbolPreview, _super);\n function SymbolPreview() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], SymbolPreview.prototype, \"width\", void 0);\n __decorate([\n Property()\n ], SymbolPreview.prototype, \"height\", void 0);\n __decorate([\n Complex({}, Point)\n ], SymbolPreview.prototype, \"offset\", void 0);\n return SymbolPreview;\n}(ChildProperty));\nexport { SymbolPreview };\n/**\n * Represents the Symbol Palette Component.\n * ```html\n *
\n * \n * ```\n */\nvar SymbolPalette = /** @class */ (function (_super) {\n __extends(SymbolPalette, _super);\n //region - protected methods \n /**\n * Constructor for creating the component\n * @hidden\n */\n function SymbolPalette(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.symbolTable = {};\n _this.info = 'info';\n /**\n * helper method for draggable\n * @return {void}\n * @private\n */\n _this.helper = function (e) {\n var clonedElement;\n var id = e.sender.target.id.split('_container')[0];\n var symbol = _this.symbolTable[id];\n if (symbol && _this.selectedSymbol) {\n _this.selectedSymbols = _this.selectedSymbol.id === symbol.id ? symbol : _this.selectedSymbol;\n var position = _this.getMousePosition(e.sender);\n clonedElement = _this.getSymbolPreview(_this.selectedSymbols, e.sender, _this.element);\n clonedElement.setAttribute('paletteId', _this.element.id);\n }\n return clonedElement;\n };\n return _this;\n }\n /**\n * Refreshes the panel when the symbol palette properties are updated\n * @param newProp Defines the new values of the changed properties\n * @param oldProp Defines the old values of the changed properties\n */\n SymbolPalette.prototype.onPropertyChanged = function (newProp, oldProp) {\n var refresh = false;\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'width':\n this.element.style.width = this.width.toString();\n break;\n case 'height':\n this.element.style.height = this.height.toString();\n break;\n case 'symbolPreview':\n break;\n case 'symbolWidth':\n case 'symbolHeight':\n case 'getSymbolInfo':\n refresh = true;\n break;\n case 'enableSearch':\n if (newProp.enableSearch) {\n this.createTextbox();\n }\n else {\n var divElement = document.getElementById(this.element.id + '_search');\n if (divElement) {\n divElement.parentNode.removeChild(divElement);\n }\n }\n break;\n case 'palettes':\n for (var _b = 0, _c = Object.keys(newProp.palettes); _b < _c.length; _b++) {\n var i = _c[_b];\n var index = Number(i);\n if (newProp.palettes[index].iconCss !== undefined) {\n this.accordionElement.items[index].iconCss = newProp.palettes[index].iconCss;\n refresh = true;\n }\n if (newProp.palettes[index].expanded !== undefined) {\n if (!this.palettes[index].isInteraction) {\n this.accordionElement.items[index].expanded = newProp.palettes[index].expanded;\n refresh = true;\n }\n else {\n this.palettes[index].isInteraction = false;\n }\n }\n }\n break;\n case 'enableAnimation':\n if (!this.enableAnimation) {\n this.accordionElement.animation = { expand: { duration: 0 }, collapse: { duration: 0 } };\n }\n else {\n this.accordionElement.animation = { expand: { duration: 400 }, collapse: { duration: 400 } };\n }\n break;\n case 'expandMode':\n this.accordionElement.expandMode = this.expandMode;\n refresh = true;\n break;\n }\n }\n if (refresh) {\n this.refreshPalettes();\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @return {string}\n */\n SymbolPalette.prototype.getPersistData = function () {\n var keyEntity = ['loaded'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Initialize nodes, connectors and renderer\n */\n SymbolPalette.prototype.preRender = function () {\n var _this = this;\n this.element.style.overflow = 'auto';\n this.element.style.height = this.height.toString();\n this.element.style.width = this.width.toString();\n if (this.enableSearch) {\n this.createTextbox();\n }\n //create accordion element\n var accordionDiv = createElement('div', { id: this.element.id + '_container' });\n this.accordionElement = new Accordion({\n expandMode: this.expandMode\n });\n if (!this.enableAnimation) {\n this.accordionElement.animation = { expand: { duration: 0 }, collapse: { duration: 0 } };\n }\n this.accordionElement.expanded = function (args) {\n var index = _this.accordionElement.items.indexOf(args.item);\n _this.palettes[index].expanded = args.isExpanded;\n _this.palettes[index].isInteraction = true;\n };\n this.element.appendChild(accordionDiv);\n createMeasureElements();\n this.unWireEvents();\n this.wireEvents();\n };\n /**\n * Renders nodes and connectors in the symbol palette\n */\n SymbolPalette.prototype.render = function () {\n this.diagramRenderer = new DiagramRenderer(this.element.id, new SvgRenderer(), false);\n this.svgRenderer = new DiagramRenderer(this.element.id, new SvgRenderer(), true);\n this.updatePalettes();\n this.accordionElement.appendTo('#' + this.element.id + '_container');\n };\n /**\n * To get Module name\n * @private\n */\n SymbolPalette.prototype.getModuleName = function () {\n return 'SymbolPalette';\n };\n /**\n * To provide the array of modules needed for control rendering\n * @return {ModuleDeclaration[]}\n * @private\n */\n SymbolPalette.prototype.requiredModules = function () {\n var modules = [];\n modules.push({\n member: 'Bpmn',\n args: []\n });\n return modules;\n };\n /**\n * To destroy the symbol palette\n * @return {void}\n */\n SymbolPalette.prototype.destroy = function () {\n if (this.allowDrag) {\n this.draggable.destroy();\n this.unWireEvents();\n this.notify('destroy', {});\n _super.prototype.destroy.call(this);\n var content = document.getElementById(this.element.id + '_container');\n if (content) {\n this.element.removeChild(content);\n var measureElemnt = 'measureElement';\n if (window[measureElemnt]) {\n window[measureElemnt].usageCount -= 1;\n if (window[measureElemnt].usageCount === 0) {\n window[measureElemnt].parentNode.removeChild(window[measureElemnt]);\n window[measureElemnt] = null;\n }\n }\n }\n this.element.classList.remove('e-symbolpalette');\n }\n };\n //end region - protected methods\n //region - private methods to render symbols\n /**\n * Method to initialize the items in the symbols\n */\n SymbolPalette.prototype.initSymbols = function (symbolGroup) {\n for (var _i = 0, _a = symbolGroup.symbols; _i < _a.length; _i++) {\n var symbol = _a[_i];\n if (symbol instanceof Node) {\n var getNodeDefaults = getFunction(this.getNodeDefaults);\n if (getNodeDefaults) {\n getNodeDefaults(symbol, this);\n }\n }\n else if (symbol instanceof Connector) {\n var getConnectorDefaults = getFunction(this.getConnectorDefaults);\n if (getConnectorDefaults) {\n getConnectorDefaults(symbol, this);\n }\n }\n this.prepareSymbol(symbol);\n this.symbolTable[symbol.id] = symbol;\n }\n };\n /**\n * Method to create the palette\n */\n SymbolPalette.prototype.renderPalette = function (symbolGroup) {\n var paletteDiv = document.createElement('div');\n paletteDiv.setAttribute('id', symbolGroup.id);\n var style = 'display:none;overflow:auto;';\n if (symbolGroup.height) {\n style += 'height:' + symbolGroup.height + 'px';\n }\n paletteDiv.setAttribute('style', style);\n this.element.appendChild(paletteDiv);\n var item = {\n header: symbolGroup.title, expanded: symbolGroup.expanded,\n content: '#' + symbolGroup.id, iconCss: symbolGroup.iconCss\n };\n this.accordionElement.items.push(item);\n this.renderSymbols(symbolGroup, paletteDiv);\n };\n /**\n * Used to add the palette item as nodes or connectors in palettes\n */\n SymbolPalette.prototype.addPaletteItem = function (paletteName, paletteSymbol) {\n var refresh;\n for (var i = 0; i < this.palettes.length; i++) {\n var symbolPaletteGroup = this.palettes[i];\n if (symbolPaletteGroup.id.indexOf(paletteName) !== -1) {\n // tslint:disable-next-line:no-any \n var param = [undefined, symbolPaletteGroup, 'symbols', {}, true];\n // tslint:disable-next-line:no-any \n var obj = new (Function.prototype.bind.apply(getObjectType(paletteSymbol), param));\n for (var i_1 = 0; i_1 < Object.keys(paletteSymbol).length; i_1++) {\n obj[Object.keys(paletteSymbol)[i_1]] = paletteSymbol[Object.keys(paletteSymbol)[i_1]];\n }\n symbolPaletteGroup.symbols.push(obj);\n this.prepareSymbol(obj);\n this.symbolTable[obj.id] = obj;\n var paletteDiv = document.getElementById(symbolPaletteGroup.id);\n paletteDiv.appendChild(this.getSymbolContainer(obj, paletteDiv));\n break;\n }\n }\n };\n /**\n * Used to remove the palette item as nodes or connectors in palettes\n */\n SymbolPalette.prototype.removePaletteItem = function (paletteName, symbolId) {\n var refresh;\n for (var i = 0; i < this.palettes.length; i++) {\n var symbolPaletteGroup = this.palettes[i];\n if (symbolPaletteGroup.id.indexOf(paletteName) !== -1) {\n for (var _i = 0, _a = symbolPaletteGroup.symbols; _i < _a.length; _i++) {\n var symbol = _a[_i];\n if (symbol.id.indexOf(symbolId) !== -1) {\n var index = symbolPaletteGroup.symbols.indexOf(symbol);\n symbolPaletteGroup.symbols.splice(index, 1);\n delete this.symbolTable[symbol.id];\n var element = document.getElementById(symbol.id + '_container');\n element.parentNode.removeChild(element);\n refresh = true;\n break;\n }\n }\n }\n if (refresh) {\n break;\n }\n }\n };\n /**\n * Method to create the symbols in canvas\n */\n SymbolPalette.prototype.prepareSymbol = function (symbol) {\n var width;\n var sw;\n var height;\n var sh;\n var stackPanel = new StackPanel();\n var obj = symbol;\n var content;\n var symbolContainer = new Canvas();\n //preparing objects\n var getSymbolTemplate = getFunction(this.getSymbolTemplate);\n if (getSymbolTemplate) {\n content = getSymbolTemplate(symbol);\n }\n if (!content) {\n content = symbol.init(this);\n }\n var symbolInfo = { width: this.symbolWidth, height: this.symbolHeight };\n var getSymbolInfo = getFunction(this.getSymbolInfo);\n if (getSymbolInfo) {\n symbolInfo = getSymbolInfo(symbol);\n }\n symbolInfo = symbolInfo || {};\n //defining custom templates\n content.relativeMode = 'Object';\n content.horizontalAlignment = content.verticalAlignment = 'Center';\n symbolContainer.style.strokeColor = symbolContainer.style.fill = 'none';\n symbolContainer.children = [content];\n content.measure(new Size());\n content.arrange(content.desiredSize);\n width = symbolInfo.width = symbolInfo.width ||\n (obj.width !== undefined ? content.actualSize.width : undefined) || this.symbolWidth;\n height = symbolInfo.height = symbolInfo.height ||\n (obj.height !== undefined ? content.actualSize.height : undefined) || this.symbolHeight;\n if (width !== undefined && height !== undefined) {\n var actualWidth = width;\n var actualHeight = height;\n if (this.symbolWidth !== undefined) {\n actualWidth = this.symbolWidth - this.symbolMargin.left - this.symbolMargin.right;\n }\n else {\n width += obj.style.strokeWidth;\n }\n if (this.symbolHeight !== undefined) {\n actualHeight = this.symbolHeight - this.symbolMargin.top - this.symbolMargin.bottom;\n }\n else {\n height += obj.style.strokeWidth;\n }\n if (symbolInfo.description && symbolInfo.description.text !== '') {\n actualHeight -= 20; // default height of the text have been reduced from the container.\n }\n sw = actualWidth / (content.width || width);\n sh = actualHeight / (content.height || height);\n if (symbolInfo.fit) {\n sw = actualWidth / symbolInfo.width;\n sh = actualHeight / symbolInfo.height;\n }\n width = actualWidth;\n height = actualHeight;\n sw = sh = Math.min(sw, sh);\n symbolContainer.width = width;\n symbolContainer.height = height;\n content.width = symbolInfo.width;\n content.height = symbolInfo.height;\n this.scaleSymbol(symbol, symbolContainer, sw, sh, width, height);\n }\n else {\n var outerBounds = void 0;\n if (symbol instanceof Connector) {\n outerBounds = getOuterBounds(symbol);\n }\n content.width = symbol.width || (outerBounds) ? outerBounds.width : content.actualSize.width;\n content.height = symbol.height || (outerBounds) ? outerBounds.height : content.actualSize.height;\n }\n symbol.wrapper = stackPanel;\n stackPanel.children = [symbolContainer];\n content.pivot = stackPanel.pivot = { x: 0, y: 0 };\n stackPanel.id = content.id + '_symbol';\n stackPanel.style.fill = stackPanel.style.strokeColor = 'transparent';\n stackPanel.offsetX = symbol.style.strokeWidth / 2;\n stackPanel.offsetY = symbol.style.strokeWidth / 2;\n //symbol description-textElement\n this.getSymbolDescription(symbolInfo, width, stackPanel);\n stackPanel.measure(new Size());\n stackPanel.arrange(stackPanel.desiredSize);\n symbolInfo.width = symbolInfo.width || content.actualSize.width;\n symbolInfo.height = symbolInfo.height || content.actualSize.height;\n symbol[this.info] = symbolInfo;\n };\n /**\n * Method to get the symbol text description\n * @return {void}\n * @private\n */\n SymbolPalette.prototype.getSymbolDescription = function (symbolInfo, width, parent) {\n if (symbolInfo && symbolInfo.description && symbolInfo.description.text) {\n var textElement = new TextElement();\n //symbol description-textElement\n symbolInfo.description.overflow = symbolInfo.description.overflow || 'Ellipsis';\n symbolInfo.description.wrap = symbolInfo.description.wrap || 'WrapWithOverflow';\n textElement.content = symbolInfo.description.text;\n textElement.width = width;\n textElement.height = 20;\n textElement.style.strokeColor = 'transparent';\n textElement.style.fill = 'transparent';\n textElement.style.strokeWidth = 0;\n textElement.style.textWrapping = symbolInfo.description.wrap;\n textElement.style.textOverflow = symbolInfo.description.overflow;\n textElement.margin = { left: 0, right: 0, top: 0, bottom: 5 };\n parent.children.push(textElement);\n }\n };\n /**\n * Method to renders the symbols\n * @return {void}\n * @private\n */\n SymbolPalette.prototype.renderSymbols = function (symbolGroup, parentDiv) {\n for (var _i = 0, _a = symbolGroup.symbols; _i < _a.length; _i++) {\n var symbol = _a[_i];\n this.getSymbolContainer(symbol, parentDiv);\n }\n };\n /**\n * Method to clone the symbol for previewing the symbols\n * @return {void}\n * @private\n */\n SymbolPalette.prototype.getSymbolPreview = function (symbol, evt, parentDiv) {\n var canvas;\n var sw;\n var sh;\n var symbolPreviewWidth = symbol.wrapper.children[0].desiredSize.width + symbol.style.strokeWidth;\n var symbolPreviewHeight = symbol.wrapper.children[0].desiredSize.height + symbol.style.strokeWidth;\n var content = symbol.wrapper.children[0].children[0];\n if (this.symbolPreview.width !== undefined || this.symbolPreview.height !== undefined) {\n symbolPreviewWidth = (this.symbolPreview.width || symbolPreviewWidth) - symbol.style.strokeWidth;\n symbolPreviewHeight = (this.symbolPreview.height || symbolPreviewHeight) - symbol.style.strokeWidth;\n sw = symbolPreviewWidth / content.actualSize.width;\n sh = symbolPreviewHeight / content.actualSize.height;\n sw = sh = Math.min(sw, sh);\n var symbolWidth = content.actualSize.width * sw;\n var symbolHeight = content.actualSize.height * sh;\n symbol.wrapper.children[0].width = symbolPreviewWidth;\n symbol.wrapper.children[0].height = symbolPreviewHeight;\n this.measureAndArrangeSymbol(content);\n this.scaleSymbol(symbol, symbol.wrapper.children[0], sw, sh, symbolWidth, symbolHeight);\n symbolPreviewWidth = symbolWidth;\n symbolPreviewHeight = symbolHeight;\n }\n var prevPosition = { x: content.offsetX, y: content.offsetY };\n content.offsetX = content.offsetY = symbol.style.strokeWidth / 2;\n content.pivot = { x: 0, y: 0 };\n this.measureAndArrangeSymbol(content);\n var previewContainer = createElement('div');\n var div;\n previewContainer.setAttribute('draggable', 'true');\n previewContainer.setAttribute('class', 'e-dragclone');\n previewContainer.style.pointerEvents = 'none';\n document.body.appendChild(previewContainer);\n var style = 'margin:5px;';\n if (symbol.shape.type === 'Native') {\n canvas = createSvgElement('svg', {\n id: symbol.id + '_preview',\n width: Math.ceil(symbolPreviewWidth) + 1,\n height: Math.ceil(symbolPreviewHeight) + 1\n });\n var gElement = createSvgElement('g', { id: symbol.id + '_g' });\n canvas.appendChild(gElement);\n previewContainer.appendChild(canvas);\n this.svgRenderer.renderElement(content, gElement, undefined, undefined, canvas);\n }\n else if (symbol.shape.type === 'HTML') {\n div = this.getHtmlSymbol(symbol, canvas, previewContainer, symbolPreviewHeight, symbolPreviewWidth, true);\n }\n else {\n canvas = CanvasRenderer.createCanvas(symbol.id + '_preview', (Math.ceil(symbolPreviewWidth) + symbol.style.strokeWidth + 1) * 2, (Math.ceil(symbolPreviewHeight) + symbol.style.strokeWidth + 1) * 2);\n previewContainer.appendChild(canvas);\n style += 'transform:scale(0.5);';\n canvas.setAttribute('transform-origin', '0 0');\n canvas.getContext('2d').setTransform(2, 0, 0, 2, 0, 0);\n this.diagramRenderer.renderElement(content, canvas, undefined);\n }\n ((div && symbol.shape.type === 'HTML') ? div : canvas).setAttribute('style', style);\n content.offsetX = prevPosition.x;\n content.offsetY = prevPosition.y;\n return previewContainer;\n };\n SymbolPalette.prototype.measureAndArrangeSymbol = function (content) {\n if (content.children) {\n content.children[0].transform = Transform.Self;\n }\n content.measure(new Size());\n content.arrange(content.desiredSize);\n if (content.children) {\n content.children[0].transform = Transform.Parent;\n }\n };\n SymbolPalette.prototype.updateSymbolSize = function (symbol, width, height) {\n var element = symbol.wrapper.children[0].children[0];\n var strokeWidth = symbol.style.strokeWidth;\n element.width = (width || element.width) - (strokeWidth + 1);\n element.height = (height || element.height) - (strokeWidth + 1);\n symbol.wrapper.measure(new Size());\n symbol.wrapper.arrange(symbol.wrapper.desiredSize);\n };\n /**\n * Method to create canvas and render the symbol\n * @return {void}\n * @private\n */\n SymbolPalette.prototype.getSymbolContainer = function (symbol, parentDiv, preview) {\n var symbolInfo = this.symbolTable[symbol.id][this.info];\n var size = this.getSymbolSize(symbol, symbolInfo);\n var width = size.width + 1;\n var height = size.height + 1;\n var container = createElement('div', {\n id: symbol.id + '_container',\n styles: 'width:' + width + 'px;height:' + height + 'px;float:left;overflow:hidden'\n });\n container.setAttribute('title', symbolInfo.description ? symbolInfo.description.text : symbol.id);\n parentDiv.appendChild(container);\n var canvas;\n var gElement;\n var div;\n if (symbol.shape.type === 'Native') {\n canvas = createSvgElement('svg', {\n id: symbol.id,\n width: Math.ceil(symbol.wrapper.actualSize.width) + 1,\n height: Math.ceil(symbol.wrapper.actualSize.height) + 1\n });\n gElement = createSvgElement('g', { id: symbol.id + '_g' });\n canvas.appendChild(gElement);\n container.appendChild(canvas);\n this.updateSymbolSize(symbol);\n this.svgRenderer.renderElement(symbol.wrapper, gElement, undefined, undefined, canvas);\n }\n else if (symbol.shape.type === 'HTML') {\n div = this.getHtmlSymbol(symbol, canvas, container, symbol.wrapper.actualSize.height, symbol.wrapper.actualSize.width, false);\n }\n else {\n canvas = CanvasRenderer.createCanvas(symbol.id, Math.ceil((symbol.wrapper.actualSize.width + symbol.style.strokeWidth) * 2) + 1, Math.ceil((symbol.wrapper.actualSize.height + symbol.style.strokeWidth) * 2) + 1);\n container.appendChild(canvas);\n canvas.getContext('2d').setTransform(2, 0, 0, 2, 0, 0);\n this.diagramRenderer.renderElement(symbol.wrapper, gElement || canvas, undefined);\n }\n if (!preview) {\n var actualWidth = symbol.wrapper.actualSize.width + symbol.style.strokeWidth;\n var actualHeight = symbol.wrapper.actualSize.height + symbol.style.strokeWidth;\n var style = 'margin-left:' +\n Math.max(this.symbolMargin.left, ((width - actualWidth) / 2))\n + 'px;margin-top:' + Math.max(this.symbolMargin.top, ((height - actualHeight) / 2))\n + 'px;pointer-events:none;transform-origin:0 0;overflow:hidden;';\n if (canvas instanceof HTMLCanvasElement) {\n style += 'transform:scale(.5,.5);';\n }\n ((div && symbol.shape.type === 'HTML') ? div : canvas).setAttribute('style', style);\n container.classList.add('e-symbol-draggable');\n return container;\n }\n return canvas;\n };\n SymbolPalette.prototype.getHtmlSymbol = function (symbol, canvas, container, height, width, isPreview) {\n var div = createHtmlElement('div', {\n 'id': symbol.id + (isPreview ? '_html_div_preview' : '_html_div')\n });\n var htmlLayer = createHtmlElement('div', {\n 'id': symbol.id + (isPreview ? '_htmlLayer_preview' : '_htmlLayer'),\n 'style': 'width:' + Math.ceil(width + 1) + 'px;' +\n 'height:' + Math.ceil(height + 1) + 'px;position:absolute',\n 'class': 'e-html-layer'\n });\n var htmlLayerDiv = createHtmlElement('div', {\n 'id': symbol.id + (isPreview ? '_htmlLayer_div_preview' : '_htmlLayer_div'),\n 'style': 'width:' + Math.ceil(width + 1) + 'px;' +\n 'height:' + Math.ceil(height + 1) + 'px;position:absolute',\n });\n htmlLayer.appendChild(htmlLayerDiv);\n div.appendChild(htmlLayer);\n canvas = CanvasRenderer.createCanvas((isPreview ? (symbol.id + '_preview') : symbol.id), Math.ceil(width) + 1, Math.ceil(height) + 1);\n div.appendChild(canvas);\n container.appendChild(div);\n this.diagramRenderer.renderElement(symbol.wrapper.children[0].children[0], canvas, htmlLayer);\n return div;\n };\n SymbolPalette.prototype.getSymbolSize = function (symbol, symbolInfo) {\n var width = symbol.wrapper.actualSize.width;\n var height = symbol.wrapper.actualSize.height;\n if (!this.symbolWidth && !this.symbolHeight) {\n width += this.symbolMargin.left + this.symbolMargin.right + symbol.style.strokeWidth;\n height += this.symbolMargin.top + this.symbolMargin.bottom + symbol.style.strokeWidth;\n }\n else {\n width = this.symbolWidth;\n height = Math.max(this.symbolHeight, height);\n }\n return new Size(width, height);\n };\n //end region - rendering symbols\n //region event handlers\n SymbolPalette.prototype.getMousePosition = function (e) {\n var offsetY;\n var offsetX;\n var touchArg;\n if (e.type.indexOf('touch') !== -1) {\n touchArg = e;\n var pageY = touchArg.changedTouches[0].clientY;\n var pageX = touchArg.changedTouches[0].clientX;\n offsetY = pageY - this.element.offsetTop;\n offsetX = pageX - this.element.offsetLeft;\n }\n else {\n offsetY = e.clientY - this.element.offsetTop;\n offsetX = e.clientX - this.element.offsetLeft;\n }\n return { x: offsetX, y: offsetY };\n };\n SymbolPalette.prototype.mouseMove = function (e, touches) {\n if (this.highlightedSymbol && (!this.selectedSymbol\n || this.selectedSymbol.id + '_container' !== this.highlightedSymbol.id)) {\n this.highlightedSymbol.classList.remove('e-symbol-hover');\n this.highlightedSymbol.style.backgroundColor = '';\n this.highlightedSymbol = null;\n }\n var id = e.target.id.split('_container')[0];\n if (this.symbolTable[id]) {\n var container = document.getElementById(id + '_container');\n container.classList.add('e-symbol-hover');\n this.highlightedSymbol = container;\n }\n e.preventDefault();\n };\n SymbolPalette.prototype.mouseUp = function (evt) {\n if (evt && evt.target) {\n if (evt.srcElement.id === 'iconSearch') {\n var element = document.getElementById('iconSearch');\n if (element.classList.contains('e-clear-searchtext')) {\n element.className = 'e-input-group-icon e-search e-icons';\n document.getElementById('textEnter').value = '';\n this.searchPalette('');\n }\n }\n else {\n evt.preventDefault();\n }\n }\n };\n SymbolPalette.prototype.keyUp = function (evt) {\n var _this = this;\n if (this.enableSearch) {\n var palette_1 = this;\n var element = document.getElementById('iconSearch');\n element.className = 'e-input-group-icon e-clear-searchtext e-icons';\n if (evt && (evt.key === 'Enter' || evt.keyCode === 13)) {\n if (evt.target instanceof HTMLInputElement) {\n this.searchPalette(evt.target.value);\n }\n }\n else {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(function () {\n if (evt.target instanceof HTMLInputElement) {\n palette_1.searchPalette(evt.target.value);\n _this.timer = null;\n }\n }, 500);\n }\n }\n };\n SymbolPalette.prototype.mouseDown = function (evt) {\n var id = evt.target.id.split('_container')[0];\n if (this.selectedSymbol) {\n if (id !== this.selectedSymbol.id) {\n var oldSymbol = document.getElementById(this.selectedSymbol.id + '_container');\n oldSymbol.classList.remove('e-symbol-selected');\n var args = { oldValue: this.selectedSymbol.id, newValue: id };\n var event_1 = 'paletteSelectionChange';\n this.trigger(event_1, args);\n }\n var container = document.getElementById(this.selectedSymbol.id + '_container');\n container.style.backgroundColor = '';\n this.selectedSymbol = null;\n }\n if (this.symbolTable[id]) {\n var container = document.getElementById(id + '_container');\n container.classList.add('e-symbol-selected');\n this.selectedSymbol = this.symbolTable[id];\n evt.preventDefault();\n }\n };\n //end region - event handlers\n // region - draggable\n SymbolPalette.prototype.initDraggable = function () {\n if (this.allowDrag) {\n var drag = void 0;\n this.draggable = new Draggable(this.element, {\n dragTarget: '.e-symbol-draggable',\n helper: this.helper,\n dragStart: this.dragStart,\n dragStop: this.dragStop,\n drag: function (args) {\n var target = 'target';\n var parent = parentsUntil(args[target], 'e-droppable');\n if (parent && parent.classList.contains('e-diagram')) {\n var e2eInstance = 'ej2_instances';\n parent[e2eInstance][0].droppable.over(args);\n }\n },\n cursorAt: { left: this.symbolPreview.offset.x, top: this.symbolPreview.offset.y }\n });\n }\n };\n SymbolPalette.prototype.dragStart = function (e) {\n var element = this.helper[0];\n if (element) {\n element.setAttribute('paletteId', this.element.id);\n }\n };\n SymbolPalette.prototype.dragStop = function (e) {\n if (!parentsUntil(e.target, 'e-diagram')) {\n remove(e.helper);\n }\n };\n //end region - draggable \n //region - helper methods\n SymbolPalette.prototype.scaleSymbol = function (symbol, symbolContainer, sw, sh, width, height) {\n if (symbol instanceof Connector) {\n var wrapper = symbol.wrapper;\n symbol.wrapper = symbolContainer.children[0];\n var point = symbol.scale(sw, sh, width, height, symbolContainer.children[0]);\n var difX = width / 2 - symbolContainer.children[0].children[0].offsetX + point.x / 2;\n var difY = height / 2 - symbolContainer.children[0].children[0].offsetY + point.y / 2;\n for (var _i = 0, _a = symbolContainer.children[0].children; _i < _a.length; _i++) {\n var child = _a[_i];\n child.offsetX += difX;\n child.offsetY += difY;\n child.staticSize = false;\n }\n symbol.wrapper = wrapper;\n }\n else if (symbol.shape instanceof BpmnShape && this.bpmnModule) {\n var wrapper = symbol.wrapper;\n symbol.wrapper = symbolContainer;\n symbolContainer.children[0].width = width;\n symbolContainer.children[0].height = height;\n this.bpmnModule.updateBPMN({ width: width, height: height }, symbol, symbol, null);\n symbol.wrapper = wrapper;\n }\n else {\n scaleElement(symbolContainer.children[0], sw, sh, symbolContainer);\n }\n };\n SymbolPalette.prototype.refreshPalettes = function () {\n this.accordionElement.items = [];\n this.updatePalettes();\n this.accordionElement.dataBind();\n };\n SymbolPalette.prototype.updatePalettes = function () {\n for (var i = 0; i < this.palettes.length; i++) {\n var symGroup = this.palettes[i];\n this.initSymbols(symGroup);\n this.renderPalette(symGroup);\n }\n };\n SymbolPalette.prototype.createTextbox = function () {\n var searchDiv = createElement('div', { id: this.element.id + '_search' });\n searchDiv.setAttribute('style', 'backgroundColor:white;height:30px');\n searchDiv.className = 'e-input-group';\n this.element.appendChild(searchDiv);\n var textBox = document.createElement('input');\n textBox.placeholder = 'Search Shapes';\n textBox.id = 'textEnter';\n textBox.setAttribute('style', 'width:100%;height:auto');\n textBox.className = 'e-input';\n searchDiv.appendChild(textBox);\n var span = createElement('span', { id: 'iconSearch', className: 'e-input-group-icon e-search e-icons' });\n searchDiv.appendChild(span);\n };\n SymbolPalette.prototype.searchPalette = function (value) {\n var symbolGroup = [];\n var element = document.getElementById('SearchPalette');\n var paletteDiv;\n //remove the existing child in palette\n if (element) {\n for (var k = element.children.length - 1; k >= 0; k--) {\n element.removeChild(element.children[k]);\n }\n }\n //add the searched item in array collection\n for (var i = 0; i < this.palettes.length; i++) {\n var symbolPaletteGroup = this.palettes[i];\n for (var j = 0; j < symbolPaletteGroup.symbols.length; j++) {\n var item = symbolPaletteGroup.symbols[j];\n if (value !== '' && item.id.toLowerCase().indexOf(value.toLowerCase()) !== -1) {\n symbolGroup.push(item);\n }\n }\n }\n var filterSymbols = getFunction(this.filterSymbols);\n if (filterSymbols) {\n symbolGroup = filterSymbols(symbolGroup) || [];\n }\n //create a palette collection\n if (!element) {\n paletteDiv = this.createSearchPalette(paletteDiv);\n element = paletteDiv;\n }\n //add the symbols into search palette\n if (symbolGroup.length > 0) {\n for (var _i = 0, symbolGroup_1 = symbolGroup; _i < symbolGroup_1.length; _i++) {\n var symbol = symbolGroup_1[_i];\n this.getSymbolContainer(symbol, element);\n }\n }\n else if (value !== '') {\n var emptyDiv = document.createElement('div');\n emptyDiv.setAttribute('id', 'EmptyDiv');\n emptyDiv.innerHTML = 'No Items To Display';\n emptyDiv.setAttribute('style', 'textAlign:center;fontStyle:italic');\n element.appendChild(emptyDiv);\n }\n else {\n var element_1 = document.getElementById('iconSearch');\n element_1.className = 'e-input-group-icon e-search e-icons';\n this.accordionElement.removeItem(0);\n }\n };\n SymbolPalette.prototype.createSearchPalette = function (paletteDiv) {\n paletteDiv = document.createElement('div');\n paletteDiv.setAttribute('id', 'SearchPalette');\n paletteDiv.setAttribute('style', 'display:none;overflow:auto;');\n this.element.appendChild(paletteDiv);\n var paletteCollection = {\n header: 'Search Results', expanded: true,\n content: '#SearchPalette',\n };\n this.accordionElement.addItem(paletteCollection, 0);\n return paletteDiv;\n };\n /**\n * Method to bind events for the symbol palette\n */\n SymbolPalette.prototype.wireEvents = function () {\n var startEvent = Browser.touchStartEvent;\n var stopEvent = Browser.touchEndEvent;\n var moveEvent = Browser.touchMoveEvent;\n var cancelEvent = 'mouseleave';\n var keyEvent = 'keyup';\n EventHandler.add(this.element, startEvent, this.mouseDown, this);\n EventHandler.add(this.element, moveEvent, this.mouseMove, this);\n EventHandler.add(this.element, stopEvent, this.mouseUp, this);\n EventHandler.add(this.element, keyEvent, this.keyUp, this);\n // initialize the draggable component\n this.initDraggable();\n };\n /**\n * Method to unbind events for the symbol palette\n */\n SymbolPalette.prototype.unWireEvents = function () {\n var startEvent = Browser.touchStartEvent;\n var stopEvent = Browser.touchEndEvent;\n var moveEvent = Browser.touchMoveEvent;\n var cancelEvent = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n var keyEvent = 'keyup';\n EventHandler.remove(this.element, startEvent, this.mouseDown);\n EventHandler.remove(this.element, moveEvent, this.mouseMove);\n EventHandler.remove(this.element, stopEvent, this.mouseUp);\n EventHandler.remove(this.element, keyEvent, this.keyUp);\n };\n __decorate([\n Property('S')\n ], SymbolPalette.prototype, \"accessKey\", void 0);\n __decorate([\n Property('100%')\n ], SymbolPalette.prototype, \"width\", void 0);\n __decorate([\n Property('100%')\n ], SymbolPalette.prototype, \"height\", void 0);\n __decorate([\n Collection([], Palette)\n ], SymbolPalette.prototype, \"palettes\", void 0);\n __decorate([\n Property()\n ], SymbolPalette.prototype, \"getSymbolInfo\", void 0);\n __decorate([\n Property()\n ], SymbolPalette.prototype, \"filterSymbols\", void 0);\n __decorate([\n Property()\n ], SymbolPalette.prototype, \"getSymbolTemplate\", void 0);\n __decorate([\n Property()\n ], SymbolPalette.prototype, \"symbolWidth\", void 0);\n __decorate([\n Property()\n ], SymbolPalette.prototype, \"symbolHeight\", void 0);\n __decorate([\n Complex({ left: 10, right: 10, top: 10, bottom: 10 }, Margin)\n ], SymbolPalette.prototype, \"symbolMargin\", void 0);\n __decorate([\n Property(true)\n ], SymbolPalette.prototype, \"allowDrag\", void 0);\n __decorate([\n Complex({}, SymbolPreview)\n ], SymbolPalette.prototype, \"symbolPreview\", void 0);\n __decorate([\n Property(false)\n ], SymbolPalette.prototype, \"enableSearch\", void 0);\n __decorate([\n Property(true)\n ], SymbolPalette.prototype, \"enableAnimation\", void 0);\n __decorate([\n Property('Multiple')\n ], SymbolPalette.prototype, \"expandMode\", void 0);\n __decorate([\n Event()\n ], SymbolPalette.prototype, \"paletteSelectionChange\", void 0);\n __decorate([\n Property()\n ], SymbolPalette.prototype, \"getNodeDefaults\", void 0);\n __decorate([\n Property()\n ], SymbolPalette.prototype, \"getConnectorDefaults\", void 0);\n return SymbolPalette;\n}(Component));\nexport { SymbolPalette };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { DiagramRenderer } from '../diagram/rendering/renderer';\nimport { CanvasRenderer } from '../diagram/rendering/canvas-renderer';\nimport { Component, Property, Browser, EventHandler, Event } from '@syncfusion/ej2-base';\nimport { setAttributeHtml, setAttributeSvg } from '../diagram/utility/dom-util';\nimport { createSvgElement, getNativeLayer, hasClass } from '../diagram/utility/dom-util';\nimport { Rect } from '../diagram/primitives/rect';\nimport { Size } from '../diagram/primitives/size';\nimport { SvgRenderer } from '../diagram/rendering/svg-renderer';\n/**\n * Overview control\n * ```\n *
\n * \n * ```\n */\nvar Overview = /** @class */ (function (_super) {\n __extends(Overview, _super);\n function Overview(options, element) {\n var _this = _super.call(this, options, element) || this;\n /** @private */\n _this.mode = 'Canvas';\n /** @private */\n _this.id = 'overview';\n _this.actionName = '';\n _this.startPoint = null;\n _this.currentPoint = null;\n _this.prevPoint = null;\n _this.scale = null;\n _this.inAction = false;\n _this.viewPortRatio = 1;\n _this.horizontalOffset = 0;\n _this.verticalOffset = 0;\n _this.model = {};\n _this.event = true;\n _this.model = { width: _this.width, height: _this.height };\n return _this;\n }\n /**\n * Updates the overview control when the objects are changed\n * @param newProp Lists the new values of the changed properties\n * @param oldProp Lists the old values of the changed properties\n */\n Overview.prototype.onPropertyChanged = function (newProp, oldProp) {\n var objectArray = [];\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'sourceID':\n this.setParent(newProp.sourceID);\n break;\n case 'width':\n case 'height':\n this.renderCanvas();\n this.setParent(this.sourceID);\n break;\n }\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @return {string}\n */\n Overview.prototype.getPersistData = function () {\n var keyEntity = ['loaded'];\n return this.addOnPersist(keyEntity);\n };\n /**\n * Initialize nodes, connectors and renderer\n */\n Overview.prototype.preRender = function () {\n this.element.style.background = 'transparent';\n this.unWireEvents();\n this.wireEvents();\n };\n Overview.prototype.render = function () {\n this.diagramRenderer = new DiagramRenderer(this.element.id, new SvgRenderer(), false);\n this.renderCanvas();\n this.setParent(this.sourceID);\n };\n Overview.prototype.getSizeValue = function (real) {\n var text;\n if (real.toString().indexOf('px') > 0 || real.toString().indexOf('%') > 0) {\n text = real.toString();\n }\n else {\n text = real.toString() + 'px';\n }\n return text;\n };\n Overview.prototype.renderCanvas = function (options) {\n var canvas = document.getElementById(this.element.id + '_canvas');\n if (!canvas) {\n canvas = document.createElement('div');\n this.element.appendChild(canvas);\n }\n var attribute = {\n 'id': this.element.id + '_canvas', 'class': 'drawing',\n 'style': 'position:relative; height:' + this.getSizeValue(this.model.height) + '; width:' +\n this.getSizeValue(this.model.width) +\n ';style:-ms-touch-action: none;touch-action: none;'\n };\n setAttributeHtml(canvas, attribute);\n this.element.setAttribute('tabindex', String(0));\n this.element.style.overflow = 'hidden';\n this.element.style.height = String(this.model.height);\n this.element.style.width = String(this.model.width);\n this.canvas = canvas;\n };\n Overview.prototype.setParent = function (id) {\n var element = document.getElementById(id);\n var instance = 'ej2_instances';\n if (this.parent) {\n var oldparent = this.parent;\n this.parent = null;\n oldparent.setOverview(null, this.id);\n this.removeDocument(this);\n }\n this.parent = this.getDiagram(element, instance);\n if (this.parent) {\n this.parent.setOverview(this);\n }\n };\n Overview.prototype.getDiagram = function (element, instance) {\n var diagram;\n var n = element[instance].length;\n for (var i = 0; i < n; i++) {\n if (hasClass(element[instance][i].element, 'e-diagram')) {\n diagram = element[instance][i];\n break;\n }\n }\n return diagram;\n };\n Overview.prototype.unWireEvents = function () {\n var start = Browser.touchStartEvent;\n var move = Browser.touchMoveEvent;\n var evnt;\n var cancel = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n var isIE11Pointer = Browser.isPointer;\n var wheelEvent = Browser.info.name === 'mozilla' ?\n (isIE11Pointer ? 'mousewheel' : 'DOMMouseScroll') : 'mousewheel';\n var stop = Browser.touchEndEvent;\n EventHandler.remove(this.element, start, this.mouseDown);\n EventHandler.remove(this.element, move, this.mouseMove);\n EventHandler.remove(this.element, stop, this.mouseUp);\n EventHandler.remove(this.element, cancel, this.documentMouseUp);\n EventHandler.remove(window, 'resize', this.windowResize);\n var container = document.getElementById(this.sourceID + 'content');\n if (container) {\n EventHandler.remove(container, 'scroll', this.scrolled);\n }\n };\n Overview.prototype.wireEvents = function () {\n var start = Browser.touchStartEvent;\n var stop = Browser.touchEndEvent;\n var move = Browser.touchMoveEvent;\n var cancel = Browser.isPointer ? 'pointerleave' : 'mouseleave';\n var isIE11Pointer = Browser.isPointer;\n var wheelEvent = Browser.info.name === 'mozilla' ?\n (isIE11Pointer ? 'mousewheel' : 'DOMMouseScroll') : 'mousewheel';\n EventHandler.add(this.element, start, this.mouseDown, this);\n EventHandler.add(this.element, move, this.mouseMove, this);\n EventHandler.add(this.element, stop, this.mouseUp, this);\n EventHandler.add(this.element, cancel, this.documentMouseUp, this);\n EventHandler.add(window, 'resize', this.windowResize, this);\n var container = document.getElementById(this.sourceID + 'content');\n if (container) {\n EventHandler.add(container, 'scroll', this.scrolled, this);\n }\n };\n /**\n * @private\n */\n /**\n * @private\n */\n Overview.prototype.renderDocument = function (view) {\n view.canvas = this.canvas;\n var g = document.getElementById(this.canvas.id + '_svg');\n if (g) {\n g.parentNode.removeChild(g);\n }\n var attr = {\n id: this.canvas.id + '_svg',\n version: '1.1',\n xlink: 'http://www.w3.org/1999/xlink',\n 'class': 'overview_svg'\n };\n var svg = createSvgElement('svg', attr);\n this.svg = svg;\n view.svg = svg;\n view.canvas.appendChild(svg);\n var ovw = document.getElementById(this.element.id);\n var element = ovw;\n var eWidth = element.clientWidth;\n var eHeight = element.clientHeight;\n var bRect = element.getBoundingClientRect();\n // Check for the window resize\n var screenX = (window.screenX < 0) ? window.screenX * -1 : window.screenX;\n var screenY = (window.screenY < 0) ? window.screenY * -1 : window.screenY;\n if (eWidth === 0) {\n eWidth = Math.floor(((window.innerWidth - screenX) - Math.floor(bRect.left)));\n }\n if (eHeight === 0) {\n eHeight = Math.floor(((window.innerHeight - screenY) - Math.floor(bRect.top)));\n }\n svg.setAttribute('width', String(eWidth));\n svg.setAttribute('height', String(eHeight));\n this.model.width = eWidth;\n this.model.height = eHeight;\n var attributes;\n if (!view.diagramLayerDiv) {\n view.diagramLayerDiv = document.createElement('div');\n var container = document.getElementById(this.element.id);\n view.diagramLayer = CanvasRenderer.createCanvas(this.element.id + '_diagramLayer', this.model.width, this.model.height);\n view.diagramLayer.setAttribute('style', 'position:absolute; left:0px; top:0px ');\n view.diagramLayerDiv.appendChild(view.diagramLayer);\n view.canvas.appendChild(view.diagramLayerDiv);\n }\n attributes = {\n 'id': this.element.id + '_diagramLayer_div',\n 'style': 'width:' + this.model.width + 'px; height:' + this.model.height + 'px;position:absolute;top:0px;left:0px'\n };\n setAttributeHtml(view.diagramLayerDiv, attributes);\n this.renderHtmlLayer(view.canvas);\n this.renderNativeLayer(view.canvas, view);\n this.addOverviewRectPanel(view);\n };\n /** @private */\n Overview.prototype.removeDocument = function (view) {\n var svg = document.getElementById(this.canvas.id + '_svg');\n this.canvas.removeChild(svg);\n var htmlLayer = document.getElementById(this.element.id + '_htmlLayer');\n this.canvas.removeChild(htmlLayer);\n var diagramLayer = document.getElementById(this.id + '_diagramLayer_div');\n this.canvas.removeChild(diagramLayer);\n view.diagramLayerDiv = null;\n view.diagramLayer = null;\n };\n Overview.prototype.renderHtmlLayer = function (canvas) {\n var div = document.createElement('div');\n var attr = { 'id': this.element.id + '_htmlLayer', 'class': 'e-html-layer' };\n setAttributeHtml(div, attr);\n var htmlLayer = div;\n div.style.pointerEvents = 'none';\n div.style.position = 'absolute';\n div.style.left = '0px';\n div.style.top = '0px';\n var htmlDiv = document.createElement('div');\n var options = {\n 'id': this.element.id + '_htmlLayer_div',\n 'style': 'position:absolute;top:0px;left:0px;'\n };\n setAttributeHtml(htmlDiv, options);\n htmlLayer.appendChild(htmlDiv);\n canvas.appendChild(htmlLayer);\n return htmlLayer;\n };\n Overview.prototype.renderNativeLayer = function (canvas, view) {\n var nativeLayerSvg = this.parent.createSvg(this.element.id + '_nativeLayer_svg', this.model.width, this.model.height);\n var nativeLayer = createSvgElement('g', { 'id': this.element.id + '_nativeLayer' });\n nativeLayerSvg.appendChild(nativeLayer);\n view.diagramLayerDiv.appendChild(nativeLayerSvg);\n setAttributeSvg(nativeLayerSvg, { 'class': 'e-native-layer' });\n };\n Overview.prototype.addOverviewRectPanel = function (view) {\n var svg = document.getElementById(this.canvas.id + '_overviewsvg');\n if (svg) {\n svg.parentNode.removeChild(svg);\n }\n var attr = ({\n id: this.canvas.id + '_overviewsvg',\n version: '1.1',\n xlink: 'http://www.w3.org/1999/xlink',\n 'style': 'position:absolute;left:0px;top:0px; aria-label:Specifies overview',\n width: this.model.width,\n height: this.model.height\n });\n svg = createSvgElement('svg', attr);\n view.canvas.appendChild(svg);\n var ovw = createSvgElement('g', { 'id': this.id + '_overviewlayer', 'style': 'pointer-events:none' });\n svg.appendChild(ovw);\n var rect = createSvgElement('rect', {\n 'fill': 'transparent', 'width': '100%', 'height': '100%', 'class': 'overviewbackrect',\n 'id': this.canvas.id + 'overviewbackrect'\n });\n rect.setAttribute('style', ' pointer-events: none; ');\n ovw.appendChild(rect);\n var svgDocument = (ovw);\n var g = createSvgElement('g', { 'id': this.canvas.id + 'overviewhandle', 'style': 'pointer-events:all' });\n ovw.appendChild(g);\n var innerrect = createSvgElement('rect', { 'id': this.canvas.id + 'overviewrect', 'fill': 'transparent' });\n g.appendChild(innerrect);\n this.renderOverviewCorner('left', g);\n this.renderOverviewCorner('right', g);\n this.renderOverviewCorner('top', g);\n this.renderOverviewCorner('bottom', g);\n this.renderOverviewCorner('topleft', g);\n this.renderOverviewCorner('topright', g);\n this.renderOverviewCorner('bottomleft', g);\n this.renderOverviewCorner('bottomright', g);\n };\n Overview.prototype.renderOverviewCorner = function (name, parent) {\n var svg = this.svg;\n var shape;\n if (name === 'top' || name === 'bottom' || name === 'right' || name === 'left') {\n shape = 'rect';\n }\n else {\n shape = 'circle';\n }\n var innerrect = createSvgElement(shape, { 'id': this.canvas.id + 'visible' + name });\n parent.appendChild(innerrect);\n var transrect = createSvgElement(shape, {\n 'id': this.canvas.id + name, 'class': 'overviewresizer', 'fill': 'transparent'\n });\n parent.appendChild(transrect);\n };\n Overview.prototype.updateOverviewRectangle = function () {\n var difx = this.currentPoint.x - this.prevPoint.x;\n var dify = this.currentPoint.y - this.prevPoint.y;\n var size = new Size();\n size.width = 0;\n size.height = 0;\n var x = 0;\n var y = 0;\n var w;\n var h;\n switch (this.resizeDirection) {\n case 'left':\n size.width -= difx;\n size.height -= difx / this.viewPortRatio;\n x = difx;\n y = difx / this.viewPortRatio;\n y /= 2;\n break;\n case 'right':\n size.width += difx;\n size.height += difx / this.viewPortRatio;\n y = difx / this.viewPortRatio;\n y /= -2;\n break;\n case 'top':\n size.height -= dify;\n size.width -= dify * this.viewPortRatio;\n y = dify;\n x = dify * this.viewPortRatio;\n x /= 2;\n break;\n case 'bottom':\n size.height += dify;\n size.width += dify * this.viewPortRatio;\n x = dify * this.viewPortRatio;\n x /= -2;\n break;\n case 'topleft':\n if (Math.abs(dify) > Math.abs(difx)) {\n difx = dify * this.viewPortRatio;\n }\n else {\n dify = difx / this.viewPortRatio;\n }\n size.width -= difx;\n size.height -= dify;\n x = difx;\n y = dify;\n break;\n case 'topright':\n if (Math.abs(dify) > Math.abs(difx)) {\n difx = -dify * this.viewPortRatio;\n }\n else {\n dify = -(difx / this.viewPortRatio);\n }\n y = dify;\n size.width += difx;\n size.height -= dify;\n break;\n case 'bottomleft':\n if (Math.abs(dify) > Math.abs(difx)) {\n difx = -dify * this.viewPortRatio;\n }\n else {\n dify = -difx / this.viewPortRatio;\n }\n x = difx;\n size.width -= difx;\n size.height += dify;\n break;\n case 'bottomright':\n if (Math.abs(dify) > Math.abs(difx)) {\n difx = dify * this.viewPortRatio;\n }\n else {\n dify = difx / this.viewPortRatio;\n }\n size.width += difx;\n size.height += dify;\n break;\n }\n this.updateHelper(x, y, size, w, h);\n };\n Overview.prototype.updateHelper = function (difx, dify, size, width, height) {\n var x;\n var y;\n var bounds;\n var svg = this.element.getElementsByTagName('svg')[2];\n var rect = svg.getElementById('helper');\n if (size) {\n bounds = rect.getBBox();\n x = bounds.x + difx;\n y = bounds.y + dify;\n width = bounds.width + size.width;\n height = bounds.height + size.height;\n }\n else {\n var difx_1;\n if (this.currentPoint.x > this.startPoint.x) {\n difx_1 = this.currentPoint.x - this.prevPoint.x;\n }\n else {\n difx_1 = this.prevPoint.x - this.currentPoint.x;\n }\n var dify_1;\n if (this.currentPoint.y > this.startPoint.y) {\n dify_1 = this.currentPoint.y - this.prevPoint.y;\n }\n else {\n dify_1 = this.prevPoint.y - this.currentPoint.y;\n }\n var w = void 0;\n var h = void 0;\n if (Math.abs(dify_1) > Math.abs(difx_1)) {\n difx_1 = this.viewPortRatio * dify_1;\n h = true;\n w = false;\n }\n else {\n dify_1 = difx_1 / this.viewPortRatio;\n w = true;\n h = false;\n }\n bounds = rect.getBBox();\n x = ((this.startPoint.x > this.currentPoint.x) ?\n bounds.x - difx_1 : bounds.x);\n y = ((this.startPoint.y > this.currentPoint.y) ? bounds.y - dify_1 : bounds.y);\n width = bounds.width + difx_1;\n height = bounds.height + dify_1;\n }\n setAttributeSvg(this.helper, {\n 'id': this.helper.id, 'x': x, 'y': y,\n 'width': Math.max(0, width), 'height': Math.max(0, height)\n });\n };\n Overview.prototype.updateOverviewrect = function (x, y, width, height) {\n var rect = document.getElementById(this.canvas.id + 'overviewrect');\n var attr = { x: x, y: y, width: Math.max(1, width), height: Math.max(1, height) };\n setAttributeHtml(rect, attr);\n this.updateOverviewCorner('top', x + 8, y - 2, Math.max(0, width - 16), 2);\n this.updateOverviewCorner('bottom', x + 8, y + height, Math.max(0, width - 16), 2);\n this.updateOverviewCorner('left', x - 2, y + 8, 2, Math.max(0, height - 16));\n this.updateOverviewCorner('right', x + width, y + 8, 2, Math.max(0, height - 16));\n this.updateOverviewCorner('topleft', x, y, 5, 5);\n this.updateOverviewCorner('topright', x + width, y, 5, 5);\n this.updateOverviewCorner('bottomleft', x, y + height, 5, 5);\n this.updateOverviewCorner('bottomright', x + width, y + height, 5, 5);\n };\n Overview.prototype.updateOverviewCorner = function (name, x, y, width, height) {\n var attr;\n var transattr;\n var rectname = 'visible' + name;\n var rect = document.getElementById(this.canvas.id + rectname);\n if (name === 'top' || name === 'bottom' || name === 'right' || name === 'left') {\n attr = { x: x, y: y, width: width, height: height, fill: '#ED1C24' };\n transattr = { x: x - 2, y: y - 2, width: width === 2 ? 4 : width, height: height === 2 ? 4 : height };\n }\n else {\n attr = { cx: x, cy: y, 'r': 4, fill: '#ED1C24' };\n transattr = { cx: x, cy: y, 'r': 6, fill: 'transparent' };\n }\n setAttributeHtml(rect, attr);\n var transrect = document.getElementById(this.canvas.id + name);\n setAttributeHtml(transrect, transattr);\n };\n Overview.prototype.translateOverviewRectangle = function () {\n var offwidth = Number(this.model.width);\n var offheight = Number(this.model.height);\n var difx = this.currentPoint.x - this.prevPoint.x;\n var dify = this.currentPoint.y - this.prevPoint.y;\n var viewPort;\n var zoom = Math.min(this.parent.scroller.viewPortWidth / offwidth, this.parent.scroller.viewPortHeight / offheight);\n var svg = this.element.getElementsByTagName('svg')[2];\n var panel = svg.getElementById(this.canvas.id\n + 'overviewrect');\n var bounds = panel.getBBox();\n var x = bounds.x + difx;\n var y = bounds.y + dify;\n var width = bounds.width;\n var height = bounds.height;\n this.updateOverviewrect(x, y, width, height);\n this.updateParentView(this.parent.scroller.currentZoom, x, y, width, height, null);\n };\n Overview.prototype.renderOverviewRect = function (x, y, width, height) {\n var offwidth = Number(this.model.width);\n var offheight = Number(this.model.height);\n var viewPort;\n var viewwidth = (width / offwidth) * this.contentWidth;\n var viewheight = (height / offheight) * this.contentHeight;\n var zoom = Math.max(this.parent.scroller.viewPortWidth / viewwidth, this.parent.scroller.viewPortHeight / viewheight);\n if (zoom >= 0.25 && zoom <= 30) {\n var point = { x: 0, y: 0 };\n this.updateParentView(zoom, x, y, width, height, point);\n var bounds = this.scrollOverviewRect(this.parent.scroller.horizontalOffset, this.parent.scroller.verticalOffset, this.parent.scroller.currentZoom, true);\n if (this.helper) {\n var panel = this.element.getElementsByTagName('rect')[10];\n var svgRect = panel.getBBox();\n bounds.x = svgRect.x;\n bounds.y = svgRect.y;\n }\n this.updateOverviewrect(bounds.x, bounds.y, bounds.width, bounds.height);\n }\n };\n Overview.prototype.scrollOverviewRect = function (hoffset, voffset, currentZoom, scaled) {\n if (!(this.actionName) || scaled) {\n var offwidth = Number(this.model.width);\n var offheight = Number(this.model.height);\n var scale = Math.min(this.contentWidth / offwidth, this.contentHeight / offheight);\n var bounds = new Rect();\n var x = bounds.x = (hoffset / currentZoom) / scale;\n var y = bounds.y = (voffset / currentZoom) / scale;\n var viewPort = void 0;\n var width = bounds.width = (this.parent.scroller.viewPortWidth / currentZoom) / scale;\n var height = bounds.height = (this.parent.scroller.viewPortHeight / currentZoom) / scale;\n var ratio = this.parent.scroller.viewPortWidth / this.parent.scroller.viewPortHeight;\n if (scaled) {\n var rect = new Rect();\n rect.x = x;\n rect.y = y;\n rect.width = width;\n rect.height = height;\n return rect;\n }\n this.updateOverviewrect(-x, -y, width, height);\n }\n return null;\n };\n Overview.prototype.updateParentView = function (zoom, x, y, width, height, focusPoint) {\n var offwidth = Number(this.model.width);\n var offheight = Number(this.model.height);\n var scalex = this.contentWidth / offwidth;\n var scaley = this.contentHeight / offheight;\n var hoffset = x * scalex * zoom;\n var voffset = y * scaley * zoom;\n var delx;\n var dely;\n var bounds = this.parent.scroller.getPageBounds();\n if (zoom !== 1 || this.actionName === 'pan') {\n delx = -hoffset - this.parent.scroller.horizontalOffset;\n dely = -voffset - this.parent.scroller.verticalOffset;\n }\n if (this.actionName === 'scale' || this.actionName === 'draw') {\n this.parent.scroller.zoom(zoom / this.parent.scroller.currentZoom, delx, dely, focusPoint);\n }\n else {\n this.parent.pan(delx, dely, focusPoint);\n }\n };\n /** @private */\n Overview.prototype.updateView = function (view) {\n var width;\n var height;\n var bounds = this.parent.scroller.getPageBounds();\n width = bounds.width;\n height = bounds.height;\n var offwidth = Number(this.model.width);\n var offheight = Number(this.model.height);\n var scale;\n var w = Math.max(width, this.parent.scroller.viewPortWidth);\n var h = Math.max(height, this.parent.scroller.viewPortHeight);\n this.contentWidth = w = Math.max(w, (offwidth / offheight) * h);\n this.contentHeight = h = Math.max(h, (offheight / offwidth) * w);\n scale = Math.min(offwidth / w, offheight / h);\n var htmlLayer = document.getElementById(this.element.id + '_htmlLayer');\n htmlLayer.style.webkitTransform = 'scale(' + scale + ') translate(' + -bounds.x + 'px,' + (-bounds.y) + 'px)';\n htmlLayer.style.transform = 'scale(' + scale + ') translate(' + -bounds.x + 'px,' + (-bounds.y) + 'px)';\n var ovw = document.getElementById(this.id + '_overviewlayer');\n ovw.setAttribute('transform', 'translate(' + (-bounds.x * scale) + ',' + (-bounds.y * scale) + ')');\n this.horizontalOffset = bounds.x * scale;\n this.verticalOffset = bounds.y * scale;\n var canvas = document.getElementById('overview_diagramLayer');\n var nativeLayer = getNativeLayer(this.element.id);\n var context = canvas.getContext('2d');\n var widthratio = (Number(this.model.width) / this.contentWidth);\n var heightratio = (Number(this.model.height) / this.contentHeight);\n widthratio = Math.min(widthratio, heightratio);\n nativeLayer.setAttribute('transform', 'translate('\n + (0) + ',' + (0) + '),scale('\n + widthratio + ')');\n context.setTransform(widthratio, 0, 0, widthratio, 0, 0);\n context.fillStyle = 'red';\n this.scrollOverviewRect(this.parent.scroller.horizontalOffset, this.parent.scroller.verticalOffset, this.parent.scroller.currentZoom);\n };\n // region - Event Handlers\n Overview.prototype.scrolled = function (evt) {\n if (this.event) {\n var bounds = this.scrollOverviewRect(this.parent.scroller.horizontalOffset, this.parent.scroller.verticalOffset, this.parent.scroller.currentZoom, true);\n this.updateOverviewrect(-bounds.x, -bounds.y, bounds.width, bounds.height);\n }\n };\n Overview.prototype.updateCursor = function (evt) {\n if (hasClass(evt.target, ('overviewresizer'))) {\n switch (evt.target.id) {\n case this.canvas.id + 'left':\n this.canvas.style.cursor = 'w-resize';\n break;\n case this.canvas.id + 'right':\n this.canvas.style.cursor = 'e-resize';\n break;\n case this.canvas.id + 'top':\n this.canvas.style.cursor = 'n-resize';\n break;\n case this.canvas.id + 'bottom':\n this.canvas.style.cursor = 's-resize';\n break;\n case this.canvas.id + 'topleft':\n this.canvas.style.cursor = 'nw-resize';\n break;\n case this.canvas.id + 'topright':\n this.canvas.style.cursor = 'ne-resize';\n break;\n case this.canvas.id + 'bottomleft':\n this.canvas.style.cursor = 'sw-resize';\n break;\n case this.canvas.id + 'bottomright':\n this.canvas.style.cursor = 'se-resize';\n break;\n }\n }\n else {\n this.canvas.style.cursor = 'default';\n }\n };\n Overview.prototype.mouseMove = function (evt) {\n this.event = false;\n this.updateCursor(evt);\n this.currentPoint = this.mousePosition(evt);\n if (this.actionName) {\n switch (this.actionName) {\n case 'draw':\n if (!this.inAction && (this.startPoint.x !== this.currentPoint.x || this.startPoint.y !== this.currentPoint.y)) {\n this.initHelper();\n this.inAction = true;\n }\n if (this.inAction) {\n this.updateHelper();\n }\n break;\n case 'scale':\n if (!this.inAction) {\n this.initHelper();\n this.inAction = true;\n }\n this.updateOverviewRectangle();\n break;\n case 'pan':\n if ((this.startPoint.x !== this.currentPoint.x || this.startPoint.y === this.currentPoint.y) || this.inAction) {\n this.inAction = true;\n this.translateOverviewRectangle();\n }\n break;\n }\n }\n this.prevPoint = this.currentPoint;\n };\n Overview.prototype.documentMouseUp = function (evt) {\n this.inAction = false;\n this.actionName = '';\n if (this.helper) {\n this.helper.parentNode.removeChild(this.helper);\n this.helper = null;\n }\n this.event = true;\n document.getElementById(this.canvas.id + 'overviewhandle').style.pointerEvents = 'all';\n };\n Overview.prototype.windowResize = function (evt) {\n var _this = this;\n if (this.resizeTo) {\n clearTimeout(this.resizeTo);\n }\n this.resizeTo = setTimeout(function () {\n var element = document.getElementById(_this.element.id);\n var bRect = element.getBoundingClientRect();\n _this.model.width = bRect.width;\n _this.model.height = bRect.height;\n _this.renderCanvas();\n _this.setParent(_this.sourceID);\n }, 10);\n return false;\n };\n /** @private */\n Overview.prototype.mouseDown = function (evt) {\n if (evt.target.id === this.canvas.id + '_overviewsvg') {\n this.actionName = 'draw';\n }\n if (evt.target.id === this.canvas.id + 'overviewrect') {\n this.actionName = 'pan';\n }\n if (hasClass(evt.target, 'overviewresizer')) {\n this.actionName = 'scale';\n switch (evt.target.id) {\n case this.canvas.id + 'left':\n this.resizeDirection = 'left';\n break;\n case this.canvas.id + 'right':\n this.resizeDirection = 'right';\n break;\n case this.canvas.id + 'top':\n this.resizeDirection = 'top';\n break;\n case this.canvas.id + 'bottom':\n this.resizeDirection = 'bottom';\n break;\n case this.canvas.id + 'topleft':\n this.resizeDirection = 'topleft';\n break;\n case this.canvas.id + 'topright':\n this.resizeDirection = 'topright';\n break;\n case this.canvas.id + 'bottomleft':\n this.resizeDirection = 'bottomleft';\n break;\n case this.canvas.id + 'bottomright':\n this.resizeDirection = 'bottomright';\n break;\n }\n }\n this.startPoint = this.prevPoint = this.mousePosition(evt);\n this.viewPortRatio = this.parent.scroller.viewPortWidth / this.parent.scroller.viewPortHeight;\n var overViewHandle = document.getElementById(this.canvas.id + 'overviewhandle');\n overViewHandle.style.pointerEvents = 'none';\n };\n Overview.prototype.mouseUp = function (evt) {\n this.currentPoint = this.mousePosition(evt);\n var offwidth = Number(this.model.width);\n var offheight = Number(this.model.height);\n if (this.actionName) {\n if ((this.startPoint.x !== this.currentPoint.x || this.startPoint.y !== this.currentPoint.y)) {\n if (this.actionName === 'pan') {\n var i = 0;\n }\n else {\n if (this.helper) {\n var bounds = (this.element.getElementsByTagName('rect')[10]).getBBox();\n this.resizeDirection = this.resizeDirection || '';\n var x = bounds.x;\n var y = bounds.y;\n var width = bounds.width;\n var height = bounds.height;\n var adjust = this.resizeDirection === 'topleft' || this.resizeDirection === 'topright' ||\n this.resizeDirection === 'bottomleft' || this.resizeDirection === 'bottomright';\n this.renderOverviewRect(x, y, width, height);\n }\n }\n }\n else {\n if (evt.target.id === this.canvas.id + '_overviewsvg' || evt.target.id === 'helper') {\n var svg = this.element.getElementsByTagName('svg')[2];\n var g = svg.getElementById(this.canvas.id\n + 'overviewrect');\n var bounds = g.getBBox();\n var width = bounds.width;\n var height = bounds.height;\n this.inAction = true;\n this.actionName = 'pan';\n this.renderOverviewRect(this.currentPoint.x - width / 2, this.currentPoint.y - height / 2, width, height);\n this.inAction = false;\n }\n }\n }\n if (this.helper) {\n this.helper.parentNode.removeChild(this.helper);\n this.helper = null;\n }\n this.actionName = '';\n this.startPoint = null;\n this.currentPoint = null;\n this.prevPoint = null;\n this.helper = null;\n this.viewPortRatio = 1;\n this.resizeDirection = '';\n this.inAction = false;\n this.event = true;\n document.getElementById(this.canvas.id + 'overviewhandle').style.pointerEvents = 'all';\n };\n Overview.prototype.initHelper = function () {\n var g = this.element.getElementsByTagName('svg')[2];\n var scale = this.parent.scroller.currentZoom;\n var x = this.startPoint.x;\n var y = this.startPoint.y;\n var width = 1;\n var height = 1;\n if (this.actionName === 'scale') {\n var rect = g.\n getElementById(this.canvas.id + 'overviewrect');\n var bounds = rect.getBBox();\n x = bounds.x;\n y = bounds.y;\n width = bounds.width;\n height = bounds.height;\n }\n var selectionRect = createSvgElement('rect', {\n 'id': 'helper', x: x, y: y, width: width, height: height,\n 'fill': 'transparent', 'stroke': 'gray', 'stroke-dasharray': '2 2', 'shape-rendering': 'crispEdges'\n });\n var overviewLayer = g.getElementById(this.id + '_overviewlayer');\n overviewLayer.appendChild(selectionRect);\n this.helper = selectionRect;\n };\n Overview.prototype.mousePosition = function (evt) {\n var touchArg;\n var offsetX;\n var offsetY;\n if (evt.type.indexOf('touch') !== -1) {\n touchArg = evt;\n var pageX = touchArg.changedTouches[0].clientX;\n var pageY = touchArg.changedTouches[0].clientY;\n offsetX = pageX - this.element.offsetLeft;\n offsetY = pageY - this.element.offsetTop;\n }\n else {\n offsetX = evt.clientX;\n offsetY = evt.clientY;\n }\n var boundingRect = this.element.getBoundingClientRect();\n offsetX = offsetX - boundingRect.left;\n offsetY = offsetY - boundingRect.top;\n return { x: offsetX + this.horizontalOffset, y: offsetY + this.verticalOffset };\n };\n // end region - Event handlers\n /**\n * To destroy the Overview\n * @return {void}\n * @private\n */\n Overview.prototype.destroy = function () {\n this.unWireEvents();\n this.notify('destroy', {});\n _super.prototype.destroy.call(this);\n if (document.getElementById(this.element.id)) {\n this.element.classList.remove('e-overview');\n var content = document.getElementById(this.element.id + '_canvas');\n if (content) {\n this.element.removeChild(content);\n }\n }\n this.parent.views.splice(this.parent.views.indexOf(this.id), 1);\n this.diagramLayerDiv = null;\n this.canvas = null;\n this.parent = null;\n };\n /**\n * Get module name.\n */\n Overview.prototype.getModuleName = function () {\n /**\n * Returns the module name\n */\n return 'Overview';\n };\n __decorate([\n Property('100%')\n ], Overview.prototype, \"width\", void 0);\n __decorate([\n Property('100%')\n ], Overview.prototype, \"height\", void 0);\n __decorate([\n Property('')\n ], Overview.prototype, \"sourceID\", void 0);\n __decorate([\n Event()\n ], Overview.prototype, \"created\", void 0);\n return Overview;\n}(Component));\nexport { Overview };\n","import * as index from '@syncfusion/ej2-diagrams';\nindex.Diagram.Inject( index.HierarchicalTree,index.MindMap,index.RadialTree,index.ComplexHierarchicalTree,index.DataBinding,index.Snapping,index.PrintAndExport,index.BpmnDiagrams,index.SymmetricLayout,index.ConnectorBridging,index.UndoRedo,index.LayoutAnimation,index.DiagramContextMenu,index.ConnectorEditing);\nexport * from '@syncfusion/ej2-diagrams';\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar Dictionary = /** @class */ (function () {\n function Dictionary() {\n this.keysInternal = [];\n this.valuesInternal = [];\n this.item = [];\n }\n Object.defineProperty(Dictionary.prototype, \"length\", {\n /**\n * @private\n */\n get: function () {\n return this.keysInternal.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Dictionary.prototype, \"keys\", {\n /**\n * @private\n */\n get: function () {\n return this.getItem();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n Dictionary.prototype.getItem = function () {\n this.item = [];\n for (var i = 0; i < this.keysInternal.length; i++) {\n this.item.push(this.keysInternal[i]);\n }\n return this.item;\n };\n /**\n * @private\n */\n Dictionary.prototype.add = function (key, value) {\n if (isNullOrUndefined(key)) {\n throw new ReferenceError('Provided key or value is not valid.');\n }\n var index = this.keysInternal.indexOf(key);\n // if (index < 0 || index > this.keysInternal.length - 1) {\n if (index < 0) {\n this.keysInternal.push(key);\n this.valuesInternal.push(value);\n }\n return 1;\n // else {\n // throw new RangeError('An item with the same key has already been added.');\n // }\n };\n /**\n * @private\n */\n Dictionary.prototype.get = function (key) {\n if (isNullOrUndefined(key)) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.keysInternal.indexOf(key);\n if (index < 0 || index > this.keysInternal.length - 1) {\n throw new RangeError('No item with the specified key has been added.');\n }\n else {\n return this.valuesInternal[index];\n }\n };\n /**\n * @private\n */\n Dictionary.prototype.set = function (key, value) {\n if (isNullOrUndefined(key)) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.keysInternal.indexOf(key);\n if (index < 0 || index > this.keysInternal.length - 1) {\n throw new RangeError('No item with the specified key has been added.');\n }\n else {\n this.valuesInternal[index] = value;\n }\n };\n /**\n * @private\n */\n Dictionary.prototype.remove = function (key) {\n if (isNullOrUndefined(key)) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.keysInternal.indexOf(key);\n if (index < 0 || index > this.keysInternal.length - 1) {\n throw new RangeError('No item with the specified key has been added.');\n }\n else {\n this.keysInternal.splice(index, 1);\n this.valuesInternal.splice(index, 1);\n return true;\n }\n };\n /**\n * @private\n */\n Dictionary.prototype.containsKey = function (key) {\n if (isNullOrUndefined(key)) {\n throw new ReferenceError('Provided key is not valid.');\n }\n var index = this.keysInternal.indexOf(key);\n if (index < 0 || index > this.keysInternal.length - 1) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n Dictionary.prototype.clear = function () {\n this.keysInternal = [];\n this.valuesInternal = [];\n };\n /**\n * @private\n */\n Dictionary.prototype.destroy = function () {\n this.clear();\n this.keysInternal = undefined;\n this.valuesInternal = undefined;\n };\n return Dictionary;\n}());\nexport { Dictionary };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from './dictionary';\n/**\n * @private\n */\nvar WUniqueFormat = /** @class */ (function () {\n function WUniqueFormat(type) {\n this.referenceCount = 0;\n this.uniqueFormatType = type;\n this.propertiesHash = new Dictionary();\n }\n /**\n * @private\n */\n WUniqueFormat.prototype.isEqual = function (source, property, modifiedValue) {\n var isEqual = false;\n switch (this.uniqueFormatType) {\n case 1:\n isEqual = this.isBorderEqual(source, property, modifiedValue);\n break;\n case 2:\n isEqual = this.isCharacterFormatEqual(source, property, modifiedValue);\n break;\n case 3:\n isEqual = this.isParagraphFormatEqual(source, property, modifiedValue);\n break;\n case 4:\n isEqual = this.isCellFormatEqual(source, property, modifiedValue);\n break;\n case 5:\n isEqual = this.isShadingEqual(source, property, modifiedValue);\n break;\n case 6:\n isEqual = this.isRowFormatEqual(source, property, modifiedValue);\n break;\n case 7:\n isEqual = this.isListFormatEqual(source, property, modifiedValue);\n break;\n case 8:\n isEqual = this.isTableFormatEqual(source, property, modifiedValue);\n break;\n case 9:\n isEqual = this.isListLevelEqual(source, property, modifiedValue);\n break;\n case 10:\n isEqual = this.isSectionFormatEqual(source, property, modifiedValue);\n break;\n default:\n break;\n }\n return isEqual;\n };\n // tslint:disable-next-line:max-line-length\n WUniqueFormat.prototype.isNotEqual = function (property, source, modifiedProperty, modifiedValue, uniqueFormatType) {\n var targetValue = undefined;\n var propertyType = WUniqueFormat.getPropertyType(uniqueFormatType, property);\n if (this.propertiesHash.containsKey(propertyType)) {\n targetValue = this.propertiesHash.get(propertyType);\n }\n var sourceValue = undefined;\n if (property === modifiedProperty) {\n sourceValue = modifiedValue;\n }\n else if (source.containsKey(propertyType)) {\n sourceValue = source.get(propertyType);\n }\n // tslint:disable-next-line:max-line-length\n if (!(targetValue === sourceValue || (!isNullOrUndefined(targetValue) && !isNullOrUndefined(sourceValue) && targetValue === sourceValue))) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n WUniqueFormat.getPropertyType = function (uniqueFormatType, property) {\n var type = 0;\n switch (uniqueFormatType) {\n case 1:\n type = this.getBorderPropertyType(property);\n break;\n case 2:\n type = this.getCharacterFormatPropertyType(property);\n break;\n case 3:\n type = this.getParaFormatPropertyType(property);\n break;\n case 4:\n type = this.getCellFormatPropertyType(property);\n break;\n case 5:\n type = this.getShadingPropertyType(property);\n break;\n case 6:\n type = this.getRowFormatType(property);\n break;\n case 7:\n type = this.getListFormatType(property);\n break;\n case 8:\n type = this.getTableFormatType(property);\n break;\n case 9:\n type = this.getListLevelType(property);\n break;\n case 10:\n type = this.getSectionFormatType(property);\n break;\n default:\n break;\n }\n return type;\n };\n WUniqueFormat.getRowFormatType = function (property) {\n if (property === 'allowBreakAcrossPages') {\n return 1;\n }\n if (property === 'isHeader') {\n return 2;\n }\n if (property === 'height') {\n return 3;\n }\n if (property === 'heightType') {\n return 4;\n }\n if (property === 'gridBefore') {\n return 5;\n }\n if (property === 'gridBeforeWidth') {\n return 6;\n }\n if (property === 'gridBeforeWidthType') {\n return 7;\n }\n if (property === 'gridAfter') {\n return 8;\n }\n if (property === 'gridAfterWidth') {\n return 9;\n }\n if (property === 'gridAfterWidthType') {\n return 10;\n }\n return 0;\n };\n WUniqueFormat.getListFormatType = function (property) {\n if (property === 'listId') {\n return 1;\n }\n if (property === 'listLevelNumber') {\n return 2;\n }\n return 0;\n };\n WUniqueFormat.getTableFormatType = function (property) {\n if (property === 'leftMargin') {\n return 1;\n }\n if (property === 'rightMargin') {\n return 2;\n }\n if (property === 'topMargin') {\n return 3;\n }\n if (property === 'bottomMargin') {\n return 4;\n }\n if (property === 'cellSpacing') {\n return 5;\n }\n if (property === 'leftIndent') {\n return 6;\n }\n if (property === 'tableAlignment') {\n return 7;\n }\n if (property === 'preferredWidth') {\n return 8;\n }\n if (property === 'preferredWidthType') {\n return 9;\n }\n return 0;\n };\n WUniqueFormat.getListLevelType = function (property) {\n if (property === 'listLevelPattern') {\n return 1;\n }\n if (property === 'startAt') {\n return 2;\n }\n if (property === 'followCharacter') {\n return 3;\n }\n if (property === 'numberFormat') {\n return 4;\n }\n if (property === 'restartLevel') {\n return 5;\n }\n return 0;\n };\n WUniqueFormat.getShadingPropertyType = function (property) {\n if (property === 'backgroundColor') {\n return 1;\n }\n if (property === 'foregroundColor') {\n return 2;\n }\n if (property === 'textureStyle') {\n return 3;\n }\n return 0;\n };\n WUniqueFormat.getCellFormatPropertyType = function (property) {\n if (property === 'leftMargin') {\n return 1;\n }\n if (property === 'rightMargin') {\n return 2;\n }\n if (property === 'topMargin') {\n return 3;\n }\n if (property === 'bottomMargin') {\n return 4;\n }\n if (property === 'columnSpan') {\n return 5;\n }\n if (property === 'rowSpan') {\n return 6;\n }\n if (property === 'verticalAlignment') {\n return 7;\n }\n if (property === 'preferredWidthType') {\n return 8;\n }\n if (property === 'preferredWidth') {\n return 9;\n }\n if (property === 'cellWidth') {\n return 10;\n }\n return 0;\n };\n WUniqueFormat.getBorderPropertyType = function (property) {\n if (property === 'color') {\n return 1;\n }\n if (property === 'lineStyle') {\n return 2;\n }\n if (property === 'lineWidth') {\n return 3;\n }\n if (property === 'shadow') {\n return 4;\n }\n if (property === 'space') {\n return 5;\n }\n if (property === 'hasNoneStyle') {\n return 6;\n }\n return 0;\n };\n WUniqueFormat.getCharacterFormatPropertyType = function (property) {\n if (property === 'fontColor') {\n return 1;\n }\n if (property === 'fontFamily') {\n return 2;\n }\n if (property === 'fontSize') {\n return 3;\n }\n if (property === 'bold') {\n return 4;\n }\n if (property === 'italic') {\n return 5;\n }\n if (property === 'underline') {\n return 6;\n }\n if (property === 'strikethrough') {\n return 7;\n }\n if (property === 'baselineAlignment') {\n return 8;\n }\n if (property === 'highlightColor') {\n return 9;\n }\n return 0;\n };\n WUniqueFormat.getParaFormatPropertyType = function (property) {\n if (property === 'leftIndent') {\n return 1;\n }\n if (property === 'rightIndent') {\n return 2;\n }\n if (property === 'firstLineIndent') {\n return 3;\n }\n if (property === 'textAlignment') {\n return 4;\n }\n if (property === 'beforeSpacing') {\n return 5;\n }\n if (property === 'afterSpacing') {\n return 6;\n }\n if (property === 'lineSpacing') {\n return 7;\n }\n if (property === 'lineSpacingType') {\n return 8;\n }\n if (property === 'outlineLevel') {\n return 9;\n }\n return 0;\n };\n WUniqueFormat.getSectionFormatType = function (property) {\n if (property === 'headerDistance') {\n return 1;\n }\n if (property === 'footerDistance') {\n return 2;\n }\n if (property === 'differentFirstPage') {\n return 3;\n }\n if (property === 'differentOddAndEvenPages') {\n return 4;\n }\n if (property === 'pageWidth') {\n return 5;\n }\n if (property === 'pageHeight') {\n return 6;\n }\n if (property === 'leftMargin') {\n return 7;\n }\n if (property === 'topMargin') {\n return 8;\n }\n if (property === 'rightMargin') {\n return 9;\n }\n if (property === 'bottomMargin') {\n return 10;\n }\n return 0;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isBorderEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('color', source, modifiedProperty, modifiedValue, 1)) {\n return false;\n }\n if (this.isNotEqual('lineStyle', source, modifiedProperty, modifiedValue, 1)) {\n return false;\n }\n if (this.isNotEqual('lineWidth', source, modifiedProperty, modifiedValue, 1)) {\n return false;\n }\n if (this.isNotEqual('shadow', source, modifiedProperty, modifiedValue, 1)) {\n return false;\n }\n if (this.isNotEqual('space', source, modifiedProperty, modifiedValue, 1)) {\n return false;\n }\n if (this.isNotEqual('hasNoneStyle', source, modifiedProperty, modifiedValue, 1)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isCharacterFormatEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('fontColor', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('fontFamily', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('fontSize', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('bold', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('italic', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('underline', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('strikethrough', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('baselineAlignment', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n if (this.isNotEqual('highlightColor', source, modifiedProperty, modifiedValue, 2)) {\n return false;\n }\n return true;\n };\n WUniqueFormat.prototype.isParagraphFormatEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('leftIndent', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('rightIndent', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('firstLineIndent', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('textAlignment', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('beforeSpacing', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('afterSpacing', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('lineSpacing', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('lineSpacingType', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n if (this.isNotEqual('outlineLevel', source, modifiedProperty, modifiedValue, 3)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isCellFormatEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('leftMargin', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('rightMargin', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('topMargin', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('bottomMargin', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('columnSpan', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('rowSpan', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('verticalAlignment', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('preferredWidthType', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('preferredWidth', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n if (this.isNotEqual('cellWidth', source, modifiedProperty, modifiedValue, 4)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isShadingEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('backgroundColor', source, modifiedProperty, modifiedValue, 5)) {\n return false;\n }\n if (this.isNotEqual('foregroundColor', source, modifiedProperty, modifiedValue, 5)) {\n return false;\n }\n if (this.isNotEqual('textureStyle', source, modifiedProperty, modifiedValue, 5)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isRowFormatEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('allowBreakAcrossPages', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('isHeader', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('height', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('heightType', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('gridBefore', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('gridBeforeWidth', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('gridBeforeWidthType', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('gridAfter', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('gridAfterWidth', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n if (this.isNotEqual('gridAfterWidthType', source, modifiedProperty, modifiedValue, 6)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isListFormatEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('listId', source, modifiedProperty, modifiedValue, 7)) {\n return false;\n }\n if (this.isNotEqual('listLevelNumber', source, modifiedProperty, modifiedValue, 7)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isTableFormatEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('leftMargin', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('rightMargin', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('topMargin', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('bottomMargin', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('cellSpacing', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('leftIndent', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('tableAlignment', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('preferredWidth', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n if (this.isNotEqual('preferredWidthType', source, modifiedProperty, modifiedValue, 8)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isListLevelEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('listLevelPattern', source, modifiedProperty, modifiedValue, 9)) {\n return false;\n }\n if (this.isNotEqual('startAt', source, modifiedProperty, modifiedValue, 9)) {\n return false;\n }\n if (this.isNotEqual('followCharacter', source, modifiedProperty, modifiedValue, 9)) {\n return false;\n }\n if (this.isNotEqual('numberFormat', source, modifiedProperty, modifiedValue, 9)) {\n return false;\n }\n if (this.isNotEqual('restartLevel', source, modifiedProperty, modifiedValue, 9)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.isSectionFormatEqual = function (source, modifiedProperty, modifiedValue) {\n if (this.isNotEqual('headerDistance', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('footerDistance', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('differentFirstPage', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('differentOddAndEvenPages', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('pageWidth', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('pageHeight', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('leftMargin', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('topMargin', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('rightMargin', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n if (this.isNotEqual('bottomMargin', source, modifiedProperty, modifiedValue, 10)) {\n return false;\n }\n return true;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.cloneItems = function (format, property, value, uniqueFormatType) {\n var propertyType = WUniqueFormat.getPropertyType(uniqueFormatType, property);\n var keys = format.propertiesHash.getItem();\n for (var i = 0; i < keys.length; i++) {\n if (keys[i] === propertyType) {\n this.propertiesHash.add(propertyType, value);\n }\n else {\n this.propertiesHash.add(keys[i], format.propertiesHash.get(keys[i]));\n }\n }\n if (!format.propertiesHash.containsKey(propertyType)) {\n this.propertiesHash.add(propertyType, value);\n }\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.mergeProperties = function (format) {\n var hash = format.cloneProperties();\n var keys = this.propertiesHash.keys;\n for (var i = 0; i < keys.length; i++) {\n if (!hash.containsKey(keys[i])) {\n hash.add(keys[i], this.propertiesHash.get(keys[i]));\n }\n }\n return hash;\n };\n /**\n * @private\n */\n WUniqueFormat.prototype.cloneProperties = function () {\n var hash = new Dictionary();\n var keys = this.propertiesHash.keys;\n for (var i = 0; i < keys.length; i++) {\n hash.add(keys[i], this.propertiesHash.get(keys[i]));\n }\n return hash;\n };\n // public cloneItemsInternal(format: WUniqueFormat): void {\n // let keys: number[] = format.propertiesHash.getItem();\n // for (let i: number = 0; i < keys.length; i++) {\n // this.propertiesHash.add(keys[i], format.propertiesHash.get(keys[i]));\n // }\n // this.referenceCount = format.referenceCount;\n // }\n /**\n * @private\n */\n WUniqueFormat.prototype.destroy = function () {\n if (!isNullOrUndefined(this.propertiesHash)) {\n this.propertiesHash.destroy();\n }\n this.propertiesHash = undefined;\n this.referenceCount = undefined;\n this.uniqueFormatType = undefined;\n };\n return WUniqueFormat;\n}());\nexport { WUniqueFormat };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { WUniqueFormat } from './unique-format';\n/**\n * @private\n */\nvar WUniqueFormats = /** @class */ (function () {\n function WUniqueFormats() {\n this.items = [];\n }\n /**\n * @private\n */\n WUniqueFormats.prototype.addUniqueFormat = function (format, type) {\n var matchedFormat = undefined;\n for (var i = 0; i < this.items.length; i++) {\n if (this.items[i].isEqual(format, undefined, undefined)) {\n matchedFormat = this.items[i];\n break;\n }\n }\n if (isNullOrUndefined(matchedFormat)) {\n matchedFormat = new WUniqueFormat(type);\n matchedFormat.propertiesHash = format;\n matchedFormat.referenceCount = 1;\n this.items.push(matchedFormat);\n }\n else {\n matchedFormat.referenceCount++;\n }\n return matchedFormat;\n };\n /**\n * @private\n */\n WUniqueFormats.prototype.updateUniqueFormat = function (uniqueFormat, property, value) {\n var matchedFormat = undefined;\n for (var i = 0; i < this.items.length; i++) {\n if (this.items[i].isEqual(uniqueFormat.propertiesHash, property, value)) {\n matchedFormat = this.items[i];\n break;\n }\n }\n if (isNullOrUndefined(matchedFormat)) {\n matchedFormat = new WUniqueFormat(uniqueFormat.uniqueFormatType);\n matchedFormat.cloneItems(uniqueFormat, property, value, uniqueFormat.uniqueFormatType);\n matchedFormat.referenceCount = 1;\n this.items.push(matchedFormat);\n }\n else {\n matchedFormat.referenceCount++;\n }\n this.remove(uniqueFormat);\n uniqueFormat = undefined;\n return matchedFormat;\n };\n /**\n * @private\n */\n WUniqueFormats.prototype.remove = function (uniqueFormat) {\n uniqueFormat.referenceCount--;\n if (uniqueFormat.referenceCount <= 0) {\n this.items.splice(this.items.indexOf(uniqueFormat), 1);\n uniqueFormat.destroy();\n uniqueFormat = undefined;\n }\n };\n /**\n * @private\n */\n WUniqueFormats.prototype.clear = function () {\n if (isNullOrUndefined(this.items)) {\n for (var i = 0; i < this.items.length; i++) {\n this.items[i].destroy();\n }\n }\n this.items = [];\n };\n /**\n * @private\n */\n WUniqueFormats.prototype.destroy = function () {\n this.clear();\n this.items = undefined;\n };\n return WUniqueFormats;\n}());\nexport { WUniqueFormats };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, Property, NotifyPropertyChanges, Event } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, L10n, setCulture, Browser } from '@syncfusion/ej2-base';\nimport { Save } from '@syncfusion/ej2-file-utils';\nimport { LayoutViewer, PageLayoutViewer, BulletsAndNumberingDialog } from './index';\nimport { Print } from './index';\nimport { BodyWidget, ParagraphWidget } from './index';\nimport { WSectionFormat, WParagraphFormat, WCharacterFormat } from './index';\nimport { SfdtReader } from './index';\nimport { Selection } from './index';\nimport { Editor, EditorHistory } from './index';\nimport { WStyles } from './index';\nimport { Search } from './index';\nimport { OptionsPane } from './index';\nimport { WordExport } from './index';\nimport { TextExport } from './index';\nimport { ContextMenu } from './index';\nimport { ImageResizer } from './index';\nimport { SfdtExport } from './index';\nimport { HyperlinkDialog, TableDialog, BookmarkDialog, StylesDialog, TableOfContentsDialog } from './index';\nimport { PageSetupDialog, ParagraphDialog, ListDialog, StyleDialog, FontDialog } from './index';\nimport { TablePropertiesDialog, BordersAndShadingDialog, CellOptionsDialog, TableOptionsDialog } from './index';\n/**\n * The Document editor component is used to draft, save or print rich text contents as page by page.\n */\nvar DocumentEditor = /** @class */ (function (_super) {\n __extends(DocumentEditor, _super);\n /**\n * Initialize the constructor of DocumentEditor\n */\n function DocumentEditor(options, element) {\n var _this = _super.call(this, options, element) || this;\n //Internal Variable\n _this.enableHeaderFooterIn = false;\n /**\n * @private\n */\n _this.isShiftingEnabled = false;\n /**\n * @private\n */\n _this.isLayoutEnabled = true;\n /**\n * @private\n */\n _this.isPastingContent = false;\n /**\n * @private\n */\n _this.parser = undefined;\n _this.disableHistoryIn = false;\n /**\n * @private\n */\n _this.findResultsList = undefined;\n /**\n * Gets or sets the name of the document.\n */\n _this.documentName = '';\n /**\n * @private\n */\n _this.tablePropertiesDialogModule = undefined;\n /**\n * @private\n */\n _this.bordersAndShadingDialogModule = undefined;\n /**\n * @private\n */\n _this.cellOptionsDialogModule = undefined;\n /**\n * @private\n */\n _this.tableOptionsDialogModule = undefined;\n /**\n * @private\n */\n _this.paragraphDialogModule = undefined;\n /**\n * @private\n */\n _this.imageResizerModule = undefined;\n /**\n * Gets or Sets a value indicating whether holding Ctrl key is required to follow hyperlink on click. The default value is true.\n */\n _this.useCtrlClickToFollowHyperlink = true;\n /**\n * Gets or sets the page outline color.\n */\n _this.pageOutline = '#000000';\n /**\n * Gets or sets a value indicating whether to enable cursor in document editor on read only state or not. The default value is false.\n */\n _this.enableCursorOnReadOnly = false;\n /**\n * Gets or sets a value indicating whether local paste needs to be enabled or not.\n */\n _this.enableLocalPaste = false;\n /**\n * @private\n */\n _this.defaultLocale = {\n 'Table': 'Table',\n 'Row': 'Row',\n 'Cell': 'Cell',\n 'Ok': 'Ok',\n 'Cancel': 'Cancel',\n 'Size': 'Size',\n 'Preferred Width': 'Preferred width',\n 'Points': 'Points',\n 'Percent': 'Percent',\n 'Measure in': 'Measure in',\n 'Alignment': 'Alignment',\n 'Left': 'Left',\n 'Center': 'Center',\n 'Right': 'Right',\n 'Justify': 'Justify',\n 'Indent from left': 'Indent from left',\n 'Borders and Shading': 'Borders and Shading',\n 'Options': 'Options',\n 'Specify height': 'Specify height',\n 'At least': 'At least',\n 'Exactly': 'Exactly',\n 'Row height is': 'Row height is',\n 'Allow row to break across pages': 'Allow row to break across pages',\n 'Repeat as header row at the top of each page': 'Repeat as header row at the top of each page',\n 'Vertical alignment': 'Vertical alignment',\n 'Top': 'Top',\n 'Bottom': 'Bottom',\n 'Default cell margins': 'Default cell margins',\n 'Default cell spacing': 'Default cell spacing',\n 'Allow spacing between cells': 'Allow spacing between cells',\n 'Cell margins': 'Cell margins',\n 'Same as the whole table': 'Same as the whole table',\n 'Borders': 'Borders',\n 'None': 'None',\n 'Single': 'Single',\n 'Dot': 'Dot',\n 'DashSmallGap': 'DashSmallGap',\n 'DashLargeGap': 'DashLargeGap',\n 'DashDot': 'DashDot',\n 'DashDotDot': 'DashDotDot',\n 'Double': 'Double',\n 'Triple': 'Triple',\n 'ThinThickSmallGap': 'ThinThickSmallGap',\n 'ThickThinSmallGap': 'ThickThinSmallGap',\n 'ThinThickThinSmallGap': 'ThinThickThinSmallGap',\n 'ThinThickMediumGap': 'ThinThickMediumGap',\n 'ThickThinMediumGap': 'ThickThinMediumGap',\n 'ThinThickThinMediumGap': 'ThinThickThinMediumGap',\n 'ThinThickLargeGap': 'ThinThickLargeGap',\n 'ThickThinLargeGap': 'ThickThinLargeGap',\n 'ThinThickThinLargeGap': 'ThinThickThinLargeGap',\n 'SingleWavy': 'SingleWavy',\n 'DoubleWavy': 'DoubleWavy',\n 'DashDotStroked': 'DashDotStroked',\n 'Emboss3D': 'Emboss3D',\n 'Engrave3D': 'Engrave3D',\n 'Outset': 'Outset',\n 'Inset': 'Inset',\n 'Thick': 'Thick',\n 'Style': 'Style',\n 'Width': 'Width',\n 'Height': 'Height',\n 'Letter': 'Letter',\n 'Tabloid': 'Tabloid',\n 'Legal': 'Legal',\n 'Statement': 'Statement',\n 'Executive': 'Executive',\n 'A3': 'A3',\n 'A4': 'A4',\n 'A5': 'A5',\n 'B4': 'B4',\n 'B5': 'B5',\n 'Custom Size': 'Custom size',\n 'Different odd and even': 'Different odd and even',\n 'Different first page': 'Different first page',\n 'From edge': 'From edge',\n 'Header': 'Header',\n 'Footer': 'Footer',\n 'Margin': 'Margins',\n 'Paper': 'Paper',\n 'Layout': 'Layout',\n 'Orientation': 'Orientation',\n 'Landscape': 'Landscape',\n 'Portrait': 'Portrait',\n 'Table Of Contents': 'Table Of Contents',\n 'Show page numbers': 'Show page numbers',\n 'Right align page numbers': 'Right align page numbers',\n 'Nothing': 'Nothing',\n 'Tab leader': 'Tab leader',\n 'Show levels': 'Show levels',\n 'Use hyperlinks instead of page numbers': 'Use hyperlinks instead of page numbers',\n 'Build table of contents from': 'Build table of contents from',\n 'Styles': 'Styles',\n 'Available styles': 'Available styles',\n 'TOC level': 'TOC level',\n 'Heading': 'Heading',\n 'List Paragraph': 'List Paragraph',\n 'Normal': 'Normal',\n 'Outline levels': 'Outline levels',\n 'Table entry fields': 'Table entry fields',\n 'Modify': 'Modify',\n 'Color': 'Color',\n 'Setting': 'Setting',\n 'Box': 'Box',\n 'All': 'All',\n 'Custom': 'Custom',\n 'Preview': 'Preview',\n 'Shading': 'Shading',\n 'Fill': 'Fill',\n 'Apply To': 'Apply to',\n 'Table Properties': 'Table Properties',\n 'Cell Options': 'Cell Options',\n 'Table Options': 'Table Options',\n 'Insert Table': 'Insert Table',\n 'Number of columns': 'Number of columns',\n 'Number of rows': 'Number of rows',\n 'Text to display': 'Text to display',\n 'Address': 'Address',\n 'Insert Hyperlink': 'Insert Hyperlink',\n 'Edit Hyperlink': 'Edit Hyperlink',\n 'Insert': 'Insert',\n 'General': 'General',\n 'Indentation': 'Indentation',\n 'Before text': 'Before text',\n 'Special': 'Special',\n 'First line': 'First line',\n 'Hanging': 'Hanging',\n 'After text': 'After text',\n 'By': 'By',\n 'Before': 'Before',\n 'Line Spacing': 'Line spacing',\n 'After': 'After',\n 'At': 'At',\n 'Multiple': 'Multiple',\n 'Spacing': 'Spacing',\n 'Define new Multilevel list': 'Define new Multilevel list',\n 'List level': 'List level',\n 'Choose level to modify': 'Choose level to modify',\n 'Level': 'Level',\n 'Number format': 'Number format',\n 'Number style for this level': 'Number style for this level',\n 'Enter formatting for number': 'Enter formatting for number',\n 'Start at': 'Start at',\n 'Restart list after': 'Restart list after',\n 'Position': 'Position',\n 'Text indent at': 'Text indent at',\n 'Aligned at': 'Aligned at',\n 'Follow number with': 'Follow number with',\n 'Tab character': 'Tab character',\n 'Space': 'Space',\n 'Arabic': 'Arabic',\n 'UpRoman': 'UpRoman',\n 'LowRoman': 'LowRoman',\n 'UpLetter': 'UpLetter',\n 'LowLetter': 'LowLetter',\n 'Number': 'Number',\n 'Leading zero': 'Leading zero',\n 'Bullet': 'Bullet',\n 'Ordinal': 'Ordinal',\n 'Ordinal Text': 'Ordinal Text',\n 'For East': 'For East',\n 'No Restart': 'No Restart',\n 'Font': 'Font',\n 'Font style': 'Font style',\n 'Underline style': 'Underline style',\n 'Font color': 'Font color',\n 'Effects': 'Effects',\n 'Strikethrough': 'Strikethrough',\n 'Superscript': 'Superscript',\n 'Subscript': 'Subscript',\n 'Double strikethrough': 'Double strikethrough',\n 'Regular': 'Regular',\n 'Bold': 'Bold',\n 'Italic': 'Italic',\n 'Cut': 'Cut',\n 'Copy': 'Copy',\n 'Paste': 'Paste',\n 'Hyperlink': 'Hyperlink',\n 'Open Hyperlink': 'Open Hyperlink',\n 'Copy Hyperlink': 'Copy Hyperlink',\n 'Remove Hyperlink': 'Remove Hyperlink',\n 'Paragraph': 'Paragraph',\n 'Merge Cells': 'Merge Cells',\n 'Insert Above': 'Insert Above',\n 'Insert Below': 'Insert Below',\n 'Insert Left': 'Insert Left',\n 'Insert Right': 'Insert Right',\n 'Delete': 'Delete',\n 'Delete Table': 'Delete Table',\n 'Delete Row': 'Delete Row',\n 'Delete Column': 'Delete Column',\n 'File Name': 'File Name',\n 'Format Type': 'Format Type',\n 'Save': 'Save',\n 'Navigation': 'Navigation',\n 'Results': 'Results',\n 'Replace': 'Replace',\n 'Replace All': 'Replace All',\n 'We replaced all': 'We replaced all',\n 'Find': 'Find',\n 'No matches': 'No matches',\n 'All Done': 'All Done',\n 'Result': 'Result',\n 'of': 'of',\n 'instances': 'instances',\n 'with': 'with',\n 'Click to follow link': 'Click to follow link',\n 'Continue Numbering': 'Continue Numbering',\n 'Bookmark name': 'Bookmark name',\n 'Close': 'Close',\n 'Restart At': 'Restart At',\n 'Properties': 'Properties',\n 'Name': 'Name',\n 'Style type': 'Style type',\n 'Style based on': 'Style based on',\n 'Style for following paragraph': 'Style for following paragraph',\n 'Formatting': 'Formatting',\n 'Numbering and Bullets': 'Numbering and Bullets',\n 'Numbering': 'Numbering',\n 'Update Field': 'Update Field',\n 'Edit Field': 'Edit Field',\n 'Bookmark': 'Bookmark',\n 'Page Setup': 'Page Setup',\n 'No bookmarks found': 'No bookmarks found',\n 'Number format tooltip information': 'Single-level number format: [PREFIX]%[LEVELNUMBER][SUFFIX]'\n + 'For example, \"Chapter %1.\" will display numbering likeChapter 1. ItemChapter 2. Item…'\n + 'Chapter N. Item'\n + 'Multilevel number format:[PREFIX]%[LEVELNUMBER][SUFFIX]+[PREFIX]%[LEVELNUMBER][SUFFIX]'\n + 'For example, \"%1.%2.\" will display numbering like1.1. Item1.2. Item…1.N. Item',\n 'Format': 'Format',\n 'Create New Style': 'Create New Style',\n 'Modify Style': 'Modify Style',\n 'New': 'New',\n 'Bullets': 'Bullets',\n 'Use bookmarks': 'Use bookmarks',\n 'Table of Contents': 'Table of Contents'\n };\n _this.viewer = new PageLayoutViewer(_this);\n _this.parser = new SfdtReader(_this.viewer);\n return _this;\n }\n DocumentEditor_1 = DocumentEditor;\n Object.defineProperty(DocumentEditor.prototype, \"enableHeaderAndFooter\", {\n /**\n * @private\n */\n get: function () {\n return this.enableHeaderFooterIn;\n },\n set: function (value) {\n this.enableHeaderFooterIn = value;\n this.viewer.updateScrollBars();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"pageCount\", {\n /**\n * Gets the total number of pages.\n */\n get: function () {\n if (!this.isDocumentLoaded || isNullOrUndefined(this.viewer)) {\n return 1;\n }\n return this.viewer.pages.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"selection\", {\n /**\n * Gets the selection object of the document editor.\n * @returns Selection\n * @default undefined\n */\n get: function () {\n return this.selectionModule;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"editor\", {\n /**\n * Gets the editor object of the document editor.\n * @returns Editor\n * @default undefined\n */\n get: function () {\n return this.editorModule;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"editorHistory\", {\n /**\n * Gets the editor history object of the document editor.\n * @returns EditorHistory\n */\n get: function () {\n return this.editorHistoryModule;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"search\", {\n /**\n * Gets the search object of the document editor.\n * @returns { Search }\n */\n get: function () {\n return this.searchModule;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"contextMenu\", {\n /**\n * Gets the context menu object of the document editor.\n * @returns ContextMenu\n */\n get: function () {\n return this.contextMenuModule;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"containerId\", {\n /**\n * @private\n */\n get: function () {\n return this.element.id;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"isDocumentLoaded\", {\n /**\n * @private\n */\n get: function () {\n return this.isDocumentLoadedIn;\n },\n set: function (value) {\n this.isDocumentLoadedIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"enableHistoryMode\", {\n /**\n * Determines whether history needs to be enabled or not.\n * @default - false\n * @private\n */\n get: function () {\n return this.enableEditorHistory && !isNullOrUndefined(this.editorHistoryModule);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"documentStart\", {\n /**\n * Gets the start text position in the document.\n * @default undefined\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.selectionModule)) {\n return this.selection.getDocumentStart();\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"documentEnd\", {\n /**\n * Gets the end text position in the document.\n * @default undefined\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.selectionModule)) {\n return this.selection.getDocumentEnd();\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"isReadOnlyMode\", {\n /**\n * @private\n */\n get: function () {\n return this.isReadOnly || isNullOrUndefined(this.editorModule) || isNullOrUndefined(this.selectionModule);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentEditor.prototype, \"enableImageResizerMode\", {\n /**\n * Specifies to enable image resizer option\n * default - false\n * @private\n */\n get: function () {\n return this.enableImageResizer && !isNullOrUndefined(this.imageResizerModule);\n },\n enumerable: true,\n configurable: true\n });\n DocumentEditor.prototype.preRender = function () {\n this.findResultsList = [];\n //pre render section\n };\n DocumentEditor.prototype.render = function () {\n this.viewer.initializeComponents();\n this.openBlank();\n if (!isNullOrUndefined(this.element)) {\n var container = this.element;\n container.style.minHeight = '200px';\n container.style.minWidth = '200px';\n }\n };\n /**\n * Get component name\n * @private\n */\n DocumentEditor.prototype.getModuleName = function () {\n return 'DocumentEditor';\n };\n /**\n * Called internally if any of the property value changed.\n * @private\n */\n DocumentEditor.prototype.onPropertyChanged = function (model, oldProp) {\n for (var _i = 0, _a = Object.keys(model); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'zoomFactor':\n if (this.viewer) {\n this.viewer.zoomFactor = model.zoomFactor;\n }\n break;\n case 'locale':\n this.localizeDialogs();\n break;\n case 'isReadOnly':\n if (!isNullOrUndefined(this.optionsPaneModule) && this.optionsPaneModule.isOptionsPaneShow) {\n this.optionsPaneModule.showHideOptionsPane(false);\n }\n break;\n }\n }\n };\n DocumentEditor.prototype.localizeDialogs = function () {\n if (this.locale !== '') {\n var l10n = new L10n('documenteditor', this.defaultLocale);\n l10n.setLocale(this.locale);\n setCulture(this.locale);\n if (this.optionsPaneModule) {\n this.optionsPaneModule.initOptionsPane(l10n);\n }\n if (this.paragraphDialogModule) {\n this.paragraphDialogModule.initParagraphDialog(l10n);\n }\n if (this.pageSetupDialogModule) {\n this.pageSetupDialogModule.initPageSetupDialog(l10n);\n }\n if (this.fontDialogModule) {\n this.fontDialogModule.initFontDialog(l10n);\n }\n if (this.hyperlinkDialogModule) {\n this.hyperlinkDialogModule.initHyperlinkDialog(l10n);\n }\n if (this.contextMenuModule) {\n this.contextMenuModule.initContextMenu(l10n);\n }\n if (this.listDialogModule) {\n this.listDialogModule.initListDialog(l10n);\n }\n if (this.tablePropertiesDialogModule) {\n this.tablePropertiesDialogModule.initTablePropertyDialog(l10n);\n }\n if (this.bordersAndShadingDialogModule) {\n this.bordersAndShadingDialogModule.initBordersAndShadingsDialog(l10n);\n }\n if (this.cellOptionsDialogModule) {\n this.cellOptionsDialogModule.initCellMarginsDialog(l10n);\n }\n if (this.tableOptionsDialogModule) {\n this.tableOptionsDialogModule.initTableOptionsDialog(l10n);\n }\n if (this.tableDialogModule) {\n this.tableDialogModule.initTableDialog(l10n);\n }\n if (this.styleDialogModule) {\n this.styleDialogModule.initStyleDialog(l10n);\n }\n if (this.tableOfContentsDialogModule) {\n this.tableOfContentsDialogModule.initTableOfContentDialog(l10n);\n }\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n * @private\n */\n DocumentEditor.prototype.getPersistData = function () {\n return 'documenteditor';\n };\n DocumentEditor.prototype.clearPreservedCollectionsInViewer = function () {\n if (this.viewer instanceof LayoutViewer) {\n this.viewer.clearDocumentItems();\n }\n };\n /**\n * @private\n */\n DocumentEditor.prototype.getDocumentEditorElement = function () {\n return this.element;\n };\n /**\n * @private\n */\n DocumentEditor.prototype.fireContentChange = function () {\n this.trigger('contentChange');\n };\n /**\n * @private\n */\n DocumentEditor.prototype.fireDocumentChange = function () {\n this.trigger('documentChange');\n };\n /**\n * @private\n */\n DocumentEditor.prototype.fireSelectionChange = function () {\n if (!this.viewer.isCompositionStart && Browser.isDevice && this.editorModule) {\n this.editorModule.predictText();\n }\n this.trigger('selectionChange');\n };\n /**\n * @private\n */\n DocumentEditor.prototype.fireZoomFactorChange = function () {\n this.trigger('zoomFactorChange');\n };\n /**\n * @private\n */\n DocumentEditor.prototype.fireViewChange = function () {\n if (this.viewer && this.viewer.pages.length > 0) {\n if (this.viewer.visiblePages.length > 0) {\n var pages = this.viewer.visiblePages;\n var eventArgs = {\n startPage: pages[0].index + 1,\n endPage: pages[pages.length - 1].index + 1\n };\n this.trigger('viewChange', eventArgs);\n }\n }\n };\n /**\n * Shows the Paragraph dialog\n * @private\n */\n DocumentEditor.prototype.showParagraphDialog = function (paragraphFormat) {\n if (this.paragraphDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.paragraphDialogModule.show(paragraphFormat);\n }\n };\n /**\n * Shows the margin dialog\n * @private\n */\n DocumentEditor.prototype.showPageSetupDialog = function () {\n if (this.pageSetupDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.pageSetupDialogModule.show();\n }\n };\n /**\n * Shows the font dialog\n * @private\n */\n DocumentEditor.prototype.showFontDialog = function (characterFormat) {\n if (this.fontDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.fontDialogModule.showFontDialog(characterFormat);\n }\n };\n /**\n * Shows the cell option dialog\n * @private\n */\n DocumentEditor.prototype.showCellOptionsDialog = function () {\n if (this.cellOptionsDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.cellOptionsDialogModule.show();\n }\n };\n /**\n * Shows the table options dialog.\n * @private\n */\n DocumentEditor.prototype.showTableOptionsDialog = function () {\n if (this.tableOptionsDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.tableOptionsDialogModule.show();\n }\n };\n /**\n * Shows insert table dialog\n * @private\n */\n DocumentEditor.prototype.showTableDialog = function () {\n if (this.tableDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.tableDialogModule.show();\n }\n };\n /**\n * Shows the table of content dialog\n * @private\n */\n DocumentEditor.prototype.showTableOfContentsDialog = function () {\n if (this.tableOfContentsDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.tableOfContentsDialogModule.show();\n }\n };\n /* tslint:enable:no-any */\n /**\n * Shows the style dialog\n * @private\n */\n DocumentEditor.prototype.showStyleDialog = function () {\n if (this.styleDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.styleDialogModule.show();\n }\n };\n /**\n * Shows the hyperlink dialog\n * @private\n */\n DocumentEditor.prototype.showHyperlinkDialog = function () {\n if (this.hyperlinkDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.hyperlinkDialogModule.show();\n }\n };\n /**\n * Shows the bookmark dialog.\n * @private\n */\n DocumentEditor.prototype.showBookmarkDialog = function () {\n if (this.bookmarkDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.bookmarkDialogModule.show();\n }\n };\n /**\n * Shows the styles dialog.\n * @private\n */\n DocumentEditor.prototype.showStylesDialog = function () {\n if (this.stylesDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.stylesDialogModule.show();\n }\n };\n /**\n * Shows the List dialog\n * @private\n */\n DocumentEditor.prototype.showListDialog = function () {\n if (this.listDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.listDialogModule.showListDialog();\n }\n };\n /**\n * Shows the table properties dialog\n * @private\n */\n DocumentEditor.prototype.showTablePropertiesDialog = function () {\n if (this.tablePropertiesDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.tablePropertiesDialogModule.show();\n }\n };\n /**\n * Shows the borders and shading dialog\n * @private\n */\n DocumentEditor.prototype.showBordersAndShadingDialog = function () {\n if (this.bordersAndShadingDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.bordersAndShadingDialogModule.show();\n }\n };\n //tslint:disable: max-func-body-length\n DocumentEditor.prototype.requiredModules = function () {\n var modules = [];\n if (this.enablePrint) {\n modules.push({\n member: 'Print', args: []\n });\n }\n if (this.enableSfdtExport || this.enableWordExport || this.enableTextExport || this.enableSelection || this.enableEditor) {\n modules.push({\n member: 'SfdtExport', args: [this.viewer]\n });\n }\n if (this.enableWordExport) {\n modules.push({\n member: 'WordExport', args: []\n });\n }\n if (this.enableTextExport) {\n modules.push({\n member: 'TextExport', args: []\n });\n }\n if (this.enableSelection || this.enableSearch || this.enableEditor) {\n modules.push({\n member: 'Selection', args: [this]\n });\n if (this.enableContextMenu) {\n modules.push({\n member: 'ContextMenu', args: [this.viewer]\n });\n }\n }\n if (this.enableSearch) {\n modules.push({\n member: 'Search', args: [this]\n });\n if (this.enableOptionsPane) {\n modules.push({\n member: 'OptionsPane', args: [this.viewer]\n });\n }\n }\n if (this.enableEditor) {\n modules.push({\n member: 'Editor', args: [this.viewer]\n });\n if (this.enableImageResizer) {\n modules.push({\n member: 'ImageResizer', args: [this, this.viewer]\n });\n }\n if (this.enableEditorHistory) {\n modules.push({\n member: 'EditorHistory', args: [this]\n });\n }\n if (this.enableHyperlinkDialog) {\n modules.push({\n member: 'HyperlinkDialog', args: [this.viewer]\n });\n }\n if (this.enableTableDialog) {\n modules.push({\n member: 'TableDialog', args: [this.viewer]\n });\n }\n if (this.enableBookmarkDialog) {\n modules.push({\n member: 'BookmarkDialog', args: [this.viewer]\n });\n }\n if (this.enableTableOfContentsDialog) {\n modules.push({\n member: 'TableOfContentsDialog', args: [this.viewer]\n });\n }\n if (this.enablePageSetupDialog) {\n modules.push({\n member: 'PageSetupDialog', args: [this.viewer]\n });\n }\n if (this.enableStyleDialog) {\n modules.push({\n member: 'StylesDialog', args: [this.viewer]\n });\n modules.push({\n member: 'StyleDialog', args: [this.viewer]\n });\n modules.push({\n member: 'BulletsAndNumberingDialog', args: [this.viewer]\n });\n }\n if (this.enableListDialog) {\n modules.push({\n member: 'ListDialog', args: [this.viewer]\n });\n }\n if (this.enableParagraphDialog) {\n modules.push({\n member: 'ParagraphDialog', args: [this.viewer]\n });\n }\n if (this.enableFontDialog) {\n modules.push({\n member: 'FontDialog', args: [this.viewer]\n });\n }\n if (this.enableTablePropertiesDialog) {\n modules.push({\n member: 'TablePropertiesDialog', args: [this.viewer]\n });\n modules.push({\n member: 'CellOptionsDialog', args: [this.viewer]\n });\n }\n if (this.enableBordersAndShadingDialog) {\n modules.push({\n member: 'BordersAndShadingDialog', args: [this.viewer]\n });\n }\n if (this.enableTableOptionsDialog) {\n modules.push({\n member: 'TableOptionsDialog', args: [this.viewer]\n });\n }\n }\n return modules;\n };\n // Public Implementation Starts\n /**\n * Opens the given Sfdt text.\n * @param {string} sfdtText.\n */\n DocumentEditor.prototype.open = function (sfdtText) {\n if (!isNullOrUndefined(this.viewer)) {\n this.clearPreservedCollectionsInViewer();\n this.viewer.lists = [];\n this.viewer.abstractLists = [];\n this.viewer.styles = new WStyles();\n if (!isNullOrUndefined(sfdtText) && this.viewer) {\n this.viewer.onDocumentChanged(this.parser.convertJsonToDocument(sfdtText));\n if (this.editorModule) {\n this.editorModule.intializeDefaultStyles();\n }\n }\n }\n };\n /**\n * Scrolls view to start of the given page number if exists.\n * @param {number} pageNumber.\n * @returns void\n */\n DocumentEditor.prototype.scrollToPage = function (pageNumber) {\n if (isNullOrUndefined(this.viewer) || pageNumber < 1 || pageNumber > this.viewer.pages.length) {\n return false;\n }\n this.viewer.scrollToPage(pageNumber - 1);\n return true;\n };\n /**\n * Enables all the modules.\n * @returns void\n */\n DocumentEditor.prototype.enableAllModules = function () {\n this.enablePrint = this.enableSfdtExport = this.enableWordExport = this.enableTextExport\n = this.enableSelection = this.enableContextMenu = this.enableSearch = this.enableOptionsPane\n = this.enableEditor = this.enableImageResizer = this.enableEditorHistory\n = this.enableHyperlinkDialog = this.enableTableDialog = this.enableBookmarkDialog\n = this.enableTableOfContentsDialog = this.enablePageSetupDialog = this.enableStyleDialog\n = this.enableListDialog = this.enableParagraphDialog = this.enableFontDialog\n = this.enableTablePropertiesDialog = this.enableBordersAndShadingDialog\n = this.enableTableOptionsDialog = true;\n // tslint:disable-next-line:max-line-length\n DocumentEditor_1.Inject(Print, SfdtExport, WordExport, TextExport, Selection, Search, Editor, ImageResizer, EditorHistory, ContextMenu, OptionsPane, HyperlinkDialog, TableDialog, BookmarkDialog, TableOfContentsDialog, PageSetupDialog, StyleDialog, ListDialog, ParagraphDialog, BulletsAndNumberingDialog, FontDialog, TablePropertiesDialog, BordersAndShadingDialog, TableOptionsDialog, CellOptionsDialog, StylesDialog);\n };\n /**\n * Resizes the component and its sub elements based on given size or container size.\n * @param width\n * @param height\n */\n DocumentEditor.prototype.resize = function (width, height) {\n if (this.element) {\n if (!isNullOrUndefined(width) && width > 200) {\n this.element.style.width = width + 'px';\n }\n if (!isNullOrUndefined(height) && height > 200) {\n this.element.style.height = height + 'px';\n }\n if (this.viewer) {\n this.viewer.updateViewerSize();\n }\n }\n };\n /**\n * Shifts the focus to the document.\n */\n DocumentEditor.prototype.focusIn = function () {\n if (this.viewer) {\n this.viewer.updateFocus();\n }\n };\n /**\n * Fits the page based on given fit type.\n * @param {PageFitType} pageFitType? - Default value of ‘pageFitType’ parameter is 'None'\n * @returns void\n */\n DocumentEditor.prototype.fitPage = function (pageFitType) {\n if (isNullOrUndefined(pageFitType)) {\n pageFitType = 'None';\n }\n if (this.viewer) {\n this.viewer.pageFitType = pageFitType;\n }\n };\n /**\n * Prints the document.\n * @param {Window} printWindow? - Default value of 'printWindow' parameter is undefined.\n */\n DocumentEditor.prototype.print = function (printWindow) {\n if (isNullOrUndefined(this.viewer)) {\n throw new Error('Invalid operation.');\n }\n if (this.printModule) {\n this.printModule.print(this.viewer, printWindow);\n }\n else {\n throw new Error('Invalid operation. Print is not enabled.');\n }\n };\n /**\n * Serialize the data to JSON string.\n */\n DocumentEditor.prototype.serialize = function () {\n var json = '';\n if (this.enableSfdtExport && this.sfdtExportModule instanceof SfdtExport) {\n json = this.sfdtExportModule.serialize();\n }\n else {\n throw new Error('Invalid operation. Sfdt export is not enabled.');\n }\n return json;\n };\n /**\n * Saves the document.\n * @param {string} fileName\n * @param {FormatType} formatType\n */\n DocumentEditor.prototype.save = function (fileName, formatType) {\n fileName = fileName || 'Untitled';\n if (isNullOrUndefined(this.viewer)) {\n throw new Error('Invalid operation.');\n }\n if (formatType === 'Docx' && this.wordExportModule) {\n if (this.wordExportModule) {\n this.wordExportModule.save(this.viewer, fileName);\n }\n }\n else if (formatType === 'Txt' && this.textExportModule) {\n this.textExportModule.save(this.viewer, fileName);\n }\n else if (formatType === 'Sfdt' && this.enableSfdtExport && this.sfdtExportModule) {\n var jsonString = this.serialize();\n var blob = new Blob([jsonString], {\n type: 'application/json'\n });\n Save.save(fileName + '.sfdt', blob);\n }\n else {\n throw new Error('Invalid operation. Specified export is not enabled.');\n }\n };\n /**\n * Saves the document as blob.\n * @param {FormatType} formatType\n */\n DocumentEditor.prototype.saveAsBlob = function (formatType) {\n var _this = this;\n if (isNullOrUndefined(this.viewer)) {\n throw new Error('Invalid operation');\n }\n return new Promise(function (resolve, reject) {\n if (formatType === 'Docx' && _this.wordExportModule) {\n resolve(_this.wordExportModule.saveAsBlob(_this.viewer));\n }\n else if (formatType === 'Txt' && _this.textExportModule) {\n resolve(_this.textExportModule.saveAsBlob(_this.viewer));\n }\n else if (formatType === 'Sfdt' && _this.enableSfdtExport && _this.sfdtExportModule) {\n resolve(_this.sfdtExportModule.saveAsBlob(_this.viewer));\n }\n });\n };\n /**\n * Opens a blank document.\n */\n DocumentEditor.prototype.openBlank = function () {\n var section = new BodyWidget();\n section.index = 0;\n section.sectionFormat = new WSectionFormat(section);\n var paragraph = new ParagraphWidget();\n paragraph.index = 0;\n paragraph.paragraphFormat = new WParagraphFormat(paragraph);\n paragraph.characterFormat = new WCharacterFormat(paragraph);\n section.childWidgets.push(paragraph);\n paragraph.containerWidget = section;\n var sections = [];\n sections.push(section);\n // tslint:disable-next-line:max-line-length\n var hfs = this.parser.parseHeaderFooter({ header: {}, footer: {}, evenHeader: {}, evenFooter: {}, firstPageHeader: {}, firstPageFooter: {} }, undefined);\n if (this.viewer) {\n this.clearPreservedCollectionsInViewer();\n this.viewer.headersFooters.push(hfs);\n this.viewer.onDocumentChanged(sections);\n if (this.editorModule) {\n this.editorModule.intializeDefaultStyles();\n var style = this.viewer.styles.findByName('Normal');\n paragraph.paragraphFormat.baseStyle = style;\n paragraph.paragraphFormat.listFormat.baseStyle = style;\n }\n }\n };\n /**\n * Gets the style names based on given style type.\n * @param styleType\n */\n DocumentEditor.prototype.getStyleNames = function (styleType) {\n if (this.viewer) {\n return this.viewer.styles.getStyleNames(styleType);\n }\n return [];\n };\n /**\n * Gets the style objects on given style type.\n * @param styleType\n */\n DocumentEditor.prototype.getStyles = function (styleType) {\n if (this.viewer) {\n return this.viewer.styles.getStyles(styleType);\n }\n return [];\n };\n /**\n * Shows the dialog.\n * @param {DialogType} dialogType\n * @returns void\n */\n DocumentEditor.prototype.showDialog = function (dialogType) {\n switch (dialogType) {\n case 'Hyperlink':\n this.showHyperlinkDialog();\n break;\n case 'Table':\n this.showTableDialog();\n break;\n case 'Bookmark':\n this.showBookmarkDialog();\n break;\n case 'TableOfContents':\n this.showTableOfContentsDialog();\n break;\n case 'PageSetup':\n this.showPageSetupDialog();\n break;\n case 'List':\n this.showListDialog();\n break;\n case 'Styles':\n this.showStylesDialog();\n break;\n case 'Style':\n this.showStyleDialog();\n break;\n case 'Paragraph':\n this.showParagraphDialog();\n break;\n case 'Font':\n this.showFontDialog();\n break;\n case 'TableProperties':\n this.showTablePropertiesDialog();\n break;\n case 'BordersAndShading':\n this.showBordersAndShadingDialog();\n break;\n case 'TableOptions':\n this.showTableOptionsDialog();\n break;\n }\n };\n /**\n * Shows the options pane.\n */\n DocumentEditor.prototype.showOptionsPane = function () {\n if (!isNullOrUndefined(this.optionsPaneModule) && !isNullOrUndefined(this.viewer)) {\n this.optionsPaneModule.showHideOptionsPane(true);\n }\n };\n /**\n * Destroys all managed resources used by this object.\n */\n DocumentEditor.prototype.destroy = function () {\n _super.prototype.destroy.call(this);\n this.destroyDependentModules();\n if (!isNullOrUndefined(this.viewer)) {\n this.viewer.destroy();\n }\n this.viewer = undefined;\n if (!isNullOrUndefined(this.element)) {\n this.element.classList.remove('e-documenteditor');\n this.element.innerHTML = '';\n }\n this.element = undefined;\n this.findResultsList = [];\n this.findResultsList = undefined;\n };\n DocumentEditor.prototype.destroyDependentModules = function () {\n if (this.printModule) {\n this.printModule.destroy();\n this.printModule = undefined;\n }\n if (this.sfdtExportModule) {\n this.sfdtExportModule.destroy();\n this.sfdtExportModule = undefined;\n }\n if (this.optionsPaneModule) {\n this.optionsPaneModule.destroy();\n this.optionsPaneModule = undefined;\n }\n if (!isNullOrUndefined(this.hyperlinkDialogModule)) {\n this.hyperlinkDialogModule.destroy();\n this.hyperlinkDialogModule = undefined;\n }\n if (this.searchModule) {\n this.searchModule.destroy();\n this.searchModule = undefined;\n }\n if (this.contextMenuModule) {\n this.contextMenuModule.destroy();\n this.contextMenuModule = undefined;\n }\n if (this.editorModule) {\n this.editorModule.destroy();\n this.editorModule = undefined;\n }\n if (this.selectionModule) {\n this.selectionModule.destroy();\n this.selectionModule = undefined;\n }\n if (this.editorHistoryModule) {\n this.editorHistoryModule.destroy();\n this.editorHistoryModule = undefined;\n }\n if (!isNullOrUndefined(this.paragraphDialogModule)) {\n this.paragraphDialogModule.destroy();\n this.paragraphDialogModule = undefined;\n }\n if (this.pageSetupDialogModule) {\n this.pageSetupDialogModule.destroy();\n this.pageSetupDialogModule = undefined;\n }\n if (this.fontDialogModule) {\n this.fontDialogModule.destroy();\n this.fontDialogModule = undefined;\n }\n if (this.listDialogModule) {\n this.listDialogModule.destroy();\n this.listDialogModule = undefined;\n }\n if (this.imageResizerModule) {\n this.imageResizerModule.destroy();\n this.imageResizerModule = undefined;\n }\n if (this.tablePropertiesDialogModule) {\n this.tablePropertiesDialogModule.destroy();\n this.tablePropertiesDialogModule = undefined;\n }\n if (this.bordersAndShadingDialogModule) {\n this.bordersAndShadingDialogModule.destroy();\n this.bordersAndShadingDialogModule = undefined;\n }\n if (this.cellOptionsDialogModule) {\n this.cellOptionsDialogModule.destroy();\n this.cellOptionsDialogModule = undefined;\n }\n if (this.tableOptionsDialogModule) {\n this.tableOptionsDialogModule.destroy();\n this.tableOptionsDialogModule = undefined;\n }\n if (this.tableDialogModule) {\n this.tableDialogModule.destroy();\n this.tableDialogModule = undefined;\n }\n if (this.styleDialogModule) {\n this.styleDialogModule = undefined;\n }\n if (this.bookmarkDialogModule) {\n this.bookmarkDialogModule.destroy();\n this.bookmarkDialogModule = undefined;\n }\n if (this.styleDialogModule) {\n this.styleDialogModule.destroy();\n this.styleDialogModule = undefined;\n }\n if (this.textExportModule) {\n this.textExportModule.destroy();\n this.textExportModule = undefined;\n }\n if (this.wordExportModule) {\n this.wordExportModule.destroy();\n this.wordExportModule = undefined;\n }\n if (this.tableOfContentsDialogModule) {\n this.tableOfContentsDialogModule.destroy();\n this.tableOfContentsDialogModule = undefined;\n }\n };\n __decorate([\n Property(1)\n ], DocumentEditor.prototype, \"zoomFactor\", void 0);\n __decorate([\n Property(true)\n ], DocumentEditor.prototype, \"isReadOnly\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enablePrint\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableSelection\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableEditor\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableEditorHistory\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableSfdtExport\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableWordExport\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableTextExport\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableOptionsPane\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableContextMenu\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableHyperlinkDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableBookmarkDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableTableOfContentsDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableSearch\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableParagraphDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableListDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableTablePropertiesDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableBordersAndShadingDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enablePageSetupDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableStyleDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableFontDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableTableOptionsDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableTableDialog\", void 0);\n __decorate([\n Property(false)\n ], DocumentEditor.prototype, \"enableImageResizer\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"documentChange\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"viewChange\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"zoomFactorChange\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"selectionChange\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"requestNavigate\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"contentChange\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"keyDown\", void 0);\n __decorate([\n Event()\n ], DocumentEditor.prototype, \"searchResultsChange\", void 0);\n DocumentEditor = DocumentEditor_1 = __decorate([\n NotifyPropertyChanges\n ], DocumentEditor);\n return DocumentEditor;\n var DocumentEditor_1;\n}(Component));\nexport { DocumentEditor };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * Print class\n */\nvar Print = /** @class */ (function () {\n function Print() {\n }\n /**\n * Gets module name.\n */\n Print.prototype.getModuleName = function () {\n return 'Print';\n };\n /**\n * Prints the current viewer\n * @param viewer\n * @param printWindow\n * @private\n */\n Print.prototype.print = function (viewer, printWindow) {\n this.printWindow(viewer, navigator.userAgent, printWindow);\n };\n /**\n * Opens print window and displays current page to print.\n * @private\n */\n Print.prototype.printWindow = function (viewer, browserUserAgent, printWindow) {\n var height = this.getPageHeight(viewer.pages);\n var width = this.getPageWidth(viewer.pages);\n var printElement = document.createElement('div');\n printElement.style.width = '100%';\n printElement.style.height = '100%';\n printElement.style.overflow = 'scroll';\n // Rendering canvas to print\n this.generatePrintContent(viewer, printElement);\n if (isNullOrUndefined(printWindow)) {\n printWindow = window.open('', 'print', 'height=452,width=1024,tabbar=no');\n }\n if ((browserUserAgent.indexOf('Chrome') !== -1) || (browserUserAgent.indexOf('Firefox')) !== -1) {\n // Chrome and Firefox\n printWindow.document.write('');\n // tslint:disable-next-line:max-line-length\n printWindow.document.write('
');\n }\n else {\n // Internet Explorer and Edge\n // tslint:disable-next-line:max-line-length\n printWindow.document.write('');\n }\n // tslint:disable-next-line:max-line-length\n printWindow.document.write(printElement.innerHTML + ' ');\n printElement = undefined;\n printWindow.document.close();\n printWindow.focus();\n var interval = setInterval(function () {\n if (printWindow.ready) {\n printWindow.print();\n printWindow.close();\n clearInterval(interval);\n }\n }, 500);\n };\n /**\n * Generates print content.\n * @private\n */\n Print.prototype.generatePrintContent = function (viewer, element) {\n // Rendering canvas to print\n var htmlString = '';\n for (var i = 0; i < viewer.pages.length; i++) {\n var page = viewer.pages[i];\n var pageHeight = page.boundingRectangle.height;\n var pageWidth = page.boundingRectangle.width;\n viewer.render.isPrinting = true;\n viewer.render.renderWidgets(page, 0, 0, 0, 0);\n var canvasURL = viewer.render.pageCanvas.toDataURL();\n viewer.render.isPrinting = false;\n // tslint:disable-next-line:max-line-length\n htmlString += ' ';\n }\n element.innerHTML = htmlString;\n };\n /**\n * Gets page width.\n * @param pages\n * @private\n */\n Print.prototype.getPageWidth = function (pages) {\n var width = 0;\n for (var i = 0; i < pages.length; i++) {\n if (width < pages[i].boundingRectangle.width) {\n width = pages[i].boundingRectangle.width;\n }\n }\n return width;\n };\n /**\n * Gets page height.\n * @private\n */\n Print.prototype.getPageHeight = function (pages) {\n var height = 0;\n for (var i = 0; i < pages.length; i++) {\n if (height < pages[i].boundingRectangle.height) {\n height = pages[i].boundingRectangle.height;\n }\n }\n return height;\n };\n /**\n * @private\n */\n Print.prototype.destroy = function () {\n return;\n };\n return Print;\n}());\nexport { Print };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\n/**\n * @private\n */\nvar WSectionFormat = /** @class */ (function () {\n function WSectionFormat(node) {\n this.uniqueSectionFormat = undefined;\n this.ownerBase = node;\n }\n Object.defineProperty(WSectionFormat.prototype, \"headerDistance\", {\n get: function () {\n return this.getPropertyValue('headerDistance');\n },\n set: function (value) {\n this.setPropertyValue('headerDistance', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"footerDistance\", {\n get: function () {\n return this.getPropertyValue('footerDistance');\n },\n set: function (value) {\n this.setPropertyValue('footerDistance', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"differentFirstPage\", {\n get: function () {\n return this.getPropertyValue('differentFirstPage');\n },\n set: function (value) {\n this.setPropertyValue('differentFirstPage', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"differentOddAndEvenPages\", {\n get: function () {\n return this.getPropertyValue('differentOddAndEvenPages');\n },\n set: function (value) {\n this.setPropertyValue('differentOddAndEvenPages', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"pageHeight\", {\n get: function () {\n return this.getPropertyValue('pageHeight');\n },\n set: function (value) {\n this.setPropertyValue('pageHeight', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"rightMargin\", {\n get: function () {\n return this.getPropertyValue('rightMargin');\n },\n set: function (value) {\n this.setPropertyValue('rightMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"pageWidth\", {\n get: function () {\n return this.getPropertyValue('pageWidth');\n },\n set: function (value) {\n this.setPropertyValue('pageWidth', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"leftMargin\", {\n get: function () {\n return this.getPropertyValue('leftMargin');\n },\n set: function (value) {\n this.setPropertyValue('leftMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"bottomMargin\", {\n get: function () {\n return this.getPropertyValue('bottomMargin');\n },\n set: function (value) {\n this.setPropertyValue('bottomMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WSectionFormat.prototype, \"topMargin\", {\n get: function () {\n return this.getPropertyValue('topMargin');\n },\n set: function (value) {\n this.setPropertyValue('topMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n WSectionFormat.prototype.destroy = function () {\n if (!isNullOrUndefined(this.uniqueSectionFormat)) {\n WSectionFormat.uniqueSectionFormats.remove(this.uniqueSectionFormat);\n }\n this.uniqueSectionFormat = undefined;\n };\n WSectionFormat.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueSectionFormat)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueSectionFormat.uniqueFormatType, property);\n return this.uniqueSectionFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WSectionFormat.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'headerDistance':\n value = 36;\n break;\n case 'footerDistance':\n value = 36;\n break;\n case 'differentFirstPage':\n value = false;\n break;\n case 'differentOddAndEvenPages':\n value = false;\n break;\n case 'pageWidth':\n value = 612;\n break;\n case 'pageHeight':\n value = 792;\n break;\n case 'leftMargin':\n value = 72;\n break;\n case 'topMargin':\n value = 72;\n break;\n case 'rightMargin':\n value = 72;\n break;\n case 'bottomMargin':\n value = 72;\n break;\n }\n return value;\n };\n WSectionFormat.prototype.getPropertyValue = function (property) {\n var hasValue = this.hasValue(property);\n if (hasValue) {\n var propertyType = WUniqueFormat.getPropertyType(WSectionFormat.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueSectionFormat) && this.uniqueSectionFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueSectionFormat.propertiesHash.get(propertyType);\n }\n }\n return WSectionFormat.getPropertyDefaultValue(property);\n };\n WSectionFormat.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WSectionFormat.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueSectionFormat)) {\n this.initializeUniqueSectionFormat(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueSectionFormat.uniqueFormatType, property);\n if (this.uniqueSectionFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueSectionFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n // tslint:disable-next-line:max-line-length\n this.uniqueSectionFormat = WSectionFormat.uniqueSectionFormats.updateUniqueFormat(this.uniqueSectionFormat, property, value);\n }\n };\n WSectionFormat.prototype.initializeUniqueSectionFormat = function (property, propValue) {\n var uniqueSectionFormatTemp = new Dictionary();\n this.addUniqueSectionFormat('headerDistance', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('footerDistance', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('differentFirstPage', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('differentOddAndEvenPages', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('pageWidth', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('pageHeight', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('leftMargin', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('topMargin', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('rightMargin', property, propValue, uniqueSectionFormatTemp);\n this.addUniqueSectionFormat('bottomMargin', property, propValue, uniqueSectionFormatTemp);\n // tslint:disable-next-line:max-line-length\n this.uniqueSectionFormat = WSectionFormat.uniqueSectionFormats.addUniqueFormat(uniqueSectionFormatTemp, WSectionFormat.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WSectionFormat.prototype.addUniqueSectionFormat = function (property, modifiedProperty, propValue, uniqueSectionFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WSectionFormat.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueSectionFormatTemp.add(propertyType, propValue);\n }\n else {\n uniqueSectionFormatTemp.add(propertyType, WSectionFormat.getPropertyDefaultValue(property));\n }\n };\n WSectionFormat.prototype.copyFormat = function (format, history) {\n if (history && (history.isUndoing || history.isRedoing)) {\n this.uniqueSectionFormat = format.uniqueSectionFormat;\n }\n else {\n if (!isNullOrUndefined(format)) {\n if (!isNullOrUndefined(format.uniqueSectionFormat) && format.uniqueSectionFormat.propertiesHash) {\n this.updateUniqueSectionFormat(format);\n }\n }\n }\n };\n WSectionFormat.prototype.updateUniqueSectionFormat = function (format) {\n var hash = undefined;\n if (this.uniqueSectionFormat) {\n hash = this.uniqueSectionFormat.mergeProperties(format.uniqueSectionFormat);\n if (this.uniqueSectionFormat.referenceCount === 0) {\n WSectionFormat.uniqueSectionFormats.remove(this.uniqueSectionFormat);\n this.uniqueSectionFormat = undefined;\n }\n }\n this.uniqueSectionFormat = new WUniqueFormat(WSectionFormat.uniqueFormatType);\n if (isNullOrUndefined(hash)) {\n hash = this.uniqueSectionFormat.mergeProperties(format.uniqueSectionFormat);\n }\n this.uniqueSectionFormat = WSectionFormat.uniqueSectionFormats.addUniqueFormat(hash, WSectionFormat.uniqueFormatType);\n };\n WSectionFormat.prototype.cloneFormat = function () {\n var format = new WSectionFormat();\n format.uniqueSectionFormat = this.uniqueSectionFormat;\n return format;\n };\n WSectionFormat.clear = function () {\n this.uniqueSectionFormats.clear();\n };\n WSectionFormat.uniqueSectionFormats = new WUniqueFormats();\n WSectionFormat.uniqueFormatType = 10;\n return WSectionFormat;\n}());\nexport { WSectionFormat };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WLevelOverride = /** @class */ (function () {\n function WLevelOverride() {\n }\n WLevelOverride.prototype.destroy = function () {\n if (!isNullOrUndefined(this.overrideListLevel)) {\n this.overrideListLevel.destroy();\n }\n this.levelNumber = undefined;\n this.startAt = undefined;\n this.overrideListLevel = undefined;\n };\n return WLevelOverride;\n}());\nexport { WLevelOverride };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { WLevelOverride } from './level-override';\n/**\n * @private\n */\nvar WList = /** @class */ (function () {\n function WList() {\n this.listId = -1;\n this.sourceListId = -1;\n this.abstractListId = -1;\n this.abstractList = undefined;\n this.levelOverrides = [];\n }\n WList.prototype.getListLevel = function (levelNumber) {\n var listLevel = undefined;\n var levelOverride = this.getLevelOverride(levelNumber);\n if (!isNullOrUndefined(levelOverride) && !isNullOrUndefined(levelOverride.overrideListLevel)) {\n listLevel = levelOverride.overrideListLevel;\n }\n else {\n listLevel = this.abstractList.levels[levelNumber];\n }\n return listLevel;\n };\n WList.prototype.getLevelOverride = function (levelNumber) {\n for (var i = 0; i < this.levelOverrides.length; i++) {\n if (this.levelOverrides[i] instanceof WLevelOverride) {\n var levelOverride = this.levelOverrides[i];\n if (levelOverride.levelNumber === levelNumber) {\n return levelOverride;\n }\n }\n }\n return undefined;\n };\n WList.prototype.destroy = function () {\n if (!isNullOrUndefined(this.levelOverrides)) {\n this.levelOverrides = [];\n }\n this.abstractListId = undefined;\n this.listId = undefined;\n this.sourceListId = undefined;\n this.levelOverrides = undefined;\n };\n WList.prototype.mergeList = function (list) {\n if (!isNullOrUndefined(this.abstractListId) && this.abstractListId !== -1) {\n this.abstractListId = list.abstractListId;\n }\n if (!isNullOrUndefined(this.listId) && this.listId !== -1) {\n this.listId = list.listId;\n }\n if (!isNullOrUndefined(this.sourceListId) && this.sourceListId !== -1) {\n this.sourceListId = list.sourceListId;\n }\n if (!isNullOrUndefined(this.levelOverrides) && this.levelOverrides.length !== 0) {\n this.levelOverrides = list.levelOverrides;\n }\n };\n return WList;\n}());\nexport { WList };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { WParagraphStyle } from './style';\nimport { WList } from '../list/list';\n/**\n * @private\n */\nvar WListFormat = /** @class */ (function () {\n function WListFormat(node) {\n this.uniqueListFormat = undefined;\n this.ownerBase = undefined;\n this.baseStyle = undefined;\n this.list = undefined;\n this.ownerBase = node;\n }\n Object.defineProperty(WListFormat.prototype, \"listId\", {\n get: function () {\n return this.getPropertyValue('listId');\n },\n set: function (listId) {\n this.setPropertyValue('listId', listId);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WListFormat.prototype, \"listLevelNumber\", {\n get: function () {\n return this.getPropertyValue('listLevelNumber');\n },\n set: function (value) {\n this.setPropertyValue('listLevelNumber', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WListFormat.prototype, \"listLevel\", {\n get: function () {\n var list = undefined;\n if (!isNullOrUndefined(this.list)) {\n list = this.list;\n }\n else {\n /* tslint:disable-next-line:no-any */\n var baseListStyle = this.baseStyle;\n while (!isNullOrUndefined(baseListStyle)) {\n if (baseListStyle.paragraphFormat.listFormat.list) {\n list = baseListStyle.paragraphFormat.listFormat.list;\n break;\n }\n else {\n baseListStyle = baseListStyle.basedOn;\n }\n }\n }\n if (!isNullOrUndefined(list)) {\n return list.getListLevel(this.listLevelNumber);\n }\n else {\n return undefined;\n }\n },\n enumerable: true,\n configurable: true\n });\n WListFormat.prototype.getPropertyValue = function (property) {\n if (!this.hasValue(property)) {\n if (this.baseStyle instanceof WParagraphStyle) {\n /* tslint:disable-next-line:no-any */\n var baseStyle = this.baseStyle;\n while (!isNullOrUndefined(baseStyle)) {\n if (baseStyle.paragraphFormat.listFormat.hasValue(property)) {\n break;\n }\n else {\n baseStyle = baseStyle.basedOn;\n }\n }\n if (!isNullOrUndefined(baseStyle)) {\n var propertyType = WUniqueFormat.getPropertyType(WListFormat.uniqueFormatType, property);\n return baseStyle.paragraphFormat.listFormat.uniqueListFormat.propertiesHash.get(propertyType);\n }\n }\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(WListFormat.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueListFormat) && this.uniqueListFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueListFormat.propertiesHash.get(propertyType);\n }\n }\n return WListFormat.getPropertyDefaultValue(property);\n };\n WListFormat.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WListFormat.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueListFormat)) {\n this.initializeUniqueListFormat(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueListFormat.uniqueFormatType, property);\n if (this.uniqueListFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueListFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n this.uniqueListFormat = WListFormat.uniqueListFormats.updateUniqueFormat(this.uniqueListFormat, property, value);\n }\n };\n WListFormat.prototype.initializeUniqueListFormat = function (property, propValue) {\n var uniqueListFormatTemp = new Dictionary();\n this.addUniqueListFormat('listId', property, propValue, uniqueListFormatTemp);\n this.addUniqueListFormat('listLevelNumber', property, propValue, uniqueListFormatTemp);\n this.uniqueListFormat = WListFormat.uniqueListFormats.addUniqueFormat(uniqueListFormatTemp, WListFormat.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WListFormat.prototype.addUniqueListFormat = function (property, modifiedProperty, propValue, uniqueListFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WListFormat.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueListFormatTemp.add(propertyType, propValue);\n }\n };\n WListFormat.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'listId':\n value = -1;\n break;\n case 'listLevelNumber':\n value = 0;\n break;\n }\n return value;\n };\n WListFormat.prototype.copyFormat = function (format) {\n if (!isNullOrUndefined(format)) {\n if (!isNullOrUndefined(format.uniqueListFormat)) {\n this.listId = format.listId;\n this.listLevelNumber = format.listLevelNumber;\n }\n if (!isNullOrUndefined(format.baseStyle)) {\n this.baseStyle = format.baseStyle;\n }\n if (!isNullOrUndefined(format.list)) {\n this.list = format.list;\n }\n }\n };\n WListFormat.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueListFormat)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueListFormat.uniqueFormatType, property);\n return this.uniqueListFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WListFormat.prototype.clearFormat = function () {\n if (!isNullOrUndefined(this.uniqueListFormat) && this.uniqueListFormat.referenceCount === 0) {\n WListFormat.uniqueListFormats.remove(this.uniqueListFormat);\n }\n this.uniqueListFormat = undefined;\n this.list = undefined;\n };\n WListFormat.prototype.destroy = function () {\n this.clearFormat();\n };\n WListFormat.clear = function () {\n this.uniqueListFormats.clear();\n };\n WListFormat.prototype.ApplyStyle = function (baseStyle) {\n this.baseStyle = baseStyle;\n };\n /**\n * For internal use\n * @private\n */\n WListFormat.prototype.getValue = function (property) {\n return this.hasValue(property) ? this.getPropertyValue(property) : undefined;\n };\n /**\n * For internal use\n * @private\n */\n WListFormat.prototype.mergeFormat = function (format) {\n if (isNullOrUndefined(this.getValue('listId'))) {\n this.listId = format.getValue('listId');\n }\n if (isNullOrUndefined(this.getValue('listLevelNumber'))) {\n this.listLevelNumber = format.getValue('listLevelNumber');\n }\n if (!isNullOrUndefined(format.list)) {\n if (isNullOrUndefined(this.list)) {\n this.list = new WList();\n }\n this.list.mergeList(format.list);\n }\n };\n WListFormat.uniqueListFormats = new WUniqueFormats();\n WListFormat.uniqueFormatType = 7;\n return WListFormat;\n}());\nexport { WListFormat };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { WListFormat } from './list-format';\nimport { WParagraphStyle } from './style';\n/**\n * @private\n */\nvar WTabStop = /** @class */ (function () {\n function WTabStop() {\n }\n Object.defineProperty(WTabStop.prototype, \"position\", {\n get: function () {\n return this.positionIn;\n },\n set: function (value) {\n this.positionIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTabStop.prototype, \"deletePosition\", {\n get: function () {\n return this.deletePositionIn;\n },\n set: function (value) {\n this.deletePositionIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTabStop.prototype, \"tabJustification\", {\n get: function () {\n return this.justification;\n },\n set: function (value) {\n this.justification = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTabStop.prototype, \"tabLeader\", {\n get: function () {\n return this.leader;\n },\n set: function (value) {\n this.leader = value;\n },\n enumerable: true,\n configurable: true\n });\n WTabStop.prototype.destroy = function () {\n this.position = undefined;\n this.deletePosition = undefined;\n this.tabJustification = undefined;\n this.leader = undefined;\n };\n return WTabStop;\n}());\nexport { WTabStop };\n/**\n * @private\n */\nvar WParagraphFormat = /** @class */ (function () {\n function WParagraphFormat(node) {\n this.uniqueParagraphFormat = undefined;\n this.ownerBase = undefined;\n this.baseStyle = undefined;\n this.tabs = undefined;\n this.ownerBase = node;\n this.listFormat = new WListFormat(this);\n this.tabs = [];\n }\n WParagraphFormat.prototype.getUpdatedTabs = function () {\n var inTabs = [];\n if (!isNullOrUndefined(this.baseStyle)) {\n /* tslint:disable-next-line:no-any */\n var baseStyle = this.baseStyle;\n var tabStops = new Dictionary();\n while (!isNullOrUndefined(baseStyle)) {\n for (var _i = 0, _a = baseStyle.paragraphFormat.tabs; _i < _a.length; _i++) {\n var tab = _a[_i];\n if (!tabStops.containsKey(tab.position)) {\n tabStops.add(tab.position, tab);\n }\n }\n baseStyle = baseStyle.basedOn;\n }\n for (var _b = 0, _c = tabStops.keys; _b < _c.length; _b++) {\n var key = _c[_b];\n if (!this.hasTabStop(key)) {\n inTabs.push(tabStops.get(key));\n }\n }\n inTabs = inTabs.concat(this.tabs.filter(function (a) { return (a.position !== 0 && a.deletePosition === 0); }));\n inTabs = inTabs.sort(function (a, b) { return a.position - b.position; });\n }\n return inTabs;\n };\n WParagraphFormat.prototype.hasTabStop = function (position) {\n for (var i = 0; i < this.tabs.length; i++) {\n if (this.tabs[i].deletePosition === position) {\n return true;\n }\n }\n return false;\n };\n Object.defineProperty(WParagraphFormat.prototype, \"leftIndent\", {\n get: function () {\n return this.getPropertyValue('leftIndent');\n },\n set: function (value) {\n this.setPropertyValue('leftIndent', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"rightIndent\", {\n get: function () {\n return this.getPropertyValue('rightIndent');\n },\n set: function (value) {\n this.setPropertyValue('rightIndent', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"firstLineIndent\", {\n get: function () {\n return this.getPropertyValue('firstLineIndent');\n },\n set: function (value) {\n this.setPropertyValue('firstLineIndent', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"beforeSpacing\", {\n get: function () {\n return this.getPropertyValue('beforeSpacing');\n },\n set: function (value) {\n this.setPropertyValue('beforeSpacing', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"afterSpacing\", {\n get: function () {\n return this.getPropertyValue('afterSpacing');\n },\n set: function (value) {\n this.setPropertyValue('afterSpacing', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"lineSpacing\", {\n get: function () {\n return this.getPropertyValue('lineSpacing');\n },\n set: function (value) {\n this.setPropertyValue('lineSpacing', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"lineSpacingType\", {\n get: function () {\n return this.getPropertyValue('lineSpacingType');\n },\n set: function (value) {\n this.setPropertyValue('lineSpacingType', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"textAlignment\", {\n get: function () {\n return this.getPropertyValue('textAlignment');\n },\n set: function (value) {\n this.setPropertyValue('textAlignment', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WParagraphFormat.prototype, \"outlineLevel\", {\n get: function () {\n return this.getPropertyValue('outlineLevel');\n },\n set: function (value) {\n this.setPropertyValue('outlineLevel', value);\n },\n enumerable: true,\n configurable: true\n });\n WParagraphFormat.prototype.getListFormatParagraphFormat = function (property) {\n if (this.listFormat.listId > 0 && this.listFormat.listLevelNumber > -1) {\n var level = this.listFormat.listLevel;\n var propertyType = WUniqueFormat.getPropertyType(WParagraphFormat.uniqueFormatType, property);\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(level) && !isNullOrUndefined(level.paragraphFormat.uniqueParagraphFormat) && level.paragraphFormat.uniqueParagraphFormat.propertiesHash.containsKey(propertyType)) {\n return level.paragraphFormat.uniqueParagraphFormat.propertiesHash.get(propertyType);\n }\n else {\n return undefined;\n }\n }\n return undefined;\n };\n WParagraphFormat.prototype.getPropertyValue = function (property) {\n if (!this.hasValue(property)) {\n var ifListFormat = this.getListFormatParagraphFormat(property);\n if (!isNullOrUndefined(ifListFormat)) {\n return ifListFormat;\n }\n else {\n if (this.baseStyle instanceof WParagraphStyle) {\n /* tslint:disable-next-line:no-any */\n var baseStyle = this.baseStyle;\n while (!isNullOrUndefined(baseStyle)) {\n if (baseStyle.paragraphFormat.hasValue(property)) {\n break;\n }\n else {\n baseStyle = baseStyle.basedOn;\n }\n }\n if (!isNullOrUndefined(baseStyle)) {\n var propertyType = WUniqueFormat.getPropertyType(WParagraphFormat.uniqueFormatType, property);\n return baseStyle.paragraphFormat.uniqueParagraphFormat.propertiesHash.get(propertyType);\n }\n }\n }\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(WParagraphFormat.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueParagraphFormat) && this.uniqueParagraphFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueParagraphFormat.propertiesHash.get(propertyType);\n }\n }\n return this.getDefaultValue(property);\n };\n WParagraphFormat.prototype.getDefaultValue = function (property) {\n var propertyType = WUniqueFormat.getPropertyType(WParagraphFormat.uniqueFormatType, property);\n var docParagraphFormat = this.documentParagraphFormat();\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(docParagraphFormat) && !isNullOrUndefined(docParagraphFormat.uniqueParagraphFormat) && docParagraphFormat.uniqueParagraphFormat.propertiesHash.containsKey(propertyType)) {\n return docParagraphFormat.uniqueParagraphFormat.propertiesHash.get(propertyType);\n }\n else {\n return WParagraphFormat.getPropertyDefaultValue(property);\n }\n };\n WParagraphFormat.prototype.documentParagraphFormat = function () {\n var docParagraphFormat;\n if (!isNullOrUndefined(this.ownerBase)) {\n if (!isNullOrUndefined(this.ownerBase.bodyWidget)) {\n docParagraphFormat = this.ownerBase.bodyWidget.page.viewer.paragraphFormat;\n }\n }\n return docParagraphFormat;\n };\n WParagraphFormat.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WParagraphFormat.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueParagraphFormat)) {\n this.initializeUniqueParagraphFormat(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueParagraphFormat.uniqueFormatType, property);\n if (this.uniqueParagraphFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueParagraphFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n // tslint:disable-next-line:max-line-length\n this.uniqueParagraphFormat = WParagraphFormat.uniqueParagraphFormats.updateUniqueFormat(this.uniqueParagraphFormat, property, value);\n }\n };\n WParagraphFormat.prototype.initializeUniqueParagraphFormat = function (property, propValue) {\n var uniqueParaFormatTemp = new Dictionary();\n this.addUniqueParaFormat('leftIndent', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('rightIndent', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('firstLineIndent', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('textAlignment', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('beforeSpacing', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('afterSpacing', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('lineSpacing', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('lineSpacingType', property, propValue, uniqueParaFormatTemp);\n this.addUniqueParaFormat('outlineLevel', property, propValue, uniqueParaFormatTemp);\n // tslint:disable-next-line:max-line-length\n this.uniqueParagraphFormat = WParagraphFormat.uniqueParagraphFormats.addUniqueFormat(uniqueParaFormatTemp, WParagraphFormat.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WParagraphFormat.prototype.addUniqueParaFormat = function (property, modifiedProperty, propValue, uniqueParaFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WParagraphFormat.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueParaFormatTemp.add(propertyType, propValue);\n }\n };\n WParagraphFormat.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'leftIndent':\n value = 0;\n break;\n case 'rightIndent':\n value = 0;\n break;\n case 'firstLineIndent':\n value = 0;\n break;\n case 'textAlignment':\n value = 'Left';\n break;\n case 'beforeSpacing':\n value = 0;\n break;\n case 'afterSpacing':\n value = 0;\n break;\n case 'lineSpacing':\n value = 1;\n break;\n case 'lineSpacingType':\n value = 'Multiple';\n break;\n case 'styleName':\n value = 'Normal';\n break;\n case 'outlineLevel':\n value = 'BodyText';\n break;\n }\n return value;\n };\n WParagraphFormat.prototype.clearFormat = function () {\n if (!isNullOrUndefined(this.listFormat)) {\n this.listFormat.clearFormat();\n }\n if (!isNullOrUndefined(this.uniqueParagraphFormat) && this.uniqueParagraphFormat.referenceCount === 0) {\n WParagraphFormat.uniqueParagraphFormats.remove(this.uniqueParagraphFormat);\n }\n this.uniqueParagraphFormat = undefined;\n this.baseStyle = undefined;\n };\n WParagraphFormat.prototype.destroy = function () {\n this.clearFormat();\n if (!isNullOrUndefined(this.listFormat)) {\n this.listFormat.destroy();\n }\n this.listFormat = undefined;\n if (this.tabs !== undefined) {\n for (var i = 0; i < this.tabs.length; i++) {\n this.tabs[i].destroy();\n }\n this.tabs = undefined;\n }\n };\n WParagraphFormat.prototype.copyFormat = function (format) {\n if (!isNullOrUndefined(format)) {\n if (!isNullOrUndefined(format.uniqueParagraphFormat)) {\n this.updateUniqueParagraphFormat(format);\n }\n if (!isNullOrUndefined(format.listFormat)) {\n this.listFormat.copyFormat(format.listFormat);\n }\n if (!isNullOrUndefined(format.baseStyle)) {\n this.baseStyle = format.baseStyle;\n }\n if (!isNullOrUndefined(format.tabs)) {\n for (var i = 0; i < format.tabs.length; i++) {\n this.tabs[i] = format.tabs[i];\n }\n }\n }\n };\n WParagraphFormat.prototype.updateUniqueParagraphFormat = function (format) {\n var hash = undefined;\n if (this.uniqueParagraphFormat) {\n hash = this.uniqueParagraphFormat.mergeProperties(format.uniqueParagraphFormat);\n if (this.uniqueParagraphFormat.referenceCount === 0) {\n WParagraphFormat.uniqueParagraphFormats.remove(this.uniqueParagraphFormat);\n this.uniqueParagraphFormat = undefined;\n }\n }\n this.uniqueParagraphFormat = new WUniqueFormat(WParagraphFormat.uniqueFormatType);\n if (isNullOrUndefined(hash)) {\n hash = this.uniqueParagraphFormat.mergeProperties(format.uniqueParagraphFormat);\n }\n this.uniqueParagraphFormat = WParagraphFormat.uniqueParagraphFormats.addUniqueFormat(hash, WParagraphFormat.uniqueFormatType);\n };\n WParagraphFormat.prototype.cloneFormat = function () {\n var format = new WParagraphFormat(undefined);\n format.uniqueParagraphFormat = this.uniqueParagraphFormat;\n format.baseStyle = this.baseStyle;\n if (isNullOrUndefined(this.listFormat)) {\n format.listFormat = undefined;\n }\n else {\n format.listFormat = new WListFormat();\n format.listFormat.listId = this.listFormat.listId;\n format.listFormat.listLevelNumber = this.listFormat.listLevelNumber;\n }\n return format;\n };\n WParagraphFormat.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueParagraphFormat) && !isNullOrUndefined(this.uniqueParagraphFormat.propertiesHash)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueParagraphFormat.uniqueFormatType, property);\n return this.uniqueParagraphFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WParagraphFormat.clear = function () {\n this.uniqueParagraphFormats.clear();\n };\n WParagraphFormat.prototype.ApplyStyle = function (baseStyle) {\n this.baseStyle = baseStyle;\n this.listFormat.ApplyStyle(this.baseStyle);\n };\n /**\n * For internal use\n * @private\n */\n WParagraphFormat.prototype.getValue = function (property) {\n return this.hasValue(property) ? this.getPropertyValue(property) : undefined;\n };\n /**\n * For internal use\n * @private\n */\n WParagraphFormat.prototype.mergeFormat = function (format) {\n if (isNullOrUndefined(this.getValue('leftIndent'))) {\n this.leftIndent = format.getValue('leftIndent');\n }\n if (isNullOrUndefined(this.getValue('rightIndent'))) {\n this.rightIndent = format.getValue('rightIndent');\n }\n if (isNullOrUndefined(this.getValue('firstLineIndent'))) {\n this.firstLineIndent = format.getValue('firstLineIndent');\n }\n if (isNullOrUndefined(this.getValue('beforeSpacing'))) {\n this.beforeSpacing = format.getValue('beforeSpacing');\n }\n if (isNullOrUndefined(this.getValue('afterSpacing'))) {\n this.afterSpacing = format.getValue('afterSpacing');\n }\n if (isNullOrUndefined(this.getValue('lineSpacing'))) {\n this.lineSpacing = format.getValue('lineSpacing');\n }\n if (isNullOrUndefined(this.getValue('lineSpacingType'))) {\n this.lineSpacingType = format.getValue('lineSpacingType');\n }\n if (isNullOrUndefined(this.getValue('textAlignment'))) {\n this.textAlignment = format.getValue('textAlignment');\n }\n if (isNullOrUndefined(this.getValue('outlineLevel'))) {\n this.outlineLevel = format.getValue('outlineLevel');\n }\n if (isNullOrUndefined(this.listFormat)) {\n this.listFormat.mergeFormat(format.listFormat);\n }\n };\n WParagraphFormat.uniqueParagraphFormats = new WUniqueFormats();\n WParagraphFormat.uniqueFormatType = 3;\n return WParagraphFormat;\n}());\nexport { WParagraphFormat };\n","import { ParagraphWidget } from '../viewer/page';\nimport { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { WParagraphStyle } from './style';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WCharacterFormat = /** @class */ (function () {\n function WCharacterFormat(node) {\n this.uniqueCharacterFormat = undefined;\n this.ownerBase = undefined;\n this.baseCharStyle = undefined;\n this.ownerBase = node;\n }\n Object.defineProperty(WCharacterFormat.prototype, \"bold\", {\n get: function () {\n return this.getPropertyValue('bold');\n },\n set: function (value) {\n this.setPropertyValue('bold', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"italic\", {\n get: function () {\n return this.getPropertyValue('italic');\n },\n set: function (value) {\n this.setPropertyValue('italic', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"fontSize\", {\n get: function () {\n return this.getPropertyValue('fontSize');\n },\n set: function (value) {\n this.setPropertyValue('fontSize', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"fontFamily\", {\n get: function () {\n return this.getPropertyValue('fontFamily');\n },\n set: function (value) {\n this.setPropertyValue('fontFamily', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"underline\", {\n get: function () {\n return this.getPropertyValue('underline');\n },\n set: function (value) {\n this.setPropertyValue('underline', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"strikethrough\", {\n get: function () {\n return this.getPropertyValue('strikethrough');\n },\n set: function (value) {\n this.setPropertyValue('strikethrough', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"baselineAlignment\", {\n get: function () {\n return this.getPropertyValue('baselineAlignment');\n },\n set: function (value) {\n this.setPropertyValue('baselineAlignment', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"highlightColor\", {\n get: function () {\n return this.getPropertyValue('highlightColor');\n },\n set: function (value) {\n this.setPropertyValue('highlightColor', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCharacterFormat.prototype, \"fontColor\", {\n get: function () {\n return this.getPropertyValue('fontColor');\n },\n set: function (value) {\n this.setPropertyValue('fontColor', value);\n },\n enumerable: true,\n configurable: true\n });\n WCharacterFormat.prototype.getPropertyValue = function (property) {\n if (!this.hasValue(property)) {\n var charStyleValue = this.checkCharacterStyle(property);\n if (!isNullOrUndefined(charStyleValue)) {\n return charStyleValue;\n }\n else {\n var baseStyleValue = this.checkBaseStyle(property);\n if (!isNullOrUndefined(baseStyleValue)) {\n return baseStyleValue;\n }\n }\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(WCharacterFormat.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueCharacterFormat) && this.uniqueCharacterFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueCharacterFormat.propertiesHash.get(propertyType);\n }\n }\n return this.getDefaultValue(property);\n };\n WCharacterFormat.prototype.getDefaultValue = function (property) {\n var propertyType = WUniqueFormat.getPropertyType(WCharacterFormat.uniqueFormatType, property);\n var docCharacterFormat = this.documentCharacterFormat();\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(docCharacterFormat) && !isNullOrUndefined(docCharacterFormat.uniqueCharacterFormat) && docCharacterFormat.uniqueCharacterFormat.propertiesHash.containsKey(propertyType)) {\n return docCharacterFormat.uniqueCharacterFormat.propertiesHash.get(propertyType);\n }\n else {\n return WCharacterFormat.getPropertyDefaultValue(property);\n }\n };\n WCharacterFormat.prototype.documentCharacterFormat = function () {\n var docCharacterFormat;\n if (!isNullOrUndefined(this.ownerBase)) {\n if (!isNullOrUndefined(this.ownerBase.paragraph)) {\n docCharacterFormat = this.ownerBase.paragraph.bodyWidget.page.viewer.characterFormat;\n }\n else {\n if (!isNullOrUndefined(this.ownerBase.bodyWidget)) {\n docCharacterFormat = this.ownerBase.bodyWidget.page.viewer.characterFormat;\n }\n }\n }\n return docCharacterFormat;\n };\n WCharacterFormat.prototype.checkBaseStyle = function (property) {\n /* tslint:disable-next-line:no-any */\n var baseStyle;\n if (!isNullOrUndefined(this.ownerBase)) {\n if (!isNullOrUndefined(this.ownerBase.paragraph)) {\n baseStyle = this.ownerBase.paragraph.paragraphFormat.baseStyle;\n }\n else {\n // tslint:disable-next-line:max-line-length\n if ((this.ownerBase instanceof ParagraphWidget) && !isNullOrUndefined(this.ownerBase.paragraphFormat)) {\n baseStyle = this.ownerBase.paragraphFormat.baseStyle;\n }\n else {\n if (!isNullOrUndefined(this.ownerBase instanceof WParagraphStyle)) {\n baseStyle = this.ownerBase.basedOn;\n }\n }\n }\n }\n while (!isNullOrUndefined(baseStyle)) {\n if (baseStyle.characterFormat.hasValue(property)) {\n break;\n }\n else {\n baseStyle = baseStyle.basedOn;\n }\n }\n if (!isNullOrUndefined(baseStyle)) {\n var propertyType = WUniqueFormat.getPropertyType(WCharacterFormat.uniqueFormatType, property);\n return baseStyle.characterFormat.uniqueCharacterFormat.propertiesHash.get(propertyType);\n }\n return undefined;\n };\n WCharacterFormat.prototype.checkCharacterStyle = function (property) {\n /* tslint:disable-next-line:no-any */\n var baseStyle = this.baseCharStyle;\n if (!isNullOrUndefined(baseStyle)) {\n while (!isNullOrUndefined(baseStyle) && baseStyle.name !== 'Default Paragraph Font') {\n var hasKey = baseStyle.characterFormat.hasValue(property);\n if (hasKey) {\n var returnPropertyType = WUniqueFormat.getPropertyType(WCharacterFormat.uniqueFormatType, property);\n return baseStyle.characterFormat.uniqueCharacterFormat.propertiesHash.get(returnPropertyType);\n }\n else {\n baseStyle = baseStyle.basedOn;\n }\n }\n }\n return undefined;\n };\n WCharacterFormat.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WCharacterFormat.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueCharacterFormat)) {\n this.initializeUniqueCharacterFormat(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueCharacterFormat.uniqueFormatType, property);\n if (this.uniqueCharacterFormat.propertiesHash.containsKey(propertyType) &&\n // tslint:disable-next-line:max-line-length\n this.uniqueCharacterFormat.propertiesHash.get(propertyType) === value) {\n return;\n }\n // tslint:disable-next-line:max-line-length\n this.uniqueCharacterFormat = WCharacterFormat.uniqueCharacterFormats.updateUniqueFormat(this.uniqueCharacterFormat, property, value);\n }\n };\n WCharacterFormat.prototype.initializeUniqueCharacterFormat = function (property, propValue) {\n var uniqueCharFormatTemp = new Dictionary();\n this.addUniqueCharacterFormat('fontColor', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('fontFamily', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('fontSize', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('bold', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('italic', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('underline', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('strikethrough', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('baselineAlignment', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('highlightColor', property, propValue, uniqueCharFormatTemp);\n this.addUniqueCharacterFormat('styleName', property, propValue, uniqueCharFormatTemp);\n // tslint:disable-next-line:max-line-length\n this.uniqueCharacterFormat = WCharacterFormat.uniqueCharacterFormats.addUniqueFormat(uniqueCharFormatTemp, WCharacterFormat.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WCharacterFormat.prototype.addUniqueCharacterFormat = function (property, modifiedProperty, propValue, uniqueCharFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WCharacterFormat.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueCharFormatTemp.add(propertyType, propValue);\n }\n };\n WCharacterFormat.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'bold':\n value = false;\n break;\n case 'italic':\n value = false;\n break;\n case 'fontSize':\n value = 11;\n break;\n case 'underline':\n value = 'None';\n break;\n case 'strikethrough':\n value = 'None';\n break;\n case 'baselineAlignment':\n value = 'Normal';\n break;\n case 'highlightColor':\n value = 'NoColor';\n break;\n case 'fontColor':\n value = '#000000';\n break;\n case 'fontFamily':\n value = 'Calibri';\n break;\n case 'styleName':\n value = 'Default Paragraph Font';\n break;\n }\n return value;\n };\n WCharacterFormat.prototype.isEqualFormat = function (format) {\n return (this.fontSize === format.fontSize\n && this.fontFamily === format.fontFamily\n && this.bold === format.bold\n && this.italic === format.italic\n && this.baselineAlignment === format.baselineAlignment\n && this.underline === format.underline\n && this.fontColor === format.fontColor\n && this.strikethrough === format.strikethrough\n && this.highlightColor === format.highlightColor);\n };\n WCharacterFormat.prototype.isSameFormat = function (format) {\n return this.baseCharStyle === format.baseCharStyle &&\n this.uniqueCharacterFormat === format.uniqueCharacterFormat;\n };\n WCharacterFormat.prototype.cloneFormat = function () {\n var format = new WCharacterFormat(undefined);\n format.uniqueCharacterFormat = this.uniqueCharacterFormat;\n format.baseCharStyle = this.baseCharStyle;\n return format;\n };\n WCharacterFormat.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueCharacterFormat) && !isNullOrUndefined(this.uniqueCharacterFormat.propertiesHash)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueCharacterFormat.uniqueFormatType, property);\n return this.uniqueCharacterFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WCharacterFormat.prototype.clearFormat = function () {\n if (!isNullOrUndefined(this.uniqueCharacterFormat) && this.uniqueCharacterFormat.referenceCount === 0) {\n WCharacterFormat.uniqueCharacterFormats.remove(this.uniqueCharacterFormat);\n }\n this.uniqueCharacterFormat = undefined;\n this.baseCharStyle = undefined;\n };\n WCharacterFormat.prototype.destroy = function () {\n this.clearFormat();\n };\n WCharacterFormat.prototype.copyFormat = function (format) {\n if (!isNullOrUndefined(format)) {\n if (!isNullOrUndefined(format.uniqueCharacterFormat) && format.uniqueCharacterFormat.propertiesHash) {\n this.updateUniqueCharacterFormat(format);\n }\n if (!isNullOrUndefined(format.baseCharStyle)) {\n this.baseCharStyle = format.baseCharStyle;\n }\n }\n };\n WCharacterFormat.prototype.updateUniqueCharacterFormat = function (format) {\n var hash = undefined;\n if (this.uniqueCharacterFormat) {\n hash = this.uniqueCharacterFormat.mergeProperties(format.uniqueCharacterFormat);\n if (this.uniqueCharacterFormat.referenceCount === 0) {\n WCharacterFormat.uniqueCharacterFormats.remove(this.uniqueCharacterFormat);\n this.uniqueCharacterFormat = undefined;\n }\n }\n this.uniqueCharacterFormat = new WUniqueFormat(WCharacterFormat.uniqueFormatType);\n if (isNullOrUndefined(hash)) {\n hash = this.uniqueCharacterFormat.mergeProperties(format.uniqueCharacterFormat);\n }\n this.uniqueCharacterFormat = WCharacterFormat.uniqueCharacterFormats.addUniqueFormat(hash, WCharacterFormat.uniqueFormatType);\n };\n WCharacterFormat.clear = function () {\n this.uniqueCharacterFormats.clear();\n };\n WCharacterFormat.prototype.ApplyStyle = function (baseCharStyle) {\n this.baseCharStyle = baseCharStyle;\n };\n /**\n * For internal use\n * @private\n */\n WCharacterFormat.prototype.getValue = function (property) {\n return this.hasValue(property) ? this.getPropertyValue(property) : undefined;\n };\n /**\n * For internal use\n * @private\n */\n WCharacterFormat.prototype.mergeFormat = function (format) {\n if (isNullOrUndefined(this.getValue('bold'))) {\n this.bold = format.getValue('bold');\n }\n if (isNullOrUndefined(this.getValue('italic'))) {\n this.italic = format.getValue('italic');\n }\n if (isNullOrUndefined(this.getValue('fontSize'))) {\n this.fontSize = format.getValue('fontSize');\n }\n if (isNullOrUndefined(this.getValue('fontFamily'))) {\n this.fontFamily = format.getValue('fontFamily');\n }\n if (isNullOrUndefined(this.getValue('underline'))) {\n this.underline = format.getValue('underline');\n }\n if (isNullOrUndefined(this.getValue('strikethrough'))) {\n this.strikethrough = format.getValue('strikethrough');\n }\n if (isNullOrUndefined(this.getValue('baselineAlignment'))) {\n this.baselineAlignment = format.getValue('baselineAlignment');\n }\n if (isNullOrUndefined(this.getValue('highlightColor'))) {\n this.highlightColor = format.getValue('highlightColor');\n }\n if (isNullOrUndefined(this.getValue('fontColor'))) {\n this.fontColor = format.getValue('fontColor');\n }\n };\n WCharacterFormat.uniqueCharacterFormats = new WUniqueFormats();\n WCharacterFormat.uniqueFormatType = 2;\n return WCharacterFormat;\n}());\nexport { WCharacterFormat };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { FieldElementBox } from '../viewer/page';\n/**\n * @private\n */\nvar HelperMethods = /** @class */ (function () {\n function HelperMethods() {\n }\n /**\n * Inserts text at specified index in string.\n * @param {string} spanText\n * @param {number} index\n * @param {string} text\n * @private\n */\n HelperMethods.insert = function (spanText, index, text) {\n if (index >= 0) {\n return [spanText.slice(0, index) + text + spanText.slice(index)].join('');\n }\n else {\n return text + this;\n }\n };\n /**\n * Removes text from specified index in string.\n * @param {string} text\n * @param {number} index\n * @param {number} length\n * @private\n */\n HelperMethods.remove = function (text, index, length) {\n if (index === 0) {\n return text.substring(index + 1, text.length);\n }\n else {\n return text.substring(0, index) + text.substring(index + 1, text.length);\n }\n };\n /**\n * Returns the index of word split character in a string.\n * @param {string} text\n * @param {string[]} wordSplitCharacter\n * @private\n */\n /* tslint:disable:no-any */\n HelperMethods.indexOfAny = function (text, wordSplitCharacter) {\n var index = undefined;\n for (var j = 0; j < wordSplitCharacter.length; j++) {\n var temp = text.indexOf(wordSplitCharacter[j]);\n if (temp !== -1 && isNullOrUndefined(index)) {\n index = temp;\n }\n else if (temp !== -1 && temp < index) {\n index = temp;\n }\n }\n return isNullOrUndefined(index) ? -1 : index;\n };\n /**\n * Returns the last index of word split character in a string.\n * @param {string} text\n * @param {string[]} wordSplitCharacter\n * @private\n */\n HelperMethods.lastIndexOfAny = function (text, wordSplitCharacter) {\n for (var i = text.length - 1; i >= 0; i--) {\n for (var j = 0; j <= wordSplitCharacter.length - 1; j++) {\n if (text[i] === wordSplitCharacter[j]) {\n return i;\n }\n }\n }\n return -1;\n };\n /**\n * Adds css styles to document header.\n * @param {string} css\n * @private\n */\n HelperMethods.addCssStyle = function (css) {\n var style = document.createElement('style');\n if (style.style.cssText) {\n style.style.cssText = css;\n }\n else {\n style.appendChild(document.createTextNode(css));\n }\n document.getElementsByTagName('head')[0].appendChild(style);\n };\n /**\n * Gets highlight color code.\n * @param {HighlightColor} highlightColor\n * @private\n */\n HelperMethods.getHighlightColorCode = function (highlightColor) {\n var color = '#ffffff';\n switch (highlightColor) {\n case 'Yellow':\n color = '#ffff00';\n break;\n case 'BrightGreen':\n color = '#00ff00';\n break;\n case 'Turquoise':\n color = '#00ffff';\n break;\n case 'Pink':\n color = '#ff00ff';\n break;\n case 'Blue':\n color = '#0000ff';\n break;\n case 'Red':\n color = '#ff0000';\n break;\n case 'DarkBlue':\n color = '#000080';\n break;\n case 'Teal':\n color = '#008080';\n break;\n case 'Green':\n color = '#008000';\n break;\n case 'Violet':\n color = '#800080';\n break;\n case 'DarkRed':\n color = '#800000';\n break;\n case 'DarkYellow':\n color = '#808000';\n break;\n case 'Gray50':\n color = '#808080';\n break;\n case 'Gray25':\n color = '#c0c0c0';\n break;\n case 'Black':\n color = '#000000';\n break;\n }\n return color;\n };\n /**\n * Converts point to pixel.\n * @param {number} point\n * @private\n */\n HelperMethods.convertPointToPixel = function (point) {\n var pixel = HelperMethods.round((point * 96 / 72), 5);\n return pixel;\n };\n /**\n * Converts pixel to point.\n * @param {number} pixel\n * @private\n */\n HelperMethods.convertPixelToPoint = function (pixel) {\n var point = HelperMethods.round((pixel * 72 / 96), 5);\n return point;\n };\n /**\n * Return true if field linked\n * @private\n */\n HelperMethods.isLinkedFieldCharacter = function (inline) {\n if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n return !isNullOrUndefined(inline.fieldEnd);\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 2) {\n return !isNullOrUndefined(inline.fieldBegin) && !isNullOrUndefined(inline.fieldEnd);\n }\n else {\n return !isNullOrUndefined(inline.fieldBegin);\n }\n };\n /**\n * Removes white space in a string.\n * @param {string} text\n * @private\n */\n HelperMethods.removeSpace = function (text) {\n if (!isNullOrUndefined(text) && text.length !== 0) {\n for (var i = 0; i < text.length; i++) {\n if (text.charAt(i) === ' ') {\n //replace the space by empty string in string\n text = text.replace(' ', '');\n }\n }\n }\n return text;\n };\n /**\n * Trims white space at start of the string.\n * @param {string} text\n * @private\n */\n HelperMethods.trimStart = function (text) {\n var i = 0;\n for (i; i < text.length; i++) {\n if (text[i] !== ' ') {\n break;\n }\n }\n return text.substring(i, text.length);\n };\n /**\n * Trims white space at end of the string.\n * @param {string} text\n * @private\n */\n HelperMethods.trimEnd = function (text) {\n var i = text.length - 1;\n for (i; i >= 0; i--) {\n if (text[i] !== ' ') {\n break;\n }\n }\n return text.substring(0, i + 1);\n };\n /**\n * Checks whether string ends with whitespace.\n * @param {string} text\n * @private\n */\n HelperMethods.endsWith = function (text) {\n if (!isNullOrUndefined(text) && text.length !== 0) {\n return text[text.length - 1] === ' ';\n }\n return false;\n };\n /**\n * @private\n * Write Characterformat\n * @param {any} characterFormat\n * @param {boolean} isInline\n * @param {WCharacterFormat} format\n */\n HelperMethods.writeCharacterFormat = function (characterFormat, isInline, format) {\n characterFormat.bold = isInline ? format.bold : format.getValue('bold');\n characterFormat.italic = isInline ? format.italic : format.getValue('italic');\n characterFormat.fontSize = isInline ? format.fontSize : format.getValue('fontSize');\n characterFormat.fontFamily = isInline ? format.fontFamily : format.getValue('fontFamily');\n characterFormat.underline = isInline ? format.underline : format.getValue('underline');\n characterFormat.strikethrough = isInline ? format.strikethrough : format.getValue('strikethrough');\n characterFormat.baselineAlignment = isInline ? format.baselineAlignment : format.getValue('baselineAlignment');\n characterFormat.highlightColor = isInline ? format.highlightColor : format.getValue('highlightColor');\n characterFormat.fontColor = isInline ? format.fontColor : format.getValue('fontColor');\n characterFormat.styleName = !isNullOrUndefined(format.baseCharStyle) ? format.baseCharStyle.name : undefined;\n };\n /* tslint:enable:no-any */\n /**\n * Rounds the values with specified decimal digits.\n * @param {number} value\n * @param {number} decimalDigits\n * @private\n */\n HelperMethods.round = function (value, decimalDigits) {\n var temp = value;\n for (var i = 0; i < decimalDigits; i++) {\n temp = temp * 10;\n }\n temp = Math.round(temp);\n for (var i = 0; i < decimalDigits; i++) {\n temp = temp / 10;\n }\n return temp;\n };\n /**\n * @private\n */\n HelperMethods.wordBefore = '\\\\b';\n /**\n * @private\n */\n HelperMethods.wordAfter = '\\\\b';\n /**\n * @private\n */\n HelperMethods.wordSplitCharacters = [' ', ',', '.', ':', ';', '<', '>', '=',\n '+', '-', '_', '{', '}', '[', ']', '`', '~', '!', '@', '#', '$', '%', '^', '&',\n '*', '(', ')', '\"', '?', '/', '|', '\\\\', '”'];\n return HelperMethods;\n}());\nexport { HelperMethods };\n/**\n * @private\n */\nvar Point = /** @class */ (function () {\n function Point(xPosition, yPosition) {\n this.xIn = 0;\n this.yIn = 0;\n this.xIn = xPosition;\n this.yIn = yPosition;\n }\n Object.defineProperty(Point.prototype, \"x\", {\n /**\n * Gets or sets x value.\n * @private\n */\n get: function () {\n return this.xIn;\n },\n set: function (value) {\n this.xIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Point.prototype, \"y\", {\n /**\n * Gets or sets y value.\n * @private\n */\n get: function () {\n return this.yIn;\n },\n set: function (value) {\n this.yIn = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n Point.prototype.copy = function (point) {\n this.xIn = point.xIn;\n this.yIn = point.yIn;\n };\n /**\n * Destroys the internal objects maintained.\n * @returns void\n */\n Point.prototype.destroy = function () {\n this.xIn = undefined;\n this.yIn = undefined;\n };\n return Point;\n}());\nexport { Point };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { WParagraphFormat } from './paragraph-format';\nimport { WCharacterFormat } from './character-format';\nimport { HelperMethods } from '../editor/editor-helper';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WStyle = /** @class */ (function () {\n function WStyle() {\n }\n return WStyle;\n}());\nexport { WStyle };\n/**\n * @private\n */\nvar WParagraphStyle = /** @class */ (function (_super) {\n __extends(WParagraphStyle, _super);\n function WParagraphStyle(node) {\n var _this = _super.call(this) || this;\n _this.ownerBase = node;\n _this.paragraphFormat = new WParagraphFormat(_this);\n _this.characterFormat = new WCharacterFormat(_this);\n return _this;\n }\n WParagraphStyle.prototype.destroy = function () {\n this.characterFormat.destroy();\n this.paragraphFormat.destroy();\n };\n WParagraphStyle.prototype.copyStyle = function (paraStyle) {\n this.name = paraStyle.name;\n this.ownerBase = paraStyle.ownerBase;\n this.type = paraStyle.type;\n this.next = paraStyle.next;\n this.basedOn = paraStyle.basedOn;\n this.link = paraStyle.link;\n this.characterFormat.copyFormat(paraStyle.characterFormat);\n this.paragraphFormat.copyFormat(paraStyle.paragraphFormat);\n };\n return WParagraphStyle;\n}(WStyle));\nexport { WParagraphStyle };\n/**\n * @private\n */\nvar WCharacterStyle = /** @class */ (function (_super) {\n __extends(WCharacterStyle, _super);\n function WCharacterStyle(node) {\n var _this = _super.call(this) || this;\n _this.ownerBase = node;\n _this.characterFormat = new WCharacterFormat(_this);\n return _this;\n }\n WCharacterStyle.prototype.destroy = function () {\n this.characterFormat.destroy();\n };\n WCharacterStyle.prototype.copyStyle = function (charStyle) {\n this.name = charStyle.name;\n this.ownerBase = charStyle.ownerBase;\n this.type = charStyle.type;\n this.next = charStyle.next;\n this.basedOn = charStyle.basedOn;\n this.characterFormat.copyFormat(charStyle.characterFormat);\n };\n return WCharacterStyle;\n}(WStyle));\nexport { WCharacterStyle };\n/**\n * @private\n */\nvar WStyles = /** @class */ (function () {\n function WStyles() {\n this.collection = [];\n /* tslint:enable:no-any */\n }\n Object.defineProperty(WStyles.prototype, \"length\", {\n get: function () {\n return this.collection.length;\n },\n enumerable: true,\n configurable: true\n });\n WStyles.prototype.remove = function (item) {\n this.collection = this.collection.filter(function (a) { return (a.name !== item.name); });\n };\n WStyles.prototype.push = function (item) {\n if (item != null && item !== undefined) {\n this.collection.push(item);\n }\n return 1;\n };\n WStyles.prototype.getItem = function (index) {\n if (this.collection.length > index) {\n return this.collection[index];\n }\n return null;\n };\n WStyles.prototype.indexOf = function (item) {\n return this.collection.indexOf(item);\n };\n WStyles.prototype.contains = function (item) {\n var index = this.collection.indexOf(item);\n return index > -1 && index < this.collection.length;\n };\n WStyles.prototype.clear = function () {\n while (this.collection.length > 0) {\n this.collection.pop();\n }\n };\n WStyles.prototype.findByName = function (name, type) {\n var returnStyle;\n for (var _i = 0, _a = this.collection; _i < _a.length; _i++) {\n var value = _a[_i];\n if (value.name === name) {\n returnStyle = value;\n if (!isNullOrUndefined(type) && value.type === type) {\n returnStyle = value;\n }\n }\n }\n return returnStyle;\n };\n WStyles.prototype.getStyleNames = function (type) {\n return this.collection.filter(function (a) { return (a.type === type); }).map(function (a) { return a.name; });\n };\n /* tslint:disable:no-any */\n WStyles.prototype.getStyles = function (type) {\n var styles = this.collection.filter(function (a) { return (a.type === type); }).map(function (a) { return a; });\n var styleObjects = [];\n for (var _i = 0, styles_1 = styles; _i < styles_1.length; _i++) {\n var style = styles_1[_i];\n var returnStyle = {};\n var returnStyleObject = {};\n returnStyleObject.characterFormat = {};\n HelperMethods.writeCharacterFormat(returnStyleObject.characterFormat, true, style.characterFormat);\n returnStyle.name = style.name;\n returnStyle.style = JSON.stringify(returnStyleObject);\n styleObjects.push(returnStyle);\n }\n return styleObjects;\n };\n return WStyles;\n}());\nexport { WStyles };\n","import { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WBorder = /** @class */ (function () {\n function WBorder(node) {\n this.uniqueBorderFormat = undefined;\n this.ownerBase = undefined;\n this.ownerBase = node;\n }\n Object.defineProperty(WBorder.prototype, \"color\", {\n get: function () {\n return this.getPropertyValue('color');\n },\n set: function (value) {\n this.setPropertyValue('color', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorder.prototype, \"lineStyle\", {\n get: function () {\n return this.getPropertyValue('lineStyle');\n },\n set: function (value) {\n this.setPropertyValue('lineStyle', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorder.prototype, \"lineWidth\", {\n get: function () {\n return this.getPropertyValue('lineWidth');\n },\n set: function (value) {\n this.setPropertyValue('lineWidth', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorder.prototype, \"shadow\", {\n get: function () {\n return this.getPropertyValue('shadow');\n },\n set: function (value) {\n this.setPropertyValue('shadow', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorder.prototype, \"space\", {\n get: function () {\n return this.getPropertyValue('space');\n },\n set: function (value) {\n this.setPropertyValue('space', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorder.prototype, \"hasNoneStyle\", {\n get: function () {\n return this.getPropertyValue('hasNoneStyle');\n },\n set: function (value) {\n this.setPropertyValue('hasNoneStyle', value);\n },\n enumerable: true,\n configurable: true\n });\n WBorder.prototype.getPropertyValue = function (property) {\n var hasValue = this.hasValue(property);\n if (hasValue) {\n var propertyType = WUniqueFormat.getPropertyType(WBorder.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueBorderFormat) && this.uniqueBorderFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueBorderFormat.propertiesHash.get(propertyType);\n }\n }\n return WBorder.getPropertyDefaultValue(property);\n };\n WBorder.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WBorder.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueBorderFormat)) {\n this.initializeUniqueBorder(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueBorderFormat.uniqueFormatType, property);\n if (this.uniqueBorderFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueBorderFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n this.uniqueBorderFormat = WBorder.uniqueBorderFormats.updateUniqueFormat(this.uniqueBorderFormat, property, value);\n }\n };\n WBorder.prototype.initializeUniqueBorder = function (property, propValue) {\n var uniqueBorderFormatTemp = new Dictionary();\n this.addUniqueBorderFormat('color', property, propValue, uniqueBorderFormatTemp);\n this.addUniqueBorderFormat('lineStyle', property, propValue, uniqueBorderFormatTemp);\n this.addUniqueBorderFormat('lineWidth', property, propValue, uniqueBorderFormatTemp);\n this.addUniqueBorderFormat('shadow', property, propValue, uniqueBorderFormatTemp);\n this.addUniqueBorderFormat('space', property, propValue, uniqueBorderFormatTemp);\n this.addUniqueBorderFormat('hasNoneStyle', property, propValue, uniqueBorderFormatTemp);\n this.uniqueBorderFormat = WBorder.uniqueBorderFormats.addUniqueFormat(uniqueBorderFormatTemp, WBorder.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WBorder.prototype.addUniqueBorderFormat = function (property, modifiedProperty, propValue, uniqueBorderFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WBorder.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueBorderFormatTemp.add(propertyType, propValue);\n }\n else {\n uniqueBorderFormatTemp.add(propertyType, WBorder.getPropertyDefaultValue(property));\n }\n };\n WBorder.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'color':\n value = '#000000';\n break;\n case 'lineStyle':\n value = 'None';\n break;\n case 'lineWidth':\n value = 0;\n break;\n case 'shadow':\n value = false;\n break;\n case 'space':\n value = 0;\n break;\n case 'hasNoneStyle':\n value = false;\n break;\n }\n return value;\n };\n WBorder.prototype.getLineWidth = function () {\n /* tslint:disable */\n switch (this.lineStyle) {\n case 'None':\n case 'Cleared':\n return 0;\n case 'Triple':\n case 'Double':\n case 'ThinThickSmallGap':\n case 'ThickThinSmallGap':\n case 'ThinThickThinSmallGap':\n case 'ThinThickMediumGap':\n case 'ThickThinMediumGap':\n case 'ThinThickThinMediumGap':\n case 'ThinThickLargeGap':\n case 'ThickThinLargeGap':\n case 'ThinThickThinLargeGap':\n case 'Emboss3D':\n case 'Engrave3D':\n {\n var lineArray = this.getBorderLineWidthArray(this.lineStyle, this.lineWidth);\n var width = 0;\n for (var i = 0; i < lineArray.length; i++) {\n width += lineArray[i];\n }\n return width;\n }\n case 'Single':\n case 'DashLargeGap':\n case 'DashSmallGap':\n case 'Dot':\n case 'DashDot':\n case 'DashDotDot':\n case 'Thick':\n return this.lineWidth;\n case 'SingleWavy':\n return (this.lineWidth === 1.5 ? 3 : 2.5); //Double wave border only draw with the fixed width\n case 'DoubleWavy':\n return (6.75); //Double wave border only draw with the fixed width\n case 'DashDotStroked':\n case 'Outset':\n return this.lineWidth;\n }\n return this.lineWidth;\n /* tslint:enable */\n };\n WBorder.prototype.getBorderLineWidthArray = function (lineStyle, lineWidth) {\n var borderLineArray = [lineWidth];\n switch (lineStyle) {\n case 'Double':\n borderLineArray = [1, 1, 1];\n break;\n case 'ThinThickSmallGap':\n borderLineArray = [1, -0.75, -0.75];\n break;\n case 'ThickThinSmallGap':\n borderLineArray = [-0.75, -0.75, 1];\n break;\n case 'ThinThickMediumGap':\n borderLineArray = [1, 0.5, 0.5];\n break;\n case 'ThickThinMediumGap':\n borderLineArray = [0.5, 0.5, 1];\n break;\n case 'ThinThickLargeGap':\n borderLineArray = [-1.5, 1, -0.75];\n break;\n case 'ThickThinLargeGap':\n borderLineArray = [-0.75, 1, -1.5];\n break;\n case 'Triple':\n borderLineArray = [1, 1, 1, 1, 1];\n break;\n case 'ThinThickThinSmallGap':\n borderLineArray = [-0.75, -0.75, 1, -0.75, -0.75];\n break;\n case 'ThinThickThinMediumGap':\n borderLineArray = [0.5, 0.5, 1, 0.5, 0.5];\n break;\n case 'ThinThickThinLargeGap':\n borderLineArray = [-0.75, 1, -1.5, 1, -0.75];\n break;\n case 'Emboss3D':\n case 'Engrave3D':\n borderLineArray = [0.25, 0, 1, 0, 0.25];\n break;\n }\n if (borderLineArray.length === 1) {\n return [lineWidth];\n }\n for (var i = 0; i < borderLineArray.length; i++) {\n if (borderLineArray[i] >= 0) {\n borderLineArray[i] = borderLineArray[i] * lineWidth;\n }\n else {\n borderLineArray[i] = Math.abs(borderLineArray[i]);\n }\n }\n return borderLineArray;\n };\n WBorder.prototype.getBorderWeight = function () {\n var weight = 0;\n var numberOfLines = this.getNumberOfLines();\n var borderNumber = this.getBorderNumber();\n switch (this.lineStyle) {\n case 'Single':\n case 'DashSmallGap':\n case 'DashDot':\n case 'DashDotDot':\n case 'Double':\n case 'Triple':\n case 'ThinThickSmallGap':\n case 'ThickThinSmallGap':\n case 'ThinThickThinSmallGap':\n case 'ThinThickMediumGap':\n case 'ThickThinMediumGap':\n case 'ThinThickThinMediumGap':\n case 'ThinThickLargeGap':\n case 'ThickThinLargeGap':\n case 'ThinThickThinLargeGap':\n case 'SingleWavy':\n case 'DoubleWavy':\n case 'DashDotStroked':\n case 'Emboss3D':\n case 'Engrave3D':\n case 'Outset':\n case 'Inset':\n case 'Thick':\n weight = numberOfLines * borderNumber;\n break;\n case 'Dot':\n case 'DashLargeGap':\n weight = 1;\n break;\n }\n return weight;\n };\n WBorder.prototype.getBorderNumber = function () {\n var borderNumber = 0;\n switch (this.lineStyle) {\n case 'Single':\n borderNumber = 1;\n break;\n case 'Thick':\n borderNumber = 2;\n break;\n case 'Double':\n borderNumber = 3;\n break;\n case 'Dot':\n borderNumber = 4;\n break;\n case 'DashLargeGap'://dashed.\n borderNumber = 5;\n break;\n case 'DashDot':\n borderNumber = 6;\n break;\n case 'DashDotDot':\n borderNumber = 7;\n break;\n case 'Triple':\n borderNumber = 8;\n break;\n case 'ThinThickSmallGap':\n borderNumber = 9;\n break;\n case 'ThickThinSmallGap':\n borderNumber = 10;\n break;\n case 'ThinThickThinSmallGap':\n borderNumber = 11;\n break;\n case 'ThinThickMediumGap':\n borderNumber = 12;\n break;\n case 'ThickThinMediumGap':\n borderNumber = 13;\n break;\n case 'ThinThickThinMediumGap':\n borderNumber = 14;\n break;\n case 'ThinThickLargeGap':\n borderNumber = 15;\n break;\n case 'ThickThinLargeGap':\n borderNumber = 16;\n break;\n case 'ThinThickThinLargeGap':\n borderNumber = 17;\n break;\n case 'SingleWavy'://wave.\n borderNumber = 18;\n break;\n case 'DoubleWavy':\n borderNumber = 19;\n break;\n case 'DashSmallGap':\n borderNumber = 20;\n break;\n case 'DashDotStroked':\n borderNumber = 21;\n break;\n case 'Emboss3D':\n borderNumber = 22;\n break;\n case 'Engrave3D':\n borderNumber = 23;\n break;\n case 'Outset':\n borderNumber = 24;\n break;\n case 'Inset':\n borderNumber = 25;\n break;\n }\n return borderNumber;\n };\n WBorder.prototype.getNumberOfLines = function () {\n //ToDo: Need to analyze more on this.\n var value = 0;\n switch (this.lineStyle) {\n case 'Single':\n case 'Dot':\n case 'DashSmallGap':\n case 'DashLargeGap':\n case 'DashDot':\n case 'DashDotDot':\n value = 1;\n break;\n case 'Double':\n value = 3;\n break;\n case 'Triple':\n value = 5;\n break;\n case 'ThinThickSmallGap':\n value = 3;\n break;\n case 'ThickThinSmallGap':\n value = 3;\n break;\n case 'ThinThickThinSmallGap':\n value = 5;\n break;\n case 'ThinThickMediumGap':\n value = 3;\n break;\n case 'ThickThinMediumGap':\n value = 3;\n break;\n case 'ThinThickThinMediumGap':\n value = 5;\n break;\n case 'ThinThickLargeGap':\n value = 3;\n break;\n case 'ThickThinLargeGap':\n value = 3;\n break;\n case 'ThinThickThinLargeGap':\n value = 5;\n break;\n case 'SingleWavy':\n value = 1;\n break;\n case 'DoubleWavy':\n value = 2;\n break;\n case 'DashDotStroked':\n value = 1;\n break;\n case 'Emboss3D':\n case 'Engrave3D':\n value = 3;\n break;\n case 'Outset':\n case 'Inset':\n case 'Thick':\n value = 1;\n break;\n }\n return value;\n };\n WBorder.prototype.getPrecedence = function () {\n var value = 0;\n switch (this.lineStyle) {\n case 'Single':\n value = 1;\n break;\n case 'Thick':\n value = 2;\n break;\n case 'Double':\n value = 3;\n break;\n case 'Dot':\n value = 4;\n break;\n case 'DashLargeGap'://dashed.\n value = 5;\n break;\n case 'DashDot':\n value = 6;\n break;\n case 'DashDotDot':\n value = 7;\n break;\n case 'Triple':\n value = 8;\n break;\n case 'ThinThickSmallGap':\n value = 9;\n break;\n case 'ThickThinSmallGap':\n value = 10;\n break;\n case 'ThinThickThinSmallGap':\n value = 11;\n break;\n case 'ThinThickMediumGap':\n value = 12;\n break;\n case 'ThickThinMediumGap':\n value = 13;\n break;\n case 'ThinThickThinMediumGap':\n value = 14;\n break;\n case 'ThinThickLargeGap':\n value = 15;\n break;\n case 'ThickThinLargeGap':\n value = 16;\n break;\n case 'ThinThickThinLargeGap':\n value = 17;\n break;\n case 'SingleWavy'://wave.\n value = 18;\n break;\n case 'DoubleWavy':\n value = 19;\n break;\n case 'DashSmallGap':\n value = 20;\n break;\n case 'DashDotStroked':\n value = 21;\n break;\n case 'Emboss3D':\n value = 22;\n break;\n case 'Engrave3D':\n value = 23;\n break;\n case 'Outset':\n value = 24;\n break;\n case 'Inset':\n value = 25;\n break;\n }\n return value;\n };\n WBorder.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueBorderFormat)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueBorderFormat.uniqueFormatType, property);\n return this.uniqueBorderFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WBorder.prototype.cloneFormat = function () {\n var border = new WBorder(undefined);\n border.color = this.color;\n border.lineStyle = this.lineStyle;\n border.lineWidth = this.lineWidth;\n border.shadow = this.shadow;\n border.space = this.space;\n return border;\n };\n WBorder.prototype.destroy = function () {\n if (!isNullOrUndefined(this.uniqueBorderFormat)) {\n WBorder.uniqueBorderFormats.remove(this.uniqueBorderFormat);\n }\n this.uniqueBorderFormat = undefined;\n };\n WBorder.prototype.copyFormat = function (border) {\n if (!isNullOrUndefined(border) && !isNullOrUndefined(border.uniqueBorderFormat)) {\n this.color = border.color;\n this.lineStyle = border.lineStyle;\n this.lineWidth = border.lineWidth;\n this.shadow = border.shadow;\n this.space = border.space;\n }\n };\n WBorder.clear = function () {\n this.uniqueBorderFormats.clear();\n };\n WBorder.uniqueBorderFormats = new WUniqueFormats();\n WBorder.uniqueFormatType = 1;\n return WBorder;\n}());\nexport { WBorder };\n","import { WBorder } from './border';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WBorders = /** @class */ (function () {\n function WBorders(node) {\n this.leftIn = new WBorder(this);\n this.rightIn = new WBorder(this);\n this.topIn = new WBorder(this);\n this.bottomIn = new WBorder(this);\n this.horizontalIn = new WBorder(this);\n this.verticalIn = new WBorder(this);\n this.diagonalUpIn = new WBorder(this);\n this.diagonalDownIn = new WBorder(this);\n this.lineWidthIn = 0;\n this.ownerBase = node;\n }\n Object.defineProperty(WBorders.prototype, \"left\", {\n get: function () {\n return this.leftIn;\n },\n set: function (value) {\n this.leftIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorders.prototype, \"right\", {\n get: function () {\n return this.rightIn;\n },\n set: function (value) {\n this.rightIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorders.prototype, \"top\", {\n get: function () {\n return this.topIn;\n },\n set: function (value) {\n this.topIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorders.prototype, \"bottom\", {\n get: function () {\n return this.bottomIn;\n },\n set: function (value) {\n this.bottomIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorders.prototype, \"horizontal\", {\n get: function () {\n return this.horizontalIn;\n },\n set: function (value) {\n this.horizontalIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorders.prototype, \"vertical\", {\n get: function () {\n return this.verticalIn;\n },\n set: function (value) {\n this.verticalIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorders.prototype, \"diagonalUp\", {\n get: function () {\n return this.diagonalUpIn;\n },\n set: function (value) {\n this.diagonalUpIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WBorders.prototype, \"diagonalDown\", {\n get: function () {\n return this.diagonalDownIn;\n },\n set: function (value) {\n this.diagonalDownIn = value;\n },\n enumerable: true,\n configurable: true\n });\n WBorders.prototype.destroy = function () {\n if (!isNullOrUndefined(this.left)) {\n this.left.destroy();\n }\n if (!isNullOrUndefined(this.top)) {\n this.top.destroy();\n }\n if (!isNullOrUndefined(this.bottom)) {\n this.bottom.destroy();\n }\n if (!isNullOrUndefined(this.right)) {\n this.right.destroy();\n }\n if (!isNullOrUndefined(this.horizontal)) {\n this.horizontal.destroy();\n }\n if (!isNullOrUndefined(this.vertical)) {\n this.vertical.destroy();\n }\n if (!isNullOrUndefined(this.diagonalDown)) {\n this.diagonalDown.destroy();\n }\n if (!isNullOrUndefined(this.diagonalUp)) {\n this.diagonalUp.destroy();\n }\n this.topIn = undefined;\n this.bottomIn = undefined;\n this.leftIn = undefined;\n this.rightIn = undefined;\n this.horizontalIn = undefined;\n this.verticalIn = undefined;\n this.diagonalDownIn = undefined;\n this.diagonalUpIn = undefined;\n this.lineWidthIn = undefined;\n this.valueIn = undefined;\n };\n WBorders.prototype.cloneFormat = function () {\n var borders = new WBorders(undefined);\n borders.top = isNullOrUndefined(this.top) ? undefined : this.top.cloneFormat();\n borders.bottom = isNullOrUndefined(this.bottom) ? undefined : this.bottom.cloneFormat();\n borders.left = isNullOrUndefined(this.left) ? undefined : this.left.cloneFormat();\n borders.right = isNullOrUndefined(this.right) ? undefined : this.right.cloneFormat();\n borders.horizontal = isNullOrUndefined(this.horizontal) ? undefined : this.horizontal.cloneFormat();\n borders.vertical = isNullOrUndefined(this.vertical) ? undefined : this.vertical.cloneFormat();\n borders.diagonalUp = isNullOrUndefined(this.diagonalUp) ? undefined : this.diagonalUp.cloneFormat();\n borders.diagonalDown = isNullOrUndefined(this.diagonalDown) ? undefined : this.diagonalDown.cloneFormat();\n return borders;\n };\n WBorders.prototype.copyFormat = function (borders) {\n if (!isNullOrUndefined(borders.left) && borders.left instanceof WBorder) {\n this.left = new WBorder(this);\n this.left.copyFormat(borders.left);\n }\n if (!isNullOrUndefined(borders.right) && borders.right instanceof WBorder) {\n this.right = new WBorder(this);\n this.right.copyFormat(borders.right);\n }\n if (!isNullOrUndefined(borders.top) && borders.top instanceof WBorder) {\n this.top = new WBorder(this);\n this.top.copyFormat(borders.top);\n }\n if (!isNullOrUndefined(borders.bottom) && borders.bottom instanceof WBorder) {\n this.bottom = new WBorder(this);\n this.bottom.copyFormat(borders.bottom);\n }\n if (!isNullOrUndefined(borders.horizontal) && borders.horizontal instanceof WBorder) {\n this.horizontal = new WBorder(this);\n this.horizontal.copyFormat(borders.horizontal);\n }\n if (!isNullOrUndefined(borders.vertical) && borders.vertical instanceof WBorder) {\n this.vertical = new WBorder(this);\n this.vertical.copyFormat(borders.vertical);\n }\n if (!isNullOrUndefined(borders.diagonalDown) && borders.diagonalDown instanceof WBorder) {\n this.diagonalDown = new WBorder(this);\n this.diagonalDown.copyFormat(borders.diagonalDown);\n }\n if (!isNullOrUndefined(borders.diagonalUp) && borders.diagonalUp instanceof WBorder) {\n this.diagonalUp = new WBorder(this);\n this.diagonalUp.copyFormat(borders.diagonalUp);\n }\n };\n return WBorders;\n}());\nexport { WBorders };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { Dictionary } from '../../base/dictionary';\n/**\n * @private\n */\nvar WShading = /** @class */ (function () {\n function WShading(node) {\n this.uniqueShadingFormat = undefined;\n this.ownerBase = undefined;\n this.ownerBase = node;\n }\n Object.defineProperty(WShading.prototype, \"backgroundColor\", {\n get: function () {\n return this.getPropertyValue('backgroundColor');\n },\n set: function (value) {\n this.setPropertyValue('backgroundColor', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WShading.prototype, \"foregroundColor\", {\n get: function () {\n return this.getPropertyValue('foregroundColor');\n },\n set: function (value) {\n this.setPropertyValue('foregroundColor', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WShading.prototype, \"textureStyle\", {\n get: function () {\n return this.getPropertyValue('textureStyle');\n },\n set: function (value) {\n this.setPropertyValue('textureStyle', value);\n },\n enumerable: true,\n configurable: true\n });\n WShading.prototype.getPropertyValue = function (property) {\n var hasValue = this.hasValue(property);\n if (hasValue) {\n var propertyType = WUniqueFormat.getPropertyType(WShading.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueShadingFormat) && this.uniqueShadingFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueShadingFormat.propertiesHash.get(propertyType);\n }\n }\n return WShading.getPropertyDefaultValue(property);\n };\n WShading.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WShading.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueShadingFormat)) {\n this.initializeUniqueShading(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueShadingFormat.uniqueFormatType, property);\n if (this.uniqueShadingFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueShadingFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n this.uniqueShadingFormat = WShading.uniqueShadingFormats.updateUniqueFormat(this.uniqueShadingFormat, property, value);\n }\n };\n WShading.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'backgroundColor':\n value = '#ffffff';\n break;\n case 'foregroundColor':\n value = 'empty';\n break;\n case 'textureStyle':\n value = 'TextureNone';\n break;\n }\n return value;\n };\n WShading.prototype.initializeUniqueShading = function (property, propValue) {\n var uniqueShadingTemp = new Dictionary();\n this.addUniqueShading('backgroundColor', property, propValue, uniqueShadingTemp);\n this.addUniqueShading('foregroundColor', property, propValue, uniqueShadingTemp);\n this.addUniqueShading('textureStyle', property, propValue, uniqueShadingTemp);\n // tslint:disable-next-line:max-line-length \n this.uniqueShadingFormat = WShading.uniqueShadingFormats.addUniqueFormat(uniqueShadingTemp, WShading.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WShading.prototype.addUniqueShading = function (property, modifiedProperty, propValue, uniqueShadingTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WShading.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueShadingTemp.add(propertyType, propValue);\n }\n else {\n uniqueShadingTemp.add(propertyType, WShading.getPropertyDefaultValue(property));\n }\n };\n WShading.prototype.destroy = function () {\n if (!isNullOrUndefined(this.uniqueShadingFormat)) {\n WShading.uniqueShadingFormats.remove(this.uniqueShadingFormat);\n }\n this.uniqueShadingFormat = undefined;\n };\n WShading.prototype.cloneFormat = function () {\n var shading = new WShading(undefined);\n shading.backgroundColor = this.backgroundColor;\n shading.foregroundColor = this.foregroundColor;\n shading.textureStyle = this.textureStyle;\n return shading;\n };\n WShading.prototype.copyFormat = function (shading) {\n if (!isNullOrUndefined(shading) && !isNullOrUndefined(shading.uniqueShadingFormat)) {\n this.backgroundColor = shading.backgroundColor;\n this.foregroundColor = shading.foregroundColor;\n this.textureStyle = shading.textureStyle;\n }\n };\n WShading.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueShadingFormat)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueShadingFormat.uniqueFormatType, property);\n return this.uniqueShadingFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WShading.clear = function () {\n this.uniqueShadingFormats.clear();\n };\n WShading.uniqueShadingFormats = new WUniqueFormats();\n WShading.uniqueFormatType = 5;\n return WShading;\n}());\nexport { WShading };\n","import { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { WBorders } from './borders';\nimport { WShading } from './shading';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WTableFormat = /** @class */ (function () {\n function WTableFormat(owner) {\n this.uniqueTableFormat = undefined;\n this.borders = new WBorders(this);\n this.shading = new WShading(this);\n this.ownerBase = undefined;\n this.ownerBase = owner;\n this.assignTableMarginValue(5.4, 0, 5.4, 0);\n }\n Object.defineProperty(WTableFormat.prototype, \"cellSpacing\", {\n get: function () {\n return this.getPropertyValue('cellSpacing');\n },\n set: function (value) {\n if (value < 0 || value > 264.6) {\n throw new RangeError('The measurement must be between 0 px and 264.6 px.');\n }\n this.setPropertyValue('cellSpacing', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"leftMargin\", {\n get: function () {\n return this.getPropertyValue('leftMargin');\n },\n set: function (value) {\n this.setPropertyValue('leftMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"topMargin\", {\n get: function () {\n return this.getPropertyValue('topMargin');\n },\n set: function (value) {\n this.setPropertyValue('topMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"rightMargin\", {\n get: function () {\n return this.getPropertyValue('rightMargin');\n },\n set: function (value) {\n this.setPropertyValue('rightMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"bottomMargin\", {\n get: function () {\n return this.getPropertyValue('bottomMargin');\n },\n set: function (value) {\n this.setPropertyValue('bottomMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"leftIndent\", {\n get: function () {\n return this.getPropertyValue('leftIndent');\n },\n set: function (value) {\n if (value < -1440 || value > 1440) {\n throw new RangeError('The measurement must be between -1440 px and 1440 px.');\n }\n this.setPropertyValue('leftIndent', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"tableAlignment\", {\n get: function () {\n return this.getPropertyValue('tableAlignment');\n },\n set: function (value) {\n this.setPropertyValue('tableAlignment', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"preferredWidth\", {\n get: function () {\n return this.getPropertyValue('preferredWidth');\n },\n set: function (value) {\n this.setPropertyValue('preferredWidth', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WTableFormat.prototype, \"preferredWidthType\", {\n get: function () {\n return this.getPropertyValue('preferredWidthType');\n },\n set: function (value) {\n this.setPropertyValue('preferredWidthType', value);\n },\n enumerable: true,\n configurable: true\n });\n WTableFormat.prototype.getPropertyValue = function (property) {\n var hasValue = this.hasValue(property);\n if (hasValue) {\n var propertyType = WUniqueFormat.getPropertyType(WTableFormat.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueTableFormat) && this.uniqueTableFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueTableFormat.propertiesHash.get(propertyType);\n }\n }\n return WTableFormat.getPropertyDefaultValue(property);\n };\n WTableFormat.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WTableFormat.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueTableFormat)) {\n this.initializeUniqueTableFormat(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueTableFormat.uniqueFormatType, property);\n if (this.uniqueTableFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueTableFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n this.uniqueTableFormat = WTableFormat.uniqueTableFormats.updateUniqueFormat(this.uniqueTableFormat, property, value);\n }\n };\n WTableFormat.prototype.initializeUniqueTableFormat = function (property, propValue) {\n var uniqueTableFormatTemp = new Dictionary();\n this.addUniqueTableFormat('cellSpacing', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('leftMargin', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('topMargin', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('bottomMargin', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('rightMargin', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('leftIndent', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('tableAlignment', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('preferredWidth', property, propValue, uniqueTableFormatTemp);\n this.addUniqueTableFormat('preferredWidthType', property, propValue, uniqueTableFormatTemp);\n this.uniqueTableFormat = WTableFormat.uniqueTableFormats.addUniqueFormat(uniqueTableFormatTemp, WTableFormat.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WTableFormat.prototype.addUniqueTableFormat = function (property, modifiedProperty, propValue, uniqueTableFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WTableFormat.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueTableFormatTemp.add(propertyType, propValue);\n }\n };\n WTableFormat.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'cellSpacing':\n value = 0;\n break;\n case 'leftMargin':\n value = 5.4;\n break;\n case 'topMargin':\n value = 0;\n break;\n case 'bottomMargin':\n value = 0;\n break;\n case 'rightMargin':\n value = 5.4;\n break;\n case 'leftIndent':\n value = 0;\n break;\n case 'tableAlignment':\n value = 'Left';\n break;\n case 'preferredWidth':\n value = 0;\n break;\n case 'preferredWidthType':\n value = 'Point';\n break;\n }\n return value;\n };\n WTableFormat.prototype.assignTableMarginValue = function (left, top, right, bottom) {\n this.leftMargin = left;\n this.topMargin = top;\n this.rightMargin = right;\n this.bottomMargin = bottom;\n };\n WTableFormat.prototype.initializeTableBorders = function () {\n this.borders.left.lineStyle = 'Single';\n this.borders.left.lineWidth = 0.5;\n this.borders.right.lineStyle = 'Single';\n this.borders.right.lineWidth = 0.5;\n this.borders.top.lineStyle = 'Single';\n this.borders.top.lineWidth = 0.5;\n this.borders.bottom.lineStyle = 'Single';\n this.borders.bottom.lineWidth = 0.5;\n this.borders.horizontal.lineStyle = 'Single';\n this.borders.horizontal.lineWidth = 0.5;\n this.borders.vertical.lineStyle = 'Single';\n this.borders.vertical.lineWidth = 0.5;\n };\n WTableFormat.prototype.destroy = function () {\n if (!isNullOrUndefined(this.borders)) {\n this.borders.destroy();\n }\n if (!isNullOrUndefined(this.shading)) {\n this.shading.destroy();\n }\n if (!isNullOrUndefined(this.uniqueTableFormat)) {\n WTableFormat.uniqueTableFormats.remove(this.uniqueTableFormat);\n }\n this.uniqueTableFormat = undefined;\n this.borders = undefined;\n this.shading = undefined;\n };\n WTableFormat.prototype.cloneFormat = function () {\n var tableFormat = new WTableFormat(undefined);\n tableFormat.leftIndent = this.leftIndent;\n tableFormat.tableAlignment = this.tableAlignment;\n tableFormat.cellSpacing = this.cellSpacing;\n tableFormat.leftMargin = this.leftMargin;\n tableFormat.rightMargin = this.rightMargin;\n tableFormat.topMargin = this.topMargin;\n tableFormat.bottomMargin = this.bottomMargin;\n tableFormat.preferredWidth = this.preferredWidth;\n tableFormat.preferredWidthType = this.preferredWidthType;\n tableFormat.borders = isNullOrUndefined(this.borders) ? undefined : this.borders.cloneFormat();\n tableFormat.shading = isNullOrUndefined(this.shading) ? undefined : this.shading.cloneFormat();\n return tableFormat;\n };\n WTableFormat.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueTableFormat)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueTableFormat.uniqueFormatType, property);\n return this.uniqueTableFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WTableFormat.prototype.copyFormat = function (format) {\n if (!isNullOrUndefined(format)) {\n if (!isNullOrUndefined(format.uniqueTableFormat)) {\n this.cellSpacing = format.cellSpacing;\n this.leftMargin = format.leftMargin;\n this.topMargin = format.topMargin;\n this.rightMargin = format.rightMargin;\n this.bottomMargin = format.bottomMargin;\n this.leftIndent = format.leftIndent;\n this.tableAlignment = format.tableAlignment;\n this.preferredWidth = format.preferredWidth;\n this.preferredWidthType = format.preferredWidthType;\n }\n if (!isNullOrUndefined(format.borders)) {\n this.borders = new WBorders(this);\n this.borders.copyFormat(format.borders);\n }\n if (!isNullOrUndefined(format.shading)) {\n this.shading = new WShading(this);\n this.shading.copyFormat(format.shading);\n }\n }\n };\n WTableFormat.clear = function () {\n this.uniqueTableFormats.clear();\n };\n WTableFormat.uniqueTableFormats = new WUniqueFormats();\n WTableFormat.uniqueFormatType = 8;\n return WTableFormat;\n}());\nexport { WTableFormat };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { WBorders } from './borders';\n/**\n * @private\n */\nvar WRowFormat = /** @class */ (function () {\n function WRowFormat(node) {\n this.uniqueRowFormat = undefined;\n /**\n * @private\n */\n this.borders = new WBorders(this);\n /**\n * @private\n */\n this.ownerBase = undefined;\n /**\n * @private\n */\n this.beforeWidth = 0;\n /**\n * @private\n */\n this.afterWidth = 0;\n this.ownerBase = node;\n }\n Object.defineProperty(WRowFormat.prototype, \"gridBefore\", {\n get: function () {\n return this.getPropertyValue('gridBefore');\n },\n set: function (value) {\n this.setPropertyValue('gridBefore', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"gridBeforeWidth\", {\n get: function () {\n return this.getPropertyValue('gridBeforeWidth');\n },\n set: function (value) {\n this.setPropertyValue('gridBeforeWidth', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"gridBeforeWidthType\", {\n get: function () {\n return this.getPropertyValue('gridBeforeWidthType');\n },\n set: function (value) {\n this.setPropertyValue('gridBeforeWidthType', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"gridAfter\", {\n get: function () {\n return this.getPropertyValue('gridAfter');\n },\n set: function (value) {\n this.setPropertyValue('gridAfter', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"gridAfterWidth\", {\n get: function () {\n return this.getPropertyValue('gridAfterWidth');\n },\n set: function (value) {\n this.setPropertyValue('gridAfterWidth', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"gridAfterWidthType\", {\n get: function () {\n return this.getPropertyValue('gridAfterWidthType');\n },\n set: function (value) {\n this.setPropertyValue('gridAfterWidthType', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"allowBreakAcrossPages\", {\n get: function () {\n return this.getPropertyValue('allowBreakAcrossPages');\n },\n set: function (value) {\n this.setPropertyValue('allowBreakAcrossPages', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"isHeader\", {\n get: function () {\n return this.getPropertyValue('isHeader');\n },\n set: function (value) {\n this.setPropertyValue('isHeader', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"height\", {\n get: function () {\n return this.getPropertyValue('height');\n },\n set: function (value) {\n if (value === 0 && (this.heightType === 'AtLeast' || this.heightType === 'Exactly')) {\n value = 1;\n }\n else if (this.heightType === 'Auto') {\n value = 0;\n }\n this.setPropertyValue('height', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WRowFormat.prototype, \"heightType\", {\n get: function () {\n return this.getPropertyValue('heightType');\n },\n set: function (value) {\n if (value === 'AtLeast' || value === 'Exactly') {\n this.height = 1;\n }\n else {\n this.height = 0;\n }\n this.setPropertyValue('heightType', value);\n },\n enumerable: true,\n configurable: true\n });\n WRowFormat.prototype.getPropertyValue = function (property) {\n var hasValue = this.hasValue(property);\n if (hasValue) {\n var propertyType = WUniqueFormat.getPropertyType(WRowFormat.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueRowFormat) && this.uniqueRowFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueRowFormat.propertiesHash.get(propertyType);\n }\n }\n return WRowFormat.getPropertyDefaultValue(property);\n };\n WRowFormat.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WRowFormat.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueRowFormat)) {\n this.initializeUniqueRowFormat(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueRowFormat.uniqueFormatType, property);\n if (this.uniqueRowFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueRowFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n this.uniqueRowFormat = WRowFormat.uniqueRowFormats.updateUniqueFormat(this.uniqueRowFormat, property, value);\n }\n };\n WRowFormat.prototype.initializeUniqueRowFormat = function (property, propValue) {\n var uniqueRowFormatTemp = new Dictionary();\n this.addUniqueRowFormat('allowBreakAcrossPages', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('isHeader', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('height', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('heightType', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('gridBefore', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('gridBeforeWidth', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('gridBeforeWidthType', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('gridAfter', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('gridAfterWidth', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('gridgridAfterWidth', property, propValue, uniqueRowFormatTemp);\n this.addUniqueRowFormat('gridBeforeWidthType', property, propValue, uniqueRowFormatTemp);\n this.uniqueRowFormat = WRowFormat.uniqueRowFormats.addUniqueFormat(uniqueRowFormatTemp, WRowFormat.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WRowFormat.prototype.addUniqueRowFormat = function (property, modifiedProperty, propValue, uniqueRowFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WRowFormat.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueRowFormatTemp.add(propertyType, propValue);\n }\n };\n WRowFormat.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'allowBreakAcrossPages':\n value = true;\n break;\n case 'isHeader':\n value = false;\n break;\n case 'height':\n value = 0;\n break;\n case 'heightType':\n value = 'Auto';\n break;\n case 'gridBefore':\n value = 0;\n break;\n case 'gridBeforeWidth':\n value = 0;\n break;\n case 'gridBeforeWidthType':\n value = 'Point';\n break;\n case 'gridAfter':\n value = 0;\n break;\n case 'gridAfterWidth':\n value = 0;\n break;\n case 'gridAfterWidthType':\n value = 'Point';\n break;\n }\n return value;\n };\n WRowFormat.prototype.cloneFormat = function () {\n var format = new WRowFormat();\n format.allowBreakAcrossPages = this.allowBreakAcrossPages;\n format.heightType = this.heightType;\n format.height = this.height;\n format.isHeader = this.isHeader;\n format.gridBefore = this.gridBefore;\n format.gridBeforeWidth = this.gridBeforeWidth;\n format.gridBeforeWidthType = this.gridBeforeWidthType;\n format.gridAfter = this.gridAfter;\n format.gridAfterWidth = this.gridAfterWidth;\n format.gridAfterWidthType = this.gridAfterWidthType;\n return format;\n };\n WRowFormat.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueRowFormat)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueRowFormat.uniqueFormatType, property);\n return this.uniqueRowFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WRowFormat.prototype.copyFormat = function (format) {\n if (!isNullOrUndefined(format)) {\n if (!isNullOrUndefined(format.uniqueRowFormat)) {\n this.allowBreakAcrossPages = format.allowBreakAcrossPages;\n this.isHeader = format.isHeader;\n this.heightType = format.heightType;\n this.height = format.height;\n this.gridBefore = format.gridBefore;\n this.gridBeforeWidth = format.gridBeforeWidth;\n this.gridBeforeWidthType = format.gridBeforeWidthType;\n this.gridAfter = format.gridAfter;\n this.gridAfterWidth = format.gridAfterWidth;\n this.gridAfterWidthType = format.gridAfterWidthType;\n }\n if (!isNullOrUndefined(format.borders)) {\n this.borders = new WBorders(this);\n this.borders.ownerBase = format;\n this.borders.copyFormat(format.borders);\n }\n }\n };\n WRowFormat.prototype.destroy = function () {\n if (!isNullOrUndefined(this.borders)) {\n this.borders.destroy();\n }\n if (!isNullOrUndefined(this.uniqueRowFormat)) {\n WRowFormat.uniqueRowFormats.remove(this.uniqueRowFormat);\n }\n this.beforeWidth = undefined;\n this.afterWidth = undefined;\n this.borders = undefined;\n this.uniqueRowFormat = undefined;\n };\n WRowFormat.clear = function () {\n this.uniqueRowFormats.clear();\n };\n WRowFormat.uniqueRowFormats = new WUniqueFormats();\n WRowFormat.uniqueFormatType = 6;\n return WRowFormat;\n}());\nexport { WRowFormat };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { WBorders } from './borders';\nimport { WShading } from './shading';\n/**\n * @private\n */\nvar WCellFormat = /** @class */ (function () {\n function WCellFormat(node) {\n this.uniqueCellFormat = undefined;\n this.borders = new WBorders(this);\n this.shading = new WShading(this);\n this.ownerBase = node;\n this.borders = new WBorders(this);\n this.shading = new WShading(this);\n }\n Object.defineProperty(WCellFormat.prototype, \"leftMargin\", {\n get: function () {\n return this.getPropertyValue('leftMargin');\n },\n set: function (value) {\n this.setPropertyValue('leftMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"rightMargin\", {\n get: function () {\n return this.getPropertyValue('rightMargin');\n },\n set: function (value) {\n this.setPropertyValue('rightMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"topMargin\", {\n get: function () {\n return this.getPropertyValue('topMargin');\n },\n set: function (value) {\n this.setPropertyValue('topMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"bottomMargin\", {\n get: function () {\n return this.getPropertyValue('bottomMargin');\n },\n set: function (value) {\n this.setPropertyValue('bottomMargin', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"cellWidth\", {\n get: function () {\n return this.getPropertyValue('cellWidth');\n },\n set: function (value) {\n this.setPropertyValue('cellWidth', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"columnSpan\", {\n get: function () {\n return this.getPropertyValue('columnSpan');\n },\n set: function (value) {\n this.setPropertyValue('columnSpan', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"rowSpan\", {\n get: function () {\n return this.getPropertyValue('rowSpan');\n },\n set: function (value) {\n this.setPropertyValue('rowSpan', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"preferredWidth\", {\n get: function () {\n return this.getPropertyValue('preferredWidth');\n },\n set: function (value) {\n this.setPropertyValue('preferredWidth', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"verticalAlignment\", {\n get: function () {\n return this.getPropertyValue('verticalAlignment');\n },\n set: function (value) {\n this.setPropertyValue('verticalAlignment', value);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WCellFormat.prototype, \"preferredWidthType\", {\n get: function () {\n return this.getPropertyValue('preferredWidthType');\n },\n set: function (value) {\n this.setPropertyValue('preferredWidthType', value);\n },\n enumerable: true,\n configurable: true\n });\n WCellFormat.prototype.getPropertyValue = function (property) {\n var hasValue = this.hasValue(property);\n if (hasValue) {\n var propertyType = WUniqueFormat.getPropertyType(WCellFormat.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueCellFormat) && this.uniqueCellFormat.propertiesHash.containsKey(propertyType)) {\n return this.uniqueCellFormat.propertiesHash.get(propertyType);\n }\n }\n return WCellFormat.getPropertyDefaultValue(property);\n };\n WCellFormat.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WCellFormat.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueCellFormat)) {\n this.initializeUniqueCellFormat(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueCellFormat.uniqueFormatType, property);\n if (this.uniqueCellFormat.propertiesHash.containsKey(propertyType) &&\n this.uniqueCellFormat.propertiesHash.get(propertyType) === value) {\n //Do nothing, since no change in property value and return\n return;\n }\n this.uniqueCellFormat = WCellFormat.uniqueCellFormats.updateUniqueFormat(this.uniqueCellFormat, property, value);\n }\n };\n WCellFormat.prototype.initializeUniqueCellFormat = function (property, propValue) {\n var uniqueCellFormatTemp = new Dictionary();\n this.addUniqueCellFormat('leftMargin', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('topMargin', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('bottomMargin', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('rightMargin', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('cellWidth', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('columnSpan', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('rowSpan', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('preferredWidth', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('verticalAlignment', property, propValue, uniqueCellFormatTemp);\n this.addUniqueCellFormat('preferredWidthType', property, propValue, uniqueCellFormatTemp);\n this.uniqueCellFormat = WCellFormat.uniqueCellFormats.addUniqueFormat(uniqueCellFormatTemp, WCellFormat.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WCellFormat.prototype.addUniqueCellFormat = function (property, modifiedProperty, propValue, uniqueCellFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WCellFormat.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueCellFormatTemp.add(propertyType, propValue);\n }\n };\n WCellFormat.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'leftMargin':\n value = undefined;\n break;\n case 'topMargin':\n value = undefined;\n break;\n case 'bottomMargin':\n value = undefined;\n break;\n case 'rightMargin':\n value = undefined;\n break;\n case 'cellWidth':\n value = 0;\n break;\n case 'columnSpan':\n value = 1;\n break;\n case 'rowSpan':\n value = 1;\n break;\n case 'preferredWidth':\n value = 0;\n break;\n case 'verticalAlignment':\n value = 'Top';\n break;\n case 'preferredWidthType':\n value = 'Point';\n break;\n }\n return value;\n };\n WCellFormat.prototype.containsMargins = function () {\n return (!isNullOrUndefined(this.leftMargin)\n || !isNullOrUndefined(this.rightMargin)\n || !isNullOrUndefined(this.bottomMargin)\n || !isNullOrUndefined(this.topMargin));\n };\n WCellFormat.prototype.destroy = function () {\n if (!isNullOrUndefined(this.borders)) {\n this.borders.destroy();\n }\n if (!isNullOrUndefined(this.shading)) {\n this.shading.destroy();\n }\n if (!isNullOrUndefined(this.uniqueCellFormat)) {\n WCellFormat.uniqueCellFormats.remove(this.uniqueCellFormat);\n }\n this.uniqueCellFormat = undefined;\n this.borders = undefined;\n this.shading = undefined;\n };\n WCellFormat.prototype.cloneFormat = function () {\n var format = new WCellFormat(undefined);\n format.verticalAlignment = this.verticalAlignment;\n format.leftMargin = this.leftMargin;\n format.rightMargin = this.rightMargin;\n format.topMargin = this.topMargin;\n format.bottomMargin = this.bottomMargin;\n format.preferredWidth = this.preferredWidth;\n format.preferredWidthType = this.preferredWidthType;\n format.cellWidth = this.cellWidth;\n format.borders = isNullOrUndefined(this.borders) ? undefined : this.borders.cloneFormat();\n format.shading = isNullOrUndefined(this.shading) ? undefined : this.shading.cloneFormat();\n return format;\n };\n WCellFormat.prototype.hasValue = function (property) {\n if (!isNullOrUndefined(this.uniqueCellFormat)) {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueCellFormat.uniqueFormatType, property);\n return this.uniqueCellFormat.propertiesHash.containsKey(propertyType);\n }\n return false;\n };\n WCellFormat.prototype.copyFormat = function (format) {\n if (!isNullOrUndefined(format)) {\n if (!isNullOrUndefined(format.uniqueCellFormat)) {\n this.cellWidth = format.cellWidth;\n this.leftMargin = format.leftMargin;\n this.topMargin = format.topMargin;\n this.rightMargin = format.rightMargin;\n this.bottomMargin = format.bottomMargin;\n this.preferredWidth = format.preferredWidth;\n this.columnSpan = format.columnSpan;\n this.rowSpan = format.rowSpan;\n this.preferredWidthType = format.preferredWidthType;\n this.verticalAlignment = format.verticalAlignment;\n }\n if (!isNullOrUndefined(format.shading)) {\n this.shading = new WShading(this);\n this.shading.copyFormat(format.shading);\n }\n if (!isNullOrUndefined(format.borders)) {\n this.borders = new WBorders(this);\n this.borders.copyFormat(format.borders);\n }\n }\n };\n WCellFormat.clear = function () {\n this.uniqueCellFormats.clear();\n };\n WCellFormat.uniqueCellFormats = new WUniqueFormats();\n WCellFormat.uniqueFormatType = 4;\n return WCellFormat;\n}());\nexport { WCellFormat };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { WTableFormat, WRowFormat, WCellFormat } from '../format/index';\nimport { WParagraphFormat, WCharacterFormat, WBorder, WBorders } from '../format/index';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../base/dictionary';\nimport { HelperMethods } from '../editor/editor-helper';\n/**\n * @private\n */\nvar Rect = /** @class */ (function () {\n function Rect(x, y, width, height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n Object.defineProperty(Rect.prototype, \"right\", {\n /**\n * @private\n */\n get: function () {\n return this.x + this.width;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Rect.prototype, \"bottom\", {\n /**\n * @private\n */\n get: function () {\n return this.y + this.height;\n },\n enumerable: true,\n configurable: true\n });\n return Rect;\n}());\nexport { Rect };\n/**\n * @private\n */\nvar Margin = /** @class */ (function () {\n function Margin(leftMargin, topMargin, rightMargin, bottomMargin) {\n this.left = leftMargin;\n this.top = topMargin;\n this.right = rightMargin;\n this.bottom = bottomMargin;\n }\n /**\n * @private\n */\n Margin.prototype.clone = function () {\n return new Margin(this.left, this.top, this.right, this.bottom);\n };\n /**\n * @private\n */\n Margin.prototype.destroy = function () {\n this.left = undefined;\n this.right = undefined;\n this.top = undefined;\n this.bottom = undefined;\n };\n return Margin;\n}());\nexport { Margin };\n/**\n * @private\n */\nvar Widget = /** @class */ (function () {\n function Widget() {\n /**\n * @private\n */\n this.childWidgets = [];\n /**\n * @private\n */\n this.x = 0;\n /**\n * @private\n */\n this.y = 0;\n /**\n * @private\n */\n this.width = 0;\n /**\n * @private\n */\n this.height = 0;\n /**\n * @private\n */\n this.index = 0;\n }\n Object.defineProperty(Widget.prototype, \"indexInOwner\", {\n /**\n * @private\n */\n get: function () {\n if (this instanceof BodyWidget && this.page) {\n return this.page.bodyWidgets.indexOf(this);\n }\n else if (this.containerWidget && this.containerWidget.childWidgets) {\n return this.containerWidget.childWidgets.indexOf(this);\n }\n return -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"firstChild\", {\n /**\n * @private\n */\n get: function () {\n return this.childWidgets.length > 0 ? this.childWidgets[0] : undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"lastChild\", {\n /**\n * @private\n */\n get: function () {\n return this.childWidgets.length > 0 ?\n this.childWidgets[this.childWidgets.length - 1] : undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"previousWidget\", {\n /**\n * @private\n */\n get: function () {\n var widget = this;\n var index = this.indexInOwner;\n if (widget instanceof BodyWidget) {\n widget = index > 0 ? widget.page.bodyWidgets[index - 1] : undefined;\n }\n else {\n widget = index > 0 ? widget.containerWidget.childWidgets[index - 1] : undefined;\n }\n return widget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"nextWidget\", {\n /**\n * @private\n */\n get: function () {\n var widget = this;\n var index = this.indexInOwner;\n if (index === -1) {\n return undefined;\n }\n if (widget instanceof BodyWidget) {\n widget = index < widget.page.bodyWidgets.length - 1 ?\n widget.page.bodyWidgets[index + 1] : undefined;\n }\n else {\n widget = index < widget.containerWidget.childWidgets.length - 1 ?\n widget.containerWidget.childWidgets[index + 1] : undefined;\n }\n return widget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"previousRenderedWidget\", {\n /**\n * @private\n */\n get: function () {\n var widget = this;\n var index = this.indexInOwner;\n if (index < 0) {\n return undefined;\n }\n if (widget instanceof BodyWidget) {\n if (index > 0) {\n widget = widget.page.bodyWidgets[index - 1];\n }\n else {\n var page = widget.page.previousPage;\n widget = page && page.bodyWidgets.length > 0 ? page.bodyWidgets[page.bodyWidgets.length - 1] : undefined;\n }\n }\n else {\n if (index > 0) {\n widget = widget.containerWidget.childWidgets[index - 1];\n }\n else {\n var previousContainer = undefined;\n if (widget.containerWidget instanceof TableCellWidget) {\n previousContainer = widget.containerWidget.getPreviousSplitWidget();\n }\n else if (!(widget.containerWidget instanceof TableRowWidget\n || widget.containerWidget instanceof HeaderFooterWidget)) {\n // Since cells are lay outed left to right, we should not navigate to previous row.\n previousContainer = widget.containerWidget.previousRenderedWidget;\n }\n while (previousContainer && previousContainer.childWidgets.length === 0) {\n previousContainer = previousContainer.previousRenderedWidget;\n if (isNullOrUndefined(previousContainer)) {\n break;\n }\n }\n widget = previousContainer && previousContainer.constructor === widget.containerWidget.constructor ?\n previousContainer.lastChild : undefined;\n }\n }\n return widget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"nextRenderedWidget\", {\n /**\n * @private\n */\n get: function () {\n var widget = this;\n var index = this.indexInOwner;\n if (index < 0) {\n return undefined;\n }\n if (widget instanceof BodyWidget) {\n if (index < widget.page.bodyWidgets.length - 1) {\n widget = widget.page.bodyWidgets[index + 1];\n }\n else {\n var page = widget.page.nextPage;\n widget = page && page.bodyWidgets.length > 0 ? page.bodyWidgets[0] : undefined;\n }\n }\n else {\n if (index < widget.containerWidget.childWidgets.length - 1) {\n widget = widget.containerWidget.childWidgets[index + 1];\n }\n else {\n var nextContainer = undefined;\n if (widget.containerWidget instanceof TableCellWidget) {\n nextContainer = widget.containerWidget.getNextSplitWidget();\n }\n else if (!(widget.containerWidget instanceof TableRowWidget\n || widget.containerWidget instanceof HeaderFooterWidget)) {\n // Since cells are lay outed left to right, we should not navigate to next row.\n nextContainer = widget.containerWidget.nextRenderedWidget;\n }\n while (nextContainer && nextContainer.childWidgets.length === 0 && !(nextContainer instanceof TableCellWidget)) {\n nextContainer = nextContainer.nextRenderedWidget;\n if (isNullOrUndefined(nextContainer)) {\n break;\n }\n }\n widget = nextContainer && nextContainer.constructor === widget.containerWidget.constructor ?\n nextContainer.firstChild : undefined;\n }\n }\n return widget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"previousSplitWidget\", {\n /**\n * @private\n */\n get: function () {\n var widget = this;\n if (widget instanceof TableCellWidget) {\n return widget.getPreviousSplitWidget();\n }\n else {\n var previous = widget.previousRenderedWidget;\n if (previous instanceof BlockWidget && widget.index === previous.index && widget.equals(previous)) {\n return previous;\n }\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Widget.prototype, \"nextSplitWidget\", {\n /**\n * @private\n */\n get: function () {\n var widget = this;\n if (widget instanceof TableCellWidget) {\n return widget.getNextSplitWidget();\n }\n else {\n var next = widget.nextRenderedWidget;\n if (next instanceof BlockWidget && widget.index === next.index && widget.equals(next)) {\n return next;\n }\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n Widget.prototype.getPreviousSplitWidgets = function () {\n var widgets = [];\n var widget = this.previousSplitWidget;\n while (widget) {\n widgets.unshift(widget);\n widget = widget.previousSplitWidget;\n }\n return widgets;\n };\n /**\n * @private\n */\n Widget.prototype.getSplitWidgets = function () {\n var widgets = this.getPreviousSplitWidgets();\n var widget = this;\n while (widget) {\n widgets.push(widget);\n widget = widget.nextSplitWidget;\n }\n return widgets;\n };\n /**\n * @private\n */\n Widget.prototype.combineWidget = function (viewer) {\n var root = this;\n var widgets = this.getSplitWidgets();\n if (widgets.length > 1) {\n root = widgets.shift();\n while (widgets.length > 0) {\n var splitWidget = widgets.shift();\n root.combine(splitWidget, viewer);\n }\n }\n if (root instanceof TableWidget) {\n root.combineRows(viewer);\n }\n return root;\n };\n Widget.prototype.combine = function (widget, viewer) {\n if (widget.childWidgets.length > 0) {\n var lastChild = this.lastChild;\n if (lastChild instanceof TableWidget) {\n lastChild.combineWidget(viewer);\n }\n else {\n var firstChild = widget.firstChild;\n if (!(widget instanceof TableWidget) && lastChild instanceof Widget && firstChild instanceof Widget &&\n lastChild.index === firstChild.index) {\n lastChild.combine(widget.childWidgets.shift(), viewer);\n }\n }\n this.addWidgets(widget.childWidgets);\n widget.childWidgets = [];\n }\n widget.destroyInternal(viewer);\n };\n /**\n * @private\n */\n Widget.prototype.addWidgets = function (childWidgets) {\n while (childWidgets.length > 0) {\n var widget = childWidgets.shift();\n if (widget instanceof LineWidget && this instanceof ParagraphWidget) {\n widget.paragraph = this;\n this.height += widget.height;\n }\n else if (widget instanceof Widget) {\n var lastChild = this.lastChild;\n widget.containerWidget = this;\n widget.y = lastChild instanceof Widget ? lastChild.y + lastChild.height : this.y;\n this.height += widget.height;\n }\n this.childWidgets.push(widget);\n }\n };\n /**\n * @private\n */\n Widget.prototype.removeChild = function (index) {\n if (index > -1 && index < this.childWidgets.length) {\n this.childWidgets.splice(index, 1);\n }\n };\n /**\n * @private\n */\n Widget.prototype.destroy = function () {\n if (this.childWidgets) {\n while (this.childWidgets.length > 0) {\n var child = this.childWidgets.pop();\n if (child instanceof LineWidget || child instanceof Widget) {\n child.destroy();\n }\n }\n }\n this.childWidgets = undefined;\n if (this.containerWidget) {\n this.containerWidget.removeChild(this.indexInOwner);\n }\n this.containerWidget = undefined;\n // if (this.margin) {\n // this.margin.destroy();\n // }\n this.margin = undefined;\n this.x = undefined;\n this.y = undefined;\n this.width = undefined;\n this.height = undefined;\n this.index = undefined;\n };\n return Widget;\n}());\nexport { Widget };\n/**\n * @private\n */\nvar BlockContainer = /** @class */ (function (_super) {\n __extends(BlockContainer, _super);\n function BlockContainer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n /**\n * @private\n */\n _this.sectionFormatIn = undefined;\n return _this;\n }\n Object.defineProperty(BlockContainer.prototype, \"sectionFormat\", {\n /**\n * @private\n */\n get: function () {\n var container = this;\n if (container instanceof BodyWidget) {\n return container.sectionFormatIn;\n }\n else if (container.page) {\n return container.page.bodyWidgets[0].sectionFormat;\n }\n return undefined;\n },\n /**\n * @private\n */\n set: function (value) {\n if (this instanceof BodyWidget) {\n this.sectionFormatIn = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlockContainer.prototype, \"sectionIndex\", {\n /**\n * @private\n */\n get: function () {\n var container = this;\n var index = 0;\n if (container instanceof BodyWidget) {\n index = container.index;\n }\n else if (container.page) {\n index = container.page.bodyWidgets[0].index;\n }\n return index;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n BlockContainer.prototype.getHierarchicalIndex = function (hierarchicalIndex) {\n var viewer = undefined;\n var node = this;\n if (node instanceof BodyWidget) {\n hierarchicalIndex = node.index + ';' + hierarchicalIndex;\n }\n else {\n if (node.headerFooterType.indexOf('Header') !== -1) {\n hierarchicalIndex = 'H' + ';' + hierarchicalIndex;\n }\n else {\n hierarchicalIndex = 'F' + ';' + hierarchicalIndex;\n }\n }\n if (!isNullOrUndefined(node.page)) {\n viewer = this.page.viewer;\n var pageIndex = viewer.pages.indexOf(this.page);\n return pageIndex + ';' + hierarchicalIndex;\n }\n return hierarchicalIndex;\n };\n return BlockContainer;\n}(Widget));\nexport { BlockContainer };\n/**\n * @private\n */\nvar BodyWidget = /** @class */ (function (_super) {\n __extends(BodyWidget, _super);\n /**\n * Initialize the constructor of BodyWidget\n */\n function BodyWidget() {\n return _super.call(this) || this;\n }\n /**\n * @private\n */\n BodyWidget.prototype.equals = function (widget) {\n return widget instanceof BodyWidget && widget.sectionFormat === this.sectionFormat;\n };\n /**\n * @private\n */\n BodyWidget.prototype.getHierarchicalIndex = function (hierarchicalIndex) {\n var viewer = undefined;\n var node = this;\n hierarchicalIndex = node.index + ';' + hierarchicalIndex;\n if (!isNullOrUndefined(node.page)) {\n viewer = this.page.viewer;\n var pageIndex = viewer.pages.indexOf(this.page);\n return pageIndex + ';' + hierarchicalIndex;\n }\n return hierarchicalIndex;\n };\n /**\n * @private\n */\n BodyWidget.prototype.getTableCellWidget = function (touchPoint) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n if (this.childWidgets[i].y <= touchPoint.y\n && (this.childWidgets[i].y + this.childWidgets[i].height) >= touchPoint.y) {\n return this.childWidgets[i].getTableCellWidget(touchPoint);\n }\n }\n var tableCellWidget = undefined;\n if (this.childWidgets.length > 0) {\n if (this.childWidgets[0].y <= touchPoint.y) {\n tableCellWidget = this.childWidgets[this.childWidgets.length - 1].getTableCellWidget(touchPoint);\n }\n else {\n tableCellWidget = this.childWidgets[0].getTableCellWidget(touchPoint);\n }\n }\n return tableCellWidget;\n };\n /**\n * @private\n */\n BodyWidget.prototype.destroyInternal = function (viewer) {\n var height = this.height;\n if (!isNullOrUndefined(this.childWidgets)) {\n for (var n = 0; n < this.childWidgets.length; n++) {\n var chilgWidget = this.childWidgets[n];\n if (chilgWidget instanceof ParagraphWidget) {\n chilgWidget.destroyInternal(viewer);\n }\n else {\n chilgWidget.destroyInternal(viewer);\n }\n if (isNullOrUndefined(this.childWidgets)) {\n break;\n }\n n--;\n }\n this.childWidgets = undefined;\n }\n // if (this instanceof HeaderFooterWidget && ((this as HeaderFooterWidget).currentNode ))) {\n // if (((this as HeaderFooterWidget).currentNode as WHeaderFooter).layoutedWidgets )) {\n // let index: number = ((this as HeaderFooterWidget).currentNode as WHeaderFooter).layoutedWidgets.indexOf(this);\n // ((this as HeaderFooterWidget).currentNode as WHeaderFooter).layoutedWidgets.splice(index, 1);\n // }\n // this.currentNode = undefined;\n /* tslint:disable: one-line */\n if (!isNullOrUndefined(this.page)) {\n var index = this.indexInOwner;\n if (this.indexInOwner > -1) {\n this.page.bodyWidgets.splice(index, 1);\n if (this.page.bodyWidgets.length === 0) {\n this.page.destroy();\n // }\n }\n else if ((this instanceof HeaderFooterWidget)\n && this.page.headerWidget === this) {\n this.page.headerWidget = undefined;\n }\n else if ((this instanceof HeaderFooterWidget)\n && this.page.footerWidget === this) {\n this.page.footerWidget = undefined;\n }\n this.page = undefined;\n }\n }\n this.destroy();\n };\n /**\n * @private\n */\n BodyWidget.prototype.destroy = function () {\n // if (this.sectionFormat) {\n // this.sectionFormat.destroy();\n // }\n this.sectionFormat = undefined;\n this.page = undefined;\n _super.prototype.destroy.call(this);\n };\n return BodyWidget;\n}(BlockContainer));\nexport { BodyWidget };\n/**\n * @private\n */\nvar HeaderFooterWidget = /** @class */ (function (_super) {\n __extends(HeaderFooterWidget, _super);\n function HeaderFooterWidget(type) {\n var _this = _super.call(this) || this;\n _this.headerFooterType = type;\n return _this;\n }\n /**\n * @private\n */\n HeaderFooterWidget.prototype.getTableCellWidget = function (point) {\n return undefined;\n };\n /**\n * @private\n */\n HeaderFooterWidget.prototype.equals = function (widget) {\n // Todo: Need to work\n return widget instanceof HeaderFooterWidget\n && widget.containerWidget === this.containerWidget;\n };\n /**\n * @private\n */\n HeaderFooterWidget.prototype.clone = function () {\n var headerFooter = new HeaderFooterWidget(this.headerFooterType);\n for (var i = 0; i < this.childWidgets.length; i++) {\n var block = this.childWidgets[i].clone();\n headerFooter.childWidgets.push(block);\n block.index = i;\n block.containerWidget = headerFooter;\n }\n headerFooter.x = this.x;\n headerFooter.y = this.y;\n headerFooter.height = 0;\n headerFooter.width = 0;\n return headerFooter;\n };\n /**\n * @private\n */\n HeaderFooterWidget.prototype.destroyInternal = function (viewer) {\n this.page = undefined;\n _super.prototype.destroy.call(this);\n };\n return HeaderFooterWidget;\n}(BlockContainer));\nexport { HeaderFooterWidget };\n/**\n * @private\n */\nvar BlockWidget = /** @class */ (function (_super) {\n __extends(BlockWidget, _super);\n function BlockWidget() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(BlockWidget.prototype, \"bodyWidget\", {\n /**\n * @private\n */\n get: function () {\n var widget = this;\n while (widget.containerWidget) {\n if (widget.containerWidget instanceof BlockContainer) {\n return widget.containerWidget;\n }\n widget = widget.containerWidget;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlockWidget.prototype, \"leftIndent\", {\n /**\n * @private\n */\n get: function () {\n var blockAdv = this;\n if (blockAdv instanceof ParagraphWidget && blockAdv.paragraphFormat instanceof WParagraphFormat) {\n return blockAdv.paragraphFormat.leftIndent;\n }\n else if (blockAdv instanceof TableWidget && blockAdv.tableFormat instanceof WTableFormat) {\n return blockAdv.tableFormat.leftIndent;\n }\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlockWidget.prototype, \"rightIndent\", {\n /**\n * @private\n */\n get: function () {\n var blockAdv = this;\n if (blockAdv instanceof ParagraphWidget && blockAdv.paragraphFormat instanceof WParagraphFormat) {\n return blockAdv.paragraphFormat.rightIndent;\n }\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlockWidget.prototype, \"isInsideTable\", {\n /**\n * @private\n */\n get: function () {\n return this.containerWidget instanceof TableCellWidget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlockWidget.prototype, \"isInHeaderFooter\", {\n /**\n * @private\n */\n get: function () {\n return this.bodyWidget instanceof HeaderFooterWidget;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BlockWidget.prototype, \"associatedCell\", {\n /**\n * @private\n */\n get: function () {\n if (this.containerWidget instanceof TableCellWidget) {\n return this.containerWidget;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n BlockWidget.prototype.getHierarchicalIndex = function (hierarchicalIndex) {\n var node = this;\n hierarchicalIndex = node.containerWidget.childWidgets.indexOf(node) + ';' + hierarchicalIndex;\n if (!isNullOrUndefined(node.containerWidget)) {\n if (node.containerWidget instanceof BlockWidget) {\n return node.containerWidget.getHierarchicalIndex(hierarchicalIndex);\n }\n else if (node.containerWidget instanceof BlockContainer) {\n hierarchicalIndex = node.containerWidget.getHierarchicalIndex(hierarchicalIndex);\n }\n }\n return hierarchicalIndex;\n };\n /**\n * @private\n */\n BlockWidget.prototype.getIndex = function () {\n if (this instanceof ParagraphWidget || this instanceof TableWidget) {\n return this.containerWidget.childWidgets.indexOf(this);\n }\n else if (this instanceof TableRowWidget) {\n return this.ownerTable.childWidgets.indexOf(this);\n }\n else if (this instanceof TableCellWidget) {\n return this.ownerRow.childWidgets.indexOf(this);\n }\n return 0;\n };\n /**\n * @private\n */\n BlockWidget.prototype.getContainerWidth = function () {\n if (this.isInsideTable) {\n return this.associatedCell.cellFormat.cellWidth - (this.associatedCell.margin.left + this.associatedCell.margin.right);\n }\n else {\n var bodyWidget = this.bodyWidget;\n var sectionFormat = bodyWidget.sectionFormat;\n return sectionFormat.pageWidth - (sectionFormat.leftMargin + sectionFormat.rightMargin);\n }\n };\n return BlockWidget;\n}(Widget));\nexport { BlockWidget };\n/**\n * @private\n */\nvar ParagraphWidget = /** @class */ (function (_super) {\n __extends(ParagraphWidget, _super);\n /**\n * Initialize the constructor of ParagraphWidget\n */\n function ParagraphWidget() {\n var _this = _super.call(this) || this;\n _this.paragraphFormat = new WParagraphFormat(_this);\n _this.characterFormat = new WCharacterFormat(_this);\n return _this;\n }\n /**\n * @private\n */\n ParagraphWidget.prototype.equals = function (widget) {\n return widget instanceof ParagraphWidget && widget.paragraphFormat === this.paragraphFormat;\n };\n /**\n * @private\n */\n ParagraphWidget.prototype.isEmpty = function () {\n if (isNullOrUndefined(this.childWidgets) || this.childWidgets.length === 0) {\n return true;\n }\n for (var j = 0; j < this.childWidgets.length; j++) {\n var inlineElement = this.childWidgets[j];\n for (var i = 0; i < inlineElement.children.length; i++) {\n var inline = inlineElement.children[i];\n if (inline.length === 0) {\n continue;\n }\n if (inline instanceof TextElementBox || inline instanceof ImageElementBox || inline instanceof BookmarkElementBox\n || (inline instanceof FieldElementBox && HelperMethods.isLinkedFieldCharacter(inline))) {\n return false;\n }\n }\n }\n return true;\n };\n /**\n * @private\n */\n ParagraphWidget.prototype.getInline = function (offset, indexInInline) {\n var inline = undefined;\n var count = 0;\n var isStarted = false;\n var splittedWidget = this.getSplitWidgets();\n for (var k = 0; k < splittedWidget.length; k++) {\n var widget = splittedWidget[k];\n for (var j = 0; j < widget.childWidgets.length; j++) {\n var line = widget.childWidgets[j];\n for (var i = 0; i < line.children.length; i++) {\n inline = line.children[i];\n if (inline instanceof ListTextElementBox) {\n continue;\n }\n if (!isStarted && (inline instanceof TextElementBox || inline instanceof ImageElementBox\n || inline instanceof BookmarkElementBox || inline instanceof FieldElementBox\n && HelperMethods.isLinkedFieldCharacter(inline))) {\n isStarted = true;\n }\n if (isStarted && offset <= count + inline.length) {\n indexInInline = (offset - count);\n return { 'element': inline, 'index': indexInInline };\n }\n count += inline.length;\n }\n }\n }\n if (offset > count) {\n indexInInline = isNullOrUndefined(inline) ? offset : inline.length;\n }\n return { 'element': inline, 'index': indexInInline };\n };\n /**\n * @private\n */\n ParagraphWidget.prototype.getLength = function () {\n var length = 0;\n for (var j = 0; j < this.childWidgets.length; j++) {\n var line = this.childWidgets[j];\n for (var i = 0; i < line.children.length; i++) {\n var element = line.children[i];\n if (element instanceof ListTextElementBox) {\n continue;\n }\n length += element.length;\n }\n }\n return length;\n };\n /**\n * @private\n */\n ParagraphWidget.prototype.getTableCellWidget = function (point) {\n return undefined;\n };\n /**\n * @private\n */\n ParagraphWidget.prototype.clone = function () {\n var paragraph = new ParagraphWidget();\n paragraph.paragraphFormat.copyFormat(this.paragraphFormat);\n paragraph.characterFormat.copyFormat(this.characterFormat);\n for (var i = 0; i < this.childWidgets.length; i++) {\n var line = this.childWidgets[i];\n var cloneLine = line.clone();\n paragraph.childWidgets.push(cloneLine);\n cloneLine.paragraph = paragraph;\n }\n paragraph.x = this.x;\n paragraph.y = this.y;\n paragraph.height = this.height;\n paragraph.width = this.width;\n return paragraph;\n };\n /**\n * @private\n */\n ParagraphWidget.prototype.destroyInternal = function (viewer) {\n var height = this.height;\n if (!isNullOrUndefined(this.childWidgets)) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var widget = this.childWidgets[i];\n widget.destroy();\n if (this.childWidgets.length === 1 && isNullOrUndefined(this.childWidgets[0].children)) {\n this.childWidgets = undefined;\n }\n if (isNullOrUndefined(this.childWidgets)) {\n break;\n }\n i--;\n }\n this.childWidgets = undefined;\n }\n if (!isNullOrUndefined(this.containerWidget) && !isNullOrUndefined(this.containerWidget.childWidgets)\n && this.containerWidget.childWidgets.indexOf(this) !== -1) {\n this.containerWidget.childWidgets.splice(this.containerWidget.childWidgets.indexOf(this), 1);\n this.containerWidget.height -= height;\n // if ((isNullOrUndefined(this.containerWidget.childWidgets) || this.containerWidget.childWidgets.length === 0)\n // && this.containerWidget instanceof BodyWidget) {\n // // (this.containerWidget as BodyWidget).destroyInternal(viewer);\n // }\n this.containerWidget = undefined;\n }\n this.destroy();\n };\n /**\n * @private\n */\n ParagraphWidget.prototype.destroy = function () {\n // if (this.paragraphFormat) {\n // this.paragraphFormat.destroy();\n // }\n this.paragraphFormat = undefined;\n // if (this.characterFormat) {\n // this.characterFormat.destroy();\n // }\n this.characterFormat = undefined;\n _super.prototype.destroy.call(this);\n };\n return ParagraphWidget;\n}(BlockWidget));\nexport { ParagraphWidget };\n/**\n * @private\n */\nvar TableWidget = /** @class */ (function (_super) {\n __extends(TableWidget, _super);\n function TableWidget() {\n var _this = _super.call(this) || this;\n _this.flags = 0;\n /**\n * @private\n */\n _this.leftMargin = 0;\n /**\n * @private\n */\n _this.topMargin = 0;\n /**\n * @private\n */\n _this.rightMargin = 0;\n /**\n * @private\n */\n _this.bottomMargin = 0;\n _this.margin = new Margin(_this.leftMargin, _this.topMargin, _this.rightMargin, _this.bottomMargin);\n _this.leftBorderWidth = 0;\n _this.rightBorderWidth = 0;\n _this.topBorderWidth = 0;\n _this.bottomBorderWidth = 0;\n _this.tableFormat = new WTableFormat(_this);\n _this.tableHolder = new WTableHolder();\n _this.spannedRowCollection = new Dictionary();\n return _this;\n }\n Object.defineProperty(TableWidget.prototype, \"isGridUpdated\", {\n /**\n * @private\n */\n get: function () {\n return ((this.flags & 0x4) >> 2) !== 0;\n },\n /**\n * @private\n */\n set: function (value) {\n this.flags = ((this.flags & 0xFB) | ((value ? 1 : 0) << 2));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableWidget.prototype, \"continueHeader\", {\n /**\n * @private\n */\n get: function () {\n return ((this.flags & 0x2) >> 1) !== 0;\n },\n /**\n * @private\n */\n set: function (value) {\n this.flags = ((this.flags & 0xFD) | ((value ? 1 : 0) << 1));\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableWidget.prototype, \"header\", {\n /**\n * @private\n */\n get: function () {\n return (this.flags & 0x1) !== 0;\n },\n /**\n * @private\n */\n set: function (value) {\n this.flags = ((this.flags & 0xFE) | (value ? 1 : 0));\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n TableWidget.prototype.equals = function (widget) {\n return widget instanceof TableWidget && widget.tableFormat === this.tableFormat;\n };\n /**\n * @private\n */\n TableWidget.prototype.combineRows = function (viewer) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n if (row.childWidgets.length === 0) {\n row.destroy();\n i--;\n }\n else {\n row.combineCells(viewer);\n }\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.contains = function (tableCell) {\n if (this.equals(tableCell.ownerTable)) {\n return true;\n }\n while (tableCell.ownerTable.isInsideTable) {\n if (this.equals(tableCell.ownerTable)) {\n return true;\n }\n tableCell = tableCell.ownerTable.associatedCell;\n }\n return this.equals(tableCell.ownerTable);\n };\n /**\n * @private\n */\n TableWidget.prototype.getOwnerWidth = function (isBasedOnViewer) {\n var width = this.getContainerWidth();\n // Left and right indents should be neglected.\n width = width - this.leftIndent - this.rightIndent;\n return width >= 0 ? width : 0;\n };\n TableWidget.prototype.getTableWidth = function () {\n var width = 0;\n for (var i = 0; i < this.childWidgets.length; i++) {\n var rowWidth = 0;\n var row = this.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n rowWidth += row.childWidgets[j].cellFormat.cellWidth;\n }\n if (width < rowWidth) {\n width = rowWidth;\n }\n }\n return width;\n };\n /**\n * @private\n */\n TableWidget.prototype.getTableClientWidth = function (clientWidth) {\n var tableWidth = clientWidth;\n if (this.tableFormat.preferredWidthType === 'Point'\n && this.tableFormat.preferredWidth > 0) {\n tableWidth = this.tableFormat.preferredWidth;\n }\n else {\n if (this.tableFormat.preferredWidthType === 'Percent'\n && this.tableFormat.preferredWidth > 0) {\n tableWidth = tableWidth * this.tableFormat.preferredWidth / 100;\n }\n else {\n //By default, if Table preferred widthType is auto , width is set based on ClientWidth and type is set as 'Point'\n this.tableFormat.preferredWidthType = 'Point';\n this.tableFormat.preferredWidth = tableWidth;\n }\n }\n return tableWidth;\n };\n /**\n * @private\n */\n TableWidget.prototype.getCellWidth = function (preferredWidth, preferredWidthType, containerWidth, cell) {\n var cellWidth = preferredWidth;\n if (preferredWidthType === 'Percent') {\n cellWidth = (preferredWidth * containerWidth) / 100;\n }\n else if (preferredWidthType === 'Point') {\n cellWidth = preferredWidth;\n }\n else if (!isNullOrUndefined(cell)) {\n cellWidth = cell.getMinimumPreferredWidth();\n }\n return cellWidth;\n };\n /**\n * @private\n */\n TableWidget.prototype.fitCellsToClientArea = function (clientWidth) {\n var tableWidth = this.getTableWidth();\n var factor = clientWidth / tableWidth;\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n row.rowFormat.gridAfterWidth *= factor;\n row.rowFormat.gridBeforeWidth *= factor;\n for (var j = 0; j < row.childWidgets.length; j++) {\n row.childWidgets[j].cellFormat.cellWidth *= factor;\n }\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.getTableCellWidget = function (point) {\n var tableCellWidget = undefined;\n for (var i = 0; i < this.childWidgets.length; i++) {\n if (this.childWidgets[i].y <= point.y\n && (this.childWidgets[i].y + this.childWidgets[i].height) >= point.y) {\n tableCellWidget = this.childWidgets[i].getTableCellWidget(point);\n break;\n }\n }\n return tableCellWidget;\n };\n /**\n * @private\n */\n TableWidget.prototype.calculateGrid = function () {\n var tempGrid = [];\n var spannedCells = [];\n var containerWidth = this.getOwnerWidth(true);\n var tableWidth = this.getTableClientWidth(containerWidth);\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n var rowFormat = row.rowFormat;\n var cellWidth = 0;\n var columnSpan = row.rowFormat.gridBefore;\n var currOffset = 0;\n if (tempGrid.indexOf(currOffset) < 0) {\n tempGrid.push(currOffset);\n }\n //Converts the row grid before width from point to twips point by 15 factor.\n cellWidth = this.getCellWidth(rowFormat.gridBeforeWidth, rowFormat.gridBeforeWidthType, tableWidth, null);\n currOffset += cellWidth;\n var startOffset = Math.round(currOffset);\n if (tempGrid.indexOf(startOffset) < 0) {\n tempGrid.push(startOffset);\n }\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n for (var k = 0; k < spannedCells.length; k++) {\n if (spannedCells[k].columnIndex < columnSpan) {\n continue;\n }\n var rowSpan = spannedCells[k].cellFormat.rowSpan;\n var removeSpannedCell = true;\n if (spannedCells[k].columnIndex > columnSpan) {\n {\n removeSpannedCell = false;\n // If the cell is the last cell in the row and the row has grid after value..\n if (j === row.childWidgets.length - 1 && row.rowFormat.gridAfter > 0) {\n // tslint:disable-next-line:max-line-length\n cellWidth = this.getCellWidth(spannedCells[k].cellFormat.preferredWidth, spannedCells[k].cellFormat.preferredWidthType, tableWidth, null);\n currOffset += cellWidth;\n }\n }\n }\n else {\n // If the table gird alone calculted then column index of the rowspanned cell will be directly taken. \n // If the gird calculation is done from the UI level opearations such as resizing then table holder \n // will have the columns at that time we can get the column index from the table holder.\n //Converts the cell width from point to twips point by 15 factor.\n // tslint:disable-next-line:max-line-length\n cellWidth = this.getCellWidth(spannedCells[k].cellFormat.preferredWidth, spannedCells[k].cellFormat.preferredWidthType, tableWidth, null);\n currOffset += cellWidth;\n }\n if (!removeSpannedCell && j === row.childWidgets.length - 1) {\n removeSpannedCell = true;\n }\n if (removeSpannedCell && i - spannedCells[k].ownerRow.rowIndex === rowSpan - 1) {\n spannedCells.splice(k, 1);\n k--;\n }\n }\n // At the start of each row, we will process the row spanned cells to get the start column index.\n // To calculate grid properly, we need the items in the spanned cells collection in the order of their column index\n if (cell.cellFormat.rowSpan > 1) {\n if (spannedCells.length === 0 || spannedCells[spannedCells.length - 1].columnIndex <= columnSpan) {\n spannedCells.push(cell);\n }\n else {\n for (var m = spannedCells.length; m > 0; m--) {\n if (spannedCells[m - 1].columnIndex > columnSpan) {\n spannedCells.splice(m - 1, 0, cell);\n }\n }\n }\n }\n columnSpan += cell.cellFormat.columnSpan;\n //Converts the cell width from pixel to twips point by 15 factor.\n cellWidth = this.getCellWidth(cell.cellFormat.preferredWidth, cell.cellFormat.preferredWidthType, tableWidth, null);\n currOffset += cellWidth;\n var offset = Math.round(currOffset);\n if (tempGrid.indexOf(offset) < 0) {\n tempGrid.push(offset);\n }\n if (j === row.childWidgets.length - 1 && rowFormat.gridAfter > 0) {\n cellWidth = this.getCellWidth(rowFormat.gridAfterWidth, 'Point', tableWidth, null);\n currOffset += cellWidth;\n if (tempGrid.indexOf(Math.round(currOffset)) < 0) {\n tempGrid.push(Math.round(currOffset));\n }\n columnSpan += rowFormat.gridAfter;\n }\n }\n }\n tempGrid.sort(function (a, b) { return a - b; });\n if (tempGrid.length - 1 !== this.tableHolder.columns.length) {\n this.updateColumnSpans(tempGrid, tableWidth);\n }\n };\n TableWidget.prototype.updateColumnSpans = function (tempGrid, containerWidth) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n if (row.rowFormat.gridBeforeWidth >= 0) {\n row.rowFormat.gridBefore = row.getGridCount(tempGrid, -1, containerWidth);\n }\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n var columnSpan = row.getGridCount(tempGrid, cell.getIndex(), containerWidth);\n if (columnSpan > 0 && cell.cellFormat.columnSpan !== columnSpan) {\n cell.cellFormat.columnSpan = columnSpan;\n }\n }\n if (row.rowFormat.gridAfterWidth >= 0) {\n row.rowFormat.gridAfter = row.getGridCount(tempGrid, row.childWidgets.length, containerWidth);\n }\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.buildTableColumns = function () {\n if (this.isGridUpdated) {\n return;\n }\n // Clear existing columns in order to start creating columns freshly.\n this.tableHolder.resetColumns();\n var containerWidth = 0;\n var tableWidth = 0;\n var rowSpannedCells = [];\n var isAutoWidth = this.tableFormat.preferredWidthType === 'Auto';\n // For continuous layout, window width should be considered. \n // If preferred width exceeds this limit, it can take upto maximum of 2112 pixels (1584 points will be assigned by Microsoft Word).\n containerWidth = this.getOwnerWidth(true);\n tableWidth = this.getTableClientWidth(containerWidth);\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n var rowFormat = row.rowFormat;\n var columnSpan = 0;\n var cellWidth = 0;\n var offset = 0;\n if (rowFormat.gridBefore > 0) {\n cellWidth = this.getCellWidth(rowFormat.gridBeforeWidth, row.rowFormat.gridAfterWidthType, tableWidth, null);\n this.tableHolder.addColumns(columnSpan, columnSpan = rowFormat.gridBefore, cellWidth, cellWidth, offset = cellWidth);\n }\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n if (rowSpannedCells.length === 0) {\n cell.columnIndex = columnSpan;\n }\n for (var k = 0; k < rowSpannedCells.length; k++) {\n var rowSpannedCell = rowSpannedCells[k];\n if (rowSpannedCell.columnIndex < columnSpan) {\n cell.columnIndex = columnSpan;\n continue;\n }\n var rowSpan = 1;\n var removeSpannedCell = true;\n rowSpan = rowSpannedCell.cellFormat.rowSpan;\n if (rowSpannedCell.columnIndex > columnSpan) {\n cell.columnIndex = columnSpan;\n removeSpannedCell = false;\n }\n else {\n // tslint:disable-next-line:max-line-length\n cellWidth = this.getCellWidth(rowSpannedCell.cellFormat.preferredWidth, rowSpannedCell.cellFormat.preferredWidthType, tableWidth, rowSpannedCell);\n var minWidth_1 = rowSpannedCell.getMinimumPreferredWidth();\n // If the table gird alone calculted then column index of the rowspanned cell will be directly taken. \n // tslint:disable-next-line:max-line-length\n // If the gird calculation is done from the UI level opearations such as resizing then table holder will have the columns at that time we can get the column index from the table holder.\n // tslint:disable-next-line:max-line-length\n if (this.tableHolder.columns.length > 0) {\n this.tableHolder.addColumns(columnSpan, columnSpan = this.tableHolder.columns.indexOf(rowSpannedCell.ownerColumn) + rowSpannedCell.cellFormat.columnSpan, cellWidth, minWidth_1, offset += cellWidth);\n cell.columnIndex = columnSpan;\n }\n else {\n // tslint:disable-next-line:max-line-length\n this.tableHolder.addColumns(columnSpan, columnSpan = rowSpannedCell.columnIndex + rowSpannedCell.cellFormat.columnSpan, cellWidth, minWidth_1, offset += cellWidth);\n cell.columnIndex = columnSpan;\n }\n }\n if (!removeSpannedCell && j === row.childWidgets.length - 1) {\n removeSpannedCell = true;\n }\n if (removeSpannedCell && i - rowSpannedCell.ownerRow.rowIndex === rowSpan - 1) {\n rowSpannedCells.splice(k, 1);\n k--;\n }\n }\n // At the start of each row, we will process the row spanned cells to get the start column index.\n // To calculate grid properly, we need the items in the spanned cells collection in the order of their column index\n if (cell.cellFormat.rowSpan > 1) {\n if (rowSpannedCells.length === 0 || rowSpannedCells[rowSpannedCells.length - 1].columnIndex <= columnSpan) {\n rowSpannedCells.push(cell);\n }\n else {\n for (var m = rowSpannedCells.length; m > 0; m--) {\n if (rowSpannedCells[m - 1].columnIndex > columnSpan) {\n rowSpannedCells.splice(m - 1, 0, cell);\n }\n }\n }\n }\n cellWidth = this.getCellWidth(cell.cellFormat.preferredWidth, cell.cellFormat.preferredWidthType, tableWidth, cell);\n var minWidth = cell.getMinimumPreferredWidth();\n this.tableHolder.addColumns(columnSpan, columnSpan += cell.cellFormat.columnSpan, cellWidth, minWidth, offset += cellWidth);\n if (j === row.childWidgets.length - 1 && rowFormat.gridAfterWidth > 0) {\n cellWidth = this.getCellWidth(rowFormat.gridAfterWidth, 'Point', tableWidth, null);\n this.tableHolder.addColumns(columnSpan, columnSpan += rowFormat.gridAfter, cellWidth, cellWidth, offset += cellWidth);\n }\n }\n }\n this.tableHolder.validateColumnWidths();\n // Fits the column width based on preferred width. i.e. Fixed layout.\n this.tableHolder.fitColumns(containerWidth, tableWidth, isAutoWidth);\n //Sets the width to cells\n this.setWidthToCells(tableWidth, isAutoWidth);\n };\n /**\n * @private\n */\n TableWidget.prototype.setWidthToCells = function (tableWidth, isAutoWidth) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var rw = this.childWidgets[i];\n var rowFormat = rw.rowFormat;\n if (rowFormat.gridBefore > 0) {\n rowFormat.beforeWidth = this.tableHolder.getCellWidth(0, rowFormat.gridBefore, tableWidth, isAutoWidth);\n }\n for (var j = 0; j < rw.childWidgets.length; j++) {\n var cell = rw.childWidgets[j];\n // tslint:disable-next-line:max-line-length\n cell.cellFormat.cellWidth = this.tableHolder.getCellWidth(cell.columnIndex, cell.cellFormat.columnSpan, tableWidth, isAutoWidth);\n //By default, if cell preferred widthType is auto , width set based on table width and type is changed to 'Point'\n if (cell.cellFormat.preferredWidthType !== 'Percent') {\n cell.cellFormat.preferredWidth = cell.cellFormat.cellWidth;\n cell.cellFormat.preferredWidthType = 'Point';\n }\n }\n if (rowFormat.gridAfter > 0) {\n rowFormat.afterWidth = this.tableHolder.getCellWidth(0, rowFormat.gridAfter, tableWidth, isAutoWidth);\n }\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.getMaxRowWidth = function (clientWidth) {\n var width = 0;\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n var rowWidth = 0;\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n rowWidth += this.getCellWidth(cell.cellFormat.preferredWidth, cell.cellFormat.preferredWidthType, clientWidth, cell);\n }\n if (width < rowWidth) {\n width = rowWidth;\n }\n }\n return width;\n };\n /**\n * @private\n */\n TableWidget.prototype.updateWidth = function (dragValue) {\n var totalPreferredWidth = this.tableHolder.getTotalWidth();\n var containerWidth = this.getTableClientWidth(this.getOwnerWidth(true));\n if (containerWidth <= totalPreferredWidth) {\n if (this.tableFormat.preferredWidthType === 'Auto') {\n this.tableFormat.preferredWidthType = 'Point';\n }\n }\n if (this.tableFormat.preferredWidthType !== 'Auto') {\n if (this.tableFormat.preferredWidthType === 'Point') {\n this.tableFormat.preferredWidth = this.getMaxRowWidth(containerWidth);\n }\n // else\n // { //ToDo:Need to anzlyze more the Percentage calculation for table width.\n // let value:number = ConvertPixelToPercent(GetMaxRowWidth(containerWidth));\n // this.tableFormat.preferredWidth = value;\n // }\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.convertPointToPercent = function (tablePreferredWidth, ownerWidth) {\n var value = 0;\n value = (tablePreferredWidth / ownerWidth) * 100;\n value = Math.round(value);\n return value < 100 ? value : 100; // The value should be lesser than or equal to 100%;\n };\n /**\n * @private\n */\n TableWidget.prototype.clone = function () {\n var table = new TableWidget();\n table.tableHolder = this.tableHolder.clone();\n table.tableFormat.copyFormat(this.tableFormat);\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i].clone();\n table.childWidgets.push(row);\n row.containerWidget = table;\n row.index = i;\n }\n table.x = this.x;\n table.y = this.y;\n table.height = this.height;\n table.width = this.width;\n table.containerWidget = this.containerWidget;\n return table;\n };\n /**\n * @private\n */\n TableWidget.getTableOf = function (node) {\n if (node instanceof WBorders) {\n var row = TableRowWidget.getRowOf(node);\n if (!isNullOrUndefined(row)) {\n return row.ownerTable;\n }\n else if (node.ownerBase instanceof WTableFormat && node.ownerBase.ownerBase instanceof TableWidget) {\n return node.ownerBase.ownerBase;\n }\n else {\n return undefined;\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n TableWidget.prototype.fitChildToClientArea = function () {\n var clientWidth = this.getContainerWidth();\n if (Math.round(clientWidth) < Math.round(this.getTableWidth())) {\n this.fitCellsToClientArea(clientWidth);\n }\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n for (var k = 0; k < cell.childWidgets.length; k++) {\n if (cell.childWidgets[k] instanceof TableWidget) {\n cell.childWidgets[k].fitChildToClientArea();\n }\n }\n }\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.getColumnCellsForSelection = function (startCell, endCell) {\n var cells = [];\n var start = startCell.columnIndex;\n var end = endCell.columnIndex + endCell.cellFormat.columnSpan;\n for (var i = 0; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n var columnIndex = cell.columnIndex;\n var columnSpan = cell.cellFormat.columnSpan;\n if ((columnIndex + columnSpan > start && columnIndex + columnSpan < end) || (columnIndex > start && columnIndex < end)) {\n if (cells.indexOf(cell) < 0) {\n cells.push(cell);\n }\n }\n else if ((columnIndex > start && columnIndex < end && columnIndex + columnSpan < end)\n || (columnIndex < start && columnIndex + columnSpan > end)) {\n if (cells.indexOf(cell) < 0) {\n cells.push(cell);\n }\n }\n else if (columnIndex === start || columnIndex + columnSpan === end) {\n if (cells.indexOf(cell) < 0) {\n cells.push(cell);\n }\n }\n }\n }\n return cells;\n };\n /**\n * Splits width equally for all the cells.\n * @param tableClientWidth\n * @private\n */\n TableWidget.prototype.splitWidthToTableCells = function (tableClientWidth) {\n for (var row = 0; row < this.childWidgets.length; row++) {\n this.childWidgets[row].splitWidthToRowCells(tableClientWidth);\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.insertTableRowsInternal = function (tableRows, startIndex) {\n for (var i = 0; i < tableRows.length; i++) {\n var row = tableRows.splice(i, 1)[0];\n row.containerWidget = this;\n this.childWidgets.splice(startIndex, 0, row);\n i--;\n }\n this.updateRowIndex(startIndex);\n this.isGridUpdated = false;\n this.buildTableColumns();\n this.isGridUpdated = true;\n };\n /**\n * @private\n */\n TableWidget.prototype.updateRowIndex = function (startIndex) {\n for (var i = startIndex; i < this.childWidgets.length; i++) {\n var row = this.childWidgets[i];\n row.index = i;\n for (var j = 0; j < row.childWidgets.length; j++) {\n row.childWidgets[j].index = j;\n row.childWidgets[j].rowIndex = row.rowIndex;\n }\n startIndex++;\n }\n };\n /**\n * @private\n */\n TableWidget.prototype.destroyInternal = function (viewer) {\n var height = this.height;\n if (!isNullOrUndefined(this.childWidgets)) {\n for (var j = 0; j < this.childWidgets.length; j++) {\n var widget = undefined;\n var childWidget = this.childWidgets[j];\n widget = childWidget;\n if (!isNullOrUndefined(widget)) {\n widget.destroyInternal(viewer);\n }\n if (isNullOrUndefined(this.childWidgets)) {\n break;\n }\n j--;\n }\n this.childWidgets = undefined;\n }\n if (!isNullOrUndefined(this.containerWidget)) {\n if (!isNullOrUndefined(this.containerWidget.childWidgets)) {\n if (this.containerWidget.childWidgets.indexOf(this) !== -1) {\n this.containerWidget.childWidgets.splice(this.containerWidget.childWidgets.indexOf(this), 1);\n }\n this.containerWidget.height -= height;\n // if ((isNullOrUndefined(this.containerWidget.childWidgets) || this.containerWidget.childWidgets.length === 0)\n // && this.containerWidget instanceof BodyWidget) {\n // // (this.containerWidget as BodyWidget).destroyInternal(viewer);\n // }\n }\n this.containerWidget = undefined;\n }\n this.destroy();\n };\n /**\n * @private\n */\n TableWidget.prototype.destroy = function () {\n // if (this.tableFormat) {\n // this.tableFormat.destroy();\n // }\n this.tableFormat = undefined;\n // if (this.spannedRowCollection) {\n // this.spannedRowCollection.destroy();\n // }\n this.spannedRowCollection = undefined;\n this.tableGrids = [];\n this.tableGrids = undefined;\n // if (this.tableHolder) {\n // this.tableHolder.destroy();\n // }\n this.tableHolder = undefined;\n this.flags = undefined;\n this.leftMargin = undefined;\n this.topMargin = undefined;\n this.rightMargin = undefined;\n this.bottomMargin = undefined;\n this.headerHeight = undefined;\n this.description = undefined;\n this.title = undefined;\n _super.prototype.destroy.call(this);\n };\n return TableWidget;\n}(BlockWidget));\nexport { TableWidget };\n/**\n * @private\n */\nvar TableRowWidget = /** @class */ (function (_super) {\n __extends(TableRowWidget, _super);\n function TableRowWidget() {\n var _this = _super.call(this) || this;\n /**\n * @private\n */\n _this.spannedRowCollection = [];\n _this.topBorderWidth = 0;\n _this.bottomBorderWidth = 0;\n _this.rowFormat = new WRowFormat(_this);\n return _this;\n }\n Object.defineProperty(TableRowWidget.prototype, \"rowIndex\", {\n /**\n * @private\n */\n get: function () {\n if (this.containerWidget) {\n return this.containerWidget.childWidgets.indexOf(this);\n }\n return -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableRowWidget.prototype, \"ownerTable\", {\n /**\n * @private\n */\n get: function () {\n if (this.containerWidget instanceof TableWidget) {\n return this.containerWidget;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableRowWidget.prototype, \"nextRow\", {\n /**\n * @private\n */\n get: function () {\n var index = this.indexInOwner;\n if (index > -1 && index < this.ownerTable.childWidgets.length - 1) {\n return this.ownerTable.childWidgets[index + 1];\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n TableRowWidget.prototype.equals = function (widget) {\n return widget instanceof TableRowWidget && widget.rowFormat === this.rowFormat;\n };\n /**\n * @private\n */\n TableRowWidget.prototype.combineCells = function (viewer) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var cell = this.childWidgets[i];\n cell.combineWidget(viewer);\n if (cell.cellFormat.rowSpan === 1) {\n var cellHeight = cell.height + cell.margin.top + cell.margin.bottom;\n if ((this.height - this.ownerTable.tableFormat.cellSpacing) < cell.height) {\n this.height = this.ownerTable.tableFormat.cellSpacing + cell.height;\n }\n }\n }\n };\n /**\n * @private\n */\n TableRowWidget.getRowOf = function (node) {\n if (node instanceof WBorders) {\n var cell = TableCellWidget.getCellOf(node);\n if (!isNullOrUndefined(cell)) {\n return cell.ownerRow;\n }\n else if (node.ownerBase instanceof WRowFormat && node.ownerBase.ownerBase instanceof TableRowWidget) {\n return node.ownerBase.ownerBase;\n }\n else {\n return undefined;\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n TableRowWidget.prototype.getCell = function (rowIndex, cellIndex) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var cell = this.childWidgets[i];\n if (cell.rowIndex === rowIndex && cell.index === cellIndex) {\n return cell;\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n TableRowWidget.prototype.splitWidthToRowCells = function (tableClientWidth) {\n var cells = this.childWidgets;\n var cellWidth = tableClientWidth / cells.length;\n for (var cell = 0; cell < cells.length; cell++) {\n cells[cell].cellFormat.preferredWidth = cellWidth;\n }\n };\n /**\n * @private\n */\n TableRowWidget.prototype.getGridCount = function (tableGrid, index, containerWidth) {\n var prevOffset = 0;\n var width = 0;\n var ownerTable = this.ownerTable;\n var rowFormat = this.rowFormat;\n if (index === -1) {\n width = ownerTable.getCellWidth(rowFormat.gridBeforeWidth, rowFormat.gridBeforeWidthType, containerWidth, null);\n }\n else {\n prevOffset += ownerTable.getCellWidth(rowFormat.gridBeforeWidth, rowFormat.gridBeforeWidthType, containerWidth, null);\n if (index > 0) {\n prevOffset += this.getCellOffset(index, containerWidth);\n }\n if (index < this.childWidgets.length) {\n var cell = this.childWidgets[index];\n width = ownerTable.getCellWidth(cell.cellFormat.preferredWidth, cell.cellFormat.preferredWidthType, containerWidth, null);\n }\n else {\n width = ownerTable.getCellWidth(rowFormat.gridAfterWidth, rowFormat.gridAfterWidthType, containerWidth, null);\n }\n }\n var gridStartIndex = this.getOffsetIndex(tableGrid, prevOffset);\n var gridEndIndex = this.getOffsetIndex(tableGrid, prevOffset + width);\n return gridEndIndex - gridStartIndex;\n };\n TableRowWidget.prototype.getOffsetIndex = function (tableGrid, offset) {\n offset = Math.round(offset);\n var index = 0;\n if (tableGrid.indexOf(offset) >= 0) {\n index = tableGrid.indexOf(offset);\n }\n else {\n for (var i = 0; i < tableGrid.length; i++) {\n if (tableGrid[i] > offset) {\n return i;\n }\n }\n index = tableGrid.length - 1;\n }\n return index;\n };\n TableRowWidget.prototype.getCellOffset = function (index, containerWidth) {\n var prevOffset = 0;\n var ownerTable = this.ownerTable;\n for (var i = 0; i < this.childWidgets.length; i++) {\n var cellFormat = this.childWidgets[i].cellFormat;\n if (i === index) {\n break;\n }\n prevOffset += ownerTable.getCellWidth(cellFormat.preferredWidth, cellFormat.preferredWidthType, containerWidth, null);\n }\n return prevOffset;\n };\n /**\n * @private\n */\n TableRowWidget.prototype.updateRowBySpannedCells = function () {\n var rowSpannedCells = this.getPreviousRowSpannedCells();\n var currentRowIndex = this.rowIndex;\n for (var i = 0; i < rowSpannedCells.length; i++) {\n var spannedCell = rowSpannedCells[i];\n var rowSpanEnd = spannedCell.ownerRow.rowIndex + spannedCell.cellFormat.rowSpan - 1;\n // If current row is row span end or includes spanned cells. then, decrease the rowspan\n if (rowSpanEnd >= currentRowIndex) {\n spannedCell.cellFormat.rowSpan -= 1;\n }\n }\n };\n /**\n * @private\n */\n TableRowWidget.prototype.getPreviousRowSpannedCells = function (include) {\n var rowSpannedCells = [];\n var row = include ? this : this.previousWidget;\n while (!isNullOrUndefined(row)) {\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n if (cell.cellFormat.rowSpan > 1) {\n rowSpannedCells.splice(0, 0, cell);\n }\n }\n row = row.previousWidget;\n }\n return rowSpannedCells;\n };\n /**\n * @private\n */\n TableRowWidget.prototype.getTableCellWidget = function (point) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var x = Math.round(this.childWidgets[i].x);\n if (x - this.childWidgets[i].margin.left - 1 <= point.x\n && (x + this.childWidgets[i].width) >= point.x) {\n return this.childWidgets[i];\n }\n else if (i === this.childWidgets.length - 1\n && (this.childWidgets[i].x + this.childWidgets[i].width) + 1 <= point.x) {\n return this.childWidgets[i];\n }\n }\n var cellWidget = undefined;\n if (this.childWidgets.length > 0) {\n if (this.childWidgets[0].x <= point.x) {\n cellWidget = this.childWidgets[this.childWidgets.length - 1].getTableCellWidget(point);\n }\n else {\n cellWidget = this.childWidgets[0].getTableCellWidget(point);\n }\n }\n return cellWidget;\n };\n /**\n * @private\n */\n TableRowWidget.prototype.destroyInternal = function (viewer) {\n var height = this.height;\n if (!isNullOrUndefined(this.childWidgets)) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var widget = this.childWidgets[i];\n widget.destroyInternal(viewer);\n if (isNullOrUndefined(this.childWidgets)) {\n break;\n }\n i--;\n }\n this.childWidgets = undefined;\n }\n if (!isNullOrUndefined(this.containerWidget)) {\n if (!isNullOrUndefined(this.containerWidget.childWidgets)) {\n this.containerWidget.childWidgets.splice(this.containerWidget.childWidgets.indexOf(this), 1);\n if ((isNullOrUndefined(this.containerWidget.childWidgets) || this.containerWidget.childWidgets.length === 0)\n && this.containerWidget instanceof TableWidget) {\n this.containerWidget.destroyInternal(viewer);\n }\n else if (this.containerWidget.containerWidget instanceof BodyWidget) {\n this.containerWidget.containerWidget.height -= height;\n }\n this.containerWidget.height -= height;\n }\n }\n this.destroy();\n };\n /**\n * @private\n */\n TableRowWidget.prototype.clone = function () {\n var row = new TableRowWidget();\n row.rowFormat.copyFormat(this.rowFormat);\n row.topBorderWidth = this.topBorderWidth;\n row.bottomBorderWidth = this.bottomBorderWidth;\n for (var i = 0; i < this.childWidgets.length; i++) {\n var cell = this.childWidgets[i].clone();\n row.childWidgets.push(cell);\n cell.containerWidget = row;\n cell.index = i;\n cell.rowIndex = this.rowIndex;\n }\n row.x = this.x;\n row.y = this.y;\n row.height = this.height;\n row.width = this.width;\n return row;\n };\n /**\n * @private\n */\n TableRowWidget.prototype.destroy = function () {\n // if (this.rowFormat) {\n // this.rowFormat.destroy();\n // }\n this.rowFormat = undefined;\n this.rowFormat = undefined;\n this.spannedRowCollection = [];\n this.spannedRowCollection = undefined;\n this.topBorderWidth = undefined;\n this.bottomBorderWidth = undefined;\n _super.prototype.destroy.call(this);\n };\n return TableRowWidget;\n}(BlockWidget));\nexport { TableRowWidget };\n/**\n * @private\n */\nvar TableCellWidget = /** @class */ (function (_super) {\n __extends(TableCellWidget, _super);\n function TableCellWidget() {\n var _this = _super.call(this) || this;\n /**\n * @private\n */\n _this.rowIndex = -1;\n _this.margin = new Margin(_this.leftMargin, _this.topMargin, _this.rightMargin, _this.bottomMargin);\n _this.leftBorderWidth = 0;\n _this.rightBorderWidth = 0;\n _this.cellFormat = new WCellFormat(_this);\n return _this;\n }\n Object.defineProperty(TableCellWidget.prototype, \"ownerColumn\", {\n /**\n * @private\n */\n get: function () {\n return this.ownerTable.tableHolder.columns[this.columnIndex];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableCellWidget.prototype, \"leftMargin\", {\n /**\n * @private\n */\n get: function () {\n if (this.cellFormat && this.cellFormat.containsMargins()) {\n return this.cellFormat.leftMargin;\n }\n else if (!isNullOrUndefined(this.ownerTable) && !isNullOrUndefined(this.ownerTable.tableFormat)) {\n return this.ownerTable.tableFormat.leftMargin;\n }\n else {\n return 0;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableCellWidget.prototype, \"topMargin\", {\n /**\n * @private\n */\n get: function () {\n if (this.cellFormat && this.cellFormat.containsMargins()) {\n return this.cellFormat.topMargin;\n }\n else if (!isNullOrUndefined(this.ownerTable) && !isNullOrUndefined(this.ownerTable.tableFormat)) {\n return this.ownerTable.tableFormat.topMargin;\n }\n else {\n return 0;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableCellWidget.prototype, \"rightMargin\", {\n /**\n * @private\n */\n get: function () {\n if (this.cellFormat && this.cellFormat.containsMargins()) {\n return this.cellFormat.rightMargin;\n }\n else if (!isNullOrUndefined(this.ownerTable) && !isNullOrUndefined(this.ownerTable.tableFormat)) {\n return this.ownerTable.tableFormat.rightMargin;\n }\n else {\n return 0;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableCellWidget.prototype, \"bottomMargin\", {\n /**\n * @private\n */\n get: function () {\n if (this.cellFormat && this.cellFormat.containsMargins()) {\n return this.cellFormat.bottomMargin;\n }\n else if (!isNullOrUndefined(this.ownerTable) && !isNullOrUndefined(this.ownerTable.tableFormat)) {\n return this.ownerTable.tableFormat.bottomMargin;\n }\n else {\n return 0;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableCellWidget.prototype, \"cellIndex\", {\n /**\n * @private\n */\n get: function () {\n if (this.ownerRow) {\n return this.ownerRow.childWidgets.indexOf(this);\n }\n return -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableCellWidget.prototype, \"ownerTable\", {\n /**\n * @private\n */\n get: function () {\n if (this.containerWidget instanceof TableRowWidget) {\n return this.containerWidget.ownerTable;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TableCellWidget.prototype, \"ownerRow\", {\n /**\n * @private\n */\n get: function () {\n return this.containerWidget;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n TableCellWidget.prototype.equals = function (widget) {\n return widget instanceof TableCellWidget && widget.cellFormat === this.cellFormat;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getContainerTable = function () {\n var table = this.ownerTable;\n while (table instanceof TableWidget && table.associatedCell instanceof TableCellWidget) {\n table = table.associatedCell.getContainerTable();\n }\n return table;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getPreviousSplitWidget = function () {\n if (this.containerWidget instanceof TableRowWidget) {\n var row = this.containerWidget;\n do {\n row = row.previousRenderedWidget;\n if (isNullOrUndefined(row) || row.index < this.rowIndex) {\n break;\n }\n var previousCell = row.getCell(this.rowIndex, this.index);\n if (previousCell && this.equals(previousCell)) {\n return previousCell;\n }\n } while (row);\n }\n return undefined;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getNextSplitWidget = function () {\n var rowSpan = this.cellFormat.rowSpan;\n if (this.containerWidget instanceof TableRowWidget) {\n var row = this.containerWidget;\n do {\n row = row.nextRenderedWidget;\n if (isNullOrUndefined(row) || row.index > this.rowIndex + rowSpan) {\n break;\n }\n var nextCell = row.getCell(this.rowIndex, this.index);\n if (nextCell && this.equals(nextCell)) {\n return nextCell;\n }\n } while (row);\n }\n return undefined;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getTableCellWidget = function (point) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n if (this.childWidgets[i].y <= point.y\n && (this.childWidgets[i].y + this.childWidgets[i].height) >= point.y) {\n return this.childWidgets[i].getTableCellWidget(point);\n }\n }\n var tableCellWidget = undefined;\n if (this.childWidgets.length > 0) {\n if (this.childWidgets[0].y <= point.y) {\n tableCellWidget = this.childWidgets[this.childWidgets.length - 1].getTableCellWidget(point);\n }\n else {\n tableCellWidget = this.childWidgets[0].getTableCellWidget(point);\n }\n }\n return tableCellWidget;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.updateWidth = function (preferredWidth) {\n if (this.cellFormat.preferredWidthType === 'Auto') {\n this.cellFormat.preferredWidth = preferredWidth;\n this.cellFormat.preferredWidthType = 'Point';\n }\n else if (this.cellFormat.preferredWidthType === 'Point') {\n this.cellFormat.preferredWidth = preferredWidth;\n }\n else if (this.cellFormat.preferredWidthType === 'Percent') {\n this.cellFormat.preferredWidth = this.convertPointToPercent(preferredWidth);\n }\n this.cellFormat.cellWidth = preferredWidth;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.convertPointToPercent = function (cellPreferredWidth) {\n var value = 0;\n var clientWidth = this.ownerTable.getOwnerWidth(true);\n var tableWidth = this.ownerTable.getTableClientWidth(clientWidth);\n value = (cellPreferredWidth / tableWidth) * 100;\n value = Math.round(value);\n return value < 100 ? value : 100; // The value should be lesser than or equal to 100%;\n };\n /**\n * @private\n */\n TableCellWidget.getCellLeftBorder = function (tableCell) {\n var leftBorder = undefined;\n var cellBorder = tableCell.cellFormat.borders;\n var rowBorders = !isNullOrUndefined(tableCell.ownerRow) ? tableCell.ownerRow.rowFormat.borders : undefined;\n var tableBorders = !isNullOrUndefined(tableCell.ownerTable) ? tableCell.ownerTable.tableFormat.borders : undefined;\n if (!isNullOrUndefined(cellBorder.left)) {\n leftBorder = cellBorder.left;\n }\n if (isNullOrUndefined(leftBorder)) {\n leftBorder = tableCell.getLeftBorderToRenderByHierarchy(leftBorder, rowBorders, tableBorders);\n }\n if (tableCell.ownerTable.tableFormat.cellSpacing > 0) {\n leftBorder = tableCell.getLeftBorderToRenderByHierarchy(leftBorder, rowBorders, tableBorders);\n }\n else {\n var prevCell = undefined;\n if (!isNullOrUndefined(tableCell.previousWidget)) {\n // if the border is shared then choose the border based on Conflict Resolution algorithm.\n prevCell = tableCell.previousWidget;\n }\n else if ((tableCell.cellFormat.columnSpan > 1 || tableCell.columnIndex > 1) && tableCell.ownerRow.rowIndex > 0) {\n var previousRow = tableCell.ownerRow.previousWidget;\n while (!isNullOrUndefined(previousRow) && previousRow.childWidgets.length > 0) {\n for (var i = 0; i < previousRow.childWidgets.length; i++) {\n var prevRowCell = previousRow.childWidgets[i];\n if (prevRowCell.columnIndex + prevRowCell.cellFormat.columnSpan === tableCell.columnIndex) {\n prevCell = previousRow.childWidgets[i];\n break;\n }\n }\n if (!isNullOrUndefined(prevCell)) {\n break;\n }\n previousRow = previousRow.previousWidget;\n }\n }\n leftBorder = tableCell.getPreviousCellLeftBorder(leftBorder, prevCell);\n }\n if (isNullOrUndefined(leftBorder)) {\n leftBorder = new WBorder(tableCell.cellFormat.borders);\n }\n return leftBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getLeftBorderWidth = function () {\n var borderWidth = 0;\n //let ownerTable = this.ownerTable;\n //Added null condition check for asynchronous loading.\n // if (this.cellFormat !== null && this.cellFormat.borders !== null) {\n // update the margins values respect to layouting of borders.\n //For normal table cells only left border is rendred. for last cell left and right border is rendred.\n // this border widths are not included in margins.\n // boderWidth = this.cellFormat.borders.GetRightBorderToRender(this).GetLineWidth();\n //need to render rightBorder specifically for all the cells when the cellSpacing is greater than zero or for last cell of each row.\n // }\n return borderWidth;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getRightBorderWidth = function () {\n var borderWidth = 0;\n var ownerTable = this.ownerTable;\n //Added null condition check for asynchronous loading.\n // if (this.cellFormat !== null && this.cellFormat.borders !== null) {\n ///need to render right border specifically for all the cells when the cell spacing is \n //greater than zero or for last cell of each row.\n // let isLastCell: boolean = false;\n // isLastCell = this.cellIndex === 0;\n // if (ownerTable.tableFormat.cellSpacing > 0 || isLastCell) {\n // boderWidth = this.cellFormat.borders.getLeftBorderToRender(this).GetLineWidth();\n // }\n // }\n return borderWidth;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getCellSpacing = function () {\n var actualCellSpacing = this.ownerTable && this.ownerTable.tableFormat ? this.ownerTable.tableFormat.cellSpacing : 0;\n var cellSpacingToLayout = actualCellSpacing;\n // Considers the left, right margins and border widths(only available for Layouted table) for Minimum width.\n if (this.ownerRow.childWidgets.length === 1) {\n cellSpacingToLayout = actualCellSpacing * 2;\n }\n else if (this.cellIndex === 0 || this.cellIndex === this.ownerRow.childWidgets.length - 1) {\n cellSpacingToLayout = actualCellSpacing + (actualCellSpacing / 2);\n }\n else {\n cellSpacingToLayout = actualCellSpacing;\n }\n return cellSpacingToLayout;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getMinimumPreferredWidth = function () {\n var defaultWidth = 0;\n defaultWidth = this.leftMargin + this.rightMargin + this.getLeftBorderWidth() + this.getRightBorderWidth() + this.getCellSpacing();\n return defaultWidth;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getPreviousCellLeftBorder = function (leftBorder, previousCell) {\n // tslint:disable-next-line:max-line-length\n if ((isNullOrUndefined(previousCell) || (!isNullOrUndefined(leftBorder) && (leftBorder.lineStyle === 'None' && !leftBorder.hasNoneStyle)))) {\n if (!isNullOrUndefined(leftBorder) && !(leftBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getLeftBorderToRenderByHierarchy(leftBorder, TableRowWidget.getRowOf(leftBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(leftBorder.ownerBase).tableFormat.borders);\n }\n }\n else {\n var prevCellRightBorder = undefined;\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(previousCell.cellFormat.borders) && !isNullOrUndefined(previousCell.cellFormat.borders.right) && previousCell.cellFormat.borders.right.lineStyle !== 'None') {\n prevCellRightBorder = previousCell.cellFormat.borders.right;\n }\n if (!isNullOrUndefined(prevCellRightBorder) && prevCellRightBorder.lineStyle !== 'None') {\n return this.getBorderBasedOnPriority(prevCellRightBorder, leftBorder);\n }\n else if (!isNullOrUndefined(leftBorder) && !(leftBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getLeftBorderToRenderByHierarchy(leftBorder, TableRowWidget.getRowOf(leftBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(leftBorder.ownerBase).tableFormat.borders);\n }\n }\n return leftBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getBorderBasedOnPriority = function (border, adjacentBorder) {\n // If the cell and its adjacent cell defined different borders then based on this algorithm the border choose to render.\n // Reference link :https://msdn.microsoft.com/en-us/library/office/documentformat.openxml.wordprocessing.tablecellborders.aspx\n if (isNullOrUndefined(border)) {\n return adjacentBorder;\n }\n else if (isNullOrUndefined(adjacentBorder)) {\n return border;\n }\n var borderWeight = border.getBorderWeight();\n var adjacentBorderWeight = adjacentBorder.getBorderWeight();\n //the border with higher wight shall be displayed.\n if (borderWeight === adjacentBorderWeight) {\n //if the border is equal weight the based on the priority the border will be choosen to render.\n var borderPriority = border.getPrecedence();\n var adjacentBorderPriority = adjacentBorder.getPrecedence();\n if (borderPriority === adjacentBorderPriority) {\n //The color with the smaller brightness value shall be displayed.\n var borderColInRGB = this.convertHexToRGB(border.color);\n var R1 = borderColInRGB.r;\n var G1 = borderColInRGB.g;\n var B1 = borderColInRGB.b;\n var adjacentBorderColInRGB = this.convertHexToRGB(adjacentBorder.color);\n var R2 = adjacentBorderColInRGB.r;\n var G2 = adjacentBorderColInRGB.g;\n var B2 = adjacentBorderColInRGB.b;\n var borderBrightness = (R1 + B1 + (2 * G1));\n var adjacentBorderBrightness = (R2 + B2 + (2 * G2));\n if (borderBrightness === adjacentBorderBrightness) {\n borderBrightness = (B1 + (2 * G1));\n adjacentBorderBrightness = (B2 + (2 * G2));\n if (borderBrightness === adjacentBorderBrightness) {\n if (G1 === G2) {\n return border;\n }\n else if (G1 > G2) {\n return adjacentBorder;\n }\n else {\n return border;\n }\n }\n else if (borderBrightness > adjacentBorderBrightness) {\n return adjacentBorder;\n }\n else {\n return border;\n }\n }\n else if (borderBrightness > adjacentBorderBrightness) {\n return adjacentBorder;\n }\n else {\n return border;\n }\n }\n else if (borderPriority > adjacentBorderPriority) {\n return border;\n }\n else {\n return adjacentBorder;\n }\n }\n else if (borderWeight > adjacentBorderWeight) {\n return border;\n }\n else {\n return adjacentBorder;\n }\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getLeftBorderToRenderByHierarchy = function (leftBorder, rowBorders, tableBorders) {\n if (!isNullOrUndefined(leftBorder) && (leftBorder.lineStyle !== 'None' || (leftBorder.hasNoneStyle &&\n //If border defined with default values then border drawn based on hierarchy. \n !(leftBorder.lineStyle === 'None' && leftBorder.lineWidth === 0 && leftBorder.color === '#000000')))) {\n return leftBorder;\n // tslint:disable-next-line:max-line-length\n }\n else if (!isNullOrUndefined(leftBorder) && (leftBorder.ownerBase instanceof WBorders) && TableCellWidget.getCellOf(leftBorder.ownerBase).columnIndex === 0) {\n if (!isNullOrUndefined(tableBorders) && !isNullOrUndefined(tableBorders.left)) {\n leftBorder = tableBorders.left;\n }\n return leftBorder;\n }\n else if (!isNullOrUndefined(rowBorders)\n && !isNullOrUndefined(rowBorders.vertical) && rowBorders.vertical.lineStyle !== 'None') {\n return leftBorder = rowBorders.vertical;\n }\n else if (!isNullOrUndefined(tableBorders)\n && !isNullOrUndefined(tableBorders.vertical) && tableBorders.vertical.lineStyle !== 'None') {\n return leftBorder = tableBorders.vertical;\n }\n else {\n return leftBorder;\n }\n };\n /**\n * @private\n */\n TableCellWidget.getCellRightBorder = function (tableCell) {\n var rightBorder = undefined;\n var cellBorder = tableCell.cellFormat.borders;\n var rowBorders = !isNullOrUndefined(tableCell.ownerRow) ? tableCell.ownerRow.rowFormat.borders : undefined;\n var tableBorders = !isNullOrUndefined(tableCell.ownerTable) ? tableCell.ownerTable.tableFormat.borders : undefined;\n if (!isNullOrUndefined(cellBorder.right)) {\n rightBorder = cellBorder.right;\n }\n if (isNullOrUndefined(rightBorder)) {\n rightBorder = tableCell.getRightBorderToRenderByHierarchy(rightBorder, rowBorders, tableBorders);\n }\n if (tableCell.ownerTable.tableFormat.cellSpacing > 0) {\n rightBorder = tableCell.getRightBorderToRenderByHierarchy(rightBorder, rowBorders, tableBorders);\n }\n else {\n var nextCell = undefined;\n if (!isNullOrUndefined(tableCell.nextWidget)) {\n nextCell = tableCell.nextWidget;\n }\n // if the border is shared then choose the border based on Conflict Resolution algorithm.\n rightBorder = tableCell.getAdjacentCellRightBorder(rightBorder, nextCell);\n }\n if (isNullOrUndefined(rightBorder)) {\n rightBorder = new WBorder(tableCell.cellFormat.borders);\n }\n return rightBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getAdjacentCellRightBorder = function (rightBorder, nextCell) {\n // tslint:disable-next-line:max-line-length\n if (isNullOrUndefined(nextCell) || (!isNullOrUndefined(rightBorder) && (rightBorder.lineStyle === 'None' && !rightBorder.hasNoneStyle))) {\n if (!isNullOrUndefined(rightBorder) && !(rightBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getRightBorderToRenderByHierarchy(rightBorder, TableRowWidget.getRowOf(rightBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(rightBorder.ownerBase).tableFormat.borders);\n }\n }\n else {\n var nextCellLeftBorder = undefined;\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(nextCell.cellFormat.borders) && !isNullOrUndefined(nextCell.cellFormat.borders.left) && nextCell.cellFormat.borders.left.lineStyle !== 'None') {\n nextCellLeftBorder = nextCell.cellFormat.borders.left;\n }\n if (!isNullOrUndefined(nextCellLeftBorder) && nextCellLeftBorder.lineStyle !== 'None') {\n return this.getBorderBasedOnPriority(rightBorder, nextCellLeftBorder);\n }\n else if (!isNullOrUndefined(rightBorder) && !(rightBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getRightBorderToRenderByHierarchy(rightBorder, TableRowWidget.getRowOf(rightBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(rightBorder.ownerBase).tableFormat.borders);\n }\n }\n return rightBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getRightBorderToRenderByHierarchy = function (rightBorder, rowBorders, tableBorders) {\n if (!isNullOrUndefined(rightBorder) && (rightBorder.lineStyle !== 'None' || (rightBorder.hasNoneStyle &&\n //If border defined with default values then border drawn based on hierarchy. \n !(rightBorder.lineStyle === 'None' && rightBorder.lineWidth === 0 && rightBorder.color === '#000000')))) {\n return rightBorder;\n // tslint:disable-next-line:max-line-length\n }\n else if (!isNullOrUndefined(rightBorder) && (rightBorder.ownerBase instanceof WBorders) && TableCellWidget.getCellOf(rightBorder.ownerBase).columnIndex === TableCellWidget.getCellOf(rightBorder.ownerBase).ownerRow.childWidgets.length - 1) {\n if (!isNullOrUndefined(tableBorders) && !isNullOrUndefined(tableBorders.right)) {\n rightBorder = tableBorders.right;\n }\n return rightBorder;\n }\n else if (!isNullOrUndefined(rowBorders)\n && !isNullOrUndefined(rowBorders.vertical) && rowBorders.vertical.lineStyle !== 'None') {\n return rightBorder = rowBorders.vertical;\n }\n else if (!isNullOrUndefined(tableBorders)\n && !isNullOrUndefined(tableBorders.vertical) && tableBorders.vertical.lineStyle !== 'None') {\n return rightBorder = tableBorders.vertical;\n }\n else {\n return rightBorder;\n }\n };\n /**\n * @private\n */\n TableCellWidget.getCellTopBorder = function (tableCell) {\n var topBorder = undefined;\n var cellBorder = tableCell.cellFormat.borders;\n var rowBorders = !isNullOrUndefined(tableCell.ownerRow) ? tableCell.ownerRow.rowFormat.borders : undefined;\n var tableBorders = !isNullOrUndefined(tableCell.ownerTable) ? tableCell.ownerTable.tableFormat.borders : undefined;\n if (!isNullOrUndefined(cellBorder.top)) {\n topBorder = cellBorder.top;\n }\n if (isNullOrUndefined(topBorder)) {\n topBorder = tableCell.getTopBorderToRenderByHierarchy(topBorder, rowBorders, tableBorders);\n }\n if (tableCell.ownerTable.tableFormat.cellSpacing > 0) {\n topBorder = tableCell.getTopBorderToRenderByHierarchy(topBorder, rowBorders, tableBorders);\n }\n else {\n var prevTopCell = undefined;\n //ToDo: Need to analyze more to get the previous cell.\n var prevRow = tableCell.ownerRow.previousWidget;\n while (!isNullOrUndefined(prevRow) && prevRow.childWidgets.length > 0) {\n for (var i = 0; i < prevRow.childWidgets.length; i++) {\n var prevRowCell = prevRow.childWidgets[i];\n if (prevRowCell.columnIndex + prevRowCell.cellFormat.columnSpan - 1 >= tableCell.columnIndex) {\n prevTopCell = prevRow.childWidgets[i];\n break;\n }\n }\n if (!isNullOrUndefined(prevTopCell)) {\n break;\n }\n prevRow = prevRow.previousWidget;\n //If all the previous rows checked and the previous top cell is null\n // then TableCell previus row matched column index cell is taken for border calculation.\n if (isNullOrUndefined(prevRow) && isNullOrUndefined(prevTopCell)) {\n prevRow = tableCell.ownerRow.previousWidget;\n if (tableCell.columnIndex < prevRow.childWidgets.length) {\n for (var i = 0; i < prevRow.childWidgets.length; i++) {\n var prevRowCell = prevRow.childWidgets[i];\n if (prevRowCell.columnIndex === tableCell.columnIndex) {\n prevTopCell = prevRow.childWidgets[i];\n break;\n }\n }\n //If table cell Column index is greater than previous row cells count then last cell is taken as previous top cell.\n }\n else {\n // tslint:disable-next-line:max-line-length\n prevTopCell = tableCell.ownerRow.previousWidget.childWidgets[tableCell.ownerRow.previousWidget.childWidgets.length - 1];\n }\n }\n }\n //If the border is shared then choose the border based on Conflict Resolution algorithm.\n topBorder = tableCell.getPreviousCellTopBorder(topBorder, prevTopCell);\n }\n if (isNullOrUndefined(topBorder)) {\n topBorder = new WBorder(tableCell.cellFormat.borders);\n }\n return topBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getPreviousCellTopBorder = function (topBorder, previousTopCell) {\n // tslint:disable-next-line:max-line-length\n if (isNullOrUndefined(previousTopCell) || (!isNullOrUndefined(topBorder) && (topBorder.lineStyle === 'None' && !topBorder.hasNoneStyle))) {\n if (!isNullOrUndefined(topBorder) && !(topBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getTopBorderToRenderByHierarchy(topBorder, TableRowWidget.getRowOf(topBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(topBorder.ownerBase).tableFormat.borders);\n }\n }\n else {\n var prevTopCellBottomBorder = undefined;\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(previousTopCell.cellFormat.borders) && !isNullOrUndefined(previousTopCell.cellFormat.borders.bottom) && previousTopCell.cellFormat.borders.bottom.lineStyle !== 'None') {\n prevTopCellBottomBorder = previousTopCell.cellFormat.borders.bottom;\n }\n if (!isNullOrUndefined(prevTopCellBottomBorder) && prevTopCellBottomBorder.lineStyle !== 'None') {\n return this.getBorderBasedOnPriority(topBorder, prevTopCellBottomBorder);\n }\n else if (!isNullOrUndefined(topBorder) && !(topBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getTopBorderToRenderByHierarchy(topBorder, TableRowWidget.getRowOf(topBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(topBorder.ownerBase).tableFormat.borders);\n }\n }\n return topBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getTopBorderToRenderByHierarchy = function (topBorder, rowBorders, tableBorders) {\n if (!isNullOrUndefined(topBorder) && (topBorder.lineStyle !== 'None' || (topBorder.hasNoneStyle &&\n //If border defined with default values then border drawn based on hierarchy. \n !(topBorder.lineStyle === 'None' && topBorder.lineWidth === 0 && topBorder.color === '#000000')))) {\n return topBorder;\n // tslint:disable-next-line:max-line-length\n }\n else if (!isNullOrUndefined(topBorder) && (topBorder.ownerBase instanceof WBorders) && TableCellWidget.getCellOf(topBorder.ownerBase).ownerRow.rowIndex === 0) {\n if (!isNullOrUndefined(tableBorders) && !isNullOrUndefined(tableBorders.top)) {\n topBorder = tableBorders.top;\n }\n return topBorder;\n }\n else if (!isNullOrUndefined(rowBorders)\n && !isNullOrUndefined(rowBorders.horizontal) && rowBorders.horizontal.lineStyle !== 'None') {\n return topBorder = rowBorders.horizontal;\n }\n else if (!isNullOrUndefined(tableBorders)\n && !isNullOrUndefined(tableBorders.horizontal) && tableBorders.horizontal.lineStyle !== 'None') {\n return topBorder = tableBorders.horizontal;\n }\n else {\n return topBorder;\n }\n };\n /**\n * @private\n */\n TableCellWidget.getCellBottomBorder = function (tableCell) {\n var bottomBorder = undefined;\n var cellBorder = tableCell.cellFormat.borders;\n var rowBorders = !isNullOrUndefined(tableCell.ownerRow) ? tableCell.ownerRow.rowFormat.borders : undefined;\n var tableBorders = !isNullOrUndefined(tableCell.ownerTable) ? tableCell.ownerTable.tableFormat.borders : undefined;\n if (!isNullOrUndefined(cellBorder.bottom)) {\n bottomBorder = cellBorder.bottom;\n }\n if (isNullOrUndefined(bottomBorder)) {\n // tslint:disable-next-line:max-line-length\n bottomBorder = tableCell.getBottomBorderToRenderByHierarchy(bottomBorder, rowBorders, tableBorders); // select the left border based on heirarchy.\n }\n if (tableCell.ownerTable.tableFormat.cellSpacing > 0) {\n bottomBorder = tableCell.getBottomBorderToRenderByHierarchy(bottomBorder, rowBorders, tableBorders);\n }\n else {\n var nextBottomCell = undefined;\n var nextRow = tableCell.ownerRow.nextWidget;\n if (!isNullOrUndefined(nextRow) && tableCell.columnIndex < nextRow.childWidgets.length) {\n nextBottomCell = nextRow.childWidgets[tableCell.columnIndex];\n }\n //If the border is shared then choose the border based on Conflict Resolution algorithm.\n bottomBorder = tableCell.getAdjacentCellBottomBorder(bottomBorder, nextBottomCell);\n }\n if (isNullOrUndefined(bottomBorder)) {\n bottomBorder = new WBorder(tableCell.cellFormat.borders);\n }\n return bottomBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getAdjacentCellBottomBorder = function (bottomBorder, nextBottomCell) {\n // tslint:disable-next-line:max-line-length\n if (isNullOrUndefined(nextBottomCell) || (!isNullOrUndefined(bottomBorder) && (bottomBorder.lineStyle === 'None' && !bottomBorder.hasNoneStyle))) {\n if (!isNullOrUndefined(bottomBorder) && !(bottomBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getBottomBorderToRenderByHierarchy(bottomBorder, TableRowWidget.getRowOf(bottomBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(bottomBorder.ownerBase).tableFormat.borders);\n }\n }\n else {\n var prevBottomCellTopBorder = undefined;\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(nextBottomCell.cellFormat.borders) && !isNullOrUndefined(nextBottomCell.cellFormat.borders.top) && nextBottomCell.cellFormat.borders.top.lineStyle !== 'None') {\n prevBottomCellTopBorder = nextBottomCell.cellFormat.borders.top;\n }\n if (!isNullOrUndefined(prevBottomCellTopBorder) && prevBottomCellTopBorder.lineStyle !== 'None') {\n return this.getBorderBasedOnPriority(bottomBorder, prevBottomCellTopBorder);\n }\n else if (!isNullOrUndefined(bottomBorder) && !(bottomBorder.ownerBase.ownerBase instanceof WTableFormat)) {\n // tslint:disable-next-line:max-line-length\n return this.getBottomBorderToRenderByHierarchy(bottomBorder, TableRowWidget.getRowOf(bottomBorder.ownerBase).rowFormat.borders, TableWidget.getTableOf(bottomBorder.ownerBase).tableFormat.borders);\n }\n }\n return bottomBorder;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.getBottomBorderToRenderByHierarchy = function (bottomBorder, rowBorders, tableBorders) {\n if (!isNullOrUndefined(bottomBorder) && (bottomBorder.lineStyle !== 'None' || (bottomBorder.hasNoneStyle &&\n //If border defined with default values then border drawn based on hierarchy. \n !(bottomBorder.lineStyle === 'None' && bottomBorder.lineWidth === 0 && bottomBorder.color === '#000000')))) {\n return bottomBorder;\n // tslint:disable-next-line:max-line-length\n }\n else if (!isNullOrUndefined(bottomBorder) && (bottomBorder.ownerBase instanceof WBorders) && TableCellWidget.getCellOf(bottomBorder.ownerBase).ownerRow.rowIndex + TableCellWidget.getCellOf(bottomBorder.ownerBase).cellFormat.rowSpan === TableCellWidget.getCellOf(bottomBorder.ownerBase).ownerTable.childWidgets.length) {\n if (!isNullOrUndefined(tableBorders) && !isNullOrUndefined(tableBorders.bottom)) {\n bottomBorder = tableBorders.bottom;\n }\n return bottomBorder;\n }\n else if (!isNullOrUndefined(rowBorders)\n && !isNullOrUndefined(rowBorders.horizontal) && rowBorders.horizontal.lineStyle !== 'None') {\n return bottomBorder = rowBorders.horizontal;\n }\n else if (!isNullOrUndefined(tableBorders)\n && !isNullOrUndefined(tableBorders.horizontal) && tableBorders.horizontal.lineStyle !== 'None') {\n return bottomBorder = tableBorders.horizontal;\n }\n else {\n return bottomBorder;\n }\n };\n TableCellWidget.prototype.convertHexToRGB = function (colorCode) {\n if (colorCode) {\n colorCode = colorCode.replace(/[^0-9A-‌​F]/gi, ''); // To remove # from color code string.\n var colCodeNo = parseInt(colorCode, 16);\n var r = (colCodeNo >> 16) & 255;\n var g = (colCodeNo >> 8) & 255;\n var b = colCodeNo & 255;\n return { 'r': r, 'g': g, 'b': b };\n }\n return undefined;\n };\n /**\n * @private\n */\n TableCellWidget.getCellOf = function (node) {\n if (node instanceof WBorders) {\n if (node.ownerBase instanceof WCellFormat && node.ownerBase.ownerBase instanceof TableCellWidget) {\n return node.ownerBase.ownerBase;\n }\n else {\n return undefined;\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.destroyInternal = function (viewer) {\n // let viewer: LayoutViewer = undefined;\n // let page: Page = this.getPage();\n // if (!isNullOrUndefined(page ))\n // viewer = page.viewer;\n if (!isNullOrUndefined(this.childWidgets)) {\n for (var i = 0; i < this.childWidgets.length; i++) {\n var widget = this.childWidgets[i];\n if (widget instanceof ParagraphWidget) {\n widget.destroyInternal(viewer);\n }\n else {\n widget.destroyInternal(viewer);\n }\n i--;\n }\n this.childWidgets = undefined;\n }\n this.destroy();\n };\n /**\n * @private\n */\n TableCellWidget.prototype.clone = function () {\n var cell = new TableCellWidget();\n cell.cellFormat.copyFormat(this.cellFormat);\n for (var i = 0; i < this.childWidgets.length; i++) {\n var block = this.childWidgets[i].clone();\n cell.childWidgets.push(block);\n block.containerWidget = cell;\n block.index = i;\n }\n cell.leftBorderWidth = this.leftBorderWidth;\n cell.rightBorderWidth = this.rightBorderWidth;\n if (this.margin) {\n cell.margin = this.margin.clone();\n }\n cell.columnIndex = this.columnIndex;\n cell.x = this.x;\n cell.y = this.y;\n cell.height = this.height;\n cell.width = this.width;\n return cell;\n };\n /**\n * @private\n */\n TableCellWidget.prototype.destroy = function () {\n // if (this.cellFormat) {\n // this.cellFormat.destroy();\n // }\n this.cellFormat = undefined;\n this.rowIndex = undefined;\n this.columnIndex = undefined;\n _super.prototype.destroy.call(this);\n };\n return TableCellWidget;\n}(BlockWidget));\nexport { TableCellWidget };\n/**\n * @private\n */\nvar LineWidget = /** @class */ (function () {\n /**\n * Initialize the constructor of LineWidget\n */\n function LineWidget(paragraphWidget) {\n /**\n * @private\n */\n this.children = [];\n /**\n * @private\n */\n this.x = 0;\n /**\n * @private\n */\n this.y = 0;\n /**\n * @private\n */\n this.width = 0;\n /**\n * @private\n */\n this.height = 0;\n this.paragraph = paragraphWidget;\n }\n Object.defineProperty(LineWidget.prototype, \"indexInOwner\", {\n /**\n * @private\n */\n get: function () {\n if (this.paragraph && this.paragraph.childWidgets) {\n return this.paragraph.childWidgets.indexOf(this);\n }\n return -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LineWidget.prototype, \"nextLine\", {\n /**\n * @private\n */\n get: function () {\n var paragraph = this.paragraph;\n var lineIndex = this.indexInOwner;\n if (lineIndex <= paragraph.childWidgets.length - 2) {\n return paragraph.childWidgets[lineIndex + 1];\n }\n else if (paragraph.nextSplitWidget) {\n var line = paragraph.nextSplitWidget.firstChild;\n if (line instanceof LineWidget && line.paragraph.equals(this.paragraph)) {\n return line;\n }\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LineWidget.prototype, \"previousLine\", {\n /**\n * @private\n */\n get: function () {\n var paragraph = this.paragraph;\n var lineIndex = this.indexInOwner;\n var splitParagraph = paragraph.previousSplitWidget;\n if (lineIndex > 0) {\n return paragraph.childWidgets[lineIndex - 1];\n }\n else if (splitParagraph instanceof ParagraphWidget) {\n var line = splitParagraph.lastChild;\n if (line instanceof LineWidget && line.paragraph.equals(this.paragraph)) {\n return line;\n }\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n LineWidget.prototype.isFirstLine = function () {\n var index = this.indexInOwner;\n if (index > -1 && this.paragraph.previousSplitWidget === undefined) {\n return index === 0;\n }\n return false;\n };\n /**\n * @private\n */\n LineWidget.prototype.isLastLine = function () {\n var index = this.indexInOwner;\n if (index > -1 && this.paragraph.nextSplitWidget === undefined) {\n return index === this.paragraph.childWidgets.length - 1;\n }\n return false;\n };\n /**\n * @private\n */\n LineWidget.prototype.getOffset = function (inline, index) {\n if (isNullOrUndefined(inline)) {\n return index;\n }\n var textIndex = index;\n var line = inline.line;\n var lineIndex = inline.line.paragraph.childWidgets.indexOf(inline.line);\n for (var i = 0; i < line.children.length; i++) {\n var inlineElement = line.children[i];\n if (inline === inlineElement) {\n break;\n }\n if (inlineElement instanceof ListTextElementBox) {\n continue;\n }\n textIndex += inlineElement.length;\n }\n return textIndex;\n };\n /**\n * @private\n */\n LineWidget.prototype.getEndOffset = function () {\n var startOffset = 0;\n var count = 0;\n for (var i = 0; i < this.children.length; i++) {\n var inlineElement = this.children[i];\n if (inlineElement.length === 0) {\n continue;\n }\n if (inlineElement instanceof ListTextElementBox) {\n continue;\n }\n if (inlineElement instanceof TextElementBox || inlineElement instanceof ImageElementBox\n || inlineElement instanceof BookmarkElementBox || (inlineElement instanceof FieldElementBox\n && HelperMethods.isLinkedFieldCharacter(inlineElement))) {\n startOffset = count + inlineElement.length;\n }\n count += inlineElement.length;\n }\n return startOffset;\n };\n /**\n * @private\n */\n LineWidget.prototype.getInline = function (offset, indexInInline) {\n var inlineElement = undefined;\n var count = 0;\n var isStarted = false;\n if (this.children.length === 0) {\n if (this.previousLine) {\n var elementBox = this.previousLine.children[this.previousLine.children.length - 1];\n if (elementBox instanceof TextElementBox && elementBox.text === '\\v') {\n inlineElement = this.previousLine.children[this.previousLine.children.length - 1];\n indexInInline = 1;\n return { 'element': inlineElement, 'index': indexInInline };\n }\n }\n }\n for (var i = 0; i < this.children.length; i++) {\n inlineElement = this.children[i];\n if (inlineElement instanceof ListTextElementBox) {\n continue;\n }\n if (!isStarted && (inlineElement instanceof TextElementBox || inlineElement instanceof ImageElementBox\n || inlineElement instanceof BookmarkElementBox\n || inlineElement instanceof FieldElementBox && HelperMethods.isLinkedFieldCharacter(inlineElement))) {\n isStarted = true;\n }\n if (isStarted && offset <= count + inlineElement.length) {\n indexInInline = (offset - count);\n return { 'element': inlineElement, 'index': indexInInline };\n }\n count += inlineElement.length;\n }\n if (offset > count) {\n indexInInline = isNullOrUndefined(inlineElement) ? offset : inlineElement.length;\n }\n return { 'element': inlineElement, 'index': indexInInline };\n };\n /**\n * @private\n */\n LineWidget.prototype.getHierarchicalIndex = function (hierarchicalIndex) {\n var node = this;\n hierarchicalIndex = node.paragraph.childWidgets.indexOf(node) + ';' + hierarchicalIndex;\n if (node.paragraph instanceof BlockWidget) {\n return node.paragraph.getHierarchicalIndex(hierarchicalIndex);\n }\n return hierarchicalIndex;\n };\n /**\n * @private\n */\n LineWidget.prototype.clone = function () {\n var line = new LineWidget(undefined);\n for (var j = 0; j < this.children.length; j++) {\n var element = this.children[j];\n var clone = element.clone();\n line.children.push(clone);\n clone.line = line;\n }\n line.width = this.width;\n line.height = this.height;\n return line;\n };\n /**\n * @private\n */\n LineWidget.prototype.destroy = function () {\n if (!isNullOrUndefined(this.children)) {\n for (var i = 0; i < this.children.length; i++) {\n this.children[i].destroy();\n }\n this.children = [];\n }\n this.children = undefined;\n if (this.paragraph) {\n this.paragraph.removeChild(this.indexInOwner);\n }\n this.paragraph = undefined;\n this.x = undefined;\n this.y = undefined;\n this.width = undefined;\n this.height = undefined;\n };\n return LineWidget;\n}());\nexport { LineWidget };\n/**\n * @private\n */\nvar ElementBox = /** @class */ (function () {\n /**\n * Initialize the constructor of ElementBox\n */\n function ElementBox() {\n /**\n * @private\n */\n this.x = 0;\n /**\n * @private\n */\n this.y = 0;\n /**\n * @private\n */\n this.width = 0;\n /**\n * @private\n */\n this.height = 0;\n /**\n * @private\n */\n this.margin = new Margin(0, 0, 0, 0);\n /**\n * @private\n */\n this.characterFormat = undefined;\n this.characterFormat = new WCharacterFormat(this);\n this.margin = new Margin(0, 0, 0, 0);\n }\n /**\n * @private\n */\n ElementBox.prototype.linkFieldCharacter = function (viewer) {\n if (!(this instanceof FieldElementBox)) {\n return;\n }\n if (this.fieldType === 0) {\n var fieldBegin = this;\n if (isNullOrUndefined(fieldBegin.fieldEnd)) {\n this.linkFieldTraversingForward(this.line, fieldBegin, fieldBegin);\n if (viewer.fields.indexOf(fieldBegin) === -1) {\n viewer.fields.push(fieldBegin);\n }\n }\n }\n else if (this.fieldType === 2) {\n var fieldSeparator = this;\n //Links the field begin for the current separator.\n if (isNullOrUndefined(fieldSeparator.fieldBegin)) {\n this.linkFieldTraversingBackwardSeparator(this.line, fieldSeparator, fieldSeparator);\n }\n fieldSeparator.fieldBegin.fieldSeparator = fieldSeparator;\n if (!isNullOrUndefined(fieldSeparator.fieldBegin)) {\n //Links to field end traversing from field separator.\n var isFieldEnd = this.linkFieldTraversingForward(this.line, fieldSeparator.fieldBegin, fieldSeparator);\n if (isNullOrUndefined(fieldSeparator.fieldEnd) && isFieldEnd) {\n fieldSeparator.fieldEnd = fieldSeparator.fieldBegin.fieldEnd;\n }\n if (fieldSeparator.fieldEnd) {\n fieldSeparator.fieldEnd.fieldSeparator = fieldSeparator;\n }\n }\n }\n else {\n var fieldEnd = this;\n //Links the field begin and separator for the current end.\n if (isNullOrUndefined(fieldEnd.fieldBegin)) {\n this.linkFieldTraversingBackward(this.line, fieldEnd, fieldEnd);\n }\n }\n };\n /**\n * @private\n */\n ElementBox.prototype.linkFieldTraversingBackward = function (line, fieldEnd, previousNode) {\n var k = line.children.length - 1;\n if (line.children.indexOf(previousNode) > -1) {\n k = line.children.indexOf(previousNode) - 1;\n }\n for (var j = k; j >= 0; j--) {\n var childNode = line.children[j];\n if (childNode instanceof FieldElementBox) {\n if (childNode.fieldType === 0) {\n if (isNullOrUndefined(childNode.fieldEnd)) {\n fieldEnd.fieldBegin = childNode;\n if (isNullOrUndefined(childNode.fieldEnd)) {\n childNode.fieldEnd = fieldEnd;\n }\n if (fieldEnd.fieldSeparator && isNullOrUndefined(fieldEnd.fieldSeparator.fieldBegin)) {\n fieldEnd.fieldSeparator.fieldBegin = childNode;\n if (isNullOrUndefined(childNode.fieldSeparator)) {\n childNode.fieldSeparator = fieldEnd.fieldSeparator;\n }\n }\n }\n return !isNullOrUndefined(fieldEnd.fieldBegin);\n }\n else if (childNode.fieldType === 2 && isNullOrUndefined(childNode.fieldEnd)) {\n fieldEnd.fieldSeparator = childNode;\n childNode.fieldEnd = fieldEnd;\n if (!isNullOrUndefined(childNode.fieldBegin)) {\n fieldEnd.fieldBegin = childNode.fieldBegin;\n }\n }\n }\n }\n if (line.previousLine) {\n this.linkFieldTraversingBackward(line.previousLine, fieldEnd, this);\n }\n else if (line.paragraph.previousRenderedWidget instanceof ParagraphWidget) {\n var prevParagraph = line.paragraph.previousRenderedWidget;\n // tslint:disable-next-line:max-line-length\n this.linkFieldTraversingBackward(prevParagraph.childWidgets[prevParagraph.childWidgets.length - 1], fieldEnd, this);\n }\n return true;\n };\n /**\n * @private\n */\n ElementBox.prototype.linkFieldTraversingForward = function (line, fieldBegin, previousNode) {\n var i = 0;\n if (line.children.indexOf(previousNode) > -1) {\n i = line.children.indexOf(previousNode) + 1;\n }\n for (var j = i; j < line.children.length; j++) {\n var node = line.children[j];\n if (node instanceof FieldElementBox) {\n if (node.fieldType === 1) {\n if (isNullOrUndefined(node.fieldBegin)) {\n fieldBegin.fieldEnd = node;\n }\n if (fieldBegin.fieldEnd && isNullOrUndefined(fieldBegin.fieldEnd.fieldBegin)) {\n fieldBegin.fieldEnd.fieldBegin = fieldBegin;\n }\n return true;\n }\n else if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n if (node.fieldType === 2 && isNullOrUndefined(node.fieldBegin)) {\n fieldBegin.fieldSeparator = node;\n if (!isNullOrUndefined(node.fieldEnd)) {\n fieldBegin.fieldEnd = node.fieldEnd;\n return true;\n }\n }\n else {\n return false;\n }\n }\n }\n }\n if (line.nextLine) {\n this.linkFieldTraversingForward(line.nextLine, fieldBegin, this);\n }\n else if (line.paragraph.nextRenderedWidget instanceof ParagraphWidget) {\n this.linkFieldTraversingForward(line.paragraph.nextRenderedWidget.childWidgets[0], fieldBegin, this);\n }\n return true;\n };\n /**\n * @private\n */\n ElementBox.prototype.linkFieldTraversingBackwardSeparator = function (line, fieldSeparator, previousNode) {\n var index = line.children.length - 1;\n if (line.children.indexOf(previousNode) > -1) {\n index = line.children.indexOf(previousNode) - 1;\n }\n for (var i = index; i >= 0; i--) {\n var childElement = line.children[i];\n if (childElement instanceof FieldElementBox) {\n if (childElement instanceof FieldElementBox && childElement.fieldType === 0) {\n if (isNullOrUndefined(childElement.fieldSeparator)) {\n fieldSeparator.fieldBegin = childElement;\n }\n return !isNullOrUndefined(fieldSeparator.fieldBegin);\n }\n }\n }\n if (line.previousLine) {\n this.linkFieldTraversingBackwardSeparator(line.previousLine, fieldSeparator, this);\n }\n else if (line.paragraph.nextRenderedWidget instanceof ParagraphWidget) {\n // tslint:disable-next-line:max-line-length\n line = line.paragraph.previousRenderedWidget.childWidgets[line.paragraph.previousRenderedWidget.childWidgets.length - 1];\n this.linkFieldTraversingBackwardSeparator(line, fieldSeparator, this);\n }\n else {\n return true;\n }\n return true;\n };\n Object.defineProperty(ElementBox.prototype, \"length\", {\n /**\n * @private\n */\n get: function () {\n return this.getLength();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ElementBox.prototype, \"indexInOwner\", {\n /**\n * @private\n */\n get: function () {\n return this.line instanceof LineWidget && this.line.children ? this.line.children.indexOf(this) : -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ElementBox.prototype, \"previousElement\", {\n /**\n * @private\n */\n get: function () {\n var index = this.indexInOwner;\n if (index > 0 && index < this.line.children.length) {\n return this.line.children[index - 1];\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ElementBox.prototype, \"nextElement\", {\n /**\n * @private\n */\n get: function () {\n var index = this.indexInOwner;\n if (index > -1 && index < this.line.children.length - 1) {\n return this.line.children[index + 1];\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ElementBox.prototype, \"nextNode\", {\n /**\n * @private\n */\n get: function () {\n var index = this.line.children.indexOf(this);\n var lineIndex = this.line.paragraph.childWidgets.indexOf(this.line);\n if (index < this.line.children.length - 1) {\n return this.line.children[index + 1];\n }\n else if (lineIndex < this.line.paragraph.childWidgets.length - 1) {\n return this.line.paragraph.childWidgets[lineIndex + 1].children[0];\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ElementBox.prototype, \"previousNode\", {\n /**\n * @private\n */\n get: function () {\n var index = this.line.children.indexOf(this);\n var lineIndex = this.line.paragraph.childWidgets.indexOf(this.line);\n if (index > 0) {\n return this.line.children[index - 1];\n }\n else if (lineIndex > 0) {\n var lineWidget = this.line.paragraph.childWidgets[lineIndex - 1];\n return lineWidget.children[lineWidget.children.length - 1];\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ElementBox.prototype, \"paragraph\", {\n /**\n * @private\n */\n get: function () {\n if (this.line) {\n return this.line.paragraph;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n ElementBox.prototype.destroy = function () {\n if (!isNullOrUndefined(this.line) && this.line.children && this.line.children.indexOf(this) > -1) {\n var index = this.line.children.indexOf(this);\n this.line.children.splice(index, 1);\n }\n this.line = undefined;\n if (this.characterFormat) {\n this.characterFormat.destroy();\n }\n this.characterFormat = undefined;\n if (this.margin) {\n this.margin.destroy();\n }\n this.margin = undefined;\n this.x = undefined;\n this.y = undefined;\n this.width = undefined;\n this.height = undefined;\n };\n /**\n * @private\n */\n ElementBox.objectCharacter = String.fromCharCode(65532);\n return ElementBox;\n}());\nexport { ElementBox };\n/**\n * @private\n */\nvar FieldElementBox = /** @class */ (function (_super) {\n __extends(FieldElementBox, _super);\n function FieldElementBox(type) {\n var _this = _super.call(this) || this;\n /**\n * @private\n */\n _this.fieldType = 0;\n /**\n * @private\n */\n _this.hasFieldEnd = false;\n _this.fieldBeginInternal = undefined;\n _this.fieldSeparatorInternal = undefined;\n _this.fieldEndInternal = undefined;\n _this.fieldType = type;\n return _this;\n }\n Object.defineProperty(FieldElementBox.prototype, \"fieldBegin\", {\n get: function () {\n return this.fieldBeginInternal;\n },\n set: function (field) {\n this.fieldBeginInternal = field;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FieldElementBox.prototype, \"fieldSeparator\", {\n get: function () {\n return this.fieldSeparatorInternal;\n },\n set: function (field) {\n this.fieldSeparatorInternal = field;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FieldElementBox.prototype, \"fieldEnd\", {\n get: function () {\n return this.fieldEndInternal;\n },\n set: function (field) {\n this.fieldEndInternal = field;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n FieldElementBox.prototype.getLength = function () {\n return 1;\n };\n /**\n * @private\n */\n FieldElementBox.prototype.clone = function () {\n var field = new FieldElementBox(this.fieldType);\n field.characterFormat.copyFormat(this.characterFormat);\n if (this.margin) {\n field.margin = this.margin.clone();\n }\n field.width = this.width;\n field.height = this.height;\n return field;\n };\n /**\n * @private\n */\n FieldElementBox.prototype.destroy = function () {\n this.fieldType = undefined;\n this.hasFieldEnd = undefined;\n this.fieldBeginInternal = undefined;\n this.fieldEndInternal = undefined;\n this.fieldSeparatorInternal = undefined;\n _super.prototype.destroy.call(this);\n };\n return FieldElementBox;\n}(ElementBox));\nexport { FieldElementBox };\n/**\n * @private\n */\nvar TextElementBox = /** @class */ (function (_super) {\n __extends(TextElementBox, _super);\n function TextElementBox() {\n var _this = _super.call(this) || this;\n /**\n * @private\n */\n _this.baselineOffset = 0;\n /**\n * @private\n */\n _this.text = '';\n return _this;\n }\n /**\n * @private\n */\n TextElementBox.prototype.getLength = function () {\n return this.text ? this.text.length : 0;\n };\n /**\n * @private\n */\n TextElementBox.prototype.clone = function () {\n var span = new TextElementBox();\n span.characterFormat.copyFormat(this.characterFormat);\n span.text = this.text;\n if (this.margin) {\n span.margin = this.margin.clone();\n }\n span.width = this.width;\n span.height = this.height;\n return span;\n };\n /**\n * @private\n */\n TextElementBox.prototype.destroy = function () {\n this.text = undefined;\n _super.prototype.destroy.call(this);\n };\n return TextElementBox;\n}(ElementBox));\nexport { TextElementBox };\n/**\n * @private\n */\nvar FieldTextElementBox = /** @class */ (function (_super) {\n __extends(FieldTextElementBox, _super);\n function FieldTextElementBox() {\n var _this = _super.call(this) || this;\n _this.fieldText = '';\n return _this;\n }\n Object.defineProperty(FieldTextElementBox.prototype, \"text\", {\n get: function () {\n return this.fieldText;\n },\n set: function (value) {\n this.fieldText = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n FieldTextElementBox.prototype.clone = function () {\n var span = new FieldTextElementBox();\n span.characterFormat.copyFormat(this.characterFormat);\n span.fieldBegin = this.fieldBegin;\n span.text = this.text;\n if (this.margin) {\n span.margin = this.margin.clone();\n }\n span.width = this.width;\n span.height = this.height;\n return span;\n };\n return FieldTextElementBox;\n}(TextElementBox));\nexport { FieldTextElementBox };\n/**\n * @private\n */\nvar TabElementBox = /** @class */ (function (_super) {\n __extends(TabElementBox, _super);\n function TabElementBox() {\n var _this = _super.call(this) || this;\n /**\n * @private\n */\n _this.tabText = '';\n /**\n * @private\n */\n _this.tabLeader = 'None';\n return _this;\n }\n /**\n * @private\n */\n TabElementBox.prototype.destroy = function () {\n this.tabText = undefined;\n this.tabLeader = undefined;\n };\n /**\n * @private\n */\n TabElementBox.prototype.clone = function () {\n var span = new TabElementBox();\n span.characterFormat.copyFormat(this.characterFormat);\n span.tabText = this.tabText;\n span.tabLeader = this.tabLeader;\n span.text = this.text;\n if (this.margin) {\n span.margin = this.margin.clone();\n }\n span.width = this.width;\n span.height = this.height;\n return span;\n };\n return TabElementBox;\n}(TextElementBox));\nexport { TabElementBox };\n/**\n * @private\n */\nvar BookmarkElementBox = /** @class */ (function (_super) {\n __extends(BookmarkElementBox, _super);\n function BookmarkElementBox(type) {\n var _this = _super.call(this) || this;\n _this.bookmarkTypeIn = 0;\n _this.refereneceIn = undefined;\n _this.nameIn = '';\n _this.bookmarkTypeIn = type;\n return _this;\n }\n Object.defineProperty(BookmarkElementBox.prototype, \"bookmarkType\", {\n /**\n * @private\n */\n get: function () {\n return this.bookmarkTypeIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BookmarkElementBox.prototype, \"name\", {\n /**\n * @private\n */\n get: function () {\n return this.nameIn;\n },\n /**\n * @private\n */\n set: function (name) {\n this.nameIn = name;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BookmarkElementBox.prototype, \"reference\", {\n /**\n * @private\n */\n get: function () {\n return this.refereneceIn;\n },\n /**\n * @private\n */\n set: function (reference) {\n this.refereneceIn = reference;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n BookmarkElementBox.prototype.getLength = function () {\n return 1;\n };\n /**\n * @private\n */\n BookmarkElementBox.prototype.destroy = function () {\n this.name = undefined;\n this.reference = undefined;\n this.bookmarkTypeIn = undefined;\n };\n /**\n * Clones the bookmark element box.\n * @param element - book mark element\n */\n /**\n * @private\n */\n BookmarkElementBox.prototype.clone = function () {\n var span = new BookmarkElementBox(this.bookmarkType);\n span.name = this.name;\n span.reference = this.reference;\n if (this.margin) {\n span.margin = this.margin.clone();\n }\n span.width = this.width;\n span.height = this.height;\n return span;\n };\n return BookmarkElementBox;\n}(ElementBox));\nexport { BookmarkElementBox };\n/**\n * @private\n */\nvar ImageElementBox = /** @class */ (function (_super) {\n __extends(ImageElementBox, _super);\n function ImageElementBox(isInlineImage) {\n var _this = _super.call(this) || this;\n _this.imageStr = '';\n _this.imgElement = undefined;\n _this.isInlineImageIn = true;\n /**\n * @private\n */\n _this.isMetaFile = false;\n _this.isInlineImageIn = isInlineImage;\n return _this;\n }\n Object.defineProperty(ImageElementBox.prototype, \"isInlineImage\", {\n /**\n * @private\n */\n get: function () {\n return this.isInlineImageIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageElementBox.prototype, \"element\", {\n /**\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.imgElement)) {\n this.imgElement = document.createElement('img');\n }\n return this.imgElement;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageElementBox.prototype, \"length\", {\n /**\n * @private\n */\n get: function () {\n return 1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageElementBox.prototype, \"imageString\", {\n /**\n * @private\n */\n get: function () {\n return this.imageStr;\n },\n /**\n * @private\n */\n set: function (value) {\n this.imageStr = value;\n if (!isNullOrUndefined(value)) {\n this.element.src = this.imageStr;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n ImageElementBox.prototype.getLength = function () {\n return 1;\n };\n /**\n * @private\n */\n ImageElementBox.prototype.clone = function () {\n var image = new ImageElementBox(this.isInlineImage);\n image.characterFormat.copyFormat(this.characterFormat);\n image.imageString = this.imageString;\n image.isMetaFile = this.isMetaFile;\n image.width = this.width;\n image.height = this.height;\n if (this.margin) {\n image.margin = this.margin.clone();\n }\n return image;\n };\n /**\n * @private\n */\n ImageElementBox.prototype.destroy = function () {\n this.imgElement = undefined;\n this.imageString = undefined;\n this.isInlineImageIn = undefined;\n _super.prototype.destroy.call(this);\n };\n return ImageElementBox;\n}(ElementBox));\nexport { ImageElementBox };\n/**\n * @private\n */\nvar ListTextElementBox = /** @class */ (function (_super) {\n __extends(ListTextElementBox, _super);\n function ListTextElementBox(listLevel, isListFollowCharacter) {\n var _this = _super.call(this) || this;\n /**\n * @private\n */\n _this.baselineOffset = 0;\n /**\n * @private\n */\n _this.isFollowCharacter = false;\n _this.listLevel = listLevel;\n _this.isFollowCharacter = isListFollowCharacter;\n return _this;\n }\n /**\n * @private\n */\n ListTextElementBox.prototype.getLength = function () {\n return this.text ? this.text.length : 0;\n };\n /**\n * @private\n */\n ListTextElementBox.prototype.clone = function () {\n var list = new ListTextElementBox(this.listLevel, this.isFollowCharacter);\n list.text = this.text;\n list.baselineOffset = this.baselineOffset;\n if (this.margin) {\n list.margin = this.margin.clone();\n }\n list.width = this.width;\n list.height = this.height;\n return list;\n };\n /**\n * @private\n */\n ListTextElementBox.prototype.destroy = function () {\n this.text = undefined;\n _super.prototype.destroy.call(this);\n };\n return ListTextElementBox;\n}(ElementBox));\nexport { ListTextElementBox };\n/**\n * @private\n */\nvar Page = /** @class */ (function () {\n /**\n * Initialize the constructor of Page\n */\n function Page() {\n /**\n * Specifies the Bonding Rectangle\n * @private\n */\n this.boundingRectangle = new Rect(96, 96, 816, 1056);\n /**\n * @private\n */\n this.repeatHeaderRowTableWidget = false;\n /**\n * Specifies the bodyWidgets\n * @default []\n * @private\n */\n this.bodyWidgets = [];\n /**\n * @private\n */\n this.headerWidget = undefined;\n /**\n * @private\n */\n this.footerWidget = undefined;\n // let text: string = 'DocumentEditor';\n }\n Object.defineProperty(Page.prototype, \"index\", {\n /**\n * @private\n */\n get: function () {\n if (this.viewer) {\n return this.viewer.pages.indexOf(this);\n }\n return -1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Page.prototype, \"previousPage\", {\n /**\n * @private\n */\n get: function () {\n var index = this.index;\n if (index > 0) {\n return this.viewer.pages[index - 1];\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Page.prototype, \"nextPage\", {\n /**\n * @private\n */\n get: function () {\n var index = this.index;\n if (index < this.viewer.pages.length - 1) {\n return this.viewer.pages[index + 1];\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Page.prototype, \"sectionIndex\", {\n /**\n * @private\n */\n get: function () {\n if (this.bodyWidgets.length > 0) {\n return this.bodyWidgets[0].index;\n }\n return -1;\n },\n enumerable: true,\n configurable: true\n });\n Page.prototype.destroy = function () {\n if (this.headerWidget) {\n if (this.viewer && this.viewer.owner.editor) {\n this.viewer.owner.editor.removeFieldInWidget(this.headerWidget);\n }\n this.headerWidget.destroy();\n }\n this.headerWidget = undefined;\n if (this.footerWidget) {\n if (this.viewer && this.viewer.owner.editor) {\n this.viewer.owner.editor.removeFieldInWidget(this.footerWidget);\n }\n this.footerWidget.destroy();\n }\n this.footerWidget = undefined;\n this.bodyWidgets = [];\n this.bodyWidgets = undefined;\n if (!isNullOrUndefined(this.viewer)) {\n if (!isNullOrUndefined(this.viewer.pages)) {\n this.viewer.removePage(this);\n }\n }\n this.viewer = undefined;\n };\n return Page;\n}());\nexport { Page };\n/**\n * @private\n */\nvar WTableHolder = /** @class */ (function () {\n function WTableHolder() {\n this.tableColumns = [];\n /**\n * @private\n */\n this.tableWidth = 0;\n }\n Object.defineProperty(WTableHolder.prototype, \"columns\", {\n get: function () {\n return this.tableColumns;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n WTableHolder.prototype.resetColumns = function () {\n for (var i = 0; i < this.tableColumns.length; i++) {\n this.tableColumns[i].destroy();\n }\n this.tableColumns = [];\n };\n /**\n * @private\n */\n WTableHolder.prototype.getPreviousSpannedCellWidth = function (previousColumnIndex, curColumnIndex) {\n var width = 0;\n for (var i = previousColumnIndex; i < curColumnIndex; i++) {\n width += this.tableColumns[i].preferredWidth;\n }\n return width;\n };\n /**\n * @private\n */\n WTableHolder.prototype.addColumns = function (currentColumnIndex, columnSpan, width, minWidth, offset) {\n for (var i = this.columns.length; i < columnSpan; i++) {\n this.columns.push(new WColumn());\n }\n var availableWidth = 0;\n for (var j = currentColumnIndex; j < columnSpan; j++) {\n availableWidth += this.columns[j].preferredWidth;\n }\n // If width to add is greater than preferred width, then preferred width will be increased.\n // In case of Gridspan > 1, only last grid column width will be updated.\n var gridSpan = columnSpan - currentColumnIndex;\n if (!(gridSpan > 1) && availableWidth < width) {\n this.columns[columnSpan - 1].preferredWidth += (width - availableWidth);\n }\n if (minWidth > this.columns[columnSpan - 1].minWidth) {\n this.columns[columnSpan - 1].minWidth = minWidth;\n }\n if (offset > this.columns[columnSpan - 1].endOffset) {\n this.columns[columnSpan - 1].endOffset = offset;\n }\n };\n /**\n * @private\n */\n WTableHolder.prototype.getTotalWidth = function () {\n var width = 0;\n for (var i = 0; i < this.columns.length; i++) {\n var column = this.columns[i];\n width += column.preferredWidth;\n }\n return width;\n };\n /**\n * @private\n */\n WTableHolder.prototype.isFitColumns = function (containerWidth, preferredTableWidth, isAutoWidth) {\n // Gets total preferred width.\n var totalColumnWidth = this.getTotalWidth();\n // If auto table width, based on total column widths, minimum value will be updated.\n if (isAutoWidth) {\n this.tableWidth = preferredTableWidth > totalColumnWidth ? totalColumnWidth : preferredTableWidth;\n }\n else {\n this.tableWidth = preferredTableWidth;\n }\n // If total columns width doesn't match table width, then all grid column widths will be updated by even factor.\n // If totalColumnWidth < TableWidth, all grid columns are enlarged. Otherwise shrinked.\n if (totalColumnWidth !== this.tableWidth) {\n var factor = this.tableWidth / totalColumnWidth;\n factor = isNaN(factor) ? 1 : factor;\n for (var i = 0; i < this.columns.length; i++) {\n var column = this.columns[i];\n //column.PreferredWidth = factor * column.PreferredWidth;\n if (factor * column.preferredWidth < column.minWidth) {\n return false;\n }\n }\n return true;\n }\n else {\n return true;\n }\n };\n /**\n * @private\n */\n WTableHolder.prototype.fitColumns = function (containerWidth, preferredTableWidth, isAutoWidth) {\n // Gets total preferred width.\n var totalColumnWidth = this.getTotalWidth();\n // If auto table width, based on total column widths, minimum value will be updated.\n if (isAutoWidth) {\n this.tableWidth = preferredTableWidth > totalColumnWidth ? totalColumnWidth : preferredTableWidth;\n }\n else {\n this.tableWidth = preferredTableWidth;\n }\n // If total columns width doesn't match table width, then all grid column widths will be updated by even factor.\n // If totalColumnWidth < TableWidth, all grid columns are enlarged. Otherwise shrinked.\n if (totalColumnWidth !== this.tableWidth) {\n var factor = this.tableWidth / totalColumnWidth;\n for (var i = 0; i < this.columns.length; i++) {\n var column = this.columns[i];\n column.preferredWidth = factor * column.preferredWidth;\n }\n }\n };\n /**\n * @private\n */\n WTableHolder.prototype.getCellWidth = function (columnIndex, columnSpan, preferredTableWidth, isAutoWidth) {\n var width = 0;\n if (isAutoWidth) {\n var cellWidth = preferredTableWidth / this.tableColumns.length;\n for (var i = 0; i < columnSpan; i++) {\n width += cellWidth;\n }\n }\n else {\n for (var i = 0; i < columnSpan; i++) {\n width += this.tableColumns[i + columnIndex].preferredWidth;\n }\n }\n return width;\n };\n /**\n * @private\n */\n WTableHolder.prototype.validateColumnWidths = function () {\n for (var i = 0; i < this.columns.length; i++) {\n if (i === 0) {\n if (this.columns[i].preferredWidth !== this.columns[i].endOffset) {\n this.columns[i].preferredWidth = this.columns[i].endOffset;\n }\n }\n else {\n // If Previous column offset + current column preferred width is less than current column offset, \n // Then current column preferred width is set to current column offset - previous column offset.\n if (this.columns[i - 1].endOffset + this.columns[i].preferredWidth < this.columns[i].endOffset) {\n this.columns[i].preferredWidth = this.columns[i].endOffset - this.columns[i - 1].endOffset;\n }\n }\n }\n };\n /**\n * @private\n */\n WTableHolder.prototype.clone = function () {\n var tableHolder = new WTableHolder();\n tableHolder.tableWidth = this.tableWidth;\n for (var i = 0; i < this.columns.length; i++) {\n tableHolder.columns.push(this.columns[i].clone());\n }\n return tableHolder;\n };\n /**\n * @private\n */\n WTableHolder.prototype.destroy = function () {\n if (!isNullOrUndefined(this.tableColumns)) {\n for (var i = 0; i < this.tableColumns.length; i++) {\n var column = this.tableColumns[i];\n column.destroy();\n }\n }\n this.tableColumns = [];\n this.tableColumns = undefined;\n this.tableWidth = undefined;\n };\n return WTableHolder;\n}());\nexport { WTableHolder };\n/**\n * @private\n */\nvar WColumn = /** @class */ (function () {\n function WColumn() {\n /**\n * @private\n */\n this.preferredWidth = 0;\n /**\n * @private\n */\n this.minWidth = 0;\n /**\n * @private\n */\n this.maxWidth = 0;\n /**\n * @private\n */\n this.endOffset = 0;\n }\n /**\n * @private\n */\n WColumn.prototype.clone = function () {\n var column = new WColumn();\n column.preferredWidth = this.preferredWidth;\n column.minWidth = this.minWidth;\n column.maxWidth = this.maxWidth;\n return column;\n };\n /**\n * @private\n */\n WColumn.prototype.destroy = function () {\n this.preferredWidth = undefined;\n this.minWidth = undefined;\n this.maxWidth = undefined;\n };\n return WColumn;\n}());\nexport { WColumn };\n","import { ContextMenu as Menu } from '@syncfusion/ej2-navigations';\nimport { isNullOrUndefined, L10n, setCulture, classList } from '@syncfusion/ej2-base';\nimport { FieldElementBox } from './viewer/page';\nvar CONTEXTMENU_COPY = '_contextmenu_copy';\nvar CONTEXTMENU_CUT = '_contextmenu_cut';\nvar CONTEXTMENU_PASTE = '_contextmenu_paste';\nvar CONTEXTMENU_UPDATE_FIELD = '_contextmenu_update_field';\nvar CONTEXTMENU_EDIT_FIELD = '_contextmenu_edit_field';\nvar CONTEXTMENU_HYPERLINK = '_contextmenu_hyperlink';\nvar CONTEXTMENU_OPEN_HYPERLINK = '_contextmenu_open_hyperlink';\nvar CONTEXTMENU_COPY_HYPERLINK = '_contextmenu_copy_hyperlink';\nvar CONTEXTMENU_REMOVE_HYPERLINK = '_contextmenu_remove_hyperlink';\nvar CONTEXTMENU_EDIT_HYPERLINK = '_contextmenu_edit_hyperlink';\nvar CONTEXTMENU_FONT_DIALOG = '_contextmenu_font_dialog';\nvar CONTEXTMENU_PARAGRAPH = '_contextmenu_paragraph_dialog';\nvar CONTEXTMENU_TABLE = '_contextmenu_table_dialog';\nvar CONTEXTMENU_INSERT_TABLE = '_contextmenu_insert_table';\nvar CONTEXTMENU_DELETE_TABLE = '_contextmenu_delete_table';\nvar CONTEXTMENU_INSERT_ABOVE = '_contextmenu_insert_above';\nvar CONTEXTMENU_INSERT_BELOW = '_contextmenu_insert_below';\nvar CONTEXTMENU_INSERT_RIGHT = '_contextmenu_insert_right';\nvar CONTEXTMENU_INSERT_LEFT = '_contextmenu_insert_left';\nvar CONTEXTMENU_COMPLETE_DELETE_TABLE = '_contextmenu_complete_table_delete';\nvar CONTEXTMENU_DELETE_ROW = '_contextmenu_delete_row';\nvar CONTEXTMENU_DELETE_COLUMN = '_contextmenu_delete_column';\nvar CONTEXTMENU_MERGE_CELL = '_contextmenu_merge_cell';\nvar CONTEXTMENU_CONTINUE_NUMBERING = '_contextmenu_continue_numbering';\nvar CONTEXTMENU_RESTART_AT = '_contextmenu_restart_at';\n/**\n * Context Menu class\n */\nvar ContextMenu = /** @class */ (function () {\n /**\n * @private\n */\n function ContextMenu(viewer) {\n var _this = this;\n /**\n * @private\n */\n this.contextMenuInstance = undefined;\n /**\n * Handles on context menu key pressed.\n * @param {PointerEvent} event\n * @private\n */\n this.onContextMenuInternal = function (event) {\n if (_this.showHideElements(_this.viewer.selection)) {\n _this.contextMenuInstance.open(event.y, event.x);\n event.preventDefault();\n }\n };\n this.viewer = viewer;\n var locale = new L10n('documenteditor', this.viewer.owner.defaultLocale);\n locale.setLocale(this.viewer.owner.locale);\n setCulture(this.viewer.owner.locale);\n this.initContextMenu(locale);\n }\n /**\n * Gets module name.\n */\n ContextMenu.prototype.getModuleName = function () {\n return 'ContextMenu';\n };\n /**\n * Initialize context menu.\n * @param localValue Localize value.\n * @private\n */\n // tslint:disable:max-func-body-length\n ContextMenu.prototype.initContextMenu = function (localValue) {\n var _this = this;\n var id = this.viewer.owner.element.id;\n this.contextMenu = document.createElement('div');\n this.contextMenu.id = this.viewer.owner.containerId + 'e-de-contextmenu';\n document.body.appendChild(this.contextMenu);\n var ul = document.createElement('ul');\n ul.style.width = 'auto';\n ul.id = this.viewer.owner.containerId + 'e-de-contextmenu-list';\n ul.style.listStyle = 'none';\n ul.style.margin = '0px';\n ul.style.padding = '0px';\n ul.style.maxHeight = 'auto';\n ul.oncontextmenu = this.disableBrowserContextmenu;\n this.contextMenu.appendChild(ul);\n var menuItems = [\n {\n text: localValue.getConstant('Cut'),\n iconCss: 'e-icons e-de-cut',\n id: id + CONTEXTMENU_CUT\n },\n {\n text: localValue.getConstant('Copy'),\n iconCss: 'e-icons e-de-copy',\n id: id + CONTEXTMENU_COPY\n },\n {\n text: localValue.getConstant('Paste'),\n iconCss: 'e-icons e-de-paste',\n id: id + CONTEXTMENU_PASTE\n },\n {\n separator: true\n },\n {\n text: localValue.getConstant('Update Field'),\n iconCss: 'e-icons e-de-update_field',\n id: id + CONTEXTMENU_UPDATE_FIELD\n },\n {\n text: localValue.getConstant('Edit Field'),\n iconCss: 'e-icons e-de-edit_field',\n id: id + CONTEXTMENU_EDIT_FIELD\n },\n {\n text: localValue.getConstant('Continue Numbering'),\n iconCss: 'e-icons e-de-continue-numbering',\n id: id + CONTEXTMENU_CONTINUE_NUMBERING\n },\n {\n text: localValue.getConstant('Restart At') + ' 1',\n iconCss: 'e-icons e-de-restart-at',\n id: id + CONTEXTMENU_RESTART_AT\n },\n {\n separator: true\n },\n {\n text: localValue.getConstant('Hyperlink'),\n iconCss: 'e-icons e-de-insertlink',\n id: id + CONTEXTMENU_HYPERLINK\n },\n {\n text: localValue.getConstant('Edit Hyperlink') + '...',\n iconCss: 'e-icons e-de-edit-hyperlink',\n id: id + CONTEXTMENU_EDIT_HYPERLINK\n },\n {\n text: localValue.getConstant('Open Hyperlink'),\n iconCss: 'e-icons e-de-open-hyperlink',\n id: id + CONTEXTMENU_OPEN_HYPERLINK\n },\n {\n text: localValue.getConstant('Copy Hyperlink'),\n iconCss: 'e-icons e-de-copy-hyperlink',\n id: id + CONTEXTMENU_COPY_HYPERLINK\n },\n {\n text: localValue.getConstant('Remove Hyperlink'),\n iconCss: 'e-icons e-de-remove-hyperlink',\n id: id + CONTEXTMENU_REMOVE_HYPERLINK\n },\n {\n separator: true\n },\n {\n text: localValue.getConstant('Font'),\n iconCss: 'e-icons e-de-fonts',\n id: id + CONTEXTMENU_FONT_DIALOG\n },\n {\n text: localValue.getConstant('Paragraph'),\n iconCss: 'e-icons e-de-paragraph',\n id: id + CONTEXTMENU_PARAGRAPH\n },\n {\n separator: true,\n },\n {\n text: localValue.getConstant('Table Properties'),\n id: id + CONTEXTMENU_TABLE,\n iconCss: 'e-icons e-de-table'\n },\n {\n text: localValue.getConstant('Merge Cells'),\n id: id + CONTEXTMENU_MERGE_CELL,\n iconCss: 'e-icons e-de-icon-table-merge-cells'\n },\n {\n text: localValue.getConstant('Insert'),\n id: id + CONTEXTMENU_INSERT_TABLE,\n iconCss: 'e-icons',\n items: [\n {\n text: localValue.getConstant('Insert Above'),\n id: id + CONTEXTMENU_INSERT_ABOVE,\n iconCss: 'e-icons e-de-insertabove'\n },\n {\n text: localValue.getConstant('Insert Below'),\n id: id + CONTEXTMENU_INSERT_BELOW,\n iconCss: 'e-icons e-de-insertbelow'\n },\n {\n text: localValue.getConstant('Insert Left'),\n id: id + CONTEXTMENU_INSERT_LEFT,\n iconCss: 'e-icons e-de-insertleft'\n },\n {\n text: localValue.getConstant('Insert Right'),\n id: id + CONTEXTMENU_INSERT_RIGHT,\n iconCss: 'e-icons e-de-insertright'\n }\n ]\n },\n {\n text: localValue.getConstant('Delete'),\n id: id + CONTEXTMENU_DELETE_TABLE,\n iconCss: 'e-icons',\n items: [\n {\n text: localValue.getConstant('Delete Table'),\n id: id + CONTEXTMENU_COMPLETE_DELETE_TABLE,\n iconCss: 'e-icons e-de-delete-table'\n },\n {\n text: localValue.getConstant('Delete Row'),\n id: id + CONTEXTMENU_DELETE_ROW,\n iconCss: 'e-icons e-de-deleterow'\n },\n {\n text: localValue.getConstant('Delete Column'),\n id: id + CONTEXTMENU_DELETE_COLUMN,\n iconCss: 'e-icons e-de-deletecolumn'\n }\n ]\n },\n ];\n var menuOptions = {\n target: '#' + this.viewer.owner.containerId + 'e-de-contextmenu',\n items: menuItems,\n select: function (args) {\n var item = args.element.id;\n _this.handleContextMenuItem(item);\n },\n };\n this.contextMenuInstance = new Menu(menuOptions, '#' + this.viewer.owner.containerId + 'e-de-contextmenu-list');\n this.contextMenuInstance.beforeOpen = function () {\n if (_this.viewer && _this.viewer.selection) {\n classList(_this.viewer.selection.caret, [], ['e-de-cursor-animation']);\n _this.viewer.selection.showCaret();\n }\n };\n this.contextMenuInstance.onClose = function () {\n if (_this.viewer && _this.viewer.selection) {\n classList(_this.viewer.selection.caret, ['e-de-cursor-animation'], []);\n _this.viewer.updateFocus();\n }\n };\n };\n /**\n * Disable browser context menu.\n */\n ContextMenu.prototype.disableBrowserContextmenu = function () {\n return false;\n };\n /**\n * Handles context menu items.\n * @param {string} item Specifies which item is selected.\n * @private\n */\n ContextMenu.prototype.handleContextMenuItem = function (item) {\n var id = this.viewer.owner.element.id;\n switch (item) {\n case id + CONTEXTMENU_COPY:\n this.viewer.selection.copy();\n break;\n case id + CONTEXTMENU_CUT:\n this.viewer.owner.editor.cut();\n break;\n case id + CONTEXTMENU_PASTE:\n if (!this.viewer.owner.isReadOnlyMode) {\n this.viewer.owner.editorModule.pasteInternal(undefined);\n }\n break;\n case id + CONTEXTMENU_UPDATE_FIELD:\n if (!this.viewer.owner.isReadOnlyMode) {\n this.viewer.owner.editorModule.updateToc();\n }\n break;\n case id + CONTEXTMENU_EDIT_FIELD:\n if (!this.viewer.owner.isReadOnlyMode) {\n this.viewer.owner.tableOfContentsDialogModule.show();\n }\n break;\n case id + CONTEXTMENU_FONT_DIALOG:\n if (this.viewer.owner.fontDialogModule) {\n this.viewer.owner.fontDialogModule.showFontDialog();\n }\n break;\n case id + CONTEXTMENU_OPEN_HYPERLINK:\n this.viewer.selection.navigateHyperlink();\n break;\n case id + CONTEXTMENU_COPY_HYPERLINK:\n this.viewer.selection.copyHyperlink();\n break;\n case id + CONTEXTMENU_EDIT_HYPERLINK:\n case id + CONTEXTMENU_HYPERLINK:\n if (this.viewer.owner.hyperlinkDialogModule) {\n this.viewer.owner.hyperlinkDialogModule.show();\n }\n break;\n case id + CONTEXTMENU_REMOVE_HYPERLINK:\n this.viewer.owner.editor.removeHyperlink();\n break;\n case id + CONTEXTMENU_PARAGRAPH:\n if (this.viewer.owner.paragraphDialogModule) {\n this.viewer.owner.paragraphDialogModule.show();\n }\n break;\n case id + CONTEXTMENU_TABLE:\n this.viewer.owner.tablePropertiesDialogModule.show();\n break;\n case id + CONTEXTMENU_MERGE_CELL:\n this.viewer.owner.editor.mergeCells();\n break;\n case id + CONTEXTMENU_INSERT_ABOVE:\n this.viewer.owner.editor.insertRow(true);\n break;\n case id + CONTEXTMENU_INSERT_BELOW:\n this.viewer.owner.editor.insertRow(false);\n break;\n case id + CONTEXTMENU_INSERT_LEFT:\n this.viewer.owner.editor.insertColumn(true);\n break;\n case id + CONTEXTMENU_INSERT_RIGHT:\n this.viewer.owner.editor.insertColumn(false);\n break;\n case id + CONTEXTMENU_COMPLETE_DELETE_TABLE:\n this.viewer.owner.editor.deleteTable();\n break;\n case id + CONTEXTMENU_DELETE_ROW:\n this.viewer.owner.editor.deleteRow();\n break;\n case id + CONTEXTMENU_DELETE_COLUMN:\n this.viewer.owner.editor.deleteColumn();\n break;\n case id + CONTEXTMENU_CONTINUE_NUMBERING:\n this.viewer.owner.editorModule.applyContinueNumbering(this.viewer.selection);\n break;\n case id + CONTEXTMENU_RESTART_AT:\n this.viewer.owner.editorModule.applyRestartNumbering(this.viewer.selection);\n break;\n }\n };\n ContextMenu.prototype.showHideElements = function (selection) {\n var owner = this.viewer.owner;\n var id = owner.element.id;\n var copy = document.getElementById(id + CONTEXTMENU_COPY);\n var cut = document.getElementById(id + CONTEXTMENU_CUT);\n var paste = document.getElementById(id + CONTEXTMENU_PASTE);\n var updateField = document.getElementById(id + CONTEXTMENU_UPDATE_FIELD);\n var editField = document.getElementById(id + CONTEXTMENU_EDIT_FIELD);\n var font = document.getElementById(id + CONTEXTMENU_FONT_DIALOG);\n var paragraph = document.getElementById(id + CONTEXTMENU_PARAGRAPH);\n var tableProperties = document.getElementById(id + CONTEXTMENU_TABLE);\n var insertTable = document.getElementById(id + CONTEXTMENU_INSERT_TABLE);\n var deleteTable = document.getElementById(id + CONTEXTMENU_DELETE_TABLE);\n var mergeCells = document.getElementById(id + CONTEXTMENU_MERGE_CELL);\n var hyperlink = document.getElementById(id + CONTEXTMENU_HYPERLINK);\n var openHyperlink = document.getElementById(id + CONTEXTMENU_OPEN_HYPERLINK);\n var editHyperlink = document.getElementById(id + CONTEXTMENU_EDIT_HYPERLINK);\n var copyHyperlink = document.getElementById(id + CONTEXTMENU_COPY_HYPERLINK);\n var removeHyperlink = document.getElementById(id + CONTEXTMENU_REMOVE_HYPERLINK);\n var continueNumbering = document.getElementById(id + CONTEXTMENU_CONTINUE_NUMBERING);\n var restartAt = document.getElementById(id + CONTEXTMENU_RESTART_AT);\n cut.style.display = 'none';\n paste.style.display = 'none';\n paste.nextSibling.style.display = 'none';\n hyperlink.style.display = 'none';\n openHyperlink.style.display = 'none';\n copyHyperlink.style.display = 'none';\n editHyperlink.style.display = 'none';\n removeHyperlink.style.display = 'none';\n removeHyperlink.nextSibling.style.display = 'none';\n mergeCells.style.display = 'none';\n font.style.display = 'none';\n paragraph.style.display = 'none';\n paragraph.nextSibling.style.display = 'none';\n insertTable.style.display = 'none';\n deleteTable.style.display = 'none';\n tableProperties.style.display = 'none';\n updateField.style.display = 'none';\n editField.style.display = 'none';\n continueNumbering.style.display = 'none';\n restartAt.style.display = 'none';\n restartAt.nextSibling.style.display = 'none';\n if (isNullOrUndefined(selection)) {\n return false;\n }\n selection.hideToolTip();\n if (selection.isEmpty) {\n cut.classList.add('e-disabled');\n copy.classList.add('e-disabled');\n }\n else {\n cut.classList.remove('e-disabled');\n copy.classList.remove('e-disabled');\n }\n if (owner.isReadOnlyMode) {\n return true;\n }\n cut.style.display = 'block';\n paste.style.display = 'block';\n paste.nextSibling.style.display = 'block';\n insertTable.classList.add('e-blankicon');\n deleteTable.classList.add('e-blankicon');\n updateField.classList.add('e-blankicon');\n editField.classList.add('e-blankicon');\n if (owner.enableLocalPaste && !isNullOrUndefined(owner.editor.copiedData)) {\n paste.classList.remove('e-disabled');\n }\n else {\n paste.classList.add('e-disabled');\n }\n if (selection.contextType === 'TableOfContents') {\n updateField.style.display = 'block';\n editField.style.display = 'block';\n restartAt.nextSibling.style.display = 'block';\n }\n else {\n var start = selection.start;\n var end = selection.end;\n if (selection.contextType === 'List'\n && owner.editorModule.getListLevel(start.paragraph).listLevelPattern !== 'Bullet') {\n continueNumbering.style.display = 'block';\n restartAt.style.display = 'block';\n restartAt.nextSibling.style.display = 'block';\n }\n var isCellOrRowSelected = start.paragraph.isInsideTable && (!end.paragraph.isInsideTable\n || start.paragraph.associatedCell !== end.paragraph.associatedCell\n || selection.isCellSelected(start.paragraph.associatedCell, start, end));\n if (isCellOrRowSelected) {\n hyperlink.classList.add('e-disabled');\n }\n else {\n if (hyperlink.classList.contains('e-disabled')) {\n hyperlink.classList.remove('e-disabled');\n }\n }\n var field = selection.getHyperlinkField();\n if (field instanceof FieldElementBox && !selection.isImageField()) {\n openHyperlink.style.display = 'block';\n copyHyperlink.style.display = 'block';\n if (owner.hyperlinkDialogModule) {\n editHyperlink.style.display = 'block';\n }\n removeHyperlink.style.display = 'block';\n removeHyperlink.nextSibling.style.display = 'block';\n }\n else {\n if (owner.hyperlinkDialogModule) {\n hyperlink.style.display = 'block';\n }\n }\n }\n if (this.viewer.owner.selection.start.paragraph.isInsideTable\n && this.viewer.owner.selection.end.paragraph.isInsideTable) {\n paragraph.nextSibling.style.display = 'block';\n if (owner.tablePropertiesDialogModule) {\n tableProperties.style.display = 'block';\n }\n insertTable.style.display = 'block';\n deleteTable.style.display = 'block';\n if (this.viewer.owner.editor.canMergeCells()) {\n mergeCells.style.display = 'block';\n }\n }\n else {\n if (this.viewer.owner.fontDialogModule) {\n font.style.display = 'block';\n font.previousSibling.style.display = 'block';\n }\n if (this.viewer.owner.paragraphDialogModule) {\n paragraph.style.display = 'block';\n }\n }\n if (selection.contextType === 'Image') {\n font.style.display = 'none';\n paragraph.style.display = 'none';\n removeHyperlink.nextSibling.style.display = 'none';\n }\n return true;\n };\n /**\n * Disposes the internal objects which are maintained.\n * @private\n */\n ContextMenu.prototype.destroy = function () {\n if (this.contextMenuInstance) {\n this.contextMenuInstance.destroy();\n }\n if (this.contextMenu) {\n if (this.contextMenu.parentElement) {\n this.contextMenu.parentElement.removeChild(this.contextMenu);\n }\n this.contextMenu.innerHTML = '';\n }\n this.contextMenu = undefined;\n this.contextMenuInstance = undefined;\n };\n return ContextMenu;\n}());\nexport { ContextMenu };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WAbstractList = /** @class */ (function () {\n function WAbstractList() {\n this.abstractListIdIn = -1;\n this.levels = [];\n }\n Object.defineProperty(WAbstractList.prototype, \"abstractListId\", {\n get: function () {\n return this.abstractListIdIn;\n },\n set: function (abstractListId) {\n this.abstractListIdIn = abstractListId;\n },\n enumerable: true,\n configurable: true\n });\n WAbstractList.prototype.destroy = function () {\n if (!isNullOrUndefined(this.levels)) {\n for (var i = 0; i < this.levels.length; i++) {\n var listLevel = this.levels[i];\n listLevel.destroy();\n this.levels.splice(this.levels.indexOf(listLevel), 1);\n i--;\n }\n this.levels = [];\n }\n this.levels = undefined;\n };\n return WAbstractList;\n}());\nexport { WAbstractList };\n","import { Dictionary } from '../../base/dictionary';\nimport { WUniqueFormat } from '../../base/unique-format';\nimport { WUniqueFormats } from '../../base/unique-formats';\nimport { WCharacterFormat } from '../format/character-format';\nimport { WParagraphFormat } from '../format/paragraph-format';\nimport { WAbstractList } from './abstract-list';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar WListLevel = /** @class */ (function () {\n function WListLevel(node) {\n this.uniqueListLevel = undefined;\n this.paragraphFormat = undefined;\n this.characterFormat = undefined;\n if (node instanceof WAbstractList) {\n this.ownerBase = node;\n }\n else {\n this.ownerBase = node;\n }\n this.characterFormat = new WCharacterFormat(undefined);\n this.paragraphFormat = new WParagraphFormat(undefined);\n }\n Object.defineProperty(WListLevel.prototype, \"listLevelPattern\", {\n get: function () {\n return this.getPropertyValue('listLevelPattern');\n },\n set: function (listLevelPattern) {\n this.setPropertyValue('listLevelPattern', listLevelPattern);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WListLevel.prototype, \"followCharacter\", {\n get: function () {\n return this.getPropertyValue('followCharacter');\n },\n set: function (followCharacter) {\n this.setPropertyValue('followCharacter', followCharacter);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WListLevel.prototype, \"startAt\", {\n get: function () {\n return this.getPropertyValue('startAt');\n },\n set: function (startAt) {\n this.setPropertyValue('startAt', startAt);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WListLevel.prototype, \"numberFormat\", {\n get: function () {\n return this.getPropertyValue('numberFormat');\n },\n set: function (numberFormat) {\n this.setPropertyValue('numberFormat', numberFormat);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WListLevel.prototype, \"restartLevel\", {\n get: function () {\n return this.getPropertyValue('restartLevel');\n },\n set: function (restartLevel) {\n this.setPropertyValue('restartLevel', restartLevel);\n },\n enumerable: true,\n configurable: true\n });\n WListLevel.prototype.getPropertyValue = function (property) {\n var propertyType = WUniqueFormat.getPropertyType(WListLevel.uniqueFormatType, property);\n if (!isNullOrUndefined(this.uniqueListLevel) && this.uniqueListLevel.propertiesHash.containsKey(propertyType)) {\n return this.uniqueListLevel.propertiesHash.get(propertyType);\n }\n return WListLevel.getPropertyDefaultValue(property);\n };\n WListLevel.prototype.setPropertyValue = function (property, value) {\n if (isNullOrUndefined(value) || value === '') {\n value = WListLevel.getPropertyDefaultValue(property);\n }\n if (isNullOrUndefined(this.uniqueListLevel)) {\n this.initializeUniqueWListLevel(property, value);\n }\n else {\n var propertyType = WUniqueFormat.getPropertyType(this.uniqueListLevel.uniqueFormatType, property);\n if (this.uniqueListLevel.propertiesHash.containsKey(propertyType) &&\n // tslint:disable-next-line:max-line-length\n this.uniqueListLevel.propertiesHash.get(propertyType) === value) {\n return;\n }\n // tslint:disable-next-line:max-line-length\n this.uniqueListLevel = WListLevel.uniqueListLevels.updateUniqueFormat(this.uniqueListLevel, property, value);\n }\n };\n WListLevel.prototype.initializeUniqueWListLevel = function (property, propValue) {\n var uniqueListLevelTemp = new Dictionary();\n this.addUniqueWListLevel('listLevelPattern', property, propValue, uniqueListLevelTemp);\n this.addUniqueWListLevel('startAt', property, propValue, uniqueListLevelTemp);\n this.addUniqueWListLevel('followCharacter', property, propValue, uniqueListLevelTemp);\n this.addUniqueWListLevel('numberFormat', property, propValue, uniqueListLevelTemp);\n this.addUniqueWListLevel('restartLevel', property, propValue, uniqueListLevelTemp);\n // tslint:disable-next-line:max-line-length \n this.uniqueListLevel = WListLevel.uniqueListLevels.addUniqueFormat(uniqueListLevelTemp, WListLevel.uniqueFormatType);\n };\n // tslint:disable-next-line:max-line-length\n WListLevel.prototype.addUniqueWListLevel = function (property, modifiedProperty, propValue, uniqueCharFormatTemp) {\n var propertyType;\n propertyType = WUniqueFormat.getPropertyType(WListLevel.uniqueFormatType, property);\n if (property === modifiedProperty) {\n uniqueCharFormatTemp.add(propertyType, propValue);\n }\n else {\n uniqueCharFormatTemp.add(propertyType, WListLevel.getPropertyDefaultValue(property));\n }\n };\n WListLevel.getPropertyDefaultValue = function (property) {\n var value = undefined;\n switch (property) {\n case 'listLevelPattern':\n value = 'Arabic';\n break;\n case 'startAt':\n value = 0;\n break;\n case 'followCharacter':\n value = 'Tab';\n break;\n case 'numberFormat':\n value = '';\n break;\n case 'restartLevel':\n value = 0;\n break;\n }\n return value;\n };\n WListLevel.prototype.destroy = function () {\n if (!isNullOrUndefined(this.characterFormat)) {\n this.characterFormat.destroy();\n }\n if (!isNullOrUndefined(this.paragraphFormat)) {\n this.paragraphFormat.destroy();\n }\n if (!isNullOrUndefined(this.uniqueListLevel)) {\n WListLevel.uniqueListLevels.remove(this.uniqueListLevel);\n }\n this.uniqueListLevel = undefined;\n this.characterFormat = undefined;\n this.paragraphFormat = undefined;\n };\n WListLevel.clear = function () {\n this.uniqueListLevels.clear();\n };\n WListLevel.dotBullet = '\\uf0b7';\n WListLevel.squareBullet = '\\uf0a7'; //Symbol font \\u25aa.\n WListLevel.arrowBullet = '\\u27a4';\n WListLevel.circleBullet = '\\uf06f' + '\\u0020';\n WListLevel.uniqueListLevels = new WUniqueFormats();\n WListLevel.uniqueFormatType = 9;\n return WListLevel;\n}());\nexport { WListLevel };\n","import { Dictionary } from '../../base/dictionary';\nimport { WListLevel } from '../list/list-level';\nimport { WCharacterFormat, WParagraphFormat } from '../format/index';\nimport { WBorder } from '../format/index';\nimport { PageLayoutViewer } from './viewer';\nimport { LineWidget, Rect, Widget, Margin, ParagraphWidget, BodyWidget, TextElementBox, ElementBox, ListTextElementBox, TableCellWidget, TableRowWidget, TableWidget, FieldElementBox, BlockWidget, HeaderFooterWidget, BlockContainer, BookmarkElementBox, FieldTextElementBox, TabElementBox } from './page';\nimport { HelperMethods } from '../editor/editor-helper';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar Layout = /** @class */ (function () {\n /**\n * viewer definition\n */\n function Layout(viewer) {\n /**\n * @private\n */\n this.allowLayout = true;\n /**\n * @private\n */\n this.isInitialLoad = true;\n this.fieldBegin = undefined;\n this.maxTextHeight = 0;\n this.maxBaseline = 0;\n this.maxTextBaseline = 0;\n this.isFieldCode = false;\n this.viewer = viewer;\n }\n /**\n * @private\n */\n Layout.prototype.layout = function () {\n // Todo: Need to handle complete document layout(relayout).\n var page = this.viewer.pages[0];\n var body = page.bodyWidgets[0];\n };\n /**\n * Releases un-managed and - optionally - managed resources.\n */\n Layout.prototype.destroy = function () {\n this.viewer = undefined;\n this.value = undefined;\n this.allowLayout = undefined;\n this.isInitialLoad = undefined;\n this.fieldBegin = undefined;\n this.maxTextHeight = undefined;\n this.maxBaseline = undefined;\n this.maxTextBaseline = undefined;\n this.isFieldCode = undefined;\n };\n /**\n * Layouts the items\n * @private\n */\n Layout.prototype.layoutItems = function (sections) {\n var page;\n for (var i = 0; i < sections.length; i++) {\n var section = sections[i];\n page = this.viewer.createNewPage(section);\n this.addBodyWidget(this.viewer.clientActiveArea, section);\n if (this.viewer.pages.length > 1) {\n var pageIndex = 0;\n for (var i_1 = 0; i_1 < this.viewer.pages.length; i_1++) {\n var prevPage = this.viewer.pages[i_1];\n var prevSectionIndex = prevPage.sectionIndex;\n var index = section.index;\n if (prevSectionIndex > index || prevPage === page) {\n break;\n }\n pageIndex++;\n }\n if (pageIndex < this.viewer.pages.length - 1) {\n this.viewer.insertPage(pageIndex, page);\n }\n }\n this.layoutSection(section, 0, this.viewer);\n }\n this.updateFieldElements();\n this.viewer.updateScrollBars();\n this.isInitialLoad = false;\n };\n /**\n * Layouts the items\n * @param section\n * @param viewer\n * @private\n */\n Layout.prototype.layoutSection = function (section, index, viewer, ownerWidget) {\n var block = section.firstChild;\n var nextBlock;\n do {\n this.viewer.updateClientAreaForBlock(block, true);\n nextBlock = this.layoutBlock(block, index);\n index = 0;\n this.viewer.updateClientAreaForBlock(block, false);\n block = nextBlock;\n } while (block);\n };\n /**\n * Layouts the header footer items\n * @param section\n * @param viewer\n * @private\n */\n Layout.prototype.layoutHeaderFooter = function (section, viewer, page) {\n //Header layout\n var headerFooterWidget = viewer.getCurrentPageHeaderFooter(section, true);\n if (headerFooterWidget) {\n var header = headerFooterWidget.clone();\n header.page = page;\n viewer.updateHFClientArea(section.sectionFormat, true);\n page.headerWidget = this.layoutHeaderFooterItems(viewer, header);\n this.updateHeaderFooterToParent(header);\n }\n //Footer Layout\n headerFooterWidget = viewer.getCurrentPageHeaderFooter(section, false);\n if (headerFooterWidget) {\n var footer = headerFooterWidget.clone();\n footer.page = page;\n viewer.updateHFClientArea(section.sectionFormat, false);\n page.footerWidget = this.layoutHeaderFooterItems(viewer, footer);\n this.updateHeaderFooterToParent(footer);\n }\n };\n /**\n * @private\n */\n Layout.prototype.updateHeaderFooterToParent = function (node) {\n var sectionIndex = node.page.sectionIndex;\n var typeIndex = this.viewer.getHeaderFooter(node.headerFooterType);\n var clone = node.clone();\n this.viewer.headersFooters[sectionIndex][typeIndex] = clone;\n for (var j = 0; j < clone.childWidgets.length; j++) {\n var child = clone.childWidgets[j];\n if (child instanceof TableWidget) {\n this.clearTableWidget(child, false, true);\n }\n }\n return clone;\n };\n Layout.prototype.linkFieldInHeaderFooter = function (widget) {\n var firstChild = widget.firstChild;\n do {\n if (firstChild instanceof ParagraphWidget) {\n this.linkFieldInParagraph(firstChild);\n }\n else {\n this.linkFieldInTable(firstChild);\n }\n //tslint:disable:no-conditional-assignment\n } while (firstChild = firstChild.nextWidget);\n };\n /**\n * @private\n */\n Layout.prototype.linkFieldInParagraph = function (widget) {\n for (var j = 0; j < widget.childWidgets.length; j++) {\n var line = widget.childWidgets[j];\n for (var i = 0; i < line.children.length; i++) {\n var element = line.children[i];\n if (element instanceof FieldElementBox && element.fieldType !== 0) {\n element.linkFieldCharacter(this.viewer);\n }\n }\n }\n };\n /**\n * @private\n */\n Layout.prototype.linkFieldInTable = function (widget) {\n for (var i = 0; i < widget.childWidgets.length; i++) {\n var row = widget.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n for (var k = 0; k < cell.childWidgets.length; k++) {\n var block = cell.childWidgets[k];\n if (block instanceof ParagraphWidget) {\n this.linkFieldInParagraph(block);\n }\n else {\n this.linkFieldInTable(block);\n }\n }\n }\n }\n };\n /**\n * Layouts the header footer items.\n * @param viewer\n * @param hfModule\n * @private\n */\n Layout.prototype.layoutHeaderFooterItems = function (viewer, widget) {\n this.viewer.updateClientAreaLocation(widget, viewer.clientActiveArea);\n if (widget.childWidgets.length === 0) {\n var pargaraph = new ParagraphWidget();\n var line = new LineWidget(pargaraph);\n pargaraph.childWidgets.push(line);\n widget.childWidgets.push(pargaraph);\n pargaraph.containerWidget = widget;\n }\n this.linkFieldInHeaderFooter(widget);\n for (var i = 0; i < widget.childWidgets.length; i++) {\n var block = widget.childWidgets[i];\n viewer.updateClientAreaForBlock(block, true);\n this.layoutBlock(block, 0);\n viewer.updateClientAreaForBlock(block, false);\n }\n var type = widget.headerFooterType;\n if (type === 'OddFooter' || type === 'EvenFooter' || type === 'FirstPageFooter') {\n this.shiftChildLocation(viewer.clientArea.y - viewer.clientActiveArea.y, widget);\n }\n return widget;\n };\n /**\n * Shifts the child location\n * @param shiftTop\n * @param bodyWidget\n */\n Layout.prototype.shiftChildLocation = function (shiftTop, bodyWidget) {\n var widgetTop = bodyWidget.y + shiftTop;\n var footerMaxHeight = bodyWidget.page.boundingRectangle.height - (bodyWidget.page.boundingRectangle.height / 100) * 40;\n widgetTop = Math.max(widgetTop, footerMaxHeight);\n shiftTop = widgetTop - bodyWidget.y;\n bodyWidget.y = widgetTop;\n for (var i = 0; i < bodyWidget.childWidgets.length; i++) {\n var childWidget = bodyWidget.childWidgets[i];\n if (childWidget instanceof ParagraphWidget) {\n childWidget.x = childWidget.x;\n childWidget.y = childWidget.y + shiftTop;\n }\n else {\n this.shiftChildLocationForTableWidget(childWidget, shiftTop);\n }\n }\n };\n /**\n * Shifts the child location for table widget.\n * @param tableWidget\n * @param shiftTop\n */\n Layout.prototype.shiftChildLocationForTableWidget = function (tableWidget, shiftTop) {\n tableWidget.y = tableWidget.y + shiftTop;\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n var childWidget = tableWidget.childWidgets[i];\n if (childWidget instanceof TableRowWidget) {\n this.shiftChildLocationForTableRowWidget(childWidget, shiftTop);\n }\n }\n };\n /**\n * Shifts the child location for table row widget.\n * @param rowWidget\n * @param shiftTop\n */\n Layout.prototype.shiftChildLocationForTableRowWidget = function (rowWidget, shiftTop) {\n rowWidget.y = rowWidget.y + shiftTop;\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n this.shiftChildLocationForTableCellWidget(rowWidget.childWidgets[i], shiftTop);\n }\n };\n /**\n * Shifts the child location for table cell widget.\n * @param cellWidget\n * @param shiftTop\n */\n Layout.prototype.shiftChildLocationForTableCellWidget = function (cellWidget, shiftTop) {\n cellWidget.y = cellWidget.y + shiftTop;\n for (var i = 0; i < cellWidget.childWidgets.length; i++) {\n if (cellWidget.childWidgets[i] instanceof ParagraphWidget) {\n cellWidget.childWidgets[i].x = cellWidget.childWidgets[i].x;\n cellWidget.childWidgets[i].y = cellWidget.childWidgets[i].y + shiftTop;\n }\n else {\n this.shiftChildLocationForTableWidget(cellWidget.childWidgets[i], shiftTop);\n }\n }\n };\n /**\n * Layouts specified block.\n * @param block\n * @private\n */\n Layout.prototype.layoutBlock = function (block, index, moveToLine) {\n var nextBlock;\n if (block instanceof ParagraphWidget) {\n nextBlock = this.layoutParagraph(block, index);\n }\n else {\n nextBlock = this.layoutTable(block, index);\n }\n return nextBlock.nextRenderedWidget;\n };\n /**\n * Adds paragraph widget.\n * @param area\n */\n Layout.prototype.addParagraphWidget = function (area, paragraphWidget) {\n var ownerParaWidget = undefined;\n if (paragraphWidget.isEmpty() && !isNullOrUndefined(paragraphWidget.paragraphFormat) &&\n (paragraphWidget.paragraphFormat.textAlignment === 'Center' || paragraphWidget.paragraphFormat.textAlignment === 'Right') &&\n paragraphWidget.paragraphFormat.listFormat.listId === -1) {\n var top_1 = 0;\n var bottom = 0;\n var width = this.viewer.textHelper.getParagraphMarkWidth(paragraphWidget.characterFormat);\n var left = area.x;\n if (paragraphWidget.paragraphFormat.textAlignment === 'Center') {\n left += (area.width - width) / 2;\n }\n else {\n left += area.width - width;\n }\n paragraphWidget.width = width;\n paragraphWidget.x = left;\n paragraphWidget.y = area.y;\n }\n else {\n paragraphWidget.width = area.width;\n paragraphWidget.x = area.x;\n paragraphWidget.y = area.y;\n }\n return paragraphWidget;\n };\n /**\n * Adds line widget.\n * @param paragraph\n */\n Layout.prototype.addLineWidget = function (paragraphWidget) {\n var line = undefined;\n line = new LineWidget(paragraphWidget);\n line.width = paragraphWidget.width;\n paragraphWidget.childWidgets.push(line);\n line.paragraph = paragraphWidget;\n return line;\n };\n /**\n * Layouts specified paragraph.\n * @private\n * @param paragraph\n */\n Layout.prototype.layoutParagraph = function (paragraph, lineIndex) {\n this.addParagraphWidget(this.viewer.clientActiveArea, paragraph);\n this.layoutListItems(paragraph);\n if (paragraph.isEmpty()) {\n this.layoutEmptyLineWidget(paragraph, true);\n }\n else {\n var line = lineIndex < paragraph.childWidgets.length ?\n paragraph.childWidgets[lineIndex] : undefined;\n while (line instanceof LineWidget) {\n if (line.isFirstLine() && isNullOrUndefined(this.fieldBegin)) {\n if (!isNullOrUndefined(paragraph.paragraphFormat)) {\n // tslint:disable-next-line:max-line-length\n var firstLineIndent = -HelperMethods.convertPointToPixel(paragraph.paragraphFormat.firstLineIndent);\n this.viewer.updateClientWidth(firstLineIndent);\n }\n }\n line = this.layoutLine(line, 0);\n paragraph = line.paragraph;\n line = line.nextLine;\n }\n }\n this.updateWidgetToPage(this.viewer, paragraph);\n return paragraph;\n };\n Layout.prototype.clearLineMeasures = function () {\n this.maxBaseline = 0;\n this.maxTextBaseline = 0;\n this.maxTextHeight = 0;\n };\n Layout.prototype.moveElementFromNextLine = function (line) {\n var nextLine = line.nextLine;\n while (nextLine instanceof LineWidget) {\n if (nextLine.children.length > 0) {\n var element = nextLine.children.splice(0, 1)[0];\n line.children.push(element);\n element.line = line;\n break;\n }\n else {\n if (nextLine.paragraph.childWidgets.length === 1) {\n nextLine.paragraph.destroy();\n }\n else {\n nextLine.destroy();\n }\n nextLine = line.nextLine;\n }\n }\n };\n Layout.prototype.layoutLine = function (line, count) {\n var paragraph = line.paragraph;\n if (line.children.length === 0) {\n this.moveElementFromNextLine(line);\n }\n var element = line.children[count];\n this.clearLineMeasures();\n while (element instanceof ElementBox) {\n this.layoutElement(element, paragraph);\n line = element.line;\n element = element.nextElement;\n }\n return line;\n };\n // tslint:disable:max-func-body-length\n Layout.prototype.layoutElement = function (element, paragraph) {\n var line = element.line;\n var text = '';\n var index = element.indexInOwner;\n if (element instanceof FieldElementBox) {\n if (element.fieldType === 0 && this.viewer.fields.indexOf(element) === -1) {\n this.viewer.fields.push(element);\n }\n this.layoutFieldCharacters(element);\n if (element.line.isLastLine() && isNullOrUndefined(element.nextNode) && !this.isFieldCode) {\n if (isNullOrUndefined(element.fieldSeparator)) {\n this.layoutEmptyLineWidget(paragraph, false, element.line);\n }\n this.moveToNextLine(line);\n }\n else if (isNullOrUndefined(element.nextElement) && this.viewer.clientActiveArea.width > 0 && !element.line.isLastLine()) {\n this.moveElementFromNextLine(line);\n }\n else if (isNullOrUndefined(element.nextElement) && this.viewer.clientActiveArea.width === 0) {\n this.moveToNextLine(line);\n if (line.paragraph.lastChild === line && !isNullOrUndefined(line.nextLine) &&\n this.viewer.clientActiveArea.height >= 0) {\n this.moveFromNextPage(line);\n }\n }\n return;\n }\n if (element instanceof ListTextElementBox || this.isFieldCode || element instanceof BookmarkElementBox) {\n if (isNullOrUndefined(element.nextElement) && this.viewer.clientActiveArea.width > 0 && !element.line.isLastLine()) {\n this.moveElementFromNextLine(line);\n }\n if (element.line.isLastLine() && isNullOrUndefined(element.nextElement)) {\n if (this.hasValidElement(line.paragraph)) {\n this.moveToNextLine(line);\n }\n else {\n this.layoutEmptyLineWidget(line.paragraph, false, line, false);\n }\n }\n return;\n }\n var width = element.width;\n if (element instanceof FieldTextElementBox) {\n text = this.viewer.getFieldResult(element.fieldBegin, element.paragraph.bodyWidget.page);\n if (text !== '') {\n element.text = text;\n }\n else {\n text = element.text;\n }\n }\n else if (element instanceof TextElementBox) {\n this.checkAndSplitTabOrLineBreakCharacter(element.text, element);\n text = element.text;\n }\n // Here field code width and height update need to skipped based on the hidden property.\n if (element instanceof TextElementBox) {\n width = this.viewer.textHelper.getTextSize(element, element.characterFormat);\n if (element.text === '\\t') {\n element.width = this.getTabWidth(paragraph, this.viewer, index, line, element);\n }\n }\n if (this.viewer instanceof PageLayoutViewer\n && this.viewer.clientActiveArea.height < element.height && this.viewer.clientActiveArea.y !== this.viewer.clientArea.y) {\n this.moveToNextPage(this.viewer, line);\n if (element instanceof FieldTextElementBox) {\n this.updateFieldText(element);\n }\n if (element.previousElement) {\n this.cutClientWidth(element.previousElement);\n }\n }\n if (width < this.viewer.clientActiveArea.width || !this.viewer.textWrap) {\n //Fits the text in current line.\n this.addElementToLine(paragraph, element);\n if (isNullOrUndefined(element.nextElement) && this.viewer.clientActiveArea.width > 0 && !element.line.isLastLine()) {\n this.moveElementFromNextLine(line);\n }\n else if (!element.line.isLastLine() && isNullOrUndefined(element.nextElement) && this.viewer.clientActiveArea.width === 0) {\n this.moveToNextLine(line);\n if (line.paragraph.lastChild === line && this.viewer.clientActiveArea.height >= 0) {\n this.moveFromNextPage(line);\n }\n }\n }\n else if (element instanceof TextElementBox) {\n if (element.text === '\\t') {\n var currentLine = element.line;\n this.addSplittedLineWidget(currentLine, currentLine.children.indexOf(element));\n this.moveToNextLine(currentLine);\n // Recalculates tab width based on new client active area X position\n element.width = this.getTabWidth(paragraph, this.viewer, index, line, element);\n this.addElementToLine(paragraph, element);\n }\n else {\n //Splits the text and arrange line by line, till end of text.\n do {\n line = element.line;\n this.splitTextForClientArea(line, element, element.text, element.width, element.characterFormat);\n this.checkLineWidgetWithClientArea(line, element);\n if (element instanceof FieldTextElementBox) {\n this.updateFieldText(element);\n }\n } while (element.line !== line && this.cutClientWidth(element));\n }\n }\n else {\n do {\n line = element.line;\n this.splitElementForClientArea(paragraph, element);\n this.checkLineWidgetWithClientArea(line, element);\n if (element instanceof FieldTextElementBox) {\n this.updateFieldText(element);\n }\n } while (element.line !== line && this.cutClientWidth(element));\n }\n if (text === '\\v') {\n var elementIndex = line.children.indexOf(element);\n if (elementIndex > -1) {\n this.addSplittedLineWidget(line, elementIndex);\n }\n }\n if (element.line.isLastLine() && isNullOrUndefined(element.nextElement) || text === '\\v') {\n this.moveToNextLine(element.line);\n if (text === '\\v' && isNullOrUndefined(element.nextNode)) {\n this.layoutEmptyLineWidget(paragraph, true, line, true);\n }\n }\n };\n /**\n * Return true if paragraph has valid inline\n * @private\n */\n Layout.prototype.hasValidElement = function (paragraph) {\n var line = paragraph.firstChild;\n if (line && !isNullOrUndefined(this.viewer.selection)) {\n var elementBox = line.children[0];\n while (elementBox) {\n if (elementBox instanceof FieldElementBox) {\n elementBox = this.viewer.selection.getNextValidElementForField(elementBox);\n if (!elementBox.line.paragraph.equals(paragraph)) {\n return false;\n }\n }\n if (elementBox instanceof TextElementBox) {\n return true;\n }\n elementBox = elementBox.nextNode;\n }\n }\n return false;\n };\n Layout.prototype.updateFieldText = function (element) {\n // tslint:disable-next-line:max-line-length\n var text = this.viewer.getFieldResult(element.fieldBegin, element.paragraph.bodyWidget.page);\n if (text !== '') {\n element.text = text;\n this.viewer.textHelper.getTextSize(element, element.characterFormat);\n }\n };\n Layout.prototype.checkLineWidgetWithClientArea = function (line, element) {\n if (line !== element.line || element.line === line && isNullOrUndefined(element.nextElement)\n && !element.line.isLastLine()) {\n this.moveToNextLine(line);\n }\n if (element.line !== line && this.viewer instanceof PageLayoutViewer\n && this.viewer.clientActiveArea.height < element.height &&\n this.viewer.clientActiveArea.y !== this.viewer.clientArea.y) {\n this.moveToNextPage(this.viewer, element.line);\n }\n else if (element.line === line && isNullOrUndefined(element.nextElement)\n && line.paragraph.lastChild === line && !line.isLastLine() && this.viewer.clientActiveArea.height >= 0) {\n this.moveFromNextPage(line);\n }\n };\n Layout.prototype.checkAndSplitTabOrLineBreakCharacter = function (text, element) {\n var char = ['\\t', '\\v'];\n var index = HelperMethods.indexOfAny(text, char);\n if (index > -1) {\n var character = text[index];\n if ((character === '\\t' && text !== '\\t') || (character === '\\v' && text !== '\\v')) {\n this.splitByLineBreakOrTab(this.viewer, element, index, character);\n }\n }\n };\n /**\n * @private\n */\n Layout.prototype.moveFromNextPage = function (line) {\n var nextLine = line.nextLine;\n if (nextLine && line.paragraph.childWidgets.indexOf(nextLine) === -1) {\n nextLine.paragraph.childWidgets.splice(nextLine.indexInOwner, 1);\n line.paragraph.childWidgets.push(nextLine);\n nextLine.paragraph = line.paragraph;\n }\n };\n Layout.prototype.cutClientWidth = function (currentElement) {\n this.clearLineMeasures();\n var line = currentElement.line;\n var width = 0;\n for (var i = 0; i < line.children.length; i++) {\n var element = line.children[i];\n width += element.width;\n if (currentElement === element) {\n break;\n }\n }\n var splitCurrentWidget = this.viewer.clientActiveArea.width - width < 0;\n if (!splitCurrentWidget) {\n this.viewer.cutFromLeft(this.viewer.clientActiveArea.x + width);\n if (currentElement.line.paragraph.paragraphFormat.textAlignment === 'Justify' &&\n currentElement instanceof TextElementBox) {\n this.splitTextElementWordByWord(currentElement);\n }\n if (isNullOrUndefined(currentElement.nextElement) && this.viewer.clientActiveArea.width > 0\n && !currentElement.line.isLastLine()) {\n this.moveElementFromNextLine(line);\n }\n }\n else if (currentElement.previousElement) {\n this.cutClientWidth(currentElement.previousElement);\n }\n return splitCurrentWidget;\n };\n Layout.prototype.layoutFieldCharacters = function (element) {\n if (element.fieldType === 0) {\n if (!this.isFieldCode && (!isNullOrUndefined(element.fieldEnd) || element.hasFieldEnd)) {\n this.viewer.fieldStacks.push(element);\n this.isFieldCode = true;\n element.hasFieldEnd = true;\n }\n }\n else if (this.viewer.fieldStacks.length > 0) {\n if (element.fieldType === 2) {\n var field = this.viewer.fieldStacks[this.viewer.fieldStacks.length - 1];\n if (field.fieldSeparator === element && (!isNullOrUndefined(field.fieldEnd) || field.hasFieldEnd)) {\n this.isFieldCode = false;\n }\n }\n else {\n var field = this.viewer.fieldStacks[this.viewer.fieldStacks.length - 1];\n if (element === field.fieldEnd) {\n this.viewer.fieldStacks.pop();\n this.isFieldCode = false;\n }\n }\n }\n };\n /**\n * Layouts empty line widget.\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.layoutEmptyLineWidget = function (paragraph, isEmptyLine, line, isShiftEnter) {\n isShiftEnter = isNullOrUndefined(isShiftEnter) ? false : isShiftEnter;\n //Calculate line height and descent based on formatting defined in paragraph.\n var paragraphMarkSize = this.viewer.textHelper.getParagraphMarkSize(paragraph.characterFormat);\n var maxHeight = paragraphMarkSize.Height;\n var beforeSpacing = this.getBeforeSpacing(paragraph);\n var lineWidget;\n if (paragraph.childWidgets.length > 0 && !isShiftEnter) {\n lineWidget = paragraph.childWidgets[0];\n }\n else {\n lineWidget = isEmptyLine ? this.addLineWidget(paragraph) : line;\n }\n //isNullOrUndefined(this.viewer.currentHeaderFooter) && \n if (this.viewer instanceof PageLayoutViewer\n && this.viewer.clientActiveArea.height < beforeSpacing + maxHeight\n && this.viewer.clientActiveArea.y !== this.viewer.clientArea.y) {\n this.moveToNextPage(this.viewer, lineWidget);\n }\n //Gets line spacing.\n var lineSpacing = this.getLineSpacing(paragraph, maxHeight);\n var maxDescent = maxHeight - paragraphMarkSize.BaselineOffset;\n //Calculate the bottom position of current line - max height + line spacing.\n if (!isNaN(this.maxTextHeight)\n && maxHeight < this.maxTextHeight) {\n maxHeight = this.maxTextHeight;\n maxDescent = maxHeight - this.maxTextBaseline;\n }\n var topMargin = 0;\n var bottomMargin = 0;\n var leftMargin = 0;\n var height = maxHeight;\n var lineSpacingType = paragraph.paragraphFormat.lineSpacingType;\n if (lineSpacingType === 'Multiple') {\n if (lineSpacing > maxHeight) {\n bottomMargin += lineSpacing - maxHeight;\n }\n else {\n topMargin += lineSpacing - maxHeight;\n }\n }\n else if (lineSpacingType === 'Exactly') {\n topMargin += lineSpacing - (topMargin + height + bottomMargin);\n }\n else if (lineSpacing > topMargin + height + bottomMargin) {\n topMargin += lineSpacing - (topMargin + height + bottomMargin);\n }\n topMargin += beforeSpacing;\n bottomMargin += HelperMethods.convertPointToPixel(paragraph.paragraphFormat.afterSpacing);\n for (var i = 0; i < lineWidget.children.length; i++) {\n var element = lineWidget.children[i];\n if (element instanceof ListTextElementBox) {\n var textAlignment = paragraph.paragraphFormat.textAlignment;\n if (textAlignment === 'Right') {\n leftMargin = this.viewer.clientArea.width - element.width;\n }\n else if (textAlignment === 'Center') {\n leftMargin = (this.viewer.clientArea.width - element.width) / 2;\n }\n element.margin = new Margin(leftMargin, topMargin, 0, bottomMargin);\n element.line = lineWidget;\n lineWidget.height = topMargin + height + bottomMargin;\n }\n }\n lineWidget.height = topMargin + height + bottomMargin;\n this.viewer.cutFromTop(this.viewer.clientActiveArea.y + lineWidget.height);\n //Clears the previous line elements from collection. \n };\n /**\n * @private\n */\n Layout.prototype.layoutListItems = function (paragraph) {\n if (!this.isFieldCode) {\n if (!isNullOrUndefined(paragraph.paragraphFormat)\n && !isNullOrUndefined(paragraph.paragraphFormat.listFormat)\n && !isNullOrUndefined(this.viewer.getListById(paragraph.paragraphFormat.listFormat.listId)) &&\n paragraph.paragraphFormat.listFormat.listLevelNumber >= 0\n && paragraph.paragraphFormat.listFormat.listLevelNumber < 9) {\n this.clearListElementBox(paragraph);\n this.layoutList(paragraph, this.viewer);\n }\n else if (paragraph.paragraphFormat.listFormat && paragraph.paragraphFormat.listFormat.listId === -1) {\n this.clearListElementBox(paragraph);\n }\n }\n };\n /**\n * Layouts list.\n * @param viewer\n */\n Layout.prototype.layoutList = function (paragraph, viewer) {\n var list = viewer.getListById(paragraph.paragraphFormat.listFormat.listId);\n viewer.updateClientWidth(-HelperMethods.convertPointToPixel(paragraph.paragraphFormat.firstLineIndent));\n var currentListLevel = this.getListLevel(list, paragraph.paragraphFormat.listFormat.listLevelNumber);\n // if (isNullOrUndefined(currentListLevel)) {\n // return;\n // }\n var lineWidget = paragraph.childWidgets[0];\n if (isNullOrUndefined(lineWidget)) {\n lineWidget = new LineWidget(paragraph);\n paragraph.childWidgets.push(lineWidget);\n }\n var element = new ListTextElementBox(currentListLevel, false);\n element.line = lineWidget;\n if (currentListLevel.listLevelPattern === 'Bullet') {\n element.text = currentListLevel.numberFormat;\n }\n else {\n element.text = this.getListNumber(paragraph.paragraphFormat.listFormat);\n }\n viewer.textHelper.updateTextSize(element, paragraph);\n var moveToNextPage;\n if (this.viewer instanceof PageLayoutViewer\n && this.viewer.clientActiveArea.height < element.height && this.viewer.clientActiveArea.y !== this.viewer.clientArea.y) {\n moveToNextPage = true;\n }\n viewer.cutFromLeft(viewer.clientActiveArea.x + element.width);\n //Adds the text element to the line\n lineWidget.children.splice(0, 0, element);\n if (currentListLevel.followCharacter !== 'None') {\n element = new ListTextElementBox(currentListLevel, true);\n if (currentListLevel.followCharacter === 'Tab') {\n element.text = '\\t';\n var index = lineWidget.children.indexOf(element);\n element.width = this.getTabWidth(paragraph, viewer, index, lineWidget, undefined);\n }\n else {\n element.text = ' ';\n viewer.textHelper.updateTextSize(element, paragraph);\n }\n viewer.cutFromLeft(viewer.clientActiveArea.x + element.width);\n //Adds the tabSpace to the line\n lineWidget.children.splice(1, 0, element);\n element.line = lineWidget;\n }\n if (moveToNextPage) {\n this.moveToNextPage(this.viewer, lineWidget);\n this.cutClientWidth(element);\n return;\n }\n if (currentListLevel.followCharacter !== 'None') {\n viewer.updateClientWidth(HelperMethods.convertPointToPixel(paragraph.paragraphFormat.firstLineIndent));\n }\n };\n /**\n * Adds body widget.\n * @param area\n * @param section\n * @private\n */\n Layout.prototype.addBodyWidget = function (area, widget) {\n var bodyWidget;\n if (widget) {\n bodyWidget = widget;\n }\n else {\n bodyWidget = new BodyWidget();\n }\n bodyWidget.width = area.width;\n bodyWidget.x = area.x;\n bodyWidget.y = area.y;\n // this.addSectionInDictionary(this.viewer, section, bodyWidget);\n return bodyWidget;\n };\n /**\n * Adds list level.\n * @param abstractList\n */\n Layout.prototype.addListLevels = function (abstractList) {\n for (var i = abstractList.levels.length; i < 9; i++) {\n var listLevel = new WListLevel(abstractList);\n var val = i % 3;\n if (abstractList.levels[0].listLevelPattern === 'Bullet') {\n listLevel.listLevelPattern = 'Bullet';\n listLevel.numberFormat = val === 0 ? '\\uf0b7' : val === 1 ? '\\uf0a7' : '\\uf0d8';\n listLevel.characterFormat.fontFamily = listLevel.numberFormat === '\\uf0a7' || '\\uf0d8' ? 'Wingdings' : 'Symbol';\n }\n else {\n listLevel.listLevelPattern = this.getListLevelPattern(val);\n listLevel.numberFormat = '%' + (i + 1).toString() + '.';\n listLevel.startAt = 1;\n listLevel.restartLevel = i;\n }\n listLevel.paragraphFormat = new WParagraphFormat(undefined);\n listLevel.paragraphFormat.leftIndent = 48 * (i + 1);\n listLevel.paragraphFormat.firstLineIndent = -24;\n abstractList.levels.push(listLevel);\n }\n };\n Layout.prototype.addSplittedLineWidget = function (lineWidget, elementIndex, splittedElementBox) {\n var paragraph = lineWidget.paragraph;\n var movedElementBox = [];\n var lineIndex = paragraph.childWidgets.indexOf(lineWidget);\n if (!isNullOrUndefined(splittedElementBox)) {\n movedElementBox.push(splittedElementBox);\n }\n var newLineWidget = undefined;\n //Move Next element box to temp collection\n for (var i = elementIndex + 1; i < lineWidget.children.length; i++) {\n movedElementBox.push(lineWidget.children[i]);\n }\n if (movedElementBox.length > 0) {\n if (lineIndex === paragraph.childWidgets.length - 1) {\n newLineWidget = new LineWidget(paragraph);\n }\n else {\n newLineWidget = paragraph.childWidgets[lineIndex + 1];\n }\n for (var j = 0; j < movedElementBox.length; j++) {\n movedElementBox[j].line = newLineWidget;\n }\n lineWidget.children.splice(elementIndex + 1, lineWidget.children.length - 1);\n newLineWidget.children = movedElementBox.concat(newLineWidget.children);\n if (paragraph.childWidgets.indexOf(newLineWidget) === -1) {\n paragraph.childWidgets.splice(lineIndex + 1, 0, newLineWidget);\n }\n }\n };\n /**\n * Adds element to line.\n * @param element\n */\n Layout.prototype.addElementToLine = function (paragraph, element) {\n this.viewer.cutFromLeft(this.viewer.clientActiveArea.x + element.width);\n if (paragraph.paragraphFormat.textAlignment === 'Justify' && element instanceof TextElementBox) {\n this.splitTextElementWordByWord(element);\n }\n };\n /**\n * Splits element for client area.\n * @param element\n */\n Layout.prototype.splitElementForClientArea = function (paragraph, element) {\n var line = element.line;\n if (element.line.children.length > 0) {\n var previousElement = element.previousElement;\n var index = element.indexInOwner;\n // if line widget contain only single image element box need to skip this from splitting\n // else move element to next line\n if (element.line.children.length > 1) {\n if (previousElement && this.viewer.clientActiveArea.x !== this.viewer.clientArea.x) {\n index -= 1;\n }\n }\n this.addSplittedLineWidget(element.line, index);\n }\n };\n /**\n * Splits by word\n * @param elementBox\n * @param text\n * @param width\n * @param characterFormat\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.splitByWord = function (lineWidget, paragraph, elementBox, text, width, characterFormat) {\n var index = this.getSplitIndexByWord(this.viewer.clientActiveArea.width, text, width, characterFormat);\n if (index > 0 && index < elementBox.length) {\n var indexOf = lineWidget.children.indexOf(elementBox);\n var lineIndex = paragraph.childWidgets.indexOf(lineWidget);\n var splittedElementBox = new TextElementBox();\n text = text.substring(index);\n splittedElementBox.text = text;\n if (text[0] === ' ') {\n var prevLength = text.length;\n text = HelperMethods.trimStart(text); //To trim white space at starting of the text.\n index += prevLength - text.length;\n }\n splittedElementBox.characterFormat.copyFormat(elementBox.characterFormat);\n splittedElementBox.width = this.viewer.textHelper.getWidth(splittedElementBox.text, characterFormat);\n elementBox.text = elementBox.text.substr(0, index);\n elementBox.width -= splittedElementBox.width;\n splittedElementBox.height = elementBox.height;\n splittedElementBox.baselineOffset = elementBox.baselineOffset;\n this.addSplittedLineWidget(lineWidget, indexOf, splittedElementBox);\n this.addElementToLine(paragraph, elementBox);\n if (elementBox.width === 0) {\n lineWidget.children.splice(indexOf, 1);\n }\n }\n };\n /**\n * Splits by character.\n * @param textElement\n * @param text\n * @param width\n * @param characterFormat\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.splitByCharacter = function (lineWidget, textElement, text, width, characterFormat) {\n var paragraph = lineWidget.paragraph;\n // tslint:disable-next-line:max-line-length\n var index = this.getTextSplitIndexByCharacter(this.viewer.clientArea.width, this.viewer.clientActiveArea.width, text, width, characterFormat);\n var splitWidth = 0;\n if (index < textElement.length) {\n splitWidth = this.viewer.textHelper.measureTextExcludingSpaceAtEnd(text.substring(0, index), characterFormat);\n text = text.substring(index);\n }\n if (splitWidth > this.viewer.clientActiveArea.width && textElement.indexInOwner > 0) {\n this.addSplittedLineWidget(lineWidget, textElement.indexInOwner - 1);\n return;\n }\n var indexOf = lineWidget.children.indexOf(textElement);\n if (index < textElement.length) {\n var lineIndex = paragraph.childWidgets.indexOf(lineWidget);\n var splittedElement = new TextElementBox();\n splittedElement.text = text;\n textElement.text = textElement.text.substr(0, index);\n splittedElement.characterFormat.copyFormat(textElement.characterFormat);\n splittedElement.width = this.viewer.textHelper.getWidth(splittedElement.text, characterFormat);\n textElement.width -= splittedElement.width;\n splittedElement.height = textElement.height;\n splittedElement.baselineOffset = textElement.baselineOffset;\n lineWidget.children.splice(textElement.indexInOwner + 1, 0, splittedElement);\n this.addSplittedLineWidget(lineWidget, indexOf);\n this.addElementToLine(paragraph, textElement);\n if (textElement.width === 0) {\n lineWidget.children.splice(indexOf, 1);\n }\n }\n else {\n //Adds the last text element on inline to line elements collection. \n this.addSplittedLineWidget(lineWidget, indexOf);\n this.addElementToLine(paragraph, textElement);\n }\n };\n /**\n * Splits text element word by word.\n * @param textElement\n */\n Layout.prototype.splitTextElementWordByWord = function (textElement) {\n var lineWidget = textElement.line;\n var indexOf = lineWidget.children.indexOf(textElement);\n var text = textElement.text;\n var format;\n var characterUptoWs = text.trim().indexOf(' ');\n if (characterUptoWs >= 0) {\n lineWidget.children.splice(indexOf, 1);\n format = textElement.characterFormat;\n var fontSize = format.fontSize;\n var index = textElement.length - HelperMethods.trimStart(text).length; //Trim start\n while (index < textElement.length) {\n index = this.getTextIndexAfterSpace(text, index);\n if (index === 0 || index === textElement.length) {\n break;\n }\n if (index < textElement.length) {\n var splittedElement = new TextElementBox();\n var splittedText = text.substring(0, index);\n text = text.substring(index);\n if (text.substring(0, 1) === ' ') {\n // start of the text is trimmed and its length is reduced from text length. \n index += text.length - HelperMethods.trimStart(text).length;\n }\n splittedElement.text = splittedText;\n splittedElement.characterFormat.copyFormat(textElement.characterFormat);\n splittedElement.line = lineWidget;\n splittedElement.width = this.viewer.textHelper.getWidth(splittedElement.text, format);\n splittedElement.height = textElement.height;\n splittedElement.baselineOffset = textElement.baselineOffset;\n lineWidget.children.splice(indexOf, 0, splittedElement);\n textElement.text = text;\n textElement.width -= splittedElement.width;\n if (textElement.width === 0) {\n lineWidget.children.splice(lineWidget.children.indexOf(textElement), 1);\n }\n index = 0;\n indexOf++;\n }\n }\n textElement.text = text;\n lineWidget.children.splice(indexOf, 0, textElement);\n }\n };\n /**\n * Splits text for client area.\n * @param element\n * @param text\n * @param width\n * @param characterFormat\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.splitTextForClientArea = function (lineWidget, element, text, width, characterFormat) {\n var paragraph = lineWidget.paragraph;\n var isSplitByWord = true;\n var index = -1;\n if (!(text.substring(0, 1) === ' ')) {\n var textWidth = width;\n var characterUptoWS = 0;\n characterUptoWS = HelperMethods.trimEnd(text).indexOf(' ') + 1;\n index = characterUptoWS;\n //Checks whether text not starts with white space. If starts with white space, no need to check previous text blocks.\n if (index > 0) {\n textWidth = this.viewer.textHelper.measureTextExcludingSpaceAtEnd(text.slice(0, index), characterFormat);\n }\n if (this.viewer.clientActiveArea.width < textWidth) {\n //Check and split the previous text elements to next line. \n isSplitByWord = this.checkPreviousElement(lineWidget, lineWidget.children.indexOf(element), characterFormat);\n if (isSplitByWord) {\n //lineWidget = paragraph.childWidgets[paragraph.childWidgets.indexOf(lineWidget) + 1] as LineWidget;\n //isSplitByWord = textWidth <= this.viewer.clientActiveArea.width;\n return;\n }\n }\n }\n else {\n index = 1;\n }\n if (width <= this.viewer.clientActiveArea.width) {\n //Fits the text in current line.\n this.addElementToLine(paragraph, element);\n }\n else if (isSplitByWord && (index > 0 || text.indexOf(' ') !== -1)) {\n this.splitByWord(lineWidget, paragraph, element, text, width, characterFormat);\n }\n else {\n this.splitByCharacter(lineWidget, element, text, width, characterFormat);\n }\n };\n /**\n * Handle tab or line break character splitting\n * @param {LayoutViewer} viewer\n * @param {TextElementBox} span\n * @param {number} index\n * @param {string} spiltBy\n * @private\n */\n Layout.prototype.splitByLineBreakOrTab = function (viewer, span, index, spiltBy) {\n // Splits tab character to separate SpanAdv\n var inlineIndex = span.line.children.indexOf(span);\n var value = span.text;\n var remainder = value.substring(index);\n var newSpan = spiltBy === '\\t' ? new TabElementBox() : new TextElementBox();\n newSpan.line = span.line;\n newSpan.characterFormat.copyFormat(span.characterFormat);\n span.line.children.splice(inlineIndex + 1, 0, newSpan);\n if (index > 0 && remainder.length === 1) {\n newSpan.text = value.substring(index);\n span.text = value.substring(0, index);\n }\n else if (index > 0) {\n newSpan.text = spiltBy;\n var newText = new TextElementBox();\n newText.line = span.line;\n newText.text = value.substring(index + 1);\n newText.characterFormat.copyFormat(span.characterFormat);\n span.line.children.splice(inlineIndex + 2, 0, newText);\n span.text = value.substring(0, index);\n }\n else if (remainder !== '') {\n newSpan.text = value.substring(index + 1);\n span.text = spiltBy;\n }\n };\n /**\n * Moves to next line.\n */\n Layout.prototype.moveToNextLine = function (line) {\n var paragraph = line.paragraph;\n var paraFormat = paragraph.paragraphFormat;\n var isParagraphStart = line.isFirstLine();\n var isParagraphEnd = line.isLastLine();\n var height = 0;\n var maxDescent = 0;\n var afterSpacing = 0;\n var beforeSpacing = 0;\n var lineSpacing = 0;\n var firstLineIndent = 0;\n this.updateLineWidget(line);\n height = this.maxTextHeight;\n maxDescent = height - this.maxTextBaseline;\n //Updates before spacing at the top of Paragraph first line.\n if (isParagraphStart) {\n beforeSpacing = this.getBeforeSpacing(paragraph);\n firstLineIndent = HelperMethods.convertPointToPixel(paraFormat.firstLineIndent);\n }\n //Updates after spacing at the bottom of Paragraph last line.\n if (isParagraphEnd) {\n afterSpacing = HelperMethods.convertPointToPixel(paraFormat.afterSpacing);\n }\n if (isNaN(this.maxTextHeight)) {\n //Calculate line height and descent based on formatting defined in paragraph.\n var measurement = this.viewer.textHelper.measureText('a', paragraph.characterFormat);\n height = measurement.Height;\n maxDescent = height - measurement.BaselineOffset;\n }\n else {\n height = this.maxTextHeight;\n maxDescent = height - this.maxTextBaseline;\n }\n // Gets line spacing.\n lineSpacing = this.getLineSpacing(paragraph, height);\n if (paraFormat.lineSpacingType === 'Exactly'\n && lineSpacing < maxDescent + this.maxBaseline) {\n lineSpacing = maxDescent + this.maxBaseline;\n }\n var subWidth = 0;\n var whiteSpaceCount = 0;\n var textAlignment = paraFormat.textAlignment;\n //Calculates the sub width, for text alignments - Center, Right, Justify.\n if (textAlignment !== 'Left' && this.viewer.textWrap && !(textAlignment === 'Justify' && isParagraphEnd)) {\n // tslint:disable-next-line:max-line-length\n var getWidthAndSpace = this.getSubWidth(line, textAlignment === 'Justify', whiteSpaceCount, firstLineIndent);\n subWidth = getWidthAndSpace.subWidth;\n whiteSpaceCount = getWidthAndSpace.spaceCount;\n }\n var addSubWidth = false;\n var lineSpacingType = paraFormat.lineSpacingType;\n for (var i = 0; i < line.children.length; i++) {\n var topMargin = 0;\n var bottomMargin = 0;\n var leftMargin = 0;\n var elementBox = line.children[i];\n // tslint:disable-next-line:max-line-length\n var alignElements = this.alignLineElements(elementBox, topMargin, bottomMargin, maxDescent, addSubWidth, subWidth, textAlignment, whiteSpaceCount, i === line.children.length - 1);\n topMargin = alignElements.topMargin;\n bottomMargin = alignElements.bottomMargin;\n addSubWidth = alignElements.addSubWidth;\n whiteSpaceCount = alignElements.whiteSpaceCount;\n //Updates line spacing, paragraph after/ before spacing and aligns the text to base line offset.\n if (lineSpacingType === 'Multiple') {\n if (lineSpacing > height) {\n bottomMargin += lineSpacing - height;\n }\n else {\n topMargin += lineSpacing - height;\n }\n }\n else if (lineSpacingType === 'Exactly') {\n topMargin += lineSpacing - (topMargin + elementBox.height + bottomMargin);\n }\n else if (lineSpacing > topMargin + elementBox.height + bottomMargin) {\n topMargin += lineSpacing - (topMargin + elementBox.height + bottomMargin);\n }\n topMargin += beforeSpacing;\n bottomMargin += afterSpacing;\n if (i === 0) {\n line.height = topMargin + elementBox.height + bottomMargin;\n if (textAlignment === 'Right') {\n //Aligns the text as right justified.\n leftMargin = subWidth;\n }\n else if (textAlignment === 'Center') {\n //Aligns the text as center justified.\n leftMargin = subWidth / 2;\n }\n }\n elementBox.margin = new Margin(leftMargin, topMargin, 0, bottomMargin);\n elementBox.line = line;\n }\n this.viewer.cutFromTop(this.viewer.clientActiveArea.y + line.height);\n };\n Layout.prototype.updateLineWidget = function (line) {\n for (var i = 0; i < line.children.length; i++) {\n var element = line.children[i];\n if (element instanceof TextElementBox || element instanceof ListTextElementBox) {\n if (this.maxTextHeight < element.height) {\n this.maxTextHeight = element.height;\n this.maxTextBaseline = element.baselineOffset;\n }\n if (this.maxBaseline < this.maxTextBaseline) {\n this.maxBaseline = this.maxTextBaseline;\n }\n }\n else if (this.maxBaseline < element.height) {\n this.maxBaseline = element.height;\n }\n }\n };\n /**\n * @param viewer\n */\n Layout.prototype.moveToNextPage = function (viewer, line) {\n var paragraphWidget = line.paragraph;\n var index = 0;\n if (!isNullOrUndefined(line)) {\n index = paragraphWidget.childWidgets.indexOf(line);\n if (index > 0) {\n paragraphWidget.height = viewer.clientActiveArea.y - paragraphWidget.y;\n }\n }\n var nextBody = this.moveBlocksToNextPage(paragraphWidget);\n this.viewer.updateClientArea(nextBody.sectionFormat, nextBody.page);\n this.viewer.updateClientAreaForBlock(paragraphWidget, true);\n if (index > 0) {\n var nextParagraph = void 0;\n if (nextBody.firstChild instanceof ParagraphWidget && nextBody.firstChild.equals(paragraphWidget)) {\n nextParagraph = nextBody.firstChild;\n }\n else {\n nextParagraph = new ParagraphWidget();\n }\n nextParagraph = this.addParagraphWidget(this.viewer.clientActiveArea, nextParagraph);\n nextParagraph.index = paragraphWidget.index;\n var insertIndex = 0;\n for (var i = index; i < paragraphWidget.childWidgets.length; i++) {\n var lineWidget = paragraphWidget.childWidgets[i];\n lineWidget.paragraph = nextParagraph;\n nextParagraph.childWidgets.splice(insertIndex, 0, lineWidget);\n lineWidget.paragraph = nextParagraph;\n insertIndex++;\n }\n nextParagraph.paragraphFormat = paragraphWidget.paragraphFormat;\n nextParagraph.characterFormat = paragraphWidget.characterFormat;\n paragraphWidget.childWidgets.splice(index);\n paragraphWidget = nextParagraph;\n }\n else {\n paragraphWidget.containerWidget.removeChild(paragraphWidget.indexInOwner);\n }\n if (nextBody.childWidgets.indexOf(paragraphWidget) === -1) {\n nextBody.childWidgets.splice(0, 0, paragraphWidget);\n }\n paragraphWidget.containerWidget = nextBody;\n this.viewer.updateClientAreaLocation(paragraphWidget, this.viewer.clientActiveArea);\n };\n /**\n * Aligns line elements\n * @param element\n * @param topMargin\n * @param bottomMargin\n * @param maxDescent\n * @param addSubWidth\n * @param subWidth\n * @param textAlignment\n * @param whiteSpaceCount\n * @param isLastElement\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.alignLineElements = function (element, topMargin, bottomMargin, maxDescent, addSubWidth, subWidth, textAlignment, whiteSpaceCount, isLastElement) {\n if (element instanceof TextElementBox || element instanceof ListTextElementBox) {\n var textElement = element instanceof TextElementBox ? element : undefined;\n //Updates the text to base line offset.\n // tslint:disable-next-line:max-line-length\n var baselineOffset = element instanceof TextElementBox ? textElement.baselineOffset : element.baselineOffset;\n topMargin += this.maxBaseline - baselineOffset;\n bottomMargin += maxDescent - (element.height - baselineOffset);\n //Updates the text to base line offset.\n if (!isNullOrUndefined(textElement) && textAlignment === 'Justify' && whiteSpaceCount > 0) {\n //Aligns the text as Justified.\n var width = textElement.width;\n var text = textElement.text;\n if (!addSubWidth) {\n text = HelperMethods.trimStart(text); // trim start\n addSubWidth = (text.length > 0);\n }\n if (addSubWidth) {\n var spaceCount = text.length - HelperMethods.removeSpace(text).length;\n if (isLastElement) {\n spaceCount -= text.length - HelperMethods.trimEnd(text).length;\n }\n if (whiteSpaceCount < spaceCount) {\n width = this.viewer.textHelper.measureTextExcludingSpaceAtEnd(text, textElement.characterFormat);\n spaceCount = whiteSpaceCount;\n }\n if (spaceCount > 0) {\n textElement.width = width + subWidth * spaceCount;\n whiteSpaceCount -= spaceCount;\n }\n }\n }\n }\n else {\n addSubWidth = true;\n //Updates the Image/UIElement to base line offset.\n topMargin += this.maxBaseline - element.height;\n bottomMargin += maxDescent;\n }\n return { 'topMargin': topMargin, 'bottomMargin': bottomMargin, 'addSubWidth': addSubWidth, 'whiteSpaceCount': whiteSpaceCount };\n };\n /**\n * Updates widget to page.\n * @param viewer\n * @param block\n * @private\n */\n Layout.prototype.updateWidgetToPage = function (viewer, paragraphWidget) {\n if (paragraphWidget.isInsideTable) {\n var cellWidget = paragraphWidget.associatedCell;\n paragraphWidget.height = viewer.clientActiveArea.y - paragraphWidget.y;\n // if (viewer instanceof PageLayoutViewer) {\n if (isNullOrUndefined(paragraphWidget.associatedCell) || isNullOrUndefined(paragraphWidget.associatedCell.ownerRow)\n || isNullOrUndefined(paragraphWidget.associatedCell.ownerRow.rowFormat)) {\n return;\n }\n if (paragraphWidget.associatedCell.ownerRow.rowFormat.heightType === 'Exactly') {\n cellWidget.height = HelperMethods.convertPointToPixel(paragraphWidget.associatedCell.ownerRow.rowFormat.height);\n }\n else {\n // tslint:disable-next-line:max-line-length\n if ([cellWidget].length <= 1 && paragraphWidget.associatedCell.ownerRow.rowFormat.heightType === 'AtLeast') {\n cellWidget.height = Math.max(HelperMethods.convertPointToPixel(paragraphWidget.associatedCell.ownerRow.rowFormat.height), this.getCellContentHeight(cellWidget));\n }\n else {\n cellWidget.height = cellWidget.height + paragraphWidget.height;\n }\n }\n // } else {\n // cellWidget.height = cellWidget.height + paragraphWidget.height;\n // }\n // cellWidget.childWidgets.push(paragraphWidget);\n paragraphWidget.containerWidget = cellWidget;\n }\n else {\n paragraphWidget.height = viewer.clientActiveArea.y - paragraphWidget.y;\n //Adds the paragraph widget to the Header Footer/ Body widget.\n // this.updateWidgetsToBody(paragraphWidget, viewer, paragraphWidget);\n //For canvas no need to render paragraph widget here. In case of div, need to render paragraph here.\n // tslint:disable-next-line:max-line-length \n // this.render.renderParagraphWidget((paragraphWidget.containerWidget as BodyWidget).page, paragraphWidget);\n }\n if (paragraphWidget.bodyWidget instanceof HeaderFooterWidget) {\n paragraphWidget.containerWidget.height += paragraphWidget.height;\n if (this.viewer.owner.enableHeaderAndFooter && paragraphWidget.bodyWidget.headerFooterType.indexOf('Footer') !== -1) {\n this.shiftFooterChildLocation(paragraphWidget.bodyWidget, this.viewer);\n }\n }\n };\n /**\n * @private\n */\n Layout.prototype.shiftFooterChildLocation = function (widget, viewer) {\n var pageHeight = widget.page.bodyWidgets[0].sectionFormat.pageHeight;\n if (widget.headerFooterType.indexOf('Footer') !== -1) {\n var footerDistance = widget.page.bodyWidgets[0].sectionFormat.footerDistance;\n var height = HelperMethods.convertPointToPixel(pageHeight - footerDistance);\n var top_2;\n if (widget.y + widget.height > height) {\n top_2 = height - (widget.y + widget.height);\n }\n else if (widget.y + widget.height < height) {\n top_2 = (widget.y + widget.height) - height;\n }\n if (!isNullOrUndefined(top_2)) {\n top_2 = height - (widget.y + widget.height);\n this.shiftChildLocation(top_2, widget);\n viewer.clientActiveArea.y += top_2;\n }\n }\n };\n /**\n * Checks previous element.\n * @param characterFormat\n */\n Layout.prototype.checkPreviousElement = function (line, index, characterFormat) {\n var paragraph = line.paragraph;\n var isSplitByWord = false;\n var lastTextElement = 0;\n for (var i = index - 1; i >= 0; i--) {\n var textElement = line.children[i];\n if (textElement instanceof TextElementBox) {\n var text = textElement.text;\n lastTextElement = i;\n if (text.length > 0 && text[text.length - 1] === ' ') {\n if (i === index - 1) {\n this.addSplittedLineWidget(line, index - 1);\n return true;\n }\n isSplitByWord = true;\n break;\n }\n else if (text === '\\t') {\n return false;\n }\n else if (text.indexOf(' ') >= 0) {\n isSplitByWord = true;\n var index_1 = text.lastIndexOf(' ') + 1;\n //Splits the text element by space.\n var splittedElement = new TextElementBox();\n splittedElement.text = text.substr(index_1);\n splittedElement.characterFormat.copyFormat(textElement.characterFormat);\n textElement.text = text.substr(0, index_1);\n this.viewer.textHelper.getTextSize(splittedElement, characterFormat);\n textElement.width -= splittedElement.width;\n textElement.height = splittedElement.height;\n if (textElement.width === 0) {\n line.children.splice(i, 1);\n }\n //Adds the text element to the line\n line.children.splice(i + 1, 0, splittedElement);\n break;\n }\n }\n else if (!(textElement instanceof ListTextElementBox)) {\n //Handled for inline images/UIelements.\n lastTextElement = i;\n isSplitByWord = true;\n break;\n }\n }\n if (isSplitByWord) {\n lastTextElement++;\n if (lastTextElement < line.children.length) {\n var splitWidth = 0;\n for (var i = lastTextElement; i < line.children.length; i++) {\n splitWidth += line.children[i].width;\n this.addSplittedLineWidget(line, i - 1);\n i--;\n }\n this.viewer.updateClientWidth(splitWidth);\n }\n }\n return isSplitByWord;\n };\n /**\n * @private\n */\n Layout.prototype.clearListElementBox = function (paragraph) {\n if (paragraph.childWidgets.length === 0) {\n return;\n }\n var line = paragraph.childWidgets[0];\n if (isNullOrUndefined(line.children)) {\n return;\n }\n for (var i = 0; i < line.children.length; i++) {\n if (line.children[i] instanceof ListTextElementBox) {\n line.children.splice(i, 1);\n i--;\n }\n else {\n break;\n }\n }\n };\n /**\n * Gets list number.\n * @param listFormat\n * @param document\n * @private\n */\n Layout.prototype.getListNumber = function (listFormat) {\n var list = this.viewer.getListById(listFormat.listId);\n var levelNumber = listFormat.listLevelNumber;\n var listLevel = this.getListLevel(list, listFormat.listLevelNumber);\n // tslint:disable-next-line:max-line-length\n var levelOverride = !isNullOrUndefined(list.levelOverrides) ? list.levelOverrides[levelNumber] : undefined;\n // If LevelOverride exists and have either override list level or StartAtOverride, then only list numbering will be restarted.\n // tslint:disable-next-line:max-line-length\n // if (!isNullOrUndefined(levelOverride) && !(document.renderedLevelOverrides.indexOf(levelOverride) > -1) && isNullOrUndefined(levelOverride.overrideListLevel)) {\n // //Add List Override style\n // document.renderedLevelOverrides.push(list.levelOverrides.getItem(levelNumber) as WLevelOverride);\n // if (document.renderedLists.containsKey((list.wordDocument as WordDocument).getAbstractListById(list.abstractListId))) {\n // tslint:disable-next-line:max-line-length\n // let levels: Dictionary = document.renderedLists.get((list.wordDocument as WordDocument).getAbstractListById(list.abstractListId));\n // if (levels.containsKey(levelNumber)) {\n // levels.remove(levelNumber);\n // }\n // }\n // }\n this.updateListValues(list, levelNumber);\n return this.getListText(list, levelNumber, listLevel);\n };\n /**\n * Gets list start value\n * @param listLevelNumber\n * @param list\n * @private\n */\n Layout.prototype.getListStartValue = function (listLevelNumber, list) {\n // tslint:disable-next-line:max-line-length\n var levelOverride = !isNullOrUndefined(list.levelOverrides) ? list.levelOverrides[listLevelNumber] : undefined;\n if (!isNullOrUndefined(levelOverride) && isNullOrUndefined(levelOverride.overrideListLevel)) {\n return levelOverride.startAt;\n }\n var listLevel = this.getListLevel(list, listLevelNumber);\n if (isNullOrUndefined(listLevel)) {\n return 0;\n }\n else {\n return listLevel.startAt;\n }\n };\n /**\n * Updates list values.\n * @param list\n * @param listLevelNumber\n * @param document\n */\n Layout.prototype.updateListValues = function (list, listLevelNumber) {\n if (!this.viewer.renderedLists.containsKey(this.viewer.getAbstractListById(list.abstractListId))) {\n var startVal = new Dictionary();\n this.viewer.renderedLists.add(this.viewer.getAbstractListById(list.abstractListId), startVal);\n var listLevel = this.getListLevel(list, listLevelNumber);\n for (var i = 0; i <= listLevelNumber; i++) {\n startVal.add(i, this.getListStartValue(i, list));\n }\n }\n else {\n // tslint:disable-next-line:max-line-length\n var levels = this.viewer.renderedLists.get(this.viewer.getAbstractListById(list.abstractListId));\n if (levels.containsKey(listLevelNumber)) {\n var startAt = levels.get(listLevelNumber);\n levels.set(listLevelNumber, startAt + 1);\n var levelNumber = listLevelNumber + 1;\n while (levelNumber < this.viewer.getAbstractListById(list.abstractListId).levels.length) {\n var listLevel = this.getListLevel(list, levelNumber);\n // if (!isNullOrUndefined(listLevel)) {\n if (levels.containsKey(levelNumber) && listLevel.restartLevel > listLevelNumber) {\n levels.remove(levelNumber);\n // if (document.renderedListLevels.indexOf(listLevel) > -1) {\n // document.renderedListLevels.pop();\n // }\n }\n // }\n levelNumber++;\n }\n }\n else {\n var levelNumber = listLevelNumber;\n while (!levels.containsKey(levelNumber - 1) && levelNumber > 0) {\n var listLevel = this.getListLevel(list, levelNumber - 1);\n // if (!isNullOrUndefined(listLevel)) {\n levels.add(levelNumber - 1, this.getListStartValue(levelNumber - 1, list));\n // if (document.renderedListLevels.indexOf(listLevel) !== -1) {\n // document.renderedListLevels.push(listLevel);\n // }\n // }\n levelNumber--;\n }\n var startAt = this.getListStartValue(listLevelNumber, list);\n levels.add(listLevelNumber, startAt);\n }\n }\n };\n /**\n * Gets list text\n * @param listAdv\n * @param listLevelNumber\n * @param currentListLevel\n * @param document\n */\n Layout.prototype.getListText = function (listAdv, listLevelNumber, currentListLevel) {\n var listText = currentListLevel.numberFormat;\n // tslint:disable-next-line:max-line-length\n if (this.viewer.renderedLists.containsKey(this.viewer.getAbstractListById(listAdv.abstractListId))) {\n var levels = this.viewer.renderedLists.get(this.viewer.getAbstractListById(listAdv.abstractListId));\n var keys = levels.keys;\n for (var i = 0; i < keys.length; i++) {\n var levelNumber = keys[i];\n var levelKey = '%' + (levelNumber + 1).toString();\n var listLevel = this.getListLevel(listAdv, levelNumber);\n if (listText.match(levelKey)) {\n if (levelNumber > listLevelNumber) {\n return '';\n }\n else if (levels.containsKey(levelNumber) && !isNullOrUndefined(listLevel)) {\n listText = listText.replace(levelKey, this.getListTextListLevel(listLevel, levels.get(levelNumber)));\n }\n else {\n listText = listText.replace(levelKey, '0');\n }\n }\n }\n }\n return listText;\n };\n /**\n * Gets the roman letter.\n * @param number\n * @private\n */\n Layout.prototype.getAsLetter = function (number) {\n // if (number <= 0) {\n // return '';\n // }\n var quotient = number / 26;\n var remainder = number % 26;\n if (remainder === 0) {\n //If number denotes the factor of 26, then reduce quotient by 1 and set remainder as 26.\n remainder = 26;\n quotient--;\n }\n //Index of A char in the ASCII table. \n var letter = String.fromCharCode(65 - 1 + remainder);\n var listValue = '';\n while (quotient >= 0) {\n listValue = listValue + letter.toString();\n quotient--;\n }\n return listValue;\n };\n /**\n * Gets list text using list level pattern.\n * @param listLevel\n * @param listValue\n * @private\n */\n Layout.prototype.getListTextListLevel = function (listLevel, listValue) {\n switch (listLevel.listLevelPattern) {\n case 'UpRoman':\n return this.getAsRoman(listValue).toUpperCase();\n case 'LowRoman':\n return this.getAsRoman(listValue).toLowerCase();\n case 'UpLetter':\n return this.getAsLetter(listValue).toUpperCase();\n case 'LowLetter':\n return this.getAsLetter(listValue).toLowerCase();\n case 'Arabic':\n return (listValue).toString();\n case 'LeadingZero':\n return this.getAsLeadingZero(listValue);\n case 'Number':\n return (listValue).toString();\n case 'OrdinalText':\n return (listValue).toString();\n case 'Ordinal':\n return (listValue).toString();\n case 'FarEast':\n return (listValue).toString();\n case 'Special':\n return (listValue).toString();\n default:\n return '';\n }\n };\n /**\n * Generate roman number for the specified number.\n * @param number\n * @param magnitude\n * @param letter\n */\n Layout.prototype.generateNumber = function (number, magnitude, letter) {\n var numberstring = '';\n while (number >= magnitude) {\n number -= magnitude;\n numberstring += letter;\n this.value = number;\n }\n return numberstring.toString();\n };\n /**\n * Gets list value prefixed with zero, if less than 10\n * @param listValue\n */\n Layout.prototype.getAsLeadingZero = function (listValue) {\n if (listValue < 10) {\n return '0' + listValue.toString();\n }\n else {\n return listValue.toString();\n }\n };\n /**\n * Gets the roman number\n * @param number\n * @private\n */\n Layout.prototype.getAsRoman = function (number) {\n var retval = '';\n this.value = number;\n retval += this.generateNumber(this.value, 1000, 'M');\n retval += this.generateNumber(this.value, 900, 'CM');\n retval += this.generateNumber(this.value, 500, 'D');\n retval += this.generateNumber(this.value, 400, 'CD');\n retval += this.generateNumber(this.value, 100, 'C');\n retval += this.generateNumber(this.value, 90, 'XC');\n retval += this.generateNumber(this.value, 50, 'L');\n retval += this.generateNumber(this.value, 40, 'XL');\n retval += this.generateNumber(this.value, 10, 'X');\n retval += this.generateNumber(this.value, 9, 'IX');\n retval += this.generateNumber(this.value, 5, 'V');\n retval += this.generateNumber(this.value, 4, 'IV');\n retval += this.generateNumber(this.value, 1, 'I');\n return retval.toString();\n };\n /**\n * Gets the list level\n * @param list\n * @param listLevelNumber\n * @private\n */\n Layout.prototype.getListLevel = function (list, listLevelNumber) {\n if (!isNullOrUndefined(list)) {\n var abstractList = this.viewer.getAbstractListById(list.abstractListId);\n if (!isNullOrUndefined(list) && abstractList.levels.length <= listLevelNumber\n && listLevelNumber >= 0 && listLevelNumber < 9) {\n this.addListLevels(abstractList);\n }\n var levelOverrideAdv = undefined;\n var level = false;\n level = (!isNullOrUndefined(list.levelOverrides))\n && !isNullOrUndefined(((levelOverrideAdv = list.levelOverrides[listLevelNumber])))\n && (!isNullOrUndefined(levelOverrideAdv.overrideListLevel));\n if (level) {\n return levelOverrideAdv.overrideListLevel;\n }\n else if (!isNullOrUndefined(abstractList) && listLevelNumber >= 0 && listLevelNumber < abstractList.levels.length) {\n return abstractList.levels[listLevelNumber];\n }\n }\n return undefined;\n };\n /**\n * Gets tab width\n * @param paragraph\n * @param viewer\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.getTabWidth = function (paragraph, viewer, index, lineWidget, element) {\n var fposition = 0;\n var isCustomTab = false;\n var tabs = paragraph.paragraphFormat.getUpdatedTabs();\n // Calculate hanging width\n if (viewer.clientActiveArea.x < viewer.clientArea.x) {\n return viewer.clientArea.x - viewer.clientActiveArea.x;\n }\n // Calculates tabwidth based on pageleftmargin and defaulttabwidth property\n var position = viewer.clientActiveArea.x -\n (viewer.clientArea.x - HelperMethods.convertPointToPixel(paragraph.paragraphFormat.leftIndent));\n var defaultTabWidth = HelperMethods.convertPointToPixel(viewer.defaultTabWidth);\n if (tabs.length === 0 && (position === 0 || defaultTabWidth === 0)) {\n return defaultTabWidth;\n }\n else {\n if (tabs.length > 0) {\n for (var i = 0; i < tabs.length; i++) {\n var tabPosition = HelperMethods.convertPointToPixel(tabs[i].position);\n if (tabs[i].tabJustification === 'Left' && position < tabPosition) {\n fposition = tabPosition;\n isCustomTab = true;\n if (!isNullOrUndefined(element)) {\n element.tabLeader = tabs[i].tabLeader;\n element.tabText = '';\n }\n break;\n }\n else if (tabs[i].tabJustification === 'Right' && position < tabPosition) {\n var tabwidth = tabPosition - position;\n var width = this.getRightTabWidth(index + 1, lineWidget, paragraph);\n if (width < tabwidth) {\n defaultTabWidth = tabwidth - width;\n }\n else {\n defaultTabWidth = 0;\n }\n fposition = position;\n isCustomTab = true;\n if (!isNullOrUndefined(element)) {\n element.tabLeader = tabs[i].tabLeader;\n element.tabText = '';\n }\n break;\n }\n }\n }\n if (!isCustomTab) {\n var diff = ((Math.round(position) * 100) % (Math.round(defaultTabWidth) * 100)) / 100;\n var cnt = (Math.round(position) - diff) / Math.round(defaultTabWidth);\n fposition = (cnt + 1) * defaultTabWidth;\n }\n return (fposition - position) > 0 ? fposition - position : defaultTabWidth;\n }\n };\n /**\n * Returns the right tab width\n * @param index - index of starting inline\n * @param lineWidget - current line widget\n * @param paragraph - current paragraph widget\n */\n Layout.prototype.getRightTabWidth = function (index, lineWidget, paragraph) {\n var width = 0;\n var isFieldCode = false;\n while (index < lineWidget.children.length) {\n var elementBox = lineWidget.children[index];\n if ((elementBox instanceof FieldElementBox) || (elementBox instanceof BookmarkElementBox) || isFieldCode) {\n if (elementBox instanceof FieldElementBox) {\n if (elementBox.fieldType === 0) {\n isFieldCode = true;\n }\n else if (elementBox.fieldType === 2) {\n isFieldCode = false;\n }\n }\n elementBox.width = 0;\n }\n else {\n this.viewer.textHelper.getTextSize(elementBox, elementBox.characterFormat);\n }\n if (elementBox instanceof TextElementBox && elementBox.text === '\\t') {\n return width;\n }\n else {\n width = width + elementBox.width;\n }\n index++;\n }\n return width;\n };\n /**\n * Gets split index by word.\n * @param clientActiveWidth\n * @param text\n * @param width\n * @param characterFormat\n */\n Layout.prototype.getSplitIndexByWord = function (clientActiveWidth, text, width, characterFormat) {\n var index = 0;\n var length = text.length;\n while (index < length) {\n var nextIndex = this.getTextIndexAfterSpace(text, index);\n if (nextIndex === 0 || nextIndex === length) {\n nextIndex = length - 1;\n }\n var splitWidth = width;\n if ((nextIndex < length - 1 || (nextIndex === length - 1 && text[nextIndex - 1] === ' ')) && index !== nextIndex) {\n splitWidth = this.viewer.textHelper.measureTextExcludingSpaceAtEnd(text.slice(0, nextIndex), characterFormat);\n }\n if (splitWidth <= clientActiveWidth) {\n index = nextIndex;\n }\n else {\n if (index === 0 && text[0] === ' ') {\n index = this.getTextIndexAfterSpace(text, 0);\n }\n break;\n }\n }\n return index;\n };\n /**\n * Gets split index by character\n * @param totalClientWidth\n * @param clientActiveAreaWidth\n * @param text\n * @param width\n * @param characterFormat\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.getTextSplitIndexByCharacter = function (totalClientWidth, clientActiveAreaWidth, text, width, characterFormat) {\n var length = text.length;\n for (var i = 0; i < length; i++) {\n var splitWidth = width;\n if (i + 1 < length) {\n splitWidth = this.viewer.textHelper.measureTextExcludingSpaceAtEnd(text.substring(0, i + 1), characterFormat);\n }\n if (splitWidth > clientActiveAreaWidth) {\n if (i === 0 && splitWidth > totalClientWidth) {\n //Handle for cell/section having client width less than a character's width.\n return (length > 1 && text[1] === ' ') ? this.getTextIndexAfterSpace(text, 1) : 1;\n }\n return i;\n }\n }\n return 0;\n };\n /**\n * Gets sub width.\n * @param justify\n * @param spaceCount\n * @param firstLineIndent\n */\n Layout.prototype.getSubWidth = function (lineWidget, justify, spaceCount, firstLineIndent) {\n var width = 0;\n var trimSpace = true;\n var lineText = '';\n for (var i = lineWidget.children.length - 1; i >= 0; i--) {\n var element = lineWidget.children[i];\n if (element instanceof TextElementBox) {\n var elementText = element.text;\n lineText = elementText + lineText;\n if (trimSpace && (elementText.trim() !== '' || elementText === '\\t')) {\n if (HelperMethods.endsWith(elementText)) {\n width += this.viewer.textHelper.measureTextExcludingSpaceAtEnd(elementText, element.characterFormat);\n }\n else {\n width += element.width;\n }\n trimSpace = false;\n }\n else if (!trimSpace) {\n width += element.width;\n }\n }\n else {\n lineText = 'a' + lineText;\n trimSpace = false;\n width += element.width;\n }\n if (!justify) {\n width = Math.round(width);\n }\n }\n lineText = lineText.trim();\n spaceCount = lineText.length - HelperMethods.removeSpace(lineText).length;\n var subWidth = (this.viewer.clientArea.width - firstLineIndent - width);\n if (subWidth <= 0 || (spaceCount === 0 && justify)) {\n spaceCount = 0;\n subWidth = 0;\n }\n else if (justify) {\n subWidth = subWidth / spaceCount;\n }\n return { 'subWidth': subWidth, 'spaceCount': spaceCount };\n };\n /**\n * Gets before spacing.\n * @param paragraph\n * @private\n */\n Layout.prototype.getBeforeSpacing = function (paragraph) {\n var beforeSpacing = 0;\n if (paragraph.previousWidget instanceof ParagraphWidget) {\n if (paragraph.previousWidget.paragraphFormat.afterSpacing < paragraph.paragraphFormat.beforeSpacing) {\n // tslint:disable-next-line:max-line-length\n beforeSpacing = paragraph.paragraphFormat.beforeSpacing - paragraph.previousWidget.paragraphFormat.afterSpacing;\n }\n }\n else {\n beforeSpacing = paragraph.paragraphFormat.beforeSpacing;\n }\n return beforeSpacing;\n };\n /**\n * Gets line spacing.\n * @param paragraph\n * @param maxHeight\n * @private\n */\n Layout.prototype.getLineSpacing = function (paragraph, maxHeight) {\n if (isNullOrUndefined(paragraph.paragraphFormat)) {\n return 0;\n }\n var lineSpacing = 0;\n switch (paragraph.paragraphFormat.lineSpacingType) {\n case 'AtLeast':\n case 'Exactly':\n lineSpacing = paragraph.paragraphFormat.lineSpacing;\n break;\n default:\n lineSpacing = paragraph.paragraphFormat.lineSpacing * maxHeight;\n break;\n }\n return lineSpacing;\n };\n /**\n * Checks whether current line is first line in a paragraph.\n * @param paragraph\n */\n Layout.prototype.isParagraphFirstLine = function (paragraph, line) {\n var widget = paragraph;\n if (isNullOrUndefined(widget.childWidgets) || widget.childWidgets.indexOf(line) === 0) {\n //If the line elements conatins the elements from previous paragraph then need to retun false.\n //Example scenario, Field start and field end in different paragraphs.\n if (line.children.length > 0 && !isNullOrUndefined(paragraph.previousWidget)\n && paragraph.previousWidget instanceof ParagraphWidget) {\n return line.paragraph.index !== paragraph.previousWidget.index;\n }\n return true; //If the line elements count is zero then also need to return true.\n }\n return false;\n };\n /**\n * Checks whether current line is last line in a paragraph.\n * @param paragraph\n */\n Layout.prototype.isParagraphLastLine = function (element) {\n var paragraph = element.line.paragraph;\n var lastLineWidget = paragraph.childWidgets[paragraph.childWidgets.length - 1];\n var lastInline = lastLineWidget.children[lastLineWidget.children.length - 1];\n if (element === lastInline) {\n // tslint:disable-next-line:max-line-length \n return (lastInline instanceof FieldElementBox) || ((!(lastInline instanceof TextElementBox && lastInline.text === '\\v')));\n }\n return false;\n };\n /**\n * Gets text index after space.\n * @param text\n * @param startIndex\n */\n Layout.prototype.getTextIndexAfterSpace = function (text, startIndex) {\n var length = text.length;\n var index = 0;\n index = text.indexOf(' ', startIndex) + 1;\n var nextIndex = index;\n if (nextIndex === 0 || nextIndex === length) {\n return nextIndex;\n }\n while (text[nextIndex] === ' ') {\n nextIndex++;\n if (nextIndex === length) {\n break;\n }\n }\n return nextIndex;\n };\n //#region Table\n /**\n * @private\n */\n Layout.prototype.moveNextWidgetsToTable = function (tableWidget, rowWidgets, moveFromNext) {\n var currentRow = moveFromNext ? rowWidgets[rowWidgets.length - 2] : rowWidgets[rowWidgets.length - 1];\n var rowIndex = currentRow.indexInOwner;\n var currentTable = tableWidget[tableWidget.length - 1];\n if (moveFromNext) {\n rowIndex += 1;\n }\n var nextWidgets = currentRow.containerWidget.childWidgets.splice(rowIndex);\n for (var i = 0; i < nextWidgets.length; i++) {\n currentTable.childWidgets.push(nextWidgets[i]);\n nextWidgets[i].containerWidget = currentTable;\n }\n };\n /**\n * Adds table cell widget.\n * @param cell\n * @param area\n * @param maxCellMarginTop\n * @param maxCellMarginBottom\n */\n Layout.prototype.addTableCellWidget = function (cell, area, maxCellMarginTop, maxCellMarginBottom) {\n //let tableCellWidget: TableCellWidget = new TableCellWidget(cell);\n var prevColumnIndex = 0;\n var cellspace = 0;\n var left = 0;\n var top = maxCellMarginTop;\n var right = 0;\n var bottom = maxCellMarginBottom;\n if (!isNullOrUndefined(cell.cellFormat)) {\n if (cell.cellFormat.containsMargins()) {\n // tslint:disable-next-line:max-line-length\n left = isNullOrUndefined(cell.cellFormat.leftMargin) ? HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.leftMargin) : HelperMethods.convertPointToPixel(cell.cellFormat.leftMargin);\n right = isNullOrUndefined(cell.cellFormat.rightMargin) ? HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.rightMargin) : HelperMethods.convertPointToPixel(cell.cellFormat.rightMargin);\n }\n else {\n left = HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.leftMargin);\n right = HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.rightMargin);\n }\n }\n cell.margin = new Margin(left, top, right, bottom);\n cell.width = HelperMethods.convertPointToPixel(cell.cellFormat.cellWidth);\n if (!isNullOrUndefined(cell.previousWidget)) {\n // tslint:disable-next-line:max-line-length\n prevColumnIndex = cell.previousWidget.columnIndex + cell.previousWidget.cellFormat.columnSpan;\n }\n // tslint:disable-next-line:max-line-length\n cellspace = !isNullOrUndefined(cell.ownerTable) && !isNullOrUndefined(cell.ownerTable.tableFormat) ? HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.cellSpacing) : 0;\n var prevSpannedCellWidth = 0;\n if (prevColumnIndex < cell.columnIndex) {\n // tslint:disable-next-line:max-line-length\n prevSpannedCellWidth = HelperMethods.convertPointToPixel(cell.ownerTable.tableHolder.getPreviousSpannedCellWidth(prevColumnIndex, cell.columnIndex));\n if (prevColumnIndex === 0) {\n prevSpannedCellWidth = prevSpannedCellWidth - cellspace / 2;\n }\n }\n cell.x = area.x + prevSpannedCellWidth + cell.margin.left;\n cell.y = area.y + cell.margin.top + cellspace;\n cell.width = cell.width - cell.margin.left - cell.margin.right;\n if (cellspace > 0) {\n cell.x += cellspace;\n if (cell.ownerTable.tableHolder.columns.length === 1) {\n cell.width -= cellspace * 2;\n }\n else if (cell.columnIndex === 0 || cell.columnIndex === cell.ownerTable.tableHolder.columns.length - 1) {\n cell.width -= ((cellspace * 2) - cellspace / 2);\n }\n else {\n cell.width -= cellspace;\n }\n }\n // update the margins values respect to layouting of borders.\n // tslint:disable-next-line:max-line-length\n //For normal table cells only left border is rendred. for last cell left and right border is rendred. this border widths are not included in margins.\n cell.leftBorderWidth = HelperMethods.convertPointToPixel(TableCellWidget.getCellLeftBorder(cell).getLineWidth());\n cell.x += cell.leftBorderWidth;\n cell.width -= cell.leftBorderWidth;\n if (cellspace > 0 || cell.cellIndex === cell.ownerRow.childWidgets.length - 1) {\n cell.rightBorderWidth = TableCellWidget.getCellRightBorder(cell).getLineWidth();\n cell.width -= cell.rightBorderWidth;\n }\n //Add the border widths to respective margin side.\n cell.margin.left = cell.margin.left + cell.leftBorderWidth;\n cell.margin.right = cell.margin.right + cell.rightBorderWidth;\n //cell.ownerWidget = owner;\n return cell;\n };\n /**\n * Adds specified row widget to table.\n * @param viewer\n * @param tableRowWidget\n * @param row\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.addWidgetToTable = function (viewer, tableCollection, rowCollection, row, endRowWidget) {\n //Adds table row widget to owner table widget.\n var tableWidget = tableCollection[0];\n var index = tableWidget.childWidgets.length;\n var prevWidget = undefined;\n var rowWidgetIndex = rowCollection.indexOf(row);\n if (rowWidgetIndex > 0) {\n prevWidget = rowCollection[rowWidgetIndex - 1];\n // Need to update on this further\n }\n else if (row.previousRenderedWidget instanceof TableRowWidget &&\n row.previousRenderedWidget.ownerTable.equals(row.ownerTable)) {\n // Need to update on this further\n prevWidget = row.previousRenderedWidget;\n }\n if (!isNullOrUndefined(prevWidget)) {\n tableWidget = prevWidget.containerWidget;\n // index = tableWidget.childWidgets.length;\n index = tableWidget.childWidgets.indexOf(prevWidget) + 1;\n if (Math.round(row.y) !== Math.round(prevWidget.y + prevWidget.height)) {\n var prevIndex = tableCollection.indexOf(tableWidget);\n if (prevIndex + 1 >= tableCollection.length) {\n //Creates new table widget for splitted rows.\n this.addTableWidget(viewer.clientActiveArea, tableCollection, true);\n }\n tableWidget = tableCollection[prevIndex + 1];\n index = tableWidget.childWidgets.length;\n }\n if (rowWidgetIndex > 0) {\n index = 0;\n }\n }\n this.updateRowHeightBySpannedCell(tableWidget, row, index);\n this.updateRowHeightByCellSpacing(tableCollection, row, viewer);\n //Remove widget from previous container after splitteing\n if (row.containerWidget && row.containerWidget !== tableWidget &&\n row.containerWidget.childWidgets.indexOf(row) !== -1) {\n row.containerWidget.childWidgets.splice(row.containerWidget.childWidgets.indexOf(row), 1);\n }\n if (tableWidget.childWidgets.indexOf(row) === -1) {\n tableWidget.childWidgets.splice(index, 0, row);\n }\n row.containerWidget = tableWidget;\n tableWidget.height = tableWidget.height + row.height;\n if (!isNullOrUndefined(tableWidget.containerWidget)\n && tableWidget.containerWidget.childWidgets.indexOf(tableWidget) >= 0 &&\n !(tableWidget.containerWidget instanceof HeaderFooterWidget)) {\n tableWidget.containerWidget.height += row.height;\n }\n this.updateHeightForRowWidget(viewer, false, tableCollection, rowCollection, row, false, endRowWidget);\n viewer.cutFromTop(row.y + row.height);\n };\n /**\n * Updates row height by spanned cell.\n * @param tableWidget\n * @param rowWidget\n * @param insertIndex\n * @param row\n * @private\n */\n Layout.prototype.updateRowHeightBySpannedCell = function (tableWidget, row, insertIndex) {\n var rowSpan = 1;\n if (tableWidget.childWidgets.length === 0 || insertIndex === 0) {\n this.updateRowHeight(row, row);\n return;\n }\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cellWidget = row.childWidgets[i];\n // tslint:disable-next-line:max-line-length\n rowSpan = (isNullOrUndefined(cellWidget) || isNullOrUndefined(cellWidget.cellFormat)) ? rowSpan : cellWidget.cellFormat.rowSpan;\n this.updateSpannedRowCollection(rowSpan, row);\n }\n if (!isNullOrUndefined(row.ownerTable)) {\n for (var i = 0; i < row.ownerTable.spannedRowCollection.length; i++) {\n if (row.ownerTable.spannedRowCollection.keys[i] === row.index) {\n // Back track to previous table row widgets and update it height if vertical merge ends with this row.\n for (var j = 0; j < insertIndex; j++) {\n var prevRowWidget = tableWidget.childWidgets[j];\n this.updateRowHeight(prevRowWidget, row);\n }\n row.ownerTable.spannedRowCollection.remove(row.ownerTable.spannedRowCollection.keys[i]);\n break;\n }\n }\n }\n };\n /**\n * Updates row height.\n * @param prevRowWidget\n * @param rowWidget\n * @param row\n */\n Layout.prototype.updateRowHeight = function (prevRowWidget, row) {\n var rowIndex = row.index;\n var rowSpan = 1;\n for (var i = 0; i < prevRowWidget.childWidgets.length; i++) {\n var cellWidget = prevRowWidget.childWidgets[i];\n // tslint:disable-next-line:max-line-length\n rowSpan = (isNullOrUndefined(cellWidget) || isNullOrUndefined(cellWidget.cellFormat)) ? rowSpan : cellWidget.cellFormat.rowSpan;\n //To update Row height- if row has row span value greater than 1, need to add it in spannedRowCollection \n this.updateSpannedRowCollection(rowSpan, row);\n if (rowIndex - cellWidget.rowIndex === rowSpan - 1) {\n var mergedCellHeight = cellWidget.y + cellWidget.height + cellWidget.margin.bottom - row.y;\n if (row.height < mergedCellHeight) {\n row.height = mergedCellHeight;\n }\n }\n }\n };\n //if row has row span value greater than 1, need to add it in spannedRowCollection\n Layout.prototype.updateSpannedRowCollection = function (rowSpan, row) {\n if (rowSpan > 1 && !isNullOrUndefined(row.ownerTable)) {\n //Checks the rowspan is already exist in the list\n if (!row.ownerTable.spannedRowCollection.containsKey(row.index + rowSpan - 1)) {\n row.ownerTable.spannedRowCollection.add(row.index + rowSpan - 1, row.index);\n }\n }\n };\n /**\n * Updates row height by cell spacing\n * @param rowWidget\n * @param viewer\n * @param row\n */\n Layout.prototype.updateRowHeightByCellSpacing = function (tableCollection, row, viewer) {\n if (row.ownerTable.tableFormat.cellSpacing > 0) {\n // In the Case of tableWidget is greater than one and rowWidget is start at the Top Position of the page. \n // In such case we have update the row height with half of cell spacing.\n // Remaining cases we have to update the entire hight\n // tslint:disable-next-line:max-line-length\n if (tableCollection.length > 1 && row.y === viewer.clientArea.y && viewer instanceof PageLayoutViewer) {\n row.height = row.height - HelperMethods.convertPointToPixel(row.ownerTable.tableFormat.cellSpacing) / 2;\n }\n }\n };\n /**\n * Checks whether row span is end.\n * @param row\n * @param viewer\n */\n Layout.prototype.isRowSpanEnd = function (row, viewer) {\n var rowIndex = row.index;\n var rowSpan = 1;\n for (var i = 0; i < viewer.splittedCellWidgets.length; i++) {\n var splittedCell = viewer.splittedCellWidgets[i];\n // tslint:disable-next-line:max-line-length\n rowSpan = (isNullOrUndefined(splittedCell) || isNullOrUndefined(splittedCell.cellFormat)) ? rowSpan : splittedCell.cellFormat.rowSpan;\n if (rowIndex - splittedCell.rowIndex === rowSpan - 1) {\n return true;\n }\n }\n return false;\n };\n /**\n * Checks whether vertical merged cell to continue or not.\n * @param row\n * @private\n */\n Layout.prototype.isVerticalMergedCellContinue = function (row) {\n var colIndex = 0;\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n if (colIndex < cell.columnIndex) {\n return true;\n }\n colIndex += cell.cellFormat.columnSpan;\n }\n return colIndex < row.ownerTable.tableHolder.columns.length;\n };\n /**\n * Splits widgets.\n * @param tableRowWidget\n * @param viewer\n * @param splittedWidget\n * @param row\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.splitWidgets = function (tableRowWidget, viewer, tableCollection, rowCollection, splittedWidget, isLastRow) {\n if (this.isFirstLineFitForRow(viewer.clientArea.bottom, tableRowWidget) && tableRowWidget.childWidgets.length > 0) {\n splittedWidget = this.getSplittedWidgetForRow(viewer.clientArea.bottom, tableCollection, rowCollection, tableRowWidget);\n if (viewer.splittedCellWidgets.length > 0 || splittedWidget !== tableRowWidget) {\n if (isLastRow) {\n for (var i = 0; i < splittedWidget.childWidgets.length; i++) {\n var cell = splittedWidget.childWidgets[i];\n if (cell.rowIndex !== splittedWidget.index) {\n splittedWidget.childWidgets.splice(i, 1);\n i--;\n }\n }\n }\n //Adds the splitted widget of a vertical merged cell, to next row widget in the next page.\n this.insertSplittedCellWidgets(viewer, tableCollection, splittedWidget, tableRowWidget.indexInOwner - 1);\n }\n }\n else {\n //Adds the splitted widget of a vertical merged cell, to next row widget in the next page.\n this.insertSplittedCellWidgets(viewer, tableCollection, splittedWidget, tableRowWidget.indexInOwner - 1);\n }\n return splittedWidget;\n };\n /**\n * Gets splitted widget for row.\n * @param bottom\n * @param tableRowWidget\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.getSplittedWidgetForRow = function (bottom, tableCollection, rowCollection, tableRowWidget) {\n var splittedWidget = undefined;\n var rowIndex = tableRowWidget.index;\n for (var i = 0; i < tableRowWidget.childWidgets.length; i++) {\n var cellWidget = tableRowWidget.childWidgets[i];\n var splittedCell = this.getSplittedWidget(bottom, true, tableCollection, rowCollection, cellWidget);\n if (!isNullOrUndefined(splittedCell)) {\n if (splittedCell === cellWidget) {\n //Returns if the whole content of the row does not fit in current page.\n return tableRowWidget;\n }\n if (tableRowWidget.childWidgets.indexOf(splittedCell) !== -1) {\n tableRowWidget.childWidgets.splice(tableRowWidget.childWidgets.indexOf(splittedCell), 1);\n }\n if (i === 0 || tableRowWidget.height < cellWidget.height + cellWidget.margin.top + cellWidget.margin.bottom) {\n tableRowWidget.height = cellWidget.height + cellWidget.margin.top + cellWidget.margin.bottom;\n }\n if (isNullOrUndefined(splittedWidget)) {\n //Creates new widget, to hold the splitted contents.\n splittedWidget = new TableRowWidget();\n splittedWidget.containerWidget = tableRowWidget.containerWidget;\n splittedWidget.index = tableRowWidget.index;\n splittedWidget.rowFormat = tableRowWidget.rowFormat;\n this.updateWidgetLocation(tableRowWidget, splittedWidget);\n splittedWidget.height = 0;\n rowCollection.push(splittedWidget);\n }\n var rowSpan = 1;\n // tslint:disable-next-line:max-line-length\n rowSpan = (isNullOrUndefined(splittedCell) || isNullOrUndefined(splittedCell.cellFormat)) ? rowSpan : splittedCell.cellFormat.rowSpan;\n if (rowIndex - splittedCell.rowIndex === rowSpan - 1\n && splittedWidget.height < splittedCell.height + splittedCell.margin.top + splittedCell.margin.bottom) {\n splittedWidget.height = splittedCell.height + splittedCell.margin.top + splittedCell.margin.bottom;\n }\n splittedWidget.childWidgets.push(splittedCell);\n splittedCell.containerWidget = splittedWidget;\n }\n }\n return splittedWidget;\n };\n /**\n * Updates widget to table.\n * @param row\n * @param viewer\n */\n /* tslint:disable */\n Layout.prototype.updateWidgetsToTable = function (tableWidgets, rowWidgets, row) {\n var rowHeight = this.getRowHeight(row, [row]);\n var viewer = this.viewer;\n //initializing row properties with default values.\n var isHeader = row.rowFormat.isHeader;\n var isAllowBreakAcrossPages = row.rowFormat.allowBreakAcrossPages;\n var heightType = row.rowFormat.heightType;\n var cellSpacing = 0;\n var count = 0;\n var tableRowWidget = row;\n var moveRowToNextTable = false;\n if (row.ownerTable.continueHeader && !isHeader) {\n row.ownerTable.continueHeader = false;\n }\n var isLastRow = false;\n cellSpacing = (!isNullOrUndefined(row.ownerTable) && !isNullOrUndefined(row.ownerTable.tableFormat)) ? HelperMethods.convertPointToPixel(row.ownerTable.tableFormat.cellSpacing) : 0;\n while (count < rowWidgets.length) {\n count = rowWidgets.length;\n if (row.ownerTable.isInsideTable || (viewer.splittedCellWidgets.length === 0 && tableRowWidget.y + tableRowWidget.height + cellSpacing <= viewer.clientArea.bottom)) {\n this.addWidgetToTable(viewer, tableWidgets, rowWidgets, tableRowWidget);\n if (viewer.splittedCellWidgets.length > 0 && isNullOrUndefined(rowWidgets[rowWidgets.length - 1].nextRow)) {\n count--;\n isLastRow = true;\n }\n }\n else {\n //Split widget for next page\n if (viewer.splittedCellWidgets.length > 0 && tableRowWidget.y + tableRowWidget.height <= viewer.clientArea.bottom) {\n var isRowSpanEnd = this.isRowSpanEnd(row, viewer);\n if (!isRowSpanEnd) {\n if (this.isVerticalMergedCellContinue(row) && tableRowWidget.y == viewer.clientArea.y) {\n this.insertSplittedCellWidgets(viewer, tableWidgets, tableRowWidget, tableRowWidget.indexInOwner - 1);\n }\n this.addWidgetToTable(viewer, tableWidgets, rowWidgets, tableRowWidget);\n continue;\n }\n }\n var splittedWidget = tableRowWidget;\n var tableWidget = tableWidgets[tableWidgets.length - 1];\n if (rowHeight + tableRowWidget.y > viewer.clientArea.bottom) {\n // tslint:disable-next-line:max-line-length\n if (!isAllowBreakAcrossPages || (isHeader && row.ownerTable.continueHeader) || (heightType === 'AtLeast' && HelperMethods.convertPointToPixel(row.rowFormat.height) < viewer.clientArea.bottom)) {\n // tslint:disable-next-line:max-line-length\n if ((heightType === 'AtLeast' && HelperMethods.convertPointToPixel(row.rowFormat.height) < viewer.clientActiveArea.height && isAllowBreakAcrossPages) || (heightType !== 'Exactly' && tableRowWidget.y === viewer.clientArea.y) || (heightType === 'Auto' && isAllowBreakAcrossPages)) {\n splittedWidget = this.splitWidgets(tableRowWidget, viewer, tableWidgets, rowWidgets, splittedWidget, isLastRow);\n }\n if (heightType === 'Exactly' && tableRowWidget.y === viewer.clientArea.y) {\n this.addWidgetToTable(viewer, tableWidgets, rowWidgets, tableRowWidget);\n count++;\n }\n if (isHeader && row.ownerTable.continueHeader) {\n row.ownerTable.header = false;\n row.ownerTable.continueHeader = false;\n row.ownerTable.headerHeight = 0;\n var pages = undefined;\n // if (viewer instanceof PageLayoutViewer) {\n pages = viewer.pages;\n // }\n if (!isNullOrUndefined(pages)) {\n for (var i = 0; i < pages.length; i++) {\n if (pages[i].repeatHeaderRowTableWidget) {\n pages[i].repeatHeaderRowTableWidget = false;\n }\n }\n }\n }\n }\n else {\n if ((heightType === 'Auto' || heightType === 'AtLeast') && isAllowBreakAcrossPages) {\n // tslint:disable-next-line:max-line-length\n if (!(HelperMethods.convertPointToPixel(row.rowFormat.height) > viewer.clientArea.bottom) || tableRowWidget.y === viewer.clientArea.y) {\n splittedWidget = this.splitWidgets(tableRowWidget, viewer, tableWidgets, rowWidgets, splittedWidget, isLastRow);\n }\n }\n else if (heightType === 'Exactly' && tableRowWidget.y === viewer.clientArea.y) {\n this.addWidgetToTable(viewer, tableWidgets, rowWidgets, tableRowWidget);\n count++;\n }\n }\n }\n else {\n var isInsertSplittedWidgets = false;\n // Splitting handled for the merged cell with allowRowBreakAcross pages. \n if (this.isVerticalMergedCellContinue(row) && (isAllowBreakAcrossPages ||\n (isInsertSplittedWidgets = tableRowWidget.y == viewer.clientArea.y))) {\n if (isInsertSplittedWidgets) {\n this.insertSplittedCellWidgets(viewer, tableWidgets, splittedWidget, tableRowWidget.indexInOwner - 1);\n }\n else {\n splittedWidget = this.splitWidgets(tableRowWidget, viewer, tableWidgets, rowWidgets, splittedWidget, isLastRow);\n }\n }\n else if (isLastRow && !isAllowBreakAcrossPages) {\n splittedWidget = this.splitWidgets(tableRowWidget, viewer, tableWidgets, rowWidgets, splittedWidget, isLastRow);\n }\n }\n //Create New table for splitted widget\n if (!isNullOrUndefined(splittedWidget)) {\n if (splittedWidget !== tableRowWidget) {\n this.addWidgetToTable(viewer, tableWidgets, rowWidgets, tableRowWidget, tableRowWidget.nextRow);\n //Updates the fitted table rows to current page.\n this.updateWidgetsToPage(tableWidgets, rowWidgets, row.ownerTable, tableRowWidget.nextRow);\n var index_2 = tableWidgets.indexOf(tableRowWidget.containerWidget);\n if (index_2 + 1 >= tableWidgets.length) {\n //Creates new table widget for splitted rows.\n this.addTableWidget(viewer.clientActiveArea, tableWidgets, true);\n }\n tableRowWidget = splittedWidget;\n }\n else {\n if (row.index > 0) {\n //Updates the fitted table rows to current page.\n this.updateWidgetsToPage(tableWidgets, rowWidgets, row.ownerTable, row);\n // Need to update on this further\n if (row.previousRenderedWidget instanceof TableRowWidget) {\n // Need to update on this further\n var prevWidget = row.previousRenderedWidget;\n if (HelperMethods.round(tableRowWidget.y, 2) === HelperMethods.round(prevWidget.y + prevWidget.height, 2)) {\n var prevIndex = tableWidgets.indexOf(prevWidget.containerWidget);\n if (prevIndex + 1 >= tableWidgets.length) {\n //Creates new table widget for splitted rows.\n this.addTableWidget(viewer.clientActiveArea, tableWidgets, true);\n }\n }\n else {\n //Creates new table widget for splitted rows.\n this.addTableWidget(viewer.clientActiveArea, tableWidgets, true);\n }\n }\n else {\n //Creates new table widget for splitted rows.\n this.addTableWidget(viewer.clientActiveArea, tableWidgets, true);\n }\n }\n moveRowToNextTable = true;\n count--;\n }\n tableWidget = tableWidgets[tableWidgets.length - 1];\n var prevBodyWidget = undefined;\n if (tableWidgets.length > 1) {\n //Get Previous Splitted Widget container\n prevBodyWidget = tableWidgets[tableWidgets.length - 2].containerWidget;\n }\n else {\n var previousBlock = row.ownerTable.previousRenderedWidget;\n prevBodyWidget = previousBlock.containerWidget;\n }\n var pageIndex = 0;\n if (!isNullOrUndefined(prevBodyWidget)) {\n pageIndex = viewer.pages.indexOf(prevBodyWidget.page);\n }\n var index = row.ownerTable.containerWidget.index;\n var bodyWidget = void 0;\n var block = void 0;\n if (moveRowToNextTable && tableWidgets.length === 1) {\n block = tableWidgets[tableWidgets.length - 1];\n }\n else {\n block = tableWidgets[tableWidgets.length - 2];\n }\n bodyWidget = this.moveBlocksToNextPage(block);\n var curretTable = tableWidgets[tableWidgets.length - 1];\n //Move Next RowWidge to next page\n if (moveRowToNextTable) {\n // tslint:disable-next-line:max-line-length\n if (row.index === 0 && curretTable.containerWidget && curretTable.containerWidget.childWidgets.indexOf(curretTable) !== -1) {\n curretTable.containerWidget.childWidgets.splice(curretTable.containerWidget.childWidgets.indexOf(curretTable), 1);\n }\n }\n if (bodyWidget.childWidgets.indexOf(curretTable) !== -1) {\n bodyWidget.childWidgets.splice(bodyWidget.childWidgets.indexOf(curretTable), 1);\n }\n bodyWidget.childWidgets.unshift(curretTable);\n curretTable.containerWidget = bodyWidget;\n if (moveRowToNextTable && row.index > 0 || rowWidgets.length > 1) {\n this.moveNextWidgetsToTable(tableWidgets, rowWidgets, !moveRowToNextTable);\n }\n moveRowToNextTable = false;\n if (row.ownerTable.header && tableRowWidget.height < viewer.clientArea.bottom) {\n // if (viewer instanceof PageLayoutViewer) {\n viewer.currentRenderingPage.repeatHeaderRowTableWidget = true;\n // }\n //Updates table widgets location.\n viewer.updateClientAreaForBlock(row.ownerTable, true, tableWidgets);\n // tslint:disable-next-line:max-line-length\n //Update splitted row widget location. if header is repeated update the y position of splitted widget to header height.\n splittedWidget.x = splittedWidget.x;\n splittedWidget.y = tableWidget.y + row.ownerTable.headerHeight;\n // let cellspace: number = viewer instanceof PageLayoutViewer ? cellspacing / 2 : cellspacing;\n var cellspace = cellSpacing / 2;\n this.updateChildLocationForRow(tableWidget.y + row.ownerTable.headerHeight - cellspace, splittedWidget);\n }\n else {\n //Updates table widgets location.\n viewer.updateClientAreaForBlock(row.ownerTable, true, tableWidgets);\n // tslint:disable-next-line:max-line-length\n //Update splitted row widget location. if header is repeated update the y position of splitted widget to header height.\n splittedWidget.x = splittedWidget.x;\n splittedWidget.y = tableWidget.y;\n // let cellspace: number = viewer instanceof PageLayoutViewer ? cellspacing / 2 : cellspacing;\n var cellspace = cellSpacing / 2;\n this.updateChildLocationForRow(tableWidget.y - cellspace, splittedWidget);\n }\n }\n isLastRow = false;\n }\n if (isHeader && row.ownerTable.continueHeader) {\n row.ownerTable.header = true;\n row.ownerTable.headerHeight = rowHeight + row.ownerTable.headerHeight;\n }\n if (isHeader && !isNullOrUndefined(this.getHeader(row.ownerTable)) && row.index === this.getHeader(row.ownerTable).index) {\n var headerHeight = this.getHeaderHeight(row.ownerTable, row, rowWidgets);\n if (headerHeight > row.ownerTable.headerHeight || headerHeight > row.ownerTable.headerHeight) {\n row.ownerTable.headerHeight = headerHeight;\n }\n if (row.ownerTable.headerHeight > viewer.clientArea.height) {\n row.ownerTable.header = false;\n row.ownerTable.continueHeader = false;\n row.ownerTable.headerHeight = 0;\n var pages = viewer.pages;\n for (var i = 0; i < pages.length; i++) {\n if (pages[i].repeatHeaderRowTableWidget) {\n pages[i].repeatHeaderRowTableWidget = false;\n }\n }\n }\n }\n if (tableWidgets.length > 2 && row.ownerTable.header && tableRowWidget.height < viewer.clientActiveArea.bottom &&\n !viewer.currentRenderingPage.repeatHeaderRowTableWidget) {\n viewer.currentRenderingPage.repeatHeaderRowTableWidget = true;\n }\n }\n };\n /* tslint:enable */\n /**\n * Gets header.\n * @param table\n * @private\n */\n Layout.prototype.getHeader = function (table) {\n var header = undefined;\n var flag = true;\n table = table.getSplitWidgets()[0];\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row.rowFormat.isHeader) {\n header = row;\n }\n else {\n flag = false;\n }\n if (!flag) {\n break;\n }\n }\n return header;\n };\n /**\n * Gets header height.\n * @param ownerTable\n * @param row\n */\n Layout.prototype.getHeaderHeight = function (ownerTable, row, rowCollection) {\n var height = 0;\n if (row.ownerTable.childWidgets.length > 0 && ownerTable.childWidgets[0].rowFormat.isHeader) {\n for (var i = 0; i < ownerTable.childWidgets.length; i++) {\n var row_1 = ownerTable.childWidgets[i];\n if (row_1.rowFormat.isHeader) {\n height = height + this.getRowHeight(row_1, rowCollection);\n }\n else {\n break;\n }\n }\n }\n return height;\n };\n /**\n * Updates widgets to row.\n * @param cell\n */\n Layout.prototype.updateWidgetToRow = function (cell) {\n var viewer = this.viewer;\n //Adds table cell widget to owner row widget.\n var rowWidget = cell.ownerRow;\n var cellLeft = rowWidget.x;\n if (rowWidget.childWidgets.length > 0) {\n var lastWidget = rowWidget.childWidgets[rowWidget.childWidgets.length - 1];\n cellLeft = lastWidget.x + lastWidget.width + lastWidget.margin.right;\n }\n // rowWidget.childWidgets.push(cell);\n cell.containerWidget = rowWidget;\n //If the row height is set as Atleast then height is set to atleast height for the first cell of the row.\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(cell.ownerRow) && cell.ownerRow.rowFormat.heightType !== 'Exactly' && HelperMethods.convertPointToPixel(cell.ownerRow.rowFormat.height) > 0 && cell.cellIndex === 0) {\n rowWidget.height = rowWidget.height + HelperMethods.convertPointToPixel(cell.ownerRow.rowFormat.height);\n }\n //Add condition not cell merged vertically.\n if (cell.cellFormat.rowSpan === 1) {\n var cellHeight = cell.height + cell.margin.top + cell.margin.bottom;\n if (rowWidget.height - HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.cellSpacing) < cellHeight) {\n rowWidget.height = cellHeight + HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.cellSpacing);\n }\n }\n };\n /**\n * Updates height for row widget.\n * @param viewer\n * @param isUpdateVerticalPosition\n * @param rowWidget\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.updateHeightForRowWidget = function (viewer, isUpdateVerticalPosition, tableCollection, rowCollection, rowWidget, isLayouted, endRowWidget) {\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n var cellspacing = 0;\n var cellWidget = undefined;\n var childWidget = rowWidget.childWidgets[i];\n // if (childWidget instanceof TableCellWidget) {\n cellWidget = childWidget;\n // }\n var rowSpan = 1;\n rowSpan = cellWidget.cellFormat.rowSpan;\n cellspacing = HelperMethods.convertPointToPixel(cellWidget.ownerTable.tableFormat.cellSpacing);\n if (rowSpan > 1) {\n var currentRowWidgetIndex = rowWidget.containerWidget.childWidgets.indexOf(rowWidget);\n // tslint:disable-next-line:max-line-length\n var rowSpanWidgetEndIndex = currentRowWidgetIndex + rowSpan - 1 - (rowWidget.index - cellWidget.rowIndex);\n if (viewer.clientArea.bottom < cellWidget.y + cellWidget.height + cellWidget.margin.bottom\n || rowSpanWidgetEndIndex >= currentRowWidgetIndex + 1) {\n this.splitSpannedCellWidget(cellWidget, tableCollection, rowCollection, viewer);\n }\n var spanEndRowWidget = rowWidget;\n if (rowSpanWidgetEndIndex > 0) {\n if (rowSpanWidgetEndIndex < rowWidget.containerWidget.childWidgets.length) {\n var childWidget_1 = rowWidget.containerWidget.childWidgets[rowSpanWidgetEndIndex];\n if (childWidget_1 instanceof TableRowWidget) {\n spanEndRowWidget = childWidget_1;\n if (spanEndRowWidget === endRowWidget) {\n spanEndRowWidget = rowWidget;\n }\n }\n }\n else {\n // tslint:disable-next-line:max-line-length\n spanEndRowWidget = rowWidget.containerWidget.childWidgets[rowWidget.containerWidget.childWidgets.length - 1];\n }\n }\n if (cellWidget.y + cellWidget.height + cellWidget.margin.bottom < spanEndRowWidget.y + spanEndRowWidget.height) {\n cellWidget.height = spanEndRowWidget.y + spanEndRowWidget.height - cellWidget.y - cellWidget.margin.bottom;\n // tslint:disable-next-line:max-line-length\n }\n else if (isLayouted && spanEndRowWidget && (spanEndRowWidget.y !== 0 && spanEndRowWidget.height !== 0) && cellWidget.y + cellWidget.height + cellWidget.margin.bottom > spanEndRowWidget.y + spanEndRowWidget.height) {\n spanEndRowWidget.height = cellWidget.y + cellWidget.height + cellWidget.margin.bottom - spanEndRowWidget.y;\n // tslint:disable-next-line:max-line-length\n //Update the next rowlayout widget location. Reason for the updation is previous row height is updated when cell height is greater. So already layouted next row location has to be updated again.\n // if (rowWidget === spanEndRowWidget && rowWidget.nextWidget instanceof TableRowWidget) {\n // let nextRow: TableRowWidget = rowWidget.nextWidget as TableRowWidget;\n // // Need to update on this further\n // // if (viewer.renderedElements.containsKey(nextRow)) {\n // // let nextWidget: TableRowWidget[] = viewer.renderedElements.get(nextRow) as TableRowWidget[];\n // // if (nextWidget.length > 0) {\n // // nextWidget[0].x = nextWidget[0].x;\n // // nextWidget[0].y = rowWidget.y + rowWidget.height;\n // // }\n // // }\n // }\n }\n }\n else {\n if (cellspacing > 0) {\n // In the Case of tableWidget is greater than one and rowWidget is start at the Top Position of the page. \n // In such case we have update the cell height with half of cell spacing.\n // Remaining cases we have to update the entire hight\n // tslint:disable-next-line:max-line-length\n if (tableCollection.length > 1 && rowWidget.y === viewer.clientArea.y && viewer instanceof PageLayoutViewer) {\n cellspacing = cellspacing / 2;\n }\n }\n cellWidget.height = rowWidget.height - cellWidget.margin.top - cellWidget.margin.bottom - cellspacing;\n }\n this.updateHeightForCellWidget(viewer, tableCollection, rowCollection, cellWidget);\n var widget = rowWidget.containerWidget;\n while (widget.containerWidget instanceof Widget) {\n widget = widget.containerWidget;\n }\n var page = undefined;\n if (widget instanceof BodyWidget) {\n page = widget.page;\n }\n // tslint:disable-next-line:max-line-length\n if ((viewer instanceof PageLayoutViewer && viewer.visiblePages.indexOf(page) !== -1) || isUpdateVerticalPosition) {\n this.updateCellVerticalPosition(cellWidget, false, false);\n }\n //Renders the current table row contents, after relayout based on editing.\n // if (viewer instanceof PageLayoutViewer && (viewer as PageLayoutViewer).visiblePages.indexOf(page) !== -1) {\n // //Added proper undefined condition check for Asynchronous operation.\n // if (!isNullOrUndefined(rowWidget.tableRow) && !isNullOrUndefined(rowWidget.tableRow.rowFormat)) {\n // this.viewer.updateScrollBars();\n // //this.render.renderTableCellWidget(page, cellWidget);\n // }\n // }\n }\n };\n /**\n * Updates height for cell widget.\n * @param viewer\n * @param cellWidget\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.updateHeightForCellWidget = function (viewer, tableWidget, rowCollection, cellWidget) {\n for (var i = 0; i < cellWidget.childWidgets.length; i++) {\n if (cellWidget.childWidgets[i] instanceof TableWidget) {\n this.updateHeightForTableWidget(tableWidget, rowCollection, cellWidget.childWidgets[i]);\n }\n }\n };\n /**\n * Gets row height.\n * @param row\n * @private\n */\n Layout.prototype.getRowHeight = function (row, rowCollection) {\n var height = 0;\n if (row.rowFormat.heightType === 'Exactly') {\n height = row.rowFormat.height;\n }\n else {\n for (var i = 0; i < rowCollection.length; i++) {\n if (rowCollection[i] instanceof TableRowWidget) {\n height = rowCollection[i].height + height;\n }\n }\n height = Math.max(height, row.rowFormat.height);\n }\n return height;\n };\n /**\n * splits spanned cell widget.\n * @param cellWidget\n * @param viewer\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.splitSpannedCellWidget = function (cellWidget, tableCollection, rowCollection, viewer) {\n var splittedCell = this.getSplittedWidget(viewer.clientArea.bottom, false, tableCollection, rowCollection, cellWidget);\n if (!isNullOrUndefined(splittedCell)) {\n //Adds the splitted contents of a vertical merged cell, in order preserve in next page.\n viewer.splittedCellWidgets.push(splittedCell);\n }\n };\n /**\n * Inserts splitted cell widgets.\n * @param viewer\n * @param rowWidget\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.insertSplittedCellWidgets = function (viewer, tableCollection, rowWidget, previousRowIndex) {\n var left = rowWidget.x;\n var tableWidth = 0;\n tableWidth = HelperMethods.convertPointToPixel(rowWidget.ownerTable.tableHolder.tableWidth);\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n var cellWidget = rowWidget.childWidgets[i];\n if (Math.round(left) < Math.round(cellWidget.x - cellWidget.margin.left)) {\n if (this.insertRowSpannedWidget(rowWidget, viewer, left, i)) {\n i--;\n continue;\n }\n var length_1 = rowWidget.childWidgets.length;\n this.insertEmptySplittedCellWidget(rowWidget, tableCollection, left, i, previousRowIndex);\n if (length_1 < rowWidget.childWidgets.length) {\n i--;\n continue;\n }\n }\n left += cellWidget.margin.left + cellWidget.width + cellWidget.margin.right;\n if (i === rowWidget.childWidgets.length - 1 && Math.round(left) < Math.round(rowWidget.x + tableWidth)) {\n if (this.insertRowSpannedWidget(rowWidget, viewer, left, i + 1)) {\n continue;\n }\n this.insertEmptySplittedCellWidget(rowWidget, tableCollection, left, i + 1, previousRowIndex);\n continue;\n }\n }\n // tslint:disable-next-line:max-line-length\n // Special case: when the child widgets of row is equal to 0 then the splitted widgets in the viewer is added in the table row widgets. \n if ((isNullOrUndefined(rowWidget.childWidgets) || rowWidget.childWidgets.length === 0) && viewer.splittedCellWidgets.length > 0) {\n for (var j = 0; j < viewer.splittedCellWidgets.length; j++) {\n var widget = viewer.splittedCellWidgets[j];\n if (Math.round(left) <= Math.round(widget.x - widget.margin.left)) {\n if (this.insertRowSpannedWidget(rowWidget, viewer, left, j)) {\n j--;\n continue;\n }\n var count = rowWidget.childWidgets.length;\n this.insertEmptySplittedCellWidget(rowWidget, tableCollection, left, j, previousRowIndex);\n if (count < rowWidget.childWidgets.length) {\n j--;\n continue;\n }\n }\n left += widget.margin.left + widget.width + widget.margin.right;\n if (j === rowWidget.childWidgets.length - 1 && Math.round(left) <\n Math.round(rowWidget.x + tableWidth)) {\n if (this.insertRowSpannedWidget(rowWidget, viewer, left, j + 1)) {\n continue;\n }\n this.insertEmptySplittedCellWidget(rowWidget, tableCollection, left, j + 1, previousRowIndex);\n continue;\n }\n }\n }\n if (viewer.splittedCellWidgets.length > 0) {\n viewer.splittedCellWidgets = [];\n }\n };\n /**\n * Inserts spanned row widget.\n * @param rowWidget\n * @param viewer\n * @param left\n * @param index\n */\n Layout.prototype.insertRowSpannedWidget = function (rowWidget, viewer, left, index) {\n var cellSpacing = 0;\n if (rowWidget.ownerTable.tableFormat.cellSpacing > 0) {\n cellSpacing = HelperMethods.convertPointToPixel(rowWidget.ownerTable.tableFormat.cellSpacing);\n }\n for (var i = 0; i < viewer.splittedCellWidgets.length; i++) {\n var splittedCell = viewer.splittedCellWidgets[i];\n if (Math.round(left) === Math.round(splittedCell.x - splittedCell.margin.left)) {\n rowWidget.childWidgets.splice(index, 0, splittedCell);\n splittedCell.containerWidget = rowWidget;\n //If the splitted cell location differs from expected location update the location of row child widgets.\n if (splittedCell.y !== rowWidget.y + splittedCell.margin.top + cellSpacing) {\n this.updateChildLocationForRow(rowWidget.y, rowWidget);\n }\n viewer.splittedCellWidgets = [];\n return true;\n }\n }\n return false;\n };\n /**\n * Inserts empty splitted cell widgets.\n * @param rowWidget\n * @param left\n * @param index\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.insertEmptySplittedCellWidget = function (currentRow, tableCollection, left, index, previousRowIndex) {\n var tableWidget = tableCollection[tableCollection.length - 1];\n for (var i = previousRowIndex; i >= 0; i--) {\n var rowWidget = tableWidget.childWidgets[i];\n var previousLeft = rowWidget.x;\n for (var j = 0; j < rowWidget.childWidgets.length; j++) {\n var rowSpan = 1;\n var cellWidget = rowWidget.childWidgets[j];\n if (Math.round(left) === Math.round(previousLeft)) {\n rowSpan = (isNullOrUndefined(cellWidget) || isNullOrUndefined(cellWidget.cellFormat)) ? rowSpan :\n cellWidget.cellFormat.rowSpan;\n if (rowSpan > 1) {\n var emptyCellWidget = this.createCellWidget(cellWidget);\n currentRow.childWidgets.splice(index, 0, emptyCellWidget);\n emptyCellWidget.containerWidget = currentRow;\n }\n return;\n }\n previousLeft += cellWidget.margin.left + cellWidget.width + cellWidget.margin.right;\n }\n }\n };\n /**\n * Gets spllited widget.\n * @param bottom\n * @param splitMinimalWidget\n * @param cellWidget\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.getSplittedWidget = function (bottom, splitMinimalWidget, tableCollection, rowCollection, cellWidget) {\n var splittedWidget = undefined;\n if (cellWidget.y + cellWidget.height > bottom - cellWidget.margin.bottom) {\n for (var i = 0; i < cellWidget.childWidgets.length; i++) {\n if (cellWidget.childWidgets[i] instanceof ParagraphWidget) {\n var paragraphWidget = cellWidget.childWidgets[i];\n var splittedPara = this.getSplittedWidgetForPara(bottom - cellWidget.margin.bottom, paragraphWidget);\n if (!isNullOrUndefined(splittedPara)) {\n if (i === 0 && splittedPara === paragraphWidget) {\n //Returns if the whole content of the cell does not fit in current page.\n return cellWidget;\n }\n if (cellWidget.childWidgets.indexOf(splittedPara) !== -1) {\n cellWidget.childWidgets.splice(cellWidget.childWidgets.indexOf(splittedPara), 1);\n i--;\n }\n cellWidget.height -= splittedPara.height;\n if (isNullOrUndefined(splittedWidget)) {\n //Creates new widget, to hold the splitted contents.\n splittedWidget = this.createCellWidget(cellWidget);\n }\n splittedWidget.height += splittedPara.height;\n splittedWidget.childWidgets.push(splittedPara);\n splittedPara.containerWidget = splittedWidget;\n }\n }\n else {\n var tableWidget = cellWidget.childWidgets[i];\n var tableCol = [tableWidget];\n //Check for nested table.\n if (bottom - cellWidget.margin.bottom < tableWidget.y + tableWidget.height) {\n var tableHeight = tableWidget.height;\n // tslint:disable-next-line:max-line-length\n var splittedTable = this.getSplittedWidgetForTable(bottom - cellWidget.margin.bottom, tableCol, tableWidget);\n if (!isNullOrUndefined(splittedTable)) {\n if (i === 0 && splittedTable === tableWidget) {\n //Returns if the whole table does not fit in current page.\n return cellWidget;\n }\n if (cellWidget.childWidgets.indexOf(splittedTable) !== -1) {\n cellWidget.childWidgets.splice(cellWidget.childWidgets.indexOf(splittedTable), 1);\n i--;\n cellWidget.height -= splittedTable.height;\n }\n else {\n cellWidget.height -= tableHeight - tableWidget.height;\n }\n if (isNullOrUndefined(splittedWidget)) {\n //Creates new widget, to hold the splitted contents.\n splittedWidget = this.createCellWidget(cellWidget);\n }\n splittedWidget.height += splittedTable.height;\n splittedWidget.childWidgets.push(splittedTable);\n splittedTable.containerWidget = splittedWidget;\n }\n }\n }\n }\n }\n if (isNullOrUndefined(splittedWidget) && splitMinimalWidget) {\n //Creates new widget, to hold the splitted contents.\n splittedWidget = this.createCellWidget(cellWidget);\n }\n return splittedWidget;\n };\n /**\n * Gets list level pattern\n * @param value\n * @private\n */\n Layout.prototype.getListLevelPattern = function (value) {\n switch (value) {\n case 0:\n return 'Arabic';\n case 1:\n return 'UpRoman';\n case 2:\n return 'LowRoman';\n case 3:\n return 'UpLetter';\n case 4:\n return 'LowLetter';\n case 5:\n return 'Ordinal';\n case 6:\n return 'Number';\n case 7:\n return 'OrdinalText';\n case 8:\n return 'LeadingZero';\n case 9:\n return 'Bullet';\n case 10:\n return 'FarEast';\n case 11:\n return 'Special';\n default:\n return 'None';\n }\n };\n /**\n * Creates cell widget.\n * @param cell\n */\n Layout.prototype.createCellWidget = function (cell) {\n var cellWidget = new TableCellWidget();\n cellWidget.cellFormat = cell.cellFormat;\n cellWidget.index = cell.index;\n cellWidget.rowIndex = cell.rowIndex;\n cellWidget.columnIndex = cell.columnIndex;\n cellWidget.containerWidget = cell.containerWidget;\n this.updateWidgetLocation(cell, cellWidget);\n cellWidget.margin = cell.margin;\n cellWidget.leftBorderWidth = HelperMethods.convertPointToPixel(cell.leftBorderWidth);\n cellWidget.rightBorderWidth = HelperMethods.convertPointToPixel(cell.rightBorderWidth);\n return cellWidget;\n };\n /**\n * Create Table Widget\n */\n Layout.prototype.createTableWidget = function (table) {\n var newTable = new TableWidget();\n if (table.header) {\n newTable.header = table.header;\n newTable.headerHeight = table.headerHeight;\n }\n newTable.index = table.index;\n newTable.tableFormat = table.tableFormat;\n newTable.tableHolder = table.tableHolder;\n newTable.isGridUpdated = table.isGridUpdated;\n return newTable;\n };\n /**\n * Gets splitted widget for paragraph.\n * @param bottom\n * @param paragraphWidget\n */\n Layout.prototype.getSplittedWidgetForPara = function (bottom, paragraphWidget) {\n var lineBottom = paragraphWidget.y;\n var splittedWidget = undefined;\n for (var i = 0; i < paragraphWidget.childWidgets.length; i++) {\n var lineWidget = paragraphWidget.childWidgets[i];\n if (bottom < lineBottom + lineWidget.height) {\n if (i === 0) {\n if (lineWidget.paragraph.containerWidget instanceof TableCellWidget) {\n //checks first line of the page is exceed the page height\n if (lineWidget.paragraph.containerWidget.y === paragraphWidget.y) {\n lineBottom += lineWidget.height;\n continue;\n }\n }\n splittedWidget = paragraphWidget;\n break;\n }\n if (paragraphWidget.childWidgets.indexOf(lineWidget) !== -1) {\n paragraphWidget.childWidgets.splice(paragraphWidget.childWidgets.indexOf(lineWidget), 1);\n i--;\n }\n paragraphWidget.height -= lineWidget.height;\n if (isNullOrUndefined(splittedWidget)) {\n //Creates new widget, to hold the splitted contents.\n splittedWidget = new ParagraphWidget();\n splittedWidget.characterFormat = paragraphWidget.characterFormat;\n splittedWidget.paragraphFormat = paragraphWidget.paragraphFormat;\n splittedWidget.index = paragraphWidget.index;\n this.updateWidgetLocation(paragraphWidget, splittedWidget);\n splittedWidget.height = lineWidget.height;\n }\n else {\n splittedWidget.height += lineWidget.height;\n }\n splittedWidget.childWidgets.push(lineWidget);\n lineWidget.paragraph = splittedWidget;\n }\n lineBottom += lineWidget.height;\n }\n return splittedWidget;\n };\n /**\n * Gets splitted table widget.\n * @param bottom\n * @param tableWidget\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.getSplittedWidgetForTable = function (bottom, tableCollection, tableWidget) {\n var rowBottom = tableWidget.y;\n var splittedWidget = undefined;\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n var rowWidget = undefined;\n var childWidget = tableWidget.childWidgets[i];\n // if (childWidget instanceof TableRowWidget) {\n rowWidget = childWidget;\n // }\n var rowHeight = rowWidget.height;\n if (bottom < rowBottom + rowHeight || !isNullOrUndefined(splittedWidget)) {\n //ToDo: Check whether row included in vertical merge or AllowRowSplitbyPage is true, if so split row.\n //Checks if atleast first line fits in the client area. \n var splittedRow = undefined;\n var allowRowBreakAcrossPages = true;\n if (!isNullOrUndefined(rowWidget) && !isNullOrUndefined(rowWidget.rowFormat)) {\n allowRowBreakAcrossPages = rowWidget.rowFormat.allowBreakAcrossPages;\n }\n if (allowRowBreakAcrossPages) {\n // tslint:disable-next-line:max-line-length\n splittedRow = (isNullOrUndefined(splittedWidget) && this.isFirstLineFitForRow(bottom, rowWidget)) ? this.getSplittedWidgetForRow(bottom, tableCollection, [rowWidget], rowWidget) : rowWidget;\n }\n if (!isNullOrUndefined(splittedRow)) {\n if (i === 0 && splittedRow === rowWidget) {\n //Returns if the whole table does not fit in current page.\n return tableWidget;\n }\n if (tableWidget.childWidgets.indexOf(splittedRow) !== -1) {\n tableWidget.childWidgets.splice(tableWidget.childWidgets.indexOf(splittedRow), 1);\n i--;\n tableWidget.height -= splittedRow.height;\n }\n else {\n tableWidget.height -= rowHeight - rowWidget.height;\n }\n if (isNullOrUndefined(splittedWidget)) {\n //Creates new widget, to hold the splitted contents.\n splittedWidget = this.createTableWidget(tableWidget);\n this.updateWidgetLocation(tableWidget, splittedWidget);\n splittedWidget.height = splittedRow.height;\n }\n else {\n splittedWidget.height += splittedRow.height;\n }\n splittedWidget.childWidgets.push(splittedRow);\n splittedRow.containerWidget = splittedWidget;\n }\n }\n rowBottom += rowWidget.height;\n }\n return splittedWidget;\n };\n /**\n * Checks whether first line fits for paragraph or not.\n * @param bottom\n * @param paraWidget\n */\n Layout.prototype.isFirstLineFitForPara = function (bottom, paraWidget) {\n var lineWidget = paraWidget.childWidgets[0];\n var cellwidget = lineWidget.paragraph.containerWidget;\n // let document: WordDocument = undefined;\n // if (!isNullOrUndefined(lineWidget.paragraph.currentNode) && !isNullOrUndefined(cellwidget.containerWidget)) {\n // document = WordDocument.getDocumentOf(lineWidget.paragraph.currentNode);\n // }\n //checks first line of the page is exceed the page height\n if (this.viewer.isFirstLineFitInShiftWidgets) {\n if (this.viewer.clientActiveArea.y === this.viewer.clientArea.y && paraWidget.y + lineWidget.height >= bottom) {\n return true;\n }\n }\n else {\n // For nested tables,\n if (cellwidget.ownerTable.isInsideTable) {\n // Gets the container cell widgets, consider it as client area for the cell widget.\n var containerCellWidget = undefined;\n if (cellwidget.containerWidget instanceof TableRowWidget &&\n cellwidget.containerWidget.containerWidget instanceof TableWidget\n && cellwidget.containerWidget.containerWidget.containerWidget instanceof TableCellWidget) {\n containerCellWidget = cellwidget.containerWidget.containerWidget.containerWidget;\n }\n if (!isNullOrUndefined(containerCellWidget) && cellwidget.containerWidget.y === containerCellWidget.y\n && paraWidget.y + lineWidget.height >= bottom) {\n return true;\n }\n }\n else if (cellwidget.containerWidget.y === this.viewer.clientArea.y && paraWidget.y + lineWidget.height >= bottom) {\n return true;\n }\n }\n return (paraWidget.y + lineWidget.height <= bottom);\n };\n /**\n * Checks whether first line fits for table or not.\n * @param bottom\n * @param tableWidget\n * @private\n */\n Layout.prototype.isFirstLineFitForTable = function (bottom, tableWidget) {\n var rowWidget = undefined;\n var isFit = false;\n var childWidget = tableWidget.childWidgets[0];\n // if (childWidget instanceof TableRowWidget) {\n rowWidget = childWidget;\n // }\n if (!isNullOrUndefined(rowWidget)) {\n isFit = this.isFirstLineFitForRow(bottom, rowWidget);\n }\n return isFit;\n };\n /**\n * Checks whether first line fits for row or not.\n * @param bottom\n * @param rowWidget\n */\n Layout.prototype.isFirstLineFitForRow = function (bottom, rowWidget) {\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n var cellWidget = rowWidget.childWidgets[i];\n if (!this.isFirstLineFitForCell(bottom, cellWidget)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Checks whether first line fits for cell or not.\n * @param bottom\n * @param cellWidget\n */\n Layout.prototype.isFirstLineFitForCell = function (bottom, cellWidget) {\n if (cellWidget.childWidgets.length === 0) {\n return true;\n }\n if (cellWidget.childWidgets[0] instanceof ParagraphWidget) {\n var paraWidget = cellWidget.childWidgets[0];\n return this.isFirstLineFitForPara(bottom - cellWidget.margin.bottom, paraWidget);\n }\n else {\n var tableWidget = cellWidget.childWidgets[0];\n return this.isFirstLineFitForTable(bottom - cellWidget.margin.bottom, tableWidget);\n }\n };\n /**\n * Updates widget location.\n * @param widget\n * @param table\n */\n Layout.prototype.updateWidgetLocation = function (widget, table) {\n table.x = widget.x;\n table.y = widget.y;\n table.width = widget.width;\n };\n /**\n * Updates child location for table.\n * @param top\n * @param tableWidget\n * @private\n */\n Layout.prototype.updateChildLocationForTable = function (top, tableWidget) {\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n var rowWidget = tableWidget.childWidgets[i];\n rowWidget.x = rowWidget.x;\n rowWidget.y = top;\n this.updateChildLocationForRow(top, rowWidget);\n top += rowWidget.height;\n }\n };\n /**\n * Updates child location for row.\n * @param top\n * @param rowWidget\n * @private\n */\n Layout.prototype.updateChildLocationForRow = function (top, rowWidget) {\n var spacing = 0;\n if (rowWidget.ownerTable.tableFormat.cellSpacing > 0) {\n spacing = HelperMethods.convertPointToPixel(rowWidget.ownerTable.tableFormat.cellSpacing);\n }\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n var cellWidget = rowWidget.childWidgets[i];\n cellWidget.x = cellWidget.x;\n cellWidget.y = top + cellWidget.margin.top + spacing;\n this.updateChildLocationForCell(cellWidget.y, cellWidget);\n }\n };\n /**\n * Updates child location for cell.\n * @param top\n * @param cellWidget\n */\n Layout.prototype.updateChildLocationForCell = function (top, cellWidget) {\n for (var i = 0; i < cellWidget.childWidgets.length; i++) {\n cellWidget.childWidgets[i].x = cellWidget.childWidgets[i].x;\n cellWidget.childWidgets[i].y = top;\n if (cellWidget.childWidgets[i] instanceof TableWidget) {\n this.updateChildLocationForTable(top, cellWidget.childWidgets[i]);\n }\n top += cellWidget.childWidgets[i].height;\n }\n };\n /**\n * Updates cell vertical position.\n * @param cellWidget\n * @param isUpdateToTop\n * @param isInsideTable\n * @private\n */\n Layout.prototype.updateCellVerticalPosition = function (cellWidget, isUpdateToTop, isInsideTable) {\n if (cellWidget.ownerTable.containerWidget instanceof BodyWidget || isInsideTable) {\n var displacement = this.getDisplacement(cellWidget, isUpdateToTop);\n //Update Y position alone for the child widget of cell\n this.updateCellContentVerticalPosition(cellWidget, displacement, isUpdateToTop);\n }\n };\n /**\n * Updates cell content vertical position.\n * @param cellWidget\n * @param displacement\n * @param isUpdateToTop\n */\n Layout.prototype.updateCellContentVerticalPosition = function (cellWidget, displacement, isUpdateToTop) {\n if (displacement === 0) {\n return;\n }\n var location = cellWidget.y + displacement;\n for (var i = 0; i < cellWidget.childWidgets.length; i++) {\n if (cellWidget.childWidgets[i] instanceof ParagraphWidget) {\n cellWidget.childWidgets[i].y = location;\n }\n else {\n location = this.updateTableWidgetLocation(cellWidget.childWidgets[i], location, isUpdateToTop);\n }\n location = location + cellWidget.childWidgets[i].height;\n }\n };\n /**\n * Updates table widget location.\n * @param tableWidget\n * @param location\n * @param isUpdateToTop\n */\n Layout.prototype.updateTableWidgetLocation = function (tableWidget, location, isUpdateToTop) {\n tableWidget.y = location = location + tableWidget.topBorderWidth;\n var cellSpacing = 0;\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n var rowWidget = tableWidget.childWidgets[i];\n rowWidget.y = location;\n for (var j = 0; j < rowWidget.childWidgets.length; j++) {\n var cellWidget = rowWidget.childWidgets[j];\n cellWidget.y = location + cellWidget.margin.top + cellSpacing;\n this.updateCellVerticalPosition(cellWidget, isUpdateToTop, true);\n }\n location = location + rowWidget.height;\n }\n return location;\n };\n /**\n * Gets displacement.\n * @param cellWidget\n * @param isUpdateToTop\n */\n Layout.prototype.getDisplacement = function (cellWidget, isUpdateToTop) {\n //Gets the height of row\n var rowHeight = 0;\n var rowWidget = cellWidget.containerWidget;\n var padding = cellWidget.margin.top + cellWidget.margin.bottom;\n if (!isNullOrUndefined(cellWidget.cellFormat) && cellWidget.cellFormat.rowSpan > 1) {\n rowHeight = cellWidget.height;\n }\n else {\n rowHeight = ((!isNullOrUndefined(rowWidget) ? rowWidget.height : 0) - padding);\n }\n //Gets the height of content within the cell\n var cellContentHeight = this.getCellContentHeight(cellWidget);\n //Displacement field holds the value which has reduced from rowHeight and cellContentHeight\n var displacement = 0;\n if (rowHeight > cellContentHeight) {\n displacement = rowHeight - cellContentHeight;\n if (cellWidget.cellFormat.verticalAlignment === 'Center') {\n displacement = displacement / 2;\n }\n else if ((cellWidget.cellFormat.verticalAlignment === 'Top' || isUpdateToTop)) {\n displacement = 0;\n }\n }\n return displacement;\n };\n /**\n * Gets cell content height.\n * @param cellWidget\n */\n Layout.prototype.getCellContentHeight = function (cellWidget) {\n if (isNullOrUndefined(cellWidget.childWidgets)) {\n return 0;\n }\n var contentHeight = 0;\n for (var i = 0; i < cellWidget.childWidgets.length; i++) {\n if (cellWidget.childWidgets[i] instanceof ParagraphWidget) {\n contentHeight += cellWidget.childWidgets[i].height;\n }\n else {\n contentHeight += cellWidget.childWidgets[i].height;\n }\n }\n return contentHeight;\n };\n /**\n * Gets table left borders.\n * @param borders\n * @private\n */\n Layout.prototype.getTableLeftBorder = function (borders) {\n if (!isNullOrUndefined(borders.left)) {\n return borders.left;\n }\n else {\n var border = new WBorder(borders);\n border.lineStyle = 'Single';\n border.lineWidth = 0.66;\n return border;\n }\n };\n /**\n * Gets table right border.\n * @param borders\n * @private\n */\n Layout.prototype.getTableRightBorder = function (borders) {\n if (!isNullOrUndefined(borders.right)) {\n return borders.right;\n }\n else {\n var border = new WBorder(borders);\n border.lineStyle = 'Single';\n border.lineWidth = 0.66;\n return border;\n }\n };\n /**\n * Get table top border.\n * @param borders\n * @private\n */\n Layout.prototype.getTableTopBorder = function (borders) {\n if (!isNullOrUndefined(borders.top)) {\n return borders.top;\n }\n else {\n var border = new WBorder(borders);\n border.lineStyle = 'Single';\n border.lineWidth = 0.66;\n return border;\n }\n };\n /**\n * Gets table bottom border.\n * @param borders\n * @private\n */\n Layout.prototype.getTableBottomBorder = function (borders) {\n if (!isNullOrUndefined(borders.bottom)) {\n return borders.bottom;\n }\n else {\n var border = new WBorder(borders);\n border.lineStyle = 'Single';\n border.lineWidth = 0.66;\n return border;\n }\n };\n /**\n * Get diagonal cell up border.\n * @param tableCell\n * @private\n */\n Layout.prototype.getCellDiagonalUpBorder = function (tableCell) {\n var diagonalUpBorder = undefined;\n var cellBorder = undefined;\n cellBorder = tableCell.cellFormat.borders;\n diagonalUpBorder = cellBorder.diagonalUp;\n return diagonalUpBorder;\n };\n /**\n * Gets diagonal cell down border\n * @param tableCell\n * @private\n */\n Layout.prototype.getCellDiagonalDownBorder = function (tableCell) {\n var diagonalDownBorder = undefined;\n var cellBorder = undefined;\n cellBorder = tableCell.cellFormat.borders;\n diagonalDownBorder = cellBorder.diagonalDown;\n return diagonalDownBorder;\n };\n /**\n * Gets table width.\n * @param table\n * @private\n */\n Layout.prototype.getTableWidth = function (table) {\n var width = 0;\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n var rowWidth = 0;\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n rowWidth += HelperMethods.convertPointToPixel(cell.cellFormat.cellWidth);\n }\n if (width < rowWidth) {\n width = rowWidth;\n }\n }\n return width;\n };\n //#region shifting\n /**\n * @private\n */\n Layout.prototype.layoutNextItemsBlock = function (blockAdv, viewer) {\n var sectionIndex = blockAdv.bodyWidget.sectionIndex;\n var block = blockAdv;\n var splittedWidget = block.getSplitWidgets();\n var nextBlock = splittedWidget[splittedWidget.length - 1].nextRenderedWidget;\n if (isNullOrUndefined(nextBlock) || this.viewer.blockToShift === block) {\n this.viewer.blockToShift = undefined;\n }\n var updateNextBlockList = true;\n while (nextBlock instanceof BlockWidget && nextBlock.bodyWidget.sectionIndex === sectionIndex) {\n var currentWidget = undefined;\n var blocks = block.getSplitWidgets();\n currentWidget = blocks[blocks.length - 1];\n // if (viewer.fieldEndParagraph === block) {\n // //Sets field end paragraph to undefined, inorder to hold reLayouting with this paragraph.\n // viewer.fieldEndParagraph = undefined;\n // }\n block = nextBlock;\n if (viewer.blockToShift === block) {\n viewer.blockToShift = undefined;\n }\n updateNextBlockList = false;\n var nextWidget = undefined;\n nextWidget = block.getSplitWidgets()[0];\n // tslint:disable-next-line:max-line-length\n if (viewer.fieldStacks.length === 0 && !isNullOrUndefined(nextWidget) && currentWidget.containerWidget === nextWidget.containerWidget\n && (HelperMethods.round(nextWidget.y, 2) === HelperMethods.round(currentWidget.y + currentWidget.height, 2))) {\n if (!isNullOrUndefined(viewer.blockToShift)) {\n viewer.blockToShift = block;\n break;\n }\n if (isNullOrUndefined(nextWidget.nextWidget)) {\n break;\n }\n }\n updateNextBlockList = true;\n if (viewer.owner.isShiftingEnabled && viewer.fieldStacks.length === 0) {\n viewer.blockToShift = block;\n break;\n }\n else if (isNullOrUndefined(this.viewer.owner.editorModule) || !this.viewer.owner.editorModule.isInsertingTOC) {\n block = block.combineWidget(this.viewer);\n var paragraph = void 0;\n if (currentWidget.containerWidget !== block.containerWidget) {\n // tslint:disable-next-line:max-line-length\n this.updateContainerWidget(block, currentWidget.containerWidget, currentWidget.indexInOwner + 1, false);\n }\n if (block instanceof TableWidget) {\n this.clearTableWidget(block, true, true);\n block.isGridUpdated = false;\n paragraph = this.viewer.selection.getFirstParagraphInFirstCell(block);\n }\n else {\n paragraph = block;\n }\n if ((this.viewer.owner.isDocumentLoaded) && this.viewer.owner.editorModule) {\n this.viewer.owner.editorModule.updateWholeListItems(paragraph);\n }\n viewer.updateClientAreaForBlock(block, true);\n this.viewer.layout.layoutBlock(block, 0);\n viewer.updateClientAreaForBlock(block, false);\n }\n splittedWidget = nextBlock.getSplitWidgets();\n nextBlock = splittedWidget[splittedWidget.length - 1].nextRenderedWidget;\n }\n if (!viewer.owner.isShiftingEnabled || this.viewer.blockToShift !== block) {\n this.viewer.owner.editorModule.updateListItemsTillEnd(block, updateNextBlockList);\n }\n };\n /**\n * @private\n */\n Layout.prototype.updateClientAreaForLine = function (paragraph, startLineWidget, elementIndex) {\n //Clears the line widget starting from current line.\n var top = this.viewer.selection.getTop(startLineWidget);\n var left = this.viewer.clientArea.x;\n this.viewer.cutFromTop(top);\n this.viewer.cutFromLeft(left);\n };\n /**\n * @private\n */\n Layout.prototype.getParentTable = function (block) {\n var widget = block;\n while (widget.containerWidget) {\n if (widget.containerWidget instanceof BlockContainer) {\n return widget;\n }\n widget = widget.containerWidget;\n }\n return undefined;\n };\n /**\n * @private\n */\n Layout.prototype.reLayoutParagraph = function (paragraphWidget, lineIndex, elementBoxIndex) {\n if (this.viewer.blockToShift === paragraphWidget) {\n this.layoutBodyWidgetCollection(paragraphWidget.index, paragraphWidget.containerWidget, paragraphWidget, false);\n }\n // let isElementMoved: boolean = elementBoxIndex > 0;\n if (paragraphWidget.isInsideTable) {\n this.reLayoutTable(paragraphWidget);\n }\n else {\n this.reLayoutLine(paragraphWidget, lineIndex);\n }\n if (paragraphWidget.bodyWidget instanceof HeaderFooterWidget &&\n paragraphWidget.bodyWidget.headerFooterType.indexOf('Footer') !== -1) {\n this.shiftFooterChildLocation(paragraphWidget.bodyWidget, this.viewer);\n }\n };\n /**\n * @private\n */\n Layout.prototype.reLayoutTable = function (block) {\n //Get Top level owner of block\n var table = this.getParentTable(block);\n //Combine splitted table in to single table\n // this.combineTableWidgets(this.viewer, table, undefined);\n //Get Parent table\n var currentTable = table.combineWidget(this.viewer);\n currentTable.isGridUpdated = false;\n currentTable.buildTableColumns();\n currentTable.isGridUpdated = true;\n var bodyWidget = currentTable.containerWidget;\n if (this.viewer.owner.enableHeaderAndFooter || block.isInHeaderFooter) {\n bodyWidget.height -= currentTable.height;\n // tslint:disable-next-line:max-line-length\n this.viewer.updateHCFClientAreaWithTop(table.bodyWidget.sectionFormat, this.viewer.isBlockInHeader(table), bodyWidget.page);\n }\n else {\n this.viewer.updateClientArea(bodyWidget.sectionFormat, bodyWidget.page);\n }\n //Clear Hieght for all the content \n if (this.viewer.owner.isDocumentLoaded && this.viewer.owner.editorModule) {\n var block_1 = this.viewer.selection.getFirstParagraphInFirstCell(currentTable);\n this.viewer.owner.editorModule.updateWholeListItems(block_1);\n }\n this.viewer.updateClientAreaForBlock(currentTable, true);\n //Remove border width\n currentTable.x -= currentTable.leftBorderWidth;\n currentTable.y -= currentTable.topBorderWidth;\n //Update Client area for current position\n this.viewer.cutFromTop(currentTable.y);\n this.clearTableWidget(currentTable, true, true);\n this.layoutBlock(currentTable, 0, true);\n this.viewer.updateClientAreaForBlock(currentTable, false);\n this.layoutNextItemsBlock(currentTable, this.viewer);\n };\n /**\n * @private\n */\n Layout.prototype.clearTableWidget = function (table, clearPosition, clearHeight) {\n table.height = 0;\n if (clearPosition) {\n table.y = 0;\n table.x = 0;\n }\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n this.clearRowWidget(row, clearPosition, clearHeight);\n }\n };\n /**\n * @private\n */\n Layout.prototype.clearRowWidget = function (row, clearPosition, clearHeight) {\n row.height = 0;\n if (clearPosition) {\n row.y = 0;\n row.x = 0;\n }\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n this.clearCellWidget(cell, clearPosition, clearHeight);\n }\n };\n /**\n * @private\n */\n Layout.prototype.clearCellWidget = function (cell, clearPosition, clearHeight) {\n cell.height = 0;\n if (clearPosition) {\n cell.y = 0;\n cell.x = 0;\n }\n for (var i = 0; i < cell.childWidgets.length; i++) {\n var block = cell.childWidgets[i];\n if (block instanceof ParagraphWidget) {\n if (clearHeight) {\n block.height = 0;\n }\n }\n else {\n this.clearTableWidget(block, clearPosition, clearHeight);\n }\n }\n };\n /**\n * @param blockIndex\n * @param bodyWidget\n * @param block\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.layoutBodyWidgetCollection = function (blockIndex, bodyWidget, block, shiftNextWidget) {\n if (!isNullOrUndefined(this.viewer.owner)\n && this.viewer.owner.isLayoutEnabled) {\n if (bodyWidget instanceof BlockContainer) {\n var curretBlock = this.checkAndGetBlock(bodyWidget, blockIndex);\n if (isNullOrUndefined(curretBlock)) {\n return;\n }\n if (bodyWidget instanceof HeaderFooterWidget) {\n // tslint:disable-next-line:max-line-length\n this.viewer.updateHCFClientAreaWithTop(bodyWidget.sectionFormat, bodyWidget.headerFooterType.indexOf('Header') !== -1, bodyWidget.page);\n curretBlock.containerWidget.height -= curretBlock.height;\n }\n else {\n this.viewer.updateClientArea(bodyWidget.sectionFormat, bodyWidget.page);\n }\n if (blockIndex > 0) {\n var prevWidget = curretBlock.getSplitWidgets()[0].previousRenderedWidget;\n this.viewer.cutFromTop(prevWidget.y + prevWidget.height);\n if (curretBlock.containerWidget !== prevWidget.containerWidget) {\n // tslint:disable-next-line:max-line-length\n this.updateContainerWidget(curretBlock, prevWidget.containerWidget, prevWidget.indexInOwner + 1, false);\n }\n }\n var currentParagraph = void 0;\n curretBlock = curretBlock.combineWidget(this.viewer);\n if (curretBlock instanceof TableWidget) {\n this.clearTableWidget(curretBlock, true, true);\n curretBlock.isGridUpdated = false;\n currentParagraph = this.viewer.selection.getFirstParagraphInFirstCell(curretBlock);\n }\n else {\n currentParagraph = curretBlock;\n }\n if ((this.viewer.owner.isDocumentLoaded) && this.viewer.owner.editorModule) {\n this.viewer.owner.editorModule.updateWholeListItems(currentParagraph);\n }\n this.viewer.updateClientAreaForBlock(curretBlock, true);\n this.viewer.layout.layoutBlock(curretBlock, 0, true);\n this.viewer.updateClientAreaForBlock(curretBlock, false);\n if (shiftNextWidget) {\n this.shiftNextWidgets(curretBlock);\n }\n else {\n this.layoutNextItemsBlock(curretBlock, this.viewer);\n }\n }\n else if (bodyWidget instanceof TableCellWidget) {\n var table = this.viewer.layout.getParentTable(bodyWidget.ownerTable.getSplitWidgets()[0]);\n this.reLayoutTable(bodyWidget.ownerTable);\n this.layoutNextItemsBlock(table, this.viewer);\n }\n }\n };\n Layout.prototype.checkAndGetBlock = function (containerWidget, blockIndex) {\n var sectionIndex = containerWidget.index;\n while (containerWidget && containerWidget.index === sectionIndex) {\n if (containerWidget.childWidgets.length > 0 && containerWidget.firstChild.index <= blockIndex &&\n containerWidget.lastChild.index >= blockIndex) {\n for (var i = 0; i < containerWidget.childWidgets.length; i++) {\n var block = containerWidget.childWidgets[i];\n if (block.index === blockIndex) {\n return block;\n }\n }\n }\n if (containerWidget instanceof BodyWidget) {\n containerWidget = containerWidget.nextRenderedWidget;\n }\n else {\n break;\n }\n }\n return undefined;\n };\n //#endregion\n //#region Table\n /**\n * Layouts table.\n * @param table\n * @private\n */\n Layout.prototype.layoutTable = function (table, startIndex) {\n if (!table.isGridUpdated) {\n table.buildTableColumns();\n table.isGridUpdated = true;\n }\n var tableView = [table];\n this.addTableWidget(this.viewer.clientActiveArea, tableView);\n this.viewer.updateClientAreaTopOrLeft(table, true);\n var isHeader = table.childWidgets[0].rowFormat.isHeader;\n if (table.childWidgets.length > 0) {\n table.header = isHeader;\n table.continueHeader = isHeader;\n table.headerHeight = 0;\n }\n var row = table.childWidgets[startIndex];\n while (row) {\n row = this.layoutRow(tableView, row);\n row = row.nextRow;\n }\n this.updateWidgetsToPage(tableView, [], table);\n return tableView[tableView.length - 1];\n };\n /**\n * Adds table widget.\n * @param area\n * @param table\n * @private\n */\n Layout.prototype.addTableWidget = function (area, table, create) {\n var tableWidget = table[table.length - 1];\n if (create) {\n tableWidget = this.createTableWidget(tableWidget);\n table.push(tableWidget);\n }\n tableWidget.width = area.width;\n tableWidget.x = area.x;\n tableWidget.y = area.y;\n //Update the table height of tableWidget when cell spacing has been defined. \n if (tableWidget.tableFormat.cellSpacing > 0) {\n tableWidget.height = tableWidget.height + HelperMethods.convertPointToPixel(tableWidget.tableFormat.cellSpacing);\n // tslint:disable-next-line:max-line-length\n tableWidget.leftBorderWidth = HelperMethods.convertPointToPixel(this.getTableLeftBorder(tableWidget.tableFormat.borders).getLineWidth());\n tableWidget.rightBorderWidth = HelperMethods.convertPointToPixel(this.getTableRightBorder(tableWidget.tableFormat.borders).getLineWidth());\n // tslint:disable-next-line:max-line-length\n tableWidget.topBorderWidth = HelperMethods.convertPointToPixel(this.getTableTopBorder(tableWidget.tableFormat.borders).getLineWidth());\n tableWidget.bottomBorderWidth = HelperMethods.convertPointToPixel(this.getTableBottomBorder(tableWidget.tableFormat.borders).getLineWidth());\n tableWidget.x += tableWidget.leftBorderWidth;\n tableWidget.y += tableWidget.topBorderWidth;\n tableWidget.width -= tableWidget.leftBorderWidth;\n tableWidget.width -= tableWidget.rightBorderWidth;\n tableWidget.height += tableWidget.bottomBorderWidth;\n }\n return tableWidget;\n };\n /**\n * Updates widget to page.\n * @param table\n * @private\n */\n Layout.prototype.updateWidgetsToPage = function (tables, rows, table, endRowWidget) {\n var viewer = this.viewer;\n var tableWidget = tables[tables.length - 1];\n if (!table.isInsideTable) {\n this.updateHeightForTableWidget(tables, rows, tableWidget, endRowWidget);\n if (tableWidget.childWidgets.length > 0 && tableWidget.y !== tableWidget.childWidgets[0].y) {\n tableWidget.y = tableWidget.childWidgets[0].y;\n }\n // Need to update on this further\n //Adds the table widget to owner cell widget.\n // tslint:disable-next-line:max-line-length\n // (viewer.renderedElements.get(table.associatedCell)[viewer.renderedElements.get(table.associatedCell).length - 1] as TableCellWidget).childWidgets.push(tableWidget);\n // tableWidget.containerWidget = viewer.renderedElements.get(table.associatedCell)[viewer.renderedElements.get(table.associatedCell).length - 1] as BodyWidget;\n // tslint:disable-next-line:max-line-length\n // (viewer.renderedElements.get(table.associatedCell)[viewer.renderedElements.get(table.associatedCell).length - 1] as TableCellWidget).height = (viewer.renderedElements.get(table.associatedCell)[viewer.renderedElements.get(table.associatedCell).length - 1] as TableCellWidget).height + tableWidget.height;\n }\n if (table.tableFormat.cellSpacing > 0) {\n // tslint:disable-next-line:max-line-length\n if (tableWidget.y + tableWidget.height + HelperMethods.convertPointToPixel(table.tableFormat.cellSpacing) > viewer.clientArea.bottom && viewer instanceof PageLayoutViewer) {\n //update the table height when split to next page. Which is equivalent Ms Word Behaviour. \n //In Ms Word if the Table Split to next page the bottom spacing of the table will be half of the current spacing.\n //And the Remaining space will be used in next page top of the table.\n tableWidget.height = tableWidget.height - HelperMethods.convertPointToPixel(table.tableFormat.cellSpacing) / 2;\n }\n //Update the current Y position of current clientactivearea.\n viewer.cutFromTop(tableWidget.y + tableWidget.height);\n }\n if (table.bodyWidget instanceof HeaderFooterWidget) {\n table.containerWidget.height += table.height;\n if (this.viewer.owner.enableHeaderAndFooter && table.bodyWidget.headerFooterType.indexOf('Footer') !== -1) {\n this.shiftFooterChildLocation(table.bodyWidget, this.viewer);\n }\n }\n };\n /**\n * Updates height for table widget.\n * @param viewer\n * @param tableWidget\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Layout.prototype.updateHeightForTableWidget = function (tables, rows, tableWidget, endRowWidget) {\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n var rowWidget = tableWidget.childWidgets[i];\n if (rowWidget === endRowWidget) {\n break;\n }\n this.updateHeightForRowWidget(this.viewer, true, tables, rows, rowWidget, true, endRowWidget);\n }\n };\n //#endregion\n //#region Row\n /**\n * Layouts table row.\n * @param row\n * @private\n */\n Layout.prototype.layoutRow = function (tableWidget, row) {\n var viewer = this.viewer;\n var rowWidgets = [row];\n var widget = this.addTableRowWidget(viewer.clientActiveArea, rowWidgets);\n viewer.updateClientAreaForRow(row, true);\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n // tslint:disable-next-line:max-line-length\n this.layoutCell(cell, this.getMaxTopOrBottomCellMargin(row, 0) + row.topBorderWidth, this.getMaxTopOrBottomCellMargin(row, 1) + row.bottomBorderWidth, widget);\n }\n viewer.updateClientAreaForRow(row, false);\n var rows = [row];\n this.updateWidgetsToTable(tableWidget, rows, row);\n return rows[rows.length - 1];\n };\n /**\n * @param area\n * @param row\n */\n Layout.prototype.addTableRowWidget = function (area, row) {\n var rowWidget = row[row.length - 1];\n rowWidget.x = area.x + rowWidget.rowFormat.gridBeforeWidth;\n rowWidget.y = area.y;\n rowWidget.width = area.width;\n var borderWidth = 0;\n if (!isNullOrUndefined(rowWidget.ownerTable) && !isNullOrUndefined(rowWidget.ownerTable.tableFormat)\n && rowWidget.ownerTable.tableFormat.cellSpacing > 0) {\n rowWidget.height = rowWidget.height + HelperMethods.convertPointToPixel(rowWidget.ownerTable.tableFormat.cellSpacing);\n //Update the table height with the border width to layout the border when the cell spacing is defined..\n for (var j = 0; j < rowWidget.childWidgets.length; j++) {\n if (!isNullOrUndefined(rowWidget.childWidgets[j].cellFormat)\n && !isNullOrUndefined(rowWidget.childWidgets[j].cellFormat.borders)) {\n // tslint:disable-next-line:max-line-length\n var width = TableCellWidget.getCellBottomBorder(rowWidget.childWidgets[j]).getLineWidth();\n if (width > borderWidth) {\n borderWidth = width;\n }\n }\n }\n //Maximum border width is calculated and hold it in a variable to add with the padding of the cells.\n rowWidget.bottomBorderWidth = HelperMethods.convertPointToPixel(borderWidth);\n if (rowWidget.index > 0 && !isNullOrUndefined(rowWidget.previousWidget)) {\n var prevRow = rowWidget.previousWidget;\n borderWidth = 0;\n for (var i = 0; i < prevRow.childWidgets.length; i++) {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(prevRow.childWidgets[i].cellFormat) && !isNullOrUndefined(prevRow.childWidgets[i].cellFormat.borders)) {\n var value = TableCellWidget.getCellBottomBorder(prevRow.childWidgets[i]).getLineWidth();\n if (value > borderWidth) {\n borderWidth = value;\n }\n }\n }\n //Maximum border width is calculated and hold it in a variable to add with the padding of the cells.\n rowWidget.topBorderWidth = HelperMethods.convertPointToPixel(borderWidth);\n }\n }\n if (!isNullOrUndefined(rowWidget.childWidgets)) {\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(rowWidget.childWidgets[i].cellFormat) && !isNullOrUndefined(rowWidget.childWidgets[i].cellFormat.borders)) {\n var value = TableCellWidget.getCellTopBorder(rowWidget.childWidgets[i]).getLineWidth();\n if (value > borderWidth) {\n borderWidth = value;\n }\n }\n }\n }\n //Maximum border width is calculated and hold it in a variable to add with the padding of the cells.\n rowWidget.topBorderWidth = HelperMethods.convertPointToPixel(borderWidth);\n //Update the table height of tableWidget when cell spacing has been defined. \n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(rowWidget.ownerTable) && !isNullOrUndefined(rowWidget.ownerTable.tableFormat) && rowWidget.ownerTable.tableFormat.cellSpacing <= 0 && rowWidget.rowIndex === rowWidget.ownerTable.childWidgets.length - 1) {\n // Update the bottom width for last row .\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(rowWidget.childWidgets[i].cellFormat) && !isNullOrUndefined(rowWidget.childWidgets[i].cellFormat.borders)) {\n var value = TableCellWidget.getCellBottomBorder(rowWidget.childWidgets[i]).getLineWidth();\n if (value > borderWidth) {\n borderWidth = value;\n }\n }\n }\n //Maximum border width is calculated and hold it in a variable to add with the padding of the cells.\n rowWidget.bottomBorderWidth = HelperMethods.convertPointToPixel(borderWidth);\n }\n //tableRowWidget.ownerWidget = owner;\n return rowWidget;\n };\n /**\n * Gets maximum top or bottom cell margin.\n * @param row\n * @param topOrBottom\n */\n Layout.prototype.getMaxTopOrBottomCellMargin = function (row, topOrBottom) {\n if (isNullOrUndefined(row.childWidgets)) {\n return 0;\n }\n var value = 0;\n for (var i = 0; i < row.childWidgets.length; i++) {\n if (row.childWidgets.length > 0) {\n var cellFormat = row.childWidgets[i].cellFormat;\n if (cellFormat.containsMargins()) {\n if (topOrBottom === 0 && !isNullOrUndefined(cellFormat.topMargin) &&\n HelperMethods.convertPointToPixel(cellFormat.topMargin) > value) {\n value = HelperMethods.convertPointToPixel(cellFormat.topMargin);\n }\n else if (topOrBottom === 1 && !isNullOrUndefined(cellFormat.bottomMargin) &&\n HelperMethods.convertPointToPixel(cellFormat.bottomMargin) > value) {\n value = HelperMethods.convertPointToPixel(cellFormat.bottomMargin);\n }\n }\n else {\n var tableFormat = row.childWidgets[i].ownerTable.tableFormat;\n if (topOrBottom === 0 && HelperMethods.convertPointToPixel(tableFormat.topMargin) > value) {\n value = HelperMethods.convertPointToPixel(tableFormat.topMargin);\n }\n else if (topOrBottom === 1 && HelperMethods.convertPointToPixel(tableFormat.bottomMargin) > value) {\n value = HelperMethods.convertPointToPixel(tableFormat.bottomMargin);\n }\n }\n }\n }\n return value;\n };\n //#endregion Row\n //#region cell\n /**\n * Layouts cell\n * @param cell\n * @param maxCellMarginTop\n * @param maxCellMarginBottom\n */\n Layout.prototype.layoutCell = function (cell, maxCellMarginTop, maxCellMarginBottom, owner) {\n var viewer = this.viewer;\n this.addTableCellWidget(cell, viewer.clientActiveArea, maxCellMarginTop, maxCellMarginBottom);\n viewer.updateClientAreaForCell(cell, true);\n if (cell.childWidgets.length === 0) {\n var paragraphWidget = new ParagraphWidget();\n paragraphWidget.characterFormat = new WCharacterFormat();\n paragraphWidget.paragraphFormat = new WParagraphFormat();\n paragraphWidget.index = 0;\n var lineWidget = new LineWidget(undefined);\n paragraphWidget.childWidgets.push(lineWidget);\n cell.childWidgets.push(paragraphWidget);\n }\n for (var i = 0; i < cell.childWidgets.length; i++) {\n var block = cell.childWidgets[i];\n viewer.updateClientAreaForBlock(block, true);\n block.containerWidget = cell;\n this.layoutBlock(block, 0);\n viewer.updateClientAreaForBlock(block, false);\n }\n this.updateWidgetToRow(cell);\n viewer.updateClientAreaForCell(cell, false);\n };\n //endregion cell\n //#region Shifting\n /**\n * @private\n */\n Layout.prototype.shiftLayoutedItems = function () {\n if (isNullOrUndefined(this.viewer.blockToShift) || isNullOrUndefined(this.viewer.blockToShift.containerWidget)) {\n this.viewer.blockToShift = undefined;\n return;\n }\n var block = this.viewer.blockToShift;\n var sectionIndex = block.bodyWidget.index;\n this.reLayoutOrShiftWidgets(block, this.viewer);\n var updateNextBlockList = true;\n // If flow layout, then all sections are in single page. Hence need to update till last block of last section.\n // Todo: For page layout and section break continuous, need to handle the same.\n var splittedWidget = block.getSplitWidgets();\n var nextBlock = splittedWidget[splittedWidget.length - 1].nextRenderedWidget;\n while (nextBlock instanceof BlockWidget && nextBlock.bodyWidget.index === sectionIndex) {\n var currentWidget = undefined;\n var blocks = block.getSplitWidgets();\n currentWidget = blocks[blocks.length - 1];\n block = nextBlock;\n updateNextBlockList = false;\n var nextWidget = undefined;\n blocks = block.getSplitWidgets();\n if (block instanceof ParagraphWidget) {\n nextWidget = blocks[0];\n }\n else {\n if (block instanceof TableWidget) {\n nextWidget = blocks[0];\n }\n }\n if (currentWidget.containerWidget === nextWidget.containerWidget\n && (HelperMethods.round(nextWidget.y, 2) === HelperMethods.round(this.viewer.clientActiveArea.y, 2)) &&\n isNullOrUndefined(nextWidget.nextWidget)) {\n break;\n }\n updateNextBlockList = true;\n this.reLayoutOrShiftWidgets(block, this.viewer);\n splittedWidget = block.getSplitWidgets();\n nextBlock = splittedWidget[splittedWidget.length - 1].nextRenderedWidget;\n }\n if (this.viewer.owner.editorModule) {\n this.viewer.owner.editorModule.updateListItemsTillEnd(block, updateNextBlockList);\n }\n this.viewer.blockToShift = undefined;\n var viewer = this.viewer;\n // if (viewer instanceof PageLayoutViewer) {\n viewer.removeEmptyPages();\n this.updateFieldElements();\n viewer.updateScrollBars();\n // }\n };\n /**\n * @private\n */\n Layout.prototype.updateFieldElements = function () {\n for (var i = 0; i < this.viewer.fields.length; i++) {\n var fieldBegin = this.viewer.fields[i];\n if (!isNullOrUndefined(this.viewer.selection)) {\n var fieldCode = this.viewer.selection.getFieldCode(fieldBegin);\n if (!isNullOrUndefined(fieldCode) && fieldCode.toLowerCase().match('numpages')) {\n var textElement = fieldBegin.fieldSeparator.nextNode;\n if (!isNullOrUndefined(textElement)) {\n textElement.text = this.viewer.pages.length.toString();\n var paragraph = fieldBegin.line.paragraph;\n if (!isNullOrUndefined(paragraph.bodyWidget) && !isNullOrUndefined(paragraph.bodyWidget.page)) {\n var lineIndex = paragraph.childWidgets.indexOf(fieldBegin.line);\n var elementIndex = fieldBegin.line.children.indexOf(textElement);\n this.reLayoutParagraph(paragraph, lineIndex, elementIndex);\n }\n }\n }\n }\n }\n };\n Layout.prototype.reLayoutOrShiftWidgets = function (blockAdv, viewer) {\n var reLayoutItems = false;\n var block = blockAdv;\n // if (block instanceof ParagraphWidget) {\n // reLayoutItems = viewer.renderedElements.get(block as ParagraphWidget).length === 0;\n // } else {\n // reLayoutItems = viewer.renderedElements.get(block as TableWidget).length === 0;\n // }\n // if (reLayoutItems) {\n // //Handle layouting the block.\n // viewer.updateClientAreaForBlock(block, true);\n // this.layoutMod.layoutBlock(block);\n // viewer.updateClientAreaForBlock(block, false);\n // } else {\n //Handled to check client area and shift layouted widget.\n this.shiftWidgetsBlock(block, viewer);\n //Updates the list value of the rendered paragraph.\n if (this.viewer.owner.editorModule) {\n this.viewer.owner.editorModule.updateRenderedListItems(block);\n }\n // }\n };\n Layout.prototype.shiftWidgetsBlock = function (block, viewer) {\n if (block instanceof ParagraphWidget) {\n this.shiftWidgetsForPara(block, viewer);\n }\n else if (block instanceof TableWidget) {\n this.shiftWidgetsForTable(block, viewer);\n }\n };\n Layout.prototype.shiftWidgetsForPara = function (paragraph, viewer) {\n var prevBodyObj = this.getBodyWidgetOfPreviousBlock(paragraph, 0);\n var prevBodyWidget = prevBodyObj.bodyWidget;\n var index = prevBodyObj.index;\n var prevWidget = undefined;\n for (var i = 0; i < paragraph.getSplitWidgets().length; i++) {\n var widget = paragraph.getSplitWidgets()[i];\n if (!isNullOrUndefined(prevWidget)) {\n this.shiftToPreviousWidget(widget, viewer, prevWidget);\n if (isNullOrUndefined(widget.childWidgets) || widget.childWidgets.length === 0) {\n i--;\n continue;\n }\n prevWidget = undefined;\n if (prevBodyWidget !== widget.containerWidget) {\n prevBodyWidget = widget.containerWidget;\n }\n }\n if (this.isFitInClientArea(widget, viewer)) {\n //Check whether this widget is moved to previous container widget.\n prevWidget = widget;\n widget.y = viewer.clientActiveArea.y;\n viewer.cutFromTop(viewer.clientActiveArea.y + widget.height);\n //Moves the paragraph widget to previous body widget.\n if (!isNullOrUndefined(prevBodyWidget) && prevBodyWidget !== widget.containerWidget) {\n index++;\n this.updateContainerWidget(widget, prevBodyWidget, index, true);\n }\n }\n else {\n var isSplittedToNewPage = this.splitWidget(widget, viewer, prevBodyWidget, index + 1);\n prevWidget = undefined;\n if (prevBodyWidget !== widget.containerWidget) {\n prevBodyWidget = widget.containerWidget;\n i--;\n }\n index = prevBodyWidget.childWidgets.indexOf(widget);\n if (isSplittedToNewPage) {\n prevBodyWidget = paragraph.getSplitWidgets()[i + 1].containerWidget;\n }\n }\n }\n };\n /**\n * @private\n */\n Layout.prototype.shiftTableWidget = function (table, viewer) {\n var tables = [table];\n this.addTableWidget(this.viewer.clientActiveArea, tables);\n this.viewer.updateClientAreaTopOrLeft(table, true);\n var row = table.childWidgets[0];\n while (row) {\n row = this.shiftRowWidget(tables, row);\n row = row.nextRow;\n }\n this.updateWidgetsToPage(tables, [], table);\n return tables[tables.length - 1];\n };\n /**\n * @private\n */\n Layout.prototype.shiftRowWidget = function (tables, row) {\n var viewer = this.viewer;\n var rows = [row];\n var widget = this.addTableRowWidget(viewer.clientActiveArea, rows);\n viewer.updateClientAreaForRow(row, true);\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n // tslint:disable-next-line:max-line-length\n this.shiftCellWidget(cell, this.getMaxTopOrBottomCellMargin(row, 0) + row.topBorderWidth, this.getMaxTopOrBottomCellMargin(row, 1) + row.bottomBorderWidth);\n }\n viewer.updateClientAreaForRow(row, false);\n this.updateWidgetsToTable(tables, rows, row);\n return rows[rows.length - 1];\n };\n /**\n * @private\n */\n Layout.prototype.shiftCellWidget = function (cell, maxCellMarginTop, maxCellMarginBottom) {\n var viewer = this.viewer;\n this.addTableCellWidget(cell, viewer.clientActiveArea, maxCellMarginTop, maxCellMarginBottom);\n viewer.updateClientAreaForCell(cell, true);\n for (var i = 0; i < cell.childWidgets.length; i++) {\n var block = cell.childWidgets[i];\n viewer.updateClientAreaForBlock(block, true);\n if (block instanceof ParagraphWidget) {\n this.shiftParagraphWidget(block);\n }\n else {\n this.shiftTableWidget(block, viewer);\n }\n viewer.updateClientAreaForBlock(block, false);\n }\n this.updateWidgetToRow(cell);\n viewer.updateClientAreaForCell(cell, false);\n };\n /**\n * @private\n */\n Layout.prototype.shiftParagraphWidget = function (paragraph) {\n this.addParagraphWidget(this.viewer.clientActiveArea, paragraph);\n this.viewer.cutFromTop(this.viewer.clientActiveArea.y + paragraph.height);\n this.updateWidgetToPage(this.viewer, paragraph);\n };\n Layout.prototype.shiftWidgetsForTable = function (table, viewer) {\n var prevObj = this.getBodyWidgetOfPreviousBlock(table, 0);\n var prevBodyWidget = prevObj.bodyWidget;\n var index = prevObj.index;\n if (prevBodyWidget !== table.containerWidget) {\n this.updateContainerWidget(table, prevBodyWidget, index + 1, true);\n }\n if (table.isInHeaderFooter) {\n table.containerWidget.height -= table.height;\n }\n table.y = this.viewer.clientActiveArea.y;\n this.updateVerticalPositionToTop(table, true);\n var isPageLayout = viewer instanceof PageLayoutViewer;\n var combinedTable = table.combineWidget(this.viewer);\n this.viewer.layout.updateChildLocationForTable(combinedTable.y, combinedTable);\n this.clearTableWidget(combinedTable, true, false);\n this.shiftTableWidget(combinedTable, this.viewer);\n this.updateVerticalPositionToTop(table, false);\n };\n Layout.prototype.updateVerticalPositionToTop = function (table, isUpdateTop) {\n //Iterate the tableWidgets counts\n for (var i = 0; i < table.getSplitWidgets().length; i++) {\n var tablewidget = table.getSplitWidgets()[i];\n //Iterate the tableWidget child items\n for (var j = 0; j < tablewidget.childWidgets.length; j++) {\n var rowWidget = tablewidget.childWidgets[j];\n //Iterate the RowWidgets child items\n for (var k = 0; k < rowWidget.childWidgets.length; k++) {\n var cellWidget = rowWidget.childWidgets[k];\n //Iterate the RowWidgets child items\n this.viewer.layout.updateCellVerticalPosition(cellWidget, isUpdateTop, false);\n }\n }\n }\n };\n // tslint:disable-next-line:max-line-length\n Layout.prototype.splitWidget = function (paragraphWidget, viewer, previousBodyWidget, index) {\n var firstLine = paragraphWidget.childWidgets[0];\n var maxElementHeight = this.getMaxElementHeight(firstLine, viewer);\n var paragraphView = paragraphWidget.getSplitWidgets();\n var nextBodyWidget = paragraphWidget.containerWidget;\n if (viewer.clientActiveArea.height >= maxElementHeight) {\n var splittedWidget = undefined;\n var widgetIndex = paragraphView.indexOf(paragraphWidget);\n if (widgetIndex < (paragraphView.length - 1)) {\n splittedWidget = paragraphView[widgetIndex + 1];\n nextBodyWidget = splittedWidget.containerWidget;\n }\n else {\n splittedWidget = new ParagraphWidget();\n splittedWidget.index = paragraphWidget.index;\n splittedWidget.characterFormat = paragraphWidget.characterFormat;\n splittedWidget.paragraphFormat = paragraphWidget.paragraphFormat;\n splittedWidget.width = paragraphWidget.width;\n splittedWidget.x = paragraphWidget.x;\n splittedWidget.y = paragraphWidget.y;\n paragraphView.push(splittedWidget);\n }\n if (previousBodyWidget !== paragraphWidget.containerWidget) {\n this.updateContainerWidget(paragraphWidget, previousBodyWidget, index, true);\n }\n for (var i = paragraphWidget.childWidgets.length - 1; i > 0; i--) {\n if (this.isFitInClientArea(paragraphWidget, viewer)) {\n break;\n }\n else {\n var line = paragraphWidget.childWidgets[i];\n //Moves the line widget to next widget.\n this.updateParagraphWidgetInternal(line, splittedWidget, 0);\n }\n }\n if (isNullOrUndefined(splittedWidget.containerWidget) && splittedWidget.childWidgets.length > 0) {\n var y = viewer.clientActiveArea.y;\n // tslint:disable-next-line:max-line-length\n var clientArea = new Rect(viewer.clientArea.x, viewer.clientArea.y, viewer.clientArea.width, viewer.clientArea.height);\n var activeArea = new Rect(viewer.clientActiveArea.x, viewer.clientActiveArea.y, viewer.clientActiveArea.width, viewer.clientActiveArea.height);\n //Checks whether next node exists, else adds new page.\n nextBodyWidget = this.moveBlocksToNextPage(paragraphWidget);\n // nextBodyWidget = this.createOrGetNextBodyWidget(previousBodyWidget, viewer);\n nextBodyWidget.childWidgets.splice(0, 0, splittedWidget);\n nextBodyWidget.height += splittedWidget.height;\n splittedWidget.containerWidget = nextBodyWidget;\n if (nextBodyWidget.childWidgets.length === 1 && nextBodyWidget.firstChild instanceof ParagraphWidget &&\n nextBodyWidget.firstChild.equals(paragraphWidget)) {\n paragraphWidget.x = paragraphWidget.x;\n paragraphWidget.y = y;\n return true;\n }\n else {\n //Resetting Client area\n viewer.clientArea = clientArea;\n viewer.clientActiveArea = activeArea;\n }\n }\n }\n else {\n nextBodyWidget = this.createOrGetNextBodyWidget(previousBodyWidget, this.viewer);\n if (paragraphWidget.containerWidget !== nextBodyWidget) {\n nextBodyWidget = this.moveBlocksToNextPage(paragraphWidget);\n this.updateContainerWidget(paragraphWidget, nextBodyWidget, 0, true);\n }\n }\n if (previousBodyWidget === paragraphWidget.containerWidget) {\n paragraphWidget.y = viewer.clientActiveArea.y;\n viewer.cutFromTop(viewer.clientActiveArea.y + paragraphWidget.height);\n }\n else {\n //Updates client area based on next body widget.\n viewer.updateClientArea(nextBodyWidget.sectionFormat, nextBodyWidget.page);\n }\n return false;\n };\n Layout.prototype.getMaxElementHeight = function (lineWidget, viewer) {\n var height = 0;\n // tslint:disable-next-line:max-line-length\n if (lineWidget.children.length === 0 || ((lineWidget.children.length === 1 && lineWidget.children[0] instanceof ListTextElementBox) || (lineWidget.children.length === 2 && lineWidget.children[0] instanceof ListTextElementBox && lineWidget.children[1] instanceof ListTextElementBox))) {\n var topMargin = 0;\n var bottomMargin = 0;\n height = viewer.selection.getParagraphMarkSize(lineWidget.paragraph, topMargin, bottomMargin).height;\n height += topMargin;\n if (lineWidget.children.length > 0) {\n var element = lineWidget.children[0];\n if (height < element.margin.top + element.height) {\n height = element.margin.top + element.height;\n }\n }\n }\n else {\n for (var i = 0; i < lineWidget.children.length; i++) {\n var element = lineWidget.children[i];\n if (height < element.margin.top + element.height) {\n height = element.margin.top + element.height;\n }\n }\n }\n return height;\n };\n Layout.prototype.createOrGetNextBodyWidget = function (bodyWidget, viewer) {\n var nextBodyWidget = undefined;\n var pageIndex = 0;\n pageIndex = viewer.pages.indexOf(bodyWidget.page);\n var page = undefined;\n var index = undefined;\n index = bodyWidget.index;\n if (pageIndex === viewer.pages.length - 1\n || viewer.pages[pageIndex + 1].sectionIndex !== index) {\n var currentWidget = new BodyWidget();\n currentWidget.sectionFormat = bodyWidget.sectionFormat;\n currentWidget.index = bodyWidget.index;\n page = viewer.createNewPage(currentWidget);\n if (viewer.pages[pageIndex + 1].sectionIndex !== index) {\n viewer.insertPage(pageIndex + 1, page);\n }\n nextBodyWidget = page.bodyWidgets[0];\n }\n else {\n page = viewer.pages[pageIndex + 1];\n nextBodyWidget = page.bodyWidgets[0];\n }\n return nextBodyWidget;\n };\n Layout.prototype.isFitInClientArea = function (paragraphWidget, viewer) {\n var lastLine = paragraphWidget.childWidgets[paragraphWidget.childWidgets.length - 1];\n var height = paragraphWidget.height;\n var maxElementHeight = this.getMaxElementHeight(lastLine, viewer);\n if (lastLine.height > maxElementHeight) {\n height -= lastLine.height - maxElementHeight;\n }\n return viewer.clientActiveArea.height >= height;\n };\n // tslint:disable-next-line:max-line-length\n Layout.prototype.shiftToPreviousWidget = function (paragraphWidget, viewer, previousWidget) {\n for (var i = 0; i < paragraphWidget.childWidgets.length; i++) {\n var line = paragraphWidget.childWidgets[i];\n var maxElementHeight = this.getMaxElementHeight(line, viewer);\n if (viewer.clientActiveArea.height >= maxElementHeight) {\n //Moves the line widget to previous widget.\n this.updateParagraphWidgetInternal(line, previousWidget, previousWidget.childWidgets.length);\n i--;\n viewer.cutFromTop(viewer.clientActiveArea.y + line.height);\n if (isNullOrUndefined(paragraphWidget.childWidgets)) {\n break;\n }\n }\n else {\n var bodyWidget = previousWidget.containerWidget;\n var nextBodyWidget = this.createOrGetNextBodyWidget(bodyWidget, viewer);\n if (paragraphWidget.containerWidget !== nextBodyWidget) {\n nextBodyWidget = this.moveBlocksToNextPage(paragraphWidget);\n }\n if (bodyWidget !== nextBodyWidget) {\n this.updateContainerWidget(paragraphWidget, nextBodyWidget, 0, true);\n }\n //Updates client area based on next page.\n viewer.updateClientArea(nextBodyWidget.sectionFormat, nextBodyWidget.page);\n break;\n }\n }\n };\n Layout.prototype.updateParagraphWidgetInternal = function (lineWidget, newParagraphWidget, index) {\n if (!isNullOrUndefined(lineWidget.paragraph)) {\n lineWidget.paragraph.childWidgets.splice(lineWidget.paragraph.childWidgets.indexOf(lineWidget), 1);\n lineWidget.paragraph.height -= lineWidget.height;\n if (!isNullOrUndefined(lineWidget.paragraph.containerWidget)) {\n lineWidget.paragraph.containerWidget.height -= lineWidget.height;\n }\n // tslint:disable-next-line:max-line-length\n if (isNullOrUndefined(lineWidget.paragraph.childWidgets) || lineWidget.paragraph.childWidgets.length === 0) {\n lineWidget.paragraph.destroyInternal(this.viewer);\n }\n }\n newParagraphWidget.childWidgets.splice(index, 0, lineWidget);\n lineWidget.paragraph = newParagraphWidget;\n newParagraphWidget.height += lineWidget.height;\n if (!isNullOrUndefined(newParagraphWidget.containerWidget)) {\n newParagraphWidget.containerWidget.height += lineWidget.height;\n }\n };\n Layout.prototype.shiftNextWidgets = function (blockAdv) {\n var block = blockAdv;\n while (block.nextWidget instanceof BlockWidget) {\n block = block.nextWidget;\n this.reLayoutOrShiftWidgets(block, this.viewer);\n }\n };\n /**\n * @private\n */\n Layout.prototype.updateContainerWidget = function (widget, bodyWidget, index, destroyAndScroll) {\n if (!isNullOrUndefined(widget.containerWidget)) {\n widget.containerWidget.childWidgets.splice(widget.containerWidget.childWidgets.indexOf(widget), 1);\n widget.containerWidget.height -= bodyWidget.height;\n if ((isNullOrUndefined(widget.containerWidget.childWidgets) || widget.containerWidget.childWidgets.length === 0)\n && widget.containerWidget instanceof BodyWidget && widget.containerWidget !== bodyWidget && destroyAndScroll) {\n var page = widget.containerWidget.page;\n if (this.viewer.pages[this.viewer.pages.length - 1] === page &&\n this.viewer.visiblePages.indexOf(page) !== -1) {\n this.viewer.scrollToBottom();\n }\n if (isNullOrUndefined(page.nextPage) || page.nextPage.bodyWidgets[0].index !== widget.containerWidget.index) {\n widget.containerWidget.destroyInternal(this.viewer);\n }\n }\n }\n bodyWidget.childWidgets.splice(index, 0, widget);\n bodyWidget.height += bodyWidget.height;\n widget.containerWidget = bodyWidget;\n };\n Layout.prototype.getBodyWidgetOfPreviousBlock = function (block, index) {\n index = 0;\n var prevBodyWidget = undefined;\n var previousBlock = block.previousRenderedWidget;\n prevBodyWidget = previousBlock ? previousBlock.containerWidget : block.containerWidget;\n index = previousBlock ? prevBodyWidget.childWidgets.indexOf(previousBlock) : block.containerWidget.childWidgets.indexOf(block);\n return { bodyWidget: prevBodyWidget, index: index };\n };\n Layout.prototype.moveBlocksToNextPage = function (block) {\n var body = block.bodyWidget;\n var page = body.page;\n var pageIndex = page.index + 1;\n var nextPage = undefined;\n var nextBody = undefined;\n var insertPage = false;\n if (this.viewer.pages.length > pageIndex) {\n nextPage = this.viewer.pages[pageIndex];\n if (nextPage.bodyWidgets.length === 0 || !body.equals(nextPage.bodyWidgets[0])) {\n nextPage = undefined;\n insertPage = true;\n }\n else {\n nextBody = nextPage.bodyWidgets[0];\n this.viewer.updateClientArea(nextBody.sectionFormat, nextBody.page);\n }\n }\n if (isNullOrUndefined(nextPage)) {\n nextBody = this.createSplitBody(body);\n nextPage = this.viewer.createNewPage(nextBody, pageIndex);\n if (insertPage) {\n this.viewer.insertPage(pageIndex, nextPage);\n }\n }\n //tslint:disable :no-constant-condition\n do {\n var lastBlock = body.lastChild;\n if (block === lastBlock) {\n break;\n }\n body.childWidgets.pop();\n nextBody.childWidgets.splice(0, 0, lastBlock);\n lastBlock.containerWidget = nextBody;\n nextBody.height += lastBlock.height;\n } while (true);\n return nextBody;\n };\n Layout.prototype.createSplitBody = function (body) {\n var newBody = this.addBodyWidget(this.viewer.clientActiveArea);\n newBody.sectionFormat = body.sectionFormat;\n newBody.index = body.index;\n return newBody;\n };\n //endregion\n //#region Relayout Parargaph \n /**\n * Relayout Paragraph from specified line widget\n * @param paragraph Paragraph to reLayout\n * @param lineIndex start line index to reLayout\n * @private\n */\n Layout.prototype.reLayoutLine = function (paragraph, lineIndex) {\n if (this.viewer.owner.isDocumentLoaded && this.viewer.owner.editorModule) {\n this.viewer.owner.editorModule.updateWholeListItems(paragraph);\n }\n var lineWidget;\n if (paragraph.paragraphFormat.listFormat && paragraph.paragraphFormat.listFormat.listId !== -1) {\n lineWidget = paragraph.getSplitWidgets()[0].firstChild;\n }\n else {\n lineWidget = paragraph.childWidgets[lineIndex];\n }\n var lineToLayout = lineWidget.previousLine;\n if (isNullOrUndefined(lineToLayout)) {\n lineToLayout = lineWidget;\n }\n var currentParagraph = lineToLayout.paragraph;\n var bodyWidget = paragraph.containerWidget;\n bodyWidget.height -= paragraph.height;\n if (this.viewer.owner.enableHeaderAndFooter || paragraph.isInHeaderFooter) {\n // tslint:disable-next-line:max-line-length\n this.viewer.updateHCFClientAreaWithTop(paragraph.bodyWidget.sectionFormat, this.viewer.isBlockInHeader(paragraph), bodyWidget.page);\n }\n else {\n this.viewer.updateClientArea(bodyWidget.sectionFormat, bodyWidget.page);\n }\n this.viewer.updateClientAreaForBlock(paragraph, true);\n if (lineToLayout.paragraph.isEmpty()) {\n this.viewer.cutFromTop(paragraph.y);\n this.layoutParagraph(paragraph, 0);\n }\n else {\n this.updateClientAreaForLine(lineToLayout.paragraph, lineToLayout, 0);\n this.layoutListItems(lineToLayout.paragraph);\n if (lineToLayout.isFirstLine() && !isNullOrUndefined(paragraph.paragraphFormat)) {\n var firstLineIndent = -HelperMethods.convertPointToPixel(paragraph.paragraphFormat.firstLineIndent);\n this.viewer.updateClientWidth(firstLineIndent);\n }\n do {\n lineToLayout = this.layoutLine(lineToLayout, 0);\n paragraph = lineToLayout.paragraph;\n lineToLayout = lineToLayout.nextLine;\n } while (lineToLayout);\n this.updateWidgetToPage(this.viewer, paragraph);\n this.viewer.updateClientAreaForBlock(paragraph, false);\n }\n this.layoutNextItemsBlock(paragraph, this.viewer);\n };\n return Layout;\n}());\nexport { Layout };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Rect, ImageElementBox, ParagraphWidget, ListTextElementBox, TableRowWidget, TableWidget, TableCellWidget, FieldElementBox, TabElementBox } from './page';\nimport { Layout } from './layout';\nimport { HelperMethods } from '../editor/editor-helper';\n/**\n * @private\n */\nvar Renderer = /** @class */ (function () {\n function Renderer(viewer) {\n this.isPrinting = false;\n this.pageLeft = 0;\n this.pageTop = 0;\n this.isFieldCode = false;\n this.viewer = viewer;\n }\n Object.defineProperty(Renderer.prototype, \"pageCanvas\", {\n /**\n * Gets page canvas.\n * @private\n */\n get: function () {\n if (this.isPrinting) {\n if (isNullOrUndefined(this.pageCanvasIn)) {\n this.pageCanvasIn = document.createElement('canvas');\n this.pageCanvasIn.getContext('2d').save();\n }\n return this.pageCanvasIn;\n }\n return isNullOrUndefined(this.viewer) ? undefined : this.viewer.containerCanvas;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Renderer.prototype, \"selectionCanvas\", {\n /**\n * Gets selection canvas.\n */\n get: function () {\n return isNullOrUndefined(this.viewer) ? undefined : this.viewer.selectionCanvas;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Renderer.prototype, \"pageContext\", {\n /**\n * Gets page context.\n */\n get: function () {\n return this.pageCanvas.getContext('2d');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Renderer.prototype, \"selectionContext\", {\n /**\n * Gets selection context.\n */\n get: function () {\n return this.selectionCanvas.getContext('2d');\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets the color.\n */\n Renderer.prototype.getColor = function (color) {\n if (color.length > 0) {\n if (color[0] === '#') {\n if (color.length > 7) {\n return color.substr(0, 7);\n }\n }\n }\n return color;\n };\n /**\n * Renders widgets.\n * @param {Page} page\n * @param {number} left\n * @param {number} top\n * @param {number} width\n * @param {number} height\n * @private\n */\n Renderer.prototype.renderWidgets = function (page, left, top, width, height) {\n if (isNullOrUndefined(this.pageCanvas) || isNullOrUndefined(page)) {\n return;\n }\n this.pageContext.fillStyle = this.getColor(this.viewer.backgroundColor);\n this.pageContext.beginPath();\n this.pageContext.fillRect(left, top, width, height);\n this.pageContext.closePath();\n this.pageContext.strokeStyle = this.viewer.owner.pageOutline;\n this.pageContext.strokeRect(left, top, width, height);\n this.pageLeft = left;\n this.pageTop = top;\n if (this.isPrinting) {\n this.setPageSize(page);\n }\n else {\n this.pageContext.beginPath();\n this.pageContext.save();\n this.pageContext.rect(left, top, width, height);\n this.pageContext.clip();\n }\n if (page.headerWidget) {\n this.renderHFWidgets(page, page.headerWidget, width, true);\n }\n if (page.footerWidget) {\n this.renderHFWidgets(page, page.footerWidget, width, false);\n }\n for (var i = 0; i < page.bodyWidgets.length; i++) {\n this.render(page, page.bodyWidgets[i]);\n }\n if (this.viewer.owner.enableHeaderAndFooter && !this.isPrinting) {\n this.renderHeaderSeparator(page, this.pageLeft, this.pageTop, page.headerWidget);\n }\n this.pageLeft = 0;\n this.pageTop = 0;\n this.pageContext.restore();\n };\n /**\n * Sets page size.\n * @param {Page} page\n */\n Renderer.prototype.setPageSize = function (page) {\n this.pageContext.clearRect(0, 0, this.pageCanvas.width, this.pageCanvas.height);\n this.selectionContext.clearRect(0, 0, this.selectionCanvas.width, this.selectionCanvas.height);\n this.pageContext.restore();\n this.selectionContext.restore();\n var width = page.boundingRectangle.width;\n var height = page.boundingRectangle.height;\n var dpr = Math.max(1, window.devicePixelRatio || 1);\n if (this.pageCanvas.width !== width * dpr || this.pageCanvas.height !== height * dpr) {\n this.pageCanvas.height = height * dpr;\n this.pageCanvas.width = width * dpr;\n this.pageCanvas.style.height = height + 'px';\n this.pageCanvas.style.width = width + 'px';\n this.pageContext.globalAlpha = 1;\n this.pageContext.scale(dpr, dpr);\n }\n };\n /**\n * Renders header footer widget.\n * @param {Page} page\n * @param {HeaderFooterWidget} headFootWidget\n */\n Renderer.prototype.renderHFWidgets = function (page, widget, width, isHeader) {\n this.pageContext.globalAlpha = this.viewer.owner.enableHeaderAndFooter ? 1 : 0.65;\n var cliped = false;\n if (isHeader) {\n var topMargin = HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.topMargin);\n var widgetHeight = Math.max((widget.y + widget.height), topMargin);\n var headerFooterHeight = page.boundingRectangle.height / 100 * 40;\n if (widgetHeight > headerFooterHeight) {\n cliped = true;\n this.pageContext.beginPath();\n this.pageContext.save();\n this.pageContext.rect(this.pageLeft, this.pageTop, width, this.getScaledValue(headerFooterHeight));\n this.pageContext.clip();\n }\n }\n for (var i = 0; i < widget.childWidgets.length; i++) {\n var block = widget.childWidgets[i];\n this.renderWidget(page, block);\n }\n if (cliped) {\n this.pageContext.restore();\n }\n this.pageContext.globalAlpha = this.viewer.owner.enableHeaderAndFooter ? 0.65 : 1;\n };\n Renderer.prototype.renderHeaderSeparator = function (page, left, top, widget) {\n //Header Widget\n var topMargin = HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.topMargin);\n var y = this.getScaledValue(Math.max((widget.y + widget.height), topMargin));\n var pageWidth = this.getScaledValue(page.boundingRectangle.width);\n var ctx = this.pageContext;\n ctx.save();\n ctx.globalAlpha = 0.65;\n var headerFooterHeight = (this.getScaledValue(page.boundingRectangle.height) / 100) * 40;\n //Maximum header height limit \n y = Math.min(y, headerFooterHeight);\n //Dash line Separator\n this.renderDashLine(ctx, left, top + y, pageWidth);\n var type = this.getHeaderFooterType(page, true);\n ctx.font = '9pt Arial';\n var width = ctx.measureText(type).width;\n this.renderHeaderFooterMark(ctx, left + 5, top + y, width + 10, 20);\n this.renderHeaderFooterMarkText(ctx, type, left + 10, y + top + 15);\n if (page.footerWidget) {\n //Footer Widget\n var footerDistance = HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.footerDistance);\n // tslint:disable-next-line:max-line-length\n var footerHeight = this.getScaledValue(page.boundingRectangle.height) -\n this.getScaledValue(Math.max(page.footerWidget.height + footerDistance, HelperMethods.convertPointToPixel(page.footerWidget.sectionFormat.bottomMargin)));\n //Maximum footer height limit \n footerHeight = Math.max((this.getScaledValue(page.boundingRectangle.height) - headerFooterHeight), footerHeight);\n this.renderDashLine(ctx, left, top + footerHeight, pageWidth);\n type = this.getHeaderFooterType(page, false);\n width = ctx.measureText(type).width;\n this.renderHeaderFooterMark(ctx, left + 5, top + footerHeight - 20, width + 10, 20);\n this.renderHeaderFooterMarkText(ctx, type, left + 10, top + footerHeight - 5);\n ctx.restore();\n }\n };\n Renderer.prototype.getHeaderFooterType = function (page, isHeader) {\n var type;\n type = isHeader ? 'Header' : 'Footer';\n if (page.bodyWidgets[0].sectionFormat.differentFirstPage && this.viewer.pages.indexOf(page) === 0) {\n type = isHeader ? 'First Page Header' : 'First Page Footer';\n }\n else if (page.bodyWidgets[0].sectionFormat.differentOddAndEvenPages) {\n if ((this.viewer.pages.indexOf(page) + 1) % 2 === 0) {\n type = isHeader ? 'Even Page Header' : 'Even Page Footer';\n }\n else {\n type = isHeader ? 'Odd Page Header' : 'Odd Page Footer';\n }\n }\n return type;\n };\n Renderer.prototype.renderDashLine = function (ctx, x, y, width) {\n ctx.beginPath();\n ctx.strokeStyle = '#000000';\n ctx.lineWidth = 1;\n ctx.setLineDash([6, 4]);\n ctx.moveTo(x, y);\n ctx.lineTo(x + width, y);\n ctx.stroke();\n ctx.setLineDash([]);\n ctx.closePath();\n };\n Renderer.prototype.renderHeaderFooterMark = function (ctx, x, y, w, h) {\n ctx.beginPath();\n ctx.fillStyle = 'lightgray';\n ctx.fillRect(x, y, w, h);\n ctx.strokeStyle = 'black';\n ctx.strokeRect(x, y, w, h);\n ctx.closePath();\n };\n Renderer.prototype.renderHeaderFooterMarkText = function (ctx, content, x, y) {\n ctx.beginPath();\n ctx.fillStyle = '#000000';\n ctx.textBaseline = 'alphabetic';\n ctx.fillText(content, x, y);\n ctx.closePath();\n };\n /**\n * Renders body widget.\n * @param {Page} page\n * @param {BodyWidget} bodyWidget\n */\n Renderer.prototype.render = function (page, bodyWidget) {\n for (var i = 0; i < bodyWidget.childWidgets.length; i++) {\n var widget = bodyWidget.childWidgets[i];\n if (i === 0 && bodyWidget.childWidgets[0] instanceof TableWidget && page.repeatHeaderRowTableWidget) {\n // tslint:disable-next-line:max-line-length\n this.renderHeader(page, widget, this.viewer.layout.getHeader(bodyWidget.childWidgets[0]));\n }\n this.renderWidget(page, widget);\n }\n };\n /**\n * Renders block widget.\n * @param {Page} page\n * @param {Widget} widget\n */\n Renderer.prototype.renderWidget = function (page, widget) {\n if (widget instanceof ParagraphWidget) {\n this.renderParagraphWidget(page, widget);\n }\n else {\n this.renderTableWidget(page, widget);\n }\n };\n /**\n * Renders header.\n * @param {Page} page\n * @param {TableWidget} widget\n * @param {WRow} header\n * @private\n */\n Renderer.prototype.renderHeader = function (page, widget, header) {\n if (isNullOrUndefined(header)) {\n return;\n }\n var top = page.viewer.clientArea.y;\n for (var i = 0; i <= header.rowIndex; i++) {\n if (header.ownerTable.getSplitWidgets()[0].childWidgets.length === 0) {\n return;\n }\n var row = header.ownerTable.getSplitWidgets()[0].childWidgets[0];\n var headerWidget = row.clone();\n headerWidget.containerWidget = row.containerWidget;\n // tslint:disable-next-line:max-line-length\n page.viewer.updateClientAreaLocation(headerWidget, new Rect(page.viewer.clientArea.x, top, headerWidget.width, headerWidget.height));\n page.viewer.layout.updateChildLocationForRow(top, headerWidget);\n var cell = undefined;\n //Renders table cell outline rectangle - Border and background color.\n for (var j = 0; j < headerWidget.childWidgets.length; j++) {\n cell = headerWidget.childWidgets[j];\n this.renderTableCellWidget(page, cell);\n }\n top += headerWidget.height;\n }\n if (widget.y !== top) {\n //this.Location.Y = top;\n page.viewer.layout.updateChildLocationForTable(top, widget);\n }\n };\n /**\n * Renders paragraph widget.\n * @param {Page} page\n * @param {ParagraphWidget} paraWidget\n */\n Renderer.prototype.renderParagraphWidget = function (page, paraWidget) {\n var top = paraWidget.y;\n var left = paraWidget.x;\n for (var i = 0; i < paraWidget.childWidgets.length; i++) {\n var widget = paraWidget.childWidgets[i];\n this.renderLine(widget, page, left, top);\n top += widget.height;\n }\n };\n /**\n * Renders table widget.\n * @param {Page} page\n * @param {TableWidget} tableWidget\n */\n Renderer.prototype.renderTableWidget = function (page, tableWidget) {\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n var widget = tableWidget.childWidgets[i];\n this.renderTableRowWidget(page, widget);\n if (tableWidget.tableFormat.cellSpacing > 0) {\n this.renderTableOutline(tableWidget);\n }\n }\n };\n /**\n * Renders table row widget.\n * @param {Page} page\n * @param {Widget} rowWidget\n */\n Renderer.prototype.renderTableRowWidget = function (page, rowWidget) {\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n var widget = rowWidget.childWidgets[i];\n this.renderTableCellWidget(page, widget);\n }\n };\n /**\n * Renders table cell widget.\n * @param {Page} page\n * @param {TableCellWidget} cellWidget\n */\n Renderer.prototype.renderTableCellWidget = function (page, cellWidget) {\n if (!this.isPrinting) {\n if (this.getScaledValue(cellWidget.y, 2) + cellWidget.height * this.viewer.zoomFactor < 0 ||\n this.getScaledValue(cellWidget.y, 2) > this.viewer.visibleBounds.height) {\n return;\n }\n }\n var widgetHeight = 0;\n if (!this.isPrinting && page.viewer.owner.selection && page.viewer.owner.selection.selectedWidgets.length > 0) {\n page.viewer.owner.selection.addSelectionHighlightTable(this.selectionContext, cellWidget);\n }\n this.renderTableCellOutline(page.viewer, cellWidget);\n for (var i = 0; i < cellWidget.childWidgets.length; i++) {\n var widget = cellWidget.childWidgets[i];\n var width = cellWidget.width + cellWidget.margin.left - cellWidget.leftBorderWidth;\n this.clipRect(cellWidget.x, cellWidget.y, this.getScaledValue(width), this.getScaledValue(cellWidget.height));\n this.renderWidget(page, widget);\n this.pageContext.restore();\n }\n };\n /**\n * Renders line widget.\n * @param {LineWidget} lineWidget\n * @param {Page} page\n * @param {number} left\n * @param {number} top\n */\n Renderer.prototype.renderLine = function (lineWidget, page, left, top) {\n if (!this.isPrinting && page.viewer.owner.selection && page.viewer.owner.selection.selectedWidgets.length > 0) {\n page.viewer.owner.selection.addSelectionHighlight(this.selectionContext, lineWidget, top);\n }\n if (lineWidget.isFirstLine()) {\n left += HelperMethods.convertPointToPixel(lineWidget.paragraph.paragraphFormat.firstLineIndent);\n }\n if (this.viewer.owner.searchModule) {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(page.viewer.owner.searchModule.searchHighlighters) && page.viewer.owner.searchModule.searchHighlighters.containsKey(lineWidget)) {\n var widgetInfo = page.viewer.owner.searchModule.searchHighlighters.get(lineWidget);\n for (var i = 0; i < widgetInfo.length; i++) {\n this.pageContext.fillStyle = '#ffe97f';\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillRect(this.getScaledValue(widgetInfo[i].left, 1), this.getScaledValue(top, 2), this.getScaledValue(widgetInfo[i].width), this.getScaledValue(lineWidget.height));\n }\n }\n }\n for (var i = 0; i < lineWidget.children.length; i++) {\n var elementBox = lineWidget.children[i];\n if (elementBox instanceof FieldElementBox || this.isFieldCode ||\n (elementBox.width === 0 && elementBox.height === 0)) {\n if (this.isFieldCode) {\n elementBox.width = 0;\n }\n left += elementBox.width + elementBox.margin.left;\n this.toSkipFieldCode(elementBox);\n continue;\n }\n var underlineY = this.getUnderlineYPosition(lineWidget);\n if (!this.isPrinting) {\n if (this.getScaledValue(top + elementBox.margin.top, 2) + elementBox.height * this.viewer.zoomFactor < 0 ||\n this.getScaledValue(top + elementBox.margin.top, 2) > this.viewer.visibleBounds.height) {\n left += elementBox.width + elementBox.margin.left;\n continue;\n }\n }\n if (elementBox instanceof ListTextElementBox) {\n this.renderListTextElementBox(elementBox, left, top, underlineY);\n }\n else if (elementBox instanceof ImageElementBox) {\n this.renderImageElementBox(elementBox, left, top, underlineY);\n }\n else {\n this.renderTextElementBox(elementBox, left, top, underlineY);\n }\n left += elementBox.width + elementBox.margin.left;\n }\n };\n Renderer.prototype.toSkipFieldCode = function (element) {\n if (element instanceof FieldElementBox) {\n if (element.fieldType === 0) {\n if ((!isNullOrUndefined(element.fieldEnd) || element.hasFieldEnd)) {\n this.isFieldCode = true;\n }\n }\n else if (element.fieldType === 2 || element.fieldType === 1) {\n this.isFieldCode = false;\n }\n }\n };\n /**\n * Gets underline y position.\n * @param {LineWidget} lineWidget\n */\n Renderer.prototype.getUnderlineYPosition = function (lineWidget) {\n var height = 0;\n var lineHeight = 0;\n for (var i = 0; i < lineWidget.children.length; i++) {\n if (lineWidget.children[i] instanceof FieldElementBox ||\n (lineWidget.children[i].width === 0 && lineWidget.children[i].height === 0)) {\n continue;\n }\n if (height < lineWidget.children[i].height + lineWidget.children[i].margin.top) {\n height = lineWidget.children[i].margin.top + lineWidget.children[i].height;\n lineHeight = lineWidget.children[i].height / 20;\n }\n }\n return height - 2 * lineHeight;\n };\n /**\n * Renders list element box\n * @param {ListTextElementBox} elementBox\n * @param {number} left\n * @param {number} top\n * @param {number} underlineY\n */\n Renderer.prototype.renderListTextElementBox = function (elementBox, left, top, underlineY) {\n var topMargin = elementBox.margin.top;\n var leftMargin = elementBox.margin.left;\n var format = elementBox.listLevel.characterFormat;\n var breakCharacterFormat = elementBox.line.paragraph.characterFormat;\n var color = format.fontColor === '#000000' ? breakCharacterFormat.fontColor : format.fontColor;\n this.pageContext.textBaseline = 'top';\n var bold = '';\n var italic = '';\n var fontFamily = format.fontFamily === 'Verdana' ? breakCharacterFormat.fontFamily : format.fontFamily;\n var fontSize = format.fontSize === 11 ? breakCharacterFormat.fontSize : format.fontSize;\n // tslint:disable-next-line:max-line-length\n var baselineAlignment = format.baselineAlignment === 'Normal' ? breakCharacterFormat.baselineAlignment : format.baselineAlignment;\n bold = format.bold ? 'bold' : breakCharacterFormat.bold ? 'bold' : '';\n italic = format.italic ? 'italic' : breakCharacterFormat.italic ? 'italic' : '';\n fontSize = fontSize === 0 ? 0.5 : fontSize / (baselineAlignment === 'Normal' ? 1 : 1.5);\n var strikethrough = format.strikethrough === 'None' ? breakCharacterFormat.strikethrough : format.strikethrough;\n var highlightColor = format.highlightColor === 'NoColor' ? breakCharacterFormat.highlightColor :\n format.highlightColor;\n if (highlightColor !== 'NoColor') {\n if (highlightColor.substring(0, 1) !== '#') {\n this.pageContext.fillStyle = HelperMethods.getHighlightColorCode(highlightColor);\n }\n else {\n this.pageContext.fillStyle = this.getColor(highlightColor);\n }\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillRect(this.getScaledValue(left + leftMargin, 1), this.getScaledValue(top + topMargin, 2), this.getScaledValue(elementBox.width), this.getScaledValue(elementBox.height));\n }\n this.pageContext.font = bold + ' ' + italic + ' ' + fontSize * this.viewer.zoomFactor + 'pt' + ' ' + fontFamily;\n if (baselineAlignment === 'Subscript') {\n topMargin += elementBox.height - elementBox.height / 1.5;\n }\n this.pageContext.fillStyle = this.getColor(color);\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillText(elementBox.text, this.getScaledValue(left + leftMargin, 1), this.getScaledValue(top + topMargin, 2), this.getScaledValue(elementBox.width));\n if (format.underline !== 'None' && !isNullOrUndefined(format.underline)) {\n this.renderUnderline(elementBox, left, top, underlineY, color, format.underline, baselineAlignment);\n }\n if (strikethrough !== 'None') {\n this.renderStrikeThrough(elementBox, left, top, format.strikethrough, color, baselineAlignment);\n }\n };\n /**\n * Renders text element box.\n * @param {TextElementBox} elementBox\n * @param {number} left\n * @param {number} top\n * @param {number} underlineY\n */\n // tslint:disable-next-line:max-line-length\n Renderer.prototype.renderTextElementBox = function (elementBox, left, top, underlineY) {\n var isHeightType = false;\n var containerWidget = elementBox.line.paragraph.containerWidget;\n if (containerWidget instanceof TableCellWidget) {\n isHeightType = (containerWidget.ownerRow.rowFormat.heightType === 'Exactly');\n }\n var topMargin = elementBox.margin.top;\n var leftMargin = elementBox.margin.left;\n if (isHeightType) {\n // tslint:disable-next-line:max-line-length\n this.clipRect(containerWidget.x, containerWidget.y, this.getScaledValue(containerWidget.width), this.getScaledValue(containerWidget.height));\n }\n var format = elementBox.characterFormat;\n if (format.highlightColor !== 'NoColor') {\n if (format.highlightColor.substring(0, 1) !== '#') {\n this.pageContext.fillStyle = HelperMethods.getHighlightColorCode(format.highlightColor);\n }\n else {\n this.pageContext.fillStyle = this.getColor(format.highlightColor);\n }\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillRect(this.getScaledValue(left + leftMargin, 1), this.getScaledValue(top + topMargin, 2), this.getScaledValue(elementBox.width), this.getScaledValue(elementBox.height));\n }\n var color = format.fontColor;\n this.pageContext.textBaseline = 'top';\n var bold = '';\n var italic = '';\n var fontSize = 11;\n bold = format.bold ? 'bold' : '';\n italic = format.italic ? 'italic' : '';\n fontSize = format.fontSize === 0 ? 0.5 : format.fontSize / (format.baselineAlignment === 'Normal' ? 1 : 1.5);\n this.pageContext.font = bold + ' ' + italic + ' ' + fontSize * this.viewer.zoomFactor + 'pt' + ' ' + format.fontFamily;\n if (format.baselineAlignment === 'Subscript') {\n topMargin += elementBox.height - elementBox.height / 1.5;\n }\n this.pageContext.fillStyle = this.getColor(color);\n var scaledWidth = this.getScaledValue(elementBox.width);\n var text = elementBox.text;\n // tslint:disable-next-line:max-line-length\n if (elementBox instanceof TabElementBox) {\n var tabElement = elementBox;\n if (tabElement.tabText === '' && !isNullOrUndefined(tabElement.tabLeader) && tabElement.tabLeader !== 'None') {\n text = this.getTabLeader(elementBox);\n tabElement.tabText = text;\n }\n else if (tabElement.tabText !== '') {\n text = tabElement.tabText;\n }\n }\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillText(text, this.getScaledValue(left + leftMargin, 1), this.getScaledValue(top + topMargin, 2), scaledWidth);\n if (format.underline !== 'None' && !isNullOrUndefined(format.underline)) {\n // tslint:disable-next-line:max-line-length\n this.renderUnderline(elementBox, left, top, underlineY, color, format.underline, format.baselineAlignment);\n }\n if (format.strikethrough !== 'None' && !isNullOrUndefined(format.strikethrough)) {\n this.renderStrikeThrough(elementBox, left, top, format.strikethrough, color, format.baselineAlignment);\n }\n if (isHeightType) {\n this.pageContext.restore();\n }\n };\n /**\n * Returns tab leader\n */\n Renderer.prototype.getTabLeader = function (elementBox) {\n var textWidth = 0;\n var tabString = this.getTabLeaderString(elementBox.tabLeader);\n var tabText = tabString;\n textWidth = this.viewer.textHelper.getWidth(tabText, elementBox.characterFormat);\n var count = Math.floor(elementBox.width / textWidth);\n for (var i = 0; i <= count; i++) {\n tabText += tabString;\n }\n return tabText.slice(0, -1);\n };\n /**\n * Returns tab leader string.\n */\n Renderer.prototype.getTabLeaderString = function (tabLeader) {\n var tabString = '';\n switch (tabLeader) {\n case 'Dot':\n tabString = '.';\n break;\n case 'Hyphen':\n tabString = '-';\n break;\n case 'Underscore':\n tabString = '_';\n break;\n }\n return tabString;\n };\n /**\n * Clips the rectangle with specified position.\n * @param {number} xPos\n * @param {number} yPos\n * @param {number} width\n * @param {number} height\n */\n Renderer.prototype.clipRect = function (xPos, yPos, width, height) {\n this.pageContext.beginPath();\n this.pageContext.save();\n this.pageContext.rect(this.getScaledValue(xPos, 1), this.getScaledValue(yPos, 2), width, height);\n this.pageContext.clip();\n };\n /**\n * Renders underline.\n * @param {ElementBox} elementBox\n * @param {number} left\n * @param {number} top\n * @param {number} underlineY\n * @param {string} color\n * @param {Underline} underline\n * @param {BaselineAlignment} baselineAlignment\n */\n // tslint:disable-next-line:max-line-length\n Renderer.prototype.renderUnderline = function (elementBox, left, top, underlineY, color, underline, baselineAlignment) {\n var renderedHeight = elementBox.height / (baselineAlignment === 'Normal' ? 1 : 1.5);\n var topMargin = elementBox.margin.top;\n var underlineHeight = renderedHeight / 20;\n var y = 0;\n if (baselineAlignment === 'Subscript' || elementBox instanceof ListTextElementBox) {\n y = (renderedHeight - 2 * underlineHeight) + top;\n topMargin += elementBox.height - renderedHeight;\n y += topMargin > 0 ? topMargin : 0;\n }\n else {\n y = underlineY + top;\n }\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillRect(this.getScaledValue(left + elementBox.margin.left, 1), this.getScaledValue(y, 2), this.getScaledValue(elementBox.width), this.getScaledValue(underlineHeight));\n };\n /**\n * Renders strike through.\n * @param {ElementBox} elementBox\n * @param {number} left\n * @param {number} top\n * @param {Strikethrough} strikethrough\n * @param {string} color\n * @param {BaselineAlignment} baselineAlignment\n */\n // tslint:disable-next-line:max-line-length\n Renderer.prototype.renderStrikeThrough = function (elementBox, left, top, strikethrough, color, baselineAlignment) {\n var renderedHeight = elementBox.height / (baselineAlignment === 'Normal' ? 1 : 1.5);\n var topMargin = elementBox.margin.top;\n if (baselineAlignment === 'Subscript') {\n topMargin += elementBox.height - renderedHeight;\n }\n top += topMargin > 0 ? topMargin : 0;\n var lineHeight = renderedHeight / 20;\n var y = (renderedHeight / 2) + (0.5 * lineHeight);\n var lineCount = 0;\n if (strikethrough === 'DoubleStrike') {\n y -= lineHeight;\n }\n while (lineCount < (strikethrough === 'DoubleStrike' ? 2 : 1)) {\n lineCount++;\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillRect(this.getScaledValue(left + elementBox.margin.left, 1), this.getScaledValue(y + top, 2), this.getScaledValue(elementBox.width), this.getScaledValue(lineHeight));\n y += 2 * lineHeight;\n }\n };\n /**\n * Renders image element box.\n * @param {ImageElementBox} elementBox\n * @param {number} left\n * @param {number} top\n * @param {number} underlineY\n */\n // tslint:disable-next-line:max-line-length\n Renderer.prototype.renderImageElementBox = function (elementBox, left, top, underlineY) {\n var topMargin = elementBox.margin.top;\n var leftMargin = elementBox.margin.left;\n var color = 'black';\n this.pageContext.textBaseline = 'top';\n var widgetWidth = 0;\n var isClipped = false;\n if (topMargin < 0 || elementBox.line.paragraph.width < elementBox.width) {\n var containerWid = elementBox.line.paragraph.containerWidget;\n // if (containerWid instanceof BodyWidget) {\n // widgetWidth = containerWid.width + containerWid.x;\n // } else \n if (containerWid instanceof TableCellWidget) {\n var leftIndent = 0;\n if (containerWid.childWidgets[0] instanceof ParagraphWidget) {\n var paraAdv = containerWid.childWidgets[0];\n leftIndent = paraAdv.paragraphFormat.leftIndent;\n }\n widgetWidth = containerWid.width + containerWid.margin.left - containerWid.leftBorderWidth - leftIndent;\n isClipped = true;\n // tslint:disable-next-line:max-line-length\n this.clipRect(left + leftMargin, top + topMargin, this.getScaledValue(widgetWidth), this.getScaledValue(containerWid.height));\n }\n }\n if (elementBox.isMetaFile) {\n /* tslint:disable:no-empty */\n }\n else {\n // tslint:disable-next-line:max-line-length\n this.pageContext.drawImage(elementBox.element, this.getScaledValue(left + leftMargin, 1), this.getScaledValue(top + topMargin, 2), this.getScaledValue(elementBox.width), this.getScaledValue(elementBox.height));\n }\n if (isClipped) {\n this.pageContext.restore();\n }\n };\n /**\n * Renders table outline.\n * @param {TableWidget} tableWidget\n */\n Renderer.prototype.renderTableOutline = function (tableWidget) {\n var layout = new Layout(this.viewer);\n var table = tableWidget;\n tableWidget.width = this.viewer.layout.getTableWidth(table);\n var border = layout.getTableTopBorder(table.tableFormat.borders);\n var lineWidth = 0;\n //ToDo: Need to draw the borders based on the line style.\n // if (!isNullOrUndefined(border )) {\n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, tableWidget.x - tableWidget.margin.left - lineWidth / 2, tableWidget.y, tableWidget.x - tableWidget.margin.left - lineWidth / 2, tableWidget.y + tableWidget.height, lineWidth);\n // }\n border = layout.getTableTopBorder(table.tableFormat.borders);\n lineWidth = 0;\n // if (!isNullOrUndefined(border )) {\n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, tableWidget.x - tableWidget.margin.left - lineWidth, tableWidget.y - lineWidth / 2, tableWidget.x + tableWidget.width + lineWidth + tableWidget.margin.right, tableWidget.y - lineWidth / 2, lineWidth);\n // }\n border = layout.getTableRightBorder(table.tableFormat.borders);\n lineWidth = 0;\n // if (!isNullOrUndefined(border )) {\n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, tableWidget.x + tableWidget.width + tableWidget.margin.right + lineWidth / 2, tableWidget.y, tableWidget.x + tableWidget.width + tableWidget.margin.right + lineWidth / 2, tableWidget.y + tableWidget.height, lineWidth);\n // }\n border = layout.getTableBottomBorder(table.tableFormat.borders);\n lineWidth = 0;\n // if (!isNullOrUndefined(border )) {\n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, tableWidget.x - tableWidget.margin.left - lineWidth, tableWidget.y + tableWidget.height - lineWidth / 2, tableWidget.x + tableWidget.width + lineWidth + tableWidget.margin.right, tableWidget.y + tableWidget.height - lineWidth / 2, lineWidth);\n // }\n };\n /**\n * Renders table cell outline.\n * @param {LayoutViewer} viewer\n * @param {TableCellWidget} cellWidget\n */\n Renderer.prototype.renderTableCellOutline = function (viewer, cellWidget) {\n var layout = viewer.layout;\n var borders = undefined;\n var tableCell = cellWidget;\n var cellTopMargin = 0;\n var cellBottomMargin = 0;\n var cellLeftMargin = 0;\n var cellRightMargin = 0;\n var height = 0;\n borders = tableCell.cellFormat.borders;\n if (cellWidget.containerWidget instanceof TableRowWidget) {\n cellBottomMargin = cellWidget.margin.bottom - cellWidget.containerWidget.bottomBorderWidth;\n cellTopMargin = cellWidget.margin.top - cellWidget.containerWidget.topBorderWidth;\n }\n cellLeftMargin = cellWidget.margin.left - cellWidget.leftBorderWidth;\n cellRightMargin = cellWidget.margin.right - cellWidget.rightBorderWidth;\n if (!isNullOrUndefined(tableCell.ownerRow) && tableCell.ownerRow.rowFormat.heightType === 'Exactly') {\n height = HelperMethods.convertPointToPixel(tableCell.ownerRow.rowFormat.height) + cellTopMargin + cellBottomMargin;\n }\n else {\n if (!isNullOrUndefined(tableCell.ownerRow) && [tableCell.ownerRow].length <= 1) {\n // tslint:disable-next-line:max-line-length\n height = Math.max(HelperMethods.convertPointToPixel(tableCell.ownerRow.rowFormat.height), cellWidget.height) + cellTopMargin + cellBottomMargin;\n }\n else {\n height = cellWidget.height + cellTopMargin + cellBottomMargin;\n }\n }\n this.renderCellBackground(height, cellWidget);\n var border = TableCellWidget.getCellLeftBorder(tableCell);\n var lineWidth = 0;\n // if (!isNullOrUndefined(border )) { \n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth()); //Renders the cell left border.\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, cellWidget.x - cellLeftMargin - lineWidth, cellWidget.y - cellTopMargin, cellWidget.x - cellLeftMargin - lineWidth, cellWidget.y + cellWidget.height + cellBottomMargin, lineWidth);\n // }\n border = TableCellWidget.getCellTopBorder(tableCell);\n // if (!isNullOrUndefined(border )) { //Renders the cell top border. \n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, cellWidget.x - cellWidget.margin.left, cellWidget.y - cellWidget.margin.top + lineWidth / 2, cellWidget.x + cellWidget.width + cellWidget.margin.right, cellWidget.y - cellWidget.margin.top + lineWidth / 2, lineWidth);\n // }\n if (tableCell.ownerTable.tableFormat.cellSpacing > 0 || tableCell.cellIndex === tableCell.ownerRow.childWidgets.length - 1) {\n border = TableCellWidget.getCellRightBorder(tableCell);\n // if (!isNullOrUndefined(border )) { //Renders the cell right border. \n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, cellWidget.x + cellWidget.width + cellWidget.margin.right - lineWidth / 2, cellWidget.y - cellTopMargin, cellWidget.x + cellWidget.width + cellWidget.margin.right - lineWidth / 2, cellWidget.y + cellWidget.height + cellBottomMargin, lineWidth);\n // }\n }\n var nextRow = tableCell.ownerRow.nextWidget;\n //Specifies the next row is within the current table widget.\n //True means current row is not rendered at page end; Otherwise False.\n var nextRowIsInCurrentTableWidget = false;\n if (!isNullOrUndefined(nextRow)) {\n var nextRowWidget = undefined;\n // if (viewer.renderedElements.containsKey(nextRow) && viewer.renderedElements.get(nextRow).length > 0) {\n nextRowWidget = nextRow;\n // }\n if (nextRowWidget instanceof TableRowWidget) {\n // tslint:disable-next-line:max-line-length\n if (cellWidget.containerWidget instanceof TableRowWidget && cellWidget.containerWidget.containerWidget instanceof TableWidget) {\n nextRowIsInCurrentTableWidget = cellWidget.containerWidget.containerWidget.childWidgets.indexOf(nextRowWidget) !== -1;\n }\n }\n }\n if (tableCell.ownerTable.tableFormat.cellSpacing > 0 || tableCell.ownerRow.rowIndex === tableCell.ownerTable.childWidgets.length - 1\n || (tableCell.cellFormat.rowSpan > 1\n && tableCell.ownerRow.rowIndex + tableCell.cellFormat.rowSpan === tableCell.ownerTable.childWidgets.length) ||\n !nextRowIsInCurrentTableWidget) {\n // tslint:disable-next-line:max-line-length\n border = (tableCell.cellFormat.rowSpan > 1 && tableCell.ownerRow.rowIndex + tableCell.cellFormat.rowSpan === tableCell.ownerTable.childWidgets.length) ?\n //true part for vertically merged cells specifically.\n tableCell.getBorderBasedOnPriority(tableCell.cellFormat.borders.bottom, TableCellWidget.getCellBottomBorder(tableCell))\n //false part for remaining cases that has been handled inside method. \n : TableCellWidget.getCellBottomBorder(tableCell);\n // if (!isNullOrUndefined(border )) {\n //Renders the cell bottom border.\n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, cellWidget.x - cellWidget.margin.left, cellWidget.y + cellWidget.height + cellBottomMargin + lineWidth / 2, cellWidget.x + cellWidget.width + cellWidget.margin.right, cellWidget.y + cellWidget.height + cellBottomMargin + lineWidth / 2, lineWidth);\n // }\n }\n border = layout.getCellDiagonalUpBorder(tableCell);\n // if (!isNullOrUndefined(border )) {\n //Renders the cell diagonal up border.\n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n if (lineWidth > 0) {\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, cellWidget.x - cellLeftMargin, cellWidget.y + cellWidget.height + cellBottomMargin, cellWidget.x + cellWidget.width + cellRightMargin, cellWidget.y - cellTopMargin, lineWidth);\n // }\n }\n border = layout.getCellDiagonalDownBorder(tableCell);\n // if (!isNullOrUndefined(border )) {\n //Renders the cell diagonal down border.\n lineWidth = HelperMethods.convertPointToPixel(border.getLineWidth());\n if (lineWidth > 0) {\n // tslint:disable-next-line:max-line-length\n this.renderSingleBorder(border, cellWidget.x - cellLeftMargin, cellWidget.y - cellTopMargin, cellWidget.x + cellWidget.width + cellRightMargin, cellWidget.y + cellWidget.height + cellBottomMargin, lineWidth);\n }\n // }\n };\n /**\n * Renders cell background.\n * @param {number} height\n * @param {TableCellWidget} cellWidget\n */\n Renderer.prototype.renderCellBackground = function (height, cellWidget) {\n var cellFormat = cellWidget.cellFormat;\n var bgColor = cellFormat.shading.backgroundColor === '#ffffff' ?\n cellWidget.ownerTable.tableFormat.shading.backgroundColor : cellFormat.shading.backgroundColor;\n this.pageContext.beginPath();\n if (bgColor !== 'empty') {\n this.pageContext.fillStyle = this.getColor(bgColor);\n var left = cellWidget.x - cellWidget.margin.left + cellWidget.leftBorderWidth;\n var top_1 = cellWidget.y - HelperMethods.convertPointToPixel(cellWidget.topMargin);\n // tslint:disable-next-line:max-line-length\n var width = cellWidget.width + cellWidget.margin.left + cellWidget.margin.right - cellWidget.leftBorderWidth - cellWidget.rightBorderWidth;\n // tslint:disable-next-line:max-line-length\n this.pageContext.fillRect(this.getScaledValue(left, 1), this.getScaledValue(top_1, 2), this.getScaledValue(width), this.getScaledValue(height));\n this.pageContext.closePath();\n }\n };\n /**\n * Renders single border.\n * @param {WBorder} border\n * @param {number} startX\n * @param {number} startY\n * @param {number} endX\n * @param {number} endY\n * @param {number} lineWidth\n */\n // tslint:disable-next-line:max-line-length\n Renderer.prototype.renderSingleBorder = function (border, startX, startY, endX, endY, lineWidth) {\n this.pageContext.beginPath();\n this.pageContext.moveTo(this.getScaledValue(startX, 1), this.getScaledValue(startY, 2));\n this.pageContext.lineTo(this.getScaledValue(endX, 1), this.getScaledValue(endY, 2));\n this.pageContext.lineWidth = this.getScaledValue(lineWidth);\n // set line color\n this.pageContext.strokeStyle = border.color;\n if (lineWidth > 0) {\n this.pageContext.stroke();\n }\n this.pageContext.closePath();\n };\n /**\n * Gets scaled value.\n * @param {number} value\n * @param {number} type\n * @private\n */\n Renderer.prototype.getScaledValue = function (value, type) {\n if (this.isPrinting) {\n return value;\n }\n if (isNullOrUndefined(type)) {\n type = 0;\n }\n var x = value * this.viewer.zoomFactor;\n return x + (type === 1 ? this.pageLeft : (type === 2 ? this.pageTop : 0));\n };\n /**\n * Destroys the internal objects which is maintained.\n */\n Renderer.prototype.destroy = function () {\n this.viewer = undefined;\n if (!isNullOrUndefined(this.pageCanvasIn)) {\n this.pageCanvasIn.innerHTML = '';\n }\n this.pageCanvasIn = undefined;\n };\n return Renderer;\n}());\nexport { Renderer };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { WCharacterFormat } from '../index';\nimport { HelperMethods } from '../editor/editor-helper';\n/**\n * @private\n */\nvar TextHelper = /** @class */ (function () {\n function TextHelper(viewer) {\n this.owner = viewer;\n if (!isNullOrUndefined(viewer)) {\n this.context = viewer.containerContext;\n }\n }\n Object.defineProperty(TextHelper.prototype, \"paragraphMark\", {\n get: function () {\n return '¶';\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextHelper.prototype, \"lineBreakMark\", {\n get: function () {\n return '↲';\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n TextHelper.prototype.getParagraphMarkWidth = function (characterFormat) {\n return this.getWidth(this.paragraphMark, characterFormat);\n };\n /**\n * @private\n */\n TextHelper.prototype.getParagraphMarkSize = function (characterFormat) {\n // Gets the text element's width;\n var width = this.getWidth(this.paragraphMark, characterFormat);\n var height = 0;\n var baselineOffset = 0;\n // Calculate the text element's height and baseline offset.\n var textHelper = this.getHeight(characterFormat);\n return {\n 'Width': width, 'Height': textHelper.Height, 'BaselineOffset': textHelper.BaselineOffset\n };\n };\n /**\n * @private\n */\n TextHelper.prototype.getTextSize = function (elementBox, characterFormat) {\n // Gets the text element's width;\n var textTrimEndWidth = 0;\n textTrimEndWidth = this.getWidth(elementBox.text, characterFormat);\n elementBox.width = textTrimEndWidth;\n // Calculate the text element's height and baseline offset.\n var textHelper = this.getHeight(characterFormat);\n elementBox.height = textHelper.Height;\n elementBox.baselineOffset = textHelper.BaselineOffset;\n if (elementBox.text[elementBox.text.length - 1] === ' ') {\n textTrimEndWidth = this.getWidth(HelperMethods.trimEnd(elementBox.text), characterFormat);\n }\n return textTrimEndWidth;\n };\n /**\n * @private\n */\n TextHelper.prototype.getHeight = function (characterFormat) {\n // Get character format property as below predefined structure to make it easy to check and retrieve\n // Predefined static structure `[FontName];[FontSize];bold;italic` to maintain as key in the collection \n var key = this.getFormatText(characterFormat);\n if (!isNullOrUndefined(this.owner.heightInfoCollection[key])) {\n return this.owner.heightInfoCollection[key];\n }\n var sizeInfo = this.getHeightInternal(characterFormat);\n this.owner.heightInfoCollection[key] = sizeInfo;\n return sizeInfo;\n };\n /**\n * @private\n */\n TextHelper.prototype.getFormatText = function (characterFormat) {\n var formatText = characterFormat.fontFamily.toLocaleLowerCase();\n formatText += ';' + characterFormat.fontSize;\n if (characterFormat.bold) {\n formatText += ';' + 'bold';\n }\n if (characterFormat.italic) {\n formatText += ';' + 'italic';\n }\n return formatText;\n };\n /**\n * @private\n */\n TextHelper.prototype.getHeightInternal = function (characterFormat) {\n var textHeight = 0;\n var baselineOffset = 0;\n var spanElement = document.createElement('span');\n spanElement.id = 'tempSpan';\n spanElement.style.whiteSpace = 'nowrap';\n spanElement.innerText = 'm';\n this.applyStyle(spanElement, characterFormat);\n var body = document.getElementsByTagName('body');\n var parentDiv = document.createElement('div');\n parentDiv.style.display = 'inline-block';\n var tempDiv = document.createElement('div');\n tempDiv.setAttribute('style', 'display:inline-block;width: 1px; height: 0px;vertical-align: baseline;');\n parentDiv.appendChild(spanElement);\n parentDiv.appendChild(tempDiv);\n document.body.appendChild(parentDiv);\n // Sets the text element's height.\n textHeight = spanElement.offsetHeight;\n // Calculate the text element's baseline offset.\n var textTopVal = spanElement.offsetTop;\n var tempDivTopVal = tempDiv.offsetTop;\n baselineOffset = tempDivTopVal - textTopVal;\n document.body.removeChild(parentDiv);\n return { 'Height': textHeight, 'BaselineOffset': baselineOffset };\n };\n /**\n * @private\n */\n TextHelper.prototype.measureTextExcludingSpaceAtEnd = function (text, characterFormat) {\n return this.getWidth(HelperMethods.trimEnd(text), characterFormat);\n };\n /**\n * @private\n */\n TextHelper.prototype.getWidth = function (text, characterFormat) {\n if (text.match('\\v')) {\n text.replace('\\v', this.lineBreakMark);\n }\n var bold = '';\n var italic = '';\n var fontFamily = '';\n var fontSize = characterFormat.fontSize;\n bold = characterFormat.bold ? 'bold' : '';\n italic = characterFormat.italic ? 'italic' : '';\n fontFamily = characterFormat.fontFamily;\n fontSize = fontSize === 0 ? 0.5 : fontSize / (characterFormat.baselineAlignment === 'Normal' ? 1 : 1.5);\n this.context.font = bold + ' ' + italic + ' ' + fontSize + 'pt' + ' ' + fontFamily;\n return this.context.measureText(text).width;\n };\n /**\n * @private\n */\n TextHelper.prototype.applyStyle = function (spanElement, characterFormat) {\n if (!isNullOrUndefined(spanElement) && !isNullOrUndefined(characterFormat)) {\n if (characterFormat.fontFamily !== '') {\n spanElement.style.fontFamily = characterFormat.fontFamily;\n }\n var fontSize = characterFormat.fontSize;\n if (fontSize <= 0.5) {\n fontSize = 0.5;\n }\n spanElement.style.fontSize = fontSize.toString() + 'pt';\n if (characterFormat.bold) {\n spanElement.style.fontWeight = 'bold';\n }\n if (characterFormat.italic) {\n spanElement.style.fontStyle = 'italic';\n }\n }\n };\n /**\n * @private\n */\n TextHelper.prototype.measureText = function (text, characterFormat) {\n // Gets the text element's width;\n var width = this.getWidth(text, characterFormat);\n var height = 0;\n var baselineOffset = 0;\n // Calculate the text element's height and baseline offset.\n var textHelper = this.getHeight(characterFormat);\n return {\n 'Width': width, 'Height': textHelper.Height, 'BaselineOffset': textHelper.BaselineOffset\n };\n };\n /**\n * @private\n */\n TextHelper.prototype.updateTextSize = function (elementBox, paragraph) {\n var format = new WCharacterFormat(undefined);\n var listCharacterFormat = elementBox.listLevel.characterFormat;\n var breakCharacterFormat = paragraph.characterFormat;\n format.fontSize = listCharacterFormat.fontSize === 11 ? breakCharacterFormat.fontSize : listCharacterFormat.fontSize;\n format.fontFamily = listCharacterFormat.fontFamily === 'Verdana' ? breakCharacterFormat.fontFamily\n : listCharacterFormat.fontFamily;\n var bold = '';\n var italic = '';\n var baselineAlignment = listCharacterFormat.baselineAlignment === 'Normal' ?\n breakCharacterFormat.baselineAlignment : listCharacterFormat.baselineAlignment;\n bold = listCharacterFormat.bold ? 'bold' : breakCharacterFormat.bold ? 'bold' : '';\n italic = listCharacterFormat.italic ? 'italic' : breakCharacterFormat.italic ? 'italic' : '';\n format.baselineAlignment = baselineAlignment;\n if (bold) {\n format.bold = true;\n }\n if (italic) {\n format.italic = true;\n }\n elementBox.width = this.getWidth(elementBox.text, format);\n // Calculate the text element's height and baseline offset.\n var textHelper = this.getHeight(format);\n elementBox.height = textHelper.Height;\n elementBox.baselineOffset = textHelper.BaselineOffset;\n };\n TextHelper.prototype.destroy = function () {\n this.owner = undefined;\n this.context = undefined;\n };\n return TextHelper;\n}());\nexport { TextHelper };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar Zoom = /** @class */ (function () {\n function Zoom(viewer) {\n var _this = this;\n this.onMouseWheelInternal = function (event) {\n if (event.ctrlKey === true) {\n event.preventDefault();\n var pageX = event.pageX - _this.viewer.viewerContainer.offsetLeft;\n if (pageX < _this.viewer.pageContainer.offsetWidth) {\n var wheel = navigator.userAgent.match('Firefox') ? event.detail < 0 : event.wheelDelta > 0;\n var zoomFactor = _this.viewer.zoomFactor;\n if (wheel) {\n if (zoomFactor <= 4.90) {\n zoomFactor += .10;\n }\n else {\n zoomFactor = 5.00;\n }\n }\n else {\n if (zoomFactor >= .20) {\n zoomFactor -= .10;\n }\n else {\n zoomFactor = 0.10;\n }\n }\n _this.viewer.zoomFactor = zoomFactor;\n }\n }\n };\n this.viewer = viewer;\n }\n Zoom.prototype.setZoomFactor = function (value) {\n this.onZoomFactorChanged();\n if (!isNullOrUndefined(this.viewer.selection)) {\n this.viewer.selection.updateCaretPosition();\n }\n this.viewer.updateTouchMarkPosition();\n if (!isNullOrUndefined(this.viewer.owner.imageResizerModule)) {\n this.viewer.owner.imageResizerModule.updateImageResizerPosition();\n }\n this.viewer.owner.fireZoomFactorChange();\n };\n //Zoom Implementation Starts\n Zoom.prototype.onZoomFactorChanged = function () {\n if (this.viewer.zoomFactor > 5) {\n this.viewer.zoomFactor = 5;\n }\n else if (this.viewer.zoomFactor < 0.1) {\n this.viewer.zoomFactor = 0.1;\n }\n this.zoom();\n };\n Zoom.prototype.zoom = function () {\n var viewer = this.viewer;\n viewer.clearContent();\n viewer.handleZoom();\n viewer.updateFocus();\n };\n return Zoom;\n}());\nexport { Zoom };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Dictionary } from '../../base/dictionary';\nimport { WAbstractList } from '../list/abstract-list';\nimport { WLevelOverride } from '../list/level-override';\nimport { WCharacterFormat, WParagraphFormat, WStyles } from '../format/index';\nimport { Layout } from './layout';\nimport { Renderer } from './render';\nimport { createElement, Browser } from '@syncfusion/ej2-base';\nimport { Page, Rect, ListTextElementBox, ParagraphWidget, HeaderFooterWidget } from './page';\nimport { LineWidget, TableWidget } from './page';\nimport { HelperMethods, Point } from '../editor/editor-helper';\nimport { TextHelper } from './text-helper';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Zoom } from './zooming';\nimport { Dialog } from '@syncfusion/ej2-popups';\n/**\n * @private\n */\nvar LayoutViewer = /** @class */ (function () {\n //#endregion\n function LayoutViewer(owner) {\n var _this = this;\n /**\n * @private\n */\n this.textWrap = true;\n /**\n * @private\n */\n this.currentPage = undefined;\n this.selectionStartPageIn = undefined;\n this.selectionEndPageIn = undefined;\n /**\n * @private\n */\n this.fieldStacks = [];\n /**\n * @private\n */\n this.splittedCellWidgets = [];\n /**\n * @private\n */\n this.tableLefts = [];\n this.tapCount = 0;\n this.timer = -1;\n this.isTimerStarted = false;\n /**\n * @private\n */\n this.isFirstLineFitInShiftWidgets = false;\n /**\n * @private\n */\n this.preZoomFactor = 0;\n /**\n * @private\n */\n this.preDifference = -1;\n /**\n * @private\n */\n this.fieldEndParagraph = undefined;\n /**\n * @private\n */\n this.fieldToLayout = undefined;\n /**\n * @private\n */\n this.backgroundColor = '#FFFFFF';\n /**\n * @private\n */\n this.containerTop = 0;\n /**\n * @private\n */\n this.containerLeft = 0;\n // Event \n /**\n * @private\n */\n this.isMouseDown = false;\n /**\n * @private\n */\n this.isSelectionChangedOnMouseMoved = false;\n /**\n * @private\n */\n this.isControlPressed = false;\n /**\n * @private\n */\n this.isTouchInput = false;\n /**\n * @private\n */\n this.useTouchSelectionMark = false;\n /**\n * @private\n */\n this.touchDownOnSelectionMark = 0;\n /**\n * @private\n */\n this.isCompositionStart = false;\n /**\n * @private\n */\n this.isCompositionUpdated = false;\n /**\n * @private\n */\n this.isCompositionCanceled = false;\n /**\n * @private\n */\n this.isCompositionEnd = false;\n /**\n * @private\n */\n this.prefix = '';\n /**\n * @private\n */\n this.suffix = '';\n /**\n * @private\n */\n this.fields = [];\n /**\n * @private\n */\n this.heightInfoCollection = {};\n /**\n * @private\n */\n this.defaultTabWidth = 36;\n /**\n * @private\n */\n this.lists = [];\n /**\n * @private\n */\n this.abstractLists = [];\n /**\n * @private\n */\n this.styles = new WStyles();\n /**\n * @private\n */\n this.preDefinedStyles = undefined;\n /**\n * @private\n */\n this.isRowOrCellResizing = false;\n this.isMouseDownInFooterRegion = false;\n this.pageFitTypeIn = 'None';\n /**\n * @private\n */\n this.fieldCollection = [];\n /**\n * @private\n */\n this.isPageField = false;\n /**\n * @private\n */\n this.mouseDownOffset = new Point(0, 0);\n this.zoomFactorInternal = 1;\n /**\n * Fires when composition starts.\n * @private\n */\n this.compositionStart = function (event) {\n event.preventDefault();\n _this.isCompositionStart = true;\n };\n /**\n * Fires on every input during composition.\n * @private\n */\n this.compositionUpdated = function (event) {\n event.preventDefault();\n _this.isCompositionUpdated = true;\n };\n /**\n * Fires when user selects a character/word and finalizes the input.\n * @private\n */\n this.compositionEnd = function (event) {\n event.preventDefault();\n _this.isCompositionUpdated = false;\n _this.isCompositionEnd = true;\n };\n // tslint:disable:no-any \n this.onImageResizer = function (args) {\n if (!isNullOrUndefined(_this.owner.imageResizerModule) && _this.owner.imageResizerModule.isImageResizerVisible\n && _this.owner.imageResizerModule.isImageResizing) {\n if (args instanceof MouseEvent) {\n _this.onMouseUpInternal(args);\n }\n else if (args instanceof TouchEvent) {\n _this.onTouchUpInternal(args);\n }\n }\n };\n // tslint:enable:no-any \n this.onTextInputInternal = function (event) {\n if (!_this.owner.isReadOnlyMode) {\n _this.owner.editorModule.onTextInputInternal(event);\n }\n else {\n _this.editableDiv.innerText = '';\n }\n };\n /**\n * Fired on paste.\n * @param {ClipboardEvent} event\n * @private\n */\n this.onPaste = function (event) {\n if (!_this.owner.isReadOnlyMode) {\n _this.owner.editorModule.pasteInternal(event);\n }\n _this.editableDiv.innerText = '';\n event.preventDefault();\n };\n /**\n * Fires when editable div loses focus.\n * @private\n */\n this.onFocusOut = function () {\n if (!isNullOrUndefined(_this.selection)) {\n if (_this.owner.contextMenuModule && _this.owner.contextMenuModule.contextMenuInstance &&\n _this.owner.contextMenuModule.contextMenuInstance.element.style.display === 'block') {\n return;\n }\n _this.selection.hideCaret();\n }\n };\n /**\n * Updates focus to editor area.\n * @private\n */\n this.updateFocus = function () {\n if (_this.selection) {\n _this.editableDiv.focus();\n _this.selection.showCaret();\n }\n };\n /**\n * Fires on scrolling.\n */\n this.scrollHandler = function () {\n _this.clearContent();\n _this.updateScrollBars();\n var vtHeight = _this.containerTop + _this.visibleBounds.height;\n if (vtHeight > _this.pageContainer.offsetHeight) {\n _this.viewerContainer.scrollTop = _this.containerTop - (vtHeight - _this.pageContainer.offsetHeight);\n }\n var viewer = _this;\n if (viewer instanceof PageLayoutViewer && !isNullOrUndefined(_this.owner)) {\n _this.owner.fireViewChange();\n }\n };\n /**\n * Fires when the window gets resized.\n * @private\n */\n this.onWindowResize = function () {\n var viewer = _this;\n var resizeTimer;\n /* tslint:disable:align */\n resizeTimer = setTimeout(function () {\n if (!isNullOrUndefined(viewer.owner) && !isNullOrUndefined(_this.owner.element)) {\n viewer.updateViewerSizeInternal(document.getElementById(viewer.owner.element.id));\n viewer.updateScrollBars();\n if (!isNullOrUndefined(_this.selection)) {\n _this.selection.updateCaretPosition();\n }\n viewer.updateTouchMarkPosition();\n if (viewer.owner.contextMenuModule && viewer.owner.contextMenuModule.contextMenuInstance) {\n viewer.owner.contextMenuModule.contextMenuInstance.close();\n }\n if (resizeTimer) {\n clearTimeout(resizeTimer);\n }\n }\n }, 100);\n };\n /**\n * @private\n */\n this.onContextMenu = function (event) {\n if (_this.owner.contextMenuModule) {\n _this.owner.contextMenuModule.onContextMenuInternal(event);\n }\n };\n /**\n * Called on mouse down.\n * @param {MouseEvent} event\n * @private\n */\n this.onMouseDownInternal = function (event) {\n if (_this.isTouchInput || event.offsetX > (_this.visibleBounds.width - (_this.visibleBounds.width - _this.viewerContainer.clientWidth))\n || event.offsetY > (_this.visibleBounds.height - (_this.visibleBounds.height - _this.viewerContainer.clientHeight))) {\n return;\n }\n if (!isNullOrUndefined(_this.selection)) {\n _this.updateCursor(event);\n // tslint:disable-next-line:max-line-length\n if (_this.isLeftButtonPressed(event) && !_this.owner.isReadOnlyMode && _this.owner.enableImageResizerMode && !isNullOrUndefined(_this.owner.imageResizerModule.selectedResizeElement)) {\n _this.owner.imageResizerModule.isImageResizing = true;\n }\n event.preventDefault();\n if (!_this.isTouchInput) {\n _this.selection.hideCaret();\n }\n var cursorPoint = new Point(event.offsetX, event.offsetY);\n var touchPoint = _this.findFocusedPage(cursorPoint, true);\n _this.mouseDownOffset.x = touchPoint.x;\n _this.mouseDownOffset.y = touchPoint.y;\n // tslint:disable-next-line:max-line-length\n _this.isMouseDownInFooterRegion = _this.selection.isCursorInsidePageRect(cursorPoint, _this.currentPage) && _this.selection.isCursorInFooterRegion(cursorPoint, _this.currentPage);\n _this.isSelectionChangedOnMouseMoved = false;\n if (!_this.owner.isReadOnlyMode && (_this.owner.editorModule.tableResize.isInCellResizerArea(touchPoint) ||\n _this.owner.editorModule.tableResize.isInRowResizerArea(touchPoint))) {\n _this.selection.hideCaret();\n _this.isMouseDown = true;\n _this.isSelectionChangedOnMouseMoved = false;\n if (_this.isLeftButtonPressed(event)) {\n _this.owner.editorModule.tableResize.startingPoint.x = touchPoint.x;\n _this.owner.editorModule.tableResize.startingPoint.y = touchPoint.y;\n _this.owner.editorModule.tableResize.handleResize(touchPoint);\n }\n return;\n }\n if (event.ctrlKey) {\n _this.isControlPressed = true;\n }\n if (_this.owner.selection.isEmpty) {\n _this.useTouchSelectionMark = false;\n }\n if (event.which === 3 && !_this.owner.selection.isEmpty\n && _this.selection.checkCursorIsInSelection(_this.getLineWidget(touchPoint), touchPoint)) {\n event.preventDefault();\n return;\n }\n _this.isTouchInput = false;\n _this.isMouseDown = true;\n _this.updateFocus();\n /* tslint:disable:align */\n _this.timer = setTimeout(function () {\n _this.tapCount++;\n if (_this.tapCount === 4) {\n _this.tapCount = 1;\n }\n }, 200);\n }\n };\n /**\n * Called on mouse move.\n * @param {MouseEvent} event\n * @private\n */\n this.onMouseMoveInternal = function (event) {\n event.preventDefault();\n if (!isNullOrUndefined(_this.selection)) {\n //For image Resizing\n if (!_this.owner.isReadOnlyMode && _this.owner.enableImageResizerMode\n && _this.owner.imageResizerModule.isImageResizing) {\n if (!_this.owner.imageResizerModule.isImageMoveToNextPage) {\n _this.owner.imageResizerModule.handleImageResizingOnMouse(event);\n }\n return;\n }\n var cursorPoint = new Point(event.offsetX, event.offsetY);\n var touchPoint = _this.findFocusedPage(cursorPoint, !_this.owner.enableHeaderAndFooter);\n if (_this.isMouseDown) {\n if (!isNullOrUndefined(_this.currentPage)) {\n var xPosition = touchPoint.x;\n var yPosition = touchPoint.y;\n if (!_this.owner.isReadOnlyMode && _this.isRowOrCellResizing) {\n _this.owner.editorModule.tableResize.handleResizing(touchPoint);\n }\n else {\n if (!(_this.isTouchInput || _this.isSelectionChangedOnMouseMoved || _this.touchDownOnSelectionMark > 0)) {\n _this.updateTextPositionForSelection(touchPoint, 1);\n }\n if (_this.isLeftButtonPressed(event)) {\n event.preventDefault();\n var touchY = yPosition;\n var textPosition = _this.owner.selection.end;\n var touchPoint_1 = new Point(xPosition, touchY);\n if (!_this.owner.enableImageResizerMode || !_this.owner.imageResizerModule.isImageResizerVisible) {\n _this.owner.selection.moveTextPosition(touchPoint_1, textPosition);\n }\n _this.isSelectionChangedOnMouseMoved = true;\n }\n }\n }\n _this.selection.checkForCursorVisibility();\n }\n if (!_this.isRowOrCellResizing && !_this.isSelectionChangedOnMouseMoved) {\n _this.updateCursor(event);\n }\n if (_this.isRowOrCellResizing) {\n _this.selection.hideCaret();\n }\n }\n };\n /**\n * Fired on double tap.\n * @param {MouseEvent} event\n * @private\n */\n this.onDoubleTap = function (event) {\n if (!isNullOrUndefined(_this.selection)) {\n _this.isTouchInput = false;\n var cursorPoint = new Point(event.offsetX, event.offsetY);\n if (_this.selection.checkAndEnableHeaderFooter(cursorPoint, _this.findFocusedPage(cursorPoint, true))) {\n return;\n }\n // tslint:disable-next-line:max-line-length\n if (_this.selection.isEmpty && !isNullOrUndefined(_this.currentPage) && !isNullOrUndefined(_this.owner.selection.start)) {\n _this.owner.selection.selectCurrentWord();\n _this.selection.checkForCursorVisibility();\n _this.tapCount = 2;\n }\n }\n };\n /**\n * Called on mouse up.\n * @param {MouseEvent} event\n * @private\n */\n this.onMouseUpInternal = function (event) {\n event.preventDefault();\n _this.isListTextSelected = false;\n var cursorPoint = new Point(event.offsetX, event.offsetY);\n var touchPoint = _this.findFocusedPage(cursorPoint, true);\n if (!isNullOrUndefined(_this.selection)) {\n var tapCount = 1;\n if (!Browser.isIE) {\n if (event.detail > 2) {\n tapCount = event.detail;\n }\n }\n else {\n tapCount = _this.tapCount;\n }\n if (_this.isRowOrCellResizing) {\n _this.owner.editorModule.tableResize.updateResizingHistory(touchPoint);\n }\n if (_this.isMouseDown && !_this.isSelectionChangedOnMouseMoved\n && !isNullOrUndefined(_this.currentPage) && !isNullOrUndefined(_this.owner.selection.start)\n && (!_this.owner.enableImageResizerMode || !_this.owner.imageResizerModule.isImageResizing)) {\n if (_this.touchDownOnSelectionMark === 0 && !_this.isRowOrCellResizing) {\n _this.updateTextPositionForSelection(touchPoint, tapCount);\n if (Browser.isIE && tapCount === 2) {\n _this.selection.checkAndEnableHeaderFooter(cursorPoint, touchPoint);\n }\n }\n _this.selection.checkForCursorVisibility();\n }\n if (!isNullOrUndefined(_this.currentPage) && !isNullOrUndefined(_this.owner.selection.start)\n && (_this.owner.selection.isEmpty || _this.owner.selection.isImageSelected) &&\n (((event.ctrlKey && _this.owner.useCtrlClickToFollowHyperlink ||\n !_this.owner.useCtrlClickToFollowHyperlink) && _this.isLeftButtonPressed(event) === true))) {\n _this.selection.navigateHyperLinkOnEvent(touchPoint, false);\n }\n if (!_this.owner.isReadOnlyMode && _this.isSelectionInListText(touchPoint)) {\n _this.selection.selectListText();\n }\n // tslint:disable-next-line:max-line-length\n if (!_this.owner.isReadOnlyMode && _this.owner.enableImageResizerMode && _this.owner.imageResizerModule.isImageResizing) {\n _this.owner.imageResizerModule.mouseUpInternal();\n _this.scrollToPosition(_this.owner.selection.start, _this.owner.selection.end);\n _this.owner.imageResizerModule.isImageResizing = false;\n _this.owner.imageResizerModule.updateHistoryForImageResizer();\n }\n // tslint:disable-next-line:max-line-length\n if (_this.owner.enableImageResizerMode && _this.owner.imageResizerModule.isImageResizerVisible && !isNullOrUndefined(_this.selection.caret)) {\n _this.selection.caret.style.display = 'none';\n }\n _this.isMouseDown = false;\n _this.isSelectionChangedOnMouseMoved = false;\n _this.isTouchInput = false;\n _this.useTouchSelectionMark = true;\n _this.isControlPressed = false;\n _this.updateFocus();\n if (_this.isListTextSelected) {\n _this.selection.hideCaret();\n }\n if (_this.owner.enableImageResizerMode) {\n var imageResizer = _this.owner.imageResizerModule;\n imageResizer.isImageResizing = false;\n imageResizer.isImageMoveToNextPage = false;\n imageResizer.leftValue = undefined;\n imageResizer.topValue = undefined;\n }\n _this.isMouseDownInFooterRegion = false;\n }\n };\n /**\n * Fired on touch start.\n * @param {TouchEvent} event\n * @private\n */\n this.onTouchStartInternal = function (event) {\n if (_this.selection) {\n _this.isCompositionStart = false;\n _this.isCompositionEnd = false;\n _this.isCompositionUpdated = false;\n _this.isCompositionCanceled = true;\n _this.isTouchInput = true;\n if (_this.isTimerStarted) {\n if (_this.tapCount === 1) {\n _this.tapCount = 2;\n }\n else {\n _this.tapCount = 3;\n _this.isTimerStarted = false;\n }\n }\n else {\n _this.isTimerStarted = true;\n _this.tapCount = 1;\n }\n if (event.touches.length === 1) {\n _this.zoomX = event.touches[0].clientX;\n _this.zoomY = event.touches[0].clientY;\n if (_this.owner.selection.isEmpty) {\n _this.useTouchSelectionMark = false;\n }\n _this.isMouseDown = true;\n _this.isSelectionChangedOnMouseMoved = false;\n var point = void 0;\n if (_this.isMouseDown) {\n point = _this.getTouchOffsetValue(event);\n }\n point = _this.findFocusedPage(point, true);\n if (_this.owner.enableImageResizerMode) {\n var resizeObj = _this.owner.imageResizerModule.getImagePointOnTouch(point);\n _this.owner.imageResizerModule.selectedResizeElement = resizeObj.selectedElement;\n }\n // tslint:disable-next-line:max-line-length\n if (_this.owner.enableImageResizerMode && !isNullOrUndefined(_this.owner.imageResizerModule.selectedResizeElement)) {\n _this.owner.imageResizerModule.isImageResizing = true;\n }\n var x = _this.owner.selection.end.location.x;\n var y = _this.selection.getCaretBottom(_this.owner.selection.end, _this.owner.selection.isEmpty) + 9;\n //TouchDownOnSelectionMark will be 2 when touch end is pressed\n _this.touchDownOnSelectionMark = ((point.y <= y && point.y >= y - 20 || point.y >= y && point.y <= y + 20)\n && (point.x <= x && point.x >= x - 20 || point.x >= x && point.x <= x + 20)) ? 1 : 0;\n if (!_this.owner.selection.isEmpty && _this.touchDownOnSelectionMark === 0) {\n x = _this.owner.selection.start.location.x;\n y = _this.selection.getCaretBottom(_this.owner.selection.start, false) + 9;\n //TouchDownOnSelectionMark will be 1 when touch start is pressed\n _this.touchDownOnSelectionMark = ((point.y <= y && point.y >= y - 20 || point.y >= y && point.y <= y + 20)\n && (point.x <= x && point.x >= x - 20 || point.x >= x && point.x <= x + 20)) ? 2 : 0;\n }\n }\n if (!isNullOrUndefined(_this.owner.contextMenuModule) && _this.owner.contextMenuModule.contextMenuInstance) {\n _this.owner.contextMenuModule.contextMenuInstance.close();\n }\n if (_this.touchDownOnSelectionMark || event.touches.length > 1) {\n event.preventDefault();\n }\n _this.timer = setTimeout(function () {\n _this.isTimerStarted = false;\n }, 200);\n }\n };\n /**\n * Fired on touch move.\n * @param {TouchEvent} event\n * @private\n */\n this.onTouchMoveInternal = function (event) {\n var touch = event.touches;\n var cursorPoint;\n if (!isNullOrUndefined(_this.selection)) {\n // tslint:disable-next-line:max-line-length\n if (_this.owner.editorModule && _this.owner.enableImageResizerMode && _this.owner.imageResizerModule.isImageResizing) {\n event.preventDefault();\n if (!_this.owner.imageResizerModule.isImageMoveToNextPage) {\n _this.owner.imageResizerModule.handleImageResizingOnTouch(event);\n _this.selection.caret.style.display = 'none';\n }\n return;\n }\n if (_this.isMouseDown) {\n cursorPoint = _this.getTouchOffsetValue(event);\n var touchPoint = _this.findFocusedPage(cursorPoint, true);\n if (_this.touchDownOnSelectionMark > 0 /*|| !this.useTouchSelectionMark*/) {\n event.preventDefault();\n var touchY = touchPoint.y;\n var textPosition = _this.owner.selection.end;\n var touchPointer = void 0;\n if (touchPoint.y <= 26) {\n touchY -= touchPoint.y < 0 ? 0 : touchPoint.y + 0.5;\n }\n else {\n touchY -= 36.5;\n }\n textPosition = _this.touchDownOnSelectionMark === 2 ? _this.selection.start : _this.selection.end;\n touchPoint = new Point(touchPoint.x, touchY);\n _this.owner.selection.moveTextPosition(touchPoint, textPosition);\n _this.isSelectionChangedOnMouseMoved = true;\n }\n _this.selection.checkForCursorVisibility();\n }\n }\n if (touch.length > 1) {\n event.preventDefault();\n _this.isMouseDown = false;\n _this.zoomX = (touch[0].clientX + touch[1].clientX) / 2;\n _this.zoomY = (touch[0].clientY + touch[1].clientY) / 2;\n // tslint:disable-next-line:max-line-length\n var currentDiff = Math.sqrt(Math.pow((touch[0].clientX - touch[1].clientX), 2) + Math.pow((touch[0].clientY - touch[1].clientY), 2));\n if (_this.preDifference > -1) {\n if (currentDiff > _this.preDifference) {\n _this.onPinchOutInternal(event);\n }\n else if (currentDiff < _this.preDifference) {\n _this.onPinchInInternal(event);\n }\n }\n else if (_this.zoomFactor < 2) {\n if (_this.preDifference !== -1) {\n if (currentDiff > _this.preDifference) {\n _this.onPinchInInternal(event);\n }\n }\n }\n else if (_this.preDifference === -1) {\n if (_this.zoomFactor > 2) {\n if (currentDiff > _this.preDifference) {\n _this.onPinchInInternal(event);\n }\n }\n }\n _this.preDifference = currentDiff;\n }\n };\n /**\n * Fired on touch up.\n * @param {TouchEvent} event\n * @private\n */\n this.onTouchUpInternal = function (event) {\n if (!isNullOrUndefined(_this.selection)) {\n var point = _this.getTouchOffsetValue(event);\n var touchPoint = _this.findFocusedPage(point, true);\n if (event.changedTouches.length === 1) {\n _this.zoomX = undefined;\n _this.zoomY = undefined;\n // tslint:disable-next-line:max-line-length\n if (_this.isMouseDown && !_this.isSelectionChangedOnMouseMoved && !isNullOrUndefined(_this.currentPage) && !isNullOrUndefined(_this.owner.selection.start)) {\n if (_this.touchDownOnSelectionMark === 0) {\n _this.updateTextPositionForSelection(new Point(touchPoint.x, touchPoint.y), _this.tapCount);\n if (_this.tapCount === 2) {\n _this.selection.checkAndEnableHeaderFooter(point, touchPoint);\n }\n }\n if (_this.owner.selection.isEmpty) {\n _this.selection.updateCaretPosition();\n }\n _this.selection.checkForCursorVisibility();\n }\n if (!isNullOrUndefined(_this.currentPage) && !isNullOrUndefined(_this.selection.start)\n && !_this.isSelectionChangedOnMouseMoved && (_this.selection.isEmpty ||\n _this.selection.isImageField() && (!_this.owner.enableImageResizerMode ||\n _this.owner.enableImageResizerMode && !_this.owner.imageResizerModule.isImageResizing))) {\n _this.selection.navigateHyperLinkOnEvent(touchPoint, true);\n }\n _this.isMouseDown = false;\n _this.touchDownOnSelectionMark = 0;\n _this.useTouchSelectionMark = true;\n _this.isSelectionChangedOnMouseMoved = false;\n }\n if (_this.owner.enableImageResizerMode && _this.owner.imageResizerModule.isImageResizing) {\n _this.owner.imageResizerModule.mouseUpInternal();\n _this.owner.imageResizerModule.isImageResizing = false;\n _this.owner.imageResizerModule.isImageMoveToNextPage = false;\n _this.scrollToPosition(_this.owner.selection.start, _this.owner.selection.end);\n _this.owner.imageResizerModule.updateHistoryForImageResizer();\n }\n // tslint:disable-next-line:max-line-length\n if (_this.owner.enableImageResizerMode && _this.owner.imageResizerModule.isImageResizerVisible && _this.isTouchInput) {\n _this.touchStart.style.display = 'none';\n _this.touchEnd.style.display = 'none';\n }\n // if (!this.owner.isReadOnlyMode && this.isSelectionInListText(touchPoint)) {\n // this.selection.selectListText();\n // }\n event.preventDefault();\n }\n _this.preDifference = -1;\n _this.isTouchInput = false;\n if (!_this.isTimerStarted) {\n _this.tapCount = 1;\n }\n if (_this.isListTextSelected) {\n _this.selection.hideCaret();\n }\n };\n /**\n * Fired on keyup event.\n * @private\n */\n this.onKeyUpInternal = function (event) {\n if (Browser.isDevice) {\n if (window.getSelection().anchorOffset !== _this.prefix.length) {\n _this.selection.setEditableDivCaretPosition(_this.editableDiv.innerText.length);\n }\n }\n if (event.ctrlKey || (event.keyCode === 17 || event.which === 17)) {\n _this.isControlPressed = false;\n }\n };\n /**\n * Fired on keydown.\n * @private\n */\n this.onKeyDownInternal = function (event) {\n var isHandled = false;\n var keyEventArgs = { 'event': event, 'isHandled': false };\n _this.owner.trigger('keyDown', keyEventArgs);\n if (keyEventArgs.isHandled) {\n return;\n }\n var key = event.which || event.keyCode;\n var ctrl = (event.ctrlKey || event.metaKey) ? true : ((key === 17) ? true : false); // ctrl detection \n var shift = event.shiftKey ? event.shiftKey : ((key === 16) ? true : false); // Shift Key detection \n var alt = event.altKey ? event.altKey : ((key === 18) ? true : false); // alt key detection\n if (ctrl && !shift && !alt) {\n switch (key) {\n case 80:\n event.preventDefault();\n _this.owner.print();\n isHandled = true;\n break;\n case 83:\n event.preventDefault();\n _this.owner.save(_this.owner.documentName === '' ? 'sample' : _this.owner.documentName, 'Sfdt');\n isHandled = true;\n break;\n }\n }\n if (!isHandled && !isNullOrUndefined(_this.selection)) {\n _this.selection.onKeyDownInternal(event, ctrl, shift, alt);\n }\n if (isHandled) {\n event.preventDefault();\n }\n };\n this.owner = owner;\n this.pages = [];\n this.render = new Renderer(this);\n this.lists = [];\n this.abstractLists = [];\n this.characterFormat = new WCharacterFormat(this);\n this.paragraphFormat = new WParagraphFormat(this);\n this.renderedLists = new Dictionary();\n this.headersFooters = [];\n this.styles = new WStyles();\n this.preDefinedStyles = new Dictionary();\n this.initalizeStyles();\n this.bookmarks = new Dictionary();\n }\n Object.defineProperty(LayoutViewer.prototype, \"containerCanvas\", {\n //#region Properties\n /**\n * Gets container canvas.\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.containerCanvasIn)) {\n this.containerCanvasIn = document.createElement('canvas');\n this.containerCanvasIn.getContext('2d').save();\n }\n if (!isNullOrUndefined(this.pageContainer)\n && this.containerCanvasIn.parentElement !== this.pageContainer) {\n this.pageContainer.appendChild(this.containerCanvasIn);\n }\n return this.containerCanvasIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"selectionCanvas\", {\n /**\n * Gets selection canvas.\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.selectionCanvasIn)) {\n this.selectionCanvasIn = document.createElement('canvas');\n this.selectionCanvas.getContext('2d').save();\n }\n if (!isNullOrUndefined(this.pageContainer)\n && this.selectionCanvasIn.parentElement !== this.pageContainer) {\n this.pageContainer.appendChild(this.selectionCanvasIn);\n }\n return this.selectionCanvasIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"containerContext\", {\n /**\n * Gets container context.\n * @private\n */\n get: function () {\n return this.containerCanvas.getContext('2d');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"selectionContext\", {\n /**\n * Gets selection context.\n * @private\n */\n get: function () {\n return this.selectionCanvas.getContext('2d');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"currentRenderingPage\", {\n /**\n * Gets the current rendering page.\n */\n get: function () {\n if (this.pages.length === 0) {\n return undefined;\n }\n return this.pages[this.pages.length - 1];\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"visibleBounds\", {\n /**\n * Gets visible bounds.\n * @private\n */\n get: function () {\n return this.visibleBoundsIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"zoomFactor\", {\n /**\n * Gets or sets zoom factor.\n * @private\n */\n get: function () {\n return this.zoomFactorInternal;\n },\n set: function (value) {\n if (this.zoomFactorInternal !== value) {\n this.preZoomFactor = this.zoomFactor;\n this.zoomFactorInternal = value;\n this.zoomModule.setZoomFactor(value);\n this.owner.zoomFactor = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"selection\", {\n /**\n * Gets the selection.\n * @private\n */\n get: function () {\n return this.owner.selection;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"selectionStartPage\", {\n /**\n * Gets or sets selection start page.\n * @private\n */\n get: function () {\n return this.selectionStartPageIn;\n },\n set: function (value) {\n this.selectionStartPageIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"selectionEndPage\", {\n /**\n * Gets or sets selection end page.\n * @private\n */\n get: function () {\n return this.selectionEndPageIn;\n },\n set: function (value) {\n this.selectionEndPageIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"dialog\", {\n /**\n * Gets the initialized default dialog.\n * @private\n */\n get: function () {\n if (!this.dialogInternal) {\n this.initDialog();\n }\n return this.dialogInternal;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"dialog2\", {\n /**\n * Gets the initialized default dialog.\n * @private\n */\n get: function () {\n if (!this.dialogInternal2) {\n this.initDialog2();\n }\n return this.dialogInternal2;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(LayoutViewer.prototype, \"pageFitType\", {\n /**\n * Gets or sets page fit type.\n * @private\n */\n get: function () {\n return this.pageFitTypeIn;\n },\n set: function (value) {\n this.pageFitTypeIn = value;\n this.onPageFitTypeChanged(this.pageFitTypeIn);\n },\n enumerable: true,\n configurable: true\n });\n LayoutViewer.prototype.initalizeStyles = function () {\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Normal', '{\"type\":\"Paragraph\",\"name\":\"Normal\",\"next\":\"Normal\"}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 1', '{\"type\":\"Paragraph\",\"name\":\"Heading 1\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"link\":\"Heading 1 Char\",\"characterFormat\":{\"fontSize\":16.0,\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"},\"paragraphFormat\":{\"leftIndent\":0.0,\"rightIndent\":0.0,\"firstLineIndent\":0.0,\"beforeSpacing\":12.0,\"afterSpacing\":0.0,\"lineSpacing\":1.0791666507720947,\"lineSpacingType\":\"Multiple\",\"textAlignment\":\"Left\",\"outlineLevel\":\"Level1\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 2', '{\"type\":\"Paragraph\",\"name\":\"Heading 2\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"link\":\"Heading 2 Char\",\"characterFormat\":{\"fontSize\":13.0,\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"},\"paragraphFormat\":{\"leftIndent\":0.0,\"rightIndent\":0.0,\"firstLineIndent\":0.0,\"beforeSpacing\":2.0,\"afterSpacing\":0.0,\"lineSpacing\":1.0791666507720947,\"lineSpacingType\":\"Multiple\",\"textAlignment\":\"Left\",\"outlineLevel\":\"Level2\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 3', '{\"type\":\"Paragraph\",\"name\":\"Heading 3\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"link\":\"Heading 3 Char\",\"characterFormat\":{\"fontSize\":12.0,\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#1F3763\"},\"paragraphFormat\":{\"leftIndent\":0.0,\"rightIndent\":0.0,\"firstLineIndent\":0.0,\"beforeSpacing\":2.0,\"afterSpacing\":0.0,\"lineSpacing\":1.0791666507720947,\"lineSpacingType\":\"Multiple\",\"textAlignment\":\"Left\",\"outlineLevel\":\"Level3\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 4', '{\"type\":\"Paragraph\",\"name\":\"Heading 4\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"link\":\"Heading 4 Char\",\"characterFormat\":{\"italic\":true,\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"},\"paragraphFormat\":{\"leftIndent\":0.0,\"rightIndent\":0.0,\"firstLineIndent\":0.0,\"beforeSpacing\":2.0,\"afterSpacing\":0.0,\"lineSpacing\":1.0791666507720947,\"lineSpacingType\":\"Multiple\",\"textAlignment\":\"Left\",\"outlineLevel\":\"Level4\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 5', '{\"type\":\"Paragraph\",\"name\":\"Heading 5\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"link\":\"Heading 5 Char\",\"characterFormat\":{\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"},\"paragraphFormat\":{\"leftIndent\":0.0,\"rightIndent\":0.0,\"firstLineIndent\":0.0,\"beforeSpacing\":2.0,\"afterSpacing\":0.0,\"lineSpacing\":1.0791666507720947,\"lineSpacingType\":\"Multiple\",\"textAlignment\":\"Left\",\"outlineLevel\":\"Level5\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 6', '{\"type\":\"Paragraph\",\"name\":\"Heading 6\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"link\":\"Heading 6 Char\",\"characterFormat\":{\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#1F3763\"},\"paragraphFormat\":{\"leftIndent\":0.0,\"rightIndent\":0.0,\"firstLineIndent\":0.0,\"beforeSpacing\":2.0,\"afterSpacing\":0.0,\"lineSpacing\":1.0791666507720947,\"lineSpacingType\":\"Multiple\",\"textAlignment\":\"Left\",\"outlineLevel\":\"Level6\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Default Paragraph Font', '{\"type\":\"Character\",\"name\":\"Default Paragraph Font\"}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 1 Char', '{\"type\":\"Character\",\"name\":\"Heading 1 Char\",\"basedOn\":\"Default Paragraph Font\",\"characterFormat\":{\"fontSize\":16.0,\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 2 Char', '{\"type\":\"Character\",\"name\":\"Heading 2 Char\",\"basedOn\":\"Default Paragraph Font\",\"characterFormat\":{\"fontSize\":13.0,\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 3 Char', '{\"type\":\"Character\",\"name\":\"Heading 3 Char\",\"basedOn\":\"Default Paragraph Font\",\"characterFormat\":{\"fontSize\":12.0,\"fontFamily\":\"Calibri Light\",\"fontColor\": \"#1F3763\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 4 Char', '{\"type\":\"Character\",\"name\":\"Heading 4 Char\",\"basedOn\":\"Default Paragraph Font\",\"characterFormat\":{\"italic\":true,\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 5 Char', '{\"type\":\"Character\",\"name\":\"Heading 5 Char\",\"basedOn\":\"Default Paragraph Font\",\"characterFormat\":{\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#2F5496\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Heading 6 Char', '{\"type\":\"Character\",\"name\":\"Heading 6 Char\",\"basedOn\":\"Default Paragraph Font\",\"characterFormat\":{\"fontFamily\":\"Calibri Light\",\"fontColor\":\"#1F3763\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Hyperlink', '{\"type\":\"Character\",\"name\":\"Hyperlink\",\"basedOn\":\"Default Paragraph Font\",\"next\":\"Normal\",\"characterFormat\":{\"fontColor\":\"#0563C1\",\"underline\": \"Single\"}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc1', '{\"type\":\"Paragraph\",\"name\":\"Toc1\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc2', '{\"type\":\"Paragraph\",\"name\":\"Toc2\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :11.0,\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc3', '{\"type\":\"Paragraph\",\"name\":\"Toc3\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :22.0,\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc4', '{\"type\":\"Paragraph\",\"name\":\"Toc4\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :33.0,\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc5', '{\"type\":\"Paragraph\",\"name\":\"Toc5\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :44.0,\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc6', '{\"type\":\"Paragraph\",\"name\":\"Toc6\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :55.0,\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc7', '{\"type\":\"Paragraph\",\"name\":\"Toc7\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :66.0,\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc8', '{\"type\":\"Paragraph\",\"name\":\"Toc8\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :77.0,\"afterSpacing\":5.0}}');\n /* tslint:disable-next-line:max-line-length */\n this.preDefinedStyles.add('Toc9', '{\"type\":\"Paragraph\",\"name\":\"Toc9\",\"basedOn\":\"Normal\",\"next\":\"Normal\",\"paragraphFormat\":{\"leftIndent\" :88.0,\"afterSpacing\":5.0}}');\n };\n /**\n * @private\n */\n LayoutViewer.prototype.clearDocumentItems = function () {\n this.headersFooters = [];\n this.fields = [];\n this.bookmarks.clear();\n this.styles.clear();\n this.characterFormat.clearFormat();\n this.paragraphFormat.clearFormat();\n };\n /**\n * @private\n */\n LayoutViewer.prototype.getAbstractListById = function (id) {\n if (isNullOrUndefined(this.abstractLists)) {\n return undefined;\n }\n for (var i = 0; i < this.abstractLists.length; i++) {\n var abstractList = this.abstractLists[i];\n if (abstractList instanceof WAbstractList && abstractList.abstractListId === id) {\n return abstractList;\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n LayoutViewer.prototype.getListById = function (id) {\n if (isNullOrUndefined(this.lists)) {\n return undefined;\n }\n for (var i = 0; i < this.lists.length; i++) {\n if (!isNullOrUndefined(this.lists[i]) && this.lists[i].listId === id) {\n return this.lists[i];\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n LayoutViewer.getListLevelNumber = function (listLevel) {\n if (listLevel.ownerBase instanceof WLevelOverride) {\n return listLevel.ownerBase.levelNumber;\n }\n else if (listLevel.ownerBase instanceof WAbstractList && !isNullOrUndefined(listLevel.ownerBase.levels)) {\n return listLevel.ownerBase.levels.indexOf(listLevel);\n }\n else {\n return -1;\n }\n };\n /**\n * Gets the bookmarks.\n * @private\n */\n LayoutViewer.prototype.getBookmarks = function (includeHidden) {\n var bookmarks = [];\n for (var i = 0; i < this.bookmarks.keys.length; i++) {\n var bookmark = this.bookmarks.keys[i];\n if (includeHidden || bookmark.indexOf('_') !== 0) {\n bookmarks.push(bookmark);\n }\n }\n return bookmarks;\n };\n /**\n * Initializes components.\n * @private\n */\n LayoutViewer.prototype.initializeComponents = function () {\n var element = this.owner.element;\n if (isNullOrUndefined(element)) {\n return;\n }\n var viewer = this;\n this.viewerContainer = createElement('div', { id: this.owner.containerId + '_viewerContainer' });\n this.viewerContainer.style.cssText = 'position:relative;backgroundColor:#FBFBFB;overflow:auto';\n element.appendChild(this.viewerContainer);\n this.viewerContainer.tabIndex = 0;\n this.viewerContainer.style.outline = 'none';\n this.pageContainer = createElement('div', { id: this.owner.containerId + '_pageContainer', className: 'e-de-background' });\n this.viewerContainer.appendChild(this.pageContainer);\n this.pageContainer.style.top = '0px';\n this.pageContainer.style.left = '0px';\n this.pageContainer.style.position = 'relative';\n this.pageContainer.style.pointerEvents = 'none';\n this.editableDiv = document.createElement('div');\n this.editableDiv.contentEditable = 'true';\n this.editableDiv.style.position = 'fixed';\n this.editableDiv.style.left = '-150em';\n this.editableDiv.style.width = '100%';\n this.editableDiv.style.height = '100%';\n this.editableDiv.id = element.id + '_editableDiv';\n this.owner.element.appendChild(this.editableDiv);\n if (this.owner.enableImageResizerMode) {\n this.owner.imageResizerModule.initializeImageResizer();\n }\n this.updateViewerSizeInternal(element);\n this.layout = new Layout(this);\n this.textHelper = new TextHelper(this);\n this.zoomModule = new Zoom(this);\n // let locale: L10n = new L10n('documenteditor', this.owner.defaultLocale);\n // locale.setLocale(this.owner.locale);\n // setCulture(this.owner.locale);\n this.initTouchEllipse();\n this.wireEvent();\n };\n /**\n * Wires events and methods.\n */\n LayoutViewer.prototype.wireEvent = function () {\n if (!isNullOrUndefined(this.selection)) {\n this.selection.initCaret();\n }\n this.editableDiv.addEventListener('paste', this.onPaste);\n if (Browser.isIE) {\n this.editableDiv.addEventListener('keypress', this.onTextInputInternal);\n }\n else {\n this.editableDiv.addEventListener('input', this.onTextInputInternal);\n }\n this.editableDiv.addEventListener('blur', this.onFocusOut);\n this.editableDiv.addEventListener('keydown', this.onKeyDownInternal);\n this.editableDiv.addEventListener('compositionstart', this.compositionStart);\n this.editableDiv.addEventListener('compositionupdate', this.compositionUpdated);\n this.editableDiv.addEventListener('compositionend', this.compositionEnd);\n this.viewerContainer.addEventListener('scroll', this.scrollHandler);\n this.viewerContainer.addEventListener('mousedown', this.onMouseDownInternal);\n this.viewerContainer.addEventListener('keydown', this.onKeyDownInternal);\n this.viewerContainer.addEventListener('mousemove', this.onMouseMoveInternal);\n this.viewerContainer.addEventListener('contextmenu', this.onContextMenu);\n this.viewerContainer.addEventListener('dblclick', this.onDoubleTap);\n this.viewerContainer.addEventListener('mouseup', this.onMouseUpInternal);\n window.addEventListener('resize', this.onWindowResize);\n window.addEventListener('keyup', this.onKeyUpInternal);\n window.addEventListener('mouseup', this.onImageResizer);\n window.addEventListener('touchend', this.onImageResizer);\n this.viewerContainer.addEventListener('touchstart', this.onTouchStartInternal);\n this.viewerContainer.addEventListener('touchmove', this.onTouchMoveInternal);\n this.viewerContainer.addEventListener('touchend', this.onTouchUpInternal);\n if (navigator.userAgent.match('Firefox')) {\n this.viewerContainer.addEventListener('DOMMouseScroll', this.zoomModule.onMouseWheelInternal);\n }\n this.viewerContainer.addEventListener('mousewheel', this.zoomModule.onMouseWheelInternal);\n };\n /**\n * Initializes dialog template.\n */\n LayoutViewer.prototype.initDialog = function () {\n if (!this.dialogInternal) {\n this.dialogTarget = createElement('div', { className: 'e-de-dlg-target' });\n document.body.appendChild(this.dialogTarget);\n this.dialogInternal = new Dialog({\n target: document.body, showCloseIcon: true,\n allowDragging: true, visible: false, width: '1px', isModal: true, position: { X: 'center', Y: 'center' }, zIndex: 20\n });\n this.dialogInternal.open = this.selection.hideCaret;\n this.dialogInternal.beforeClose = this.updateFocus;\n this.dialogInternal.appendTo(this.dialogTarget);\n }\n };\n /**\n * Initializes dialog template.\n */\n LayoutViewer.prototype.initDialog2 = function () {\n if (!this.dialogInternal2) {\n var target = createElement('div', { className: 'e-de-dlg-target' });\n document.body.appendChild(target);\n this.dialogInternal2 = new Dialog({\n target: document.body, showCloseIcon: true,\n allowDragging: true, visible: false, width: '1px', isModal: true, position: { X: 'center', Y: 'Top' }, zIndex: 10\n });\n this.dialogInternal2.appendTo(target);\n }\n };\n /**\n * Clears the context.\n * @private\n */\n LayoutViewer.prototype.clearContent = function () {\n this.containerContext.clearRect(0, 0, this.containerCanvas.width, this.containerCanvas.height);\n this.selectionContext.clearRect(0, 0, this.selectionCanvas.width, this.selectionCanvas.height);\n };\n /**\n * Fired when the document gets changed.\n * @param {WordDocument} document\n */\n LayoutViewer.prototype.onDocumentChanged = function (sections) {\n this.clearContent();\n if (this.owner.editorModule) {\n this.owner.editorModule.tocStyles = {};\n this.owner.editorModule.tocBookmarkId = 0;\n }\n this.heightInfoCollection = {};\n this.owner.isDocumentLoaded = false;\n for (var i = 0; i < this.pages.length; i++) {\n this.pages[i].bodyWidgets[0].destroy();\n }\n this.pages = [];\n if (!isNullOrUndefined(this.renderedLists)) {\n this.renderedLists.clear();\n }\n if (!isNullOrUndefined(this.owner.editorHistory)) {\n this.owner.editorHistory.destroy();\n }\n this.owner.isDocumentLoaded = true;\n this.layout.isInitialLoad = true;\n this.layout.layoutItems(sections);\n if (this.owner.selection) {\n this.owner.selection.selectRange(this.owner.documentStart, this.owner.documentStart);\n }\n if (this.owner.optionsPaneModule) {\n this.owner.optionsPaneModule.showHideOptionsPane(false);\n }\n this.owner.fireDocumentChange();\n };\n /**\n * Initialize touch ellipse.\n */\n LayoutViewer.prototype.initTouchEllipse = function () {\n var style = 'height: 30px;width: 30px;position: absolute;background-color: transparent;margin: 0px;padding: 0px;z-index:5';\n // tslint:disable-next-line:max-line-length\n var ellipse = ' height: 12px;width: 12px;border-radius: 50%;background-color: white;position: absolute;margin: 0px 6px 0px 6px;border-width: 2px;border-style: solid;border-color: #000000;';\n this.touchStart = createElement('div', { className: 'e-touch-ellipse', styles: style });\n var start = createElement('div', { styles: ellipse });\n this.touchEnd = createElement('div', { className: 'e-touch-ellipse', styles: style });\n this.touchStart.style.display = 'none';\n var end = createElement('div', { styles: ellipse });\n this.touchStart.appendChild(start);\n this.touchEnd.appendChild(end);\n this.touchEnd.style.display = 'none';\n this.viewerContainer.appendChild(this.touchStart);\n this.viewerContainer.appendChild(this.touchEnd);\n };\n /**\n * Updates touch mark position.\n * @private\n */\n LayoutViewer.prototype.updateTouchMarkPosition = function () {\n if (this.touchStart.style.display !== 'none' && !isNullOrUndefined(this.selection)) {\n if (!this.selection.isEmpty) {\n var y = this.selection.getCaretBottom(this.selection.start, false);\n var page = this.selection.getPage(this.selection.start.paragraph);\n var viewer = this;\n // tslint:disable-next-line:max-line-length\n var pageTop = (page.boundingRectangle.y - viewer.pageGap * (this.pages.indexOf(page) + 1)) * this.zoomFactor + viewer.pageGap * (this.pages.indexOf(page) + 1);\n // tslint:disable-next-line:max-line-length\n this.touchStart.style.left = page.boundingRectangle.x + (Math.round(this.selection.start.location.x) * this.zoomFactor - 14) + 'px';\n this.touchStart.style.top = pageTop + ((y) * this.zoomFactor) + 'px';\n if (!this.selection.isEmpty) {\n y = this.selection.getCaretBottom(this.selection.end, false);\n page = this.selection.getPage(this.selection.end.paragraph);\n }\n // tslint:disable-next-line:max-line-length\n this.touchEnd.style.left = page.boundingRectangle.x + (Math.round(this.selection.end.location.x) * this.zoomFactor - 14) + 'px';\n this.touchEnd.style.top = pageTop + (y * this.zoomFactor) + 'px';\n }\n else {\n this.selection.updateCaretPosition();\n }\n }\n };\n LayoutViewer.prototype.isSelectionInListText = function (cursorPoint) {\n var widget = this.getLineWidget(cursorPoint);\n if (!isNullOrUndefined(widget) && widget.children[0] instanceof ListTextElementBox) {\n var left = this.getLeftValue(widget);\n var width = widget.children[0].width;\n var height = widget.children[0].height;\n if (this.isInsideRect(left, widget.paragraph.y, width, height, cursorPoint)) {\n this.selectionLineWidget = widget;\n return true;\n }\n }\n return false;\n };\n /**\n * Check whether touch point is inside the rectangle or not.\n * @param x\n * @param y\n * @param width\n * @param height\n * @param touchPoint\n * @private\n */\n LayoutViewer.prototype.isInsideRect = function (x, y, width, height, touchPoint) {\n if ((touchPoint.x > x && touchPoint.x <= x + width) && (touchPoint.y > y && touchPoint.y <= y + height)) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n LayoutViewer.prototype.getLeftValue = function (widget) {\n var left = widget.paragraph.x;\n var paragraphFormat = widget.paragraph.paragraphFormat;\n if (this.selection.isParagraphFirstLine(widget)) {\n if (paragraphFormat.textAlignment === 'Right') {\n left -= HelperMethods.convertPointToPixel(paragraphFormat.firstLineIndent);\n left -= HelperMethods.convertPointToPixel(paragraphFormat.leftIndent);\n }\n else {\n left += HelperMethods.convertPointToPixel(paragraphFormat.firstLineIndent);\n }\n }\n var element = widget.children[0];\n if (element instanceof ListTextElementBox) {\n left += element.margin.left;\n }\n return left;\n };\n /**\n * Checks whether left mouse button is pressed or not.\n */\n LayoutViewer.prototype.isLeftButtonPressed = function (event) {\n this.isTouchInput = false;\n var button = event.which || event.button;\n return button === 1;\n };\n /**\n * Gets touch offset value.\n */\n LayoutViewer.prototype.getTouchOffsetValue = function (event) {\n var targetElement = this.viewerContainer;\n var offset = targetElement.getBoundingClientRect();\n var touchOffsetValues = event.touches[0];\n if (isNullOrUndefined(touchOffsetValues)) {\n touchOffsetValues = event.changedTouches[0];\n }\n var offsetX = touchOffsetValues.pageX - offset.left;\n var offsetY = touchOffsetValues.pageY - offset.top;\n return new Point(offsetX, offsetY);\n };\n /**\n * Fired on pinch zoom in.\n * @param {TouchEvent} event\n */\n LayoutViewer.prototype.onPinchInInternal = function (event) {\n this.preZoomFactor = this.zoomFactor;\n var updatedZoomFactor = this.zoomFactor - 0.01;\n if (updatedZoomFactor < 5 && updatedZoomFactor > 2) {\n updatedZoomFactor = updatedZoomFactor - 0.01;\n }\n if (updatedZoomFactor < 0.1) {\n updatedZoomFactor = 0.1;\n }\n this.zoomFactor = updatedZoomFactor;\n };\n /**\n * Fired on pinch zoom out.\n * @param {TouchEvent} event\n */\n LayoutViewer.prototype.onPinchOutInternal = function (event) {\n this.preZoomFactor = this.zoomFactor;\n var updatedZoomFactor = this.zoomFactor + 0.01;\n if (updatedZoomFactor > 2) {\n updatedZoomFactor = updatedZoomFactor + 0.01;\n }\n if (updatedZoomFactor > 5) {\n updatedZoomFactor = 5;\n }\n this.zoomFactor = updatedZoomFactor;\n };\n /**\n * Gets page width.\n * @private\n */\n LayoutViewer.prototype.getPageWidth = function (page) {\n var width = page.boundingRectangle.width;\n return width;\n };\n /**\n * Removes specified page.\n * @private\n */\n LayoutViewer.prototype.removePage = function (page) {\n if (this.currentPage === page) {\n this.currentPage = undefined;\n }\n var index = this.pages.indexOf(page);\n // if (index > -1) {\n this.pages.splice(index, 1);\n // } \n //this.removeRenderedPages();\n var viewer = this;\n if (!isNullOrUndefined(viewer.visiblePages)) {\n if ((viewer.visiblePages).indexOf(page) > -1) {\n var pageIndex = (viewer.visiblePages).indexOf(page);\n (viewer.visiblePages).splice(pageIndex, 1);\n }\n }\n //(viewer as PageLayoutViewer).visiblePages.remove(page);\n var height = 0;\n for (var i = 0; i < this.pages.length; i++) {\n height = height + this.pages[i].boundingRectangle.height;\n }\n //Updates the vertical height.\n height -= page.boundingRectangle.height + 20;\n //ToDo:Update horizontal width, if removed page has max width.\n var top = 20;\n if (index > 0) {\n top += this.pages[index - 1].boundingRectangle.bottom;\n }\n if (index !== -1) {\n for (var i = index; i < this.pages.length; i++) {\n //Update bounding rectangle of next pages in collection.\n page = this.pages[i];\n // tslint:disable-next-line:max-line-length\n page.boundingRectangle = new Rect(page.boundingRectangle.x, top, page.boundingRectangle.width, page.boundingRectangle.height);\n top = page.boundingRectangle.bottom + 20;\n page.repeatHeaderRowTableWidget = false;\n }\n }\n };\n // private removeRenderedPages(): void {\n // for (let i: number = 0; i < this.pages.length; i++) {\n // this.clearContainer(this.pages[i]);\n // }\n // }\n /**\n * Updates viewer size on window resize.\n * @private\n */\n LayoutViewer.prototype.updateViewerSize = function () {\n var viewer = this;\n var element = this.owner.getDocumentEditorElement();\n viewer.updateViewerSizeInternal(element);\n viewer.updateScrollBars();\n if (!isNullOrUndefined(this.selection)) {\n this.selection.updateCaretPosition();\n }\n };\n /**\n * Updates viewer size.\n */\n LayoutViewer.prototype.updateViewerSizeInternal = function (element) {\n if (!isNullOrUndefined(element)) {\n var rect = element.getBoundingClientRect();\n var width = 0;\n var height = 0;\n height = rect.height > 0 ? rect.height : 200;\n if (this.owner.optionsPaneModule && this.owner.optionsPaneModule.isOptionsPaneShow) {\n var optionsRect = this.owner.optionsPaneModule.optionsPane.getBoundingClientRect();\n width = (rect.width - optionsRect.width) > 0 ? (rect.width - optionsRect.width) : 200;\n }\n else {\n width = rect.width > 0 ? rect.width : 200;\n }\n this.viewerContainer.style.height = height.toString() + 'px';\n this.viewerContainer.style.width = Math.ceil(width) + 'px';\n this.visibleBoundsIn = new Rect(0, 0, width, height);\n this.containerCanvas.width = width;\n this.containerCanvas.height = height;\n this.selectionCanvas.width = width;\n this.selectionCanvas.height = height;\n }\n };\n /**\n * Updates client area for block.\n * @private\n */\n LayoutViewer.prototype.updateClientAreaForBlock = function (block, beforeLayout, tableCollection) {\n var leftIndent = HelperMethods.convertPointToPixel(block.leftIndent);\n var rightIndent = HelperMethods.convertPointToPixel(block.rightIndent);\n if (beforeLayout) {\n if (block instanceof TableWidget && tableCollection) {\n var tableWidget = tableCollection[0];\n this.clientActiveArea.x = this.clientArea.x = tableWidget.x;\n this.clientActiveArea.width = this.clientArea.width = tableWidget.width;\n //Updates the location of last item.\n tableWidget = tableCollection[tableCollection.length - 1];\n tableWidget.x = this.clientActiveArea.x;\n tableWidget.y = this.clientActiveArea.y;\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n else {\n // tslint:disable-next-line:max-line-length\n if (block instanceof TableWidget && !isNullOrUndefined(block.tableFormat) && block.tableFormat.tableAlignment !== 'Left') {\n if (!block.isGridUpdated) {\n block.buildTableColumns();\n block.isGridUpdated = true;\n }\n var tableWidth = block.getMaxRowWidth(block.getTableClientWidth(block.getOwnerWidth(false)));\n // Fore resizing table, the tableholder table width taken for updated width. \n // Since, the columns will be cleared if we performed resizing.\n if (this.owner.editor && this.owner.editor.tableResize.currentResizingTable === block\n && this.owner.editor.tableResize.resizerPosition === 0) {\n tableWidth = block.tableHolder.tableWidth;\n }\n tableWidth = HelperMethods.convertPointToPixel(tableWidth);\n if (block.tableFormat.tableAlignment === 'Center') {\n leftIndent = (this.clientArea.width - tableWidth) / 2;\n }\n else {\n leftIndent = this.clientArea.width - tableWidth;\n }\n this.tableLefts.push(leftIndent);\n }\n this.clientActiveArea.x = this.clientArea.x = this.clientArea.x + leftIndent;\n var width = this.clientArea.width - (leftIndent + rightIndent);\n this.clientActiveArea.width = this.clientArea.width = width > 0 ? width : 0;\n // tslint:disable-next-line:max-line-length\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n }\n else {\n // tslint:disable-next-line:max-line-length\n if (block instanceof TableWidget && block.tableFormat.tableAlignment !== 'Left' && this.tableLefts.length > 0) {\n leftIndent = this.tableLefts.pop();\n }\n this.clientActiveArea.x = this.clientArea.x = this.clientArea.x - leftIndent;\n var width = this.clientArea.width + leftIndent + rightIndent;\n this.clientActiveArea.width = this.clientArea.width = width > 0 ? width : 0;\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n };\n /**\n * Updates client active area left.\n * @private\n */\n LayoutViewer.prototype.cutFromLeft = function (x) {\n if (x < this.clientActiveArea.x) {\n x = this.clientActiveArea.x;\n }\n if (x > this.clientActiveArea.right && this.textWrap) {\n x = this.clientActiveArea.right;\n }\n this.clientActiveArea.width = this.clientActiveArea.right > x ? this.clientActiveArea.right - x : 0;\n this.clientActiveArea.x = x;\n };\n /**\n * Updates client active area top.\n * @private\n */\n LayoutViewer.prototype.cutFromTop = function (y) {\n if (y < this.clientActiveArea.y) {\n y = this.clientActiveArea.y;\n }\n if (y > this.clientActiveArea.bottom) {\n y = this.clientActiveArea.bottom;\n }\n this.clientActiveArea.height = this.clientActiveArea.bottom - y;\n this.clientActiveArea.x = this.clientArea.x;\n this.clientActiveArea.width = this.clientArea.width;\n this.clientActiveArea.y = y;\n };\n /**\n * Updates client width.\n * @private\n */\n LayoutViewer.prototype.updateClientWidth = function (width) {\n this.clientActiveArea.x -= width;\n if (this.clientActiveArea.width + width > 0) {\n this.clientActiveArea.width += width;\n }\n else {\n this.clientActiveArea.width = 0;\n }\n };\n /**\n * Inserts page in specified index.\n * @private\n */\n LayoutViewer.prototype.insertPage = function (index, page) {\n if (this.pages.indexOf(page) > -1) {\n this.pages.splice(this.pages.indexOf(page), 1);\n }\n this.pages.splice(index, 0, page);\n var top = 20;\n if (index > 0) {\n top += this.pages[index - 1].boundingRectangle.bottom;\n }\n for (var i = index; i < this.pages.length; i++) {\n //Update bounding rectangle of next pages in collection.\n page = this.pages[i];\n page.boundingRectangle = new Rect(page.boundingRectangle.x, top, page.boundingRectangle.width, page.boundingRectangle.height);\n top = page.boundingRectangle.bottom + 20;\n }\n };\n /**\n * Updates client area.\n * @private\n */\n LayoutViewer.prototype.updateClientArea = function (sectionFormat, page) {\n var top = 0;\n var headerDistance = 48;\n var footerDistance = 48;\n var pageHeight = HelperMethods.convertPointToPixel(sectionFormat.pageHeight);\n var bottomMargin = HelperMethods.convertPointToPixel(sectionFormat.bottomMargin);\n if (!isNullOrUndefined(sectionFormat)) {\n top = HelperMethods.convertPointToPixel(sectionFormat.topMargin);\n headerDistance = HelperMethods.convertPointToPixel(sectionFormat.headerDistance);\n footerDistance = HelperMethods.convertPointToPixel(sectionFormat.footerDistance);\n }\n if (!isNullOrUndefined(page.headerWidget)) {\n top = Math.min(Math.max(headerDistance + page.headerWidget.height, top), pageHeight / 100 * 40);\n }\n var bottom = 0.667 + bottomMargin;\n if (!isNullOrUndefined(page.footerWidget)) {\n bottom = 0.667 + Math.min(pageHeight / 100 * 40, Math.max(footerDistance + page.footerWidget.height, bottomMargin));\n }\n var width = 0;\n var height = 0;\n if (!isNullOrUndefined(sectionFormat)) {\n width = HelperMethods.convertPointToPixel(sectionFormat.pageWidth - sectionFormat.leftMargin - sectionFormat.rightMargin);\n height = pageHeight - top - bottom;\n }\n if (width < 0) {\n width = 0;\n }\n this.clientArea = new Rect(HelperMethods.convertPointToPixel(sectionFormat.leftMargin), top, width, pageHeight - top - bottom);\n this.clientActiveArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n };\n /**\n * Updates client area left or top position.\n * @private\n */\n LayoutViewer.prototype.updateClientAreaTopOrLeft = function (tableWidget, beforeLayout) {\n if (beforeLayout) {\n this.clientActiveArea.y = this.clientActiveArea.y + tableWidget.topBorderWidth;\n this.clientActiveArea.x = this.clientActiveArea.x + tableWidget.leftBorderWidth;\n }\n };\n /**\n * Updates client area for table.\n * @private\n */\n LayoutViewer.prototype.updateClientAreaForTable = function (tableWidget) {\n this.clientActiveArea.x = this.clientArea.x = tableWidget.x;\n this.clientActiveArea.width = this.clientArea.width = tableWidget.width;\n };\n /**\n * Updates client area for row.\n * @private\n */\n LayoutViewer.prototype.updateClientAreaForRow = function (row, beforeLayout) {\n // tslint:disable-next-line:max-line-length\n var tableWidget = row.ownerTable;\n if (beforeLayout) {\n //tslint:disable:no-empty\n }\n else {\n this.clientActiveArea.x = this.clientArea.x = tableWidget.x;\n this.clientActiveArea.width = this.clientArea.width = tableWidget.width;\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n };\n /**\n * Updates client area for cell.\n * @private\n */\n LayoutViewer.prototype.updateClientAreaForCell = function (cell, beforeLayout) {\n // tslint:disable-next-line:max-line-length\n var rowWidget = cell.ownerRow;\n var cellWidget = cell;\n if (beforeLayout) {\n this.clientActiveArea.x = this.clientArea.x = cellWidget.x;\n this.clientActiveArea.y = cellWidget.y;\n this.clientActiveArea.width = this.clientArea.width = cellWidget.width > 0 ? cellWidget.width : 0;\n if (this instanceof PageLayoutViewer) {\n this.clientActiveArea.height = Number.POSITIVE_INFINITY;\n }\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n else {\n this.clientActiveArea.x = this.clientArea.x = cellWidget.x + cellWidget.width + cellWidget.margin.right;\n if (rowWidget.x + rowWidget.width - this.clientArea.x < 0) {\n this.clientActiveArea.width = this.clientArea.width = 0;\n }\n else {\n this.clientActiveArea.width = this.clientArea.width = rowWidget.x + rowWidget.width - this.clientArea.x;\n }\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea.y = cellWidget.y - cellWidget.margin.top - HelperMethods.convertPointToPixel(cell.ownerTable.tableFormat.cellSpacing);\n if (!cell.ownerTable.isInsideTable) {\n this.clientActiveArea.height = this.clientArea.bottom - rowWidget.y > 0 ? this.clientArea.bottom - rowWidget.y : 0;\n }\n this.clientArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n // tslint:disable-next-line:max-line-length\n this.clientActiveArea = new Rect(this.clientActiveArea.x, this.clientActiveArea.y, this.clientActiveArea.width, this.clientActiveArea.height);\n }\n };\n //Widget\n /**\n * Updates client area location.\n * @param widget\n * @param area\n * @private\n */\n LayoutViewer.prototype.updateClientAreaLocation = function (widget, area) {\n widget.x = area.x;\n widget.y = area.y;\n widget.width = area.width;\n };\n /**\n * Updates text position for selection.\n * @param cursorPoint\n * @param tapCount\n * @param clearMultiSelection\n * @private\n */\n LayoutViewer.prototype.updateTextPositionForSelection = function (cursorPoint, tapCount) {\n var widget = this.getLineWidget(cursorPoint);\n if (!isNullOrUndefined(widget)) {\n this.selection.updateTextPosition(widget, cursorPoint);\n }\n if (tapCount > 1) {\n this.isMouseDown = false;\n this.useTouchSelectionMark = false;\n if (this.pages.length === 0) {\n return;\n }\n //Double tap/triple tap selection\n if (!isNullOrUndefined(this.currentPage) && !isNullOrUndefined(this.owner.selection.start)) {\n if (tapCount % 2 === 0) {\n this.owner.selection.selectCurrentWord();\n }\n else {\n this.owner.selection.selectCurrentParagraph();\n }\n }\n }\n };\n /**\n * Scrolls to specified position.\n * @param startPosition\n * @param endPosition\n * @private\n */\n LayoutViewer.prototype.scrollToPosition = function (startPosition, endPosition) {\n if (this.owner.enableImageResizerMode && this.owner.imageResizerModule.isImageResizing\n || this.isMouseDownInFooterRegion || this.isRowOrCellResizing) {\n return;\n }\n var lineWidget = this.selection.getLineWidgetInternal(endPosition.currentWidget, endPosition.offset, true);\n if (isNullOrUndefined(lineWidget)) {\n return;\n }\n var top = this.selection.getTop(lineWidget);\n if (this.isMouseDown) {\n var prevLineWidget = this.selection.getLineWidgetInternal(endPosition.currentWidget, endPosition.offset, false);\n var prevTop = this.selection.getTop(prevLineWidget);\n if (prevLineWidget !== lineWidget && endPosition.location.y >= prevTop) {\n lineWidget = prevLineWidget;\n }\n }\n var height = lineWidget.height;\n //Gets current page.\n var endPage = this.selection.getPage(lineWidget.paragraph);\n this.currentPage = endPage;\n var x = 0;\n var y = 0;\n var viewer = this;\n var horizontalWidth = 0;\n var isPageLayout = viewer instanceof PageLayoutViewer;\n if (isPageLayout) {\n var pageLayout = viewer;\n if (isNullOrUndefined(endPage)) {\n return;\n }\n var pageWidth = endPage.boundingRectangle.width;\n x = (this.visibleBounds.width - pageWidth * this.zoomFactor) / 2;\n if (x < 30) {\n x = 30;\n }\n // tslint:disable-next-line:max-line-length\n y = endPage.boundingRectangle.y * this.zoomFactor + (this.pages.indexOf(endPage) + 1) * viewer.pageGap * (1 - this.zoomFactor);\n }\n var scrollTop = this.containerTop;\n var scrollLeft = this.containerLeft;\n var pageHeight = this.visibleBounds.height;\n var caretInfo = this.selection.updateCaretSize(this.owner.selection.end, true);\n var topMargin = caretInfo.topMargin;\n var caretHeight = caretInfo.height;\n x += (endPosition.location.x) * this.zoomFactor;\n y += (endPosition.location.y + topMargin) * this.zoomFactor;\n //vertical scroll bar update\n if ((scrollTop + 20) > y) {\n this.viewerContainer.scrollTop = (y - 10);\n }\n else if (scrollTop + pageHeight < y + caretHeight) {\n this.viewerContainer.scrollTop = y + caretHeight - pageHeight + 10;\n }\n else {\n this.selection.updateCaretToPage(startPosition, endPage);\n }\n this.selection.updateCaretToPage(startPosition, endPage);\n var scrollBarWidth = this.viewerContainer.offsetWidth - this.viewerContainer.clientWidth;\n if (scrollLeft > x) {\n this.viewerContainer.scrollLeft = x - (viewer.pageContainer.offsetWidth / 100) * 20;\n }\n else if (scrollLeft + this.visibleBounds.width < x + scrollBarWidth) {\n this.viewerContainer.scrollLeft = scrollLeft + (viewer.pageContainer.offsetWidth / 100) * 15 + scrollBarWidth;\n }\n };\n /**\n * Gets line widget using cursor point.\n * @private\n */\n LayoutViewer.prototype.getLineWidget = function (cursorPoint) {\n return this.getLineWidgetInternal(cursorPoint, false);\n };\n /**\n * Gets line widget.\n * @private\n */\n LayoutViewer.prototype.getLineWidgetInternal = function (cursorPoint, isMouseDragged) {\n var widget = undefined;\n if (!isNullOrUndefined(this.currentPage)) {\n var childWidgets = void 0;\n if (this.owner.enableHeaderAndFooter) {\n var page = this.currentPage;\n var pageTop = this.selection.getPageTop(page);\n var pageBottom = page.boundingRectangle.height;\n var headerHeight = Math.max((page.headerWidget.y + page.headerWidget.height), HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.topMargin)) * this.zoomFactor;\n var footerDistance = HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.footerDistance);\n var footerHeight = (page.boundingRectangle.height -\n Math.max(page.footerWidget.height + footerDistance, footerDistance * 2));\n if (isMouseDragged) {\n if (this.isBlockInHeader(this.selection.start.paragraph)) {\n childWidgets = this.currentPage.headerWidget;\n }\n else {\n childWidgets = this.currentPage.footerWidget;\n }\n }\n else {\n if (cursorPoint.y <= pageBottom && cursorPoint.y >= footerHeight) {\n childWidgets = this.currentPage.footerWidget;\n }\n else if ((cursorPoint.y) >= 0 && (cursorPoint.y) <= headerHeight) {\n childWidgets = this.currentPage.headerWidget;\n }\n }\n if (isNullOrUndefined(childWidgets)) {\n return undefined;\n }\n return this.selection.getLineWidgetBodyWidget(childWidgets, cursorPoint);\n }\n else {\n for (var i = 0; i < this.currentPage.bodyWidgets.length; i++) {\n var bodyWidgets = this.currentPage.bodyWidgets[i];\n widget = this.selection.getLineWidgetBodyWidget(bodyWidgets, cursorPoint);\n if (!isNullOrUndefined(widget)) {\n break;\n }\n }\n }\n }\n return widget;\n };\n /**\n * @private\n */\n LayoutViewer.prototype.isBlockInHeader = function (block) {\n while (!(block.containerWidget instanceof HeaderFooterWidget)) {\n if (!block.containerWidget) {\n return false;\n }\n block = block.containerWidget;\n }\n return block.containerWidget.headerFooterType.indexOf('Header') !== -1;\n };\n /**\n * Clears selection highlight.\n * @private\n */\n LayoutViewer.prototype.clearSelectionHighlight = function () {\n var canClear = true;\n canClear = (!this.isControlPressed || !this.isMouseDown);\n // if (this.owner.selection.selectionRanges.length > 0 && canClear) {\n if (this.owner.selection.clearSelectionHighlightInSelectedWidgets()) {\n this.selectionContext.clearRect(0, 0, this.selectionCanvas.width, this.selectionCanvas.height);\n }\n // } else if (!isNullOrUndefined(this.owner.selection.currentSelectionRange) && this.isMouseDown) {\n // this.owner.selection.currentSelectionRange.clearSelectionHighlight();\n // }\n //this.renderVisiblePages();\n };\n /**\n * @private\n */\n LayoutViewer.prototype.removeEmptyPages = function () {\n var scrollToLastPage = false;\n var viewer = this;\n for (var j = 0; j < this.pages.length; j++) {\n var page = this.pages[j];\n if (page.bodyWidgets.length === 0 || page.bodyWidgets[0].childWidgets.length === 0) {\n // tslint:disable-next-line:max-line-length\n if (j === this.pages.length - 1 && viewer instanceof PageLayoutViewer && viewer.visiblePages.indexOf(this.pages[j]) !== -1) {\n scrollToLastPage = true;\n }\n this.removePage(this.pages[j]);\n j--;\n }\n }\n if (scrollToLastPage) {\n this.scrollToBottom();\n }\n };\n /**\n * @private\n */\n LayoutViewer.prototype.scrollToBottom = function () {\n if (this.selection.start.paragraph && this.selection.start.paragraph.bodyWidget) {\n var page = this.selection.start.paragraph.bodyWidget.page;\n var containerHeight = this.visibleBounds.height;\n this.viewerContainer.scrollTop = page.boundingRectangle.bottom - containerHeight;\n }\n };\n /**\n * Returns the field code result.\n * @private\n */\n LayoutViewer.prototype.getFieldResult = function (fieldBegin, page) {\n if (!isNullOrUndefined(page) && !isNullOrUndefined(this.selection)) {\n var fieldCode = this.selection.getFieldCode(fieldBegin);\n var fieldCodes = fieldCode.split('\\*');\n if (fieldCodes.length > 1) {\n var fieldCategory = fieldCodes[0].replace(/[^\\w\\s]/gi, '').trim().toLowerCase();\n var fieldPattern = fieldCodes[1].replace(/[^\\w\\s]/gi, '').trim();\n switch (fieldCategory) {\n case 'page':\n return this.getFieldText(fieldPattern, (page.index + 1));\n case 'numpages':\n return this.getFieldText(fieldPattern, page.viewer.pages.length);\n default:\n break;\n }\n }\n }\n return '';\n };\n /**\n * Returns field text.\n */\n LayoutViewer.prototype.getFieldText = function (pattern, value) {\n switch (pattern) {\n case 'ALPHABETIC':\n return this.layout.getAsLetter(value).toUpperCase();\n case 'alphabetic':\n return this.layout.getAsLetter(value).toLowerCase();\n case 'roman':\n return this.layout.getAsRoman(value).toLowerCase();\n case 'ROMAN':\n return this.layout.getAsRoman(value).toUpperCase();\n default:\n return value.toString();\n }\n };\n /**\n * Destroys the internal objects maintained for control.\n */\n LayoutViewer.prototype.destroy = function () {\n if (!isNullOrUndefined(this.owner)) {\n this.unWireEvent();\n }\n this.pages = [];\n this.pages = undefined;\n this.fieldStacks = [];\n this.fieldStacks = undefined;\n this.splittedCellWidgets = [];\n this.splittedCellWidgets = undefined;\n this.fields = [];\n this.fields = undefined;\n if (this.layout) {\n this.layout.destroy();\n }\n this.layout = undefined;\n if (!isNullOrUndefined(this.render)) {\n this.render.destroy();\n }\n this.render = undefined;\n if (this.dialogInternal) {\n this.dialogInternal.destroy();\n }\n this.dialogInternal = undefined;\n if (this.dialogTarget && this.dialogTarget.parentElement) {\n this.dialogTarget.parentElement.removeChild(this.dialogTarget);\n }\n this.dialogTarget = undefined;\n if (!isNullOrUndefined(this.touchStart)) {\n this.touchStart.innerHTML = '';\n }\n if (this.textHelper) {\n this.textHelper.destroy();\n }\n this.textHelper = undefined;\n this.touchStart = undefined;\n if (!isNullOrUndefined(this.touchEnd)) {\n this.touchEnd.innerHTML = '';\n }\n this.touchEnd = undefined;\n if (!isNullOrUndefined(this.containerCanvasIn)) {\n this.containerCanvasIn.innerHTML = '';\n }\n this.containerCanvasIn = undefined;\n if (!isNullOrUndefined(this.selectionCanvasIn)) {\n this.selectionCanvasIn.innerHTML = '';\n }\n this.selectionCanvasIn = undefined;\n if (!isNullOrUndefined(this.editableDiv)) {\n this.editableDiv.innerHTML = '';\n }\n this.editableDiv = undefined;\n if (!isNullOrUndefined(this.pageContainer)) {\n this.pageContainer.innerHTML = '';\n }\n this.pageContainer = undefined;\n if (!isNullOrUndefined(this.viewerContainer)) {\n this.viewerContainer.innerHTML = '';\n }\n this.viewerContainer = undefined;\n this.owner = undefined;\n this.heightInfoCollection = undefined;\n };\n /**\n * Un-Wires events and methods\n */\n LayoutViewer.prototype.unWireEvent = function () {\n this.viewerContainer.removeEventListener('scroll', this.scrollHandler);\n this.viewerContainer.removeEventListener('mousedown', this.onMouseDownInternal);\n this.viewerContainer.removeEventListener('mousemove', this.onMouseMoveInternal);\n if (Browser.isIE) {\n this.editableDiv.removeEventListener('keypress', this.onTextInputInternal);\n }\n else {\n this.editableDiv.removeEventListener('input', this.onTextInputInternal);\n }\n this.editableDiv.removeEventListener('paste', this.onPaste);\n this.viewerContainer.removeEventListener('contextmenu', this.onContextMenu);\n this.editableDiv.removeEventListener('blur', this.onFocusOut);\n this.editableDiv.removeEventListener('keydown', this.onKeyDownInternal);\n this.editableDiv.removeEventListener('compositionstart', this.compositionStart);\n this.editableDiv.removeEventListener('compositionupdate', this.compositionUpdated);\n this.editableDiv.removeEventListener('compositionend', this.compositionEnd);\n this.viewerContainer.removeEventListener('mouseup', this.onMouseUpInternal);\n this.viewerContainer.removeEventListener('dblclick', this.onDoubleTap);\n window.removeEventListener('resize', this.onWindowResize);\n window.removeEventListener('keyup', this.onKeyUpInternal);\n window.removeEventListener('mouseup', this.onImageResizer);\n window.removeEventListener('touchend', this.onImageResizer);\n };\n return LayoutViewer;\n}());\nexport { LayoutViewer };\n/**\n * @private\n */\nvar PageLayoutViewer = /** @class */ (function (_super) {\n __extends(PageLayoutViewer, _super);\n /**\n * Initialize the constructor of PageLayoutViewer\n */\n function PageLayoutViewer(owner) {\n var _this = _super.call(this, owner) || this;\n _this.pageLeft = 30;\n /**\n * @private\n */\n _this.pageGap = 20;\n /**\n * @private\n */\n _this.visiblePages = [];\n if (isNullOrUndefined(owner) || isNullOrUndefined(owner.element)) {\n return _this;\n }\n return _this;\n }\n /**\n * Creates new page.\n * @private\n */\n PageLayoutViewer.prototype.createNewPage = function (section, index) {\n var viewer = this;\n var yPos = this.pageGap;\n if (this.pages.length > 0) {\n yPos = this.pages[this.pages.length - 1].boundingRectangle.bottom + this.pageGap;\n }\n var page = new Page();\n page.viewer = this;\n // tslint:disable-next-line:max-line-length\n var pageWidth = !isNullOrUndefined(section.sectionFormat) ? HelperMethods.convertPointToPixel(section.sectionFormat.pageWidth) : 816;\n // tslint:disable-next-line:max-line-length\n var pageHeight = !isNullOrUndefined(section.sectionFormat) ? HelperMethods.convertPointToPixel(section.sectionFormat.pageHeight) : 1056;\n var xPos = (this.visibleBounds.width - pageWidth * this.zoomFactor) / 2;\n if (xPos < this.pageLeft) {\n xPos = this.pageLeft;\n }\n page.boundingRectangle = new Rect(xPos, yPos, pageWidth, pageHeight);\n if (isNullOrUndefined(index)) {\n this.pages.push(page);\n }\n else {\n this.pages.splice(index, 0, page);\n }\n this.updateClientArea(section.sectionFormat, page);\n page.bodyWidgets.push(section);\n page.bodyWidgets[page.bodyWidgets.length - 1].page = page;\n this.layout.layoutHeaderFooter(section, viewer, page);\n this.updateClientArea(section.sectionFormat, page);\n return page;\n };\n /**\n * Updates cursor.\n */\n PageLayoutViewer.prototype.updateCursor = function (event) {\n var hyperlinkField = undefined;\n var div = this.viewerContainer;\n var point = new Point(event.offsetX, event.offsetY);\n var touchPoint = this.findFocusedPage(point, true);\n var widget = this.getLineWidget(touchPoint);\n var widgetInfo;\n var left;\n var top;\n var editor = !this.owner.isReadOnlyMode ? this.owner.editorModule : undefined;\n var isRowResize = editor ? editor.tableResize.isInRowResizerArea(touchPoint) : false;\n var isCellResize = editor ? editor.tableResize.isInCellResizerArea(touchPoint) : false;\n var resizePosition = '';\n if (this.owner.enableImageResizerMode) {\n var resizeObj = this.owner.imageResizerModule.getImagePoint(touchPoint);\n this.owner.imageResizerModule.selectedResizeElement = resizeObj.selectedElement;\n resizePosition = resizeObj.resizePosition;\n }\n var lineLeft = 0;\n if (!isNullOrUndefined(widget)) {\n lineLeft = this.selection.getLineStartLeft(widget);\n hyperlinkField = this.selection.getHyperLinkFieldInCurrentSelection(widget, touchPoint);\n widgetInfo = this.selection.updateTextPositionIn(widget, undefined, 0, touchPoint, true);\n left = this.selection.getLeft(widget);\n top = this.selection.getTop(widget);\n this.selection.setHyperlinkContentToToolTip(hyperlinkField, widget, touchPoint.x);\n }\n if (!isNullOrUndefined(hyperlinkField) && (event.ctrlKey &&\n this.owner.useCtrlClickToFollowHyperlink || !this.owner.useCtrlClickToFollowHyperlink)) {\n div.style.cursor = 'pointer';\n return;\n }\n else if (touchPoint.x >= lineLeft &&\n event.offsetX < (this.visibleBounds.width - (this.visibleBounds.width - this.viewerContainer.clientWidth)) &&\n event.offsetY < (this.visibleBounds.height - (this.visibleBounds.height - this.viewerContainer.clientHeight))) {\n if (this.selection.isEmpty) {\n div.style.cursor = 'text';\n }\n else {\n div.style.cursor = this.selection.checkCursorIsInSelection(widget, touchPoint) ? 'default' : 'text';\n }\n }\n else {\n div.style.cursor = 'default';\n }\n if (!isNullOrUndefined(resizePosition) && resizePosition !== '') {\n div.style.cursor = resizePosition;\n }\n else if (!isNullOrUndefined(widgetInfo) && widgetInfo.isImageSelected && left < touchPoint.x && top < touchPoint.y &&\n left + widget.width > touchPoint.x && top + widget.height > touchPoint.y) {\n div.style.cursor = 'move';\n }\n if (isRowResize) {\n div.style.cursor = 'row-resize';\n }\n else if (isCellResize) {\n div.style.cursor = 'col-resize';\n }\n };\n /**\n * Finds focused page.\n * @private\n */\n PageLayoutViewer.prototype.findFocusedPage = function (currentPoint, updateCurrentPage) {\n var point = new Point(currentPoint.x, currentPoint.y);\n point.x += this.viewerContainer.scrollLeft;\n point.y += this.viewerContainer.scrollTop;\n for (var i = 0; i < this.pages.length; i++) {\n var page = this.pages[i];\n var pageTop = (page.boundingRectangle.y - this.pageGap * (i + 1)) * this.zoomFactor + this.pageGap * (i + 1);\n var pageHeight = (page.boundingRectangle.height * this.zoomFactor) + this.pageGap;\n var pageLeft = page.boundingRectangle.x;\n var pageRight = ((page.boundingRectangle.right - pageLeft) * this.zoomFactor) + pageLeft;\n if (pageTop <= point.y && pageTop + pageHeight >= point.y) {\n if (updateCurrentPage) {\n this.currentPage = page;\n }\n point.y = (point.y - (pageTop)) / this.zoomFactor;\n if (point.x > pageRight) {\n point.x = page.boundingRectangle.right;\n }\n else if (point.x < pageLeft) {\n point.x = 0;\n }\n else {\n point.x = (point.x - pageLeft) / this.zoomFactor;\n }\n return point;\n }\n }\n return point;\n };\n /**\n * Fired when page fit type changed.\n * @private\n */\n PageLayoutViewer.prototype.onPageFitTypeChanged = function (pageFitType) {\n var width = this.visibleBounds.width;\n var height = this.visibleBounds.height;\n var section = this.visiblePages[0].bodyWidgets[0];\n var pageWidth = HelperMethods.convertPointToPixel(section.sectionFormat.pageWidth);\n var pageHeight = HelperMethods.convertPointToPixel(section.sectionFormat.pageHeight);\n switch (pageFitType) {\n case 'FitOnePage':\n if (height > 0 && pageHeight > 0) {\n var zoomFactor = (this.visibleBounds.height - 2 * this.pageGap - (this.pageGap - 2)) / pageHeight;\n if (zoomFactor === this.zoomFactor) {\n if (!isNullOrUndefined(this.owner.selection) && !isNullOrUndefined(this.owner.selection.start) &&\n !isNullOrUndefined(this.owner.selection.end)) {\n this.scrollToPosition(this.owner.selection.start, this.owner.selection.end);\n }\n }\n else {\n this.zoomFactor = zoomFactor;\n }\n }\n break;\n case 'FitPageWidth':\n if (width > 0 && pageWidth > 0) {\n this.zoomFactor = (this.visibleBounds.width - 80) / pageWidth;\n }\n break;\n default:\n this.zoomFactor = 100 / 100;\n break;\n }\n };\n /**\n * @private\n */\n PageLayoutViewer.prototype.handleZoom = function () {\n var prevScaleFactor = this.preZoomFactor;\n var page = null;\n var verticalHeight = 0;\n var scrollToPosition = false;\n if (this.selection && isNullOrUndefined(this.zoomX && isNullOrUndefined(this.zoomY))) {\n var x = 0;\n var y = 0;\n var endPage = this.selection.getPage(this.selection.end.currentWidget.paragraph);\n x = (this.visibleBounds.width - endPage.boundingRectangle.width * prevScaleFactor) / 2;\n if (x < 30) {\n x = 30;\n }\n // tslint:disable-next-line:max-line-length\n y = endPage.boundingRectangle.y * prevScaleFactor + (this.pages.indexOf(endPage) + 1) * this.pageGap * (1 - prevScaleFactor);\n var caretInfo = this.selection.updateCaretSize(this.owner.selection.end, true);\n var topMargin = caretInfo.topMargin;\n var caretHeight = caretInfo.height;\n x += (this.selection.end.location.x) * prevScaleFactor;\n y += (this.selection.end.location.y + topMargin) * prevScaleFactor;\n if (x >= this.containerLeft && x <= this.visibleBounds.width &&\n y >= this.containerTop && y <= this.containerTop + this.visibleBounds.height) {\n scrollToPosition = true;\n }\n }\n for (var i = 0; i < this.pages.length; i++) {\n verticalHeight = verticalHeight + this.pages[i].boundingRectangle.height;\n }\n var horizontalWidth = 0;\n for (var i = 0; i < this.pages.length; i++) {\n if (horizontalWidth < this.pages[i].boundingRectangle.width) {\n horizontalWidth = this.pages[i].boundingRectangle.width;\n }\n }\n // tslint:disable-next-line:max-line-length\n var height = (verticalHeight * this.zoomFactor + (this.pages.length + 1) * this.pageGap * (1 - this.zoomFactor)) - this.visibleBounds.height;\n var horWidth = horizontalWidth * this.zoomFactor - this.visibleBounds.width;\n if (this.visibleBounds.width - horizontalWidth * this.zoomFactor < 60) {\n horWidth += 60;\n }\n //Update Vertical Scroll bar\n if (height > 0) {\n var value = this.containerTop;\n if (this.visiblePages.length > 0) {\n page = this.visiblePages[0];\n // tslint:disable-next-line:max-line-length\n var prevPageTop = (page.boundingRectangle.y - (page.index + 1) * this.pageGap) * prevScaleFactor + (page.index + 1) * this.pageGap;\n var zoomY = this.zoomY;\n if (isNullOrUndefined) {\n zoomY = this.visibleBounds.height / 2;\n }\n var prevY = value + zoomY;\n while (prevY > prevPageTop + (page.boundingRectangle.height * prevScaleFactor)) {\n var pageIndex = page.index + 1;\n if (pageIndex === this.pages.length) {\n break;\n }\n page = this.pages[pageIndex];\n // tslint:disable-next-line:max-line-length\n prevPageTop = (page.boundingRectangle.y - (page.index + 1) * this.pageGap) * prevScaleFactor + (page.index + 1) * this.pageGap;\n }\n // tslint:disable-next-line:max-line-length\n var currentY = (page.boundingRectangle.y - (page.index + 1) * this.pageGap) * this.zoomFactor + (page.index + 1) * this.pageGap\n + ((prevY - prevPageTop) < 0 ? prevY - prevPageTop : (prevY - prevPageTop) * (this.zoomFactor / prevScaleFactor));\n value = currentY - zoomY;\n zoomY = this.visibleBounds.height / 2;\n }\n this.viewerContainer.scrollTop = value;\n }\n else {\n this.viewerContainer.scrollTop = 0;\n }\n // update Horizontal Scroll Bar\n if (horWidth > 0) {\n var value = this.containerLeft;\n if (this.visiblePages.length > 0) {\n if (page === null) {\n page = this.visiblePages[0];\n }\n var zoomX = this.zoomX;\n if (isNullOrUndefined(zoomX)) {\n zoomX = this.visibleBounds.width / 2;\n }\n var prevValue = (page.boundingRectangle.width * prevScaleFactor) / page.boundingRectangle.width;\n var prevX = value + zoomX;\n // tslint:disable-next-line:max-line-length\n var currentX = page.boundingRectangle.x\n + ((prevX - page.boundingRectangle.x) < 0 ? prevX - page.boundingRectangle.x : (prevX - page.boundingRectangle.x) * (this.zoomFactor / prevValue));\n value = currentX - zoomX;\n zoomX = this.visibleBounds.width / 2;\n }\n this.viewerContainer.scrollLeft = value;\n }\n else {\n this.viewerContainer.scrollLeft = 0;\n }\n this.updateScrollBars();\n if (scrollToPosition) {\n this.scrollToPosition(this.selection.start, this.selection.end);\n }\n };\n /**\n * Gets current page header footer.\n * @private\n */\n PageLayoutViewer.prototype.getCurrentPageHeaderFooter = function (section, isHeader) {\n return this.getCurrentHeaderFooter(this.getHeaderFooterType(section, isHeader), section.index);\n };\n /**\n * Get header footer type\n * @private\n */\n PageLayoutViewer.prototype.getHeaderFooterType = function (section, isHeader) {\n var type;\n type = isHeader ? 'OddHeader' : 'OddFooter';\n // tslint:disable-next-line:max-line-length\n if (section.sectionFormat.differentFirstPage && (this.pages.length === 1 || this.pages[this.pages.length - 1].bodyWidgets[0].index !== section.index)) {\n type = isHeader ? 'FirstPageHeader' : 'FirstPageFooter';\n }\n else if (section.sectionFormat.differentOddAndEvenPages && this.pages.length % 2 === 0) {\n type = isHeader ? 'EvenHeader' : 'EvenFooter';\n }\n return type;\n };\n /**\n * Gets current header footer.\n * @param type\n * @param section\n * @private\n */\n PageLayoutViewer.prototype.getCurrentHeaderFooter = function (type, sectionIndex) {\n if (this.headersFooters[sectionIndex]) {\n var index = this.getHeaderFooter(type);\n var headerFooter = this.headersFooters[sectionIndex][index];\n if (!headerFooter) {\n headerFooter = this.createHeaderFooterWidget(type);\n this.headersFooters[sectionIndex][index] = headerFooter;\n }\n return headerFooter;\n }\n else if (sectionIndex > 0) {\n return this.getCurrentHeaderFooter(type, sectionIndex - 1);\n }\n return undefined;\n };\n PageLayoutViewer.prototype.createHeaderFooterWidget = function (type) {\n var headerFooter = new HeaderFooterWidget(type);\n var paragraph = new ParagraphWidget();\n paragraph.childWidgets.push(new LineWidget(paragraph));\n return headerFooter;\n };\n /**\n * Gets header footer.\n * @param type\n * @private\n */\n PageLayoutViewer.prototype.getHeaderFooter = function (type) {\n switch (type) {\n case 'OddHeader':\n return 0;\n case 'OddFooter':\n return 1;\n case 'EvenHeader':\n return 2;\n case 'EvenFooter':\n return 3;\n case 'FirstPageHeader':\n return 4;\n case 'FirstPageFooter':\n return 5;\n }\n };\n /**\n * Updates header footer client area.\n * @private\n */\n PageLayoutViewer.prototype.updateHFClientArea = function (sectionFormat, isHeader) {\n // tslint:disable-next-line:max-line-length\n var width = HelperMethods.convertPointToPixel(sectionFormat.pageWidth - sectionFormat.leftMargin - sectionFormat.rightMargin);\n if (width < 0) {\n width = 0;\n }\n if (isHeader) {\n // tslint:disable-next-line:max-line-length\n this.clientArea = new Rect(HelperMethods.convertPointToPixel(sectionFormat.leftMargin), HelperMethods.convertPointToPixel(sectionFormat.headerDistance), width, Number.POSITIVE_INFINITY);\n }\n else {\n // tslint:disable-next-line:max-line-length\n this.clientArea = new Rect(HelperMethods.convertPointToPixel(sectionFormat.leftMargin), HelperMethods.convertPointToPixel(sectionFormat.pageHeight - sectionFormat.footerDistance), width, Number.POSITIVE_INFINITY);\n }\n this.clientActiveArea = new Rect(this.clientArea.x, this.clientArea.y, this.clientArea.width, this.clientArea.height);\n };\n /**\n * @private\n */\n PageLayoutViewer.prototype.updateHCFClientAreaWithTop = function (sectionFormat, isHeader, page) {\n this.updateHFClientArea(sectionFormat, isHeader);\n if (!isHeader) {\n if (page.footerWidget.y < this.clientActiveArea.y) {\n this.clientActiveArea.y = page.footerWidget.y;\n this.clientActiveArea.height = Number.POSITIVE_INFINITY;\n }\n }\n };\n /**\n * Scrolls to the specified page\n * @private\n */\n PageLayoutViewer.prototype.scrollToPage = function (pageIndex) {\n var top = 0;\n for (var i = 0; i < this.pages.length; i++) {\n top = this.pages[i].boundingRectangle.y - (this.pageGap / 2);\n if (i === pageIndex) {\n break;\n }\n }\n this.viewerContainer.scrollTop = top;\n this.updateScrollBars();\n };\n /**\n * Updates scroll bars.\n * @private\n */\n PageLayoutViewer.prototype.updateScrollBars = function () {\n var height = 0;\n for (var i = 0; i < this.pages.length; i++) {\n height = height + this.pages[i].boundingRectangle.height;\n }\n var width = 0;\n for (var i = 0; i < this.pages.length; i++) {\n if (width < this.pages[i].boundingRectangle.width) {\n width = this.pages[i].boundingRectangle.width;\n }\n }\n var containerWidth = (width * this.zoomFactor) + (this.pageLeft * 2);\n var containerHeight = (height * this.zoomFactor) + (this.pages.length + 1) * this.pageGap;\n var viewerWidth = this.visibleBounds.width;\n var viewerHeight = this.visibleBounds.height;\n if (this.visibleBounds.width !== this.viewerContainer.clientWidth) {\n viewerWidth -= (this.visibleBounds.width - this.viewerContainer.clientWidth);\n }\n else if (containerHeight > viewerHeight) {\n viewerWidth -= this.viewerContainer.offsetWidth - this.viewerContainer.clientWidth;\n }\n if (containerWidth > viewerWidth) {\n viewerHeight -= (this.visibleBounds.height - this.viewerContainer.clientHeight);\n }\n width = containerWidth > viewerWidth ? containerWidth : viewerWidth;\n height = containerHeight > viewerHeight ? containerHeight : viewerHeight;\n if (parseInt(this.pageContainer.style.width.replace('px', ''), 10) !== width ||\n parseInt(this.pageContainer.style.height.replace('px', ''), 10) !== width) {\n this.pageContainer.style.width = width.toString() + 'px';\n this.pageContainer.style.height = height.toString() + 'px';\n }\n // if (!isNullOrUndefined(this.selection) && !this.selection.isEmpty) {\n // this.selectionContext.clearRect(0, 0, this.selectionCanvas.width, this.selectionCanvas.height);\n // }\n var displayPixelRatio = Math.max(1, window.devicePixelRatio || 1);\n if (this.containerCanvas.width !== Math.floor(viewerWidth * displayPixelRatio)\n || this.containerCanvas.height !== Math.floor(viewerHeight * displayPixelRatio)) {\n this.containerCanvas.width = viewerWidth * displayPixelRatio;\n this.containerCanvas.height = viewerHeight * displayPixelRatio;\n this.containerCanvas.style.width = viewerWidth + 'px';\n this.containerCanvas.style.height = viewerHeight + 'px';\n this.containerContext.scale(displayPixelRatio, displayPixelRatio);\n this.selectionCanvas.width = viewerWidth * displayPixelRatio;\n this.selectionCanvas.height = viewerHeight * displayPixelRatio;\n this.selectionCanvas.style.width = viewerWidth + 'px';\n this.selectionCanvas.style.height = viewerHeight + 'px';\n this.selectionContext.scale(displayPixelRatio, displayPixelRatio);\n }\n this.containerContext.globalAlpha = 1;\n this.selectionContext.globalAlpha = 0.4;\n for (var i = 0; i < this.pages.length; i++) {\n var left = (width - this.pages[i].boundingRectangle.width * this.zoomFactor) / 2;\n if (left > this.pageLeft) {\n // tslint:disable-next-line:max-line-length\n this.pages[i].boundingRectangle = new Rect(left, this.pages[i].boundingRectangle.y, this.pages[i].boundingRectangle.width, this.pages[i].boundingRectangle.height);\n }\n else {\n // tslint:disable-next-line:max-line-length\n this.pages[i].boundingRectangle = new Rect(this.pageLeft, this.pages[i].boundingRectangle.y, this.pages[i].boundingRectangle.width, this.pages[i].boundingRectangle.height);\n }\n }\n this.updateScrollBarPosition(containerWidth, containerHeight, viewerWidth, viewerHeight, width, height);\n };\n // tslint:disable-next-line:max-line-length\n PageLayoutViewer.prototype.updateScrollBarPosition = function (containerWidth, containerHeight, viewerWidth, viewerHeight, width, height) {\n var left = 0;\n var viewerHeight1 = parseFloat(this.viewerContainer.style.height);\n var containerHeight1 = parseFloat(this.pageContainer.style.height);\n this.containerTop = this.viewerContainer.scrollTop;\n this.containerCanvas.style.position = 'absolute';\n this.containerCanvas.style.top = this.containerTop.toString() + 'px';\n this.selectionCanvas.style.position = 'absolute';\n this.selectionCanvas.style.top = this.containerTop.toString() + 'px';\n this.containerLeft = this.viewerContainer.scrollLeft;\n this.containerCanvas.style.left = this.containerLeft + 'px';\n this.selectionCanvas.style.left = this.containerLeft + 'px';\n this.updateVisiblePages();\n };\n /**\n * Updates visible pages.\n * @private\n */\n PageLayoutViewer.prototype.updateVisiblePages = function () {\n var left = 0;\n var width = 0;\n // Clears the container first.\n this.visiblePages = [];\n var height = this.visibleBounds.height;\n var vertical = this.viewerContainer.scrollTop;\n for (var i = 0; i < this.pages.length; i++) {\n var page = this.pages[i];\n var y = (page.boundingRectangle.y - this.pageGap * (i + 1)) * this.zoomFactor + this.pageGap * (i + 1);\n var pageH = page.boundingRectangle.height * this.zoomFactor;\n var left_1 = page.boundingRectangle.x;\n var isTopFit = y >= vertical && y <= vertical + height;\n var isBottomFit = y + pageH >= vertical && y + pageH <= vertical + height;\n var isMiddleFit = y <= vertical && y + pageH >= vertical + height;\n //UI Virtualization\n if (isTopFit || isBottomFit || isMiddleFit) {\n this.addVisiblePage(page, left_1, y);\n }\n }\n };\n /**\n * Adds visible pages.\n */\n PageLayoutViewer.prototype.addVisiblePage = function (page, x, y) {\n var width = page.boundingRectangle.width * this.zoomFactor;\n var height = page.boundingRectangle.height * this.zoomFactor;\n // tslint:disable-next-line:max-line-length\n if (this.owner.enableImageResizerMode && this.owner.imageResizerModule.currentPage !== undefined && this.owner.imageResizerModule.currentPage === page && this.owner.imageResizerModule.isImageResizerVisible) {\n this.owner.imageResizerModule.setImageResizerPositions(x, y, width, height);\n }\n this.visiblePages.push(page);\n this.renderPage(page, x, y, width, height);\n };\n /**\n * Render specified page widgets.\n */\n PageLayoutViewer.prototype.renderPage = function (page, x, y, width, height) {\n this.render.renderWidgets(page, x - this.containerLeft, y - this.containerTop, width, height);\n };\n /**\n * Renders visible pages.\n * @private\n */\n PageLayoutViewer.prototype.renderVisiblePages = function () {\n if (isNullOrUndefined(this.visiblePages) || this.visiblePages.length < 1) {\n return;\n }\n this.clearContent();\n for (var i = 0; i < this.visiblePages.length; i++) {\n var page = this.visiblePages[i];\n var width = page.boundingRectangle.width * this.zoomFactor;\n var height = page.boundingRectangle.height * this.zoomFactor;\n var x = page.boundingRectangle.x;\n var y = (page.boundingRectangle.y - this.pageGap * (i + 1)) * this.zoomFactor + this.pageGap * (i + 1);\n this.renderPage(page, x, y, width, height);\n }\n };\n return PageLayoutViewer;\n}(LayoutViewer));\nexport { PageLayoutViewer };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { WList } from '../list/list';\nimport { WListLevel } from '../list/list-level';\nimport { WAbstractList } from '../list/abstract-list';\nimport { WLevelOverride } from '../list/level-override';\nimport { WCharacterFormat, WListFormat, WParagraphFormat, WCellFormat, WTableFormat, WSectionFormat, WRowFormat } from '../format/index';\nimport { WCharacterStyle, WParagraphStyle, WTabStop } from '../format/index';\nimport { LineWidget, ParagraphWidget, ImageElementBox, BodyWidget, TextElementBox, TableCellWidget, TableRowWidget, TableWidget, FieldElementBox, HeaderFooterWidget, BookmarkElementBox, FieldTextElementBox, TabElementBox } from './page';\nimport { HelperMethods } from '../editor/editor-helper';\n/**\n * @private\n */\nvar SfdtReader = /** @class */ (function () {\n function SfdtReader(viewer) {\n /* tslint:disable:no-any */\n this.viewer = undefined;\n this.viewer = viewer;\n }\n Object.defineProperty(SfdtReader.prototype, \"isPasting\", {\n get: function () {\n return this.viewer && this.viewer.owner.isPastingContent;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n * @param json\n */\n SfdtReader.prototype.convertJsonToDocument = function (json) {\n var sections = [];\n var jsonObject = JSON.parse(json);\n this.parseCharacterFormat(jsonObject.characterFormat, this.viewer.characterFormat);\n this.parseParagraphFormat(jsonObject.paragraphFormat, this.viewer.paragraphFormat);\n if (!isNullOrUndefined(jsonObject.background)) {\n this.viewer.backgroundColor = this.getColor(jsonObject.background.color);\n }\n if (!isNullOrUndefined(jsonObject.abstractLists)) {\n this.parseAbstractList(jsonObject, this.viewer.abstractLists);\n }\n if (!isNullOrUndefined(jsonObject.lists)) {\n this.parseList(jsonObject, this.viewer.lists);\n }\n if (!isNullOrUndefined(jsonObject.styles)) {\n this.parseStyles(jsonObject, this.viewer.styles);\n }\n if (!isNullOrUndefined(jsonObject.sections)) {\n this.parseSections(jsonObject.sections, sections);\n }\n return sections;\n };\n SfdtReader.prototype.parseStyles = function (data, styles) {\n for (var i = 0; i < data.styles.length; i++) {\n if (isNullOrUndefined(this.viewer.styles.findByName(data.styles[i].name))) {\n this.parseStyle(data, data.styles[i], styles);\n }\n }\n };\n SfdtReader.prototype.parseStyle = function (data, style, styles) {\n var wStyle;\n if (!isNullOrUndefined(style.type)) {\n if (style.type === 'Paragraph') {\n wStyle = new WParagraphStyle();\n wStyle.type = 'Paragraph';\n }\n if (style.type === 'Character') {\n wStyle = new WCharacterStyle();\n wStyle.type = 'Character';\n }\n if (!isNullOrUndefined(style.name)) {\n wStyle.name = style.name;\n }\n styles.push(wStyle);\n if (!isNullOrUndefined(style.basedOn)) {\n var basedOn = styles.findByName(style.basedOn);\n if (!isNullOrUndefined(basedOn)) {\n if (basedOn.type === wStyle.type) {\n wStyle.basedOn = basedOn;\n }\n }\n else {\n var basedStyle = this.getStyle(style.basedOn, data);\n var styleString = void 0;\n if (!isNullOrUndefined(basedStyle) && basedStyle.type === wStyle.type) {\n styleString = basedStyle;\n }\n else {\n if (wStyle.type === 'Paragraph') {\n styleString = JSON.parse('{\"type\":\"Paragraph\",\"name\":\"Normal\",\"next\":\"Normal\"}');\n }\n else {\n styleString = JSON.parse('{\"type\": \"Character\",\"name\": \"Default Paragraph Font\"}');\n }\n }\n this.parseStyle(data, styleString, styles);\n wStyle.basedOn = styles.findByName(styleString.name);\n }\n }\n if (!isNullOrUndefined(style.link)) {\n var link = styles.findByName(style.link);\n var linkStyle = this.getStyle(style.link, data);\n var styleString = void 0;\n if (isNullOrUndefined(link)) {\n if (isNullOrUndefined(linkStyle)) {\n //Construct the CharacterStyle string\n var charaStyle = {};\n charaStyle.characterFormat = style.characterFormat;\n charaStyle.name = style.name + ' Char';\n charaStyle.type = 'Character';\n //TODO: Implement basedOn\n charaStyle.basedOn = style.basedOn === 'Normal' ? 'Default Paragraph Font' : (style.basedOn + ' Char');\n styleString = charaStyle;\n }\n else {\n styleString = linkStyle;\n }\n this.parseStyle(data, styleString, styles);\n wStyle.link = isNullOrUndefined(styles.findByName(styleString.name)) ? style.link : styles.findByName(styleString.name);\n }\n else {\n wStyle.link = link;\n }\n }\n if (!isNullOrUndefined(style.characterFormat)) {\n this.parseCharacterFormat(style.characterFormat, wStyle.characterFormat);\n }\n if (!isNullOrUndefined(style.paragraphFormat)) {\n this.parseParagraphFormat(style.paragraphFormat, wStyle.paragraphFormat);\n }\n if (!isNullOrUndefined(style.next)) {\n if (style.next === style.name) {\n wStyle.next = wStyle;\n }\n else {\n var next = styles.findByName(style.next);\n if (!isNullOrUndefined(next) && next.type === wStyle.type) {\n wStyle.next = next;\n }\n else {\n var nextStyleString = this.getStyle(style.next, data);\n if (!isNullOrUndefined(nextStyleString)) {\n this.parseStyle(data, nextStyleString, styles);\n wStyle.next = styles.findByName(nextStyleString.name);\n }\n else {\n wStyle.next = wStyle;\n }\n }\n }\n }\n }\n };\n SfdtReader.prototype.getStyle = function (name, data) {\n for (var i = 0; i < data.styles.length; i++) {\n if (data.styles[i].name === name) {\n return data.styles[i];\n }\n }\n return undefined;\n };\n SfdtReader.prototype.parseAbstractList = function (data, abstractLists) {\n for (var i = 0; i < data.abstractLists.length; i++) {\n var abstractList = new WAbstractList();\n var abstract = data.abstractLists[i];\n abstractLists.push(abstractList);\n if (!isNullOrUndefined(abstract)) {\n if (!isNullOrUndefined(abstract.abstractListId)) {\n abstractList.abstractListId = abstract.abstractListId;\n }\n if (!isNullOrUndefined(abstract.levels)) {\n for (var j = 0; j < abstract.levels.length; j++) {\n var level = abstract.levels[j];\n if (!isNullOrUndefined(level)) {\n var listLevel = this.parseListLevel(level, abstractList);\n abstractList.levels.push(listLevel);\n }\n }\n }\n }\n }\n };\n SfdtReader.prototype.parseListLevel = function (data, owner) {\n var listLevel = new WListLevel(owner);\n if (data.listLevelPattern === 'Bullet') {\n listLevel.listLevelPattern = 'Bullet';\n listLevel.numberFormat = !isNullOrUndefined(data.numberFormat) ? data.numberFormat : '';\n }\n else {\n listLevel.listLevelPattern = data.listLevelPattern;\n listLevel.startAt = data.startAt;\n listLevel.numberFormat = !isNullOrUndefined(data.numberFormat) ? data.numberFormat : '';\n if (data.restartLevel >= 0) {\n listLevel.restartLevel = data.restartLevel;\n }\n else {\n listLevel.restartLevel = data.levelNumber;\n }\n }\n listLevel.followCharacter = data.followCharacter;\n this.parseCharacterFormat(data.characterFormat, listLevel.characterFormat);\n this.parseParagraphFormat(data.paragraphFormat, listLevel.paragraphFormat);\n return listLevel;\n };\n SfdtReader.prototype.parseList = function (data, listCollection) {\n for (var i = 0; i < data.lists.length; i++) {\n var list = new WList();\n var lists = data.lists[i];\n if (!isNullOrUndefined(lists.abstractListId)) {\n list.abstractListId = lists.abstractListId;\n list.abstractList = this.viewer.getAbstractListById(lists.abstractListId);\n }\n listCollection.push(list);\n if (!isNullOrUndefined(lists.listId)) {\n list.listId = lists.listId;\n }\n if (lists.hasOwnProperty('levelOverrides')) {\n this.parseLevelOverride(lists.levelOverrides, list);\n }\n }\n };\n SfdtReader.prototype.parseLevelOverride = function (data, list) {\n if (isNullOrUndefined(data)) {\n return;\n }\n for (var i = 0; i < data.length; i++) {\n var levelOverrides = new WLevelOverride();\n var levelOverride = data[i];\n levelOverrides.startAt = levelOverride.startAt;\n levelOverrides.levelNumber = levelOverride.levelNumber;\n if (!isNullOrUndefined(levelOverride.overrideListLevel)) {\n levelOverrides.overrideListLevel = this.parseListLevel(levelOverride.overrideListLevel, levelOverrides);\n }\n list.levelOverrides.push(levelOverrides);\n }\n };\n SfdtReader.prototype.parseSections = function (data, sections) {\n for (var i = 0; i < data.length; i++) {\n var section = new BodyWidget();\n section.sectionFormat = new WSectionFormat(section);\n section.index = i;\n var item = data[i];\n if (!isNullOrUndefined(item.sectionFormat)) {\n this.parseSectionFormat(item.sectionFormat, section.sectionFormat);\n }\n if (isNullOrUndefined(item.headersFooters)) {\n item.headersFooters = {};\n }\n this.viewer.headersFooters.push(this.parseHeaderFooter(item.headersFooters, this.viewer.headersFooters));\n this.parseTextBody(item.blocks, section);\n for (var i_1 = 0; i_1 < section.childWidgets.length; i_1++) {\n section.childWidgets[i_1].containerWidget = section;\n }\n sections.push(section);\n }\n };\n /**\n * @private\n */\n SfdtReader.prototype.parseHeaderFooter = function (data, headersFooters) {\n var hfs = {};\n if (!isNullOrUndefined(data.header)) {\n var oddHeader = new HeaderFooterWidget('OddHeader');\n hfs[0] = oddHeader;\n this.parseTextBody(data.header.blocks, oddHeader);\n }\n if (!isNullOrUndefined(data.footer)) {\n var oddFooter = new HeaderFooterWidget('OddFooter');\n hfs[1] = oddFooter;\n this.parseTextBody(data.footer.blocks, oddFooter);\n }\n if (!isNullOrUndefined(data.evenHeader)) {\n var evenHeader = new HeaderFooterWidget('EvenHeader');\n hfs[2] = evenHeader;\n this.parseTextBody(data.evenHeader.blocks, evenHeader);\n }\n if (!isNullOrUndefined(data.evenFooter)) {\n var evenFooter = new HeaderFooterWidget('EvenFooter');\n hfs[3] = evenFooter;\n this.parseTextBody(data.evenFooter.blocks, evenFooter);\n }\n if (!isNullOrUndefined(data.firstPageHeader)) {\n var firstPageHeader = new HeaderFooterWidget('FirstPageHeader');\n hfs[4] = firstPageHeader;\n this.parseTextBody(data.firstPageHeader.blocks, firstPageHeader);\n }\n if (!isNullOrUndefined(data.firstPageFooter)) {\n var firstPageFooter = new HeaderFooterWidget('FirstPageFooter');\n hfs[5] = firstPageFooter;\n this.parseTextBody(data.firstPageFooter.blocks, firstPageFooter);\n }\n return hfs;\n };\n SfdtReader.prototype.parseTextBody = function (data, section) {\n this.parseBody(data, section.childWidgets, section);\n };\n SfdtReader.prototype.parseBody = function (data, blocks, container) {\n if (!isNullOrUndefined(data)) {\n for (var i = 0; i < data.length; i++) {\n var block = data[i];\n if (block.hasOwnProperty('inlines')) {\n var writeInlineFormat = false;\n //writeInlineFormat = this.isPasting && i === data.length - 1;\n var paragraph = new ParagraphWidget();\n paragraph.characterFormat = new WCharacterFormat(paragraph);\n paragraph.paragraphFormat = new WParagraphFormat(paragraph);\n this.parseCharacterFormat(block.characterFormat, paragraph.characterFormat);\n this.parseParagraphFormat(block.paragraphFormat, paragraph.paragraphFormat);\n var styleObj = void 0;\n if (!isNullOrUndefined(block.paragraphFormat) && !isNullOrUndefined(block.paragraphFormat.styleName)) {\n styleObj = this.viewer.styles.findByName(block.paragraphFormat.styleName, 'Paragraph');\n if (!isNullOrUndefined(styleObj)) {\n paragraph.paragraphFormat.ApplyStyle(styleObj);\n }\n }\n if (block.inlines.length > 0) {\n this.parseParagraph(block.inlines, paragraph, writeInlineFormat);\n }\n blocks.push(paragraph);\n paragraph.index = i;\n paragraph.containerWidget = container;\n }\n else if (block.hasOwnProperty('rows')) {\n this.parseTable(block, blocks, i, container);\n }\n }\n }\n };\n SfdtReader.prototype.parseTable = function (block, blocks, index, section) {\n var table = new TableWidget();\n table.index = index;\n table.tableFormat = new WTableFormat(table);\n if (!isNullOrUndefined(block.tableFormat)) {\n this.parseTableFormat(block.tableFormat, table.tableFormat);\n }\n table.title = block.title;\n table.description = block.description;\n for (var i = 0; i < block.rows.length; i++) {\n var row = new TableRowWidget();\n row.rowFormat = new WRowFormat(row);\n var tableRow = block.rows[i];\n if (tableRow.hasOwnProperty('rowFormat')) {\n this.parseRowFormat(tableRow.rowFormat, row.rowFormat);\n this.parseRowGridValues(tableRow, row.rowFormat);\n this.parseRowGridValues(tableRow.rowFormat, row.rowFormat);\n row.index = i;\n for (var j = 0; j < block.rows[i].cells.length; j++) {\n var cell = new TableCellWidget();\n cell.cellFormat = new WCellFormat(cell);\n row.childWidgets.push(cell);\n cell.containerWidget = row;\n cell.index = j;\n cell.rowIndex = i;\n if (block.rows[i].cells[j].hasOwnProperty('cellFormat')) {\n this.parseCellFormat(block.rows[i].cells[j].cellFormat, cell.cellFormat);\n }\n this.parseTextBody(block.rows[i].cells[j].blocks, cell);\n }\n }\n table.childWidgets.push(row);\n row.containerWidget = table;\n }\n table.containerWidget = section;\n blocks.push(table);\n table.isGridUpdated = false;\n };\n SfdtReader.prototype.parseRowGridValues = function (data, rowFormat) {\n if (!isNullOrUndefined(data.gridBefore)) {\n rowFormat.gridBefore = data.gridBefore;\n }\n if (!isNullOrUndefined(data.gridBeforeWidth)) {\n rowFormat.gridBeforeWidth = data.gridBeforeWidth;\n }\n if (!isNullOrUndefined(data.gridBeforeWidthType)) {\n rowFormat.gridBeforeWidthType = data.gridBeforeWidthType;\n }\n if (!isNullOrUndefined(data.gridAfter)) {\n rowFormat.gridAfter = data.gridAfter;\n }\n if (!isNullOrUndefined(data.gridAfterWidth)) {\n rowFormat.gridAfterWidth = data.gridAfterWidth;\n }\n if (!isNullOrUndefined(data.gridAfterWidthType)) {\n rowFormat.gridAfterWidthType = data.gridAfterWidthType;\n }\n };\n SfdtReader.prototype.parseParagraph = function (data, paragraph, writeInlineFormat) {\n var lineWidget = new LineWidget(paragraph);\n for (var i = 0; i < data.length; i++) {\n var inline = data[i];\n if (inline.hasOwnProperty('text')) {\n var textElement = undefined;\n if (this.viewer.isPageField) {\n textElement = new FieldTextElementBox();\n textElement.fieldBegin = this.viewer.fieldStacks[this.viewer.fieldStacks.length - 1];\n }\n else if (inline.text === '\\t') {\n textElement = new TabElementBox();\n }\n else {\n textElement = new TextElementBox();\n }\n textElement.characterFormat = new WCharacterFormat(textElement);\n this.parseCharacterFormat(inline.characterFormat, textElement.characterFormat, writeInlineFormat);\n /*�tslint:disable-next-line:max-line-length */\n if (!isNullOrUndefined(inline.characterFormat) && !isNullOrUndefined(inline.characterFormat.styleName)) {\n var charStyle = this.viewer.styles.findByName(inline.characterFormat.styleName, 'Character');\n textElement.characterFormat.ApplyStyle(charStyle);\n }\n textElement.text = inline.text;\n textElement.line = lineWidget;\n lineWidget.children.push(textElement);\n }\n else if (inline.hasOwnProperty('imageString')) {\n var image = new ImageElementBox(data[i].isInlineImage);\n image.isMetaFile = data[i].isMetaFile;\n image.characterFormat = new WCharacterFormat(image);\n image.line = lineWidget;\n lineWidget.children.push(image);\n image.imageString = inline.imageString;\n image.width = HelperMethods.convertPointToPixel(inline.width);\n image.height = HelperMethods.convertPointToPixel(inline.height);\n this.parseCharacterFormat(inline.characterFormat, image.characterFormat);\n }\n else if (inline.hasOwnProperty('hasFieldEnd') || (inline.hasOwnProperty('fieldType') && inline.fieldType === 0)) {\n var fieldBegin = new FieldElementBox(0);\n fieldBegin.hasFieldEnd = inline.hasFieldEnd;\n this.viewer.fieldStacks.push(fieldBegin);\n fieldBegin.line = lineWidget;\n this.viewer.fields.push(fieldBegin);\n lineWidget.children.push(fieldBegin);\n }\n else if (inline.hasOwnProperty('fieldType')) {\n var field = undefined;\n if (inline.fieldType === 2) {\n field = new FieldElementBox(2);\n this.fieldSeparator = field;\n if (this.viewer.fieldStacks.length > 0) {\n field.fieldBegin = this.viewer.fieldStacks[this.viewer.fieldStacks.length - 1];\n field.fieldBegin.fieldSeparator = field;\n //finds the whether the field is page filed or not\n var lineWidgetCount = lineWidget.children.length;\n if (lineWidgetCount >= 2 && (lineWidget.children[lineWidgetCount - 2] instanceof FieldElementBox)\n && lineWidget.children[lineWidgetCount - 2].hasFieldEnd\n && (lineWidget.children[lineWidgetCount - 1] instanceof TextElementBox)) {\n var fieldElementText = lineWidget.children[lineWidgetCount - 1].text;\n if (fieldElementText.match('PAGE')) {\n this.viewer.isPageField = true;\n }\n }\n }\n }\n else if (inline.fieldType === 1) {\n field = new FieldElementBox(1);\n //For Field End Updated begin and separator. \n if (this.viewer.fieldStacks.length > 0) {\n field.fieldBegin = this.viewer.fieldStacks[this.viewer.fieldStacks.length - 1];\n field.fieldBegin.fieldEnd = field;\n }\n if (!isNullOrUndefined(field.fieldBegin) && field.fieldBegin.fieldSeparator) {\n field.fieldSeparator = field.fieldBegin.fieldSeparator;\n field.fieldBegin.fieldSeparator.fieldEnd = field;\n }\n //After setting all the property clear the field values\n this.viewer.fieldStacks.splice(this.viewer.fieldStacks.length - 1, 1);\n this.fieldSeparator = undefined;\n this.viewer.isPageField = false;\n this.viewer.fieldCollection.push(field.fieldBegin);\n }\n field.line = lineWidget;\n lineWidget.children.push(field);\n }\n else if (inline.hasOwnProperty('bookmarkType')) {\n var bookmark = undefined;\n bookmark = new BookmarkElementBox(inline.bookmarkType);\n bookmark.name = inline.name;\n lineWidget.children.push(bookmark);\n bookmark.line = lineWidget;\n if (inline.bookmarkType === 0) {\n this.viewer.bookmarks.add(bookmark.name, bookmark);\n }\n else if (inline.bookmarkType === 1) {\n if (this.viewer.bookmarks.containsKey(bookmark.name)) {\n var bookmarkStart = this.viewer.bookmarks.get(bookmark.name);\n bookmarkStart.reference = bookmark;\n bookmark.reference = bookmarkStart;\n }\n }\n }\n }\n paragraph.childWidgets.push(lineWidget);\n };\n SfdtReader.prototype.parseTableFormat = function (sourceFormat, tableFormat) {\n this.parseBorders(sourceFormat.borders, tableFormat.borders);\n if (!isNullOrUndefined(sourceFormat.cellSpacing)) {\n tableFormat.cellSpacing = sourceFormat.cellSpacing;\n }\n if (!isNullOrUndefined(sourceFormat.leftMargin)) {\n tableFormat.leftMargin = sourceFormat.leftMargin;\n }\n if (!isNullOrUndefined(sourceFormat.topMargin)) {\n tableFormat.topMargin = sourceFormat.topMargin;\n }\n if (!isNullOrUndefined(sourceFormat.rightMargin)) {\n tableFormat.rightMargin = sourceFormat.rightMargin;\n }\n if (!isNullOrUndefined(sourceFormat.bottomMargin)) {\n tableFormat.bottomMargin = sourceFormat.bottomMargin;\n }\n if (!isNullOrUndefined(sourceFormat.leftIndent)) {\n tableFormat.leftIndent = sourceFormat.leftIndent;\n }\n this.parseShading(sourceFormat.shading, tableFormat.shading);\n if (!isNullOrUndefined(sourceFormat.tableAlignment)) {\n tableFormat.tableAlignment = sourceFormat.tableAlignment;\n }\n if (!isNullOrUndefined(sourceFormat.preferredWidth)) {\n tableFormat.preferredWidth = sourceFormat.preferredWidth;\n }\n if (!isNullOrUndefined(sourceFormat.preferredWidthType)) {\n tableFormat.preferredWidthType = sourceFormat.preferredWidthType;\n }\n };\n SfdtReader.prototype.parseCellFormat = function (sourceFormat, cellFormat) {\n if (!isNullOrUndefined(sourceFormat)) {\n this.parseBorders(sourceFormat.borders, cellFormat.borders);\n if (!sourceFormat.isSamePaddingAsTable) {\n // cellFormat.ClearMargins();\n //else\n this.parseCellMargin(sourceFormat, cellFormat);\n }\n if (!isNullOrUndefined(sourceFormat.cellWidth)) {\n cellFormat.cellWidth = sourceFormat.cellWidth;\n }\n if (!isNullOrUndefined(sourceFormat.columnSpan)) {\n cellFormat.columnSpan = sourceFormat.columnSpan;\n }\n if (!isNullOrUndefined(sourceFormat.rowSpan)) {\n cellFormat.rowSpan = sourceFormat.rowSpan;\n }\n this.parseShading(sourceFormat.shading, cellFormat.shading);\n if (!isNullOrUndefined(sourceFormat.verticalAlignment)) {\n cellFormat.verticalAlignment = sourceFormat.verticalAlignment;\n }\n if (!isNullOrUndefined(sourceFormat.preferredWidthType)) {\n cellFormat.preferredWidthType = sourceFormat.preferredWidthType;\n }\n if (!isNullOrUndefined(sourceFormat.preferredWidth)) {\n cellFormat.preferredWidth = sourceFormat.preferredWidth;\n }\n }\n };\n SfdtReader.prototype.parseCellMargin = function (sourceFormat, cellFormat) {\n if (!isNullOrUndefined(sourceFormat.leftMargin)) {\n cellFormat.leftMargin = sourceFormat.leftMargin;\n }\n if (!isNullOrUndefined(sourceFormat.rightMargin)) {\n cellFormat.rightMargin = sourceFormat.rightMargin;\n }\n if (!isNullOrUndefined(sourceFormat.topMargin)) {\n cellFormat.topMargin = sourceFormat.topMargin;\n }\n if (!isNullOrUndefined(sourceFormat.bottomMargin)) {\n cellFormat.bottomMargin = sourceFormat.bottomMargin;\n }\n };\n SfdtReader.prototype.parseRowFormat = function (sourceFormat, rowFormat) {\n if (!isNullOrUndefined(sourceFormat)) {\n if (!isNullOrUndefined(sourceFormat.allowBreakAcrossPages)) {\n rowFormat.allowBreakAcrossPages = sourceFormat.allowBreakAcrossPages;\n }\n if (!isNullOrUndefined(sourceFormat.isHeader)) {\n rowFormat.isHeader = sourceFormat.isHeader;\n }\n if (!isNullOrUndefined(sourceFormat.heightType)) {\n rowFormat.heightType = sourceFormat.heightType;\n }\n if (!isNullOrUndefined(sourceFormat.height)) {\n rowFormat.height = sourceFormat.height;\n }\n this.parseBorders(sourceFormat.borders, rowFormat.borders);\n }\n };\n SfdtReader.prototype.parseBorders = function (sourceBorders, destBorder) {\n if (!isNullOrUndefined(sourceBorders)) {\n this.parseBorder(sourceBorders.left, destBorder.left);\n this.parseBorder(sourceBorders.right, destBorder.right);\n this.parseBorder(sourceBorders.top, destBorder.top);\n this.parseBorder(sourceBorders.bottom, destBorder.bottom);\n this.parseBorder(sourceBorders.vertical, destBorder.vertical);\n this.parseBorder(sourceBorders.horizontal, destBorder.horizontal);\n this.parseBorder(sourceBorders.diagonalDown, destBorder.diagonalDown);\n this.parseBorder(sourceBorders.diagonalUp, destBorder.diagonalUp);\n }\n };\n SfdtReader.prototype.parseBorder = function (sourceBorder, destBorder) {\n if (!isNullOrUndefined(sourceBorder)) {\n if (!isNullOrUndefined(sourceBorder.color)) {\n destBorder.color = this.getColor(sourceBorder.color);\n }\n if (!isNullOrUndefined(sourceBorder.lineStyle)) {\n destBorder.lineStyle = sourceBorder.lineStyle;\n }\n if (!isNullOrUndefined(sourceBorder.lineWidth)) {\n destBorder.lineWidth = sourceBorder.lineWidth;\n }\n if (!isNullOrUndefined(sourceBorder.hasNoneStyle)) {\n destBorder.hasNoneStyle = sourceBorder.hasNoneStyle;\n }\n }\n };\n SfdtReader.prototype.parseShading = function (sourceShading, destShading) {\n if (!isNullOrUndefined(sourceShading)) {\n if (!isNullOrUndefined(sourceShading.backgroundColor)) {\n destShading.backgroundColor = this.getColor(sourceShading.backgroundColor);\n }\n if (!isNullOrUndefined(sourceShading.foregroundColor)) {\n destShading.foregroundColor = this.getColor(sourceShading.foregroundColor);\n }\n if (!isNullOrUndefined(sourceShading.texture)) {\n destShading.textureStyle = sourceShading.texture;\n }\n }\n };\n SfdtReader.prototype.parseCharacterFormat = function (sourceFormat, characterFormat, writeInlineFormat) {\n if (!isNullOrUndefined(sourceFormat)) {\n if (writeInlineFormat && sourceFormat.hasOwnProperty('inlineFormat')) {\n this.parseCharacterFormat(sourceFormat.inlineFormat, characterFormat);\n return;\n }\n if (!isNullOrUndefined(sourceFormat.baselineAlignment)) {\n characterFormat.baselineAlignment = sourceFormat.baselineAlignment;\n }\n if (!isNullOrUndefined(sourceFormat.underline)) {\n characterFormat.underline = sourceFormat.underline;\n }\n if (!isNullOrUndefined(sourceFormat.strikethrough)) {\n characterFormat.strikethrough = sourceFormat.strikethrough;\n }\n if (!isNullOrUndefined(sourceFormat.fontSize)) {\n characterFormat.fontSize = sourceFormat.fontSize;\n }\n if (!isNullOrUndefined(sourceFormat.fontFamily)) {\n characterFormat.fontFamily = sourceFormat.fontFamily;\n }\n if (!isNullOrUndefined(sourceFormat.bold)) {\n characterFormat.bold = sourceFormat.bold;\n }\n if (!isNullOrUndefined(sourceFormat.italic)) {\n characterFormat.italic = sourceFormat.italic;\n }\n if (!isNullOrUndefined(sourceFormat.highlightColor)) {\n characterFormat.highlightColor = sourceFormat.highlightColor;\n }\n if (!isNullOrUndefined(sourceFormat.fontColor)) {\n characterFormat.fontColor = this.getColor(sourceFormat.fontColor);\n }\n }\n };\n SfdtReader.prototype.getColor = function (color) {\n var convertColor = color;\n return convertColor || '#ffffff';\n };\n SfdtReader.prototype.parseParagraphFormat = function (sourceFormat, paragraphFormat) {\n if (!isNullOrUndefined(sourceFormat)) {\n if (!isNullOrUndefined(sourceFormat.leftIndent)) {\n paragraphFormat.leftIndent = sourceFormat.leftIndent;\n }\n if (!isNullOrUndefined(sourceFormat.rightIndent)) {\n paragraphFormat.rightIndent = sourceFormat.rightIndent;\n }\n if (!isNullOrUndefined(sourceFormat.firstLineIndent)) {\n paragraphFormat.firstLineIndent = sourceFormat.firstLineIndent;\n }\n if (!isNullOrUndefined(sourceFormat.afterSpacing)) {\n paragraphFormat.afterSpacing = sourceFormat.afterSpacing;\n }\n if (!isNullOrUndefined(sourceFormat.beforeSpacing)) {\n paragraphFormat.beforeSpacing = sourceFormat.beforeSpacing;\n }\n if (!isNullOrUndefined(sourceFormat.lineSpacing)) {\n paragraphFormat.lineSpacing = sourceFormat.lineSpacing;\n }\n if (!isNullOrUndefined(sourceFormat.lineSpacingType)) {\n paragraphFormat.lineSpacingType = sourceFormat.lineSpacingType;\n }\n if (!isNullOrUndefined(sourceFormat.textAlignment)) {\n paragraphFormat.textAlignment = sourceFormat.textAlignment;\n }\n if (!isNullOrUndefined(sourceFormat.outlineLevel)) {\n paragraphFormat.outlineLevel = sourceFormat.outlineLevel;\n }\n paragraphFormat.listFormat = new WListFormat();\n if (sourceFormat.hasOwnProperty('listFormat')) {\n this.parseListFormat(sourceFormat, paragraphFormat.listFormat);\n }\n if (sourceFormat.hasOwnProperty('tabs')) {\n this.parseTabStop(sourceFormat.tabs, paragraphFormat.tabs);\n }\n }\n };\n SfdtReader.prototype.parseListFormat = function (block, listFormat) {\n if (!isNullOrUndefined(block.listFormat)) {\n if (!isNullOrUndefined(block.listFormat.listId)) {\n listFormat.listId = block.listFormat.listId;\n listFormat.list = this.viewer.getListById(block.listFormat.listId);\n }\n if (!isNullOrUndefined(block.listFormat.listLevelNumber)) {\n listFormat.listLevelNumber = block.listFormat.listLevelNumber;\n }\n }\n };\n SfdtReader.prototype.parseSectionFormat = function (data, sectionFormat) {\n if (!isNullOrUndefined(data.pageWidth)) {\n sectionFormat.pageWidth = data.pageWidth;\n }\n if (!isNullOrUndefined(data.pageHeight)) {\n sectionFormat.pageHeight = data.pageHeight;\n }\n if (!isNullOrUndefined(data.leftMargin)) {\n sectionFormat.leftMargin = data.leftMargin;\n }\n if (!isNullOrUndefined(data.topMargin)) {\n sectionFormat.topMargin = data.topMargin;\n }\n if (!isNullOrUndefined(data.rightMargin)) {\n sectionFormat.rightMargin = data.rightMargin;\n }\n if (!isNullOrUndefined(data.bottomMargin)) {\n sectionFormat.bottomMargin = data.bottomMargin;\n }\n if (!isNullOrUndefined(data.headerDistance)) {\n sectionFormat.headerDistance = data.headerDistance;\n }\n if (!isNullOrUndefined(data.footerDistance)) {\n sectionFormat.footerDistance = data.footerDistance;\n }\n if (!isNullOrUndefined(data.differentFirstPage)) {\n sectionFormat.differentFirstPage = data.differentFirstPage;\n }\n if (!isNullOrUndefined(data.differentOddAndEvenPages)) {\n sectionFormat.differentOddAndEvenPages = data.differentOddAndEvenPages;\n }\n };\n SfdtReader.prototype.parseTabStop = function (wTabs, tabs) {\n for (var i = 0; i < wTabs.length; i++) {\n var tabStop = new WTabStop();\n tabStop.position = wTabs[i].position;\n tabStop.tabLeader = wTabs[i].tabLeader;\n tabStop.deletePosition = wTabs[i].deletePosition;\n tabStop.tabJustification = wTabs[i].tabJustification;\n tabs.push(tabStop);\n }\n };\n return SfdtReader;\n}());\nexport { SfdtReader };\n","import { WShading } from '../format/index';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { WList } from '../list/list';\nimport { WAbstractList } from '../list/abstract-list';\nimport { WListLevel } from '../list/list-level';\n/**\n * Selection character format implementation\n */\nvar SelectionCharacterFormat = /** @class */ (function () {\n /**\n * @private\n */\n function SelectionCharacterFormat(selection) {\n this.boldIn = undefined;\n this.italicIn = undefined;\n this.underlineIn = undefined;\n this.strikeThroughIn = undefined;\n this.baselineAlignmentIn = undefined;\n this.highlightColorIn = undefined;\n this.fontSizeIn = 0;\n this.fontColorIn = undefined;\n this.selection = selection;\n }\n Object.defineProperty(SelectionCharacterFormat.prototype, \"fontSize\", {\n /**\n * Gets or sets the font size of selected contents.\n */\n get: function () {\n return this.fontSizeIn;\n },\n set: function (value) {\n if (value === this.fontSizeIn) {\n return;\n }\n this.fontSizeIn = value;\n this.notifyPropertyChanged('fontSize');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"fontFamily\", {\n /**\n * Gets or sets the font family of selected contents.\n */\n get: function () {\n return this.fontFamilyIn;\n },\n set: function (value) {\n if (value === this.fontFamilyIn) {\n return;\n }\n this.fontFamilyIn = value;\n this.notifyPropertyChanged('fontFamily');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"fontColor\", {\n /**\n * Gets or sets the font color of selected contents.\n */\n get: function () {\n return this.fontColorIn;\n },\n set: function (value) {\n if (value === this.fontColorIn) {\n return;\n }\n this.fontColorIn = value;\n this.notifyPropertyChanged('fontColor');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"bold\", {\n /**\n * Gets or sets the bold formatting of selected contents.\n */\n get: function () {\n return this.boldIn;\n },\n set: function (value) {\n if (value === this.boldIn) {\n return;\n }\n this.boldIn = value;\n this.notifyPropertyChanged('bold');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"italic\", {\n /**\n * Gets or sets the italic formatting of selected contents.\n */\n get: function () {\n return this.italicIn;\n },\n set: function (value) {\n if (value === this.italic) {\n return;\n }\n this.italicIn = value;\n this.notifyPropertyChanged('italic');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"strikethrough\", {\n /**\n * Gets or sets the strikethrough property of selected contents.\n */\n get: function () {\n return this.strikeThroughIn;\n },\n set: function (value) {\n if (value === this.strikeThroughIn) {\n return;\n }\n this.strikeThroughIn = value;\n this.notifyPropertyChanged('strikethrough');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"baselineAlignment\", {\n /**\n * Gets or sets the baseline alignment property of selected contents.\n */\n get: function () {\n return this.baselineAlignmentIn;\n },\n set: function (value) {\n if (value === this.baselineAlignmentIn) {\n return;\n }\n this.baselineAlignmentIn = value;\n this.notifyPropertyChanged('baselineAlignment');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"underline\", {\n /**\n * Gets or sets the underline style of selected contents.\n */\n get: function () {\n return this.underlineIn;\n },\n set: function (value) {\n if (value === this.underlineIn) {\n return;\n }\n this.underlineIn = value;\n this.notifyPropertyChanged('underline');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCharacterFormat.prototype, \"highlightColor\", {\n /**\n * Gets or sets the highlight color of selected contents.\n */\n get: function () {\n return this.highlightColorIn;\n },\n set: function (value) {\n if (value === this.highlightColorIn) {\n return;\n }\n this.highlightColorIn = value;\n this.notifyPropertyChanged('highlightColor');\n },\n enumerable: true,\n configurable: true\n });\n SelectionCharacterFormat.prototype.getPropertyValue = function (property) {\n switch (property) {\n case 'bold':\n return this.bold;\n case 'italic':\n return this.italic;\n case 'fontSize':\n if (this.fontSize >= 1) {\n return this.fontSize;\n }\n return undefined;\n case 'fontFamily':\n return this.fontFamily;\n case 'strikethrough':\n return this.strikethrough;\n case 'baselineAlignment':\n return this.baselineAlignment;\n case 'highlightColor':\n return this.highlightColor;\n case 'underline':\n return this.underline;\n case 'fontColor':\n return this.fontColor;\n default:\n return undefined;\n }\n };\n /**\n * Notifies whenever property gets changed.\n * @param {string} propertyName\n */\n SelectionCharacterFormat.prototype.notifyPropertyChanged = function (propertyName) {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(this.selection) && (this.selection.isCleared || this.selection.owner.isReadOnlyMode || !this.selection.owner.isDocumentLoaded || this.selection.owner.isPastingContent) && !this.selection.isRetrieveFormatting) {\n return;\n }\n if (!isNullOrUndefined(this.selection) && !isNullOrUndefined(this.selection.start) && !this.selection.isRetrieveFormatting) {\n var propertyValue = this.getPropertyValue(propertyName);\n if (!isNullOrUndefined(propertyValue)) {\n this.selection.owner.editorModule.onApplyCharacterFormat(propertyName, propertyValue);\n }\n }\n };\n /**\n * Copies the source format.\n * @param {WCharacterFormat} format\n * @returns void\n * @private\n */\n SelectionCharacterFormat.prototype.copyFormat = function (format) {\n this.styleName = !isNullOrUndefined(format.baseCharStyle) ? format.baseCharStyle.name : 'Default Paragraph Font';\n this.fontSize = format.fontSize;\n this.fontFamily = format.fontFamily;\n this.bold = format.bold;\n this.italic = format.italic;\n this.baselineAlignment = format.baselineAlignment;\n this.underline = format.underline;\n this.fontColor = format.fontColor;\n this.highlightColor = format.highlightColor;\n this.strikethrough = format.strikethrough;\n };\n /**\n * Combines the format.\n * @param {WCharacterFormat} format\n * @private\n */\n SelectionCharacterFormat.prototype.combineFormat = function (format) {\n if (!isNullOrUndefined(this.bold) && this.bold !== format.bold) {\n this.bold = undefined;\n }\n if (!isNullOrUndefined(this.italic) && this.italic !== format.italic) {\n this.italic = undefined;\n }\n if (this.fontSize !== 0 && this.fontSize !== format.fontSize) {\n this.fontSize = 0;\n }\n if (!isNullOrUndefined(this.fontFamily) && this.fontFamily !== format.fontFamily) {\n this.fontFamily = undefined;\n }\n if (!isNullOrUndefined(this.highlightColor) && this.highlightColor !== format.highlightColor) {\n this.highlightColor = undefined;\n }\n if (!isNullOrUndefined(this.baselineAlignment) && this.baselineAlignment !== format.baselineAlignment) {\n this.baselineAlignment = undefined;\n }\n if (!isNullOrUndefined(this.fontColor) && (this.fontColor !== format.fontColor)) {\n this.fontColor = undefined;\n }\n if (!isNullOrUndefined(this.underline) && this.underline !== format.underline) {\n this.underline = undefined;\n }\n if (!isNullOrUndefined(this.strikethrough) && this.strikethrough !== format.strikethrough) {\n this.strikethrough = undefined;\n }\n };\n /**\n * Clones the format.\n * @param {SelectionCharacterFormat} selectionCharacterFormat\n * @returns void\n * @private\n */\n SelectionCharacterFormat.prototype.cloneFormat = function (selectionCharacterFormat) {\n this.bold = selectionCharacterFormat.bold;\n this.italic = selectionCharacterFormat.italic;\n this.underline = selectionCharacterFormat.underline;\n this.strikethrough = selectionCharacterFormat.strikethrough;\n this.baselineAlignment = selectionCharacterFormat.baselineAlignment;\n this.highlightColor = selectionCharacterFormat.highlightColor;\n this.fontSize = selectionCharacterFormat.fontSize;\n this.fontFamily = selectionCharacterFormat.fontFamily;\n this.fontColor = selectionCharacterFormat.fontColor;\n this.styleName = selectionCharacterFormat.styleName;\n };\n /**\n * Checks whether current format is equal to the source format or not.\n * @param {SelectionCharacterFormat} format\n * @returns boolean\n * @private\n */\n SelectionCharacterFormat.prototype.isEqualFormat = function (format) {\n return (this.fontSize === format.fontSize\n && this.strikethrough === format.strikethrough\n && this.bold === format.bold\n && this.fontFamily === format.fontFamily\n && this.underline === format.underline\n && this.highlightColor === format.highlightColor\n && this.italic === format.italic\n && this.baselineAlignment === format.baselineAlignment\n && this.fontColor === format.fontColor);\n };\n /**\n * Clears the format.\n * @returns void\n * @private\n */\n SelectionCharacterFormat.prototype.clearFormat = function () {\n this.fontSizeIn = 0;\n this.boldIn = undefined;\n this.italicIn = undefined;\n this.fontFamilyIn = undefined;\n this.fontColorIn = undefined;\n this.underlineIn = undefined;\n this.strikeThroughIn = undefined;\n this.highlightColorIn = undefined;\n this.baselineAlignmentIn = undefined;\n this.styleName = undefined;\n };\n /**\n * Destroys the maintained resources.\n * @returns void\n * @private\n */\n SelectionCharacterFormat.prototype.destroy = function () {\n this.fontSizeIn = undefined;\n this.boldIn = undefined;\n this.italicIn = undefined;\n this.fontFamilyIn = undefined;\n this.fontColorIn = undefined;\n this.underlineIn = undefined;\n this.strikeThroughIn = undefined;\n this.baselineAlignmentIn = undefined;\n this.highlightColorIn = undefined;\n this.selection = undefined;\n this.styleName = undefined;\n };\n return SelectionCharacterFormat;\n}());\nexport { SelectionCharacterFormat };\n/**\n * Selection paragraph format implementation\n */\nvar SelectionParagraphFormat = /** @class */ (function () {\n /**\n * @private\n */\n function SelectionParagraphFormat(selection, viewer) {\n // Declaring the character format properties.\n this.leftIndentIn = 0;\n this.rightIndentIn = 0;\n this.beforeSpacingIn = 0;\n this.afterSpacingIn = 0;\n this.textAlignmentIn = undefined;\n this.firstLineIndentIn = 0;\n this.lineSpacingIn = 1;\n this.lineSpacingTypeIn = undefined;\n this.listLevelNumberIn = -1;\n this.selection = selection;\n this.viewer = viewer;\n }\n Object.defineProperty(SelectionParagraphFormat.prototype, \"leftIndent\", {\n /**\n * Gets or Sets the left indent for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.leftIndentIn;\n },\n set: function (value) {\n if (value === this.leftIndentIn) {\n return;\n }\n this.leftIndentIn = value;\n this.notifyPropertyChanged('leftIndent');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"rightIndent\", {\n /**\n * Gets or Sets the right indent for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.rightIndentIn;\n },\n set: function (value) {\n if (value === this.rightIndentIn) {\n return;\n }\n this.rightIndentIn = value;\n this.notifyPropertyChanged('rightIndent');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"firstLineIndent\", {\n /**\n * Gets or Sets the first line indent for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.firstLineIndentIn;\n },\n set: function (value) {\n if (value === this.firstLineIndentIn) {\n return;\n }\n this.firstLineIndentIn = value;\n this.notifyPropertyChanged('firstLineIndent');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"textAlignment\", {\n /**\n * Gets or Sets the text alignment for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.textAlignmentIn;\n },\n set: function (value) {\n if (value === this.textAlignmentIn) {\n return;\n }\n this.textAlignmentIn = value;\n this.notifyPropertyChanged('textAlignment');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"afterSpacing\", {\n /**\n * Gets or Sets the after spacing for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.afterSpacingIn;\n },\n set: function (value) {\n if (value === this.afterSpacingIn) {\n return;\n }\n this.afterSpacingIn = value;\n this.notifyPropertyChanged('afterSpacing');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"beforeSpacing\", {\n /**\n * Gets or Sets the before spacing for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.beforeSpacingIn;\n },\n set: function (value) {\n if (value === this.beforeSpacingIn) {\n return;\n }\n this.beforeSpacingIn = value;\n this.notifyPropertyChanged('beforeSpacing');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"lineSpacing\", {\n /**\n * Gets or Sets the line spacing for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.lineSpacingIn;\n },\n set: function (value) {\n if (value === this.lineSpacingIn) {\n return;\n }\n this.lineSpacingIn = value;\n this.notifyPropertyChanged('lineSpacing');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"lineSpacingType\", {\n /**\n * Gets or Sets the line spacing type for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.lineSpacingTypeIn;\n },\n set: function (value) {\n if (value === this.lineSpacingTypeIn) {\n return;\n }\n this.lineSpacingTypeIn = value;\n this.notifyPropertyChanged('lineSpacingType');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"listLevelNumber\", {\n /**\n * Gets or Sets the list level number for selected paragraphs.\n * @default undefined\n */\n get: function () {\n return this.listLevelNumberIn;\n },\n set: function (value) {\n if (value === this.listLevelNumberIn) {\n return;\n }\n this.listLevelNumberIn = value;\n this.notifyPropertyChanged('listLevelNumber');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionParagraphFormat.prototype, \"listText\", {\n /**\n * Gets the list text for selected paragraphs.\n */\n get: function () {\n var listFormat = undefined;\n var list = this.viewer.getListById(this.listId);\n if (list instanceof WList && this.listLevelNumberIn > -1 && this.listLevelNumberIn < 9) {\n var listLevel = list.getListLevel(this.listLevelNumber);\n if (listLevel instanceof WListLevel) {\n if (listLevel.listLevelPattern === 'Bullet') {\n listFormat = listLevel.numberFormat;\n }\n else {\n listFormat = listLevel.numberFormat;\n for (var i = 0; i < 9; i++) {\n var levelPattern = '%' + (i + 1);\n if (listFormat.indexOf(levelPattern) > -1) {\n var level = i === this.listLevelNumberIn ? listLevel : list.getListLevel(i);\n var listText = this.selection.owner.viewer.layout.getListTextListLevel(level, 1);\n listFormat = listFormat.replace(levelPattern, listText);\n }\n }\n }\n }\n }\n return listFormat;\n },\n enumerable: true,\n configurable: true\n });\n SelectionParagraphFormat.prototype.getPropertyValue = function (property) {\n switch (property) {\n case 'leftIndent':\n return this.leftIndent;\n case 'rightIndent':\n return this.rightIndent;\n case 'firstLineIndent':\n return this.firstLineIndent;\n case 'beforeSpacing':\n return this.beforeSpacing;\n case 'afterSpacing':\n return this.afterSpacing;\n case 'textAlignment':\n return this.textAlignment;\n case 'lineSpacing':\n return this.lineSpacing;\n case 'lineSpacingType':\n return this.lineSpacingType;\n default:\n return undefined;\n }\n };\n /**\n * Notifies whenever the property gets changed.\n * @param {string} propertyName\n */\n SelectionParagraphFormat.prototype.notifyPropertyChanged = function (propertyName) {\n if (!isNullOrUndefined(this.selection) &&\n (this.selection.owner.isReadOnlyMode || !this.selection.owner.isDocumentLoaded)\n && !this.selection.isRetrieveFormatting) {\n return;\n }\n if (!isNullOrUndefined(this.selection) && !isNullOrUndefined(this.selection.start) && !this.selection.isRetrieveFormatting) {\n var editorModule = this.selection.owner.editorModule;\n var value = this.getPropertyValue(propertyName);\n if ((propertyName === 'leftIndent' || propertyName === 'rightIndent' || propertyName === 'firstLineIndent')\n && !(value >= -1056 && value < 1056)) {\n return;\n }\n if (propertyName === 'listLevelNumber') {\n editorModule.onApplyListInternal(this.viewer.getListById(this.listId), this.listLevelNumber);\n }\n else {\n editorModule.onApplyParagraphFormat(propertyName, value, propertyName === 'textAlignment' ? true : false, false);\n }\n }\n };\n /**\n * Copies the format.\n * @param {WParagraphFormat} format\n * @returns void\n * @private\n */\n SelectionParagraphFormat.prototype.copyFormat = function (format) {\n this.styleName = !isNullOrUndefined(format.baseStyle) ? format.baseStyle.name : 'Normal';\n this.leftIndent = format.leftIndent;\n this.rightIndent = format.rightIndent;\n this.firstLineIndent = format.firstLineIndent;\n this.afterSpacing = format.afterSpacing;\n this.beforeSpacing = format.beforeSpacing;\n this.lineSpacing = format.lineSpacing;\n this.lineSpacingType = format.lineSpacingType;\n this.textAlignment = format.textAlignment;\n if (!isNullOrUndefined(format.listFormat) && !isNullOrUndefined(format.listFormat.listId)) {\n this.listId = format.listFormat.listId;\n this.listLevelNumber = format.listFormat.listLevelNumber;\n }\n else {\n this.listId = undefined;\n this.listLevelNumber = 0;\n }\n };\n /**\n * Copies to format.\n * @param {WParagraphFormat} format\n * @private\n */\n SelectionParagraphFormat.prototype.copyToFormat = function (format) {\n if (isNullOrUndefined(format)) {\n return;\n }\n if (!isNullOrUndefined(this.afterSpacing)) {\n format.afterSpacing = this.afterSpacing;\n }\n if (!isNullOrUndefined(this.beforeSpacing)) {\n format.beforeSpacing = this.beforeSpacing;\n }\n if (!isNullOrUndefined(this.leftIndent)) {\n format.leftIndent = this.leftIndent;\n }\n if (!isNullOrUndefined(this.rightIndent)) {\n format.rightIndent = this.rightIndent;\n }\n if (!isNullOrUndefined(this.textAlignment)) {\n format.textAlignment = this.textAlignment;\n }\n if (!isNullOrUndefined(this.lineSpacing)) {\n format.lineSpacing = this.lineSpacing;\n }\n if (!isNullOrUndefined(this.lineSpacingType)) {\n format.lineSpacingType = this.lineSpacingType;\n }\n if (!isNullOrUndefined(this.firstLineIndent)) {\n format.firstLineIndent = this.firstLineIndent;\n }\n };\n /**\n * Combines the format.\n * @param {WParagraphFormat} format\n * @private\n */\n SelectionParagraphFormat.prototype.combineFormat = function (format) {\n if (!isNullOrUndefined(this.leftIndent) && this.leftIndent !== format.leftIndent) {\n this.leftIndent = undefined;\n }\n if (!isNullOrUndefined(this.rightIndent) && this.rightIndent !== format.rightIndent) {\n this.rightIndent = undefined;\n }\n if (!isNullOrUndefined(this.firstLineIndent) && this.firstLineIndent !== format.firstLineIndent) {\n this.firstLineIndent = undefined;\n }\n if (this.lineSpacing !== 0 && this.lineSpacing !== format.lineSpacing) {\n this.lineSpacing = 0;\n }\n if (this.beforeSpacing !== -1 && this.beforeSpacing !== format.beforeSpacing) {\n this.beforeSpacing = -1;\n }\n if (this.afterSpacing !== -1 && this.afterSpacing !== format.afterSpacing) {\n this.afterSpacing = -1;\n }\n if (!isNullOrUndefined(this.lineSpacingType) && this.lineSpacingType !== format.lineSpacingType) {\n this.lineSpacingType = undefined;\n }\n if (!isNullOrUndefined(this.textAlignment) && this.textAlignment !== format.textAlignment) {\n this.textAlignment = undefined;\n }\n // tslint:disable-next-line:max-line-length\n if (this.listLevelNumber >= 0 && !isNullOrUndefined(this.listId) && (isNullOrUndefined(format.listFormat) || format.listFormat.listLevelNumber !== this.listLevelNumber)) {\n this.listLevelNumber = -1;\n }\n // tslint:disable-next-line:max-line-length\n if (isNullOrUndefined(format.listFormat) || isNullOrUndefined(format.listFormat.listId) || (!isNullOrUndefined(this.listId) && this.listId !== format.listFormat.listId)) {\n this.listId = undefined;\n }\n };\n /**\n * Clears the format.\n * @returns void\n * @private\n */\n SelectionParagraphFormat.prototype.clearFormat = function () {\n this.leftIndent = 0;\n this.rightIndent = 0;\n this.beforeSpacing = 0;\n this.afterSpacing = 0;\n this.firstLineIndent = 0;\n this.lineSpacing = 1;\n this.textAlignment = undefined;\n this.lineSpacingType = undefined;\n this.listId = undefined;\n this.listLevelNumber = -1;\n this.styleName = undefined;\n };\n /**\n * Gets the clone of list at current selection.\n * @returns WList\n * @private\n */\n SelectionParagraphFormat.prototype.getList = function () {\n var list = this.viewer.getListById(this.listId);\n if (!isNullOrUndefined(list)) {\n var listAdv = new WList();\n var abstractList = new WAbstractList();\n var currentAbstractList = this.viewer.getAbstractListById(list.abstractListId);\n var editor = this.selection.owner.editorModule;\n if (!isNullOrUndefined(currentAbstractList)) {\n for (var i = 0; i < currentAbstractList.levels.length; i++) {\n var level = editor.cloneListLevel(currentAbstractList.levels[i]);\n abstractList.levels.push(level);\n level.ownerBase = abstractList;\n }\n }\n else {\n abstractList.levels.push(new WListLevel(abstractList));\n }\n if (!isNullOrUndefined(list.levelOverrides)) {\n for (var i = 0; i < list.levelOverrides.length; i++) {\n var levelOverride = editor.cloneLevelOverride(list.levelOverrides[i]);\n listAdv.levelOverrides.push(levelOverride);\n }\n }\n listAdv.abstractList = abstractList;\n listAdv.abstractListId = abstractList.abstractListId;\n listAdv.sourceListId = list.listId;\n return listAdv;\n }\n return undefined;\n };\n /**\n * Modifies the list at current selection.\n * @param {WList} listAdv\n * @private\n */\n SelectionParagraphFormat.prototype.setList = function (listAdv) {\n if (this.viewer.owner.isReadOnlyMode || !this.viewer.owner.isDocumentLoaded) {\n return;\n }\n var list = this.viewer.getListById(this.listId);\n var collection = undefined;\n var currentAbstractList = listAdv ? this.viewer.getAbstractListById(listAdv.abstractListId) : undefined;\n if (!isNullOrUndefined(list) && !isNullOrUndefined(listAdv)\n && !isNullOrUndefined(currentAbstractList) && listAdv.sourceListId === list.listId) {\n var history_1 = this.viewer.owner.editorHistory;\n var listLevel = this.viewer.layout.getListLevel(list, 1);\n this.selection.owner.isLayoutEnabled = false;\n this.viewer.owner.editorModule.setOffsetValue(this.selection);\n if (history_1) {\n collection = history_1.updateListChangesInHistory(currentAbstractList, list);\n }\n this.viewer.owner.editorModule.updateListParagraphs();\n if (history_1) {\n history_1.applyListChanges(this.selection, collection);\n }\n this.selection.owner.isLayoutEnabled = true;\n this.viewer.renderedLists.clear();\n // this.viewer.pages = [];\n this.viewer.owner.editorModule.layoutWholeDocument();\n this.viewer.owner.editorModule.updateSelectionTextPosition(false);\n if (history_1 && history_1.currentBaseHistoryInfo) {\n if (history_1.currentBaseHistoryInfo.modifiedProperties.length > 0) {\n history_1.currentBaseHistoryInfo.updateSelection();\n }\n history_1.updateHistory();\n }\n this.viewer.owner.editorModule.fireContentChange();\n }\n else if (!isNullOrUndefined(listAdv)) {\n this.selection.owner.isLayoutEnabled = false;\n if (!isNullOrUndefined(currentAbstractList) && this.viewer.abstractLists.indexOf(currentAbstractList) === -1) {\n this.viewer.abstractLists.push(currentAbstractList);\n }\n if (this.viewer.lists.indexOf(listAdv) === -1) {\n this.viewer.lists.push(listAdv);\n }\n //currentAbstractList.listType = 'Numbering';\n this.selection.owner.isLayoutEnabled = true;\n this.selection.owner.editorModule.onApplyList(listAdv);\n }\n else {\n this.selection.owner.editorModule.onApplyList(undefined);\n }\n };\n /**\n * Destroys the managed resources.\n * @returns void\n * @private\n */\n SelectionParagraphFormat.prototype.destroy = function () {\n this.leftIndentIn = undefined;\n this.rightIndentIn = undefined;\n this.beforeSpacingIn = undefined;\n this.afterSpacingIn = undefined;\n this.firstLineIndentIn = undefined;\n this.lineSpacingIn = undefined;\n this.textAlignmentIn = undefined;\n this.lineSpacingTypeIn = undefined;\n this.listId = undefined;\n this.listLevelNumberIn = undefined;\n this.viewer = undefined;\n this.selection = undefined;\n this.styleName = undefined;\n };\n return SelectionParagraphFormat;\n}());\nexport { SelectionParagraphFormat };\n/**\n * Selection section format implementation\n */\nvar SelectionSectionFormat = /** @class */ (function () {\n /**\n * @private\n */\n function SelectionSectionFormat(selection) {\n this.differentFirstPageIn = undefined;\n this.differentOddAndEvenPagesIn = undefined;\n this.selection = selection;\n }\n Object.defineProperty(SelectionSectionFormat.prototype, \"pageHeight\", {\n /**\n * Gets or sets the page height.\n */\n get: function () {\n return this.pageHeightIn;\n },\n set: function (value) {\n this.pageHeightIn = value;\n this.notifyPropertyChanged('pageHeight');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"pageWidth\", {\n /**\n * Gets or sets the page width.\n */\n get: function () {\n return this.pageWidthIn;\n },\n set: function (value) {\n this.pageWidthIn = value;\n this.notifyPropertyChanged('pageWidth');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"leftMargin\", {\n /**\n * Gets or sets the page left margin.\n */\n get: function () {\n return this.leftMarginIn;\n },\n set: function (value) {\n this.leftMarginIn = value;\n this.notifyPropertyChanged('leftMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"bottomMargin\", {\n /**\n * Gets or sets the page bottom margin.\n */\n get: function () {\n return this.bottomMarginIn;\n },\n set: function (value) {\n this.bottomMarginIn = value;\n this.notifyPropertyChanged('bottomMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"topMargin\", {\n /**\n * Gets or sets the page top margin.\n */\n get: function () {\n return this.topMarginIn;\n },\n set: function (value) {\n this.topMarginIn = value;\n this.notifyPropertyChanged('topMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"rightMargin\", {\n /**\n * Gets or sets the page right margin.\n */\n get: function () {\n return this.rightMarginIn;\n },\n set: function (value) {\n this.rightMarginIn = value;\n this.notifyPropertyChanged('rightMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"headerDistance\", {\n /**\n * Gets or sets the header distance.\n */\n get: function () {\n return this.headerDistanceIn;\n },\n set: function (value) {\n this.headerDistanceIn = value;\n this.notifyPropertyChanged('headerDistance');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"footerDistance\", {\n /**\n * Gets or sets the footer distance.\n */\n get: function () {\n return this.footerDistanceIn;\n },\n set: function (value) {\n this.footerDistanceIn = value;\n this.notifyPropertyChanged('footerDistance');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"differentFirstPage\", {\n /**\n * Gets or sets a value indicating whether the section has different first page.\n */\n get: function () {\n return this.differentFirstPageIn;\n },\n set: function (value) {\n this.differentFirstPageIn = value;\n this.notifyPropertyChanged('differentFirstPage');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionSectionFormat.prototype, \"differentOddAndEvenPages\", {\n /**\n * Gets or sets a value indicating whether the section has different odd and even page.\n */\n get: function () {\n return this.differentOddAndEvenPagesIn;\n },\n set: function (value) {\n this.differentOddAndEvenPagesIn = value;\n this.notifyPropertyChanged('differentOddAndEvenPages');\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Copies the format.\n * @param {WSectionFormat} format\n * @returns void\n * @private\n */\n SelectionSectionFormat.prototype.copyFormat = function (format) {\n this.pageHeight = format.pageHeight;\n this.pageWidth = format.pageWidth;\n this.leftMargin = format.leftMargin;\n this.topMargin = format.topMargin;\n this.rightMargin = format.rightMargin;\n this.bottomMargin = format.bottomMargin;\n this.headerDistance = format.headerDistance;\n this.footerDistance = format.footerDistance;\n this.differentFirstPage = format.differentFirstPage;\n this.differentOddAndEvenPages = format.differentOddAndEvenPages;\n };\n SelectionSectionFormat.prototype.notifyPropertyChanged = function (propertyName) {\n var selection = this.selection;\n if (!isNullOrUndefined(selection) && (selection.isCleared || selection.owner.isPastingContent\n || selection.owner.isReadOnlyMode || !selection.owner.isDocumentLoaded)\n && !selection.isRetrieveFormatting) {\n return;\n }\n if (!isNullOrUndefined(selection) && !isNullOrUndefined(selection.start) && !selection.isRetrieveFormatting) {\n var value = this.getPropertyvalue(propertyName);\n if (!isNullOrUndefined(value)) {\n selection.owner.editorModule.onApplySectionFormat(propertyName, value);\n }\n }\n };\n SelectionSectionFormat.prototype.getPropertyvalue = function (propertyName) {\n switch (propertyName) {\n case 'pageHeight':\n if (this.pageHeight > 0) {\n return this.pageHeight;\n }\n return undefined;\n case 'pageWidth':\n if (this.pageWidth > 0) {\n return this.pageWidth;\n }\n return undefined;\n case 'leftMargin':\n if (this.leftMargin >= 0) {\n return this.leftMargin;\n }\n return undefined;\n case 'rightMargin':\n if (this.rightMargin >= 0) {\n return this.rightMargin;\n }\n return undefined;\n case 'topMargin':\n if (this.topMargin >= 0) {\n return this.topMargin;\n }\n return undefined;\n case 'bottomMargin':\n if (this.bottomMargin >= 0) {\n return this.bottomMargin;\n }\n return undefined;\n case 'differentFirstPage':\n if (!isNullOrUndefined(this.differentFirstPage)) {\n return this.differentFirstPage;\n }\n return undefined;\n case 'differentOddAndEvenPages':\n if (!isNullOrUndefined(this.differentOddAndEvenPages)) {\n return this.differentOddAndEvenPages;\n }\n return undefined;\n case 'headerDistance':\n return this.headerDistanceIn;\n case 'footerDistance':\n return this.footerDistance;\n default:\n return undefined;\n }\n };\n /**\n * Combines the format.\n * @param {WSectionFormat} format\n * @private\n */\n SelectionSectionFormat.prototype.combineFormat = function (format) {\n if (this.pageHeight > 0 && this.pageHeight !== format.pageHeight) {\n this.pageHeight = 0;\n }\n if (this.pageWidth > 0 && this.pageWidth !== format.pageWidth) {\n this.pageWidth = 0;\n }\n if (this.leftMargin > -1 && this.leftMargin !== format.leftMargin) {\n this.leftMargin = -1;\n }\n if (this.topMargin > -1 && this.topMargin !== format.topMargin) {\n this.topMargin = -1;\n }\n if (this.rightMargin > -1 && this.rightMargin !== format.rightMargin) {\n this.rightMargin = -1;\n }\n if (this.bottomMargin > -1 && this.bottomMargin !== format.bottomMargin) {\n this.bottomMargin = -1;\n }\n if (this.headerDistance !== 0 && this.headerDistance !== format.headerDistance) {\n this.headerDistance = 0;\n }\n if (this.footerDistance !== 0 && this.footerDistance !== format.footerDistance) {\n this.footerDistance = 0;\n }\n if (!isNullOrUndefined(this.differentFirstPage) && this.differentFirstPage !== format.differentFirstPage) {\n this.differentFirstPage = undefined;\n }\n if (!isNullOrUndefined(this.differentOddAndEvenPages) && this.differentOddAndEvenPages !== format.differentOddAndEvenPages) {\n this.differentOddAndEvenPages = undefined;\n }\n };\n /**\n * Clears the format.\n * @returns void\n * @private\n */\n SelectionSectionFormat.prototype.clearFormat = function () {\n this.headerDistance = 0;\n this.footerDistance = 0;\n this.pageHeight = 0;\n this.pageWidth = 0;\n this.leftMargin = -1;\n this.rightMargin = -1;\n this.topMargin = -1;\n this.bottomMargin = -1;\n this.differentFirstPage = undefined;\n this.differentOddAndEvenPages = undefined;\n };\n /**\n * Destroys the managed resources.\n * @returns void\n * @private\n */\n SelectionSectionFormat.prototype.destroy = function () {\n this.headerDistanceIn = undefined;\n this.footerDistanceIn = undefined;\n this.pageHeightIn = undefined;\n this.pageWidthIn = undefined;\n this.leftMarginIn = undefined;\n this.rightMarginIn = undefined;\n this.topMarginIn = undefined;\n this.bottomMarginIn = undefined;\n this.differentFirstPageIn = undefined;\n this.differentOddAndEvenPagesIn = undefined;\n this.selection = undefined;\n };\n return SelectionSectionFormat;\n}());\nexport { SelectionSectionFormat };\n/**\n * Selection table format implementation\n */\nvar SelectionTableFormat = /** @class */ (function () {\n /**\n * @private\n */\n function SelectionTableFormat(selection) {\n this.leftIndentIn = 0;\n this.backgroundIn = undefined;\n this.tableAlignmentIn = undefined;\n this.cellSpacingIn = 0;\n this.leftMarginIn = 0;\n this.rightMarginIn = 0;\n this.topMarginIn = 0;\n this.bottomMarginIn = 0;\n this.preferredWidthIn = 0;\n this.selection = selection;\n }\n Object.defineProperty(SelectionTableFormat.prototype, \"table\", {\n /**\n * Gets or sets the table.\n * @private\n */\n get: function () {\n return this.tableIn;\n },\n set: function (value) {\n this.tableIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"leftIndent\", {\n /**\n * Gets or Sets the left indent for selected table.\n * @private\n */\n get: function () {\n return this.leftIndentIn;\n },\n set: function (value) {\n if (value === this.leftIndentIn) {\n return;\n }\n this.leftIndentIn = value;\n this.notifyPropertyChanged('leftIndent');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"topMargin\", {\n /**\n * Gets or Sets the default top margin of cell for selected table.\n * @default undefined\n */\n get: function () {\n return this.topMarginIn;\n },\n set: function (value) {\n if (value === this.topMarginIn) {\n return;\n }\n this.topMarginIn = value;\n this.notifyPropertyChanged('topMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"background\", {\n /**\n * Gets or Sets the background for selected table.\n * @default undefined\n */\n get: function () {\n return this.backgroundIn;\n },\n set: function (value) {\n if (value === this.backgroundIn) {\n return;\n }\n this.backgroundIn = value;\n this.notifyPropertyChanged('background');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"tableAlignment\", {\n /**\n * Gets or Sets the table alignment for selected table.\n * @default undefined\n */\n get: function () {\n return this.tableAlignmentIn;\n },\n set: function (value) {\n if (value === this.tableAlignmentIn) {\n return;\n }\n this.tableAlignmentIn = value;\n this.notifyPropertyChanged('tableAlignment');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"leftMargin\", {\n /**\n * Gets or Sets the default left margin of cell for selected table.\n * @default undefined\n */\n get: function () {\n return this.leftMarginIn;\n },\n set: function (value) {\n if (value === this.leftMarginIn) {\n return;\n }\n this.leftMarginIn = value;\n this.notifyPropertyChanged('leftMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"bottomMargin\", {\n /**\n * Gets or Sets the default bottom margin of cell for selected table.\n * @default undefined\n */\n get: function () {\n return this.bottomMarginIn;\n },\n set: function (value) {\n if (value === this.bottomMarginIn) {\n return;\n }\n this.bottomMarginIn = value;\n this.notifyPropertyChanged('bottomMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"cellSpacing\", {\n /**\n * Gets or Sets the cell spacing for selected table.\n * @default undefined\n */\n get: function () {\n return this.cellSpacingIn;\n },\n set: function (value) {\n if (value === this.cellSpacingIn) {\n return;\n }\n this.cellSpacingIn = value;\n this.notifyPropertyChanged('cellSpacing');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"rightMargin\", {\n /**\n * Gets or Sets the default right margin of cell for selected table.\n * @default undefined\n */\n get: function () {\n return this.rightMarginIn;\n },\n set: function (value) {\n if (value === this.rightMarginIn) {\n return;\n }\n this.rightMarginIn = value;\n this.notifyPropertyChanged('rightMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"preferredWidth\", {\n /**\n * Gets or Sets the preferred width for selected table.\n * @default undefined\n */\n get: function () {\n return this.preferredWidthIn;\n },\n set: function (value) {\n if (value === this.preferredWidthIn) {\n return;\n }\n this.preferredWidthIn = value;\n this.notifyPropertyChanged('preferredWidth');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionTableFormat.prototype, \"preferredWidthType\", {\n /**\n * Gets or Sets the preferred width type for selected table.\n * @default undefined\n */\n get: function () {\n return this.preferredWidthTypeIn;\n },\n set: function (value) {\n if (value === this.preferredWidthTypeIn) {\n return;\n }\n this.preferredWidthTypeIn = value;\n this.notifyPropertyChanged('preferredWidthType');\n },\n enumerable: true,\n configurable: true\n });\n SelectionTableFormat.prototype.getPropertyValue = function (propertyName) {\n switch (propertyName) {\n case 'tableAlignment':\n return this.tableAlignment;\n case 'leftIndent':\n return this.leftIndent;\n case 'cellSpacing':\n return this.cellSpacing;\n case 'leftMargin':\n return this.leftMargin;\n case 'rightMargin':\n return this.rightMargin;\n case 'topMargin':\n return this.topMargin;\n case 'bottomMargin':\n return this.bottomMargin;\n case 'background':\n var shading = new WShading();\n shading.backgroundColor = this.background;\n return shading;\n case 'preferredWidth':\n return this.preferredWidth;\n case 'preferredWidthType':\n return this.preferredWidthType;\n default:\n return undefined;\n }\n };\n SelectionTableFormat.prototype.notifyPropertyChanged = function (propertyName) {\n if (!isNullOrUndefined(this.selection) && (this.selection.isCleared\n || !this.selection.owner.isDocumentLoaded || this.selection.owner.isReadOnlyMode\n || this.selection.owner.isPastingContent) && !this.selection.isRetrieveFormatting) {\n return;\n }\n if (!isNullOrUndefined(this.selection) && !isNullOrUndefined(this.selection.start) && !this.selection.isRetrieveFormatting) {\n var value = this.getPropertyValue(propertyName);\n if (propertyName === 'background') {\n propertyName = 'shading';\n }\n if (!isNullOrUndefined(value)) {\n this.selection.owner.editorModule.onApplyTableFormat(propertyName, value);\n }\n }\n };\n /**\n * Copies the format.\n * @param {WTableFormat} format Format to copy.\n * @returns void\n * @private\n */\n SelectionTableFormat.prototype.copyFormat = function (format) {\n this.leftIndent = format.leftIndent;\n this.background = format.shading.backgroundColor;\n this.tableAlignment = format.tableAlignment;\n this.leftMargin = format.leftMargin;\n this.rightMargin = format.rightMargin;\n this.topMargin = format.topMargin;\n this.bottomMargin = format.bottomMargin;\n this.cellSpacing = format.cellSpacing;\n this.preferredWidth = format.preferredWidth;\n this.preferredWidthType = format.preferredWidthType;\n };\n /**\n * Clears the format.\n * @returns void\n * @private\n */\n SelectionTableFormat.prototype.clearFormat = function () {\n this.table = undefined;\n this.leftIndent = 0;\n this.background = undefined;\n this.leftIndent = 0;\n this.leftMargin = 0;\n this.rightMargin = 0;\n this.topMargin = 0;\n this.bottomMargin = 0;\n this.cellSpacing = 0;\n this.tableAlignment = undefined;\n };\n /**\n * Destroys the managed resources.\n * @returns void\n * @private\n */\n SelectionTableFormat.prototype.destroy = function () {\n this.leftIndentIn = undefined;\n this.backgroundIn = undefined;\n this.leftIndentIn = undefined;\n this.leftMarginIn = undefined;\n this.rightMarginIn = undefined;\n this.topMarginIn = undefined;\n this.bottomMarginIn = undefined;\n this.cellSpacingIn = undefined;\n this.tableAlignmentIn = undefined;\n this.tableIn = undefined;\n this.selection = undefined;\n };\n return SelectionTableFormat;\n}());\nexport { SelectionTableFormat };\n/**\n * Selection cell format implementation\n */\nvar SelectionCellFormat = /** @class */ (function () {\n /**\n * @private\n */\n function SelectionCellFormat(selection) {\n this.verticalAlignmentIn = undefined;\n this.leftMarginIn = 0;\n this.rightMarginIn = 0;\n this.topMarginIn = 0;\n this.bottomMarginIn = 0;\n this.backgroundIn = undefined;\n this.preferredWidthTypeIn = undefined;\n this.selection = selection;\n }\n Object.defineProperty(SelectionCellFormat.prototype, \"verticalAlignment\", {\n /**\n * Gets or sets the vertical alignment of the selected cells.\n * @default undefined\n */\n get: function () {\n return this.verticalAlignmentIn;\n },\n set: function (value) {\n if (value === this.verticalAlignmentIn) {\n return;\n }\n this.verticalAlignmentIn = value;\n this.notifyPropertyChanged('verticalAlignment');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCellFormat.prototype, \"leftMargin\", {\n /**\n * Gets or Sets the left margin for selected cells.\n * @default undefined\n */\n /* tslint:disable */\n get: function () {\n return this.leftMarginIn;\n },\n set: function (value) {\n if (value === this.leftMarginIn) {\n return;\n }\n this.leftMarginIn = value;\n this.notifyPropertyChanged('leftMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCellFormat.prototype, \"rightMargin\", {\n /**\n * Gets or Sets the right margin for selected cells.\n * @default undefined\n */\n get: function () {\n return this.rightMarginIn;\n },\n set: function (value) {\n if (value === this.rightMarginIn) {\n return;\n }\n this.rightMarginIn = value;\n this.notifyPropertyChanged('rightMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCellFormat.prototype, \"topMargin\", {\n /**\n * Gets or Sets the top margin for selected cells.\n * @default undefined\n */\n get: function () {\n return this.topMarginIn;\n },\n set: function (value) {\n if (value === this.topMarginIn) {\n return;\n }\n this.topMarginIn = value;\n this.notifyPropertyChanged('topMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCellFormat.prototype, \"bottomMargin\", {\n /**\n * Gets or Sets the bottom margin for selected cells.\n * @default undefined\n */\n get: function () {\n return this.bottomMarginIn;\n },\n set: function (value) {\n if (value === this.bottomMarginIn) {\n return;\n }\n this.bottomMarginIn = value;\n this.notifyPropertyChanged('bottomMargin');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCellFormat.prototype, \"background\", {\n /**\n * Gets or Sets the background for selected cells.\n * @default undefined\n */\n get: function () {\n return this.backgroundIn;\n },\n /* tslint:enable */\n set: function (value) {\n if (value === this.backgroundIn) {\n return;\n }\n this.backgroundIn = value;\n this.notifyPropertyChanged('background');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCellFormat.prototype, \"preferredWidthType\", {\n /* tslint:disable */\n /**\n * Gets or Sets the preferred width type for selected cells.\n * @default undefined\n */\n get: function () {\n return this.preferredWidthTypeIn;\n },\n set: function (value) {\n if (value === this.preferredWidthTypeIn) {\n return;\n }\n this.preferredWidthTypeIn = value;\n this.notifyPropertyChanged('preferredWidthType');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionCellFormat.prototype, \"preferredWidth\", {\n /**\n * Gets or Sets the preferred width for selected cells.\n * @default undefined\n */\n get: function () {\n return this.preferredWidthIn;\n },\n set: function (value) {\n if (value === this.preferredWidthIn) {\n return;\n }\n this.preferredWidthIn = value;\n this.notifyPropertyChanged('preferredWidth');\n },\n enumerable: true,\n configurable: true\n });\n /* tslint:enable */\n SelectionCellFormat.prototype.notifyPropertyChanged = function (propertyName) {\n var selection = this.selection;\n if (!isNullOrUndefined(selection)) {\n if ((selection.isCleared || !selection.owner.isDocumentLoaded\n || selection.owner.isReadOnlyMode || selection.owner.isPastingContent) && !selection.isRetrieveFormatting) {\n return;\n }\n if (!isNullOrUndefined(this.selection.start) && !this.selection.isRetrieveFormatting) {\n var value = this.getPropertyValue(propertyName);\n if (propertyName === 'background') {\n propertyName = 'shading';\n }\n if (!isNullOrUndefined(value)) {\n this.selection.owner.editorModule.onApplyTableCellFormat(propertyName, value);\n }\n }\n }\n };\n SelectionCellFormat.prototype.getPropertyValue = function (propertyName) {\n switch (propertyName) {\n case 'verticalAlignment':\n return this.verticalAlignment;\n case 'leftMargin':\n return this.leftMargin;\n case 'rightMargin':\n return this.rightMargin;\n case 'topMargin':\n return this.topMargin;\n case 'bottomMargin':\n return this.bottomMargin;\n case 'preferredWidth':\n return this.preferredWidth;\n case 'preferredWidthType':\n return this.preferredWidthType;\n case 'background':\n var shading = new WShading();\n shading.backgroundColor = this.background;\n return shading;\n default:\n return undefined;\n }\n };\n /**\n * Copies the format.\n * @param {WCellFormat} format Source Format to copy.\n * @returns void\n * @private\n */\n SelectionCellFormat.prototype.copyFormat = function (format) {\n this.leftMargin = format.leftMargin;\n this.rightMargin = format.rightMargin;\n this.topMargin = format.topMargin;\n this.bottomMargin = format.bottomMargin;\n this.background = format.shading.backgroundColor;\n this.verticalAlignment = format.verticalAlignment;\n this.preferredWidth = format.preferredWidth;\n this.preferredWidthType = format.preferredWidthType;\n };\n /**\n * Clears the format.\n * @returns void\n * @private\n */\n SelectionCellFormat.prototype.clearCellFormat = function () {\n this.leftMargin = undefined;\n this.rightMargin = undefined;\n this.topMargin = undefined;\n this.bottomMargin = undefined;\n this.background = undefined;\n this.verticalAlignment = undefined;\n };\n /**\n * Combines the format.\n * @param {WCellFormat} format\n * @private\n */\n SelectionCellFormat.prototype.combineFormat = function (format) {\n if (!isNullOrUndefined(this.leftMargin) && this.leftMargin !== format.leftMargin) {\n this.leftMargin = undefined;\n }\n if (!isNullOrUndefined(this.topMargin) && this.topMargin !== format.topMargin) {\n this.topMargin = undefined;\n }\n if (!isNullOrUndefined(this.rightMargin) && this.rightMargin !== format.rightMargin) {\n this.rightMargin = undefined;\n }\n if (!isNullOrUndefined(this.bottomMargin) && this.bottomMargin !== format.bottomMargin) {\n this.bottomMargin = undefined;\n }\n if (!isNullOrUndefined(this.background) && this.background !== format.shading.backgroundColor) {\n this.background = undefined;\n }\n if (!isNullOrUndefined(this.verticalAlignment) && this.verticalAlignment !== format.verticalAlignment) {\n this.verticalAlignment = undefined;\n }\n if (!isNullOrUndefined(this.preferredWidth) && this.preferredWidth !== format.preferredWidth) {\n this.preferredWidth = undefined;\n }\n if (!isNullOrUndefined(this.preferredWidthType) && this.preferredWidthType !== format.preferredWidthType) {\n this.preferredWidthType = undefined;\n }\n };\n /**\n * Clears the format.\n * @returns void\n * @private\n */\n SelectionCellFormat.prototype.clearFormat = function () {\n this.background = undefined;\n this.bottomMargin = 0;\n this.leftMargin = 0;\n this.rightMargin = 0;\n this.topMargin = 0;\n this.verticalAlignment = undefined;\n };\n /**\n * Destroys the manages resources.\n * @returns void\n * @private\n */\n SelectionCellFormat.prototype.destroy = function () {\n this.backgroundIn = undefined;\n this.verticalAlignmentIn = undefined;\n this.bottomMarginIn = undefined;\n this.leftMarginIn = undefined;\n this.rightMarginIn = undefined;\n this.topMarginIn = undefined;\n this.selection = undefined;\n };\n return SelectionCellFormat;\n}());\nexport { SelectionCellFormat };\n/**\n * Selection row format implementation\n */\nvar SelectionRowFormat = /** @class */ (function () {\n /**\n * @private\n */\n function SelectionRowFormat(selection) {\n this.heightIn = undefined;\n this.heightTypeIn = undefined;\n this.isHeaderIn = undefined;\n this.allowRowBreakAcrossPagesIn = undefined;\n this.selection = selection;\n }\n Object.defineProperty(SelectionRowFormat.prototype, \"height\", {\n /**\n * Gets or Sets the height for selected rows.\n * @default undefined\n */\n get: function () {\n return this.heightIn;\n },\n set: function (value) {\n if (value === this.heightIn) {\n return;\n }\n this.heightIn = value;\n this.notifyPropertyChanged('height');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionRowFormat.prototype, \"heightType\", {\n /**\n * Gets or Sets the height type for selected rows.\n * @default undefined\n */\n get: function () {\n return this.heightTypeIn;\n },\n set: function (value) {\n if (value === this.heightTypeIn) {\n return;\n }\n this.heightTypeIn = value;\n this.notifyPropertyChanged('heightType');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionRowFormat.prototype, \"isHeader\", {\n /**\n * Gets or Sets a value indicating whether the selected rows are header rows or not.\n * @default undefined\n */\n get: function () {\n return this.isHeaderIn;\n },\n set: function (value) {\n if (value === this.isHeaderIn) {\n return;\n }\n this.isHeaderIn = value;\n this.notifyPropertyChanged('isHeader');\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionRowFormat.prototype, \"allowBreakAcrossPages\", {\n /**\n * Gets or Sets a value indicating whether to allow break across pages for selected rows.\n * @default undefined\n */\n get: function () {\n return this.allowRowBreakAcrossPagesIn;\n },\n set: function (value) {\n if (value === this.allowRowBreakAcrossPagesIn) {\n return;\n }\n this.allowRowBreakAcrossPagesIn = value;\n this.notifyPropertyChanged('allowBreakAcrossPages');\n },\n enumerable: true,\n configurable: true\n });\n SelectionRowFormat.prototype.notifyPropertyChanged = function (propertyName) {\n var selection = this.selection;\n if (!isNullOrUndefined(selection) && (selection.isCleared || selection.owner.isReadOnlyMode\n || !selection.owner.isDocumentLoaded || selection.owner.isPastingContent) && !selection.isRetrieveFormatting) {\n return;\n }\n if (!isNullOrUndefined(selection) && !isNullOrUndefined(selection.start) && !selection.isRetrieveFormatting) {\n var value = this.getPropertyValue(propertyName);\n if (!isNullOrUndefined(value)) {\n selection.owner.editorModule.onApplyTableRowFormat(propertyName, value);\n }\n }\n };\n SelectionRowFormat.prototype.getPropertyValue = function (propertyName) {\n switch (propertyName) {\n case 'height':\n return this.height;\n case 'heightType':\n return this.heightType;\n case 'isHeader':\n return this.isHeader;\n case 'allowBreakAcrossPages':\n return this.allowBreakAcrossPages;\n default:\n return undefined;\n }\n };\n /**\n * Copies the format.\n * @param {WRowFormat} format\n * @returns void\n * @private\n */\n SelectionRowFormat.prototype.copyFormat = function (format) {\n this.height = format.height;\n this.heightType = format.heightType;\n this.allowBreakAcrossPages = format.allowBreakAcrossPages;\n this.isHeader = format.isHeader;\n };\n /**\n * Combines the format.\n * @param {WRowFormat} format\n * @private\n */\n SelectionRowFormat.prototype.combineFormat = function (format) {\n if (!isNullOrUndefined(this.height) && this.height !== format.height) {\n this.height = undefined;\n }\n if (!isNullOrUndefined(this.heightType) && this.heightType !== format.heightType) {\n this.heightType = undefined;\n }\n if (!isNullOrUndefined(this.allowBreakAcrossPages) && this.allowBreakAcrossPages !== format.allowBreakAcrossPages) {\n this.allowBreakAcrossPages = undefined;\n }\n if (!isNullOrUndefined(this.isHeader) && this.isHeader !== format.isHeader) {\n this.isHeader = undefined;\n }\n };\n /**\n * Clears the row format.\n * @returns void\n * @private\n */\n SelectionRowFormat.prototype.clearRowFormat = function () {\n this.height = undefined;\n this.heightType = undefined;\n this.allowBreakAcrossPages = undefined;\n this.isHeader = undefined;\n };\n /**\n * Clears the format.\n * @returns void\n * @private\n */\n SelectionRowFormat.prototype.clearFormat = function () {\n this.height = 0;\n this.heightType = undefined;\n this.allowBreakAcrossPages = undefined;\n this.isHeader = undefined;\n };\n /**\n * Destroys the managed resources.\n * @returns void\n * @private\n */\n SelectionRowFormat.prototype.destroy = function () {\n this.heightIn = undefined;\n this.heightTypeIn = undefined;\n this.allowRowBreakAcrossPagesIn = undefined;\n this.isHeaderIn = undefined;\n this.selection = undefined;\n };\n return SelectionRowFormat;\n}());\nexport { SelectionRowFormat };\n/**\n * Selection image format implementation\n */\nvar SelectionImageFormat = /** @class */ (function () {\n /**\n * @private\n */\n function SelectionImageFormat(selection) {\n this.selection = selection;\n }\n Object.defineProperty(SelectionImageFormat.prototype, \"width\", {\n /**\n * Gets the width of the image.\n */\n get: function () {\n if (this.image) {\n return this.image.width;\n }\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionImageFormat.prototype, \"height\", {\n /**\n * Gets the height of the image.\n */\n get: function () {\n if (this.image) {\n return this.image.height;\n }\n return 0;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Resizes the image based on given size.\n * @param width\n * @param height\n */\n SelectionImageFormat.prototype.resize = function (width, height) {\n this.updateImageFormat(width, height);\n };\n /**\n * Update image width and height\n * @private\n */\n SelectionImageFormat.prototype.updateImageFormat = function (width, height) {\n if (this.image) {\n if (this.selection.owner.editorModule) {\n this.selection.owner.editorModule.onImageFormat(this.image, width, height);\n }\n }\n };\n /**\n * @private\n */\n SelectionImageFormat.prototype.copyImageFormat = function (image) {\n this.image = image;\n };\n /**\n * @private\n */\n SelectionImageFormat.prototype.clearImageFormat = function () {\n this.image = undefined;\n };\n return SelectionImageFormat;\n}());\nexport { SelectionImageFormat };\n/* tslint:enable */ \n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { HelperMethods } from '../editor/editor-helper';\n/**\n * @private\n */\nvar HtmlExport = /** @class */ (function () {\n function HtmlExport() {\n /* tslint:disable:no-any */\n this.document = undefined;\n /* tslint:disable:no-any */\n /**\n * @private\n */\n this.fieldCheck = 0;\n /* tslint:enable:no-any */\n }\n /* tslint:disable:no-any */\n /**\n * @private\n */\n HtmlExport.prototype.writeHtml = function (document) {\n this.document = document;\n var html = '';\n for (var i = 0; i < document.sections.length; i++) {\n html = this.serializeSection(document.sections[i]);\n }\n return html;\n };\n /**\n * @private\n */\n HtmlExport.prototype.serializeSection = function (section) {\n var string = '';\n for (var i = 0; i < section.blocks.length; i++) {\n var block = section.blocks[i];\n if (block.hasOwnProperty('inlines')) {\n string += this.serializeParagraph(block);\n }\n else {\n string += this.serializeTable(block);\n }\n }\n return string;\n };\n // Serialize Paragraph \n /**\n * @private\n */\n HtmlExport.prototype.serializeParagraph = function (paragraph) {\n var blockStyle = '';\n var startString = undefined;\n var isList = false;\n var tagAttributes = [];\n tagAttributes.push('style=\"' + this.serializeParagraphStyle(paragraph, '', isList) + '\"');\n blockStyle += this.createAttributesTag('p', tagAttributes);\n if (paragraph.inlines.length === 0) {\n //Handled to preserve non breaking space for empty paragraphs similar to MS Word behavior.\n blockStyle += ' ';\n }\n else {\n blockStyle = this.serializeInlines(paragraph, blockStyle);\n }\n blockStyle += this.endTag('p');\n return blockStyle;\n };\n //SerializeInlines\n /**\n * @private\n */\n HtmlExport.prototype.serializeInlines = function (paragraph, blockStyle) {\n var inline = undefined;\n var i = 0;\n while (paragraph.inlines.length > i) {\n inline = paragraph.inlines[i];\n if (inline.hasOwnProperty('imageString')) {\n blockStyle += this.serializeImageContainer(inline);\n }\n else if (inline.hasOwnProperty('fieldType')) {\n if (inline.fieldType === 0) {\n this.fieldCheck = 1;\n var tagAttributes = [];\n tagAttributes.push('style=\"' + this.serializeInlineStyle(inline.characterFormat, '') + '\"');\n blockStyle += this.createAttributesTag('a', tagAttributes);\n }\n else if (inline.fieldType === 2) {\n this.fieldCheck = 2;\n }\n else {\n blockStyle += this.endTag('a');\n this.fieldCheck = 0;\n }\n }\n else {\n var text = isNullOrUndefined(inline.text) ? '' : inline.text;\n if (this.fieldCheck === 0) {\n blockStyle += this.serializeSpan(text, inline.characterFormat);\n }\n if (this.fieldCheck === 1) {\n var hyperLink = text.replace('\\\"', '');\n blockStyle += ' href= \\\"' + hyperLink.replace('HYPERLINK', '').trim();\n blockStyle += '\\\"';\n blockStyle += '>';\n }\n if (this.fieldCheck === 2) {\n blockStyle += text;\n }\n }\n i++;\n }\n return blockStyle;\n };\n // Serialize Span\n /**\n * @private\n */\n HtmlExport.prototype.serializeSpan = function (spanText, characterFormat) {\n var spanClass = '';\n if (spanText.indexOf('\\v') !== -1) {\n spanClass += ' ';\n return spanClass.toString();\n }\n var tagAttributes = [];\n this.serializeInlineStyle(characterFormat, '');\n tagAttributes.push('style=\"' + this.serializeInlineStyle(characterFormat, '') + '\"');\n spanClass += this.createAttributesTag('span', tagAttributes);\n var ignoreFirstSpace = false;\n // Todo: Need to handle it.\n // If the text starts with white-space, need to check whether it is a continuous space.\n // if (characterFormat.ownerBase instanceof WInline) {\n // let inline: WInline = (characterFormat.ownerBase as WInline);\n // tslint:disable:max-line-length \n // if (inline instanceof WSpan && !isNullOrUndefined(inline.text) && inline.text !== '' && (inline as WSpan).text[0] === ' ') {\n // Check previous inline until, it has valid rendered text.\n // do {\n // inline = WInline.getPreviousTextInline((inline as WSpan));\n // } while (inline instanceof WSpan && !isNullOrUndefined(inline.text));\n // } else {\n // inline = undefined;\n // }\n // If current white-space is a continuation of consecutive spaces, this will be set true.\n // ignoreFirstSpace = inline instanceof WSpan && !isNullOrUndefined(inline.text)\n // && (inline as WSpan).text[(inline as WSpan).text.length - 1] === ' ';\n // }\n var text = this.decodeHtmlNames(spanText.toString());\n spanClass += text;\n spanClass += this.endTag('span');\n return spanClass.toString();\n };\n //Serialize Image\n /**\n * @private\n */\n HtmlExport.prototype.serializeImageContainer = function (image) {\n var imageStyle = '';\n var tagAttributes = [];\n this.serializeInlineStyle(image.characterFormat, '');\n var imageSource = '';\n if (!isNullOrUndefined(image.imageString)) {\n imageSource = image.imageString;\n }\n var width = HelperMethods.convertPointToPixel(image.width);\n var height = HelperMethods.convertPointToPixel(image.height);\n tagAttributes.push('width=\"', width.toString() + '\"');\n tagAttributes.push('height=\"', height.toString() + '\"');\n tagAttributes.push('src=\"', imageSource + '\"');\n imageStyle += this.createAttributesTag('img', tagAttributes);\n imageStyle += (this.endTag('img'));\n return imageStyle.toString();\n };\n // Serialize Table Cell\n /**\n * @private\n */\n HtmlExport.prototype.serializeCell = function (cell) {\n var blockStyle = '';\n var tagAttributes = [];\n var cellHtml = '';\n tagAttributes = [];\n if (!isNullOrUndefined(cell.cellFormat)) {\n //if (cell.cellFormat.shading.backgroundColor !== Color.FromArgb(0, 0, 0, 0)) {\n tagAttributes.push('bgcolor=\"' + cell.cellFormat.shading.backgroundColor + '\"');\n // }\n if (cell.cellFormat.columnSpan > 1) {\n tagAttributes.push('colspan=\"' + cell.cellFormat.columnSpan.toString() + '\"');\n }\n if (cell.cellFormat.rowSpan > 1) {\n tagAttributes.push('rowspan=\"' + cell.cellFormat.rowSpan.toString() + '\"');\n }\n if (cell.cellFormat.cellWidth !== 0) {\n tagAttributes.push('width=\"' + cell.cellFormat.cellWidth.toString() + '\"');\n }\n if (cell.cellFormat.verticalAlignment !== 'Top') {\n tagAttributes.push('valign=\"' + cell.cellFormat.verticalAlignment.toString().toLowerCase() + '\"');\n }\n if (!isNullOrUndefined(cell.cellFormat.leftMargin) && cell.cellFormat.leftMargin !== 0) {\n cellHtml += ('padding-left:' + cell.cellFormat.leftMargin.toString() + 'pt;');\n }\n if (!isNullOrUndefined(cell.cellFormat.rightMargin) && cell.cellFormat.rightMargin !== 0) {\n cellHtml += ('padding-right:' + cell.cellFormat.rightMargin.toString() + 'pt;');\n }\n if (!isNullOrUndefined(cell.cellFormat.topMargin) && cell.cellFormat.topMargin !== 0) {\n cellHtml += ('padding-top:' + cell.cellFormat.topMargin.toString() + 'pt;');\n }\n if (!isNullOrUndefined(cell.cellFormat.bottomMargin) && cell.cellFormat.bottomMargin !== 0) {\n cellHtml += ('padding-bottom:' + cell.cellFormat.bottomMargin.toString() + 'pt;');\n }\n if (!isNullOrUndefined(cell.cellFormat.borders)) {\n cellHtml += this.serializeCellBordersStyle(cell.cellFormat.borders);\n }\n }\n if (cellHtml.length !== 0) {\n tagAttributes.push('style=\"' + cellHtml + '\"');\n }\n blockStyle += (this.createAttributesTag('td', tagAttributes));\n for (var k = 0; k < cell.blocks.length; k++) {\n var block = cell.blocks[k];\n if (block.hasOwnProperty('rows')) {\n blockStyle += this.serializeTable(block);\n }\n else {\n blockStyle += this.serializeParagraph(block);\n }\n }\n blockStyle += (this.endTag('td'));\n return blockStyle;\n };\n // Serialize Table\n /**\n * @private\n */\n HtmlExport.prototype.serializeTable = function (table) {\n var html = '';\n html += this.createTableStartTag(table);\n for (var j = 0; j < table.rows.length; j++) {\n html += this.serializeRow(table.rows[j]);\n }\n html += this.createTableEndTag();\n return html;\n };\n // Serialize Row\n /**\n * @private\n */\n HtmlExport.prototype.serializeRow = function (row) {\n var html = '';\n html += this.createRowStartTag(row);\n for (var k = 0; k < row.cells.length; k++) {\n html += this.serializeCell(row.cells[k]);\n }\n return html;\n };\n // Serialize Styles\n /**\n * @private\n */\n HtmlExport.prototype.serializeParagraphStyle = function (paragraph, className, isList) {\n var paragraphClass = '';\n paragraphClass += this.serializeCharacterFormat(paragraph.characterFormat);\n paragraphClass += this.serializeParagraphFormat(paragraph.paragraphFormat, isList);\n return paragraphClass;\n };\n /**\n * @private\n */\n HtmlExport.prototype.serializeInlineStyle = function (characterFormat, className) {\n return this.serializeCharacterFormat(characterFormat);\n };\n /**\n * @private\n */\n HtmlExport.prototype.serializeTableBorderStyle = function (borders) {\n var borderStyle = '';\n borderStyle += ('border-left-style:' + this.convertBorderLineStyle(borders.left.lineStyle));\n borderStyle += ';';\n borderStyle += ('border-left-width:' + borders.left.lineWidth.toString() + 'pt');\n borderStyle += ';';\n borderStyle += ('border-left-color:' + borders.left.color);\n borderStyle += ';';\n borderStyle += ('border-right-style:' + this.convertBorderLineStyle(borders.right.lineStyle));\n borderStyle += ';';\n borderStyle += ('border-right-width:' + borders.right.lineWidth.toString() + 'pt');\n borderStyle += ';';\n borderStyle += ('border-right-color:' + borders.right.color);\n borderStyle += ';';\n borderStyle += ('border-top-style:' + this.convertBorderLineStyle(borders.top.lineStyle));\n borderStyle += ';';\n borderStyle += ('border-top-width:' + borders.top.lineWidth.toString() + 'pt');\n borderStyle += ';';\n borderStyle += ('border-top-color:' + borders.top.color);\n borderStyle += ';';\n borderStyle += ('border-Bottom-style:' + this.convertBorderLineStyle(borders.bottom.lineStyle));\n borderStyle += ';';\n borderStyle += ('border-Bottom-width:' + borders.bottom.lineWidth.toString() + 'pt');\n borderStyle += ';';\n borderStyle += ('border-Bottom-color:' + borders.bottom.color);\n borderStyle += ';';\n return borderStyle;\n };\n /**\n * @private\n */\n HtmlExport.prototype.serializeCellBordersStyle = function (borders) {\n var borderStyle = '';\n borderStyle = 'border:solid 1px;';\n // Todo: handle\n // let border: WBorder = undefined;\n // //LeftBorder\n // border = WCell.getCellLeftBorder(WCell.getCellOf(borders));\n // if (!isNullOrUndefined(border) && border.lineStyle !== 'None') {\n // borderStyle += this.serializeBorderStyle(border, 'left');\n // } else if (!isNullOrUndefined(border) && border.hasNoneStyle) {\n // borderStyle += ('border-left-style:none;');\n // }\n // //RightBorder\n // border = WCell.getCellRightBorder(WCell.getCellOf(borders));\n // if (!isNullOrUndefined(border) && border.lineStyle !== 'None') {\n // borderStyle += this.serializeBorderStyle(border, 'right');\n // } else if (!isNullOrUndefined(border) && border.hasNoneStyle) {\n // borderStyle += ('border-right-style:none');\n // }\n // //TopBorder\n // border = WCell.getCellTopBorder(WCell.getCellOf(borders));\n // if (!isNullOrUndefined(border) && border.lineStyle !== 'None') {\n // borderStyle += this.serializeBorderStyle(border, 'top');\n // } else if (!isNullOrUndefined(border) && border.hasNoneStyle) {\n // borderStyle += ('border-top-style:none');\n // }\n // //BottomBorder\n // border = WCell.getCellBottomBorder(WCell.getCellOf(borders));\n // if (!isNullOrUndefined(border) && border.lineStyle !== 'None') {\n // borderStyle += this.serializeBorderStyle(border, 'bottom');\n // } else if (!isNullOrUndefined(border) && border.hasNoneStyle) {\n // borderStyle += ('border-bottom-style:none');\n // }\n return borderStyle;\n };\n /**\n * @private\n */\n HtmlExport.prototype.serializeBorderStyle = function (border, borderPosition) {\n var borderStyle = '';\n borderStyle += ('border-' + borderPosition + '-style:' + this.convertBorderLineStyle(border.lineStyle));\n borderStyle += ';';\n if (border.lineWidth > 0) {\n borderStyle += ('border-' + borderPosition + '-width:' + border.lineWidth.toString() + 'pt;');\n }\n //if (border.color !== Color.FromArgb(0, 0, 0, 0))\n borderStyle += ('border-' + borderPosition + '-color:' + border.color + ';');\n return borderStyle;\n };\n /**\n * @private\n */\n HtmlExport.prototype.convertBorderLineStyle = function (lineStyle) {\n switch (lineStyle) {\n case 'None':\n return 'none';\n case 'Single':\n return 'solid';\n case 'Dot':\n return 'dotted';\n case 'DashSmallGap':\n case 'DashLargeGap':\n case 'DashDot':\n case 'DashDotDot':\n return 'dashed';\n case 'Double':\n case 'Triple':\n case 'ThinThickSmallGap':\n case 'ThickThinSmallGap':\n case 'ThinThickThinSmallGap':\n case 'ThinThickMediumGap':\n case 'ThickThinMediumGap':\n case 'ThinThickThinMediumGap':\n case 'ThinThickLargeGap':\n case 'ThickThinLargeGap':\n case 'ThinThickThinLargeGap':\n return 'double';\n case 'SingleWavy':\n return 'solid';\n case 'DoubleWavy':\n return 'double';\n case 'DashDotStroked':\n return 'solid';\n case 'Emboss3D':\n return 'ridge';\n case 'Engrave3D':\n return 'groove';\n case 'Outset':\n return 'outset';\n case 'Inset':\n return 'inset';\n default:\n return 'solid';\n }\n };\n // Serialize Format\n /**\n * @private\n */\n HtmlExport.prototype.serializeCharacterFormat = function (characterFormat) {\n if (!isNullOrUndefined(characterFormat.inlineFormat)) {\n return this.serializeCharacterFormat(characterFormat.inlineFormat);\n }\n var propertyValue;\n var charStyle = '';\n if (characterFormat.bold) {\n charStyle += 'font-weight';\n charStyle += ':';\n charStyle += 'bold';\n charStyle += ';';\n }\n charStyle += 'font-style';\n charStyle += ':';\n if (characterFormat.italic) {\n charStyle += 'italic';\n }\n else {\n charStyle += 'normal';\n }\n charStyle += ';';\n // Double strike through will become Single strike through while saving HTML using MS Word.\n if (characterFormat.strikethrough === 'SingleStrike' || characterFormat.strikethrough === 'DoubleStrike') {\n charStyle += 'text-decoration';\n charStyle += ':';\n charStyle += 'line-through';\n charStyle += ';';\n }\n //Text Baseline Alignment\n // tslint:disable-next-line:max-line-length\n if (characterFormat.baselineAlignment === 'Superscript' || characterFormat.baselineAlignment === 'Subscript') {\n charStyle += 'vertical-align';\n charStyle += ':';\n charStyle += characterFormat.baselineAlignment === 'Superscript' ? 'super' : 'sub';\n charStyle += ';';\n }\n //Text Foreground and Background Color \n if (!isNullOrUndefined(characterFormat.highlightColor)) {\n charStyle += 'background-color';\n charStyle += ':';\n charStyle += characterFormat.highlightColor.toString();\n charStyle += ';';\n }\n //Font Color\n propertyValue = characterFormat.fontColor;\n if (!isNullOrUndefined(propertyValue)) {\n charStyle += 'color';\n charStyle += ':';\n charStyle += propertyValue;\n charStyle += ';';\n }\n if (!isNullOrUndefined(characterFormat.underline) && characterFormat.underline !== 'None') {\n charStyle += 'text-decoration';\n charStyle += ':';\n charStyle += 'underline';\n charStyle += ';';\n }\n propertyValue = characterFormat.fontSize;\n if (!isNullOrUndefined(propertyValue)) {\n charStyle += 'font-size';\n charStyle += ':';\n charStyle += propertyValue.toString();\n charStyle += 'pt';\n charStyle += ';';\n }\n propertyValue = characterFormat.fontFamily;\n if (!isNullOrUndefined(propertyValue)) {\n charStyle += 'font-family';\n charStyle += ':';\n charStyle += propertyValue.toString();\n charStyle += ';';\n }\n return charStyle.toString();\n };\n /**\n * @private\n */\n HtmlExport.prototype.serializeParagraphFormat = function (paragraphFormat, isList) {\n if (!isNullOrUndefined(paragraphFormat.inlineFormat)) {\n return this.serializeParagraphFormat(paragraphFormat.inlineFormat, isList);\n }\n var propertyValue;\n var paraStyle = '';\n propertyValue = paragraphFormat.textAlignment;\n if (!isNullOrUndefined(propertyValue)) {\n paraStyle += 'text-align:' + propertyValue.toLowerCase() + ';';\n }\n propertyValue = paragraphFormat.beforeSpacing;\n if (!isNullOrUndefined(propertyValue)) {\n paraStyle += 'margin-top:' + propertyValue.toString() + 'pt; ';\n }\n propertyValue = paragraphFormat.rightIndent;\n if (!isNullOrUndefined(propertyValue)) {\n paraStyle += 'margin-right:' + propertyValue.toString() + 'pt; ';\n }\n propertyValue = paragraphFormat.afterSpacing;\n if (!isNullOrUndefined(propertyValue)) {\n paraStyle += 'margin-bottom:' + propertyValue.toString() + 'pt; ';\n }\n propertyValue = paragraphFormat.leftIndent;\n if (isList) {\n if (isNullOrUndefined(propertyValue)) {\n propertyValue = -48;\n }\n else {\n propertyValue -= 48;\n }\n }\n if (!isNullOrUndefined(propertyValue)) {\n paraStyle += 'margin-left:' + propertyValue.toString() + 'pt; ';\n }\n propertyValue = paragraphFormat.firstLineIndent;\n if (isList) {\n if (isNullOrUndefined(propertyValue)) {\n propertyValue = 24;\n }\n else {\n propertyValue += 24;\n }\n }\n if (!isNullOrUndefined(propertyValue) && propertyValue !== 0) {\n paraStyle += 'text-indent:' + propertyValue.toString() + 'pt;';\n }\n propertyValue = paragraphFormat.lineSpacing;\n if (!isNullOrUndefined(propertyValue)) {\n if (paragraphFormat.lineSpacingType === 'Multiple') {\n propertyValue = (propertyValue * 100).toString() + '%;';\n }\n else {\n propertyValue = propertyValue.toString() + 'pt;';\n }\n paraStyle += 'line-height:' + propertyValue;\n }\n return paraStyle.toString();\n };\n /**\n * @private\n */\n HtmlExport.prototype.createAttributesTag = function (tagValue, localProperties) {\n var sb = '';\n sb += '<';\n sb += tagValue;\n for (var i = 0; i < localProperties.length; i++) {\n sb += ' ';\n sb += localProperties[i];\n }\n if (tagValue !== 'a') {\n sb += '>';\n }\n return sb;\n };\n /**\n * @private\n */\n HtmlExport.prototype.createTag = function (tagValue) {\n var s = '';\n s += '<';\n s += tagValue;\n s += '>';\n return s;\n };\n /**\n * @private\n */\n HtmlExport.prototype.endTag = function (tagValue) {\n var sb = '';\n sb += '<';\n sb += '/';\n sb += tagValue;\n sb += '>';\n return sb;\n };\n /**\n * @private\n */\n HtmlExport.prototype.createTableStartTag = function (table) {\n var blockStyle = '';\n var tableStyle = '';\n var tagAttributes = [];\n tagAttributes.push('border=\"' + '1\"');\n if (!isNullOrUndefined(table.tableFormat)) {\n //if (table.tableFormat.shading.backgroundColor !== Color.FromArgb(0, 0, 0, 0)) {\n tagAttributes.push('bgcolor=\"' + table.tableFormat.shading.backgroundColor + '\"');\n //}\n if (table.tableFormat.leftIndent !== 0) {\n tagAttributes.push('left-indent=\"' + table.tableFormat.leftIndent.toString() + 'pt;');\n }\n if (table.tableFormat.cellSpacing > 0) {\n tagAttributes.push('cellspacing=\"' + (((table.tableFormat.cellSpacing * 72) / 96) * 2).toString() + '\"');\n }\n else {\n tableStyle += ('border-collapse:collapse;');\n }\n tagAttributes.push('cellpadding=\"' + '0\"');\n if (!isNullOrUndefined(table.tableFormat.borders)) {\n tableStyle += this.serializeTableBorderStyle(table.tableFormat.borders);\n }\n }\n if (tableStyle.length !== 0) {\n tagAttributes.push('style=\"', tableStyle.toString() + '\"');\n }\n return blockStyle += (this.createAttributesTag('table', tagAttributes));\n };\n /**\n * @private\n */\n HtmlExport.prototype.createTableEndTag = function () {\n var blockStyle = '';\n blockStyle += (this.endTag('table'));\n return blockStyle;\n };\n /**\n * @private\n */\n HtmlExport.prototype.createRowStartTag = function (row) {\n var blockStyle = '';\n var tagAttributes = [];\n if (row.rowFormat.isHeader) {\n blockStyle += (this.createTag('thead'));\n }\n if (row.rowFormat.height > 0) {\n tagAttributes.push('height=\"' + row.rowFormat.height + '\"');\n }\n return blockStyle + this.createAttributesTag('tr', tagAttributes);\n };\n /**\n * @private\n */\n HtmlExport.prototype.createRowEndTag = function (row) {\n var blockStyle = '';\n blockStyle += (this.endTag('tr'));\n if (row.rowFormat.isHeader) {\n blockStyle += (this.endTag('thead'));\n }\n return blockStyle;\n };\n /**\n * @private\n */\n HtmlExport.prototype.decodeHtmlNames = function (text) {\n if (text === '\\t') {\n return ' ';\n }\n var splittedText = text.split(' ');\n var htmlText = '';\n if (splittedText.length > 0) {\n htmlText = splittedText[0];\n for (var i = 0; i < splittedText.length - 1; i++) {\n htmlText += ' ' + splittedText[i + 1];\n }\n }\n return htmlText;\n };\n return HtmlExport;\n}());\nexport { HtmlExport };\n","import { Widget, TableRowWidget, TableWidget, LineWidget, ElementBox, TextElementBox, ListTextElementBox, ImageElementBox, ParagraphWidget, TableCellWidget, FieldElementBox, BlockContainer, BookmarkElementBox } from '../index';\nimport { HelperMethods } from '../index';\nimport { Point } from '../index';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * @private\n */\nvar TextPosition = /** @class */ (function () {\n function TextPosition(owner) {\n /**\n * @private\n */\n this.location = new Point(0, 0);\n /**\n * @private\n */\n this.isUpdateLocation = true;\n this.owner = owner;\n this.viewer = this.owner.viewer;\n }\n Object.defineProperty(TextPosition.prototype, \"paragraph\", {\n /**\n * @private\n */\n get: function () {\n return this.currentWidget.paragraph;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextPosition.prototype, \"isAtParagraphStart\", {\n /**\n * @private\n */\n get: function () {\n return this.offset === this.owner.selection.getStartOffset(this.paragraph);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextPosition.prototype, \"isAtParagraphEnd\", {\n /**\n * @private\n */\n get: function () {\n return this.owner.selection.isParagraphLastLine(this.currentWidget)\n && this.offset === this.owner.selection.getLineLength(this.currentWidget);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextPosition.prototype, \"selection\", {\n /**\n * @private\n */\n get: function () {\n return this.owner.selection;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextPosition.prototype, \"hierarchicalPosition\", {\n /**\n * Gets the hierarchical position of logical text position in the document\n * @returns {string}\n */\n get: function () {\n return this.getHierarchicalIndexInternal();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Return clone of current text position\n * @private\n */\n TextPosition.prototype.clone = function () {\n var textPosition = new TextPosition(this.owner);\n textPosition.currentWidget = this.currentWidget;\n textPosition.offset = this.offset;\n textPosition.location = this.location;\n return textPosition;\n };\n /**\n * Set text position for paragraph and inline\n * @private\n */\n TextPosition.prototype.setPositionForSelection = function (line, element, index, physicalLocation) {\n //Set the start end position\n var isParagraphEnd = false;\n if (isNullOrUndefined(element)) {\n this.currentWidget = line;\n }\n else {\n this.currentWidget = element.line;\n if (element.nextNode instanceof FieldElementBox && index > element.length) {\n isParagraphEnd = this.selection.isLastRenderedInline(element, element.length);\n }\n }\n this.location = physicalLocation;\n if (isParagraphEnd) {\n this.offset = this.selection.getParagraphLength(this.currentWidget.paragraph) + 1;\n }\n else {\n this.offset = this.currentWidget.getOffset(element, index);\n }\n };\n /**\n * Set text position\n * @private\n */\n TextPosition.prototype.setPositionFromLine = function (line, offset, location) {\n this.currentWidget = line;\n this.offset = offset;\n if (location instanceof Point) {\n this.location.copy(location);\n }\n };\n /**\n * Set text position\n * @private\n */\n TextPosition.prototype.setPosition = function (line, positionAtStart) {\n this.currentWidget = line;\n this.offset = positionAtStart ? this.selection.getStartOffset(line.paragraph)\n : this.selection.getParagraphLength(line.paragraph) + 1;\n this.updatePhysicalPosition(true);\n };\n /**\n * Set position for text position\n * @private\n */\n TextPosition.prototype.setPositionInternal = function (textPosition) {\n this.currentWidget = textPosition.currentWidget;\n this.offset = textPosition.offset;\n this.location = textPosition.location;\n };\n /**\n * Set position for current index\n * @private\n */\n TextPosition.prototype.setPositionForCurrentIndex = function (hierarchicalIndex) {\n var index = { index: hierarchicalIndex };\n var paragraph = this.getParagraphWidget(index); //ref hierarchicalIndex\n this.offset = parseFloat(index.index);\n this.setPositionParagraph(paragraph, this.offset);\n };\n /**\n * Get Page\n */\n TextPosition.prototype.getPage = function (position) {\n var page;\n var index = position.index.indexOf(';');\n var newValue = '0';\n if (index >= 0) {\n newValue = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n }\n index = parseInt(newValue, 10);\n page = this.viewer.pages[index];\n return page;\n };\n /**\n * @private\n */\n TextPosition.prototype.getParagraphWidget = function (position) {\n if (isNullOrUndefined(position.index)) {\n return undefined;\n }\n var page = this.getPage(position);\n var child = this.getLineWidget(undefined, position, page);\n return child;\n };\n /**\n * @private\n */\n TextPosition.prototype.getLineWidget = function (widget, position, page) {\n if (isNullOrUndefined(position.index)) {\n return undefined;\n }\n var index = position.index.indexOf(';');\n var value = '0';\n if (index >= 0) {\n value = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n }\n if (value === 'H' || value === 'F') {\n if (value === 'H') {\n widget = page.headerWidget;\n }\n else {\n widget = page.footerWidget;\n }\n }\n else if (!isNullOrUndefined(page)) {\n widget = page.bodyWidgets[0];\n }\n index = parseInt(value, 10);\n if (widget instanceof BlockContainer) {\n index = position.index.indexOf(';');\n value = '0';\n value = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n index = parseInt(value, 10);\n }\n if (widget instanceof TableRowWidget && index >= widget.childWidgets.length) {\n position.index = '0;0';\n index = widget.childWidgets.length - 1;\n }\n if (index >= 0 && index < widget.childWidgets.length) {\n var child = widget.childWidgets[index];\n if (child instanceof LineWidget) {\n if (position.index.indexOf(';') > 0) {\n position.index = '0';\n }\n return child;\n }\n if (child instanceof Widget) {\n if (position.index.indexOf(';') > 0) {\n return this.getLineWidget(child, position);\n }\n else {\n //If table is shifted to previous text position then return the first paragraph within table.\n if (child instanceof TableWidget) {\n return this.getLineWidget(this.selection.getFirstParagraphInFirstCell(child), position);\n }\n else if (child instanceof TableRowWidget && position.index.indexOf(';') === -1) {\n return this.selection.getFirstParagraphInFirstCell(child.ownerTable).childWidgets[0];\n }\n return undefined;\n }\n }\n }\n else if (widget.nextRenderedWidget instanceof Widget) {\n position.index = '0';\n if (widget.nextRenderedWidget instanceof TableWidget) {\n return this.selection.getFirstParagraphInFirstCell(widget.nextRenderedWidget).firstChild;\n }\n return this.getLineWidget(widget.nextRenderedWidget, position);\n }\n return undefined;\n };\n /**\n * Update physical location of paragraph\n * @private\n */\n TextPosition.prototype.updatePhysicalPosition = function (moveNextLine) {\n if (this.currentWidget && this.owner.isLayoutEnabled && this.isUpdateLocation) {\n this.location = this.selection.getPhysicalPositionInternal(this.currentWidget, this.offset, moveNextLine);\n }\n };\n /**\n * Return true if text position are in same paragraph and offset\n * @private\n */\n TextPosition.prototype.isAtSamePosition = function (textPosition) {\n return this.currentWidget === textPosition.currentWidget\n && this.offset === textPosition.offset;\n };\n /**\n * Return true if text position is in same paragraph\n * @private\n */\n TextPosition.prototype.isInSameParagraph = function (textPosition) {\n if (isNullOrUndefined(textPosition)) {\n throw new Error('textPosition is undefined.');\n }\n return this.paragraph === textPosition.paragraph;\n };\n /**\n * Return true is current text position exist before given text position\n * @private\n */\n TextPosition.prototype.isExistBefore = function (textPosition) {\n if (isNullOrUndefined(textPosition)) {\n throw new Error('textPosition is undefined.');\n }\n if (this.currentWidget === textPosition.currentWidget) {\n return this.offset < textPosition.offset;\n }\n var currentParagraph = this.currentWidget.paragraph;\n var paragraph = textPosition.currentWidget.paragraph;\n if (currentParagraph === paragraph) {\n return currentParagraph.childWidgets.indexOf(this.currentWidget) < paragraph.childWidgets.indexOf(textPosition.currentWidget);\n }\n if (currentParagraph.containerWidget === paragraph.containerWidget) {\n if (currentParagraph.isInsideTable) {\n return currentParagraph.associatedCell.childWidgets.indexOf(currentParagraph) <\n paragraph.associatedCell.childWidgets.indexOf(paragraph);\n //handle after header footer implementation\n // } else if ((this.currentParagraph).owner instanceof WHeaderFooter) {\n // return ((this.currentParagraph).owner as WHeaderFooter).blocks.indexOf((this.currentParagraph)) <\n // ((textPosition.currentParagraph).owner as WHeaderFooter).blocks.indexOf((textPosition.currentParagraph));\n }\n else {\n return (currentParagraph.containerWidget.childWidgets.indexOf(currentParagraph)) <\n (paragraph.containerWidget.childWidgets.indexOf(paragraph));\n }\n }\n return this.owner.selection.isExistBefore(currentParagraph, paragraph);\n };\n /**\n * Return true is current text position exist after given text position\n * @private\n */\n TextPosition.prototype.isExistAfter = function (textPosition) {\n if (isNullOrUndefined(textPosition)) {\n throw new Error('textPosition is undefined.');\n }\n if (this.currentWidget === textPosition.currentWidget) {\n return this.offset > textPosition.offset;\n }\n if (this.currentWidget.paragraph === textPosition.currentWidget.paragraph) {\n return this.currentWidget.paragraph.childWidgets.indexOf(this.currentWidget) >\n textPosition.currentWidget.paragraph.childWidgets.indexOf(textPosition.currentWidget);\n }\n var startParagraph = this.currentWidget.paragraph;\n var endParagraph = textPosition.currentWidget.paragraph;\n if (startParagraph.containerWidget.index === endParagraph.containerWidget.index) {\n if (startParagraph.isInsideTable) {\n return startParagraph.associatedCell.childWidgets.indexOf(startParagraph) >\n endParagraph.associatedCell.childWidgets.indexOf(endParagraph);\n // } else if ((this.currentParagraph).owner instanceof WHeaderFooter) {\n // return ((this.currentParagraph).owner as WHeaderFooter).blocks.indexOf((this.currentParagraph)) >\n // ((textPosition.currentParagraph).owner as WHeaderFooter).blocks.indexOf((textPosition.currentParagraph));\n }\n else {\n return (startParagraph.containerWidget.childWidgets.indexOf(startParagraph) >\n (endParagraph.containerWidget.childWidgets.indexOf(endParagraph)));\n }\n }\n return this.owner.selection.isExistAfter(startParagraph, endParagraph);\n };\n /**\n * Return hierarchical index of current text position\n * @private\n */\n TextPosition.prototype.getHierarchicalIndexInternal = function () {\n return this.getHierarchicalIndex(this.currentWidget, this.offset.toString());\n };\n /**\n * @private\n */\n TextPosition.prototype.getHierarchicalIndex = function (line, hierarchicalIndex) {\n var node = line;\n if (node) {\n return node.getHierarchicalIndex(hierarchicalIndex);\n }\n return hierarchicalIndex;\n };\n /**\n * @private\n */\n TextPosition.prototype.setPositionParagraph = function (line, offsetInLine) {\n this.currentWidget = line;\n this.offset = offsetInLine;\n this.updatePhysicalPosition(true);\n };\n /**\n * @private\n */\n TextPosition.prototype.setPositionForLineWidget = function (lineWidget, offset) {\n var lineLength = this.selection.getLineLength(lineWidget);\n var lineIndex = lineWidget.paragraph.childWidgets.indexOf(lineWidget);\n if (offset > lineLength + 1) {\n var nextLineWidget = void 0;\n if (lineIndex >= lineWidget.paragraph.childWidgets.length - 1) {\n var nextBlock = this.selection.getNextRenderedBlock(lineWidget.paragraph);\n if (nextBlock && nextBlock.index === lineWidget.paragraph.index) {\n nextLineWidget = nextBlock.firstChild;\n }\n }\n else {\n nextLineWidget = lineWidget.paragraph.childWidgets[lineIndex + 1];\n }\n this.setPositionForLineWidget(nextLineWidget, offset - lineLength);\n return;\n }\n else if (offset < 0) {\n var prevLine = lineWidget.paragraph.childWidgets[lineIndex - 1];\n var curretOffSet = this.selection.getLineLength(prevLine) + offset;\n this.setPositionForLineWidget(prevLine, curretOffSet);\n return;\n }\n else {\n this.currentWidget = lineWidget;\n this.offset = offset;\n }\n this.updatePhysicalPosition(true);\n };\n /**\n * move to next text position\n * @private\n */\n TextPosition.prototype.moveNextPosition = function (isNavigate) {\n if (isNullOrUndefined(isNavigate)) {\n isNavigate = true;\n }\n var inline = this.selection.getNextStartInline(this.currentWidget, this.offset);\n if (inline instanceof FieldElementBox && inline.fieldType === 0 && !isNullOrUndefined(inline.fieldEnd)) {\n if (isNavigate) {\n this.moveNextPositionInternal(inline);\n this.moveNextPosition();\n return;\n }\n else {\n var line = inline.fieldEnd.line;\n var fieldEnd = inline.fieldEnd;\n var fieldEndOffset = line.getOffset(fieldEnd, 1);\n var fieldEndIndex = this.getHierarchicalIndex(line, fieldEndOffset.toString());\n if (TextPosition.isForwardSelection(this.selection.end.getHierarchicalIndexInternal(), fieldEndIndex)) {\n //If field end is after selection end, extend selection end to field end.\n this.selection.end.moveToInline(inline.fieldEnd, 1);\n return;\n }\n this.moveToInline(inline.fieldEnd, 1);\n }\n }\n var nextOffset = this.selection.getNextValidOffset(this.currentWidget, this.offset);\n var lineIndex = this.paragraph.childWidgets.indexOf(this.currentWidget);\n var index = 0;\n if (nextOffset > this.offset) {\n this.offset = nextOffset;\n var info = this.currentWidget.getInline(this.offset, index);\n inline = info.element;\n index = info.index;\n if (!isNullOrUndefined(inline) && index === inline.length && inline.nextNode instanceof FieldElementBox) {\n var nextValidInline = this.selection.getNextValidElement(inline.nextNode);\n //Moves to field end mark.\n if (nextValidInline instanceof FieldElementBox && nextValidInline.fieldType === 1) {\n inline = nextValidInline;\n this.offset = this.currentWidget.getOffset(inline, 1);\n }\n }\n }\n else if (lineIndex + 1 < this.paragraph.childWidgets.length) {\n var nextLineWidget = this.paragraph.childWidgets[lineIndex + 1];\n if (nextLineWidget) {\n this.currentWidget = nextLineWidget;\n this.offset = this.selection.getStartLineOffset(this.currentWidget);\n }\n var inlineObj = this.currentWidget.getInline(this.offset, index);\n inline = inlineObj.element;\n index = inlineObj.index;\n if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n this.offset++;\n }\n }\n else {\n this.updateOffsetToNextParagraph(index, false);\n }\n //Gets physical position in current page.\n this.updatePhysicalPosition(true);\n };\n /**\n * Move text position to previous paragraph inside table\n * @private\n */\n TextPosition.prototype.moveToPreviousParagraphInTable = function (selection) {\n var previousParagraph;\n var currentPara = this.currentWidget.paragraph;\n if (currentPara.isInsideTable) {\n previousParagraph = selection.getPreviousSelectionCell(currentPara.associatedCell);\n }\n else {\n previousParagraph = selection.getPreviousParagraphBlock(currentPara);\n }\n if (isNullOrUndefined(previousParagraph)) {\n return;\n }\n this.currentWidget = previousParagraph.childWidgets[previousParagraph.childWidgets.length - 1];\n this.offset = this.currentWidget.getEndOffset() + 1;\n };\n TextPosition.prototype.updateOffsetToNextParagraph = function (indexInInline, isHighlight) {\n //Moves to owner and get next paragraph.\n var inline;\n var positionAtStart = false;\n var nextParagraph = undefined;\n var lineIndex = this.paragraph.childWidgets.indexOf(this.currentWidget);\n if (!isHighlight) {\n nextParagraph = this.selection.getNextParagraphBlock(this.paragraph);\n }\n else if (lineIndex + 1 < this.paragraph.childWidgets.length) {\n var nextLineWidget = this.paragraph.childWidgets[lineIndex + 1];\n if (nextLineWidget) {\n this.currentWidget = nextLineWidget;\n this.offset = 0;\n }\n }\n else {\n nextParagraph = this.selection.getNextSelectionBlock(this.paragraph);\n if (!isNullOrUndefined(nextParagraph)) {\n if (nextParagraph.containerWidget instanceof TableCellWidget) {\n if (this.selection.start.paragraph.isInsideTable) {\n // tslint:disable-next-line:max-line-length\n var containerCell = this.selection.getContainerCellOf(this.selection.start.paragraph.associatedCell, nextParagraph.associatedCell);\n positionAtStart = !containerCell.ownerTable.contains(nextParagraph.associatedCell);\n }\n else {\n positionAtStart = true;\n }\n }\n }\n }\n if (!isNullOrUndefined(nextParagraph) && nextParagraph.childWidgets.length > 0) {\n if (!positionAtStart) {\n this.currentWidget = nextParagraph.firstChild;\n this.offset = isHighlight ? 1 : this.selection.getStartLineOffset(this.currentWidget);\n }\n else {\n this.currentWidget = nextParagraph.childWidgets[nextParagraph.childWidgets.length - 1];\n this.offset = this.selection.getLineLength(this.currentWidget) + 1;\n }\n }\n var inlineObj = this.currentWidget.getInline(this.offset, indexInInline);\n inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n this.offset++;\n }\n };\n TextPosition.prototype.updateOffsetToPrevPosition = function (index, isHighlight) {\n var inlineInfo;\n var inline;\n var lineIndex = this.paragraph.childWidgets.indexOf(this.currentWidget);\n var prevOffset = this.selection.getPreviousValidOffset(this.currentWidget.paragraph, this.offset);\n if (this.offset > prevOffset) {\n this.offset = prevOffset;\n }\n else if (lineIndex > 0) {\n var prevLineWidget = this.paragraph.childWidgets[lineIndex - 1];\n if (prevLineWidget) {\n this.currentWidget = prevLineWidget;\n this.offset = this.currentWidget.getEndOffset();\n }\n }\n else {\n //Moves to owner and get previous paragraph.\n var previousParagraph = undefined;\n var positionAtStart = false;\n if (!isHighlight) {\n previousParagraph = this.selection.getPreviousParagraphBlock(this.paragraph);\n }\n else {\n previousParagraph = this.selection.getPreviousSelectionBlock(this.paragraph);\n if (!isNullOrUndefined(previousParagraph)) {\n if (previousParagraph.containerWidget instanceof TableCellWidget) {\n if (this.selection.start.paragraph.isInsideTable) {\n // tslint:disable-next-line:max-line-length\n var containerCell = this.selection.getContainerCellOf(this.selection.start.paragraph.associatedCell, previousParagraph.associatedCell);\n positionAtStart = !containerCell.ownerTable.contains(previousParagraph.associatedCell);\n }\n else {\n positionAtStart = true;\n }\n }\n }\n }\n if (!isNullOrUndefined(previousParagraph)) {\n if (!positionAtStart) {\n this.currentWidget = previousParagraph.childWidgets[previousParagraph.childWidgets.length - 1];\n this.offset = this.currentWidget.getEndOffset();\n }\n else {\n this.currentWidget = previousParagraph.firstChild;\n this.offset = this.selection.getStartLineOffset(this.currentWidget);\n }\n }\n }\n index = 0;\n inlineInfo = this.currentWidget.getInline(this.offset, index);\n inline = inlineInfo.element;\n index = inlineInfo.index;\n if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n this.offset++;\n }\n if (inline instanceof FieldElementBox) {\n //Checks if field character is part of rendered field, otherwise moves to previous rendered content.\n var previousInline = this.selection.getPreviousValidElement(inline);\n if (!isNullOrUndefined(previousInline)) {\n inline = previousInline;\n this.currentWidget = inline.line;\n this.offset = this.currentWidget.getOffset(inline, inline.length);\n if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n this.offset--;\n }\n }\n }\n //Gets physical position in current page.\n this.updatePhysicalPosition(true);\n };\n /**\n * Moves the text position to start of the next paragraph.\n */\n TextPosition.prototype.moveToNextParagraphStartInternal = function () {\n var paragraph = this.currentWidget.paragraph;\n if (!isNullOrUndefined(this.selection.getNextParagraphBlock(paragraph))) {\n // tslint:disable-next-line:max-line-length\n this.currentWidget = this.selection.getNextParagraphBlock(paragraph).firstChild;\n this.offset = this.selection.getStartOffset(paragraph);\n this.updatePhysicalPosition(true);\n }\n };\n /**\n * Move to previous position\n * @private\n */\n TextPosition.prototype.movePreviousPosition = function () {\n var index = 0;\n var inlineInfo = this.currentWidget.getInline(this.offset, index);\n var inline = inlineInfo.element;\n index = inlineInfo.index;\n var lineIndex = this.paragraph.childWidgets.indexOf(this.currentWidget);\n if (inline instanceof FieldElementBox && inline.fieldType === 1 && !isNullOrUndefined(inline.fieldBegin)) {\n this.movePreviousPositionInternal(inline);\n }\n this.updateOffsetToPrevPosition(index, false);\n };\n /**\n * Move to next position\n * @private\n */\n TextPosition.prototype.moveNextPositionInternal = function (fieldBegin) {\n var inline;\n if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n inline = fieldBegin.fieldEnd;\n }\n else {\n inline = fieldBegin.fieldSeparator;\n this.currentWidget = inline.line;\n // tslint:disable-next-line:max-line-length\n if (this.currentWidget === fieldBegin.fieldEnd.line && !this.selection.hasValidInline(this.paragraph, inline, fieldBegin.fieldEnd)) {\n inline = fieldBegin.fieldEnd;\n }\n }\n this.currentWidget = inline.line;\n this.offset = this.currentWidget.getOffset(inline, 1);\n };\n /**\n * Move text position backward\n * @private\n */\n TextPosition.prototype.moveBackward = function () {\n var indexInInline = 0;\n var inlineObj = this.currentWidget.getInline(this.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!this.owner.selection.isEmpty && !isNullOrUndefined(inline)) {\n var nextInline = this.selection.getNextRenderedElementBox(inline, indexInInline);\n if (nextInline instanceof FieldElementBox && nextInline.fieldType === 0) {\n var hierarchicalIndex = this.owner.selection.start.getHierarchicalIndexInternal();\n // tslint:disable-next-line:max-line-length\n var fieldEndOffset = nextInline.fieldEnd.line.getOffset(nextInline.fieldEnd, 1);\n // tslint:disable-next-line:max-line-length\n var fieldEndIndex = this.getHierarchicalIndex(nextInline.fieldEnd.line, fieldEndOffset.toString());\n if (!TextPosition.isForwardSelection(fieldEndIndex, hierarchicalIndex)) {\n //If field end is after selection start, move selection start to field end.\n // tslint:disable-next-line:max-line-length\n this.owner.selection.start.setPositionParagraph(nextInline.fieldEnd.line, fieldEndOffset);\n return;\n }\n }\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 1 && !isNullOrUndefined(inline.fieldBegin)) {\n var hierarchicalIndex = this.owner.selection.start.getHierarchicalIndexInternal();\n var fieldEndOffset = inline.line.getOffset(inline, 1);\n var fieldEndIndex = this.getHierarchicalIndex(inline.line, fieldEndOffset.toString());\n if (!TextPosition.isForwardSelection(hierarchicalIndex, fieldEndIndex)) {\n //If field end is after selection start, extend selection end to field begin.\n // tslint:disable-next-line:max-line-length\n var fieldBeginOffset = inline.fieldBegin.line.getOffset(inline.fieldBegin, 0);\n this.currentWidget = inline.fieldBegin.line;\n this.offset = fieldBeginOffset;\n //Updates physical position in current page.\n this.updatePhysicalPosition(true);\n return;\n }\n this.movePreviousPositionInternal(inline);\n }\n this.updateOffsetToPrevPosition(indexInInline, true);\n };\n /**\n * Move text position forward\n * @private\n */\n TextPosition.prototype.moveForward = function () {\n var indexInInline = 0;\n var inlineObj = this.currentWidget.getInline(this.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!isNullOrUndefined(inline)) {\n if (!this.owner.selection.isEmpty && indexInInline === inline.length && inline instanceof FieldElementBox\n && inline.fieldType === 1) {\n var hierarchicalIndex = this.owner.selection.start.getHierarchicalIndexInternal();\n // tslint:disable-next-line:max-line-length\n var fieldBeginOffset = inline.fieldBegin.line.getOffset(inline.fieldBegin, 0);\n // tslint:disable-next-line:max-line-length\n var fieldBeginIndex = this.getHierarchicalIndex(inline.fieldBegin.line, fieldBeginOffset.toString());\n if (!TextPosition.isForwardSelection(hierarchicalIndex, fieldBeginIndex)) {\n //If field begin is before selection start, move selection start to field begin.\n // tslint:disable-next-line:max-line-length\n this.owner.selection.start.setPositionParagraph(inline.fieldBegin.line, fieldBeginOffset);\n return;\n }\n }\n inline = this.selection.getNextRenderedElementBox(inline, indexInInline);\n }\n if (inline instanceof FieldElementBox && !isNullOrUndefined(inline.fieldEnd)) {\n var selectionStartParagraph = this.owner.selection.start.paragraph;\n var selectionStartIndex = 0;\n // tslint:disable-next-line:max-line-length\n var selectionStartInlineObj = selectionStartParagraph.getInline(this.owner.selection.start.offset, selectionStartIndex);\n var selectionStartInline = selectionStartInlineObj.element;\n selectionStartIndex = selectionStartInlineObj.index;\n var nextRenderInline = this.selection.getNextRenderedElementBox(selectionStartInline, selectionStartIndex);\n if (nextRenderInline === inline) {\n this.moveNextPositionInternal(inline);\n }\n else {\n //If selection start is before field begin, extend selection end to field end.\n inline = inline.fieldEnd;\n this.currentWidget = inline.line;\n this.offset = this.currentWidget.getOffset(inline, 1);\n //Updates physical position in current page.\n this.updatePhysicalPosition(true);\n return;\n }\n }\n else if ((inline instanceof FieldElementBox)\n && (inline.fieldType === 0 || inline.fieldType === 1)) {\n this.currentWidget = inline.line;\n this.offset = this.currentWidget.getOffset(inline, 1);\n }\n indexInInline = 0;\n var nextOffset = this.selection.getNextValidOffset(this.currentWidget, this.offset);\n var length = this.selection.getLineLength(this.currentWidget);\n var isParagraphEnd = this.selection.isParagraphLastLine(this.currentWidget);\n if (this.offset < nextOffset) {\n this.offset = nextOffset;\n var inlineObj_1 = this.currentWidget.getInline(this.offset, indexInInline);\n inline = inlineObj_1.element;\n indexInInline = inlineObj_1.index;\n if (!isNullOrUndefined(inline) && indexInInline === inline.length && inline.nextNode instanceof FieldElementBox) {\n var nextValidInline = this.selection.getNextValidElement(inline.nextNode);\n //Moves to field end mark.\n if (nextValidInline instanceof FieldElementBox && nextValidInline.fieldType === 1) {\n inline = nextValidInline;\n this.offset = this.currentWidget.getOffset(inline, 1);\n }\n }\n }\n else if (this.offset === nextOffset && this.offset < length + 1 && isParagraphEnd) {\n this.offset = length + 1;\n }\n else {\n this.updateOffsetToNextParagraph(indexInInline, true);\n }\n //Gets physical position in current page.\n this.updatePhysicalPosition(true);\n };\n /**\n * Move to given inline\n * @private\n */\n TextPosition.prototype.moveToInline = function (inline, index) {\n this.currentWidget = inline.line;\n this.offset = this.currentWidget.getOffset(inline, index);\n //Updates physical position in current page.\n this.updatePhysicalPosition(true);\n };\n /**\n * Return true is start element exist before end element\n * @private\n */\n TextPosition.isForwardSelection = function (start, end) {\n if (start === end) {\n return true;\n }\n start = start.replace(/C;/g, '');\n end = end.replace(/C;/g, '');\n start = start.replace(/H;/g, '');\n end = end.replace(/H;/g, '');\n start = start.replace(/F;/g, '');\n end = end.replace(/F;/g, '');\n var selectionStart = start.split(';');\n var selectionEnd = end.split(';');\n var length = selectionStart.length;\n if (length > selectionEnd.length) {\n length = selectionEnd.length - 1;\n }\n for (var i = 0; i < length; i++) {\n var startOffset = parseFloat(selectionStart[i]);\n var endOffset = parseFloat(selectionEnd[i]);\n if (startOffset !== endOffset) {\n return startOffset < endOffset;\n }\n }\n return false;\n };\n /**\n * Move to previous position offset\n * @private\n */\n TextPosition.prototype.movePreviousPositionInternal = function (fieldEnd) {\n var inline;\n if (isNullOrUndefined(fieldEnd.fieldSeparator)) {\n inline = this.selection.getPreviousValidElement(fieldEnd.fieldBegin);\n }\n else {\n inline = this.selection.getPreviousValidElement(fieldEnd);\n }\n this.currentWidget = inline.line;\n this.offset = this.currentWidget.getOffset(inline, inline instanceof FieldElementBox ? 0 : inline.length);\n };\n /**\n * Moves the text position to start of the word.\n * @private\n */\n TextPosition.prototype.moveToWordStartInternal = function (type) {\n var endOffset = this.currentWidget.getEndOffset();\n var currentPara = this.currentWidget.paragraph;\n var selection = this.selection;\n if (type === 2 && (this.offset === endOffset || this.offset === endOffset + 1)) {\n return;\n }\n if (this.offset === endOffset + 1) {\n this.offset = endOffset;\n }\n else if (this.offset === selection.getStartOffset(currentPara) && this.currentWidget === currentPara.childWidgets[0]) {\n var previousParagraph = selection.getPreviousParagraphBlock(currentPara);\n if (isNullOrUndefined(previousParagraph)) {\n return;\n }\n this.currentWidget = previousParagraph.childWidgets[previousParagraph.childWidgets.length - 1];\n this.offset = this.currentWidget.getEndOffset();\n }\n else {\n if (this.offset === selection.getStartLineOffset(this.currentWidget)) {\n var lineIndex = currentPara.childWidgets.indexOf(this.currentWidget);\n if (lineIndex - 1 >= 0) {\n this.currentWidget = currentPara.childWidgets[lineIndex - 1];\n this.offset = this.currentWidget.getEndOffset();\n }\n }\n var isStarted = false;\n var endSelection = false;\n var indexInInline = 0;\n var inlineObj = this.currentWidget.getInline(this.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n // tslint:disable-next-line:max-line-length \n this.getPreviousWordOffset(inline, selection, indexInInline, type, (inline instanceof FieldElementBox && inline.fieldType === 1), isStarted, endSelection, this);\n }\n if (type === 1) {\n this.calculateOffset();\n }\n this.updatePhysicalPosition(true);\n };\n /**\n * Get next word offset\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getNextWordOffset = function (inline, indexInInline, type, isInField, endSelection, endPosition, excludeSpace) {\n if (inline instanceof TextElementBox) {\n this.getNextWordOffsetSpan(inline, indexInInline, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else if (inline instanceof ImageElementBox) {\n // tslint:disable-next-line:max-line-length\n this.getNextWordOffsetImage(inline, indexInInline, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n // tslint:disable-next-line:max-line-length\n this.getNextWordOffsetFieldBegin(inline, indexInInline, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 2 || inline instanceof BookmarkElementBox) {\n // tslint:disable-next-line:max-line-length\n this.getNextWordOffsetFieldSeperator(inline, indexInInline, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 1) {\n // tslint:disable-next-line:max-line-length\n this.getNextWordOffsetFieldEnd(inline, indexInInline, type, isInField, endSelection, endPosition, excludeSpace);\n }\n };\n /**\n * get next word offset from field begin\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getNextWordOffsetFieldBegin = function (fieldBegin, indexInInline, type, isInField, endSelection, endPosition, excludeSpace) {\n var startOffset = fieldBegin.line.getOffset(fieldBegin, 0);\n var endOffset = startOffset + fieldBegin.length;\n if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n this.getNextWordOffsetFieldEnd(fieldBegin.fieldEnd, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else if (type === 0) {\n // tslint:disable-next-line:max-line-length\n this.getNextWordOffsetFieldSeperator(fieldBegin.fieldSeparator, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else if (!isNullOrUndefined(fieldBegin.fieldEnd)) {\n var inline = fieldBegin.fieldSeparator;\n // tslint:disable-next-line:max-line-length\n if (inline.line.paragraph === fieldBegin.fieldEnd.line.paragraph && !this.selection.hasValidInline(inline.line.paragraph, inline, fieldBegin.fieldEnd)) {\n inline = fieldBegin.fieldEnd;\n }\n // tslint:disable-next-line:max-line-length\n this.getNextWordOffset(inline, 0, type, !(endPosition.paragraph === fieldBegin.line.paragraph && endPosition.offset === startOffset), endSelection, endPosition, excludeSpace);\n // tslint:disable-next-line:max-line-length\n if (endSelection && !isNullOrUndefined(fieldBegin.fieldSeparator) && (endPosition.paragraph === fieldBegin.line.paragraph) && (endPosition.offset === fieldBegin.fieldSeparator.line.getOffset(fieldBegin.fieldSeparator, fieldBegin.fieldSeparator.length))) {\n endPosition.setPositionParagraph(fieldBegin.line, startOffset);\n return;\n }\n if (!endSelection) {\n // tslint:disable-next-line:max-line-length\n endPosition.setPositionParagraph(fieldBegin.fieldEnd.line, fieldBegin.fieldEnd.line.getOffset(fieldBegin.fieldEnd, fieldBegin.fieldEnd.length));\n }\n }\n };\n /**\n * get next word offset from image\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getNextWordOffsetImage = function (image, indexInInline, type, isInField, endSelection, endPosition, excludeSpace) {\n if (isInField) {\n endPosition.setPositionParagraph(image.line, image.line.getOffset(image, indexInInline));\n endSelection = false;\n return;\n }\n if (indexInInline === 0) {\n var startOffset = image.line.getOffset(image, 0);\n endSelection = true;\n if (endPosition.offset === startOffset) {\n if (isNullOrUndefined(image.nextNode)) {\n endPosition.setPositionParagraph(image.line, startOffset + image.length);\n }\n else {\n this.getNextWordOffset(image.nextNode, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n }\n else {\n endPosition.setPositionParagraph(image.line, startOffset);\n }\n }\n else if (!isNullOrUndefined(image.nextNode)) {\n this.getNextWordOffset(image.nextNode, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n };\n /**\n * get next word offset from span\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getNextWordOffsetSpan = function (span, indexInInline, type, isInField, endSelection, endPosition, excludeSpace) {\n if (span.text === '\\t' || span.text === '\\v') {\n if (isInField) {\n endPosition.setPositionParagraph(span.line, span.line.getOffset(span, indexInInline));\n endSelection = false;\n return;\n }\n if (indexInInline === 0) {\n endSelection = true;\n var startOffset = span.line.getOffset(span, 0);\n if (endPosition.offset === startOffset) {\n endPosition.setPositionParagraph(span.line, startOffset + span.length);\n }\n else {\n endPosition.setPositionParagraph(span.line, startOffset);\n }\n }\n else if (!isNullOrUndefined(span.nextNode)) {\n this.getNextWordOffset(span.nextNode, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n }\n else {\n var wordEndIndex = 0;\n if (indexInInline === 0 && endSelection && (HelperMethods.wordSplitCharacters.indexOf(span.text[0]) === -1)) {\n endPosition.setPositionParagraph(span.line, span.line.getOffset(span, indexInInline));\n if (isInField) {\n return;\n }\n }\n else if (indexInInline < span.length) {\n // tslint:disable-next-line:max-line-length\n var txt = indexInInline > 0 && span.text.length - 1 >= indexInInline ? span.text.slice(indexInInline, span.length) : span.text;\n wordEndIndex = HelperMethods.indexOfAny(txt, HelperMethods.wordSplitCharacters);\n if (wordEndIndex !== -1) {\n if (isInField) {\n endSelection = false;\n return;\n }\n var offset = span.line.getOffset(span, wordEndIndex + indexInInline);\n // tslint:disable-next-line:max-line-length\n if ((excludeSpace || txt[wordEndIndex] !== ' ') && !endSelection && span.line.paragraph === endPosition.paragraph && offset !== endPosition.offset) {\n endSelection = true;\n endPosition.setPositionParagraph(span.line, offset);\n return;\n }\n wordEndIndex++;\n while (wordEndIndex < txt.length && HelperMethods.wordSplitCharacters.indexOf(txt[wordEndIndex]) !== -1) {\n if (txt[wordEndIndex] !== ' ' && txt[wordEndIndex] !== ' ') {\n break;\n }\n wordEndIndex++;\n }\n endSelection = true;\n if (wordEndIndex < txt.length) {\n // tslint:disable-next-line:max-line-length\n endPosition.setPositionParagraph(span.line, span.line.getOffset(span, wordEndIndex + indexInInline));\n }\n else if (!isNullOrUndefined(span.nextNode)) {\n // tslint:disable-next-line:max-line-length\n this.getNextWordOffset(span.nextNode, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else {\n // tslint:disable-next-line:max-line-length\n endPosition.setPositionParagraph(span.line, span.line.getOffset(span, wordEndIndex + indexInInline));\n }\n }\n else if (!isNullOrUndefined(span.nextNode)) {\n this.getNextWordOffset(span.nextNode, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n else {\n endPosition.setPositionParagraph(span.line, span.line.getEndOffset());\n }\n }\n else if (!isNullOrUndefined(span.nextNode)) {\n this.getNextWordOffset(span.nextNode, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n }\n };\n /**\n * get next word offset from field separator\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getNextWordOffsetFieldSeperator = function (fieldSeparator, indexInInline, type, isInField, endSelection, endPosition, excludeSpace) {\n if (!isNullOrUndefined(fieldSeparator.nextNode)) {\n this.getNextWordOffset(fieldSeparator.nextNode, 0, type, isInField, endSelection, endPosition, excludeSpace);\n }\n };\n /**\n * get next word offset from field end\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getNextWordOffsetFieldEnd = function (fieldEnd, indexInInline, type, isInField, endSelection, endPosition, excludeSpace) {\n var startOffset = fieldEnd.line.getOffset(fieldEnd, 0);\n var endOffset = startOffset + fieldEnd.length;\n if (endPosition.offset === startOffset) {\n endPosition.setPositionParagraph(fieldEnd.line, endOffset);\n if (isNullOrUndefined(fieldEnd.nextNode)) {\n return;\n }\n }\n if (!isNullOrUndefined(fieldEnd.nextNode)) {\n this.getNextWordOffset(fieldEnd.nextNode, 0, type, false, endSelection, endPosition, excludeSpace);\n if (endPosition.offset === endOffset) {\n endPosition.setPositionParagraph(fieldEnd.line, startOffset);\n }\n }\n else {\n endPosition.setPositionParagraph(fieldEnd.line, startOffset);\n }\n endSelection = true;\n };\n /**\n * Get previous word offset\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getPreviousWordOffset = function (inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n if (inline instanceof TextElementBox) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffsetSpan(inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else if (inline instanceof ImageElementBox) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffsetImage(inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffsetFieldBegin(inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 2) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffsetFieldSeparator(inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 1) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffsetFieldEnd(inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else if (inline instanceof BookmarkElementBox) {\n this.getPreviousWordOffsetBookMark(inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else if (inline instanceof ListTextElementBox && inline.previousNode) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffsetSpan(inline.previousNode, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n };\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getPreviousWordOffsetBookMark = function (bookmark, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n if (bookmark.previousNode) {\n if (bookmark.previousNode instanceof TextElementBox) {\n var inline = bookmark.previousNode;\n if (HelperMethods.lastIndexOfAny(inline.text, HelperMethods.wordSplitCharacters) !== inline.text.length - 1) {\n this.getPreviousWordOffset(inline, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else {\n endPosition.setPositionParagraph(bookmark.line, bookmark.line.getOffset(bookmark, 0));\n }\n }\n }\n else {\n endPosition.setPositionParagraph(bookmark.line, selection.getStartLineOffset(bookmark.line));\n }\n };\n /**\n * get previous word offset from field end\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getPreviousWordOffsetFieldEnd = function (fieldEnd, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n var startOffset = fieldEnd.line.getOffset(fieldEnd, 0);\n var endOffset = startOffset + fieldEnd.length;\n if (isNullOrUndefined(fieldEnd.fieldSeparator)) {\n this.getPreviousWordOffsetFieldBegin(fieldEnd.fieldBegin, selection, 0, type, isInField, isStarted, endSelection, endPosition);\n }\n else if (type === 0 && !isNullOrUndefined(fieldEnd.previousNode)) {\n var inline = fieldEnd.previousNode;\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffset(inline, selection, inline.length, type, (inline instanceof FieldElementBox && inline.fieldType === 1), isStarted, endSelection, endPosition);\n }\n else if (!isNullOrUndefined(fieldEnd.fieldBegin) && type !== 0) {\n var inline = fieldEnd.previousNode;\n // tslint:disable-next-line:max-line-length\n if (isNullOrUndefined(inline) || (inline.line.paragraph === fieldEnd.fieldBegin.line.paragraph && !selection.hasValidInline(inline.line.paragraph, inline, fieldEnd.fieldBegin))) {\n inline = fieldEnd.fieldBegin;\n }\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffset(inline, selection, inline.length, type, !(endPosition.paragraph === fieldEnd.line.paragraph && endPosition.offset === endOffset), isStarted, endSelection, endPosition);\n if (endSelection && endPosition.paragraph === fieldEnd.line.paragraph\n && endPosition.offset === startOffset) {\n endPosition.setPositionParagraph(fieldEnd.line, endOffset);\n return;\n }\n if (!endSelection) {\n // tslint:disable-next-line:max-line-length\n endPosition.setPositionParagraph(fieldEnd.fieldBegin.line, fieldEnd.fieldBegin.line.getOffset(fieldEnd.fieldBegin, 0));\n }\n }\n };\n /**\n * get previous word offset from field separator\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getPreviousWordOffsetFieldSeparator = function (fieldSeparator, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n this.getPreviousWordOffsetFieldBegin(fieldSeparator.fieldBegin, selection, fieldSeparator.fieldBegin.length, type, isInField, isStarted, endSelection, endPosition);\n };\n /**\n * get previous word offset from field begin\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getPreviousWordOffsetFieldBegin = function (fieldBegin, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n var startOffset = fieldBegin.line.getOffset(fieldBegin, 0);\n var endOffset = startOffset + fieldBegin.length;\n if (endPosition.offset === endOffset) {\n endPosition.setPositionParagraph(fieldBegin.line, startOffset);\n }\n if (!isNullOrUndefined(fieldBegin.previousNode)) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffset(fieldBegin.previousNode, selection, fieldBegin.previousNode.length, type, false, isStarted, endSelection, endPosition);\n if (endPosition.offset === startOffset) {\n if (type !== 0 && !isNullOrUndefined(fieldBegin.fieldSeparator)) {\n // tslint:disable-next-line:max-line-length\n endPosition.setPositionParagraph(fieldBegin.line, fieldBegin.fieldSeparator.line.getOffset(fieldBegin.fieldSeparator, fieldBegin.fieldSeparator.length));\n }\n }\n }\n else {\n endPosition.setPositionParagraph(fieldBegin.line, selection.getStartLineOffset(fieldBegin.line));\n }\n };\n /**\n * get previous word offset from image\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.getPreviousWordOffsetImage = function (image, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n if (isInField) {\n endPosition.setPositionParagraph(image.line, image.line.getOffset(image, indexInInline));\n endSelection = false;\n return;\n }\n if (indexInInline === image.length) {\n var endOffset = image.line.getOffset(image, image.length);\n if (endOffset === endPosition.offset) {\n endPosition.setPositionParagraph(image.line, endOffset - image.length);\n }\n else {\n endPosition.setPositionParagraph(image.line, endOffset);\n }\n }\n else if (!isNullOrUndefined(image.previousNode)) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffset(image.previousNode, selection, image.previousNode.length, type, isInField, isStarted, endSelection, endPosition);\n }\n };\n /**\n * Get previous word offset from span\n * @private\n */\n // tslint:disable-next-line:max-line-length \n TextPosition.prototype.getPreviousWordOffsetSpan = function (span, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n if (span.text === '\\t' || span.text === '\\v') {\n if (isInField) {\n endSelection = false;\n return;\n }\n if (indexInInline === span.length) {\n endSelection = true;\n var endOffset = span.line.getOffset(span, span.length);\n if (endOffset === endPosition.offset) {\n endPosition.setPositionParagraph(span.line, endOffset - span.length);\n }\n else {\n endPosition.setPositionParagraph(span.line, endOffset);\n }\n }\n else if (!isNullOrUndefined(span.previousNode)) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffset(span.previousNode, selection, span.previousNode.length, type, isInField, isStarted, endSelection, endPosition);\n }\n }\n else {\n var wordStartIndex = 0;\n if (!isStarted) {\n while (indexInInline > 0 && span.text[indexInInline - 1] === ' ') {\n indexInInline--;\n }\n endPosition.setPositionParagraph(span.line, span.line.getOffset(span, indexInInline));\n }\n if (indexInInline > 0) {\n isStarted = true;\n if (indexInInline === 0 && endSelection && (HelperMethods.wordSplitCharacters.indexOf(span.text[0])) === -1) {\n endPosition.setPositionParagraph(span.line, span.line.getOffset(span, indexInInline));\n endSelection = true;\n return;\n }\n var txt = span.text.length > indexInInline ? span.text.slice(0, indexInInline) : span.text;\n wordStartIndex = HelperMethods.lastIndexOfAny(txt, HelperMethods.wordSplitCharacters);\n if (wordStartIndex !== -1) {\n if (isInField) {\n endSelection = false;\n return;\n }\n while (wordStartIndex > 0 && endSelection && txt[wordStartIndex] !== ' '\n && (HelperMethods.wordSplitCharacters.indexOf(txt[wordStartIndex - 1])) !== -1) {\n wordStartIndex--;\n }\n if (txt[wordStartIndex] === ' ' || txt[wordStartIndex] === ' ' || !endSelection) {\n wordStartIndex++;\n }\n endSelection = true;\n if (wordStartIndex > 0) {\n var offset = span.line.getOffset(span, wordStartIndex);\n if (span.line.paragraph === endPosition.paragraph && offset === endPosition.offset) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffsetSpan(span, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n else {\n endPosition.setPositionParagraph(span.line, offset);\n }\n }\n else if (span.previousNode instanceof TextElementBox) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffset(span.previousNode, selection, span.previousNode.length, type, isInField, isStarted, endSelection, endPosition);\n }\n else {\n endPosition.setPositionParagraph(span.line, span.line.getOffset(span, 0));\n }\n }\n else {\n this.setPreviousWordOffset(span, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n }\n else {\n this.setPreviousWordOffset(span, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition);\n }\n }\n };\n /**\n * set previous word offset in span\n * @private\n */\n // tslint:disable-next-line:max-line-length\n TextPosition.prototype.setPreviousWordOffset = function (span, selection, indexInInline, type, isInField, isStarted, endSelection, endPosition) {\n if (span.previousNode instanceof ElementBox && span.line === span.previousNode.line) {\n // tslint:disable-next-line:max-line-length\n this.getPreviousWordOffset(span.previousNode, selection, span.previousNode.length, type, isInField, isStarted, endSelection, endPosition);\n }\n else {\n endPosition.setPositionParagraph(span.line, selection.getStartLineOffset(span.line));\n }\n };\n /**\n * Validate if text position is in field forward\n * @private\n */\n TextPosition.prototype.validateForwardFieldSelection = function (currentIndex, selectionEndIndex) {\n var textPosition = new TextPosition(this.owner);\n textPosition.setPositionForCurrentIndex(currentIndex);\n textPosition.isUpdateLocation = false;\n var isPositionMoved = false;\n while (currentIndex !== selectionEndIndex && TextPosition.isForwardSelection(currentIndex, selectionEndIndex)) {\n if (!isPositionMoved) {\n textPosition.moveNextPosition(false);\n var nextIndex = textPosition.getHierarchicalIndexInternal();\n //Handled specifically to break infinite looping, if selection ends at last paragraph mark.\n if (currentIndex === nextIndex) {\n break;\n }\n }\n var indexInInline = 0;\n var inlineObj = textPosition.currentWidget.getInline(textPosition.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!isNullOrUndefined(inline)) {\n var selectionStartIndex = this.selection.start.getHierarchicalIndexInternal();\n if (indexInInline === inline.length && inline instanceof FieldElementBox && inline.fieldType === 1) {\n if (inline.line.getOffset(inline, 0) === this.offset) {\n return;\n }\n var lineWidget = inline.fieldBegin.line;\n var fieldBeginOffset = lineWidget.getOffset(inline.fieldBegin, 0);\n var fieldBeginIndex = this.getHierarchicalIndex(lineWidget, fieldBeginOffset.toString());\n if (!TextPosition.isForwardSelection(selectionStartIndex, fieldBeginIndex)) {\n this.selection.start.setPositionParagraph(lineWidget, fieldBeginOffset);\n }\n }\n var nextInline = this.selection.getNextRenderedElementBox(inline, indexInInline);\n if (!isNullOrUndefined(nextInline) && nextInline instanceof ElementBox) {\n inline = nextInline;\n }\n }\n isPositionMoved = (inline instanceof FieldElementBox && inline.fieldType === 0 && !isNullOrUndefined(inline.fieldEnd));\n if (isPositionMoved) {\n if (inline.line.getOffset(inline, 0) === this.offset) {\n return;\n }\n var fieldEnd = inline.fieldEnd;\n var paragraph = fieldEnd.line.paragraph;\n var fieldEndOffset = fieldEnd.line.getOffset(fieldEnd, 1);\n var fieldEndIndex = this.getHierarchicalIndex(fieldEnd.line, fieldEndOffset.toString());\n if (!TextPosition.isForwardSelection(fieldEndIndex, selectionEndIndex)) {\n //If selection end is after field begin, extend selection end to field end.\n this.moveToInline(inline.fieldEnd, 1);\n return;\n }\n textPosition.moveToInline(inline.fieldEnd, 1);\n }\n currentIndex = textPosition.getHierarchicalIndexInternal();\n }\n };\n /**\n * Validate if text position is in field backward\n * @private\n */\n TextPosition.prototype.validateBackwardFieldSelection = function (currentIndex, selectionEndIndex) {\n var textPosition = new TextPosition(this.owner);\n textPosition.setPositionForCurrentIndex(currentIndex);\n textPosition.isUpdateLocation = false;\n var selectionStartIndex = this.selection.start.getHierarchicalIndexInternal();\n while (currentIndex !== selectionEndIndex && TextPosition.isForwardSelection(selectionEndIndex, currentIndex)) {\n var indexInInline = 0;\n var inlineObj = textPosition.currentWidget.getInline(textPosition.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!isNullOrUndefined(inline)) {\n var nextInline = this.selection.getNextRenderedElementBox(inline, indexInInline);\n if (nextInline instanceof FieldElementBox && nextInline.fieldType === 0) {\n var paragraph = nextInline.fieldEnd.line;\n var fieldEndOffset = paragraph.getOffset(nextInline.fieldEnd, 1);\n var fieldEndIndex = this.getHierarchicalIndex(paragraph, fieldEndOffset.toString());\n if (!TextPosition.isForwardSelection(fieldEndIndex, selectionStartIndex)) {\n this.selection.start.setPositionParagraph(paragraph, fieldEndOffset);\n selectionStartIndex = fieldEndIndex;\n }\n }\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 1 && !isNullOrUndefined(inline.fieldBegin)) {\n var line = inline.fieldBegin.line;\n var fieldBegin = inline.fieldBegin;\n var fieldBeginOffset = line.getOffset(fieldBegin, 0);\n var fieldBeginIndex = this.getHierarchicalIndex(line, fieldBeginOffset.toString());\n if (!TextPosition.isForwardSelection(selectionEndIndex, fieldBeginIndex)) {\n //If field begin is before selection end, extend selection end to field begin.\n this.moveToInline(inline.fieldBegin, 0);\n return;\n }\n textPosition.moveToInline(inline.fieldBegin, 0);\n }\n else {\n textPosition.movePreviousPosition();\n }\n currentIndex = textPosition.getHierarchicalIndexInternal();\n }\n };\n /**\n * @private\n */\n TextPosition.prototype.paragraphStartInternal = function (selection, moveToPreviousParagraph) {\n var offset = selection.getStartLineOffset(this.currentWidget);\n if (this.offset === offset && moveToPreviousParagraph) {\n var startParagraph = this.moveToNextParagraphInTableCheck();\n if (startParagraph) {\n this.moveToPreviousParagraphInTable(selection);\n }\n else if (!isNullOrUndefined(selection.getPreviousParagraphBlock(this.currentWidget.paragraph))) {\n var paragraphValue = selection.getPreviousParagraphBlock(this.currentWidget.paragraph);\n this.currentWidget = paragraphValue.childWidgets[0];\n this.offset = selection.getStartLineOffset(this.currentWidget);\n }\n }\n else {\n this.currentWidget = this.currentWidget.paragraph.getSplitWidgets()[0].childWidgets[0];\n this.offset = offset;\n }\n this.calculateOffset();\n };\n /**\n * @private\n */\n TextPosition.prototype.calculateOffset = function () {\n var selectionStartIndex = this.owner.selection.start.getHierarchicalIndexInternal();\n var selectionEndIndex = this.getHierarchicalIndexInternal();\n if (selectionStartIndex !== selectionEndIndex) {\n this.validateBackwardFieldSelection(selectionStartIndex, selectionEndIndex);\n }\n this.updatePhysicalPosition(true);\n };\n /**\n * Moves the text position to start of the paragraph.\n * @private\n */\n TextPosition.prototype.moveToParagraphStartInternal = function (selection, moveToPreviousParagraph) {\n var startOffset = selection.getStartOffset(this.paragraph);\n if (this.offset === startOffset && moveToPreviousParagraph) {\n var paragraphstart = this.moveToNextParagraphInTableCheck();\n if (paragraphstart) {\n this.moveToPreviousParagraphInTable(selection);\n }\n else if (!isNullOrUndefined(selection.getPreviousParagraphBlock(this.paragraph))) {\n this.currentWidget = selection.getPreviousParagraphBlock(this.paragraph).firstChild;\n this.offset = selection.getStartOffset(this.paragraph);\n }\n }\n else {\n this.currentWidget = this.paragraph.firstChild;\n this.offset = selection.getStartLineOffset(this.currentWidget);\n }\n var selectionStartIndex = this.owner.selection.start.getHierarchicalIndexInternal();\n var selectionEndIndex = this.getHierarchicalIndexInternal();\n if (selectionStartIndex !== selectionEndIndex) {\n this.validateBackwardFieldSelection(selectionStartIndex, selectionEndIndex);\n }\n this.updatePhysicalPosition(false);\n };\n /**\n * Moves the text position to end of the paragraph.\n * @private\n */\n TextPosition.prototype.moveToParagraphEndInternal = function (selection, moveToNextParagraph) {\n // tslint:disable-next-line:max-line-length\n var splittedParagraph = this.currentWidget.paragraph;\n while (splittedParagraph.nextSplitWidget) {\n splittedParagraph = splittedParagraph.nextSplitWidget;\n }\n this.currentWidget = splittedParagraph.childWidgets[splittedParagraph.childWidgets.length - 1];\n var endOffset = this.currentWidget.getEndOffset() + 1;\n if (this.offset === endOffset && moveToNextParagraph) {\n var paragraphEnd = this.moveToNextParagraphInTableCheck();\n if (paragraphEnd) {\n this.moveToNextParagraphInTable();\n }\n else if (!isNullOrUndefined(selection.getNextParagraphBlock(this.currentWidget.paragraph))) {\n var endParagraph = selection.getNextParagraphBlock(this.currentWidget.paragraph);\n this.currentWidget = endParagraph.childWidgets[endParagraph.childWidgets.length - 1];\n this.offset = this.currentWidget.getEndOffset() + 1;\n }\n }\n else {\n this.offset = endOffset;\n }\n this.calculateOffset();\n };\n /**\n * @private\n */\n TextPosition.prototype.moveUp = function (selection, left) {\n var paragraph = this.currentWidget.paragraph;\n //Moves text position to start of line.\n this.moveToLineStartInternal(selection, true);\n //Moves previous line starting.\n this.movePreviousPosition();\n var prevLine = undefined;\n var currentParagraph = this.currentWidget.paragraph;\n if (paragraph.isInsideTable && paragraph !== currentParagraph && paragraph.associatedCell !== currentParagraph.associatedCell\n // tslint:disable-next-line:max-line-length\n && (!isNullOrUndefined(currentParagraph.associatedCell) && (paragraph.associatedCell.ownerRow === currentParagraph.associatedCell.ownerRow))) {\n var ownerRow = currentParagraph.associatedCell.ownerRow;\n if (ownerRow.previousRenderedWidget instanceof TableRowWidget) {\n // tslint:disable-next-line:max-line-length\n var cell = selection.getFirstCellInRegion(ownerRow.previousRenderedWidget, currentParagraph.associatedCell, left, true);\n var lastParagraph = selection.getLastParagraph(cell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], false);\n }\n else {\n var prevBlock = ownerRow.ownerTable.previousRenderedWidget;\n do {\n if (prevBlock instanceof TableWidget) {\n prevBlock = selection.getLastBlockInLastCell(prevBlock);\n }\n } while (prevBlock instanceof TableWidget);\n if (prevBlock instanceof ParagraphWidget) {\n this.setPosition(prevBlock.childWidgets[prevBlock.childWidgets.length - 1], false);\n }\n }\n prevLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n }\n else {\n if (!paragraph.isInsideTable && this.currentWidget.paragraph.isInsideTable) {\n // tslint:disable-next-line:max-line-length\n var cell = selection.getFirstCellInRegion(this.currentWidget.paragraph.associatedCell.ownerRow, this.currentWidget.paragraph.associatedCell, this.owner.selection.upDownSelectionLength, true);\n var lastParagraph = selection.getLastParagraph(cell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], false);\n // tslint:disable-next-line:max-line-length\n }\n else if (paragraph.isInsideTable && (!isNullOrUndefined(this.currentWidget.paragraph.associatedCell) && paragraph.associatedCell.ownerRow.previousRenderedWidget !== paragraph.associatedCell.ownerRow.previousSplitWidget &&\n paragraph.associatedCell.ownerRow.previousRenderedWidget === this.currentWidget.paragraph.associatedCell.ownerRow)) {\n // tslint:disable-next-line:max-line-length\n var cell = selection.getLastCellInRegion(this.currentWidget.paragraph.associatedCell.ownerRow, this.currentWidget.paragraph.associatedCell, this.owner.selection.upDownSelectionLength, true);\n var lastParagraph = selection.getLastParagraph(cell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], false);\n }\n prevLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n }\n //Moves till the Up/Down selection width.\n var top = selection.getTop(prevLine);\n selection.updateTextPositionWidget(prevLine, new Point(left, top), this, false);\n };\n /**\n * @private\n */\n TextPosition.prototype.moveDown = function (selection, left) {\n //Moves text position to end of line.\n var prevParagraph = this.currentWidget.paragraph;\n var prevOffset = this.offset;\n this.moveToLineEndInternal(selection, true);\n var length = this.selection.getParagraphLength(this.currentWidget.paragraph);\n if (this.offset > length) {\n this.offset = length;\n }\n //Moves next line starting.\n this.moveNextPosition();\n var nextLine = undefined;\n // tslint:disable-next-line:max-line-length\n if (prevParagraph.isInsideTable && prevParagraph !== this.currentWidget.paragraph && prevParagraph.associatedCell !== this.currentWidget.paragraph.associatedCell && (!isNullOrUndefined(this.currentWidget.paragraph.associatedCell) && prevParagraph.associatedCell.ownerRow === this.currentWidget.paragraph.associatedCell.ownerRow)) {\n var ownerRow = this.currentWidget.paragraph.associatedCell.ownerRow;\n // tslint:disable-next-line:max-line-length\n if (prevParagraph.isInsideTable && this.currentWidget.paragraph.isInsideTable && prevParagraph.associatedCell.cellFormat.rowSpan > 1 && prevParagraph.associatedCell.cellFormat.rowSpan + prevParagraph.associatedCell.ownerRow.rowIndex === prevParagraph.associatedCell.ownerTable.childWidgets.length) {\n //If the prevParagraph owner cell is Verically merged upto the last row, then theposition moved to next column. the position moved to out of the current tabel so owner row is assigned to last row.\n // tslint:disable-next-line:max-line-length\n ownerRow = this.currentWidget.paragraph.associatedCell.ownerTable.childWidgets[this.currentWidget.paragraph.associatedCell.ownerTable.childWidgets.length - 1];\n }\n if (ownerRow.nextRenderedWidget instanceof TableRowWidget) {\n // tslint:disable-next-line:max-line-length\n var cell = this.selection.getLastCellInRegion(ownerRow.nextRenderedWidget, this.currentWidget.paragraph.associatedCell, left, false);\n this.setPosition(this.selection.getFirstParagraph(cell).childWidgets[0], true);\n }\n else {\n var nextBlock = this.selection.getNextRenderedBlock(ownerRow.ownerTable);\n do {\n if (nextBlock instanceof TableWidget) {\n nextBlock = this.selection.getFirstBlockInFirstCell(nextBlock);\n }\n } while (nextBlock instanceof TableWidget);\n if (nextBlock instanceof ParagraphWidget) {\n this.setPosition(nextBlock.childWidgets[0], true);\n }\n }\n nextLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n }\n else {\n if (!prevParagraph.isInsideTable && this.currentWidget.paragraph.isInsideTable) {\n // tslint:disable-next-line:max-line-length\n var cell = this.selection.getLastCellInRegion(this.currentWidget.paragraph.associatedCell.ownerRow, this.currentWidget.paragraph.associatedCell, this.owner.selection.upDownSelectionLength, false);\n this.setPosition(this.selection.getFirstParagraph(cell).childWidgets[0], true);\n // tslint:disable-next-line:max-line-length\n }\n else if (prevParagraph.isInsideTable && (!isNullOrUndefined(this.currentWidget.paragraph.associatedCell) && prevParagraph.associatedCell.ownerRow.nextRenderedWidget !== prevParagraph.associatedCell.ownerRow.nextSplitWidget\n && prevParagraph.associatedCell.ownerRow.nextRenderedWidget === this.currentWidget.paragraph.associatedCell.ownerRow)) {\n // tslint:disable-next-line:max-line-length\n var cell = selection.getLastCellInRegion(this.currentWidget.paragraph.associatedCell.ownerRow, this.currentWidget.paragraph.associatedCell, this.owner.selection.upDownSelectionLength, true);\n this.setPosition(selection.getFirstParagraph(cell).childWidgets[0], false);\n }\n nextLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n }\n //Moves till the Up/Down selection width.\n var top = this.selection.getTop(nextLine);\n this.selection.updateTextPositionWidget(nextLine, new Point(left, top), this, false);\n };\n /**\n * Moves the text position to start of the line.\n * @private\n */\n TextPosition.prototype.moveToLineStartInternal = function (selection, moveToPreviousLine) {\n if (this.location.x > this.viewer.clientActiveArea.right) {\n this.offset = this.offset - 1;\n }\n var currentLine = selection.getLineWidgetInternal(this.currentWidget, this.offset, moveToPreviousLine);\n var firstElement = selection.getFirstElementInternal(currentLine);\n var startOffset = selection.getStartOffset(this.currentWidget.paragraph);\n if (isNullOrUndefined(firstElement) && this.offset > startOffset) {\n var index = 0;\n var inlineObj = this.currentWidget.getInline(this.offset, index);\n var inline = inlineObj.element;\n index = inlineObj.index;\n if (inline instanceof TextElementBox && inline.text !== '\\v') {\n this.offset = startOffset;\n }\n }\n else if (!isNullOrUndefined(firstElement)) {\n var indexInInline = selection.getIndexInInline(firstElement);\n this.currentWidget = firstElement.line;\n this.offset = this.currentWidget.getOffset(firstElement, indexInInline);\n indexInInline = 0;\n var inlineObj = this.currentWidget.getInline(this.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (inline instanceof FieldElementBox) {\n //Checks if field character is part of rendered field, otherwise moves to previous rendered content.\n var prevInline = selection.getPreviousValidElement(inline);\n if (!isNullOrUndefined(prevInline)) {\n inline = prevInline;\n this.currentWidget = inline.line;\n this.offset = this.currentWidget.getOffset(inline, inline.length);\n if (inline instanceof FieldElementBox) {\n this.offset--;\n }\n }\n }\n }\n this.updatePhysicalPosition(true);\n };\n /**\n * Check paragraph is inside table\n * @private\n */\n TextPosition.prototype.moveToNextParagraphInTableCheck = function () {\n if ((this.selection.start.paragraph.isInsideTable || this.paragraph.isInsideTable)\n && (this.selection.start.paragraph.associatedCell !== this.paragraph.associatedCell\n || this.selection.isCellSelected(this.selection.start.paragraph.associatedCell, this.selection.start, this))) {\n return true;\n }\n return false;\n };\n /**\n * Moves the text position to end of the word.\n * @private\n */\n TextPosition.prototype.moveToWordEndInternal = function (type, excludeSpace) {\n // type === 0 -------->CTRL+ARROW Navigation\n // type === 1 -------->CTRL+SHIFT+ARROW Selection\n // type === 2 -------->Double-tap Word Selection\n var incrementValue = 0;\n var endOffset = this.currentWidget.getEndOffset();\n if (this.selection.isParagraphFirstLine(this.currentWidget)) {\n if (this.currentWidget.children[0] instanceof ListTextElementBox) {\n incrementValue = 1;\n }\n if (this.currentWidget.children[1] instanceof ListTextElementBox) {\n incrementValue = 2;\n }\n }\n if (this.offset + incrementValue === endOffset || this.offset === endOffset + 1) {\n if (this.offset === endOffset && type !== 0) {\n this.setPositionParagraph(this.currentWidget, endOffset + 1);\n }\n else {\n var nextParagraph = this.selection.getNextParagraphBlock(this.currentWidget.paragraph);\n if (isNullOrUndefined(nextParagraph)) {\n return;\n }\n this.currentWidget = nextParagraph.childWidgets[0];\n this.offset = this.selection.getStartLineOffset(this.currentWidget);\n if (type === 1) {\n // tslint:disable-next-line:max-line-length\n var nextWord = this.moveToNextParagraphInTableCheck();\n if (nextWord) {\n this.moveToNextParagraphInTable();\n }\n else {\n this.moveToWordEndInternal(type, excludeSpace);\n }\n }\n }\n }\n else {\n var indexInInline = 0;\n var endSelection = false;\n var inlineObj = this.currentWidget.getInline(this.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n this.getNextWordOffset(inline, indexInInline, type, false, endSelection, this, excludeSpace);\n }\n if (type !== 0) {\n var selectionStartIndex = this.owner.selection.start.getHierarchicalIndexInternal();\n var selectionEndIndex = this.getHierarchicalIndexInternal();\n if (selectionStartIndex !== selectionEndIndex) {\n this.validateForwardFieldSelection(selectionStartIndex, selectionEndIndex);\n }\n }\n this.updatePhysicalPosition(true);\n };\n /**\n * move text position to next paragraph inside table\n * @private\n */\n TextPosition.prototype.moveToNextParagraphInTable = function () {\n var paragraph = this.currentWidget.paragraph;\n var nextParagraph = (paragraph.isInsideTable) ? this.selection.getNextSelectionCell(paragraph.associatedCell) :\n this.selection.getNextParagraphBlock(paragraph);\n if (isNullOrUndefined(nextParagraph)) {\n return;\n }\n this.currentWidget = nextParagraph.childWidgets[nextParagraph.childWidgets.length - 1];\n this.offset = this.currentWidget.getEndOffset() + 1;\n };\n /**\n * Moves the text position to start of the previous paragraph.\n */\n TextPosition.prototype.moveToPreviousParagraph = function (selection) {\n var startOffset = selection.getStartOffset(this.currentWidget.paragraph);\n // tslint:disable-next-line:max-line-length\n if (this.offset === startOffset && !isNullOrUndefined(selection.getPreviousParagraphBlock(this.currentWidget.paragraph))) {\n var previousParagraph = selection.getPreviousParagraphBlock(this.currentWidget.paragraph);\n this.currentWidget = previousParagraph.childWidgets[0];\n this.offset = selection.getStartOffset(this.currentWidget.paragraph);\n }\n else {\n this.offset = selection.getStartOffset(this.currentWidget.paragraph);\n }\n this.updatePhysicalPosition(true);\n };\n /**\n * Move to previous line from current position\n * @private\n */\n TextPosition.prototype.moveToPreviousLine = function (selection, left) {\n var currentIndex = this.getHierarchicalIndexInternal();\n var currentLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n //Moves text position to start of line.\n this.moveToLineStartInternal(selection, true);\n if (this.currentWidget.paragraph.isInsideTable) {\n this.moveUpInTable(selection);\n }\n else {\n this.moveBackward();\n }\n var prevLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n var lineStart = selection.getLeft(prevLine);\n var lineWidth = selection.getWidth(prevLine, true);\n //Moves till the Up/Down selection width.\n if (lineWidth + lineStart >= left && currentLine !== prevLine) {\n var top_1 = selection.getTop(prevLine);\n var point = new Point(left, top_1);\n selection.updateTextPositionWidget(prevLine, point, this, true);\n }\n //Checks if the current position is between field result, then move to field begin.\n var selectionEndIndex = this.getHierarchicalIndexInternal();\n this.validateBackwardFieldSelection(currentIndex, selectionEndIndex);\n };\n /**\n * @private\n */\n TextPosition.prototype.moveToLineEndInternal = function (selection, moveToNextLine) {\n if (this.location.x > this.viewer.clientActiveArea.right) {\n this.offset = this.offset - 1;\n }\n var currentLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n var firstElement = selection.getFirstElementInternal(currentLine);\n if (isNullOrUndefined(firstElement) && this.offset === selection.getStartLineOffset(this.currentWidget)) {\n this.offset = selection.getParagraphLength(this.paragraph) + 1;\n this.updatePhysicalPosition(true);\n }\n else if (!isNullOrUndefined(firstElement)) {\n var lastElement = currentLine.children[currentLine.children.length - 1];\n var index = 0;\n index += lastElement instanceof TextElementBox ? lastElement.length : 1;\n this.currentWidget = lastElement.line;\n if (index === lastElement.length\n && isNullOrUndefined(lastElement.nextNode) && selection.isParagraphLastLine(this.currentWidget)) {\n var length_1 = selection.getLineLength(this.currentWidget);\n this.offset = moveToNextLine ? length_1 + 1 : length_1;\n }\n else {\n var inline = lastElement;\n while (!isNullOrUndefined(inline) && inline.length === index && inline.nextNode instanceof FieldElementBox) {\n var nextInline = selection.getNextValidElement(inline.nextNode);\n if (inline !== nextInline) {\n inline = nextInline;\n index = 0;\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 0\n && !isNullOrUndefined(inline.fieldEnd)) {\n var fieldBegin = inline;\n if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n inline = fieldBegin.fieldEnd;\n }\n else {\n inline = fieldBegin.fieldSeparator;\n this.currentWidget = inline.line;\n if (this.currentWidget === fieldBegin.fieldEnd.line\n && !selection.hasValidInline(this.currentWidget.paragraph, inline, fieldBegin.fieldEnd)) {\n inline = fieldBegin.fieldEnd;\n }\n }\n this.currentWidget = inline.line;\n }\n if (inline instanceof FieldElementBox) {\n index = 1;\n }\n }\n if (index === inline.length && isNullOrUndefined(inline.nextNode)) {\n index++;\n }\n if (!moveToNextLine && inline instanceof ElementBox && inline.text === '\\v') {\n index--;\n }\n this.offset = this.currentWidget.getOffset(inline, index);\n }\n this.updatePhysicalPosition(moveToNextLine);\n }\n };\n /**\n * Move to next line\n * @private\n */\n TextPosition.prototype.moveToNextLine = function (left) {\n var selection = this.selection;\n var textPosition = new TextPosition(this.owner);\n textPosition.setPositionInternal(this);\n var currentIndex = this.getHierarchicalIndexInternal();\n var currentLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n var isAtLineStart = this.offset === 0 ? true : false;\n //Moves text position to end of line.\n this.moveToLineEndInternal(selection, true);\n var isMoveToLineEnd = !textPosition.isAtSamePosition(this);\n textPosition.setPositionInternal(this);\n if (this.currentWidget.paragraph.isInsideTable) {\n this.moveDownInTable(selection);\n }\n else {\n this.moveNextPosition();\n this.moveForward();\n }\n var nextLine = selection.getLineWidgetParagraph(this.offset, this.currentWidget);\n var lineStart = selection.getLeft(nextLine);\n var firstElement = selection.getFirstElementInternal(nextLine);\n // tslint:disable-next-line:max-line-length\n var firstItemWidth = isNullOrUndefined(firstElement) ? selection.getWidth(nextLine, true) : selection.getLeftInternal(nextLine, firstElement, 1) - lineStart;\n //Moves till the Up/Down selection width.\n if (lineStart < left && (firstItemWidth / 2 < left - lineStart)) {\n var top_2 = selection.getTop(nextLine);\n var point = new Point(left, top_2);\n selection.updateTextPositionWidget(nextLine, point, this, true);\n var width = selection.getWidth(nextLine, true);\n if (width < left - lineStart) {\n this.moveToLineEndInternal(selection, true);\n }\n }\n else if (isMoveToLineEnd && this.currentWidget.paragraph.isInsideTable\n && this.currentWidget === this.owner.selection.start.currentWidget) {\n this.setPositionInternal(textPosition);\n }\n else if (!isMoveToLineEnd) {\n this.moveToLineEndInternal(selection, true);\n }\n //Checks if the current position is between field result, then move to field end.\n var selectionEndIndex = this.getHierarchicalIndexInternal();\n this.validateForwardFieldSelection(currentIndex, selectionEndIndex);\n };\n /**\n * Move upward in table\n * @private\n */\n TextPosition.prototype.moveUpInTable = function (selection) {\n var isPositionUpdated = false;\n var end = this.owner.selection.end;\n var isBackwardSelection = !this.owner.selection.isEmpty;\n isPositionUpdated = end.paragraph.isInsideTable;\n if (isPositionUpdated) {\n var startCell = this.currentWidget.paragraph.associatedCell;\n var endCell = end.paragraph.associatedCell;\n var containerCell = selection.getContainerCellOf(endCell, startCell);\n isPositionUpdated = containerCell.ownerTable.contains(startCell);\n if (isPositionUpdated) {\n endCell = selection.getSelectedCell(endCell, containerCell);\n startCell = selection.getSelectedCell(startCell, containerCell);\n // tslint:disable-next-line:max-line-length\n var isInContainerCell = selection.containsCell(containerCell, this.currentWidget.paragraph.associatedCell);\n var isContainerCellSelected = selection.isCellSelected(containerCell, this, end);\n if (!isContainerCellSelected) {\n // tslint:disable-next-line:max-line-length\n isContainerCellSelected = this.currentWidget.paragraph === selection.getFirstParagraph(containerCell) && this.isAtParagraphStart;\n }\n if ((isInContainerCell && isContainerCellSelected\n || !isInContainerCell) && !isNullOrUndefined(startCell.ownerRow.previousRenderedWidget)) {\n //Moves to cell in previous row.\n var row = startCell.ownerRow.previousRenderedWidget;\n // tslint:disable-next-line:max-line-length\n var cell = selection.getFirstCellInRegion(row, containerCell, this.owner.selection.upDownSelectionLength, true);\n var previousParagraph = selection.getLastParagraph(cell);\n this.setPosition(previousParagraph.childWidgets[0], true);\n return;\n }\n else if (isInContainerCell && isContainerCellSelected\n && isNullOrUndefined(startCell.ownerRow.previousRenderedWidget) || !isInContainerCell) {\n if (isBackwardSelection) {\n //Moves to first cell of row.\n startCell = startCell.ownerRow.childWidgets[0];\n var previousParagraph = selection.getFirstParagraph(startCell);\n this.setPosition(previousParagraph.childWidgets[0], true);\n }\n else {\n //Moves to last cell of row.\n startCell = startCell.ownerRow.childWidgets[startCell.ownerRow.childWidgets.length - 1];\n var previousParagraph = selection.getLastParagraph(startCell);\n this.setPosition(previousParagraph.childWidgets[0], false);\n }\n }\n }\n }\n if (!isPositionUpdated) {\n //Moves to previous row / previous block.\n var cell = selection.getContainerCell(this.currentWidget.paragraph.associatedCell);\n if (isBackwardSelection) {\n //Moves to first cell of row.\n cell = cell.ownerRow.childWidgets[0];\n var previousParagraph = selection.getFirstParagraph(cell);\n this.setPosition(previousParagraph.childWidgets[0], true);\n }\n else {\n //Moves to end of row.\n cell = cell.ownerRow.childWidgets[cell.ownerRow.childWidgets.length - 1];\n var previousParagraph = selection.getLastParagraph(cell);\n this.setPosition(previousParagraph.childWidgets[0], false);\n }\n }\n //Moves to previous row / previous block.\n this.moveBackward();\n };\n /**\n * Move down inside table\n * @private\n */\n TextPosition.prototype.moveDownInTable = function (selection) {\n var isPositionUpdated = false;\n var isForwardSelection = this.owner.selection.isEmpty || this.owner.selection.isForward;\n isPositionUpdated = this.owner.selection.start.paragraph.isInsideTable;\n if (isPositionUpdated) {\n var startCell = this.owner.selection.start.paragraph.associatedCell;\n var endCell = this.currentWidget.paragraph.associatedCell;\n var containerCell = selection.getContainerCellOf(startCell, endCell);\n isPositionUpdated = containerCell.ownerTable.contains(endCell);\n if (isPositionUpdated) {\n startCell = selection.getSelectedCell(startCell, containerCell);\n endCell = selection.getSelectedCell(endCell, containerCell);\n // tslint:disable-next-line:max-line-length\n var isInContainerCell = selection.containsCell(containerCell, this.currentWidget.paragraph.associatedCell);\n var isContainerCellSelected = selection.isCellSelected(containerCell, this.owner.selection.start, this);\n if ((isInContainerCell && isContainerCellSelected\n || !isInContainerCell) && !isNullOrUndefined(endCell.ownerRow.nextRenderedWidget)) {\n //Moves to cell in next row.\n var row = endCell.ownerRow.nextRenderedWidget;\n // tslint:disable-next-line:max-line-length\n var cell = selection.getLastCellInRegion(row, containerCell, this.owner.selection.upDownSelectionLength, false);\n var lastParagraph = selection.getLastParagraph(cell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], false);\n return;\n }\n else if (isInContainerCell && isContainerCellSelected\n && isNullOrUndefined(endCell.ownerRow.nextRenderedWidget) || !isInContainerCell) {\n if (isForwardSelection) {\n //Moves to last cell of row.\n endCell = endCell.ownerRow.childWidgets[endCell.ownerRow.childWidgets.length - 1];\n var lastParagraph = selection.getLastParagraph(endCell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], false);\n }\n else {\n //Moves to first cell of row.\n endCell = endCell.ownerRow.childWidgets[0];\n var lastParagraph = selection.getFirstParagraph(endCell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], true);\n }\n }\n }\n }\n if (!isPositionUpdated) {\n //Moves to next row / next block.\n var cell = selection.getContainerCell(this.currentWidget.paragraph.associatedCell);\n if (isForwardSelection) {\n //Moves to end of row.\n cell = cell.ownerRow.childWidgets[cell.ownerRow.childWidgets.length - 1];\n var lastParagraph = selection.getLastParagraph(cell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], false);\n }\n else if (cell.ownerRow.nextRenderedWidget) {\n //Moves to first cell of row.\n cell = cell.ownerRow.nextRenderedWidget.childWidgets[0];\n var lastParagraph = selection.getFirstParagraph(cell);\n this.setPosition(lastParagraph.childWidgets[lastParagraph.childWidgets.length - 1], true);\n }\n }\n //Moves to next row / next block.\n this.moveForward();\n };\n /**\n * @private\n */\n TextPosition.prototype.destroy = function () {\n this.offset = undefined;\n this.isUpdateLocation = undefined;\n if (!isNullOrUndefined(this.location)) {\n this.location.destroy();\n }\n this.location = undefined;\n this.currentWidget = undefined;\n this.owner = undefined;\n this.viewer = undefined;\n };\n return TextPosition;\n}());\nexport { TextPosition };\n/**\n * @private\n */\nvar SelectionWidgetInfo = /** @class */ (function () {\n function SelectionWidgetInfo(left, width) {\n this.leftIn = 0;\n this.widthIn = 0;\n this.leftIn = left;\n this.widthIn = width;\n }\n Object.defineProperty(SelectionWidgetInfo.prototype, \"left\", {\n /**\n * @private\n */\n get: function () {\n return this.leftIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.leftIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectionWidgetInfo.prototype, \"width\", {\n /**\n * @private\n */\n get: function () {\n return this.widthIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.widthIn = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n SelectionWidgetInfo.prototype.destroy = function () {\n this.widthIn = undefined;\n this.leftIn = undefined;\n };\n return SelectionWidgetInfo;\n}());\nexport { SelectionWidgetInfo };\n/**\n * @private\n */\nvar Hyperlink = /** @class */ (function () {\n function Hyperlink(fieldBeginAdv, selection) {\n this.linkInternal = '';\n this.localRef = '';\n this.opensNewWindow = false;\n var fieldCode = selection.getFieldCode(fieldBeginAdv);\n var lowercase = fieldCode.toLowerCase();\n if (lowercase.substring(0, 9) === 'hyperlink') {\n this.parseFieldValues(fieldCode.substring(9).trim(), selection);\n }\n }\n Object.defineProperty(Hyperlink.prototype, \"navigationLink\", {\n /**\n * Gets navigation link.\n * @returns string\n * @private\n */\n get: function () {\n return this.linkInternal;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Hyperlink.prototype, \"localReference\", {\n /**\n * Gets the local reference if any.\n * @returns string\n * @private\n */\n get: function () {\n return this.localRef;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Hyperlink.prototype, \"linkType\", {\n /**\n * Gets hyper link type.\n * @returns HyperLinkType\n * @private\n */\n get: function () {\n return this.typeInternal;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Parse field values\n * @param {string} value\n * @returns Void\n */\n Hyperlink.prototype.parseFieldValues = function (value, selection) {\n var codes = value.split(' ');\n var isLocalRef = false;\n for (var i = 0; i < codes.length; i++) {\n var code = codes[i];\n if (code.length < 1) {\n continue;\n }\n if (code === '\\\\t' || code === '\\\\l') {\n isLocalRef = true;\n }\n else if (code === '\\\\n') {\n this.opensNewWindow = true;\n }\n else {\n code = this.parseFieldValue(code, code[0] === '\\\"' ? '\\\"' : undefined);\n if (isLocalRef) {\n this.localRef = code;\n isLocalRef = false;\n }\n else {\n this.linkInternal = code;\n }\n }\n }\n this.setLinkType();\n };\n Hyperlink.prototype.parseFieldValue = function (value, endChar) {\n value = value.substring(1);\n var endIndex = endChar ? value.indexOf(endChar) : -1;\n if (endIndex < 0) {\n endIndex = value.length;\n }\n return value.substring(0, endIndex).trim();\n };\n Hyperlink.prototype.setLinkType = function () {\n // If only local reference.\n if (isNullOrUndefined(this.linkInternal) || this.linkInternal.length < 1) {\n this.typeInternal = 'Bookmark';\n return;\n }\n // Validates link.\n if (this.linkInternal.substring(0, 4) === ('www.')) {\n this.linkInternal = 'http://' + this.navigationLink;\n }\n else if (this.linkInternal[0] === '@') {\n this.linkInternal = 'mailto:' + this.navigationLink;\n }\n // Finds proper link type.\n if (this.linkInternal.substring(0, 7) === 'http://'\n || this.linkInternal.substring(0, 8) === 'https://') {\n this.typeInternal = 'WebPage';\n }\n else if (this.linkInternal.substring(0, 7) === 'mailto:') {\n this.typeInternal = 'Email';\n }\n else {\n this.typeInternal = 'File';\n }\n };\n /**\n * @private\n */\n Hyperlink.prototype.destroy = function () {\n this.linkInternal = undefined;\n this.localRef = undefined;\n this.typeInternal = undefined;\n this.opensNewWindow = undefined;\n };\n return Hyperlink;\n}());\nexport { Hyperlink };\n/**\n * @private\n */\nvar ImageFormat = /** @class */ (function () {\n /**\n * Constructor for image format class\n * @param imageContainer - Specifies for image width and height values.\n */\n function ImageFormat(imageContainer) {\n /**\n * @private\n */\n this.width = 0;\n /**\n * @private\n */\n this.height = 0;\n this.width = imageContainer.width;\n this.height = imageContainer.height;\n }\n /**\n * Dispose the internal objects which are maintained.\n * @private\n */\n ImageFormat.prototype.destroy = function () {\n this.width = undefined;\n this.height = undefined;\n };\n return ImageFormat;\n}());\nexport { ImageFormat };\n","import { Widget, BodyWidget, TableRowWidget, TableWidget, LineWidget, ElementBox, TextElementBox, ListTextElementBox, ImageElementBox, ParagraphWidget, TableCellWidget, FieldElementBox, BlockWidget, HeaderFooterWidget, BlockContainer, BookmarkElementBox } from '../viewer/page';\nimport { HelperMethods } from '../editor/editor-helper';\nimport { SelectionCharacterFormat, SelectionCellFormat, SelectionParagraphFormat, SelectionRowFormat, SelectionSectionFormat, SelectionTableFormat, SelectionImageFormat } from './selection-format';\nimport { Point } from '../editor/editor-helper';\nimport { isNullOrUndefined, createElement, L10n } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../base/dictionary';\nimport { WParagraphFormat, WParagraphStyle } from '../index';\nimport { HtmlExport } from '../writer/html-export';\nimport { Popup } from '@syncfusion/ej2-popups';\nimport { TextPosition, SelectionWidgetInfo, Hyperlink } from './selection-helper';\n/**\n * Selection\n */\nvar Selection = /** @class */ (function () {\n /**\n * @private\n */\n function Selection(documentEditor) {\n var _this = this;\n /**\n * @private\n */\n this.upDownSelectionLength = 0;\n /**\n * @private\n */\n this.isSkipLayouting = false;\n /**\n * @private\n */\n this.isImageSelected = false;\n this.contextTypeInternal = undefined;\n /**\n * @private\n */\n this.caret = undefined;\n //Format Retrieval Field\n /**\n * @private\n */\n this.isRetrieveFormatting = false;\n /**\n * @private\n */\n this.skipFormatRetrieval = false;\n this.isMoveDownOrMoveUp = false;\n /**\n * @private\n */\n this.selectedWidgets = undefined;\n /**\n * Hides caret.\n * @private\n */\n this.hideCaret = function () {\n _this.caret.style.display = 'none';\n };\n this.owner = documentEditor;\n this.viewer = this.owner.viewer;\n this.start = new TextPosition(this.owner);\n this.end = new TextPosition(this.owner);\n this.selectedWidgets = new Dictionary();\n this.characterFormatIn = new SelectionCharacterFormat(this);\n this.paragraphFormatIn = new SelectionParagraphFormat(this, this.viewer);\n this.sectionFormatIn = new SelectionSectionFormat(this);\n this.rowFormatIn = new SelectionRowFormat(this);\n this.cellFormatIn = new SelectionCellFormat(this);\n this.tableFormatIn = new SelectionTableFormat(this);\n this.imageFormatInternal = new SelectionImageFormat(this);\n }\n Object.defineProperty(Selection.prototype, \"htmlWriter\", {\n /**\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.htmlWriterIn)) {\n this.htmlWriterIn = new HtmlExport();\n }\n return this.htmlWriterIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"start\", {\n /**\n * Gets the start text position of last range in the selection\n * @returns {TextPosition}\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.owner) && !isNullOrUndefined(this.viewer)) {\n if (isNullOrUndefined(this.startInternal)) {\n this.startInternal = this.owner.documentStart;\n }\n return this.startInternal;\n }\n return undefined;\n },\n /**\n * @private\n */\n set: function (value) {\n this.startInternal = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"characterFormat\", {\n //Format retrieval properties\n /**\n * Gets the instance of selection character format.\n * @default undefined\n * @return {SelectionCharacterFormat}\n */\n get: function () {\n return this.characterFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"paragraphFormat\", {\n /**\n * Gets the instance of selection paragraph format.\n * @default undefined\n * @return {SelectionParagraphFormat}\n */\n get: function () {\n return this.paragraphFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"sectionFormat\", {\n /**\n * Gets the instance of selection section format.\n * @default undefined\n * @return {SelectionSectionFormat}\n */\n get: function () {\n return this.sectionFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"tableFormat\", {\n /**\n * Gets the instance of selection table format.\n * @default undefined\n * @return {SelectionTableFormat}\n */\n get: function () {\n return this.tableFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"cellFormat\", {\n /**\n * Gets the instance of selection cell format.\n * @default undefined\n * @return {SelectionCellFormat}\n */\n get: function () {\n return this.cellFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"rowFormat\", {\n /**\n * Gets the instance of selection row format.\n * @default undefined\n * @returns SelectionRowFormat\n */\n get: function () {\n return this.rowFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"imageFormat\", {\n /**\n * Gets the instance of selection image format.\n * @default undefined\n * @returns SelectionImageFormat\n */\n get: function () {\n return this.imageFormatInternal;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"end\", {\n /**\n * Gets the start text position of selection range.\n * @private\n */\n get: function () {\n return this.endInternal;\n },\n /**\n * For internal use\n * @private\n */\n set: function (value) {\n this.endInternal = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"startPage\", {\n /**\n * Gets the page number where the selection ends.\n * @private\n */\n get: function () {\n if (!this.owner.isDocumentLoaded || isNullOrUndefined(this.viewer)\n || isNullOrUndefined(this.viewer.selectionStartPage)) {\n return 1;\n }\n return this.viewer.pages.indexOf(this.viewer.selectionStartPage) + 1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"endPage\", {\n /**\n * Gets the page number where the selection ends.\n * @private\n */\n get: function () {\n if (!this.owner.isDocumentLoaded || isNullOrUndefined(this.viewer)\n || isNullOrUndefined(this.viewer.selectionEndPage)) {\n return 1;\n }\n return this.viewer.pages.indexOf(this.viewer.selectionEndPage) + 1;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"isForward\", {\n /**\n * Determines whether the selection direction is forward or not.\n * @default false\n * @returns {boolean}\n * @private\n */\n get: function () {\n return this.start.isExistBefore(this.end);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"isEmpty\", {\n /**\n * Determines whether the start and end positions are same or not.\n * @default false\n * @returns {boolean}\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.start)) {\n return true;\n }\n return this.start.isAtSamePosition(this.end);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"text\", {\n /**\n * Gets the text within selection.\n * @default ''\n * @returns {string}\n */\n get: function () {\n return this.getText(false);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"contextType\", {\n /**\n * Gets the context type of the selection.\n */\n get: function () {\n return this.contextTypeInternal;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Selection.prototype, \"isCleared\", {\n /**\n * @private\n */\n get: function () {\n return isNullOrUndefined(this.end);\n },\n enumerable: true,\n configurable: true\n });\n Selection.prototype.getModuleName = function () {\n return 'Selection';\n };\n //Public API\n /**\n * Moves the selection to the header of current page.\n */\n Selection.prototype.goToHeader = function () {\n this.owner.enableHeaderAndFooter = true;\n this.enableHeadersFootersRegion(this.start.paragraph.bodyWidget.page.headerWidget);\n };\n /**\n * Moves the selection to the footer of current page.\n */\n Selection.prototype.goToFooter = function () {\n this.owner.enableHeaderAndFooter = true;\n this.enableHeadersFootersRegion(this.start.paragraph.bodyWidget.page.footerWidget);\n };\n /**\n * Closes the header and footer region.\n */\n Selection.prototype.closeHeaderFooter = function () {\n this.disableHeaderFooter();\n };\n /**\n * Moves the selection to the start of specified page number.\n */\n Selection.prototype.goToPage = function (pageNumber) {\n if (pageNumber >= 1 && pageNumber <= this.viewer.pages.length) {\n var page = this.viewer.pages[pageNumber - 1];\n this.updateTextPositionForBlockContainer(page.bodyWidgets[0]);\n }\n };\n /**\n * Selects the entire table if the context is within table.\n */\n Selection.prototype.selectTable = function () {\n if (!this.owner.enableSelection) {\n return;\n }\n this.selectTableInternal();\n };\n /**\n * Selects the entire row if the context is within table.\n */\n Selection.prototype.selectRow = function () {\n if (!this.owner.enableSelection) {\n return;\n }\n this.selectTableRow();\n };\n /**\n * Selects the entire column if the context is within table.\n */\n Selection.prototype.selectColumn = function () {\n if (!this.owner.enableSelection) {\n return;\n }\n this.selectColumnInternal();\n };\n /**\n * Selects the entire cell if the context is within table.\n */\n Selection.prototype.selectCell = function () {\n if (!this.owner.enableSelection) {\n return;\n }\n this.selectTableCell();\n };\n /**\n * Select content based on selection settings\n */\n Selection.prototype.select = function (selectionSettings) {\n var point = new Point(selectionSettings.x, selectionSettings.y);\n var pageCoordinates = this.viewer.findFocusedPage(point, true);\n if (selectionSettings.extend) {\n this.moveTextPosition(pageCoordinates, this.end);\n }\n else {\n this.viewer.updateTextPositionForSelection(pageCoordinates, 1);\n }\n };\n /**\n * Toggles the bold property of selected contents.\n * @private\n */\n Selection.prototype.toggleBold = function () {\n if (this.owner.editorModule) {\n this.owner.editorModule.toggleBold();\n }\n };\n /**\n * Toggles the italic property of selected contents.\n * @private\n */\n Selection.prototype.toggleItalic = function () {\n if (this.owner.editorModule) {\n this.owner.editorModule.toggleItalic();\n }\n };\n /**\n * Toggles the underline property of selected contents.\n * @param underline Default value of ‘underline’ parameter is Single.\n * @private\n */\n Selection.prototype.toggleUnderline = function (underline) {\n if (this.owner.editor) {\n this.owner.editor.toggleUnderline(underline);\n }\n };\n /**\n * Toggles the strike through property of selected contents.\n * @param {Strikethrough} strikethrough Default value of strikethrough parameter is SingleStrike.\n * @private\n */\n Selection.prototype.toggleStrikethrough = function (strikethrough) {\n if (this.owner.editor) {\n this.owner.editor.toggleStrikethrough(strikethrough);\n }\n };\n /**\n * Toggles the highlight color property of selected contents.\n * @param {HighlightColor} highlightColor Default value of ‘underline’ parameter is Yellow.\n * @private\n */\n Selection.prototype.toggleHighlightColor = function (highlightColor) {\n if (this.owner.editor) {\n this.owner.editor.toggleHighlightColor(highlightColor);\n }\n };\n /**\n * Toggles the subscript formatting of selected contents.\n * @private\n */\n Selection.prototype.toggleSubscript = function () {\n if (this.owner.editor) {\n this.owner.editor.toggleSubscript();\n }\n };\n /**\n * Toggles the superscript formatting of selected contents.\n * @private\n */\n Selection.prototype.toggleSuperscript = function () {\n if (this.owner.editor) {\n this.owner.editor.toggleSuperscript();\n }\n };\n /**\n * Toggles the text alignment property of selected contents.\n * @param {TextAlignment} textAlignment Default value of ‘textAlignment parameter is TextAlignment.Left.\n * @private\n */\n Selection.prototype.toggleTextAlignment = function (textAlignment) {\n if (this.owner.editor) {\n this.owner.editor.toggleTextAlignment(textAlignment);\n }\n };\n /**\n * Increases the left indent of selected paragraphs to a factor of 36 points.\n * @private\n */\n Selection.prototype.increaseIndent = function () {\n if (this.owner.editor) {\n this.owner.editor.increaseIndent();\n }\n };\n /**\n * Decreases the left indent of selected paragraphs to a factor of 36 points.\n * @private\n */\n Selection.prototype.decreaseIndent = function () {\n if (this.owner.editor) {\n this.owner.editor.decreaseIndent();\n }\n };\n /**\n * Fires the `requestNavigate` event if current selection context is in hyperlink.\n */\n Selection.prototype.navigateHyperlink = function () {\n var fieldBegin = this.getHyperlinkField();\n if (fieldBegin) {\n this.fireRequestNavigate(fieldBegin);\n }\n };\n /**\n * Navigate Hyperlink\n * @param fieldBegin\n * @private\n */\n Selection.prototype.fireRequestNavigate = function (fieldBegin) {\n var hyperlink = new Hyperlink(fieldBegin, this);\n var eventArgs = {\n isHandled: false,\n navigationLink: hyperlink.navigationLink,\n linkType: hyperlink.linkType,\n localReference: hyperlink.localReference\n };\n this.owner.trigger('requestNavigate', eventArgs);\n if (!eventArgs.isHandled) {\n this.viewer.selection.navigateBookmark(hyperlink.localReference, true);\n }\n };\n /**\n * Copies the hyperlink URL if the context is within hyperlink.\n */\n Selection.prototype.copyHyperlink = function () {\n var hyperLinkField = this.getHyperlinkField();\n var linkText = this.getLinkText(hyperLinkField);\n this.copyToClipboard(linkText);\n };\n //Selection add, Highlight, remove API starts\n /**\n * @private\n */\n Selection.prototype.highlightSelection = function (isSelectionChanged) {\n if (this.owner.enableImageResizerMode) {\n this.owner.imageResizerModule.hideImageResizer();\n }\n if (this.isEmpty) {\n this.updateCaretPosition();\n }\n else {\n if (this.isForward) {\n this.highlightSelectedContent(this.start, this.end);\n }\n else {\n this.highlightSelectedContent(this.end, this.start);\n }\n }\n this.viewer.updateTouchMarkPosition();\n if (isSelectionChanged) {\n this.viewer.scrollToPosition(this.start, this.end);\n }\n };\n /**\n * @private\n */\n Selection.prototype.createHighlightBorder = function (lineWidget, width, left, top) {\n if (width < 0) {\n width = 0;\n }\n var page = this.getPage(lineWidget.paragraph);\n var height = lineWidget.height;\n var selectionWidget = undefined;\n if (!this.selectedWidgets.containsKey(lineWidget)) {\n selectionWidget = new SelectionWidgetInfo(left, width);\n this.selectedWidgets.add(lineWidget, selectionWidget);\n }\n var viewer = this.viewer;\n var pageTop = this.getPageTop(page);\n var pageLeft = page.boundingRectangle.x;\n if (viewer.containerTop <= pageTop\n || pageTop < viewer.containerTop + viewer.selectionCanvas.height) {\n viewer.selectionContext.fillStyle = 'gray';\n viewer.selectionContext.globalAlpha = 0.4;\n var zoomFactor = viewer.zoomFactor;\n this.clipSelection(page, pageTop);\n // tslint:disable-next-line:max-line-length\n viewer.selectionContext.fillRect((pageLeft + (left * zoomFactor)) - viewer.containerLeft, (pageTop + (top * zoomFactor)) - viewer.containerTop, width * zoomFactor, height * zoomFactor);\n viewer.selectionContext.restore();\n }\n };\n /**\n * Create selection highlight inside table\n * @private\n */\n Selection.prototype.createHighlightBorderInsideTable = function (cellWidget) {\n var page = this.getPage(cellWidget);\n var selectionWidget = undefined;\n var left = cellWidget.x - cellWidget.margin.left + cellWidget.leftBorderWidth;\n var width = cellWidget.width + cellWidget.margin.left\n + cellWidget.margin.right - cellWidget.leftBorderWidth - cellWidget.rightBorderWidth;\n var top = cellWidget.y;\n var height = cellWidget.height;\n var pageTop = this.getPageTop(page);\n var pageLeft = page.boundingRectangle.x;\n var isVisiblePage = this.viewer.containerTop <= pageTop\n || pageTop < this.viewer.containerTop + this.viewer.selectionCanvas.height;\n if (this.selectedWidgets.containsKey(cellWidget)) {\n selectionWidget = this.selectedWidgets.get(cellWidget);\n if (isVisiblePage) {\n // tslint:disable-next-line:max-line-length\n this.viewer.selectionContext.clearRect((pageLeft + (selectionWidget.left * this.viewer.zoomFactor) - this.viewer.containerLeft), (pageTop + (top * this.viewer.zoomFactor)) - this.viewer.containerTop, selectionWidget.width * this.viewer.zoomFactor, height * this.viewer.zoomFactor);\n }\n }\n selectionWidget = new SelectionWidgetInfo(left, width);\n this.selectedWidgets.add(cellWidget, selectionWidget);\n if (isVisiblePage) {\n this.viewer.selectionContext.fillStyle = 'gray';\n this.viewer.selectionContext.globalAlpha = 0.4;\n var zoomFactor = this.viewer.zoomFactor;\n this.clipSelection(page, pageTop);\n // tslint:disable-next-line:max-line-length\n this.viewer.selectionContext.fillRect((pageLeft + (left * zoomFactor)) - this.viewer.containerLeft, (pageTop + (top * zoomFactor)) - this.viewer.containerTop, width * zoomFactor, height * zoomFactor);\n this.viewer.selectionContext.restore();\n }\n };\n /**\n * @private\n */\n Selection.prototype.clipSelection = function (page, pageTop) {\n var viewer = this.viewer;\n var width = page.boundingRectangle.width * viewer.zoomFactor;\n var height = page.boundingRectangle.height * viewer.zoomFactor;\n var left = page.boundingRectangle.x;\n viewer.selectionContext.beginPath();\n viewer.selectionContext.save();\n viewer.selectionContext.rect(left - viewer.containerLeft, pageTop - viewer.containerTop, width, height);\n viewer.selectionContext.clip();\n };\n /**\n * Add selection highlight\n * @private\n */\n Selection.prototype.addSelectionHighlight = function (canvasContext, widget, top) {\n if (this.selectedWidgets.containsKey(widget)) {\n var height = this.viewer.render.getScaledValue(widget.height);\n var widgetInfo = this.selectedWidgets.get(widget);\n var width = this.viewer.render.getScaledValue(widgetInfo.width);\n var left = this.viewer.render.getScaledValue(widgetInfo.left, 1);\n canvasContext.fillStyle = 'gray';\n var page = this.owner.selection.getPage(widget.paragraph);\n this.owner.selection.clipSelection(page, this.owner.selection.getPageTop(page));\n canvasContext.fillRect(left, this.viewer.render.getScaledValue(top, 2), width, height);\n canvasContext.restore();\n }\n };\n /**\n * Add Selection highlight inside table\n * @private\n */\n Selection.prototype.addSelectionHighlightTable = function (canvasContext, tableCellWidget) {\n if (this.selectedWidgets.containsKey(tableCellWidget)) {\n var selectionWidget = this.selectedWidgets.get(tableCellWidget);\n var left = this.viewer.render.getScaledValue(selectionWidget.left, 1);\n var top_1 = this.viewer.render.getScaledValue(tableCellWidget.y, 2);\n var width = this.viewer.render.getScaledValue(selectionWidget.width);\n var height = this.viewer.render.getScaledValue(tableCellWidget.height);\n canvasContext.fillStyle = 'gray';\n var page = this.owner.selection.getPage(tableCellWidget);\n this.owner.selection.clipSelection(page, this.owner.selection.getPageTop(page));\n canvasContext.fillRect(left, top_1, width, height);\n canvasContext.restore();\n }\n };\n /**\n * Remove Selection highlight\n * @private\n */\n Selection.prototype.removeSelectionHighlight = function (widget) {\n var left = 0;\n var top = 0;\n var width = 0;\n var height = 0;\n var page = undefined;\n if (widget instanceof LineWidget) {\n var lineWidget = widget;\n var currentParaWidget = lineWidget.paragraph;\n page = !isNullOrUndefined(currentParaWidget) ?\n this.getPage((lineWidget.paragraph)) : undefined;\n if (isNullOrUndefined(page)) {\n return;\n }\n top = this.getTop(lineWidget);\n height = lineWidget.height;\n }\n else if (widget instanceof TableCellWidget) {\n page = !isNullOrUndefined(widget) ?\n this.getPage(widget) : undefined;\n if (isNullOrUndefined(page)) {\n return;\n }\n top = widget.y;\n height = widget.height;\n }\n if (isNullOrUndefined(page)) {\n return;\n }\n var widgetInfo = this.selectedWidgets.get(widget);\n width = widgetInfo.width;\n left = widgetInfo.left;\n var pageRect = page.boundingRectangle;\n var pageIndex = this.viewer.pages.indexOf(page);\n var pageGap = this.viewer.pageGap;\n var pageTop = (pageRect.y - pageGap * (pageIndex + 1)) * this.viewer.zoomFactor + pageGap * (pageIndex + 1);\n var pageLeft = pageRect.x;\n var zoomFactor = this.viewer.zoomFactor;\n if (this.viewer.containerTop <= pageTop\n || pageTop < this.viewer.containerTop + this.viewer.selectionCanvas.height) {\n // tslint:disable-next-line:max-line-length\n this.viewer.selectionContext.clearRect((pageLeft + (left * zoomFactor) - this.viewer.containerLeft) - 0.5, (pageTop + (top * zoomFactor)) - this.viewer.containerTop - 0.5, width * zoomFactor + 0.5, height * zoomFactor + 0.5);\n }\n };\n /**\n * Select Current word\n * @private\n */\n Selection.prototype.selectCurrentWord = function () {\n var startPosition = this.start.clone();\n var endPosition = this.end.clone();\n this.selectCurrentWordRange(startPosition, endPosition, false);\n this.selectRange(startPosition, endPosition);\n };\n /**\n * Select current paragraph\n * @private\n */\n Selection.prototype.selectCurrentParagraph = function () {\n if (!isNullOrUndefined(this.start)) {\n this.start.paragraphStartInternal(this, false);\n this.end.moveToParagraphEndInternal(this, false);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n }\n };\n /**\n * Select current word range\n * @private\n */\n Selection.prototype.selectCurrentWordRange = function (startPosition, endPosition, excludeSpace) {\n if (!isNullOrUndefined(startPosition)) {\n if (startPosition.offset > 0) {\n var wordStart = startPosition.clone();\n var indexInInline = 0;\n var inlineObj = startPosition.currentWidget.getInline(startPosition.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!isNullOrUndefined(inline) && inline instanceof FieldElementBox && inline.fieldType === 1) {\n // tslint:disable-next-line:max-line-length\n if (startPosition.offset > 2 && (!isNullOrUndefined(inline.fieldSeparator) || isNullOrUndefined(inline.fieldBegin))) {\n wordStart.setPositionParagraph(wordStart.currentWidget, startPosition.offset - 2);\n wordStart.moveToWordEndInternal(0, false);\n if (!(wordStart.paragraph === startPosition.paragraph && wordStart.offset === startPosition.offset - 1)) {\n startPosition.moveToWordStartInternal(2);\n }\n }\n else if (startPosition.offset > 3 && isNullOrUndefined(inline.fieldSeparator)) {\n wordStart.setPositionParagraph(wordStart.currentWidget, startPosition.offset - 3);\n wordStart.moveToWordEndInternal(0, false);\n if (!(wordStart.paragraph === startPosition.paragraph && wordStart.offset === startPosition.offset)) {\n startPosition.moveToWordStartInternal(2);\n }\n }\n }\n else {\n wordStart.setPositionParagraph(wordStart.currentWidget, startPosition.offset - 1);\n wordStart.moveToWordEndInternal(0, false);\n if (!(wordStart.paragraph === startPosition.paragraph && wordStart.offset === startPosition.offset)) {\n startPosition.moveToWordStartInternal(2);\n }\n }\n }\n endPosition.moveToWordEndInternal(2, excludeSpace);\n }\n };\n /**\n * Extend selection to paragraph start\n * @private\n */\n Selection.prototype.extendToParagraphStart = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.paragraphStartInternal(this, true);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Extend selection to paragraph end\n * @private\n */\n Selection.prototype.extendToParagraphEnd = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToParagraphEndInternal(this, true);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Move to next text position\n * @private\n */\n Selection.prototype.moveNextPosition = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n if (this.isEmpty) {\n this.start.moveNextPosition();\n this.end.setPositionInternal(this.start);\n }\n this.updateForwardSelection();\n this.upDownSelectionLength = this.start.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Move to next paragraph\n * @private\n */\n Selection.prototype.moveToNextParagraph = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToNextParagraphStartInternal();\n this.start.setPositionInternal(this.end);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Move to previous text position\n * @private\n */\n Selection.prototype.movePreviousPosition = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n if (this.isEmpty) {\n this.start.movePreviousPosition();\n this.end.setPositionInternal(this.start);\n }\n this.updateBackwardSelection();\n this.upDownSelectionLength = this.start.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Move to previous paragraph\n * @private\n */\n Selection.prototype.moveToPreviousParagraph = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToPreviousParagraph(this);\n this.start.setPositionInternal(this.end);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Extend selection to previous line\n * @private\n */\n Selection.prototype.extendToPreviousLine = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToPreviousLine(this, this.upDownSelectionLength);\n this.fireSelectionChanged(true);\n };\n /**\n * Extend selection to line end\n * @private\n */\n Selection.prototype.extendToLineEnd = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToLineEndInternal(this, true);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Extend to line start\n * @private\n */\n Selection.prototype.extendToLineStart = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToLineStartInternal(this, true);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * @private\n */\n Selection.prototype.moveUp = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n if (!this.isEmpty) {\n if (this.isForward) {\n this.end.setPositionInternal(this.start);\n }\n else {\n this.start.setPositionInternal(this.end);\n }\n this.upDownSelectionLength = this.start.location.x;\n }\n this.upDownSelectionLength = this.start.location.x;\n this.start.moveUp(this, this.upDownSelectionLength);\n this.end.setPositionInternal(this.start);\n this.fireSelectionChanged(true);\n };\n /**\n * @private\n */\n Selection.prototype.moveDown = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n if (!this.isEmpty) {\n if (this.isForward) {\n this.start.setPositionInternal(this.end);\n }\n else {\n this.end.setPositionInternal(this.start);\n }\n this.upDownSelectionLength = this.start.location.x;\n }\n this.start.moveDown(this, this.upDownSelectionLength);\n this.end.setPositionInternal(this.start);\n this.fireSelectionChanged(true);\n };\n Selection.prototype.updateForwardSelection = function () {\n if (!this.isEmpty) {\n if (this.isForward) {\n this.start.setPositionInternal(this.end);\n }\n else {\n this.end.setPositionInternal(this.start);\n }\n }\n };\n Selection.prototype.updateBackwardSelection = function () {\n if (!this.isEmpty) {\n if (this.isForward) {\n this.end.setPositionInternal(this.start);\n }\n else {\n this.start.setPositionInternal(this.end);\n }\n }\n };\n /**\n * @private\n */\n Selection.prototype.getFirstBlockInFirstCell = function (table) {\n if (table.childWidgets.length > 0) {\n var firstrow = table.childWidgets[0];\n if (firstrow.childWidgets.length > 0) {\n var firstcell = firstrow.childWidgets[0];\n if (firstcell.childWidgets.length === 0) {\n return undefined;\n }\n return firstcell.childWidgets[0];\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getFirstCellInRegion = function (row, startCell, selectionLength, isMovePrevious) {\n var cellStart = this.getCellLeft(row, startCell);\n var cellEnd = cellStart + startCell.cellFormat.cellWidth;\n var flag = true;\n if (cellStart <= selectionLength && selectionLength < cellEnd) {\n for (var k = 0; k < row.childWidgets.length; k++) {\n var left = this.getCellLeft(row, row.childWidgets[k]);\n if (HelperMethods.round(cellStart, 2) <= HelperMethods.round(left, 2) &&\n HelperMethods.round(left, 2) < HelperMethods.round(cellEnd, 2)) {\n flag = false;\n return row.childWidgets[k];\n }\n }\n }\n else {\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cellLeft = this.getCellLeft(row, row.childWidgets[j]);\n if (cellLeft <= selectionLength && cellLeft +\n row.childWidgets[j].cellFormat.cellWidth > selectionLength) {\n flag = false;\n return row.childWidgets[j];\n }\n }\n }\n if (flag) {\n if (!isNullOrUndefined(row.previousRenderedWidget) && isMovePrevious) {\n var previousWidget = row.previousRenderedWidget;\n return this.getFirstCellInRegion(previousWidget, startCell, selectionLength, isMovePrevious);\n }\n else if (!isNullOrUndefined(row.nextRenderedWidget) && !isMovePrevious) {\n return this.getFirstCellInRegion(row.nextRenderedWidget, startCell, selectionLength, isMovePrevious);\n }\n }\n return row.childWidgets[0];\n };\n /**\n * @private\n */\n Selection.prototype.getFirstParagraph = function (tableCell) {\n while (tableCell.previousSplitWidget) {\n tableCell = tableCell.previousSplitWidget;\n }\n var firstBlock = tableCell.firstChild;\n return this.getFirstParagraphBlock(firstBlock);\n };\n /**\n * Get last block in last cell\n * @private\n */\n //Table\n Selection.prototype.getLastBlockInLastCell = function (table) {\n if (table.childWidgets.length > 0) {\n var lastrow = table.childWidgets[table.childWidgets.length - 1];\n var lastcell = lastrow.childWidgets[lastrow.childWidgets.length - 1];\n return lastcell.childWidgets[lastcell.childWidgets.length - 1];\n }\n return undefined;\n };\n /**\n * Move to line start\n * @private\n */\n Selection.prototype.moveToLineStart = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.updateBackwardSelection();\n this.start.moveToLineStartInternal(this, false);\n this.end.setPositionInternal(this.start);\n this.upDownSelectionLength = this.start.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Move to line end\n * @private\n */\n Selection.prototype.moveToLineEnd = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.updateForwardSelection();\n this.start.moveToLineEndInternal(this, false);\n this.end.setPositionInternal(this.start);\n this.upDownSelectionLength = this.start.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Get Page top\n * @private\n */\n Selection.prototype.getPageTop = function (page) {\n // tslint:disable-next-line:max-line-length\n return (page.boundingRectangle.y - this.viewer.pageGap * (this.viewer.pages.indexOf(page) + 1)) * this.viewer.zoomFactor + this.viewer.pageGap * (this.viewer.pages.indexOf(page) + 1);\n };\n /**\n * Move text position to cursor point\n * @private\n */\n Selection.prototype.moveTextPosition = function (cursorPoint, textPosition) {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n //Updates the text position based on the cursor position.\n var widget = this.viewer.getLineWidgetInternal(cursorPoint, true);\n if (!isNullOrUndefined(widget)) {\n this.updateTextPositionWidget(widget, cursorPoint, textPosition, true);\n }\n this.upDownSelectionLength = textPosition.location.x;\n var selectionStartIndex = this.start.getHierarchicalIndexInternal();\n var selectionEndIndex = this.end.getHierarchicalIndexInternal();\n if (selectionStartIndex !== selectionEndIndex) {\n // Extends selection end to field begin or field end.\n if (TextPosition.isForwardSelection(selectionStartIndex, selectionEndIndex)) {\n textPosition.validateForwardFieldSelection(selectionStartIndex, selectionEndIndex);\n }\n else {\n textPosition.validateBackwardFieldSelection(selectionStartIndex, selectionEndIndex);\n }\n }\n this.fireSelectionChanged(true);\n };\n //Helper Method Implementation \n //Document\n /**\n * Get document start position\n * @private\n */\n Selection.prototype.getDocumentStart = function () {\n var textPosition = undefined;\n var block = this.viewer.pages[0].bodyWidgets[0].childWidgets[0];\n return this.setPositionForBlock(block, true);\n };\n /**\n * Get document end position\n * @private\n */\n Selection.prototype.getDocumentEnd = function () {\n var textPosition = undefined;\n var documentStart = this.owner.documentStart;\n var lastPage = this.viewer.pages[this.viewer.pages.length - 1];\n if (!isNullOrUndefined(documentStart) && lastPage.bodyWidgets[0].childWidgets.length > 0) {\n var block = undefined;\n var section = lastPage.bodyWidgets[0];\n var blocks = section.childWidgets;\n var lastBlkItem = blocks.length - 1;\n var lastBlock = blocks[lastBlkItem];\n if (lastBlock instanceof BlockWidget) {\n block = lastBlock;\n }\n textPosition = this.setPositionForBlock(block, false);\n }\n return textPosition;\n };\n //Keyboard shortcut internal API\n /**\n * @private\n * Handles control end key.\n */\n Selection.prototype.handleControlEndKey = function () {\n var documentEnd = undefined;\n if (!isNullOrUndefined(this.owner.documentEnd)) {\n documentEnd = this.owner.documentEnd;\n }\n if (!isNullOrUndefined(documentEnd)) {\n this.owner.selection.selectContent(documentEnd, true);\n }\n this.checkForCursorVisibility();\n };\n /**\n * @private\n * Handles control home key.\n */\n Selection.prototype.handleControlHomeKey = function () {\n var documentStart = undefined;\n if (!isNullOrUndefined(this.owner.documentStart)) {\n documentStart = this.owner.documentStart;\n }\n if (!isNullOrUndefined(documentStart)) {\n this.owner.selection.selectContent(documentStart, true);\n }\n this.checkForCursorVisibility();\n };\n /**\n * @private\n * Handles control left key.\n */\n Selection.prototype.handleControlLeftKey = function () {\n this.extendToWordStart(true);\n this.checkForCursorVisibility();\n };\n /**\n * @private\n * Handles control right key.\n */\n Selection.prototype.handleControlRightKey = function () {\n this.extendToWordEnd(true);\n this.checkForCursorVisibility();\n };\n /**\n * Handles control down key.\n * @private\n */\n Selection.prototype.handleControlDownKey = function () {\n this.moveToNextParagraph();\n this.checkForCursorVisibility();\n };\n /**\n * Handles control up key.\n * @private\n */\n Selection.prototype.handleControlUpKey = function () {\n this.moveToPreviousParagraph();\n this.checkForCursorVisibility();\n };\n /**\n * @private\n * Handles shift left key.\n */\n Selection.prototype.handleShiftLeftKey = function () {\n this.extendBackward();\n this.checkForCursorVisibility();\n };\n /**\n * Handles shift up key.\n * @private\n */\n Selection.prototype.handleShiftUpKey = function () {\n this.extendToPreviousLine();\n this.checkForCursorVisibility();\n };\n /**\n * Handles shift right key.\n * @private\n */\n Selection.prototype.handleShiftRightKey = function () {\n this.extendForward();\n this.checkForCursorVisibility();\n };\n /**\n * Handles shift down key.\n * @private\n */\n Selection.prototype.handleShiftDownKey = function () {\n this.extendToNextLine();\n this.checkForCursorVisibility();\n };\n /**\n * @private\n * Handles control shift left key.\n */\n Selection.prototype.handleControlShiftLeftKey = function () {\n this.extendToWordStart(false);\n this.checkForCursorVisibility();\n };\n /**\n * Handles control shift up key.\n * @private\n */\n Selection.prototype.handleControlShiftUpKey = function () {\n this.extendToParagraphStart();\n this.checkForCursorVisibility();\n };\n /**\n * Handles control shift right key\n * @private\n */\n Selection.prototype.handleControlShiftRightKey = function () {\n this.extendToWordEnd(false);\n this.checkForCursorVisibility();\n };\n /**\n * Handles control shift down key.\n * @private\n */\n Selection.prototype.handleControlShiftDownKey = function () {\n this.extendToParagraphEnd();\n this.checkForCursorVisibility();\n };\n /**\n * Handles left key.\n * @private\n */\n Selection.prototype.handleLeftKey = function () {\n this.movePreviousPosition();\n this.checkForCursorVisibility();\n };\n /**\n * Handles up key.\n * @private\n */\n Selection.prototype.handleUpKey = function () {\n this.isMoveDownOrMoveUp = true;\n this.moveUp();\n this.isMoveDownOrMoveUp = false;\n this.checkForCursorVisibility();\n };\n /**\n * Handles right key.\n * @private\n */\n Selection.prototype.handleRightKey = function () {\n this.moveNextPosition();\n this.checkForCursorVisibility();\n };\n /**\n * Handles end key.\n * @private\n */\n Selection.prototype.handleEndKey = function () {\n this.moveToLineEnd();\n this.checkForCursorVisibility();\n };\n /**\n * Handles home key.\n * @private\n */\n Selection.prototype.handleHomeKey = function () {\n this.moveToLineStart();\n this.checkForCursorVisibility();\n };\n /**\n * Handles down key.\n * @private\n */\n Selection.prototype.handleDownKey = function () {\n this.isMoveDownOrMoveUp = true;\n this.moveDown();\n this.isMoveDownOrMoveUp = false;\n this.checkForCursorVisibility();\n };\n /**\n * Handles shift end key.\n * @private\n */\n Selection.prototype.handleShiftEndKey = function () {\n this.extendToLineEnd();\n this.checkForCursorVisibility();\n };\n /**\n * Handles shift home key.\n * @private\n */\n Selection.prototype.handleShiftHomeKey = function () {\n this.extendToLineStart();\n this.checkForCursorVisibility();\n };\n /**\n * Handles control shift end key.\n * @private\n */\n Selection.prototype.handleControlShiftEndKey = function () {\n var documentEnd = undefined;\n if (!isNullOrUndefined(this.owner.documentEnd)) {\n documentEnd = this.owner.documentEnd;\n }\n if (!isNullOrUndefined(documentEnd)) {\n this.end.setPosition(documentEnd.currentWidget, false);\n this.fireSelectionChanged(true);\n }\n this.checkForCursorVisibility();\n };\n /**\n * Handles control shift home key.\n * @private\n */\n Selection.prototype.handleControlShiftHomeKey = function () {\n var documentStart = undefined;\n if (!isNullOrUndefined(this.owner.documentStart)) {\n documentStart = this.owner.documentStart;\n }\n if (!isNullOrUndefined(documentStart)) {\n this.end.setPositionInternal(documentStart);\n this.fireSelectionChanged(true);\n }\n this.checkForCursorVisibility();\n };\n /**\n * Handles tab key.\n * @param isNavigateInCell\n * @param isShiftTab\n * @private\n */\n Selection.prototype.handleTabKey = function (isNavigateInCell, isShiftTab) {\n var start = this.start;\n if (isNullOrUndefined(start)) {\n return;\n }\n if (start.paragraph.isInsideTable && this.end.paragraph.isInsideTable && (isNavigateInCell || isShiftTab)) {\n //Perform tab navigation\n if (isShiftTab) {\n this.selectPreviousCell();\n }\n else {\n this.selectNextCell();\n }\n }\n else if ((isNavigateInCell || isShiftTab) && !isNullOrUndefined(start) && start.offset === this.getStartOffset(start.paragraph)\n && !isNullOrUndefined(start.paragraph.paragraphFormat) && !isNullOrUndefined(start.paragraph.paragraphFormat.listFormat)\n && start.paragraph.paragraphFormat.listFormat.listId !== -1 && !this.owner.isReadOnlyMode) {\n this.owner.editorModule.updateListLevel(isShiftTab ? false : true);\n }\n else if (!this.owner.isReadOnlyMode) {\n this.owner.editorModule.handleTextInput('\\t');\n }\n this.checkForCursorVisibility();\n };\n Selection.prototype.selectPreviousCell = function () {\n var tableCell = this.start.paragraph.associatedCell;\n var tableRow = tableCell.ownerRow;\n var tableAdv = tableRow.ownerTable;\n if (isNullOrUndefined(tableCell.previousWidget)) {\n if (!isNullOrUndefined(tableRow.previousRenderedWidget)) {\n //Move text selection or cursor to previous row's last cell\n var prevRow = undefined;\n if (tableRow.previousRenderedWidget instanceof TableRowWidget) {\n prevRow = tableRow.previousRenderedWidget;\n }\n this.selectTableCellInternal(prevRow.childWidgets[prevRow.childWidgets.length - 1], true);\n }\n }\n else {\n //Move text selection or cursor to next cell in current row\n var prevCell = undefined;\n if (tableCell.previousWidget instanceof TableCellWidget) {\n prevCell = tableCell.previousWidget;\n }\n this.selectTableCellInternal(prevCell, true);\n }\n };\n Selection.prototype.selectNextCell = function () {\n var tableCell = this.start.paragraph.associatedCell;\n var tableRow = tableCell.ownerRow;\n var tableAdv = tableRow.ownerTable;\n if (isNullOrUndefined(tableCell.nextWidget)) {\n if (isNullOrUndefined(tableRow.nextRenderedWidget) && !this.owner.isReadOnlyMode) {\n //Insert new row below \n this.owner.editorModule.insertRow(false);\n }\n else {\n //Move text selection or cursor to next row's first cell\n var nextRow = undefined;\n if (tableRow.nextRenderedWidget instanceof TableRowWidget) {\n nextRow = tableRow.nextRenderedWidget;\n }\n this.selectTableCellInternal(nextRow.childWidgets[0], true);\n }\n // }\n }\n else {\n //Move text selection or cursor to next cell in current row\n var nextCell = undefined;\n if (tableCell.nextRenderedWidget instanceof TableCellWidget) {\n nextCell = tableCell.nextRenderedWidget;\n }\n this.selectTableCellInternal(nextCell, true);\n }\n };\n /**\n * Select given table cell\n * @private\n */\n Selection.prototype.selectTableCellInternal = function (tableCell, clearMultiSelection) {\n var firstParagraph = this.getFirstParagraph(tableCell);\n var lastParagraph = this.getLastParagraph(tableCell);\n if (firstParagraph === lastParagraph && lastParagraph.isEmpty()) {\n this.selectParagraph(lastParagraph, true);\n }\n else {\n var firstLineWidget = lastParagraph.childWidgets[0];\n this.start.setPosition(firstParagraph.childWidgets[0], true);\n this.end.setPositionParagraph(firstLineWidget, firstLineWidget.getEndOffset());\n this.fireSelectionChanged(true);\n }\n };\n /**\n * Select while table\n * @private\n */\n Selection.prototype.selectTableInternal = function () {\n var start = this.start;\n var end = this.end;\n if (!this.isForward) {\n start = this.end;\n end = this.start;\n }\n if (!isNullOrUndefined(start) && !isNullOrUndefined(end) && !isNullOrUndefined(this.getTable(start, end))) {\n var containerCell = this.getContainerCellOf(start.paragraph.associatedCell, end.paragraph.associatedCell);\n var table = containerCell.ownerTable;\n var firstPara = this.getFirstParagraphBlock(table);\n var lastPara = this.getLastParagraphBlock(table);\n var offset = lastPara.lastChild.getEndOffset();\n this.start.setPosition(firstPara.childWidgets[0], true);\n this.end.setPositionParagraph(lastPara.lastChild, offset + 1);\n }\n this.selectPosition(this.start, this.end);\n };\n /**\n * Select single column\n * @private\n */\n Selection.prototype.selectColumnInternal = function () {\n var startTextPos = this.start;\n var endTextPos = this.end;\n if (!this.isForward) {\n startTextPos = this.end;\n endTextPos = this.start;\n }\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(startTextPos) && !isNullOrUndefined(endTextPos) && !isNullOrUndefined(this.getTable(startTextPos, endTextPos))) {\n var containerCell = this.getContainerCellOf(startTextPos.paragraph.associatedCell, endTextPos.paragraph.associatedCell);\n if (containerCell.ownerTable.contains(endTextPos.paragraph.associatedCell)) {\n var startCell = this.getSelectedCell(startTextPos.paragraph.associatedCell, containerCell);\n var endCell = this.getSelectedCell(endTextPos.paragraph.associatedCell, containerCell);\n if (this.containsCell(containerCell, endTextPos.paragraph.associatedCell)) {\n var row = startCell.ownerRow;\n var columnCells = containerCell.ownerTable.getColumnCellsForSelection(containerCell, containerCell);\n if (columnCells.length > 0) {\n var firstPara = this.getFirstParagraph(columnCells[0]);\n var lastPara = this.getLastParagraph(columnCells[columnCells.length - 1]);\n this.start.setPosition(firstPara.firstChild, true);\n var lastLine = lastPara.lastChild;\n this.end.setPositionParagraph(lastLine, lastLine.getEndOffset() + 1);\n }\n }\n else {\n var startCellColumnCells = containerCell.ownerTable.getColumnCellsForSelection(startCell, startCell);\n var endCellColumnCells = containerCell.ownerTable.getColumnCellsForSelection(endCell, endCell);\n if (startCellColumnCells.length > 0 && endCellColumnCells.length > 0) {\n var firstPara = this.getFirstParagraph(startCellColumnCells[0]);\n // tslint:disable-next-line:max-line-length\n var lastPara = this.getLastParagraph(endCellColumnCells[endCellColumnCells.length - 1]);\n this.start.setPosition(firstPara.firstChild, true);\n var lastLine = lastPara.lastChild;\n this.end.setPositionParagraph(lastLine, lastLine.getEndOffset() + 1);\n }\n }\n }\n }\n this.selectPosition(this.start, this.end);\n };\n /**\n * Select single row\n * @private\n */\n Selection.prototype.selectTableRow = function () {\n var startPos = this.start;\n var endPos = this.end;\n if (!this.isForward) {\n startPos = this.end;\n endPos = this.start;\n }\n if (!isNullOrUndefined(startPos) && !isNullOrUndefined(endPos) && !isNullOrUndefined(this.getTable(startPos, endPos))) {\n var containerCell = void 0;\n containerCell = this.getContainerCellOf(startPos.paragraph.associatedCell, endPos.paragraph.associatedCell);\n if (containerCell.ownerTable.contains(endPos.paragraph.associatedCell)) {\n var startCell = this.getSelectedCell(startPos.paragraph.associatedCell, containerCell);\n var endCell = this.getSelectedCell(endPos.paragraph.associatedCell, containerCell);\n if (this.containsCell(containerCell, endPos.paragraph.associatedCell)) {\n var row = startCell.ownerRow;\n var firstPara = this.getFirstParagraph(row.childWidgets[0]);\n var lastPara = this.getLastParagraph(row.childWidgets[row.childWidgets.length - 1]);\n this.start.setPosition(firstPara.firstChild, true);\n this.end.setPositionParagraph(lastPara.lastChild, lastPara.lastChild.getEndOffset() + 1);\n }\n else {\n var firstPara = this.getFirstParagraph(startCell.ownerRow.childWidgets[0]);\n var lastPara = void 0;\n // tslint:disable-next-line:max-line-length\n lastPara = this.getLastParagraph(endCell.ownerRow.childWidgets[endCell.ownerRow.childWidgets.length - 1]);\n this.start.setPosition(firstPara.firstChild, true);\n this.end.setPositionParagraph(lastPara.lastChild, lastPara.lastChild.getEndOffset() + 1);\n }\n }\n }\n this.selectPosition(this.start, this.end);\n };\n /**\n * Select single cell\n * @private\n */\n Selection.prototype.selectTableCell = function () {\n var start = this.start;\n var end = this.end;\n if (!this.isForward) {\n start = this.end;\n end = this.start;\n }\n if (isNullOrUndefined(this.getTable(start, end))) {\n return;\n }\n if (this.isEmpty) {\n if (start.paragraph.isInsideTable && !isNullOrUndefined(start.paragraph.associatedCell)) {\n var firstPara = this.getFirstParagraph(start.paragraph.associatedCell);\n var lastPara = this.getLastParagraph(end.paragraph.associatedCell);\n if (firstPara === lastPara) {\n this.start.setPosition(lastPara.firstChild, true);\n this.end.setPositionParagraph(lastPara.lastChild, lastPara.lastChild.getEndOffset() + 1);\n }\n else {\n this.start.setPosition(firstPara.firstChild, true);\n this.end.setPositionParagraph(lastPara.lastChild, lastPara.lastChild.getEndOffset() + 1);\n }\n }\n }\n else {\n var containerCell = this.getContainerCell(start.paragraph.associatedCell);\n // tslint:disable-next-line:max-line-length\n if (this.containsCell(containerCell, start.paragraph.associatedCell) && this.containsCell(containerCell, end.paragraph.associatedCell)) {\n var firstPara = this.getFirstParagraph(containerCell);\n var lastPara = this.getLastParagraph(containerCell);\n if (!isNullOrUndefined(firstPara) && !isNullOrUndefined(lastPara)) {\n this.start.setPosition(firstPara.firstChild, true);\n this.end.setPositionParagraph(lastPara.lastChild, lastPara.lastChild.getEndOffset() + 1);\n }\n }\n }\n this.selectPosition(this.start, this.end);\n };\n /**\n * @private\n * Selects the entire document.\n */\n Selection.prototype.selectAll = function () {\n var documentStart;\n var documentEnd;\n if (this.owner.enableHeaderAndFooter) {\n var headerFooter = this.getContainerWidget(this.start.paragraph);\n documentStart = this.setPositionForBlock(headerFooter.firstChild, true);\n documentEnd = this.setPositionForBlock(headerFooter.lastChild, false);\n }\n else {\n documentStart = this.owner.documentStart;\n documentEnd = this.owner.documentEnd;\n }\n //Selects the entire document. \n if (!isNullOrUndefined(documentStart)) {\n this.start.setPositionInternal(documentStart);\n this.end.setPositionParagraph(documentEnd.currentWidget, documentEnd.offset + 1);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n }\n };\n /**\n * Extend selection backward\n * @private\n */\n Selection.prototype.extendBackward = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveBackward();\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Extent selection forward\n * @private\n */\n Selection.prototype.extendForward = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveForward();\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Extend selection to word start and end\n * @private\n */\n Selection.prototype.extendToWordStartEnd = function () {\n if ((this.start.paragraph.isInsideTable || this.end.paragraph.isInsideTable)\n && (this.start.paragraph.associatedCell !== this.end.paragraph.associatedCell\n || this.isCellSelected(this.start.paragraph.associatedCell, this.start, this.end))) {\n return true;\n }\n return false;\n };\n /**\n * Extend selection to word start\n * @private\n */\n Selection.prototype.extendToWordStart = function (isNavigation) {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n var isCellSelected = this.extendToWordStartEnd();\n if (isCellSelected) {\n this.end.moveToPreviousParagraphInTable(this);\n }\n else {\n this.end.moveToWordStartInternal(isNavigation ? 0 : 1);\n }\n if (isNavigation) {\n this.start.setPositionInternal(this.end);\n }\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Extent selection to word end\n * @private\n */\n Selection.prototype.extendToWordEnd = function (isNavigation) {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n var isCellSelect = this.extendToWordStartEnd();\n if (isCellSelect) {\n this.end.moveToNextParagraphInTable();\n }\n else {\n this.end.moveToWordEndInternal(isNavigation ? 0 : 1, false);\n }\n if (isNavigation) {\n this.start.setPositionInternal(this.end);\n }\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Extend selection to next line\n * @private\n */\n Selection.prototype.extendToNextLine = function () {\n if (isNullOrUndefined(this.start)) {\n return;\n }\n this.end.moveToNextLine(this.upDownSelectionLength);\n this.fireSelectionChanged(true);\n };\n //Selection Text get API\n //Selection add, Highlight, remove API enda\n Selection.prototype.getTextPosition = function (hierarchicalIndex) {\n var textPosition = new TextPosition(this.owner);\n textPosition.setPositionForCurrentIndex(hierarchicalIndex);\n return textPosition;\n };\n /**\n * Get Selected text\n * @private\n */\n Selection.prototype.getText = function (includeObject) {\n if (isNullOrUndefined(this.start) || isNullOrUndefined(this.end)\n || isNullOrUndefined(this.start.paragraph) || isNullOrUndefined(this.end.paragraph)) {\n return undefined;\n }\n var startPosition = this.start;\n var endPosition = this.end;\n if (startPosition.isAtSamePosition(endPosition)) {\n return '';\n }\n return this.getTextInternal(startPosition, endPosition, includeObject);\n };\n /**\n * Get selected text\n * @private\n */\n Selection.prototype.getTextInternal = function (start, end, includeObject) {\n if (start.isExistAfter(end)) {\n var temp = end;\n end = start;\n start = temp;\n }\n var startPosition = start;\n var endPosition = end;\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(start) && !isNullOrUndefined(end) && !isNullOrUndefined(start.paragraph) && !isNullOrUndefined(end.paragraph)) {\n var startIndex = 0;\n var endIndex = 0;\n var startOffset = start.offset;\n var endOffset = end.offset;\n var startInlineObj = start.currentWidget.getInline(startOffset, startIndex);\n startIndex = startInlineObj.index;\n var inline = startInlineObj.element;\n // If the start position is at the beginning of field begin that has field end, then field code should be skipped.\n if (inline instanceof FieldElementBox && !isNullOrUndefined(inline.fieldEnd)) {\n var elementInfo = this.getRenderedInline(inline, startIndex);\n inline = elementInfo.element;\n startIndex = elementInfo.index;\n }\n var endInlineObj = end.currentWidget.getInline(endOffset, endIndex);\n var endInline = endInlineObj.element;\n endIndex = endInlineObj.index;\n var text = '';\n // Retrieves the text from start inline.\n if (inline instanceof ImageElementBox && includeObject && startIndex === 0) {\n text = ElementBox.objectCharacter;\n }\n else if (inline instanceof TextElementBox) {\n // tslint:disable-next-line:max-line-length\n text = ((isNullOrUndefined(inline.text)) || (inline.text) === '') || inline.text.length < startIndex ? text : inline.text.substring(startIndex);\n }\n if (startPosition.paragraph === endPosition.paragraph) {\n if (inline instanceof ElementBox) {\n if (inline === endInline && inline instanceof TextElementBox) {\n text = text.length < endIndex - startIndex ? text : text.substring(0, endIndex - startIndex);\n }\n else if (inline.nextNode instanceof ElementBox) {\n // tslint:disable-next-line:max-line-length\n text = text + this.getTextInline(inline.nextNode, endPosition.paragraph, endInline, endIndex, includeObject);\n }\n }\n }\n else {\n if (inline instanceof ElementBox && inline.nextNode instanceof ElementBox) {\n text = text + this.getTextInline(inline.nextNode, endPosition.paragraph, undefined, 0, includeObject);\n }\n else {\n // tslint:disable-next-line:max-line-length\n var nextParagraphWidget = this.viewer.selection.getNextParagraphBlock(startPosition.paragraph);\n text = text + '\\r';\n while (!isNullOrUndefined(nextParagraphWidget) && nextParagraphWidget.isEmpty()) {\n text = text + '\\r';\n if (nextParagraphWidget === endPosition.paragraph) {\n return text;\n }\n nextParagraphWidget = this.viewer.selection.getNextParagraphBlock(nextParagraphWidget);\n }\n if (!isNullOrUndefined(nextParagraphWidget) && !nextParagraphWidget.isEmpty()) {\n // tslint:disable-next-line:max-line-length\n text = text + this.getTextInline(nextParagraphWidget.childWidgets[0].children[0], endPosition.paragraph, endInline, endIndex, includeObject);\n }\n }\n }\n // If the selection includes end paragraph mark.\n if (endOffset === (endPosition.currentWidget).getEndOffset() + 1) {\n text = text + '\\r';\n }\n return text;\n }\n return undefined;\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getTextInline = function (inlineElement, endParagraphWidget, endInline, endIndex, includeObject) {\n var text = '';\n do {\n if (inlineElement === endInline) {\n if (inlineElement instanceof TextElementBox) {\n var span = inlineElement;\n if (!(isNullOrUndefined(span.text) || span.text === '')) {\n if (span.text.length < endIndex) {\n text = text + span.text;\n }\n else {\n text = text + span.text.substring(0, endIndex);\n }\n }\n // tslint:disable-next-line:max-line-length\n }\n else if (inlineElement instanceof ImageElementBox && includeObject && endIndex === inlineElement.length) {\n text = text + ElementBox.objectCharacter;\n }\n return text;\n }\n if (inlineElement instanceof TextElementBox) {\n text = text + inlineElement.text;\n }\n else if (inlineElement instanceof ImageElementBox && includeObject) {\n text = text + ElementBox.objectCharacter;\n }\n else if (inlineElement instanceof FieldElementBox && !isNullOrUndefined(inlineElement.fieldEnd)) {\n if (!isNullOrUndefined(inlineElement.fieldSeparator)) {\n inlineElement = inlineElement.fieldSeparator;\n }\n else {\n inlineElement = inlineElement.fieldEnd;\n }\n }\n if (isNullOrUndefined(inlineElement.nextNode)) {\n break;\n }\n inlineElement = inlineElement.nextNode;\n } while (!isNullOrUndefined(inlineElement));\n if (endParagraphWidget === inlineElement.line.paragraph) {\n return text;\n }\n // tslint:disable-next-line:max-line-length\n var nextParagraphWidget = this.viewer.selection.getNextParagraphBlock(inlineElement.line.paragraph);\n while (!isNullOrUndefined(nextParagraphWidget) && nextParagraphWidget.isEmpty()) {\n text = text + '\\r';\n if (nextParagraphWidget === endParagraphWidget) {\n return text;\n }\n nextParagraphWidget = this.viewer.selection.getNextParagraphBlock(nextParagraphWidget);\n }\n if (!isNullOrUndefined(nextParagraphWidget) && !nextParagraphWidget.isEmpty()) {\n var lineWidget = nextParagraphWidget.childWidgets[0];\n // tslint:disable-next-line:max-line-length\n text = text + '\\r' + this.getTextInline(lineWidget.children[0], endParagraphWidget, endInline, endIndex, includeObject);\n }\n return text;\n };\n /**\n * Returns field code.\n * @private\n * @param fieldBegin\n */\n Selection.prototype.getFieldCode = function (fieldBegin) {\n var fieldCode = '';\n if (!(fieldBegin.fieldEnd instanceof FieldElementBox)) {\n return fieldCode;\n }\n var paragraph = fieldBegin.paragraph;\n var endParagraph = fieldBegin.fieldEnd.paragraph;\n if (fieldBegin.fieldSeparator instanceof FieldElementBox) {\n endParagraph = fieldBegin.fieldSeparator.paragraph;\n }\n var startLineIndex = fieldBegin.line.indexInOwner;\n var startIndex = fieldBegin.indexInOwner;\n do {\n fieldCode += this.getFieldCodeInternal(paragraph, startLineIndex, startIndex);\n if (paragraph === endParagraph) {\n break;\n }\n paragraph = this.getNextParagraphBlock(paragraph);\n startLineIndex = 0;\n startIndex = 0;\n } while (paragraph instanceof ParagraphWidget);\n return fieldCode.trim();\n };\n Selection.prototype.getFieldCodeInternal = function (paragraph, startLineIndex, inlineIndex) {\n var fieldCode = '';\n for (var i = startLineIndex; i < paragraph.childWidgets.length; i++) {\n var line = paragraph.childWidgets[i];\n for (var i_1 = inlineIndex; i_1 < line.children.length; i_1++) {\n var element = line.children[i_1];\n if (element instanceof TextElementBox) {\n fieldCode += element.text;\n }\n if (element instanceof FieldElementBox\n && (element.fieldType === 2 || element.fieldType === 1)) {\n return fieldCode;\n }\n }\n inlineIndex = 0;\n }\n return fieldCode;\n };\n /**\n * @private\n */\n Selection.prototype.getTocFieldInternal = function () {\n var paragraph = this.start.paragraph;\n if (!this.isEmpty && !this.isForward) {\n paragraph = this.end.paragraph;\n }\n while (paragraph instanceof ParagraphWidget && paragraph.childWidgets.length > 0) {\n var line = paragraph.firstChild;\n if (line.children.length > 0) {\n var element = line.children[0];\n var nextElement = element.nextNode;\n if (element instanceof FieldElementBox && element.fieldType === 0 && nextElement instanceof TextElementBox\n && nextElement.text.trim().toLowerCase().indexOf('toc') === 0) {\n return element;\n }\n }\n paragraph = paragraph.previousRenderedWidget;\n }\n return undefined;\n };\n /**\n * Get next paragraph in bodyWidget\n * @private\n */\n Selection.prototype.getNextParagraph = function (section) {\n if (section.nextRenderedWidget instanceof BodyWidget) {\n var block = section.nextRenderedWidget.childWidgets[0];\n return this.getFirstParagraphBlock(block);\n }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.getPreviousParagraph = function (section) {\n if (section.previousRenderedWidget instanceof BodyWidget) {\n var bodyWidget = section.previousRenderedWidget;\n var block = bodyWidget.childWidgets[bodyWidget.childWidgets.length - 1];\n return this.getLastParagraphBlock(block);\n }\n return undefined;\n };\n /**\n * Get first paragraph in cell\n * @private\n */\n Selection.prototype.getFirstParagraphInCell = function (cell) {\n var firstBlock = cell.childWidgets[0];\n if (firstBlock instanceof ParagraphWidget) {\n return firstBlock;\n }\n else {\n return this.getFirstParagraphInFirstCell(firstBlock);\n }\n };\n /**\n * Get first paragraph in first cell\n * @private\n */\n Selection.prototype.getFirstParagraphInFirstCell = function (table) {\n if (table.childWidgets.length > 0) {\n var firstRow = table.childWidgets[0];\n var cell = firstRow.childWidgets[0];\n var block = cell.childWidgets[0];\n return this.getFirstParagraphBlock(block);\n }\n return undefined;\n };\n /**\n * Get last paragraph in last cell\n * @private\n */\n Selection.prototype.getLastParagraphInLastCell = function (table) {\n if (table.childWidgets.length > 0) {\n var lastrow = table.lastChild;\n var lastcell = lastrow.lastChild;\n var lastBlock = lastcell.lastChild;\n return this.getLastParagraphBlock(lastBlock);\n }\n return undefined;\n };\n /**\n * Get last paragraph in first row\n * @private\n */\n Selection.prototype.getLastParagraphInFirstRow = function (table) {\n if (table.childWidgets.length > 0) {\n var row = table.firstChild;\n var lastcell = row.lastChild;\n var lastBlock = lastcell.lastChild;\n return this.getLastParagraphBlock(lastBlock);\n }\n return undefined;\n };\n /**\n * Get Next start inline\n * @private\n */\n Selection.prototype.getNextStartInline = function (line, offset) {\n var indexInInline = 0;\n var inlineObj = line.getInline(offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!isNullOrUndefined(inline) && indexInInline === inline.length && inline.nextNode instanceof FieldElementBox) {\n var nextValidInline = this.getNextValidElement(inline.nextNode);\n if (nextValidInline instanceof FieldElementBox && nextValidInline.fieldType === 0) {\n inline = nextValidInline;\n }\n }\n return inline;\n };\n /**\n * Get previous text inline\n * @private\n */\n Selection.prototype.getPreviousTextInline = function (inline) {\n if (inline.previousNode instanceof TextElementBox) {\n return inline.previousNode;\n }\n if (inline.previousNode instanceof FieldElementBox && HelperMethods.isLinkedFieldCharacter(inline.previousNode)) {\n if (inline.previousNode.fieldType === 0 || inline.previousNode.fieldType === 1) {\n return inline.previousNode;\n }\n return inline.previousNode.fieldBegin;\n }\n if (!isNullOrUndefined(inline.previousNode)) {\n return this.getPreviousTextInline((inline.previousNode));\n }\n return undefined;\n };\n /**\n * Get next text inline\n * @private\n */\n Selection.prototype.getNextTextInline = function (inline) {\n if (inline.nextNode instanceof TextElementBox) {\n return inline.nextNode;\n }\n if (inline.nextNode instanceof FieldElementBox && (HelperMethods.isLinkedFieldCharacter(inline.nextNode))) {\n if (inline.nextNode.fieldType === 1 || inline.nextNode.fieldType === 0) {\n return inline.nextNode;\n }\n return inline.nextNode.fieldEnd;\n }\n if (!isNullOrUndefined(inline.nextNode)) {\n return this.getNextTextInline((inline.nextNode));\n }\n return undefined;\n };\n /**\n * Get container table\n * @private\n */\n Selection.prototype.getContainerTable = function (block) {\n if (block.isInsideTable) {\n if (block.associatedCell.ownerTable.isInsideTable) {\n block = this.getContainerTable(block.associatedCell.ownerTable);\n }\n else {\n block = block.associatedCell.ownerTable;\n }\n }\n if (block instanceof TableWidget) {\n return block;\n }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.isExistBefore = function (start, block) {\n if (start.isInsideTable) {\n var cell1 = start.associatedCell;\n if (block.isInsideTable) {\n var cell2 = block.associatedCell;\n if (cell1 === cell2) {\n return cell1.childWidgets.indexOf(start) < cell1.childWidgets.indexOf(block);\n }\n if (cell1.ownerRow === cell2.ownerRow) {\n return cell1.cellIndex < cell2.cellIndex;\n }\n if (cell1.ownerTable === cell2.ownerTable) {\n return cell1.ownerRow.rowIndex < cell2.ownerRow.rowIndex;\n }\n //Checks if current block exists before the block.\n var containerCell = this.getContainerCellOf(cell1, cell2);\n if (containerCell.ownerTable.contains(cell2)) {\n cell1 = this.getSelectedCell(cell1, containerCell);\n cell2 = this.getSelectedCell(cell2, containerCell);\n if (cell1 === containerCell) {\n return this.isExistBefore(start, cell2.ownerTable);\n }\n if (cell2 === containerCell) {\n return this.isExistBefore(cell1.ownerTable, block);\n }\n if (containerCell.ownerRow === cell2.ownerRow) {\n return containerCell.cellIndex < cell2.cellIndex;\n }\n if (containerCell.ownerTable === cell2.ownerTable) {\n return containerCell.ownerRow.rowIndex < cell2.ownerRow.rowIndex;\n }\n return this.isExistBefore(cell1.ownerTable, cell2.ownerTable);\n }\n return this.isExistBefore(containerCell.ownerTable, this.getContainerTable(cell2.ownerTable));\n }\n else {\n var ownerTable = this.getContainerTable(start);\n return this.isExistBefore(ownerTable, block);\n }\n }\n else if (block.isInsideTable) {\n var ownerTable = this.getContainerTable(block);\n return this.isExistBefore(start, ownerTable);\n }\n else {\n {\n if (start.containerWidget === block.containerWidget) {\n return start.index <\n block.index;\n }\n if (start.containerWidget instanceof BodyWidget && block.containerWidget instanceof BodyWidget) {\n //Splitted blocks \n var startPage = this.viewer.pages.indexOf(start.containerWidget.page);\n var endPage = this.viewer.pages.indexOf(block.containerWidget.page);\n return startPage < endPage;\n }\n }\n }\n return false;\n };\n /**\n * @private\n */\n Selection.prototype.isExistAfter = function (start, block) {\n if (start.isInsideTable) {\n var cell1 = start.associatedCell;\n //Current paragraph in cell, paragraph in cell\n if (block.isInsideTable) {\n var cell2 = block.associatedCell;\n if (cell1 === cell2) {\n return cell1.childWidgets.indexOf(start) > cell1.childWidgets.indexOf(block);\n }\n if (cell1.ownerRow === cell2.ownerRow) {\n return cell1.cellIndex > cell2.cellIndex;\n }\n if (cell1.ownerTable === cell2.ownerTable) {\n return cell1.ownerRow.rowIndex > cell2.ownerRow.rowIndex;\n }\n //Checks if this block exists before block.\n var containerCell = this.getContainerCellOf(cell1, cell2);\n if (containerCell.ownerTable.contains(cell2)) {\n cell1 = this.getSelectedCell(cell1, containerCell);\n cell2 = this.getSelectedCell(cell2, containerCell);\n if (cell1 === containerCell) {\n return this.isExistAfter(start, cell2.ownerTable);\n }\n if (cell2 === containerCell) {\n return this.isExistAfter(cell1.ownerTable, block);\n }\n if (containerCell.ownerRow === cell2.ownerRow) {\n return containerCell.cellIndex > cell2.cellIndex;\n }\n if (containerCell.ownerTable === cell2.ownerTable) {\n return containerCell.ownerRow.rowIndex > cell2.ownerRow.rowIndex;\n }\n return this.isExistAfter(cell1.ownerTable, cell2.ownerTable);\n }\n return this.isExistAfter(containerCell.ownerTable, this.getContainerTable(cell2.ownerTable));\n }\n else {\n var ownerTable = this.getContainerTable(start);\n return this.isExistAfter(ownerTable, block);\n }\n }\n else if (block.isInsideTable) {\n var ownerTable = this.getContainerTable(block);\n return this.isExistAfter(start, ownerTable);\n }\n else {\n if (start.containerWidget === block.containerWidget) {\n return start.index >\n block.index;\n }\n if (start.containerWidget instanceof BodyWidget && block.containerWidget instanceof BodyWidget) {\n //Splitted blocks \n var startPage = this.viewer.pages.indexOf(start.containerWidget.page);\n var endPage = this.viewer.pages.indexOf(block.containerWidget.page);\n return startPage > endPage;\n }\n // if (start.owner instanceof WHeaderFooter) {\n // return (start.owner as WHeaderFooter).childWidgets.indexOf(start) \n // > (block.owner as WHeaderFooter).childWidgets.indexOf(block);\n // } else if (start.section === block.section && start.section instanceof WSection) {\n // return (start.section as WSection).childWidgets.indexOf(start)\n // > (start.section as WSection).childWidgets.indexOf(block);\n // } else if (start.wordDocument instanceof WordDocument) {\n // tslint:disable-next-line:max-line-length\n // return (start.wordDocument as WordDocument).sections.indexOf(start.section as WSection) > (start.wordDocument as WordDocument).sections.indexOf(block.section as WSection);\n }\n return false;\n };\n /**\n * Return true if current inline in exist before inline\n * @private\n */\n Selection.prototype.isExistBeforeInline = function (currentInline, inline) {\n if (currentInline.line === inline.line) {\n return currentInline.line.children.indexOf(currentInline) <\n inline.line.children.indexOf(inline);\n }\n if (currentInline.line.paragraph === inline.line.paragraph) {\n return currentInline.line.paragraph.childWidgets.indexOf(currentInline.line)\n < inline.line.paragraph.childWidgets.indexOf(inline.line);\n }\n var startParagraph = currentInline.line.paragraph;\n var endParagraph = inline.line.paragraph;\n if (startParagraph.containerWidget === endParagraph.containerWidget) {\n if (startParagraph.isInsideTable) {\n return startParagraph.associatedCell.childWidgets.indexOf(startParagraph) <\n endParagraph.associatedCell.childWidgets.indexOf(endParagraph);\n }\n else if (startParagraph.containerWidget instanceof HeaderFooterWidget) {\n // return ((currentInline.owner as WParagraph).owner as WHeaderFooter).blocks.indexOf(currentInline.owner as WParagraph) <\n // ((inline.owner as WParagraph).owner as WHeaderFooter).blocks.indexOf(inline.owner as WParagraph);\n }\n else {\n return startParagraph.containerWidget.childWidgets.indexOf(startParagraph) <\n endParagraph.containerWidget.childWidgets.indexOf(endParagraph);\n }\n }\n return this.isExistBefore(startParagraph, endParagraph);\n };\n /**\n * Return true id current inline is exist after inline\n * @private\n */\n Selection.prototype.isExistAfterInline = function (currentInline, inline) {\n if (currentInline.line === inline.line) {\n return currentInline.line.children.indexOf(currentInline) >\n inline.line.children.indexOf(inline);\n }\n if (currentInline.line.paragraph === inline.line.paragraph) {\n return currentInline.line.paragraph.childWidgets.indexOf(currentInline.line)\n > inline.line.paragraph.childWidgets.indexOf(inline.line);\n }\n var startParagraph = currentInline.line.paragraph;\n var endParagraph = inline.line.paragraph;\n if (startParagraph.containerWidget === endParagraph.containerWidget) {\n if (startParagraph.isInsideTable) {\n return startParagraph.associatedCell.childWidgets.indexOf(startParagraph) >\n endParagraph.associatedCell.childWidgets.indexOf(endParagraph);\n }\n else if (startParagraph.containerWidget instanceof HeaderFooterWidget) {\n // return ((currentInline.owner as WParagraph).owner as WHeaderFooter).blocks.indexOf(currentInline.owner as WParagraph) <\n // ((inline.owner as WParagraph).owner as WHeaderFooter).blocks.indexOf(inline.owner as WParagraph);\n }\n else {\n return startParagraph.containerWidget.childWidgets.indexOf(startParagraph) >\n endParagraph.containerWidget.childWidgets.indexOf(endParagraph);\n }\n }\n return this.isExistAfter(startParagraph, endParagraph);\n };\n /**\n * Get next rendered block\n * @private\n */\n Selection.prototype.getNextRenderedBlock = function (block) {\n if (isNullOrUndefined(block.nextWidget)) {\n return block.nextRenderedWidget;\n }\n return block.nextWidget;\n };\n /**\n * Get next rendered block\n * @private\n */\n Selection.prototype.getPreviousRenderedBlock = function (block) {\n if (isNullOrUndefined(block.previousWidget)) {\n return block.previousRenderedWidget;\n }\n return block.previousWidget;\n };\n /**\n * Get Next paragraph in block\n * @private\n */\n Selection.prototype.getNextParagraphBlock = function (block) {\n if (block.nextRenderedWidget instanceof ParagraphWidget) {\n return block.nextRenderedWidget;\n }\n else if (block.nextRenderedWidget instanceof TableWidget) {\n return this.getFirstParagraphInFirstCell(block.nextRenderedWidget);\n }\n if (block.containerWidget instanceof TableCellWidget) {\n return this.getNextParagraphCell(block.containerWidget);\n }\n else if (block.containerWidget instanceof BodyWidget) {\n var bodyWidget = block.containerWidget;\n return this.getNextParagraph(block.containerWidget);\n }\n else if (block.containerWidget instanceof HeaderFooterWidget && this.isMoveDownOrMoveUp) {\n return this.getFirstBlockInNextHeaderFooter(block);\n }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.getFirstBlockInNextHeaderFooter = function (block) {\n var headerFooter = block.containerWidget;\n var nextBlock;\n if (headerFooter.headerFooterType.indexOf('Header') !== -1) {\n nextBlock = headerFooter.page.footerWidget.firstChild;\n }\n else if (headerFooter.page.nextPage) {\n nextBlock = headerFooter.page.nextPage.headerWidget.firstChild;\n }\n else {\n return undefined;\n }\n if (nextBlock instanceof ParagraphWidget) {\n return nextBlock;\n }\n else {\n return this.getFirstBlockInFirstCell(nextBlock);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getLastBlockInPreviousHeaderFooter = function (block) {\n var headerFooter = block.containerWidget;\n var previousBlock;\n if (headerFooter.headerFooterType.indexOf('Footer') !== -1) {\n previousBlock = headerFooter.page.headerWidget.lastChild;\n }\n else if (headerFooter.page.previousPage) {\n previousBlock = headerFooter.page.previousPage.footerWidget.lastChild;\n }\n else {\n return undefined;\n }\n if (previousBlock instanceof ParagraphWidget) {\n return previousBlock;\n }\n else {\n return this.getFirstBlockInFirstCell(previousBlock);\n }\n };\n /**\n * Get previous paragraph in block\n * @private\n */\n Selection.prototype.getPreviousParagraphBlock = function (block) {\n if (block.previousRenderedWidget instanceof ParagraphWidget) {\n return block.previousRenderedWidget;\n }\n else if (block.previousRenderedWidget instanceof TableWidget) {\n return this.getLastParagraphInLastCell((block.previousRenderedWidget));\n }\n if (block.containerWidget instanceof TableCellWidget) {\n return this.getPreviousParagraphCell((block.containerWidget));\n }\n else if (block.containerWidget instanceof BodyWidget) {\n return this.getPreviousParagraph(block.containerWidget);\n }\n else if (block.containerWidget instanceof HeaderFooterWidget && this.isMoveDownOrMoveUp) {\n return this.getLastBlockInPreviousHeaderFooter(block);\n }\n return undefined;\n };\n /**\n * Get first paragraph in block\n * @private\n */\n Selection.prototype.getFirstParagraphBlock = function (block) {\n if (block instanceof ParagraphWidget) {\n return block;\n }\n else if (block instanceof TableWidget) {\n return this.getFirstParagraphInFirstCell(block);\n }\n return undefined;\n };\n /**\n * Get last paragraph in block\n * @private\n */\n Selection.prototype.getLastParagraphBlock = function (block) {\n if (block instanceof ParagraphWidget) {\n return block;\n }\n else if (block instanceof TableWidget) {\n return this.getLastParagraphInLastCell(block);\n }\n return undefined;\n };\n /**\n * Return true if paragraph has valid inline\n * @private\n */\n Selection.prototype.hasValidInline = function (paragraph, start, end) {\n var index = paragraph.childWidgets.indexOf(start.line);\n for (var i = index; i < paragraph.childWidgets.length; i++) {\n for (var j = 0; j < paragraph.childWidgets[i].children.length; j++) {\n var inline = paragraph.childWidgets[i].children[j];\n if (inline.length === 0) {\n continue;\n }\n if (inline === end) {\n return false;\n }\n if (inline instanceof TextElementBox || inline instanceof ImageElementBox\n || (inline instanceof FieldElementBox && HelperMethods.isLinkedFieldCharacter(inline))) {\n return true;\n }\n }\n }\n return false;\n };\n /**\n * Get paragraph length\n * @private\n */\n Selection.prototype.getParagraphLength = function (paragraph, endLine, elementInfo) {\n var length = 0;\n for (var j = 0; j < paragraph.childWidgets.length; j++) {\n var line = paragraph.childWidgets[j];\n if (endLine instanceof LineWidget && endLine === line) {\n if (elementInfo) {\n length += this.getLineLength(line, elementInfo);\n }\n break;\n }\n length += this.getLineLength(line);\n }\n return length;\n };\n /**\n * Get Line length\n * @private\n */\n Selection.prototype.getLineLength = function (line, elementInfo) {\n var length = 0;\n for (var i = 0; i < line.children.length; i++) {\n var element = line.children[i];\n if (element instanceof ListTextElementBox) {\n continue;\n }\n if (elementInfo && elementInfo.element instanceof ElementBox && elementInfo.element === element) {\n length += elementInfo.index;\n break;\n }\n length += element.length;\n }\n return length;\n };\n /**\n * Get line information\n * @private\n */\n Selection.prototype.getLineInfo = function (paragraph, offset) {\n var line = undefined;\n var length = 0;\n var childLength = paragraph.childWidgets.length;\n for (var j = 0; j < childLength; j++) {\n line = paragraph.childWidgets[j];\n length = this.getLineLength(line);\n if (offset <= length || j === childLength - 1) {\n break;\n }\n else {\n offset = offset - length;\n }\n }\n return { 'line': line, 'offset': offset };\n };\n /**\n * @private\n */\n Selection.prototype.getElementInfo = function (line, offset) {\n var index = 0;\n var element = undefined;\n for (var i = 0; i < line.children.length; i++) {\n element = line.children[i];\n if (element instanceof ListTextElementBox) {\n continue;\n }\n if (offset > element.length\n && (!(offset === element.length + 1 && isNullOrUndefined(element.nextNode)))) {\n offset = offset - element.length;\n }\n else {\n break;\n }\n }\n return { 'element': element, 'index': offset };\n };\n /**\n * Get paragraph start offset\n * @private\n */\n Selection.prototype.getStartOffset = function (paragraph) {\n var startOffset = 0;\n if (paragraph.childWidgets.length > 0) {\n var childWidgets = paragraph.childWidgets[0];\n return this.getStartLineOffset(childWidgets);\n }\n return startOffset;\n };\n /**\n * @private\n */\n Selection.prototype.getStartLineOffset = function (line) {\n var startOffset = 0;\n for (var i = 0; i < line.children.length; i++) {\n var inline = line.children[i];\n if (inline.length === 0) {\n continue;\n }\n if (inline instanceof TextElementBox || inline instanceof ImageElementBox || inline instanceof BookmarkElementBox\n || (inline instanceof FieldElementBox && HelperMethods.isLinkedFieldCharacter(inline))) {\n return startOffset;\n }\n if (inline instanceof ListTextElementBox) {\n continue;\n }\n startOffset += inline.length;\n }\n return startOffset;\n };\n /**\n * Get previous paragraph from selection\n * @private\n */\n Selection.prototype.getPreviousSelectionCell = function (cell) {\n if (!isNullOrUndefined(cell.previousRenderedWidget)) {\n if (!this.isForward) {\n var block = cell.previousRenderedWidget.childWidgets[0];\n if (block instanceof ParagraphWidget) {\n return block;\n }\n else {\n return this.getFirstParagraphInLastRow(block);\n }\n }\n else {\n var widgets = cell.previousRenderedWidget.childWidgets;\n var block = widgets[widgets.length - 1];\n if (block instanceof ParagraphWidget) {\n return block;\n }\n else {\n // tslint:disable-next-line:max-line-length\n return this.getPreviousParagraphSelection(block.childWidgets[block.childWidgets.length - 1]);\n }\n }\n }\n return this.getPreviousSelectionRow(cell.ownerRow);\n };\n /**\n * Get previous paragraph selection in selection\n * @private\n */\n Selection.prototype.getPreviousSelectionRow = function (row) {\n if (!isNullOrUndefined(row.previousRenderedWidget)) {\n if (!this.isForward) {\n var cell = row.previousRenderedWidget.childWidgets[0];\n var block = cell.childWidgets[0];\n return this.getFirstParagraphBlock(block);\n }\n else {\n return this.getPreviousParagraphSelection(row.previousRenderedWidget);\n }\n }\n return this.getPreviousSelectionBlock(row.ownerTable);\n };\n /**\n * @private\n */\n Selection.prototype.getNextSelectionBlock = function (block) {\n if (block.nextRenderedWidget instanceof ParagraphWidget) {\n return block.nextRenderedWidget;\n }\n else if (block.nextRenderedWidget instanceof TableWidget) {\n if (this.isEmpty || this.isForward) {\n return this.getLastParagraphInFirstRow(block.nextRenderedWidget);\n }\n else {\n return this.getNextParagraphSelection(block.nextRenderedWidget.childWidgets[0]);\n }\n }\n if (block.containerWidget instanceof TableCellWidget) {\n return this.getNextSelectionCell(block.containerWidget);\n }\n else if (block.containerWidget instanceof BodyWidget) {\n return this.getNextSelection(block.containerWidget);\n }\n return undefined;\n };\n /**\n * Get next paragraph from selected cell\n * @private\n */\n Selection.prototype.getNextSelectionCell = function (cell) {\n if (!isNullOrUndefined(cell.nextRenderedWidget)) {\n if (this.isEmpty || this.isForward) {\n // tslint:disable-next-line:max-line-length\n var block = cell.nextRenderedWidget.childWidgets[cell.nextRenderedWidget.childWidgets.length - 1];\n return this.getLastParagraphBlock(block);\n }\n else {\n //Return first paragraph in cell. \n var block = cell.nextRenderedWidget.childWidgets[0];\n if (block instanceof ParagraphWidget) {\n return block;\n }\n else {\n return this.getNextParagraphSelection(block.childWidgets[0]);\n }\n }\n }\n return this.getNextSelectionRow(cell.ownerRow);\n };\n /**\n * Get next paragraph in selection\n * @private\n */\n Selection.prototype.getNextSelectionRow = function (row) {\n if (!isNullOrUndefined(row.nextRenderedWidget)) {\n var isForwardSelection = this.isEmpty || this.isForward;\n if (isForwardSelection) {\n // tslint:disable-next-line:max-line-length\n var cell = row.nextRenderedWidget.childWidgets[row.nextRenderedWidget.childWidgets.length - 1];\n var block = cell.childWidgets[cell.childWidgets.length - 1];\n return this.getLastParagraphBlock(block);\n }\n else {\n return this.getNextParagraphSelection(row.nextRenderedWidget);\n }\n }\n return this.getNextSelectionBlock(row.ownerTable);\n };\n /**\n * Get next block with selection\n * @private\n */\n Selection.prototype.getNextSelection = function (section) {\n if (section.nextRenderedWidget instanceof BodyWidget) {\n var block = section.nextRenderedWidget.childWidgets[0];\n if (block instanceof ParagraphWidget) {\n return block;\n }\n else {\n if (this.isEmpty || this.isForward) {\n return this.getLastParagraphInFirstRow(block);\n }\n else {\n return this.getNextParagraphSelection(block.childWidgets[0]);\n }\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.getNextParagraphSelection = function (row) {\n //Iterate the exact cell based on UP/Down selection length.\n var cell = row.childWidgets[0];\n if (this.start.paragraph.isInsideTable\n && row.ownerTable.contains(this.start.paragraph.associatedCell)) {\n var startCell = this.getCellInTable(row.ownerTable, this.start.paragraph.associatedCell);\n cell = this.getFirstCellInRegion(row, startCell, this.upDownSelectionLength, false);\n }\n var block = cell.childWidgets[0];\n return this.getFirstParagraphBlock(block);\n };\n /**\n * @private\n */\n Selection.prototype.getPreviousSelectionBlock = function (block) {\n if (block.previousRenderedWidget instanceof ParagraphWidget) {\n return block.previousRenderedWidget;\n }\n else if (block.previousRenderedWidget instanceof TableWidget) {\n if (!this.isForward) {\n return this.getFirstParagraphInLastRow(block.previousRenderedWidget);\n }\n else {\n // tslint:disable-next-line:max-line-length\n return this.getPreviousParagraphSelection(block.previousRenderedWidget.childWidgets[block.previousRenderedWidget.childWidgets.length - 1]);\n }\n }\n if (block.containerWidget instanceof TableCellWidget) {\n return this.getPreviousSelectionCell(block.containerWidget);\n }\n else if (block.containerWidget instanceof BodyWidget) {\n return this.getPreviousSelection(block.containerWidget);\n }\n return undefined;\n };\n /**\n * Get previous paragraph in selection\n * @private\n */\n Selection.prototype.getPreviousSelection = function (section) {\n if (section.previousRenderedWidget instanceof BodyWidget) {\n var prevBodyWidget = section.previousRenderedWidget;\n var block = prevBodyWidget.childWidgets[prevBodyWidget.childWidgets.length - 1];\n if (block instanceof ParagraphWidget) {\n return block;\n }\n else {\n if (!this.isForward) {\n return this.getFirstParagraphInLastRow(block);\n }\n else {\n var tableWidget = block;\n // tslint:disable-next-line:max-line-length\n return this.getPreviousParagraphSelection(tableWidget.childWidgets[tableWidget.childWidgets.length - 1]);\n }\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.getPreviousParagraphSelection = function (row) {\n //Iterate the exact cell based on UP/Down selection length.\n var cell = row.childWidgets[row.childWidgets.length - 1];\n if (this.start.paragraph.isInsideTable\n && row.ownerTable.contains(this.start.paragraph.associatedCell)) {\n var startCell = this.getCellInTable(row.ownerTable, this.start.paragraph.associatedCell);\n cell = this.getLastCellInRegion(row, startCell, this.upDownSelectionLength, true);\n }\n var block = cell.childWidgets[cell.childWidgets.length - 1];\n return this.getLastParagraphBlock(block);\n };\n /**\n * Get last cell in the selected region\n * @private\n */\n Selection.prototype.getLastCellInRegion = function (row, startCell, selLength, isMovePrev) {\n var start = this.getCellLeft(row, startCell);\n var end = start + startCell.cellFormat.cellWidth;\n var flag = true;\n if (start <= selLength && selLength < end) {\n for (var i = row.childWidgets.length - 1; i >= 0; i--) {\n var left = this.getCellLeft(row, row.childWidgets[i]);\n if (HelperMethods.round(start, 2) <= HelperMethods.round(left, 2) &&\n HelperMethods.round(left, 2) < HelperMethods.round(end, 2)) {\n flag = false;\n return row.childWidgets[i];\n }\n }\n }\n else {\n for (var i = row.childWidgets.length - 1; i >= 0; i--) {\n var left = this.getCellLeft(row, row.childWidgets[i]);\n if (left <= selLength && left + row.childWidgets[i].cellFormat.cellWidth > selLength) {\n flag = false;\n return row.childWidgets[i];\n }\n }\n }\n if (flag) {\n if (!isNullOrUndefined(row.previousRenderedWidget) && isMovePrev) {\n return this.getLastCellInRegion(row.previousRenderedWidget, startCell, selLength, isMovePrev);\n }\n else if (!isNullOrUndefined(row.nextRenderedWidget) && !isMovePrev) {\n return this.getLastCellInRegion(row.nextRenderedWidget, startCell, selLength, isMovePrev);\n }\n }\n return row.childWidgets[row.childWidgets.length - 1];\n };\n /**\n * Get Container table\n * @private\n */\n Selection.prototype.getCellInTable = function (table, tableCell) {\n while (tableCell.ownerTable.isInsideTable) {\n if (table.equals(tableCell.ownerTable)) {\n return tableCell;\n }\n tableCell = tableCell.ownerTable.associatedCell;\n }\n return tableCell;\n };\n /**\n * Get first paragraph in last row\n * @private\n */\n Selection.prototype.getFirstParagraphInLastRow = function (table) {\n if (table.childWidgets.length > 0) {\n var lastRow = table.childWidgets[table.childWidgets.length - 1];\n var lastCell = lastRow.childWidgets[0];\n var lastBlock = lastCell.childWidgets[0];\n return this.getFirstParagraphBlock(lastBlock);\n }\n return undefined;\n };\n /**\n * Get previous valid offset\n * @private\n */\n Selection.prototype.getPreviousValidOffset = function (paragraph, offset) {\n if (offset === 0) {\n return 0;\n }\n var validOffset = 0;\n var count = 0;\n for (var i = 0; i < paragraph.childWidgets.length; i++) {\n var lineWidget = paragraph.childWidgets[i];\n for (var j = 0; j < lineWidget.children.length; j++) {\n var inline = lineWidget.children[j];\n if (inline.length === 0) {\n continue;\n }\n if (offset <= count + inline.length) {\n return offset - 1 === count ? validOffset : offset - 1;\n }\n if (inline instanceof TextElementBox || inline instanceof ImageElementBox\n || (inline instanceof FieldElementBox && HelperMethods.isLinkedFieldCharacter(inline))) {\n validOffset = count + inline.length;\n }\n count += inline.length;\n }\n }\n return offset - 1 === count ? validOffset : offset - 1;\n };\n /**\n * Get next valid offset\n * @private\n */\n Selection.prototype.getNextValidOffset = function (line, offset) {\n var count = 0;\n for (var i = 0; i < line.children.length; i++) {\n var inline = line.children[i];\n if (inline.length === 0 || inline instanceof ListTextElementBox) {\n continue;\n }\n if (offset < count + inline.length) {\n if (inline instanceof TextElementBox || inline instanceof ImageElementBox\n || (inline instanceof FieldElementBox && HelperMethods.isLinkedFieldCharacter(inline))) {\n return (offset > count ? offset : count) + 1;\n }\n }\n count += inline.length;\n }\n return offset;\n };\n /**\n * Get paragraph mark size info\n * @private\n */\n Selection.prototype.getParagraphMarkSize = function (paragraph, topMargin, bottomMargin) {\n var size = this.viewer.textHelper.getParagraphMarkSize(paragraph.characterFormat);\n var baselineOffset = size.BaselineOffset;\n var maxHeight = size.Height;\n var maxBaselineOffset = baselineOffset;\n if (paragraph instanceof ParagraphWidget) {\n // let paragraphWidget: ParagraphWidget[] = paragraph.renderedElement() as ParagraphWidget[];\n if (paragraph.childWidgets.length > 0) {\n var lineWidget = paragraph.childWidgets[0];\n }\n //Gets line spacing.\n var lineSpacing = this.viewer.layout.getLineSpacing(paragraph, maxHeight);\n var beforeSpacing = this.viewer.layout.getBeforeSpacing(paragraph);\n topMargin = maxBaselineOffset - baselineOffset;\n bottomMargin = maxHeight - maxBaselineOffset - (size.Height - baselineOffset);\n //Updates line spacing, paragraph after/ before spacing and aligns the text to base line offset.\n var lineSpacingType = paragraph.paragraphFormat.lineSpacingType;\n if (lineSpacingType === 'Multiple') {\n if (lineSpacing > maxHeight) {\n bottomMargin += lineSpacing - maxHeight;\n }\n else {\n topMargin += lineSpacing - maxHeight;\n }\n }\n else if (lineSpacingType === 'Exactly') {\n topMargin += lineSpacing - (topMargin + size.Height + bottomMargin);\n }\n else if (lineSpacing > topMargin + size.Height + bottomMargin) {\n topMargin += lineSpacing - (topMargin + size.Height + bottomMargin);\n }\n topMargin += beforeSpacing;\n bottomMargin += paragraph.paragraphFormat.afterSpacing;\n }\n return { 'width': size.Width, 'height': size.Height, 'topMargin': topMargin, 'bottomMargin': bottomMargin };\n };\n /**\n * @private\n */\n Selection.prototype.getPhysicalPositionInternal = function (line, offset, moveNextLine) {\n if (line.paragraph.isEmpty()) {\n var paragraphWidget = line.paragraph;\n var left = paragraphWidget.x;\n if (paragraphWidget.childWidgets.length > 0) {\n var lineWidget = paragraphWidget.childWidgets[0];\n left = this.getLeft(lineWidget);\n }\n var topMargin = 0;\n var bottomMargin = 0;\n var size = this.getParagraphMarkSize(line.paragraph, topMargin, bottomMargin);\n if (offset > 0) {\n left += size.width;\n }\n return new Point(left, paragraphWidget.y + topMargin);\n }\n else {\n var indexInInline = 0;\n var inlineObj = line.getInline(offset, indexInInline);\n var inline = inlineObj.element; //return indexInInline must\n indexInInline = inlineObj.index;\n // tslint:disable-next-line:max-line-length\n // if (inline.length === indexInInline && !isNullOrUndefined(inline.nextNode) && this.viewer.renderedElements.containsKey(inline) &&\n // this.viewer.renderedElements.get(inline).length > 0 && this.viewer.renderedElements.containsKey(inline.nextNode as WInline)\n // && this.viewer.renderedElements.get(inline.nextNode as WInline).length > 0 &&\n // tslint:disable-next-line:max-line-length\n // (this.viewer.renderedElements.get(inline)[this.viewer.renderedElements.get(inline).length - 1] as ElementBox).line !== (this.viewer.renderedElements.get(inline.nextNode as WInline)[0] as ElementBox).line) {\n // //Handled specifically to move the cursor at start of next line.\n // inline = inline.nextNode as WInline;\n // indexInInline = 0;\n // }\n return this.getPhysicalPositionInline(inline, indexInInline, moveNextLine);\n }\n };\n /**\n * Highlight selected content\n * @private\n */\n Selection.prototype.highlightSelectedContent = function (start, end) {\n if (start.paragraph.isInsideTable && (!end.paragraph.isInsideTable\n || (!start.paragraph.associatedCell.equals(end.paragraph.associatedCell))\n || this.isCellSelected(start.paragraph.associatedCell, start, end))) {\n this.highlightCell(start.paragraph.associatedCell, this, start, end);\n }\n else {\n var inline = undefined;\n var index = 0;\n if (!this.owner.isReadOnlyMode && start.paragraph === end.paragraph) {\n if (start.offset + 1 === end.offset) {\n var inlineObj = end.currentWidget.getInline(end.offset, index);\n inline = inlineObj.element; // return index value\n index = inlineObj.index;\n if (inline instanceof ImageElementBox) {\n var startOffset = start.currentWidget.getOffset(inline, 0);\n if (startOffset !== start.offset) {\n inline = undefined;\n }\n }\n }\n else {\n var indexInInline = 0;\n var startInlineObj = start.currentWidget.getInline(start.offset, indexInInline);\n var startInline = startInlineObj.element; //return indexInInline\n indexInInline = startInlineObj.index;\n if (indexInInline === startInline.length) {\n startInline = this.getNextRenderedElementBox(startInline, indexInInline);\n }\n var endInlineObj = end.currentWidget.getInline(end.offset, indexInInline);\n var endInline = endInlineObj.element; //return indexInInline\n indexInInline = endInlineObj.index;\n // tslint:disable-next-line:max-line-length\n if (startInline instanceof FieldElementBox && endInline instanceof FieldElementBox && !isNullOrUndefined(startInline.fieldSeparator)) {\n var fieldValue = startInline.fieldSeparator.nextNode;\n if (fieldValue instanceof ImageElementBox && fieldValue.nextNode === endInline) {\n inline = fieldValue;\n }\n }\n }\n }\n if (!this.owner.isReadOnlyMode && inline instanceof ImageElementBox && this.owner.isDocumentLoaded) {\n var elementBoxObj = this.getElementBoxInternal(inline, index);\n var elementBox = elementBoxObj.element; //return index \n index = elementBoxObj.index;\n if (this.owner.enableImageResizerMode) {\n this.owner.imageResizerModule.positionImageResizer(elementBox);\n this.owner.imageResizerModule.showImageResizer();\n }\n if (this.viewer.isTouchInput) {\n this.viewer.touchStart.style.display = 'none';\n this.viewer.touchEnd.style.display = 'none';\n }\n }\n else {\n this.highlight(start.paragraph, start, end);\n }\n }\n };\n /**\n * @private\n */\n Selection.prototype.highlight = function (paragraph, start, end) {\n var selectionStartIndex = 0;\n var selectionEndIndex = 0;\n var startElement = undefined;\n var endElement = undefined;\n var startLineWidget = undefined;\n var endLineWidget = undefined;\n //return start Element and selection start index\n var startLineObj = this.getStartLineWidget(paragraph, start, startElement, selectionStartIndex);\n startElement = startLineObj.element;\n if (isNullOrUndefined(startElement)) {\n startLineWidget = paragraph.childWidgets[0];\n }\n else {\n startLineWidget = startElement.line;\n }\n selectionStartIndex = startLineObj.index;\n var endLineObj = this.getEndLineWidget(end, endElement, selectionEndIndex);\n endElement = endLineObj.element;\n if (endElement) {\n endLineWidget = endElement.line;\n }\n else {\n endLineWidget = end.paragraph.childWidgets[end.paragraph.childWidgets.length - 1];\n }\n selectionEndIndex = endLineObj.index;\n var top = 0;\n var left = 0;\n if (!isNullOrUndefined(startLineWidget)) {\n top = this.getTop(startLineWidget);\n left = this.getLeftInternal(startLineWidget, startElement, selectionStartIndex);\n }\n if (!isNullOrUndefined(startLineWidget) && startLineWidget === endLineWidget) {\n //Selection ends in current line.\n var right = this.getLeftInternal(endLineWidget, endElement, selectionEndIndex);\n this.createHighlightBorder(startLineWidget, right - left, left, top);\n }\n else {\n if (!isNullOrUndefined(startLineWidget)) {\n var x = startLineWidget.paragraph.x;\n this.createHighlightBorder(startLineWidget, this.getWidth(startLineWidget, true) - (left - x), left, top);\n var lineIndex = startLineWidget.paragraph.childWidgets.indexOf(startLineWidget);\n //Iterates to last item of paragraph or selection end. \n this.highlightParagraph(paragraph, lineIndex + 1, endLineWidget, endElement, selectionEndIndex);\n if (paragraph.childWidgets.indexOf(end.currentWidget) !== -1) {\n return;\n }\n }\n this.highlightNextBlock(paragraph, start, end);\n }\n };\n Selection.prototype.highlightNextBlock = function (paragraph, start, end) {\n var block = paragraph.nextRenderedWidget;\n if (!isNullOrUndefined(block)) {\n if (block instanceof ParagraphWidget) {\n this.highlight(block, start, end);\n }\n else {\n this.highlightTable(block, start, end);\n }\n }\n };\n /**\n * Get start line widget\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getStartLineWidget = function (paragraph, start, startElement, selectionStartIndex) {\n var offset = paragraph === start.paragraph ? start.offset : this.getStartOffset(paragraph);\n var startInlineObj = undefined;\n if (paragraph === start.paragraph) {\n startInlineObj = start.currentWidget.getInline(offset, selectionStartIndex);\n }\n else {\n startInlineObj = paragraph.firstChild.getInline(offset, selectionStartIndex);\n }\n startElement = startInlineObj.element; //return selectionStartIndex\n selectionStartIndex = startInlineObj.index;\n if (startElement instanceof FieldElementBox) {\n var inlineInfo = this.getRenderedInline(startElement, selectionStartIndex);\n startElement = inlineInfo.element;\n selectionStartIndex = inlineInfo.index;\n }\n if (offset === this.getParagraphLength(start.paragraph) + 1) {\n selectionStartIndex++;\n }\n return {\n 'index': selectionStartIndex, 'element': startElement\n };\n };\n /**\n * Get end line widget\n * @private\n */\n Selection.prototype.getEndLineWidget = function (end, endElement, selectionEndIndex) {\n var endInlineObj = end.currentWidget.getInline(end.offset, selectionEndIndex);\n endElement = endInlineObj.element; //return selection end index\n selectionEndIndex = endInlineObj.index;\n if (endElement instanceof FieldElementBox) {\n var inlineInfo = this.getRenderedInline(endElement, selectionEndIndex);\n endElement = inlineInfo.element;\n selectionEndIndex = inlineInfo.index;\n }\n var lineIndex = end.paragraph.childWidgets.indexOf(end.currentWidget);\n if (lineIndex === end.paragraph.childWidgets.length - 1 && end.offset === this.getLineLength(end.currentWidget) + 1) {\n selectionEndIndex = endElement ? endElement.length + 1 : 1;\n }\n return { 'index': selectionEndIndex, 'element': endElement };\n };\n /**\n * Get line widget\n * @private\n */\n Selection.prototype.getLineWidgetInternal = function (line, offset, moveToNextLine) {\n var lineWidget = undefined;\n if (line.children.length === 0 && line instanceof LineWidget) {\n lineWidget = line;\n }\n else {\n var indexInInline = 0;\n var inlineInfo = line.getInline(offset, indexInInline);\n var inline = inlineInfo.element;\n indexInInline = inlineInfo.index;\n lineWidget = inline instanceof ElementBox ? inline.line\n : this.getLineWidgetInternalInline(inline, indexInInline, moveToNextLine);\n }\n return lineWidget;\n };\n /**\n * Get last line widget\n * @private\n */\n Selection.prototype.getLineWidgetParagraph = function (offset, line) {\n var linewidget = undefined;\n if (line.children.length === 0) {\n linewidget = line;\n }\n else {\n var indexInInline = 0;\n var inlineInfo = line.getInline(offset, indexInInline);\n var inline = inlineInfo.element;\n indexInInline = inlineInfo.index;\n linewidget = this.getLineWidget(inline, indexInInline);\n }\n return linewidget;\n };\n /**\n * Highlight selected cell\n * @private\n */\n /* tslint:disable */\n // tslint:disable-next-line:max-line-length \n Selection.prototype.highlightCells = function (table, startCell, endCell) {\n var start = this.getCellLeft(startCell.ownerRow, startCell);\n var end = start + startCell.cellFormat.cellWidth;\n var endCellLeft = this.getCellLeft(endCell.ownerRow, endCell);\n var endCellRight = endCellLeft + endCell.cellFormat.cellWidth;\n if (start > endCellLeft) {\n start = endCellLeft;\n }\n if (end < endCellRight) {\n end = endCellRight;\n }\n if (start > this.upDownSelectionLength) {\n start = this.upDownSelectionLength;\n }\n if (end < this.upDownSelectionLength) {\n end = this.upDownSelectionLength;\n }\n var tableWidgetCollection = table.getSplitWidgets();\n var startTableIndex = tableWidgetCollection.indexOf(startCell.ownerRow.ownerTable);\n var endTableIndex = tableWidgetCollection.indexOf(endCell.ownerRow.ownerTable);\n if (startTableIndex === endTableIndex) {\n var count = table.childWidgets.indexOf(endCell.ownerRow);\n for (var i = table.childWidgets.indexOf(startCell.ownerRow); i <= count; i++) {\n this.highlightRow(table.childWidgets[i], start, end);\n }\n }\n else {\n var startRowIndex = 0;\n var endRowIndex = 0;\n for (var i = startTableIndex; i <= endTableIndex; i++) {\n table = tableWidgetCollection[i];\n if (i === startTableIndex) {\n startRowIndex = table.childWidgets.indexOf(startCell.ownerRow);\n }\n else {\n startRowIndex = 0;\n }\n if (i === endTableIndex) {\n endRowIndex = table.childWidgets.indexOf(endCell.ownerRow);\n }\n else {\n endRowIndex = table.childWidgets.length - 1;\n }\n for (var j = startRowIndex; j <= endRowIndex; j++) {\n this.highlightRow(table.childWidgets[j], start, end);\n }\n }\n }\n };\n /* tslint:enable */\n /**\n * highlight selected table\n * @private\n */\n Selection.prototype.highlightTable = function (table, start, end) {\n this.highlightInternal(table.childWidgets[0], start, end);\n if (!end.paragraph.isInsideTable //Selection end is outside the table cell.\n || !table.contains(end.paragraph.associatedCell)) {\n this.highlightNextBlock(table, start, end);\n }\n };\n /**\n * Get cell left\n * @private\n */\n Selection.prototype.getCellLeft = function (row, cell) {\n var left = 0;\n left += cell.x - cell.margin.left;\n return left;\n };\n /**\n * Get next paragraph for row\n * @private\n */\n Selection.prototype.getNextParagraphRow = function (row) {\n if (!isNullOrUndefined(row.nextRenderedWidget)) {\n var cell = row.nextRenderedWidget.childWidgets[0];\n var block = cell.childWidgets[0];\n return this.getFirstParagraphBlock(block);\n }\n return this.getNextParagraphBlock(row.ownerTable);\n };\n /**\n * Get previous paragraph from row\n * @private\n */\n Selection.prototype.getPreviousParagraphRow = function (row) {\n if (!isNullOrUndefined(row.previousRenderedWidget)) {\n // tslint:disable-next-line:max-line-length\n var cell = row.previousRenderedWidget.lastChild;\n var block = cell.lastChild ? cell.lastChild : (cell.previousSplitWidget).lastChild;\n return this.getLastParagraphBlock(block);\n }\n return this.getPreviousParagraphBlock(row.ownerTable);\n };\n /**\n * Return true if row contain cell\n * @private\n */\n Selection.prototype.containsRow = function (row, tableCell) {\n if (row.childWidgets.indexOf(tableCell) !== -1) {\n return true;\n }\n while (tableCell.ownerTable.isInsideTable) {\n if (row.childWidgets.indexOf(tableCell) !== -1) {\n return true;\n }\n tableCell = tableCell.ownerTable.associatedCell;\n }\n return row.childWidgets.indexOf(tableCell) !== -1;\n };\n /**\n * Highlight selected row\n * @private\n */\n Selection.prototype.highlightRow = function (row, start, end) {\n for (var i = 0; i < row.childWidgets.length; i++) {\n var left = this.getCellLeft(row, row.childWidgets[i]);\n if (HelperMethods.round(start, 2) <= HelperMethods.round(left, 2) &&\n HelperMethods.round(left, 2) < HelperMethods.round(end, 2)) {\n this.highlightCellWidget(row.childWidgets[i]);\n }\n }\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.highlightInternal = function (row, start, end) {\n for (var i = 0; i < row.childWidgets.length; i++) {\n this.highlightCellWidget(row.childWidgets[i]);\n }\n if (end.paragraph.isInsideTable && this.containsRow(row, end.paragraph.associatedCell)) {\n return;\n }\n else if (row.nextRenderedWidget instanceof TableRowWidget) {\n this.highlightInternal(row.nextRenderedWidget, start, end);\n }\n };\n /**\n * Get last paragraph in cell\n * @private\n */\n Selection.prototype.getLastParagraph = function (cell) {\n while (cell.nextSplitWidget) {\n if (cell.nextSplitWidget.childWidgets.length > 0) {\n cell = cell.nextSplitWidget;\n }\n else {\n break;\n }\n }\n var lastBlock;\n if (cell.childWidgets.length > 0) {\n lastBlock = cell.lastChild;\n }\n else {\n lastBlock = cell.previousSplitWidget.lastChild;\n }\n return this.getLastParagraphBlock(lastBlock);\n };\n /**\n * Return true is source cell contain cell\n * @private\n */\n Selection.prototype.containsCell = function (sourceCell, cell) {\n if (sourceCell.equals(cell)) {\n return true;\n }\n while (cell.ownerTable.isInsideTable) {\n if (sourceCell.equals(cell.ownerTable.associatedCell)) {\n return true;\n }\n cell = cell.ownerTable.associatedCell;\n }\n return false;\n };\n /**\n * Return true if cell is selected\n * @private\n */\n Selection.prototype.isCellSelected = function (cell, startPosition, endPosition) {\n var lastParagraph = this.getLastParagraph(cell);\n // tslint:disable-next-line:max-line-length\n var isAtCellEnd = lastParagraph === endPosition.paragraph && endPosition.offset === this.getParagraphLength(lastParagraph) + 1;\n return isAtCellEnd || (!this.containsCell(cell, startPosition.paragraph.associatedCell) ||\n !this.containsCell(cell, endPosition.paragraph.associatedCell));\n };\n /**\n * Return Container cell\n * @private\n */\n Selection.prototype.getContainerCellOf = function (cell, tableCell) {\n while (cell.ownerTable.isInsideTable) {\n if (cell.ownerTable.contains(tableCell)) {\n return cell;\n }\n cell = cell.ownerTable.associatedCell;\n }\n return cell;\n };\n /**\n * Get Selected cell\n * @private\n */\n Selection.prototype.getSelectedCell = function (cell, containerCell) {\n if (cell.ownerTable.equals(containerCell.ownerTable)) {\n return cell;\n }\n while (cell.ownerTable.isInsideTable) {\n if (cell.ownerTable.associatedCell.equals(containerCell)) {\n return cell;\n }\n cell = cell.ownerTable.associatedCell;\n }\n return cell;\n };\n /**\n * @private\n */\n Selection.prototype.getSelectedCells = function () {\n var cells = [];\n for (var i = 0; i < this.selectedWidgets.keys.length; i++) {\n var widget = this.selectedWidgets.keys[i];\n if (widget instanceof TableCellWidget) {\n cells.push(widget);\n }\n }\n return cells;\n };\n /**\n * Get Next paragraph from cell\n * @private\n */\n Selection.prototype.getNextParagraphCell = function (cell) {\n if (cell.nextRenderedWidget && cell.nextRenderedWidget instanceof TableCellWidget) {\n //Return first paragraph in cell. \n cell = cell.nextRenderedWidget;\n var block = cell.firstChild;\n if (block) {\n return this.getFirstParagraphBlock(block);\n }\n else {\n return this.getNextParagraphCell(cell);\n }\n }\n return this.getNextParagraphRow(cell.containerWidget);\n };\n /**\n * Get previous paragraph from cell\n * @private\n */\n Selection.prototype.getPreviousParagraphCell = function (cell) {\n if (!isNullOrUndefined(cell.previousRenderedWidget) && cell.previousRenderedWidget instanceof TableCellWidget) {\n cell = cell.previousRenderedWidget;\n var block = cell.lastChild;\n return this.getLastParagraphBlock(block);\n }\n return this.getPreviousParagraphRow(cell.ownerRow);\n };\n /**\n * Get cell's container cell\n * @private\n */\n Selection.prototype.getContainerCell = function (cell) {\n while (!isNullOrUndefined(cell.ownerTable) && cell.ownerTable.isInsideTable) {\n cell = cell.ownerTable.associatedCell;\n }\n return cell;\n };\n /**\n * Highlight selected cell\n * @private\n */\n /* tslint:disable */\n Selection.prototype.highlightCell = function (cell, selection, start, end) {\n if (end.paragraph.isInsideTable) {\n var containerCell = this.getContainerCellOf(cell, end.paragraph.associatedCell);\n if (containerCell.ownerTable.contains(end.paragraph.associatedCell)) {\n var startCell = this.getSelectedCell(cell, containerCell);\n var endCell = this.getSelectedCell(end.paragraph.associatedCell, containerCell);\n if (this.containsCell(containerCell, end.paragraph.associatedCell)) {\n /* tslint:enable */\n //Selection end is in container cell.\n if (this.isCellSelected(containerCell, start, end)) {\n this.highlightCellWidget(containerCell);\n }\n else {\n if (startCell === containerCell) {\n this.highlight(start.paragraph, start, end);\n }\n else {\n this.highlightContainer(startCell, start, end);\n }\n }\n }\n else {\n //Selection end is not in container cell.\n this.highlightCellWidget(containerCell);\n if (containerCell.ownerRow.equals(endCell.ownerRow)) {\n //Highlight other selected cells in current row.\n startCell = containerCell;\n while (!isNullOrUndefined(startCell.nextRenderedWidget)) {\n startCell = startCell.nextRenderedWidget;\n this.highlightCellWidget(startCell);\n if (startCell === endCell) {\n break;\n }\n }\n }\n else {\n this.highlightCells(containerCell.ownerTable, containerCell, endCell);\n }\n }\n }\n else {\n this.highlightContainer(containerCell, start, end);\n }\n }\n else {\n var cell1 = this.getContainerCell(cell);\n this.highlightContainer(cell1, start, end);\n }\n };\n /**\n * @private\n */\n Selection.prototype.highlightContainer = function (cell, start, end) {\n this.highlightInternal(cell.containerWidget, start, end);\n this.highlightNextBlock(cell.ownerTable, start, end);\n };\n /**\n * Get previous valid element\n * @private\n */\n Selection.prototype.getPreviousValidElement = function (inline) {\n var previousValidInline = undefined;\n while (inline instanceof FieldElementBox) {\n if (HelperMethods.isLinkedFieldCharacter(inline)) {\n if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n previousValidInline = inline;\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 1) {\n previousValidInline = inline;\n if (isNullOrUndefined(inline.fieldSeparator)) {\n inline = inline.fieldBegin;\n previousValidInline = inline;\n }\n }\n else {\n inline = inline.fieldBegin;\n previousValidInline = inline;\n }\n }\n inline = inline.previousNode;\n }\n return isNullOrUndefined(previousValidInline) ? inline : previousValidInline;\n };\n /**\n * Get next valid element\n * @private\n */\n Selection.prototype.getNextValidElement = function (inline) {\n var nextValidInline = undefined;\n while (inline instanceof FieldElementBox) {\n if (inline.fieldType === 0 && !isNullOrUndefined(inline.fieldEnd)) {\n return isNullOrUndefined(nextValidInline) ? inline : nextValidInline;\n }\n else if (inline.fieldType === 1 && !isNullOrUndefined(inline.fieldBegin)) {\n nextValidInline = inline;\n }\n inline = inline.nextNode;\n }\n return (isNullOrUndefined(nextValidInline) ? inline : nextValidInline);\n };\n /**\n * Return next valid inline with index\n * @private\n */\n Selection.prototype.validateTextPosition = function (inline, index) {\n if (inline.length === index && inline.nextNode instanceof FieldElementBox) {\n //If inline is last item within field, then set field end as text position.\n var nextInline = this.getNextValidElement(inline.nextNode);\n if (nextInline instanceof FieldElementBox && nextInline.fieldType === 1) {\n inline = nextInline;\n index = 1;\n }\n }\n else if (index === 0 && inline.previousNode instanceof FieldElementBox) {\n var prevInline = this.getPreviousValidElement(inline.previousNode);\n inline = prevInline;\n index = inline instanceof FieldElementBox ? 0 : inline.length;\n if (inline instanceof FieldElementBox && inline.fieldType === 1) {\n index++;\n }\n }\n return { 'element': inline, 'index': index };\n };\n /**\n * Get inline physical location\n * @private\n */\n Selection.prototype.getPhysicalPositionInline = function (inline, index, moveNextLine) {\n var element = undefined;\n element = this.getElementBox(inline, index, moveNextLine).element;\n var lineWidget = undefined;\n if (isNullOrUndefined(element) || isNullOrUndefined(element.line)) {\n if (inline instanceof FieldElementBox || inline instanceof BookmarkElementBox) {\n return this.getFieldCharacterPosition(inline);\n }\n return new Point(0, 0);\n }\n var margin = element.margin;\n var top = 0;\n var left = 0;\n if (element instanceof TextElementBox && element.text === '\\v' && isNullOrUndefined(inline.nextNode)) {\n lineWidget = this.getNextLineWidget(element.line.paragraph, element);\n index = 0;\n }\n else {\n lineWidget = element.line;\n }\n top = this.getTop(lineWidget);\n if (element instanceof ImageElementBox) {\n var format = element.line.paragraph.characterFormat;\n var previousInline = this.getPreviousTextElement(inline);\n if (!isNullOrUndefined(previousInline)) {\n format = previousInline.characterFormat;\n }\n else {\n var nextInline = this.getNextTextElement(inline);\n if (!isNullOrUndefined(nextInline)) {\n format = nextInline.characterFormat;\n }\n }\n var measureObj = this.viewer.textHelper.getHeight(format); //return ascent\n var ascent = measureObj.Height - measureObj.BaselineOffset;\n if (element.margin.top + element.height - ascent > 0) {\n top += element.margin.top + element.height - ascent;\n }\n }\n else if (!(element instanceof FieldElementBox)) {\n top += margin.top > 0 ? margin.top : 0;\n }\n left = (isNullOrUndefined(element) || isNullOrUndefined(lineWidget)) ? 0 : this.getLeftInternal(lineWidget, element, index);\n return new Point(left, top);\n };\n /**\n * Get field character position\n * @private\n */\n Selection.prototype.getFieldCharacterPosition = function (firstInline) {\n var nextValidInline = this.getNextValidElementForField(firstInline);\n //If field separator/end exists at end of paragraph, then move to next paragraph.\n if (isNullOrUndefined(nextValidInline)) {\n var nextParagraph = firstInline.line.paragraph;\n return this.getEndPosition(nextParagraph);\n }\n else {\n return this.getPhysicalPositionInline(nextValidInline, 0, true);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getNextValidElementForField = function (firstInline) {\n if (firstInline instanceof FieldElementBox && firstInline.fieldType === 0\n && HelperMethods.isLinkedFieldCharacter(firstInline)) {\n var fieldBegin = firstInline;\n if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n firstInline = fieldBegin.fieldEnd;\n }\n else {\n firstInline = fieldBegin.fieldSeparator;\n }\n }\n var nextValidInline = undefined;\n if (!isNullOrUndefined(firstInline.nextNode)) {\n nextValidInline = this.getNextValidElement(firstInline.nextNode);\n }\n return nextValidInline;\n };\n /**\n * Get paragraph end position\n * @private\n */\n Selection.prototype.getEndPosition = function (widget) {\n var left = widget.x;\n var top = widget.y;\n var lineWidget = undefined;\n if (widget.childWidgets.length > 0) {\n lineWidget = widget.childWidgets[widget.childWidgets.length - 1];\n left += this.getWidth(lineWidget, false);\n }\n if (!isNullOrUndefined(lineWidget)) {\n top = this.getTop(lineWidget);\n }\n var topMargin = 0;\n var bottomMargin = 0;\n var size = this.getParagraphMarkSize(widget, topMargin, bottomMargin);\n return new Point(left, top + size.topMargin);\n };\n /**\n * Get element box\n * @private\n */\n Selection.prototype.getElementBox = function (currentInline, index, moveToNextLine) {\n var elementBox = undefined;\n if (!(currentInline instanceof FieldElementBox || currentInline instanceof BookmarkElementBox)) {\n elementBox = currentInline;\n }\n return { 'element': elementBox, 'index': index };\n };\n /**\n * @private\n */\n Selection.prototype.getPreviousTextElement = function (inline) {\n if (inline.previousNode instanceof TextElementBox) {\n return inline.previousNode;\n }\n if (!isNullOrUndefined(inline.previousNode)) {\n return this.getPreviousTextElement(inline.previousNode);\n }\n return undefined;\n };\n /**\n * Get next text inline\n * @private\n */\n Selection.prototype.getNextTextElement = function (inline) {\n if (inline.nextNode instanceof TextElementBox) {\n return inline.nextNode;\n }\n if (!isNullOrUndefined(inline.nextNode)) {\n return this.getNextTextElement(inline.nextNode);\n }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.getNextRenderedElementBox = function (inline, indexInInline) {\n if (inline instanceof FieldElementBox) {\n var fieldBegin = inline;\n if (fieldBegin.fieldType === 0) {\n inline = this.getRenderedField(fieldBegin);\n if (fieldBegin === inline) {\n return fieldBegin;\n }\n }\n indexInInline = 1;\n }\n while (!isNullOrUndefined(inline) && indexInInline === inline.length && inline.nextNode instanceof FieldElementBox) {\n var nextValidInline = this.getNextValidElement((inline.nextNode));\n if (nextValidInline instanceof FieldElementBox && nextValidInline.fieldType === 0) {\n var fieldBegin = nextValidInline;\n inline = this.getRenderedField(fieldBegin);\n if (!isNullOrUndefined(inline) && fieldBegin === inline) {\n return fieldBegin;\n }\n indexInInline = 1;\n }\n else {\n inline = nextValidInline;\n }\n }\n return inline;\n };\n /**\n * @private\n */\n Selection.prototype.getElementBoxInternal = function (inline, index) {\n var element = undefined;\n element = inline;\n return {\n 'element': element, 'index': index\n };\n };\n /**\n * Get Line widget\n * @private\n */\n Selection.prototype.getLineWidget = function (inline, index) {\n return this.getLineWidgetInternalInline(inline, index, true);\n };\n /**\n * @private\n */\n Selection.prototype.getLineWidgetInternalInline = function (inline, index, moveToNextLine) {\n var elementObj = this.getElementBox(inline, index, moveToNextLine);\n var element = elementObj.element; //return index\n index = elementObj.index;\n if (!isNullOrUndefined(element)) {\n if (moveToNextLine && element instanceof TextElementBox && element.text === '\\v' && index === 1) {\n return this.getNextLineWidget(element.line.paragraph, element);\n }\n else {\n return element.line;\n }\n }\n var startInline = inline;\n //ToDo: Check previous inline here.\n var nextValidInline = this.getNextValidElementForField(startInline);\n //If field separator/end exists at end of paragraph, then move to next paragraph.\n if (isNullOrUndefined(nextValidInline)) {\n var lineWidget = undefined;\n var widget = startInline.line.paragraph;\n if (widget.childWidgets.length > 0) {\n lineWidget = widget.childWidgets[widget.childWidgets.length - 1];\n }\n return lineWidget;\n }\n else {\n return this.getLineWidget(nextValidInline, 0);\n }\n };\n /**\n * Get next line widget\n * @private\n */\n Selection.prototype.getNextLineWidget = function (paragraph, element) {\n var lineWidget = undefined;\n var widget = paragraph;\n if (widget.childWidgets.length > 0) {\n var widgetIndex = widget.childWidgets.indexOf(element.line);\n if (widgetIndex === widget.childWidgets.length - 1) {\n widget = paragraph;\n // widget = paragraph.leafWidgets[paragraph.leafWidgets.length - 1];\n widgetIndex = -1;\n }\n else if (widgetIndex > widget.childWidgets.length - 1) {\n widget = this.getNextParagraphBlock(paragraph);\n widgetIndex = -1;\n }\n else if (widgetIndex < 0) {\n // widget = paragraph.leafWidgets[paragraph.leafWidgets.length - 1];\n widget = paragraph;\n widgetIndex = widget.childWidgets.indexOf(element.line);\n }\n lineWidget = widget.childWidgets[widgetIndex + 1];\n }\n return lineWidget;\n };\n /**\n * Get Caret height\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getCaretHeight = function (inline, index, format, isEmptySelection, topMargin, isItalic) {\n var elementBoxInfo = this.getElementBox(inline, index, false);\n var element = elementBoxInfo.element;\n var currentInline = inline;\n if (isNullOrUndefined(element)) {\n if (currentInline instanceof FieldElementBox) {\n return this.getFieldCharacterHeight(currentInline, format, isEmptySelection, topMargin, isItalic);\n }\n return { 'height': this.viewer.textHelper.getHeight(format).Height, 'topMargin': topMargin, 'isItalic': isItalic };\n }\n var margin = element.margin;\n var heightElement = element.height;\n var maxLineHeight = 0;\n if (element instanceof ImageElementBox) {\n var previousInline = this.getPreviousTextElement(inline);\n var nextInline = this.getNextTextElement(inline);\n if (isNullOrUndefined(previousInline) && isNullOrUndefined(nextInline)) {\n var top_2 = 0;\n var bottom = 0;\n var paragarph = inline.line.paragraph;\n var sizeInfo = this.getParagraphMarkSize(paragarph, top_2, bottom);\n top_2 = sizeInfo.topMargin;\n bottom = sizeInfo.bottomMargin;\n maxLineHeight = sizeInfo.height;\n isItalic = paragarph.characterFormat.italic;\n if (!isEmptySelection) {\n maxLineHeight += paragarph.paragraphFormat.afterSpacing;\n }\n }\n else if (isNullOrUndefined(previousInline)) {\n isItalic = nextInline.characterFormat.italic;\n return this.getCaretHeight(nextInline, 0, nextInline.characterFormat, isEmptySelection, topMargin, isItalic);\n }\n else {\n if (!isNullOrUndefined(nextInline) && element instanceof ImageElementBox) {\n //Calculates the caret size using image character format.\n var textSizeInfo = this.viewer.textHelper.getHeight(element.characterFormat);\n var charHeight = textSizeInfo.Height;\n var baselineOffset = textSizeInfo.BaselineOffset;\n // tslint:disable-next-line:max-line-length\n maxLineHeight = (element.margin.top < 0 && baselineOffset > element.margin.top + element.height) ? element.margin.top + element.height + charHeight - baselineOffset : charHeight;\n if (!isEmptySelection) {\n maxLineHeight += element.margin.bottom;\n }\n }\n else {\n isItalic = previousInline.characterFormat.italic;\n // tslint:disable-next-line:max-line-length\n return this.getCaretHeight(previousInline, previousInline.length, previousInline.characterFormat, isEmptySelection, topMargin, isItalic);\n }\n }\n }\n else {\n var baselineAlignment = format.baselineAlignment;\n var elementHeight = heightElement;\n if (baselineAlignment !== 'Normal' && isEmptySelection) {\n //Set the caret height as sub/super script text height and updates the top margin for sub script text.\n elementHeight = elementHeight / 1.5;\n if (baselineAlignment === 'Subscript') {\n topMargin = heightElement - elementHeight;\n }\n }\n maxLineHeight = (margin.top < 0 ? margin.top : 0) + elementHeight;\n if (!isEmptySelection) {\n maxLineHeight += margin.bottom;\n }\n }\n if (!isEmptySelection) {\n return { 'height': maxLineHeight, 'topMargin': topMargin, 'isItalic': isItalic };\n }\n var height = this.viewer.textHelper.getHeight(format).Height;\n if (height > maxLineHeight) {\n height = maxLineHeight;\n }\n return { 'height': height, 'topMargin': topMargin, 'isItalic': isItalic };\n };\n /**\n * Get field characters height\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getFieldCharacterHeight = function (startInline, format, isEmptySelection, topMargin, isItalic) {\n var nextValidInline = this.getNextValidElementForField(startInline);\n //If field separator/end exists at end of paragraph, then move to next paragraph.\n if (isNullOrUndefined(nextValidInline)) {\n var nextParagraph = startInline.line.paragraph;\n var height = this.viewer.textHelper.getParagraphMarkSize(format).Height;\n var top_3 = 0;\n var bottom = 0;\n var sizeInfo = this.getParagraphMarkSize(nextParagraph, top_3, bottom);\n var maxLineHeight = sizeInfo.height;\n top_3 = sizeInfo.topMargin;\n bottom = sizeInfo.bottomMargin;\n if (!isEmptySelection) {\n maxLineHeight += bottom;\n return { 'height': maxLineHeight, 'topMargin': topMargin, 'isItalic': isItalic };\n }\n if (height > maxLineHeight) {\n height = maxLineHeight;\n }\n return { 'height': height, 'topMargin': topMargin, 'isItalic': isItalic };\n }\n else {\n return this.getCaretHeight(nextValidInline, 0, format, isEmptySelection, topMargin, isItalic);\n }\n };\n /**\n * Get rendered inline\n * @private\n */\n //FieldCharacter\n Selection.prototype.getRenderedInline = function (inline, inlineIndex) {\n var prevInline = this.getPreviousValidElement(inline);\n while (prevInline instanceof FieldElementBox) {\n prevInline = this.getPreviousTextElement(prevInline);\n if (prevInline instanceof FieldElementBox) {\n prevInline = prevInline.previousNode;\n }\n }\n if (!isNullOrUndefined(prevInline)) {\n inlineIndex = prevInline.length;\n return { 'element': prevInline, 'index': inlineIndex };\n }\n inlineIndex = 0;\n var nextInline = this.getNextRenderedElementBox(inline, 0);\n if (nextInline instanceof FieldElementBox && nextInline.fieldType === 0) {\n nextInline = nextInline.fieldSeparator;\n nextInline = nextInline.nextNode;\n while (nextInline instanceof FieldElementBox) {\n if (nextInline instanceof FieldElementBox && nextInline.fieldType === 0\n && HelperMethods.isLinkedFieldCharacter(nextInline)) {\n if (isNullOrUndefined(nextInline.fieldSeparator)) {\n nextInline = nextInline.fieldEnd;\n }\n else {\n nextInline = nextInline.fieldSeparator;\n }\n }\n nextInline = nextInline.nextNode;\n }\n }\n return { 'element': nextInline, 'index': inlineIndex };\n };\n //Field Begin\n /**\n * Get rendered field\n * @private\n */\n Selection.prototype.getRenderedField = function (fieldBegin) {\n var inline = fieldBegin;\n if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n inline = fieldBegin.fieldEnd;\n }\n else {\n inline = fieldBegin.fieldSeparator;\n var paragraph = inline.line.paragraph;\n if (paragraph === fieldBegin.fieldEnd.line.paragraph\n && !this.hasValidInline(paragraph, inline, fieldBegin.fieldEnd)) {\n inline = fieldBegin.fieldEnd;\n }\n else {\n return inline;\n }\n }\n return inline;\n };\n /**\n * Return true is inline is tha last inline\n * @private\n */\n Selection.prototype.isLastRenderedInline = function (inline, index) {\n while (index === inline.length && inline.nextNode instanceof FieldElementBox) {\n var nextValidInline = this.getNextValidElement(inline.nextNode);\n index = 0;\n if (nextValidInline instanceof FieldElementBox && nextValidInline.fieldType === 0) {\n inline = nextValidInline;\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 0 && !isNullOrUndefined(inline.fieldEnd)) {\n var fieldBegin = inline;\n if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n inline = fieldBegin.fieldEnd;\n index = 1;\n }\n else {\n inline = fieldBegin.fieldSeparator;\n var paragraph = inline.line.paragraph;\n index = 1;\n if (paragraph === fieldBegin.fieldEnd.line.paragraph\n && !this.hasValidInline(paragraph, inline, fieldBegin.fieldEnd)) {\n inline = fieldBegin.fieldEnd;\n }\n else {\n break;\n }\n }\n }\n }\n return index === inline.length && isNullOrUndefined(inline.nextNode);\n };\n /**\n * Get page\n * @private\n */\n Selection.prototype.getPage = function (widget) {\n var page = undefined;\n if (widget.containerWidget instanceof BlockContainer) {\n var bodyWidget = widget.containerWidget;\n page = widget.containerWidget.page;\n }\n else if (!isNullOrUndefined(widget.containerWidget)) {\n page = this.getPage(widget.containerWidget);\n }\n return page;\n };\n /**\n * Clear Selection highlight\n * @private\n */\n Selection.prototype.clearSelectionHighlightInSelectedWidgets = function () {\n var isNonEmptySelection = false;\n var widgets = this.selectedWidgets.keys;\n for (var i = 0; i < widgets.length; i++) {\n this.removeSelectionHighlight(widgets[i]);\n isNonEmptySelection = true;\n }\n this.selectedWidgets.clear();\n return isNonEmptySelection;\n };\n /**\n * Clear selection highlight\n * @private\n */\n Selection.prototype.clearChildSelectionHighlight = function (widget) {\n for (var i = 0; i < widget.childWidgets.length; i++) {\n if (widget.childWidgets[i] instanceof LineWidget) {\n this.clearSelectionHighlightLineWidget(widget.childWidgets[i]);\n }\n else if (widget.childWidgets[i] instanceof TableCellWidget) {\n this.clearSelectionHighlight(widget.childWidgets[i]);\n }\n else if (widget.childWidgets[i] instanceof Widget) {\n this.clearChildSelectionHighlight(widget.childWidgets[i]);\n }\n }\n };\n /**\n * Get line widget from paragraph widget\n * @private\n */\n //Body Widget\n Selection.prototype.getLineWidgetBodyWidget = function (widget, point) {\n for (var i = 0; i < widget.childWidgets.length; i++) {\n var childWidget = widget.childWidgets[i];\n if (childWidget instanceof Widget && childWidget.y <= point.y\n && (childWidget.y + childWidget.height) >= point.y) {\n if (childWidget instanceof ParagraphWidget) {\n return this.getLineWidgetParaWidget(childWidget, point);\n }\n else {\n return this.getLineWidgetTableWidget(childWidget, point);\n }\n }\n }\n var line = undefined;\n if (widget.childWidgets.length > 0) {\n var firstChild = widget.childWidgets[0];\n if (firstChild instanceof Widget && firstChild.y <= point.y) {\n if (widget.childWidgets[widget.childWidgets.length - 1] instanceof ParagraphWidget) {\n // tslint:disable-next-line:max-line-length\n line = this.getLineWidgetParaWidget(widget.childWidgets[widget.childWidgets.length - 1], point);\n }\n else {\n // tslint:disable-next-line:max-line-length\n line = this.getLineWidgetTableWidget(widget.childWidgets[widget.childWidgets.length - 1], point);\n }\n }\n else {\n var childWidget = undefined;\n if (firstChild instanceof Widget) {\n childWidget = firstChild;\n }\n if (!isNullOrUndefined(childWidget)) {\n if (childWidget instanceof ParagraphWidget) {\n line = this.getLineWidgetParaWidget(firstChild, point);\n }\n else {\n line = this.getLineWidgetTableWidget(firstChild, point);\n }\n }\n }\n }\n return line;\n };\n //ParagraphWidget\n /**\n * Get line widget from paragraph widget\n * @private\n */\n Selection.prototype.getLineWidgetParaWidget = function (widget, point) {\n var childWidgets = widget.childWidgets;\n var top = widget.y;\n for (var i = 0; i < childWidgets.length; i++) {\n if (top <= point.y\n && (top + childWidgets[i].height) >= point.y) {\n return childWidgets[i];\n }\n top += childWidgets[i].height;\n }\n var lineWidget = undefined;\n if (childWidgets.length > 0) {\n if (widget.y <= point.y) {\n lineWidget = childWidgets[childWidgets.length - 1];\n }\n else {\n lineWidget = childWidgets[0];\n }\n }\n return lineWidget;\n };\n /**\n * highlight paragraph widget\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.highlightParagraph = function (widget, startIndex, endLine, endElement, endIndex) {\n var top = 0;\n for (var i = startIndex; i < widget.childWidgets.length; i++) {\n var line = widget.childWidgets[i];\n if (i === startIndex) {\n top = this.getTop(line);\n }\n var left = this.getLeft(line);\n if (line === endLine) {\n //Selection ends in current line.\n var right = this.getLeftInternal(endLine, endElement, endIndex);\n this.createHighlightBorder(line, right - left, left, top);\n return;\n }\n this.createHighlightBorder(line, this.getWidth(line, true) - (left - widget.x), left, top);\n top += line.height;\n }\n };\n //Table Widget\n /**\n * Get line widget form table widget\n * @private\n */\n Selection.prototype.getLineWidgetTableWidget = function (widget, point) {\n var lineWidget = undefined;\n for (var i = 0; i < widget.childWidgets.length; i++) {\n //Removed the height condition check to handle the vertically merged cells.\n var childWidget = widget.childWidgets[i];\n if (childWidget instanceof TableRowWidget && childWidget.y <= point.y) {\n lineWidget = this.getLineWidgetRowWidget(childWidget, point);\n var cellWidget = undefined;\n if (!isNullOrUndefined(lineWidget) && lineWidget.paragraph.containerWidget instanceof TableCellWidget) {\n cellWidget = lineWidget.paragraph.containerWidget;\n }\n var cellSpacing = 0;\n var rowSpan = 0;\n if (!isNullOrUndefined(cellWidget)) {\n var tableWidget = cellWidget.ownerRow.containerWidget;\n cellSpacing = HelperMethods.convertPointToPixel(tableWidget.tableFormat.cellSpacing);\n rowSpan = cellWidget.cellFormat.rowSpan;\n }\n var leftCellSpacing = 0;\n var rightCellSpacing = 0;\n var topCellSpacing = 0;\n var bottomCellSpacing = 0;\n if (cellSpacing > 0) {\n leftCellSpacing = cellWidget.cellIndex === 0 ? cellSpacing : cellSpacing / 2;\n // tslint:disable-next-line:max-line-length\n rightCellSpacing = cellWidget.cellIndex === cellWidget.ownerRow.childWidgets.length - 1 ? cellSpacing : cellSpacing / 2;\n var rowWidget = undefined;\n if (cellWidget.containerWidget instanceof TableRowWidget) {\n rowWidget = cellWidget.containerWidget;\n }\n var tableWidget = undefined;\n if (cellWidget.containerWidget.containerWidget instanceof TableWidget) {\n tableWidget = cellWidget.containerWidget.containerWidget;\n }\n if (!isNullOrUndefined(rowWidget) && !isNullOrUndefined(tableWidget)) {\n topCellSpacing = cellWidget.ownerRow.rowIndex === 0 ? cellSpacing : cellSpacing / 2;\n if (cellWidget.ownerRow.rowIndex + rowSpan === cellWidget.ownerTable.childWidgets.length) {\n bottomCellSpacing = cellSpacing;\n }\n else {\n bottomCellSpacing = cellSpacing / 2;\n }\n }\n }\n if ((!isNullOrUndefined(lineWidget) && lineWidget.paragraph.x <= point.x\n && lineWidget.paragraph.x + lineWidget.width >= point.x\n && lineWidget.paragraph.y <= point.y && this.getTop(lineWidget) + lineWidget.height >= point.y)\n || (!isNullOrUndefined(cellWidget) && cellWidget.x - cellWidget.margin.left - leftCellSpacing <= point.x\n && cellWidget.x + cellWidget.width + cellWidget.margin.right + rightCellSpacing >= point.x\n && cellWidget.y - cellWidget.margin.top - topCellSpacing <= point.y\n && cellWidget.y + cellWidget.height + cellWidget.margin.bottom + bottomCellSpacing >= point.y)) {\n break;\n }\n }\n }\n return lineWidget;\n };\n //TableRowWidget\n /**\n * Get line widget fom row\n * @private\n */\n Selection.prototype.getLineWidgetRowWidget = function (widget, point) {\n for (var i = 0; i < widget.childWidgets.length; i++) {\n var cellSpacing = 0;\n cellSpacing = HelperMethods.convertPointToPixel(widget.ownerTable.tableFormat.cellSpacing);\n var leftCellSpacing = 0;\n var rightCellSpacing = 0;\n if (cellSpacing > 0) {\n leftCellSpacing = widget.childWidgets[i].columnIndex === 0 ? cellSpacing : cellSpacing / 2;\n // tslint:disable-next-line:max-line-length\n rightCellSpacing = widget.childWidgets[i].cellIndex === widget.childWidgets[i].ownerRow.childWidgets.length - 1 ? cellSpacing : cellSpacing / 2;\n }\n if (widget.childWidgets[i].x -\n // tslint:disable-next-line:max-line-length\n widget.childWidgets[i].margin.left - leftCellSpacing <= point.x && (widget.childWidgets[i].x +\n // tslint:disable-next-line:max-line-length\n widget.childWidgets[i].width) + widget.childWidgets[i].margin.right + rightCellSpacing >= point.x) {\n return this.getLineWidgetCellWidget(widget.childWidgets[i], point);\n }\n }\n var lineWidget = undefined;\n if (widget.childWidgets.length > 0) {\n if (widget.childWidgets[0].x <= point.x) {\n lineWidget = this.getLineWidgetCellWidget(widget.childWidgets[widget.childWidgets.length - 1], point);\n }\n else {\n lineWidget = this.getLineWidgetCellWidget(widget.childWidgets[0], point);\n }\n }\n return lineWidget;\n };\n /**\n * @private\n */\n Selection.prototype.getFirstBlock = function (cell) {\n if (cell.childWidgets.length > 0) {\n return cell.childWidgets[0];\n }\n return undefined;\n };\n //Table Cell Widget\n /**\n * Highlight selected cell widget\n * @private\n */\n Selection.prototype.highlightCellWidget = function (widget) {\n var widgets = [];\n if (widget.previousSplitWidget || widget.nextSplitWidget) {\n widgets = widget.getSplitWidgets();\n }\n else {\n widgets.push(widget);\n }\n for (var i = 0; i < widgets.length; i++) {\n widget = widgets[i];\n //Clears Selection highlight of the child widgets.\n this.clearChildSelectionHighlight(widget);\n //Highlights the entire cell.\n this.createHighlightBorderInsideTable(widget);\n }\n };\n /**\n * Clear selection highlight\n * @private\n */\n Selection.prototype.clearSelectionHighlight = function (widget) {\n if (this.selectedWidgets.containsKey(widget)) {\n this.removeSelectionHighlight(widget);\n this.selectedWidgets.remove(widget);\n }\n };\n /**\n * Get line widget from cell widget\n * @private\n */\n Selection.prototype.getLineWidgetCellWidget = function (widget, point) {\n for (var i = 0; i < widget.childWidgets.length; i++) {\n if (widget.childWidgets[i].y <= point.y\n && (widget.childWidgets[i].y + widget.childWidgets[i].height) >= point.y) {\n if (widget.childWidgets[i] instanceof ParagraphWidget) {\n return this.getLineWidgetParaWidget(widget.childWidgets[i], point);\n }\n else {\n return this.getLineWidgetTableWidget(widget.childWidgets[i], point);\n }\n }\n }\n var lineWidget = undefined;\n if (widget.childWidgets.length > 0) {\n if (widget.childWidgets[0].y <= point.y) {\n if (widget.childWidgets[widget.childWidgets.length - 1] instanceof ParagraphWidget) {\n // tslint:disable-next-line:max-line-length\n lineWidget = this.getLineWidgetParaWidget(widget.childWidgets[widget.childWidgets.length - 1], point);\n }\n else {\n lineWidget = this.getLineWidgetTableWidget(widget.childWidgets[0], point);\n }\n }\n }\n return lineWidget;\n };\n //LineWidget\n /**\n * update text position\n * @private\n */\n Selection.prototype.updateTextPosition = function (widget, point) {\n var caretPosition = point;\n var element = undefined;\n var index = 0;\n var isImageSelected = false;\n var isImageSelectedObj = this.updateTextPositionIn(widget, element, index, point, false);\n if (!isNullOrUndefined(isImageSelectedObj)) {\n element = isImageSelectedObj.element;\n index = isImageSelectedObj.index;\n caretPosition = isImageSelectedObj.caretPosition;\n isImageSelected = isImageSelectedObj.isImageSelected;\n this.isImageSelected = isImageSelected;\n }\n if (isImageSelected) {\n this.selectInternal(widget, element, index, caretPosition);\n if (index === 0) {\n this.extendForward();\n }\n else {\n this.extendBackward();\n }\n }\n else {\n this.selectInternal(widget, element, index, caretPosition);\n }\n };\n /**\n * @private\n */\n /* tslint:disable */\n Selection.prototype.updateTextPositionIn = function (widget, inline, index, caretPosition, includeParagraphMark) {\n var isImageSelected = false;\n var top = this.getTop(widget);\n var left = widget.paragraph.x;\n var elementValues = this.getFirstElement(widget, left);\n var element = elementValues.element;\n left = elementValues.left;\n if (isNullOrUndefined(element)) {\n var topMargin = 0;\n var bottomMargin = 0;\n var size = this.getParagraphMarkSize(widget.paragraph, topMargin, bottomMargin);\n topMargin = size.topMargin;\n bottomMargin = size.bottomMargin;\n var selectParaMark = this.viewer.mouseDownOffset.y >= top && this.viewer.mouseDownOffset.y < top + widget.height ? (this.viewer.mouseDownOffset.x < left + size.width) : true;\n if (selectParaMark && includeParagraphMark && caretPosition.x > left + size.width / 2) {\n left += size.width;\n if (widget.children.length > 0) {\n inline = widget.children[widget.children.length - 1];\n index = inline.length;\n }\n index++;\n }\n caretPosition = new Point(left, topMargin > 0 ? top + topMargin : top);\n }\n else {\n if (!isNullOrUndefined(element)) {\n if (caretPosition.x > left + element.margin.left) {\n for (var i = widget.children.indexOf(element); i < widget.children.length; i++) {\n element = widget.children[i];\n if (caretPosition.x < left + element.margin.left + element.width || i === widget.children.length - 1) {\n break;\n }\n left += element.margin.left + element.width;\n }\n if (caretPosition.x > left + element.margin.left + element.width) {\n //Line End\n index = element instanceof TextElementBox ? element.length : 1;\n left += element.margin.left + element.width;\n }\n else if (element instanceof TextElementBox) {\n var x = caretPosition.x - left - element.margin.left;\n left += element.margin.left;\n var prevWidth = 0;\n var charIndex = 0;\n for (var i = 1; i <= element.length; i++) {\n var width = 0;\n if (i === element.length) {\n width = element.width;\n }\n else {\n width = this.viewer.textHelper.getWidth(element.text.substr(0, i), element.characterFormat);\n }\n if (x < width || i === element.length) {\n //Updates exact left position of the caret.\n var charWidth = width - prevWidth;\n if (x - prevWidth > charWidth / 2) {\n left += width;\n charIndex = i;\n }\n else {\n left += prevWidth;\n charIndex = i - 1;\n if (i === 1 && element !== widget.children[0]) {\n var curIndex = widget.children.indexOf(element);\n if (!(widget.children[curIndex - 1] instanceof ListTextElementBox)) {\n element = widget.children[curIndex - 1];\n charIndex = element instanceof TextElementBox ? element.length : 1;\n }\n }\n }\n break;\n }\n prevWidth = width;\n }\n index = charIndex;\n }\n else {\n isImageSelected = element instanceof ImageElementBox;\n if (caretPosition.x - left - element.margin.left > element.width / 2) {\n index = 1;\n left += element.margin.left + element.width;\n }\n else if (element !== widget.children[0] && !isImageSelected) {\n var curIndex = widget.children.indexOf(element);\n if (!(widget.children[curIndex - 1] instanceof ListTextElementBox)) {\n element = widget.children[curIndex - 1];\n index = element instanceof TextElementBox ? element.length : 1;\n }\n }\n }\n if (element instanceof TextElementBox && element.text === '\\v') {\n index = 0;\n }\n }\n else {\n left += element.margin.left;\n }\n if (element instanceof TextElementBox) {\n top += element.margin.top > 0 ? element.margin.top : 0;\n }\n else {\n var textMetrics = this.viewer.textHelper.getHeight(element.characterFormat); //for ascent and descent\n var height = textMetrics.Height; //after text helper class\n var baselineOffset = textMetrics.BaselineOffset; //baseline calculation\n top += element.margin.top + element.height - baselineOffset;\n }\n inline = element;\n var inlineObj = this.validateTextPosition(inline, index);\n inline = inlineObj.element;\n index = inlineObj.index;\n var isParagraphEnd = isNullOrUndefined(inline.nextNode) && index === inline.length;\n var isLineEnd = isNullOrUndefined(inline.nextNode)\n && inline instanceof TextElementBox && inline.text === '\\v';\n if (includeParagraphMark && inline.nextNode instanceof FieldElementBox && index === inline.length) {\n isParagraphEnd = this.isLastRenderedInline(inline, index);\n }\n if (includeParagraphMark && isParagraphEnd || isLineEnd) {\n var width = 0;\n //Include width of Paragraph mark.\n if (isParagraphEnd) {\n width = this.viewer.textHelper.getParagraphMarkWidth(widget.paragraph.characterFormat);\n var selectParaMark = this.viewer.mouseDownOffset.y >= top && this.viewer.mouseDownOffset.y < top + widget.height ? (this.viewer.mouseDownOffset.x < left + width) : true;\n if (selectParaMark && caretPosition.x > left + width / 2) {\n left += width;\n index = inline.length + 1;\n }\n //Include width of line break mark.\n }\n else if (isLineEnd) {\n width = element.width;\n left += width;\n index = inline.length;\n }\n }\n caretPosition = new Point(left, top);\n }\n }\n return {\n 'element': inline,\n 'index': index,\n 'caretPosition': caretPosition,\n 'isImageSelected': isImageSelected\n };\n };\n /* tslint:enable */\n /**\n * Get text length if the line widget\n * @private\n */\n // public getTextLength(viewer: LayoutViewer, widget: LineWidget, element: ElementBox): number {\n // let length: number = 0;\n // let count: number = widget.children.indexOf(element);\n // if (widget.children.length > 0 && widget.children[0] instanceof ListTextElementBox) {\n // if (widget.children[1] instanceof ListTextElementBox) {\n // count -= 2;\n // } else {\n // count -= 1;\n // }\n // }\n // for (let i: number = 1; i < count; i++) {\n // length += widget.children[i].length;\n // }\n // return length;\n // }\n /**\n * Get Line widget left\n * @private\n */\n Selection.prototype.getLeft = function (widget) {\n var left = widget.paragraph.x;\n var paragraphFormat = widget.paragraph.paragraphFormat;\n if (this.isParagraphFirstLine(widget) && !(paragraphFormat.textAlignment === 'Right')) {\n left += HelperMethods.convertPointToPixel(paragraphFormat.firstLineIndent);\n }\n for (var i = 0; i < widget.children.length; i++) {\n var element = widget.children[i];\n if (element instanceof ListTextElementBox) {\n if (i === 0) {\n left += element.margin.left + element.width;\n }\n else {\n left += element.width;\n }\n }\n else {\n left += element.margin.left;\n break;\n }\n }\n return left;\n };\n /**\n * Get line widget top\n * @private\n */\n Selection.prototype.getTop = function (widget) {\n var top = widget.paragraph.y;\n var count = widget.paragraph.childWidgets.indexOf(widget);\n for (var i = 0; i < count; i++) {\n top += widget.paragraph.childWidgets[i].height;\n }\n return top;\n };\n /**\n * Get first element the widget\n * @private\n */\n Selection.prototype.getFirstElement = function (widget, left) {\n var firstLineIndent = 0;\n if (this.isParagraphFirstLine(widget)) {\n firstLineIndent = HelperMethods.convertPointToPixel(widget.paragraph.paragraphFormat.firstLineIndent);\n }\n left += firstLineIndent;\n var element = undefined;\n for (var i = 0; i < widget.children.length; i++) {\n element = widget.children[i];\n if (element instanceof ListTextElementBox) {\n left += element.margin.left + element.width;\n element = undefined;\n }\n else {\n break;\n }\n }\n return { 'element': element, 'left': left };\n };\n /**\n * Return inline index\n * @private\n */\n //ElementBox\n Selection.prototype.getIndexInInline = function (elementBox) {\n var indexInInline = 0;\n if (elementBox instanceof TextElementBox) {\n var count = elementBox.line.children.indexOf(elementBox);\n for (var i = 0; i < count; i++) {\n var element = elementBox.line.children[i];\n if (element instanceof FieldElementBox || element instanceof ListTextElementBox) {\n continue;\n }\n indexInInline += element.length;\n }\n }\n return indexInInline;\n };\n /**\n * Return true if widget is first inline of paragraph\n * @private\n */\n Selection.prototype.isParagraphFirstLine = function (widget) {\n if (isNullOrUndefined(widget.paragraph.previousSplitWidget) &&\n widget === widget.paragraph.firstChild) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n Selection.prototype.isParagraphLastLine = function (widget) {\n if (isNullOrUndefined(widget.paragraph.nextSplitWidget)\n && widget === widget.paragraph.lastChild) {\n return true;\n }\n return false;\n };\n /**\n * Return line widget width\n * @private\n */\n Selection.prototype.getWidth = function (widget, includeParagraphMark) {\n var width = 0;\n if (this.isParagraphFirstLine(widget)) {\n width += HelperMethods.convertPointToPixel(widget.paragraph.paragraphFormat.firstLineIndent);\n }\n for (var i = 0; i < widget.children.length; i++) {\n width += widget.children[i].margin.left + widget.children[i].width;\n }\n if (includeParagraphMark && widget.paragraph.childWidgets.indexOf(widget) === widget.paragraph.childWidgets.length - 1\n && isNullOrUndefined(widget.paragraph.nextSplitWidget)) {\n width += this.viewer.textHelper.getParagraphMarkWidth(widget.paragraph.characterFormat);\n }\n return width;\n };\n /**\n * Return line widget left\n * @private\n */\n Selection.prototype.getLeftInternal = function (widget, elementBox, index) {\n var left = widget.paragraph.x;\n if (this.isParagraphFirstLine(widget)) {\n // tslint:disable-next-line:max-line-length\n left += HelperMethods.convertPointToPixel(widget.paragraph.paragraphFormat.firstLineIndent);\n }\n var count = widget.children.indexOf(elementBox);\n if ((widget.children.length === 1 && widget.children[0] instanceof ListTextElementBox) || (widget.children.length === 2\n && widget.children[0] instanceof ListTextElementBox && widget.children[1] instanceof ListTextElementBox)) {\n count = widget.children.length;\n }\n for (var i = 0; i < count; i++) {\n var widgetInternal = widget.children[i];\n if (i === 1 && widget.children[i] instanceof ListTextElementBox) {\n left += widget.children[i].width;\n }\n else {\n left += widget.children[i].margin.left + widget.children[i].width;\n }\n }\n if (!isNullOrUndefined(elementBox)) {\n left += elementBox.margin.left;\n }\n if (elementBox instanceof TextElementBox) {\n if (index === elementBox.length) {\n left += elementBox.width;\n }\n else if (index > elementBox.length) {\n // tslint:disable-next-line:max-line-length\n left += elementBox.width + this.viewer.textHelper.getParagraphMarkWidth(elementBox.line.paragraph.characterFormat);\n }\n else {\n // tslint:disable-next-line:max-line-length\n left += this.viewer.textHelper.getWidth(elementBox.text.substr(0, index), elementBox.characterFormat);\n }\n }\n else if (index > 0) {\n if (!isNullOrUndefined(elementBox) && !(elementBox instanceof ListTextElementBox)) {\n left += elementBox.width;\n if (index === 2) {\n var paragraph = elementBox.line.paragraph;\n left += this.viewer.textHelper.getParagraphMarkWidth(paragraph.characterFormat);\n }\n }\n else {\n left += this.viewer.textHelper.getParagraphMarkWidth(widget.paragraph.characterFormat);\n }\n }\n return left;\n };\n /**\n * Return line widget start offset\n * @private\n */\n Selection.prototype.getLineStartLeft = function (widget) {\n var left = widget.paragraph.x;\n if (this.isParagraphFirstLine(widget)) {\n left += HelperMethods.convertPointToPixel(widget.paragraph.paragraphFormat.firstLineIndent);\n }\n if (widget.children.length > 0) {\n left += widget.children[0].margin.left;\n }\n return left;\n };\n /**\n * Update text position\n * @private\n */\n Selection.prototype.updateTextPositionWidget = function (widget, point, textPosition, includeParagraphMark) {\n var caretPosition = point;\n var inline = undefined;\n var index = 0;\n var updatePositionObj;\n updatePositionObj = this.updateTextPositionIn(widget, inline, index, caretPosition, includeParagraphMark);\n inline = updatePositionObj.element;\n index = updatePositionObj.index;\n caretPosition = updatePositionObj.caretPosition;\n textPosition.setPositionForSelection(widget, inline, index, caretPosition);\n };\n /**\n * Clear selection highlight\n * @private\n */\n Selection.prototype.clearSelectionHighlightLineWidget = function (widget) {\n if (!isNullOrUndefined(this.owner) && this.selectedWidgets.length > 0) {\n this.clearSelectionHighlight(this);\n }\n };\n /**\n * Return first element from line widget\n * @private\n */\n Selection.prototype.getFirstElementInternal = function (widget) {\n var element = undefined;\n for (var i = 0; i < widget.children.length; i++) {\n element = widget.children[i];\n if (element instanceof ListTextElementBox) {\n element = undefined;\n }\n else {\n break;\n }\n }\n return element;\n };\n //Selection API \n /**\n * Select content between given range\n * @private\n */\n Selection.prototype.selectRange = function (startPosition, endPosition) {\n this.start.setPositionInternal(startPosition);\n this.end.setPositionInternal(endPosition);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Selects current paragraph\n * @private\n */\n Selection.prototype.selectParagraph = function (paragraph, positionAtStart) {\n var line = paragraph.firstChild;\n if (positionAtStart) {\n this.start.setPosition(line, positionAtStart);\n }\n else {\n var endOffset = line.getEndOffset();\n this.start.setPositionParagraph(line, endOffset);\n }\n this.end.setPositionInternal(this.start);\n this.upDownSelectionLength = this.start.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * @private\n */\n Selection.prototype.setPositionForBlock = function (block, selectFirstBlock) {\n var position;\n if (block instanceof TableWidget) {\n if (selectFirstBlock) {\n block = this.getFirstParagraphInFirstCell(block);\n }\n else {\n block = this.getLastParagraphInLastCell(block);\n }\n }\n if (block instanceof ParagraphWidget) {\n position = new TextPosition(this.owner);\n if (selectFirstBlock) {\n position.setPosition(block.firstChild, true);\n }\n else {\n var line = block.lastChild;\n position.setPositionParagraph(line, line.getEndOffset());\n }\n }\n return position;\n };\n /**\n * Select content in given text position\n * @private\n */\n Selection.prototype.selectContent = function (textPosition, clearMultiSelection) {\n if (isNullOrUndefined(textPosition)) {\n throw new Error('textPosition is undefined.');\n }\n this.start.setPositionInternal(textPosition);\n this.end.setPositionInternal(textPosition);\n this.upDownSelectionLength = this.end.location.x;\n this.fireSelectionChanged(true);\n };\n /**\n * Select paragraph\n * @private\n */\n Selection.prototype.selectInternal = function (lineWidget, element, index, physicalLocation) {\n this.start.setPositionForSelection(lineWidget, element, index, physicalLocation);\n this.end.setPositionInternal(this.start);\n this.upDownSelectionLength = physicalLocation.x;\n this.fireSelectionChanged(true);\n };\n /**\n * @private\n */\n Selection.prototype.selects = function (lineWidget, offset, skipSelectionChange) {\n this.viewer.clearSelectionHighlight();\n this.start.setPositionForLineWidget(lineWidget, offset);\n this.end.setPositionInternal(this.start);\n if (!skipSelectionChange) {\n this.fireSelectionChanged(true);\n }\n };\n /**\n * Select content between start and end position\n * @private\n */\n Selection.prototype.selectPosition = function (startPosition, endPosition) {\n if (isNullOrUndefined(startPosition) || isNullOrUndefined(endPosition)) {\n throw new Error('TextPosition cannot be undefined');\n }\n if (isNullOrUndefined(startPosition.paragraph)\n || startPosition.offset > this.getParagraphLength(startPosition.paragraph) + 1) {\n throw new Error('Start TextPosition is not valid.');\n }\n if (isNullOrUndefined(endPosition.paragraph)\n || endPosition.offset > this.getParagraphLength(endPosition.paragraph) + 1) {\n throw new Error('End TextPosition is not valid.');\n }\n if (startPosition.isAtSamePosition(endPosition)) {\n // Select start position.\n this.selectRange(startPosition, startPosition);\n }\n else {\n // If both text position exists within same comment or outside comment, and not at same position.\n if (startPosition.isExistBefore(endPosition)) {\n // tslint:disable-next-line:max-line-length\n endPosition.validateForwardFieldSelection(startPosition.getHierarchicalIndexInternal(), endPosition.getHierarchicalIndexInternal());\n }\n else {\n // tslint:disable-next-line:max-line-length\n startPosition.validateForwardFieldSelection(endPosition.getHierarchicalIndexInternal(), startPosition.getHierarchicalIndexInternal());\n }\n this.selectRange(startPosition, endPosition);\n }\n };\n /**\n * Notify selection change event\n * @private\n */\n Selection.prototype.fireSelectionChanged = function (isSelectionChanged) {\n if (!this.isEmpty) {\n if (this.isForward) {\n this.start.updatePhysicalPosition(true);\n this.end.updatePhysicalPosition(false);\n }\n else {\n this.start.updatePhysicalPosition(false);\n this.end.updatePhysicalPosition(true);\n }\n }\n if (!this.skipFormatRetrieval) {\n this.retrieveCurrentFormatProperties();\n }\n this.viewer.clearSelectionHighlight();\n this.hideToolTip();\n if (this.owner.isLayoutEnabled && !this.owner.isShiftingEnabled) {\n this.highlightSelection(true);\n }\n if (isSelectionChanged) {\n if (this.start.paragraph.isInHeaderFooter && !this.owner.enableHeaderAndFooter) {\n this.owner.enableHeaderAndFooter = true;\n }\n else if (!this.start.paragraph.isInHeaderFooter && this.owner.enableHeaderAndFooter) {\n this.owner.enableHeaderAndFooter = false;\n }\n this.owner.fireSelectionChange();\n }\n this.viewer.updateFocus();\n };\n //Formats Retrieval\n /**\n * Retrieve all current selection format\n * @private\n */\n Selection.prototype.retrieveCurrentFormatProperties = function () {\n this.isRetrieveFormatting = true;\n var startPosition = this.start;\n var endPosition = this.end;\n if (!this.isForward) {\n startPosition = this.end;\n endPosition = this.start;\n }\n this.retrieveImageFormat(startPosition, endPosition);\n this.retrieveCharacterFormat(startPosition, endPosition);\n this.retrieveParagraphFormat(startPosition, endPosition);\n this.retrieveSectionFormat(startPosition, endPosition);\n this.retrieveTableFormat(startPosition, endPosition);\n if (!this.isImageSelected) {\n this.imageFormat.clearImageFormat();\n }\n this.isRetrieveFormatting = false;\n this.setCurrentContextType();\n };\n /**\n * @private\n */\n Selection.prototype.retrieveImageFormat = function (start, end) {\n var image;\n if (start.currentWidget === end.currentWidget && start.offset + 1 === end.offset) {\n var elementInfo = end.currentWidget.getInline(end.offset, 0);\n image = elementInfo.element;\n var index = elementInfo.index;\n if (image instanceof ImageElementBox) {\n var startOffset = start.currentWidget.getOffset(image, 0);\n if (startOffset !== start.offset) {\n image = undefined;\n }\n }\n }\n if (image instanceof ImageElementBox) {\n this.imageFormat.copyImageFormat(image);\n }\n else {\n this.imageFormat.clearImageFormat();\n }\n };\n Selection.prototype.setCurrentContextType = function () {\n var contextIsinImage = this.imageFormat.image ? true : false;\n var contextIsinTable = (isNullOrUndefined(this.tableFormat) || isNullOrUndefined(this.tableFormat.table)) ? false : true;\n var style = this.start.paragraph.paragraphFormat.baseStyle;\n if (style instanceof WParagraphStyle && style.name.toLowerCase().indexOf('toc') === 0) {\n var tocField = this.getTocFieldInternal();\n if (!isNullOrUndefined(tocField)) {\n this.contextTypeInternal = 'TableOfContents';\n return;\n }\n }\n if (this.start.paragraph.isInHeaderFooter) {\n var isInHeader = this.start.paragraph.bodyWidget.headerFooterType.indexOf('Header') !== -1;\n if (contextIsinTable) {\n if (contextIsinImage) {\n this.contextTypeInternal = isInHeader ? 'HeaderTableImage' : 'FooterTableImage';\n }\n else {\n this.contextTypeInternal = isInHeader ? 'HeaderTableText' : 'FooterTableText';\n }\n }\n else {\n if (contextIsinImage) {\n this.contextTypeInternal = isInHeader ? 'HeaderImage' : 'FooterImage';\n }\n else {\n this.contextTypeInternal = isInHeader ? 'HeaderText' : 'FooterText';\n }\n }\n }\n else {\n if (contextIsinTable) {\n this.contextTypeInternal = contextIsinImage ? 'TableImage' : 'TableText';\n }\n else {\n this.contextTypeInternal = contextIsinImage ? 'Image' : 'Text';\n }\n }\n };\n //Table Format retrieval starts\n /**\n * Retrieve selection table format\n * @private\n */\n Selection.prototype.retrieveTableFormat = function (start, end) {\n var tableAdv = this.getTable(start, end);\n if (!isNullOrUndefined(tableAdv)) {\n this.tableFormat.copyFormat(tableAdv.tableFormat);\n this.tableFormat.table = tableAdv;\n this.retrieveCellFormat(start, end);\n this.retrieveRowFormat(start, end);\n }\n else {\n //When the selection is out of table\n this.tableFormat.clearFormat();\n }\n };\n /**\n * Retrieve selection cell format\n * @private\n */\n Selection.prototype.retrieveCellFormat = function (start, end) {\n if (start.paragraph.isInsideTable && end.paragraph.isInsideTable) {\n this.cellFormat.copyFormat(start.paragraph.associatedCell.cellFormat);\n this.getCellFormat(start.paragraph.associatedCell.ownerTable, start, end);\n }\n else {\n //When the selection is out of table\n this.cellFormat.clearCellFormat();\n }\n };\n /**\n * Retrieve selection row format\n * @private\n */\n Selection.prototype.retrieveRowFormat = function (start, end) {\n if (start.paragraph.isInsideTable && end.paragraph.isInsideTable) {\n this.rowFormat.copyFormat(start.paragraph.associatedCell.ownerRow.rowFormat);\n this.getRowFormat(start.paragraph.associatedCell.ownerTable, start, end);\n }\n else {\n //When the selection is out of table\n this.rowFormat.clearRowFormat();\n }\n };\n /**\n * Get selected cell format\n * @private\n */\n Selection.prototype.getCellFormat = function (table, start, end) {\n if (start.paragraph.associatedCell.equals(end.paragraph.associatedCell)) {\n return;\n }\n var isStarted = false;\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row === start.paragraph.associatedCell.ownerRow) {\n isStarted = true;\n }\n if (isStarted) {\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n if (this.isCellSelected(cell, start, end)) {\n this.cellFormat.combineFormat(cell.cellFormat);\n }\n if (cell === end.paragraph.associatedCell) {\n this.cellFormat.combineFormat(cell.cellFormat);\n return;\n }\n }\n }\n }\n };\n /**\n * Get selected row format\n * @private\n */\n Selection.prototype.getRowFormat = function (table, start, end) {\n var tableRow = start.paragraph.associatedCell.ownerRow;\n if (tableRow === end.paragraph.associatedCell.ownerRow) {\n return;\n }\n for (var i = table.childWidgets.indexOf(tableRow) + 1; i < table.childWidgets.length; i++) {\n var tempTableRow = table.childWidgets[i];\n this.rowFormat.combineFormat(tempTableRow.rowFormat);\n if (tempTableRow === end.paragraph.associatedCell.ownerRow) {\n return;\n }\n }\n };\n /**\n * Return table with given text position\n * @private\n */\n Selection.prototype.getTable = function (startPosition, endPosition) {\n if (!isNullOrUndefined(startPosition.paragraph.associatedCell) && !isNullOrUndefined(endPosition.paragraph.associatedCell)) {\n var startTable = startPosition.paragraph.associatedCell.ownerTable;\n var endTable = startPosition.paragraph.associatedCell.ownerTable;\n if (startTable === endTable) {\n return startTable;\n }\n else {\n if (startTable.contains(startPosition.paragraph.associatedCell)) {\n return startTable;\n }\n else if (endTable.contains(startPosition.paragraph.associatedCell)) {\n return endTable;\n }\n else if (!startTable.isInsideTable || !endTable.isInsideTable) {\n return undefined;\n }\n else {\n do {\n startTable = startTable.associatedCell.ownerTable;\n if (startTable === endTable || startTable.contains(endTable.associatedCell)) {\n return startTable;\n }\n else if (endTable.contains(startTable.associatedCell)) {\n return endTable;\n }\n } while (!isNullOrUndefined(startTable.associatedCell));\n }\n }\n }\n return undefined;\n };\n Selection.prototype.getContainerWidget = function (block) {\n var bodyWidget;\n if (block.containerWidget instanceof BlockContainer) {\n bodyWidget = block.containerWidget;\n }\n else {\n bodyWidget = block.containerWidget;\n while (!(bodyWidget instanceof BlockContainer)) {\n bodyWidget = bodyWidget.containerWidget;\n }\n }\n return bodyWidget;\n };\n //Table format retrieval ends\n //Section format retrieval starts\n /**\n * Retrieve selection section format\n * @private\n */\n Selection.prototype.retrieveSectionFormat = function (start, end) {\n var startParaSection = this.getContainerWidget(start.paragraph);\n var endParaSection = this.getContainerWidget(end.paragraph);\n if (!isNullOrUndefined(startParaSection)) {\n this.sectionFormat.copyFormat(startParaSection.sectionFormat);\n var startPageIndex = this.viewer.pages.indexOf(startParaSection.page);\n var endPageIndex = this.viewer.pages.indexOf(endParaSection.page);\n for (var i = startPageIndex + 1; i <= endPageIndex; i++) {\n this.sectionFormat.combineFormat(this.viewer.pages[i].bodyWidgets[0].sectionFormat);\n }\n }\n };\n //section format retrieval ends.\n //Paragraph format retrieval implementation starts.\n /**\n * Retrieve selection paragraph format\n * @private\n */\n Selection.prototype.retrieveParagraphFormat = function (start, end) {\n this.getParagraphFormatForSelection(start.paragraph, this, start, end);\n };\n /**\n * @private\n */\n Selection.prototype.getParagraphFormatForSelection = function (paragraph, selection, start, end) {\n //Selection start in cell.\n if (start.paragraph.isInsideTable && (!end.paragraph.isInsideTable\n || start.paragraph.associatedCell !== end.paragraph.associatedCell\n || this.isCellSelected(start.paragraph.associatedCell, start, end))) {\n this.getParagraphFormatInternalInCell(start.paragraph.associatedCell, start, end);\n }\n else {\n this.getParagraphFormatInternalInParagraph(paragraph, start, end);\n }\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getParagraphFormatInternalInParagraph = function (paragraph, start, end) {\n if (start.paragraph === paragraph) {\n this.paragraphFormat.copyFormat(paragraph.paragraphFormat);\n }\n else {\n this.paragraphFormat.combineFormat(paragraph.paragraphFormat);\n }\n if (end.paragraph === paragraph) {\n return;\n }\n var block = this.getNextRenderedBlock(paragraph);\n if (!isNullOrUndefined(block)) {\n this.getParagraphFormatInternalInBlock(block, start, end);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getParagraphFormatInternalInBlock = function (block, start, end) {\n if (block instanceof ParagraphWidget) {\n this.getParagraphFormatInternalInParagraph(block, start, end);\n }\n else {\n this.getParagraphFormatInternalInTable(block, start, end);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getParagraphFormatInternalInTable = function (table, start, end) {\n for (var i = 0; i < table.childWidgets.length; i++) {\n var tableRow = table.childWidgets[i];\n for (var j = 0; j < tableRow.childWidgets.length; j++) {\n this.getParagraphFormatInCell(tableRow.childWidgets[j]);\n }\n if (end.paragraph.isInsideTable && this.containsRow(tableRow, end.paragraph.associatedCell)) {\n return;\n }\n }\n var block = this.getNextRenderedBlock(table);\n //Goto the next block.\n this.getParagraphFormatInternalInBlock(block, start, end);\n };\n /**\n * Get paragraph format in cell\n * @private\n */\n Selection.prototype.getParagraphFormatInCell = function (cell) {\n for (var i = 0; i < cell.childWidgets.length; i++) {\n this.getParagraphFormatInBlock(cell.childWidgets[i]);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getParagraphFormatInBlock = function (block) {\n if (block instanceof ParagraphWidget) {\n this.getParagraphFormatInParagraph(block);\n }\n else {\n this.getParagraphFormatInTable(block);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getParagraphFormatInTable = function (tableAdv) {\n for (var i = 0; i < tableAdv.childWidgets.length; i++) {\n var tableRow = tableAdv.childWidgets[i];\n for (var j = 0; j < tableRow.childWidgets.length; j++) {\n this.getParagraphFormatInCell(tableRow.childWidgets[j]);\n }\n }\n };\n /**\n * @private\n */\n Selection.prototype.getParagraphFormatInParagraph = function (paragraph) {\n this.paragraphFormat.combineFormat(paragraph.paragraphFormat);\n };\n /**\n * Get paragraph format in cell\n * @private\n */\n Selection.prototype.getParagraphFormatInternalInCell = function (cellAdv, start, end) {\n if (end.paragraph.isInsideTable) {\n var containerCell = this.getContainerCellOf(cellAdv, end.paragraph.associatedCell);\n if (containerCell.ownerTable.contains(end.paragraph.associatedCell)) {\n var startCell = this.getSelectedCell(cellAdv, containerCell);\n var endCell = this.getSelectedCell(end.paragraph.associatedCell, containerCell);\n if (this.containsCell(containerCell, end.paragraph.associatedCell)) {\n //Selection end is in container cell.\n if (this.isCellSelected(containerCell, start, end)) {\n this.getParagraphFormatInCell(containerCell);\n }\n else {\n if (startCell === containerCell) {\n this.getParagraphFormatInternalInParagraph(start.paragraph, start, end);\n }\n else {\n this.getParagraphFormatInRow(startCell.ownerRow, start, end);\n }\n }\n }\n else {\n //Format other selected cells in current table.\n this.getParaFormatForCell(containerCell.ownerTable, containerCell, endCell);\n }\n }\n else {\n this.getParagraphFormatInRow(containerCell.ownerRow, start, end);\n }\n }\n else {\n var cell = this.getContainerCell(cellAdv);\n this.getParagraphFormatInRow(cell.ownerRow, start, end);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getParaFormatForCell = function (table, startCell, endCell) {\n var startCellIn = this.getCellLeft(startCell.ownerRow, startCell);\n var endCellIn = startCellIn + startCell.cellFormat.cellWidth;\n var endCellLeft = this.getCellLeft(endCell.ownerRow, endCell);\n var endCellRight = endCellLeft + endCell.cellFormat.cellWidth;\n if (startCellIn > endCellLeft) {\n startCellIn = endCellLeft;\n }\n if (endCellIn < endCellRight) {\n endCellIn = endCellRight;\n }\n if (startCellIn > this.upDownSelectionLength) {\n startCellIn = this.upDownSelectionLength;\n }\n if (startCellIn < this.upDownSelectionLength) {\n startCellIn = this.upDownSelectionLength;\n }\n var count = table.childWidgets.indexOf(endCell.ownerRow);\n for (var i = table.childWidgets.indexOf(startCell.ownerRow); i <= count; i++) {\n var tableRow = table.childWidgets[i];\n for (var j = 0; j < tableRow.childWidgets.length; j++) {\n var cell = tableRow.childWidgets[j];\n var left = this.getCellLeft(tableRow, cell);\n if (HelperMethods.round(startCellIn, 2) <= HelperMethods.round(left, 2)\n && HelperMethods.round(left, 2) < HelperMethods.round(endCellIn, 2)) {\n this.getParagraphFormatInCell(cell);\n }\n }\n }\n };\n /**\n * Get paragraph format ins row\n * @private\n */\n Selection.prototype.getParagraphFormatInRow = function (tableRow, start, end) {\n for (var i = tableRow.rowIndex; i < tableRow.ownerTable.childWidgets.length; i++) {\n var row = tableRow.ownerTable.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n this.getParagraphFormatInCell(row.childWidgets[j]);\n }\n if (end.paragraph.isInsideTable && this.containsRow(row, end.paragraph.associatedCell)) {\n return;\n }\n }\n var block = this.getNextRenderedBlock(tableRow.ownerTable);\n //Goto the next block.\n this.getParagraphFormatInternalInBlock(block, start, end);\n };\n // paragraph format retrieval implementation ends\n // Character format retrieval implementation starts.\n /**\n * Retrieve Selection character format\n * @private\n */\n Selection.prototype.retrieveCharacterFormat = function (start, end) {\n this.characterFormat.copyFormat(start.paragraph.characterFormat);\n if (start.paragraph === end.paragraph && start.currentWidget.isLastLine()\n && start.offset === this.getLineLength(start.currentWidget) && start.offset + 1 === end.offset) {\n return;\n }\n var para = start.paragraph;\n if (start.offset === this.getParagraphLength(para) && !this.isEmpty) {\n para = this.getNextParagraphBlock(para);\n }\n while (!isNullOrUndefined(para) && para !== end.paragraph && para.isEmpty()) {\n para = this.getNextParagraphBlock(para);\n }\n var offset = para === start.paragraph ? start.offset : 0;\n var indexInInline = 0;\n if (!isNullOrUndefined(para) && !para.isEmpty()) {\n var position = new TextPosition(this.owner);\n var elemInfo = start.currentWidget.getInline(offset, indexInInline);\n var physicalLocation = this.getPhysicalPositionInternal(start.currentWidget, offset, true);\n position.setPositionForSelection(start.currentWidget, elemInfo.element, elemInfo.index, physicalLocation);\n this.getCharacterFormatForSelection(para, this, position, end);\n }\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getCharacterFormatForSelection = function (paragraph, selection, startPosition, endPosition) {\n //Selection start in cell.\n if (startPosition.paragraph instanceof ParagraphWidget && startPosition.paragraph.isInsideTable\n && (!endPosition.paragraph.isInsideTable\n || startPosition.paragraph.associatedCell !== endPosition.paragraph.associatedCell\n || this.isCellSelected(startPosition.paragraph.associatedCell, startPosition, endPosition))) {\n this.getCharacterFormatInTableCell(startPosition.paragraph.associatedCell, selection, startPosition, endPosition);\n }\n else {\n this.getCharacterFormat(paragraph, startPosition, endPosition);\n }\n };\n /**\n * Get Character format\n * @private\n */\n //Format Retrieval\n Selection.prototype.getCharacterFormatForTableRow = function (tableRowAdv, start, end) {\n for (var i = tableRowAdv.rowIndex; i < tableRowAdv.ownerTable.childWidgets.length; i++) {\n var tableRow = tableRowAdv.ownerTable.childWidgets[i];\n for (var j = 0; j < tableRow.childWidgets.length; j++) {\n this.getCharacterFormatForSelectionCell(tableRow.childWidgets[j], start, end);\n }\n if (end.paragraph.isInsideTable && this.containsRow(tableRow, end.paragraph.associatedCell)) {\n return;\n }\n }\n var block = this.getNextRenderedBlock(tableRowAdv.ownerTable);\n // //Goto the next block.\n this.getCharacterFormatForBlock(block, start, end);\n };\n /**\n * Get Character format in table\n * @private\n */\n Selection.prototype.getCharacterFormatInTableCell = function (tableCell, selection, start, end) {\n if (end.paragraph.isInsideTable) {\n var containerCell = this.getContainerCellOf(tableCell, end.paragraph.associatedCell);\n if (containerCell.ownerTable.contains(end.paragraph.associatedCell)) {\n var startCell = this.getSelectedCell(tableCell, containerCell);\n var endCell = this.getSelectedCell(end.paragraph.associatedCell, containerCell);\n if (this.containsCell(containerCell, end.paragraph.associatedCell)) {\n //Selection end is in container cell.\n if (this.isCellSelected(containerCell, start, end)) {\n this.getCharacterFormatForSelectionCell(containerCell, start, end);\n }\n else {\n if (startCell === containerCell) {\n this.getCharacterFormat(start.paragraph, start, end);\n }\n else {\n this.getCharacterFormatForTableRow(startCell.ownerRow, start, end);\n }\n }\n }\n else {\n //Format other selected cells in current table.\n this.getCharacterFormatInternalInTable(containerCell.ownerTable, containerCell, endCell, start, end);\n }\n }\n else {\n this.getCharacterFormatForTableRow(containerCell.ownerRow, start, end);\n }\n }\n else {\n var cell = this.getContainerCell(tableCell);\n this.getCharacterFormatForTableRow(cell.ownerRow, start, end);\n }\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Selection.prototype.getCharacterFormatInternalInTable = function (table, startCell, endCell, startPosition, endPosition) {\n var startIn = this.getCellLeft(startCell.ownerRow, startCell);\n var endIn = startIn + startCell.cellFormat.cellWidth;\n var endCellLeft = this.getCellLeft(endCell.ownerRow, endCell);\n var endCellRight = endCellLeft + endCell.cellFormat.cellWidth;\n if (startIn > endCellLeft) {\n startIn = endCellLeft;\n }\n if (endIn < endCellRight) {\n endIn = endCellRight;\n }\n if (startIn > this.upDownSelectionLength) {\n startIn = this.upDownSelectionLength;\n }\n if (endIn < this.upDownSelectionLength) {\n endIn = this.upDownSelectionLength;\n }\n var count = table.childWidgets.indexOf(endCell.ownerRow);\n for (var i = table.childWidgets.indexOf(startCell.ownerRow); i <= count; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n var left = this.getCellLeft(row, cell);\n if (HelperMethods.round(startIn, 2) <= HelperMethods.round(left, 2) &&\n HelperMethods.round(left, 2) < HelperMethods.round(endIn, 2)) {\n this.getCharacterFormatForSelectionCell(cell, startPosition, endPosition);\n }\n }\n }\n };\n /**\n * Get character format with in selection\n * @private\n */\n Selection.prototype.getCharacterFormat = function (paragraph, start, end) {\n if (paragraph !== start.paragraph && paragraph !== end.paragraph) {\n this.getCharacterFormatInternal(paragraph, this);\n return;\n }\n if (end.paragraph === paragraph && start.paragraph !== paragraph && end.offset === 0) {\n return;\n }\n var startOffset = 0;\n var length = this.getParagraphLength(paragraph);\n if (paragraph === start.paragraph) {\n startOffset = start.offset;\n //Sets selection character format. \n var isUpdated = this.setCharacterFormat(paragraph, start, end, length);\n if (isUpdated) {\n return;\n }\n }\n var startLineWidget = paragraph.childWidgets.indexOf(start.currentWidget) !== -1 ?\n paragraph.childWidgets.indexOf(start.currentWidget) : 0;\n var endLineWidget = paragraph.childWidgets.indexOf(end.currentWidget) !== -1 ?\n paragraph.childWidgets.indexOf(end.currentWidget) : paragraph.childWidgets.length - 1;\n var endOffset = end.offset;\n if (paragraph !== end.paragraph) {\n endOffset = length;\n }\n var isFieldStartSelected = false;\n for (var i = startLineWidget; i <= endLineWidget; i++) {\n var lineWidget = paragraph.childWidgets[i];\n if (i !== startLineWidget) {\n startOffset = this.getStartLineOffset(lineWidget);\n }\n if (lineWidget === end.currentWidget) {\n endOffset = end.offset;\n }\n else {\n endOffset = this.getLineLength(lineWidget);\n }\n var count = 0;\n for (var j = 0; j < lineWidget.children.length; j++) {\n var inline = lineWidget.children[j];\n if (startOffset >= count + inline.length) {\n count += inline.length;\n continue;\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 0\n && HelperMethods.isLinkedFieldCharacter(inline)) {\n var nextInline = isNullOrUndefined(inline.fieldSeparator) ?\n inline.fieldEnd : inline.fieldSeparator;\n do {\n count += inline.length;\n inline = inline.nextNode;\n i++;\n } while (!isNullOrUndefined(inline) && inline !== nextInline);\n isFieldStartSelected = true;\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 1\n && HelperMethods.isLinkedFieldCharacter(inline) && isFieldStartSelected) {\n var fieldInline = inline.fieldBegin;\n do {\n this.characterFormat.combineFormat(fieldInline.characterFormat);\n fieldInline = fieldInline.nextNode;\n } while (!(fieldInline instanceof FieldElementBox));\n }\n if (inline instanceof TextElementBox) {\n this.characterFormat.combineFormat(inline.characterFormat);\n }\n if (isNullOrUndefined(inline) || endOffset <= count + inline.length) {\n break;\n }\n count += inline.length;\n }\n }\n if (end.paragraph === paragraph) {\n return;\n }\n var block = this.getNextRenderedBlock(paragraph);\n if (!isNullOrUndefined(block)) {\n this.getCharacterFormatForBlock(block, start, end);\n }\n };\n Selection.prototype.setCharacterFormat = function (para, startPos, endPos, length) {\n var index = 0;\n var startOffset = startPos.offset;\n var inlineAndIndex = startPos.currentWidget.getInline(startOffset, index);\n index = inlineAndIndex.index;\n var inline = inlineAndIndex.element;\n if (isNullOrUndefined(inline)) {\n var currentLineIndex = startPos.paragraph.childWidgets.indexOf(startPos.currentWidget);\n if (startPos.currentWidget.previousLine) {\n inline = startPos.currentWidget.previousLine.children[startPos.currentWidget.previousLine.children.length - 1];\n this.characterFormat.copyFormat(inline.characterFormat);\n return true;\n }\n }\n if (startOffset < length) {\n if (this.isEmpty) {\n if (inline instanceof TextElementBox || (inline instanceof FieldElementBox\n && (inline.fieldType === 0 || inline.fieldType === 1))) {\n var previousNode = this.getPreviousTextElement(inline);\n if (startOffset === 0 && previousNode) {\n inline = previousNode;\n }\n this.characterFormat.copyFormat(inline.characterFormat);\n }\n else {\n if (!isNullOrUndefined(this.getPreviousTextElement(inline))) {\n this.characterFormat.copyFormat(this.getPreviousTextElement(inline).characterFormat);\n }\n else if (!isNullOrUndefined(this.getNextTextElement(inline))) {\n this.characterFormat.copyFormat(this.getNextTextElement(inline).characterFormat);\n }\n else {\n this.characterFormat.copyFormat(para.characterFormat);\n }\n }\n return true;\n }\n else {\n if (index === inline.length && !isNullOrUndefined(inline.nextNode)) {\n this.characterFormat.copyFormat(this.getNextValidCharacterFormat(inline));\n }\n else if (inline instanceof TextElementBox) {\n this.characterFormat.copyFormat(inline.characterFormat);\n }\n else if (inline instanceof FieldElementBox) {\n this.characterFormat.copyFormat(this.getNextValidCharacterFormatOfField(inline));\n }\n }\n }\n else {\n if (length === endPos.offset) {\n if (inline instanceof TextElementBox || inline instanceof FieldElementBox) {\n this.characterFormat.copyFormat(inline.characterFormat);\n }\n else if (!isNullOrUndefined(inline)) {\n inline = this.getPreviousTextElement(inline);\n if (!isNullOrUndefined(inline)) {\n this.characterFormat.copyFormat(inline.characterFormat);\n }\n }\n else {\n this.characterFormat.copyFormat(para.characterFormat);\n }\n return true;\n }\n }\n return false;\n };\n /**\n * @private\n */\n Selection.prototype.getCharacterFormatForBlock = function (block, start, end) {\n if (block instanceof ParagraphWidget) {\n this.getCharacterFormat(block, start, end);\n }\n else {\n this.getCharacterFormatInTable(block, start, end);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getCharacterFormatInTable = function (table, start, end) {\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n this.getCharacterFormatForSelectionCell(row.childWidgets[j], start, end);\n }\n if (end.paragraph.isInsideTable && this.containsRow(row, end.paragraph.associatedCell)) {\n return;\n }\n }\n var blockAdv = this.getNextRenderedBlock(table);\n // //Goto the next block.\n this.getCharacterFormatForBlock(blockAdv, start, end);\n };\n /**\n * Get character format in selection\n * @private\n */\n Selection.prototype.getCharacterFormatForSelectionCell = function (cell, start, end) {\n for (var i = 0; i < cell.childWidgets.length; i++) {\n this.getCharacterFormatForBlock(cell.childWidgets[i], start, end);\n }\n };\n /**\n * @private\n */\n Selection.prototype.getCharacterFormatInternal = function (paragraph, selection) {\n for (var i = 0; i < paragraph.childWidgets.length; i++) {\n var linewidget = paragraph.childWidgets[i];\n for (var j = 0; j < linewidget.children.length; j++) {\n var element = linewidget.children[j];\n if (!(element instanceof ImageElementBox || element instanceof FieldElementBox)) {\n selection.characterFormat.combineFormat(element.characterFormat);\n }\n }\n }\n };\n /**\n * Get next valid character format from inline\n * @private\n */\n Selection.prototype.getNextValidCharacterFormat = function (inline) {\n var startInline = this.getNextTextElement(inline);\n if (isNullOrUndefined(startInline)) {\n return inline.characterFormat;\n }\n var fieldBegin = undefined;\n if (startInline instanceof FieldElementBox) {\n if (fieldBegin.fieldType === 0) {\n fieldBegin = startInline;\n }\n }\n if (isNullOrUndefined(fieldBegin)) {\n return startInline.characterFormat;\n }\n else {\n return this.getNextValidCharacterFormatOfField(fieldBegin);\n }\n };\n /**\n * Get next valid paragraph format from field\n * @private\n */\n Selection.prototype.getNextValidCharacterFormatOfField = function (fieldBegin) {\n var startInline = fieldBegin;\n if (HelperMethods.isLinkedFieldCharacter(fieldBegin)) {\n if (isNullOrUndefined(fieldBegin.fieldSeparator)) {\n startInline = fieldBegin.fieldEnd;\n }\n else {\n startInline = fieldBegin.fieldSeparator;\n }\n }\n var nextValidInline = undefined;\n if (!isNullOrUndefined(startInline.nextNode)) {\n //Check the next node is a valid and returns inline.\n nextValidInline = this.getNextValidElement(startInline.nextNode);\n }\n //If field separator/end exists at end of paragraph, then move to next paragraph.\n if (isNullOrUndefined(nextValidInline)) {\n return startInline.characterFormat;\n }\n return nextValidInline.characterFormat;\n };\n /**\n * Return true if cursor point with in selection range\n * @private\n */\n Selection.prototype.checkCursorIsInSelection = function (widget, point) {\n if (isNullOrUndefined(this.start) || this.isEmpty || isNullOrUndefined(widget)) {\n return false;\n }\n var isSelected = false;\n do {\n if (this.selectedWidgets.containsKey(widget)) {\n var top_4 = void 0;\n var left = void 0;\n if (widget instanceof LineWidget) {\n top_4 = this.owner.selection.getTop(widget);\n left = this.owner.selection.getLeft(widget);\n }\n else {\n top_4 = widget.y;\n left = widget.x;\n }\n var widgetInfo = this.selectedWidgets.get(widget);\n isSelected = widgetInfo.left <= point.x && top_4 <= point.y &&\n top_4 + widget.height >= point.y && widgetInfo.left + widgetInfo.width >= point.x;\n }\n widget = (widget instanceof LineWidget) ? widget.paragraph : widget.containerWidget;\n } while (!isNullOrUndefined(widget) && !isSelected);\n return isSelected;\n };\n /**\n * Copy paragraph for to selection paragraph format\n * @private\n */\n Selection.prototype.copySelectionParagraphFormat = function () {\n var format = new WParagraphFormat();\n this.paragraphFormat.copyToFormat(format);\n return format;\n };\n /**\n * Get hyperlink display text\n * @private\n */\n // tslint:disable-next-line\n Selection.prototype.getHyperlinkDisplayText = function (paragraph, fieldSeparator, fieldEnd, isNestedField, format) {\n var para = paragraph;\n if (para !== fieldEnd.line.paragraph) {\n isNestedField = true;\n return { displayText: '<>', 'isNestedField': isNestedField, 'format': format };\n }\n var displayText = '';\n var lineIndex = para.childWidgets.indexOf(fieldSeparator.line);\n var index = para.childWidgets[lineIndex].children.indexOf(fieldSeparator);\n for (var j = lineIndex; j < para.childWidgets.length; j++) {\n var lineWidget = para.childWidgets[j];\n if (j !== lineIndex) {\n index = -1;\n }\n for (var i = index + 1; i < lineWidget.children.length; i++) {\n var inline = lineWidget.children[i];\n if (inline === fieldEnd) {\n return { 'displayText': displayText, 'isNestedField': isNestedField, 'format': format };\n }\n if (inline instanceof TextElementBox) {\n displayText += inline.text;\n format = inline.characterFormat;\n }\n else if (inline instanceof FieldElementBox) {\n if (inline instanceof FieldElementBox && inline.fieldType === 0\n && !isNullOrUndefined(inline.fieldEnd)) {\n if (isNullOrUndefined(inline.fieldSeparator)) {\n index = lineWidget.children.indexOf(inline.fieldEnd);\n }\n else {\n index = lineWidget.children.indexOf(inline.fieldSeparator);\n }\n }\n }\n else {\n isNestedField = true;\n return { 'displayText': '<>', 'isNestedField': isNestedField, 'format': format };\n }\n }\n }\n return { 'displayText': displayText, 'isNestedField': isNestedField, 'format': format };\n };\n /**\n * Navigates hyperlink on mouse Event.\n * @private\n */\n Selection.prototype.navigateHyperLinkOnEvent = function (cursorPoint, isTouchInput) {\n var _this = this;\n var widget = this.viewer.getLineWidget(cursorPoint);\n if (!isNullOrUndefined(widget)) {\n var hyperLinkField = this.getHyperLinkFieldInCurrentSelection(widget, cursorPoint);\n //Invokes Hyperlink navigation events.\n if (!isNullOrUndefined(hyperLinkField)) {\n this.viewer.updateTextPositionForSelection(cursorPoint, 1);\n this.fireRequestNavigate(hyperLinkField);\n setTimeout(function () {\n if (_this.viewer) {\n _this.viewer.isTouchInput = isTouchInput;\n _this.viewer.updateFocus();\n _this.viewer.isTouchInput = false;\n }\n });\n }\n }\n };\n /**\n * @private\n */\n Selection.prototype.getLinkText = function (fieldBegin) {\n var hyperlink = new Hyperlink(fieldBegin, this);\n var link = hyperlink.navigationLink;\n if (hyperlink.localReference.length > 0) {\n if (hyperlink.localReference[0] === '_' && (isNullOrUndefined(link) || link.length === 0)) {\n link = 'Current Document';\n }\n else {\n link += '#' + hyperlink.localReference;\n }\n }\n hyperlink.destroy();\n return link;\n };\n /**\n * Set Hyperlink content to tool tip element\n * @private\n */\n Selection.prototype.setHyperlinkContentToToolTip = function (fieldBegin, widget, xPos) {\n if (fieldBegin) {\n if (this.owner.contextMenuModule &&\n this.owner.contextMenuModule.contextMenuInstance.element.style.display === 'block') {\n return;\n }\n if (!this.toolTipElement) {\n this.toolTipElement = createElement('div', { className: 'e-de-tooltip' });\n this.viewer.viewerContainer.appendChild(this.toolTipElement);\n }\n this.toolTipElement.style.display = 'block';\n var l10n = new L10n('documenteditor', this.owner.defaultLocale);\n l10n.setLocale(this.owner.locale);\n var toolTipText = l10n.getConstant('Click to follow link');\n if (this.owner.useCtrlClickToFollowHyperlink) {\n toolTipText = 'Ctrl+' + toolTipText;\n }\n var linkText = this.getLinkText(fieldBegin);\n this.toolTipElement.innerHTML = linkText + '' + toolTipText + ' ';\n var widgetTop = this.getTop(widget) * this.viewer.zoomFactor;\n var page = this.getPage(widget.paragraph);\n var containerWidth = this.viewer.viewerContainer.getBoundingClientRect().width + this.viewer.viewerContainer.scrollLeft;\n var left = page.boundingRectangle.x + xPos * this.viewer.zoomFactor;\n if ((left + this.toolTipElement.clientWidth + 10) > containerWidth) {\n left = left - ((this.toolTipElement.clientWidth - (containerWidth - left)) + 15);\n }\n var top_5 = this.getPageTop(page) + (widgetTop - this.toolTipElement.offsetHeight);\n top_5 = top_5 > this.viewer.viewerContainer.scrollTop ? top_5 : top_5 + widget.height + this.toolTipElement.offsetHeight;\n this.showToolTip(left, top_5);\n if (!isNullOrUndefined(this.toolTipField) && fieldBegin !== this.toolTipField) {\n this.toolTipObject.position = { X: left, Y: top_5 };\n }\n this.toolTipObject.show();\n this.toolTipField = fieldBegin;\n }\n else {\n this.hideToolTip();\n }\n };\n /**\n * Show hyperlink tooltip\n * @private\n */\n Selection.prototype.showToolTip = function (x, y) {\n if (!this.toolTipObject) {\n this.toolTipObject = new Popup(this.toolTipElement, {\n height: 'auto',\n width: 'auto',\n relateTo: this.viewer.viewerContainer.parentElement,\n position: { X: x, Y: y }\n });\n }\n };\n /**\n * Hide tooltip object\n * @private\n */\n Selection.prototype.hideToolTip = function () {\n this.toolTipField = undefined;\n if (this.toolTipObject) {\n this.toolTipObject.hide();\n this.toolTipObject.destroy();\n this.toolTipObject = undefined;\n this.toolTipElement.style.display = 'none';\n }\n };\n /**\n * Return hyperlink field\n * @private\n */\n Selection.prototype.getHyperLinkFieldInCurrentSelection = function (widget, cursorPosition) {\n var inline = undefined;\n var top = this.getTop(widget);\n var lineStartLeft = this.getLineStartLeft(widget);\n if (cursorPosition.y < top || cursorPosition.y > top + widget.height\n || cursorPosition.x < lineStartLeft || cursorPosition.x > lineStartLeft + widget.paragraph.width) {\n return undefined;\n }\n var left = widget.paragraph.x;\n var elementValues = this.getFirstElement(widget, left);\n left = elementValues.left;\n var element = elementValues.element;\n if (isNullOrUndefined(element)) {\n var width = this.viewer.textHelper.getParagraphMarkWidth(widget.paragraph.characterFormat);\n if (cursorPosition.x <= lineStartLeft + width || cursorPosition.x >= lineStartLeft + width) {\n //Check if paragraph is within a field result.\n var checkedFields = [];\n var field = this.getHyperLinkFields(widget.paragraph, checkedFields);\n checkedFields = [];\n checkedFields = undefined;\n return field;\n }\n }\n else {\n if (cursorPosition.x > left + element.margin.left) {\n for (var i = widget.children.indexOf(element); i < widget.children.length; i++) {\n element = widget.children[i];\n if (cursorPosition.x < left + element.margin.left + element.width || i === widget.children.length - 1) {\n break;\n }\n left += element.margin.left + element.width;\n }\n }\n inline = element;\n var width = element.margin.left + element.width;\n if (isNullOrUndefined(inline.nextNode)) {\n //Include width of Paragraph mark.\n width += this.viewer.textHelper.getParagraphMarkWidth(inline.line.paragraph.characterFormat);\n }\n if (cursorPosition.x <= left + width) {\n //Check if inline is within a field result.\n var checkedFields = [];\n var field = this.getHyperLinkFieldInternal(inline.line.paragraph, inline, checkedFields);\n checkedFields = [];\n checkedFields = undefined;\n return field;\n }\n }\n return undefined;\n };\n /**\n * Return field if paragraph contain hyperlink field\n * @private\n */\n Selection.prototype.getHyperlinkField = function () {\n if (isNullOrUndefined(this.end)) {\n return undefined;\n }\n var index = 0;\n var currentInline = this.end.currentWidget.getInline(this.end.offset, index);\n index = currentInline.index;\n var inline = currentInline.element;\n var checkedFields = [];\n var field = undefined;\n if (isNullOrUndefined(inline)) {\n field = this.getHyperLinkFields(this.end.paragraph, checkedFields);\n }\n else {\n var paragraph = inline.line.paragraph;\n field = this.getHyperLinkFieldInternal(paragraph, inline, checkedFields);\n }\n checkedFields = [];\n return field;\n };\n /**\n * @private\n */\n Selection.prototype.getHyperLinkFields = function (paragraph, checkedFields) {\n for (var i = 0; i < this.viewer.fields.length; i++) {\n if (checkedFields.indexOf(this.viewer.fields[i]) !== -1 || isNullOrUndefined(this.viewer.fields[i].fieldSeparator)) {\n continue;\n }\n else {\n checkedFields.push(this.viewer.fields[i]);\n }\n var field = this.getFieldCode(this.viewer.fields[i]);\n field = field.trim().toLowerCase();\n if (field.match('hyperlink ') && this.paragraphIsInFieldResult(this.viewer.fields[i], paragraph)) {\n return this.viewer.fields[i];\n }\n }\n // if (paragraph.containerWidget instanceof BodyWidget && !(paragraph instanceof WHeaderFooter)) {\n // return this.getHyperLinkFields((paragraph.con as WCompositeNode), checkedFields);\n // }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.getHyperLinkFieldInternal = function (paragraph, inline, fields) {\n for (var i = 0; i < this.viewer.fields.length; i++) {\n if (fields.indexOf(this.viewer.fields[i]) !== -1 || isNullOrUndefined(this.viewer.fields[i].fieldSeparator)) {\n continue;\n }\n else {\n fields.push(this.viewer.fields[i]);\n }\n var fieldCode = this.getFieldCode(this.viewer.fields[i]);\n fieldCode = fieldCode.trim().toLowerCase();\n if (fieldCode.match('hyperlink ') && (this.inlineIsInFieldResult(this.viewer.fields[i], inline) || this.isImageField())) {\n return this.viewer.fields[i];\n }\n }\n if (paragraph.containerWidget instanceof BodyWidget && !(paragraph instanceof HeaderFooterWidget)) {\n return this.getHyperLinkFieldInternal(paragraph.containerWidget, inline, fields);\n }\n return undefined;\n };\n /**\n * @private\n */\n Selection.prototype.getBlock = function (currentIndex) {\n if (currentIndex === '' || isNullOrUndefined(currentIndex)) {\n return undefined;\n }\n var index = { index: currentIndex };\n var page = this.start.getPage(index);\n var bodyIndex = index.index.indexOf(';');\n var value = index.index.substring(0, bodyIndex);\n index.index = index.index.substring(bodyIndex).replace(';', '');\n var bodyWidget = page.bodyWidgets[parseInt(value, 10)];\n return this.getBlockInternal(bodyWidget, index.index);\n };\n /**\n * Return Block relative to position\n * @private\n */\n Selection.prototype.getBlockInternal = function (widget, position) {\n if (position === '' || isNullOrUndefined(position)) {\n return undefined;\n }\n var index = position.indexOf(';');\n var value = position.substring(0, index);\n position = position.substring(index).replace(';', '');\n var node = widget;\n // if (node instanceof Widget && value === 'HF') {\n // //Gets the block in Header footers.\n // let blockObj: BlockInfo = this.getBlock((node as WSection).headersFooters, position);\n // tslint:disable-next-line:max-line-length\n // return { 'node': (!isNullOrUndefined(blockObj)) ? blockObj.node : undefined, 'position': (!isNullOrUndefined(blockObj)) ? blockObj.position : undefined };\n // }\n index = parseInt(value, 10);\n if (index >= 0 && index < widget.childWidgets.length) {\n var child = widget.childWidgets[(index)];\n if (position.indexOf(';') >= 0) {\n if (child instanceof ParagraphWidget) {\n if (position.indexOf(';') >= 0) {\n position = '0';\n }\n return child;\n }\n if (child instanceof BlockWidget) {\n var blockObj = this.getBlockInternal(child, position);\n return blockObj;\n }\n }\n else {\n return child;\n }\n }\n else {\n return node;\n }\n return node;\n };\n /**\n * Return true if inline is in field result\n * @private\n */\n Selection.prototype.inlineIsInFieldResult = function (fieldBegin, inline) {\n if (!isNullOrUndefined(fieldBegin.fieldEnd) && !isNullOrUndefined(fieldBegin.fieldSeparator)) {\n if (this.isExistBeforeInline(fieldBegin.fieldSeparator, inline)) {\n return this.isExistAfterInline(fieldBegin.fieldEnd, inline);\n }\n }\n return false;\n };\n /**\n * Retrieve true if paragraph is in field result\n * @private\n */\n Selection.prototype.paragraphIsInFieldResult = function (fieldBegin, paragraph) {\n if (!isNullOrUndefined(fieldBegin.fieldEnd) && !isNullOrUndefined(fieldBegin.fieldSeparator)) {\n var fieldParagraph = fieldBegin.fieldSeparator.line.paragraph;\n if (fieldBegin.fieldSeparator.line.paragraph === paragraph\n || this.isExistBefore(fieldParagraph, paragraph)) {\n var currentParagraph = fieldBegin.fieldEnd.line.paragraph;\n return (currentParagraph !== paragraph && this.isExistAfter(fieldParagraph, paragraph));\n }\n }\n return false;\n };\n /**\n * Return true if image is In field\n * @private\n */\n Selection.prototype.isImageField = function () {\n if (this.start.paragraph.isEmpty() || this.end.paragraph.isEmpty()) {\n return false;\n }\n var startPosition = this.start;\n var endPosition = this.end;\n if (!this.isForward) {\n startPosition = this.end;\n endPosition = this.start;\n }\n var indexInInline = 0;\n var inlineInfo = startPosition.paragraph.getInline(startPosition.offset, indexInInline);\n var inline = inlineInfo.element;\n indexInInline = inlineInfo.index;\n if (indexInInline === inline.length) {\n inline = this.getNextRenderedElementBox(inline, indexInInline);\n }\n inlineInfo = endPosition.paragraph.getInline(endPosition.offset, indexInInline);\n var endInline = inlineInfo.element;\n indexInInline = inlineInfo.index;\n if (inline instanceof FieldElementBox && inline.fieldType === 0\n && endInline instanceof FieldElementBox && endInline.fieldType === 1 && inline.fieldSeparator) {\n var fieldValue = inline.fieldSeparator.nextNode;\n if (fieldValue instanceof ImageElementBox && fieldValue.nextNode === endInline) {\n return true;\n }\n }\n return false;\n };\n /**\n * Select List Text\n * @private\n */\n Selection.prototype.selectListText = function () {\n var lineWidget = this.viewer.selectionLineWidget;\n var endOffset = '0';\n var selectionIndex = lineWidget.getHierarchicalIndex(endOffset);\n var startPosition = this.getTextPosition(selectionIndex);\n var endPosition = this.getTextPosition(selectionIndex);\n this.selectRange(startPosition, endPosition);\n this.highlightListText(this.viewer.selectionLineWidget);\n this.contextTypeInternal = 'List';\n };\n /**\n * Manually select the list text\n * @private\n */\n Selection.prototype.highlightListText = function (linewidget) {\n var width = linewidget.children[0].width;\n var left = this.viewer.getLeftValue(linewidget);\n var top = linewidget.paragraph.y;\n this.createHighlightBorder(linewidget, width, left, top);\n this.viewer.isListTextSelected = true;\n };\n /**\n * @private\n */\n Selection.prototype.updateImageSize = function (imageFormat) {\n this.owner.isShiftingEnabled = true;\n var startPosition = this.start;\n var endPosition = this.end;\n if (!this.isForward) {\n startPosition = this.end;\n endPosition = this.start;\n }\n var inline = null;\n var index = 0;\n var paragraph = startPosition.paragraph;\n if (paragraph === endPosition.paragraph\n && startPosition.offset + 1 === endPosition.offset) {\n var inlineObj = paragraph.getInline(endPosition.offset, index);\n inline = inlineObj.element;\n index = inlineObj.index;\n }\n if (inline instanceof ImageElementBox) {\n var width = inline.width;\n var height = inline.height;\n inline.width = imageFormat.width;\n inline.height = imageFormat.height;\n imageFormat.width = width;\n imageFormat.height = height;\n if (paragraph != null && paragraph.containerWidget != null && this.owner.editorModule) {\n var lineIndex = paragraph.childWidgets.indexOf(inline.line);\n var elementIndex = inline.line.children.indexOf(inline);\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, elementIndex);\n this.highlightSelection(false);\n }\n }\n };\n /**\n * Gets selected table content\n * @private\n */\n Selection.prototype.getSelectedCellsInTable = function (table, startCell, endCell) {\n var startColumnIndex = startCell.columnIndex;\n var endColumnIndex = endCell.columnIndex + endCell.cellFormat.columnSpan - 1;\n var startRowindex = startCell.ownerRow.index;\n var endRowIndex = endCell.ownerRow.index;\n var cells = [];\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row.index >= startRowindex && row.index <= endRowIndex) {\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n if (cell.columnIndex >= startColumnIndex && cell.columnIndex <= endColumnIndex) {\n cells.push(cell);\n }\n }\n }\n if (row.index > endRowIndex) {\n break;\n }\n }\n return cells;\n // return html;\n };\n /**\n * Copies the selected content to clipboard.\n */\n Selection.prototype.copy = function () {\n if (this.isEmpty) {\n return;\n }\n this.copySelectedContent(false);\n };\n /**\n * @private\n */\n Selection.prototype.copySelectedContent = function (isCut) {\n if (isNullOrUndefined(this.owner.sfdtExportModule)) {\n return;\n }\n var startPosition = this.start;\n var endPosition = this.end;\n if (!this.isForward) {\n startPosition = this.end;\n endPosition = this.start;\n }\n /* tslint:disable:no-any */\n // tslint:disable-next-line:max-line-length\n var document = this.owner.sfdtExportModule.write(startPosition.currentWidget, startPosition.offset, endPosition.currentWidget, endPosition.offset, true);\n /* tslint:enable:no-any */\n if (this.owner.editorModule) {\n this.owner.editorModule.copiedData = JSON.stringify(document);\n }\n var html = this.htmlWriter.writeHtml(document);\n this.copyToClipboard(html);\n if (isCut && this.owner.editorModule) {\n this.owner.editorModule.handleCut(this);\n }\n this.viewer.updateFocus();\n };\n /**\n * Copy content to clipboard\n * @private\n */\n Selection.prototype.copyToClipboard = function (htmlContent) {\n window.getSelection().removeAllRanges();\n var div = document.createElement('div');\n div.style.left = '-10000px';\n div.style.top = '-10000px';\n div.innerHTML = htmlContent;\n document.body.appendChild(div);\n var range = document.createRange();\n range.selectNodeContents(div);\n window.getSelection().addRange(range);\n var copySuccess = false;\n try {\n copySuccess = document.execCommand('copy');\n }\n catch (e) {\n // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open.\n }\n finally {\n window.getSelection().removeAllRanges();\n div.parentNode.removeChild(div);\n this.viewer.viewerContainer.focus();\n }\n return copySuccess;\n };\n // Caret implementation starts\n /**\n * Shows caret in current selection position.\n * @private\n */\n Selection.prototype.showCaret = function () {\n // tslint:disable-next-line:max-line-length\n var page = !isNullOrUndefined(this.viewer.currentPage) ? this.viewer.currentPage : this.viewer.currentRenderingPage;\n if (isNullOrUndefined(page) || this.viewer.isRowOrCellResizing || this.owner.enableImageResizerMode && this.owner.imageResizerModule.isImageResizerVisible) {\n return;\n }\n var left = page.boundingRectangle.x;\n var right = page.boundingRectangle.width * this.viewer.zoomFactor + left;\n if (!this.owner.enableImageResizerMode || !this.owner.imageResizerModule.isImageResizerVisible) {\n // tslint:disable-next-line:max-line-length\n if (this.isEmpty && (!this.owner.isReadOnlyMode || this.owner.enableCursorOnReadOnly)) {\n var caretLeft = parseInt(this.caret.style.left.replace('px', ''), 10);\n if (caretLeft < left || caretLeft > right) {\n this.caret.style.display = 'none';\n }\n else {\n this.caret.style.display = 'block';\n }\n }\n else if (this.isImageSelected && !this.owner.enableImageResizerMode) {\n this.caret.style.display = 'block';\n }\n else {\n if (this.caret.style.display === 'block' || isNullOrUndefined(this)) {\n this.caret.style.display = 'none';\n }\n }\n }\n if (!isNullOrUndefined(this) && this.viewer.isTouchInput && !this.owner.isReadOnlyMode) {\n var caretStartLeft = parseInt(this.viewer.touchStart.style.left.replace('px', ''), 10) + 14;\n var caretEndLeft = parseInt(this.viewer.touchEnd.style.left.replace('px', ''), 10) + 14;\n var page_1 = this.getSelectionPage(this.start);\n if (page_1) {\n if (caretEndLeft < left || caretEndLeft > right) {\n this.viewer.touchEnd.style.display = 'none';\n }\n else {\n this.viewer.touchEnd.style.display = 'block';\n }\n if (!this.isEmpty) {\n left = page_1.boundingRectangle.x;\n right = page_1.boundingRectangle.width * this.viewer.zoomFactor + left;\n }\n if (caretStartLeft < left || caretStartLeft > right) {\n this.viewer.touchStart.style.display = 'none';\n }\n else {\n this.viewer.touchStart.style.display = 'block';\n }\n }\n }\n else {\n this.viewer.touchStart.style.display = 'none';\n this.viewer.touchEnd.style.display = 'none';\n }\n };\n /**\n * To set the editable div caret position\n * @private\n */\n Selection.prototype.setEditableDivCaretPosition = function (index) {\n this.viewer.editableDiv.focus();\n var child = this.viewer.editableDiv.childNodes[this.viewer.editableDiv.childNodes.length - 1];\n if (child) {\n var range = document.createRange();\n range.setStart(child, index);\n range.collapse(true);\n window.getSelection().removeAllRanges();\n window.getSelection().addRange(range);\n }\n };\n /**\n * Initializes caret.\n * @private\n */\n Selection.prototype.initCaret = function () {\n this.caret = createElement('div', {\n styles: 'position:absolute',\n className: 'e-de-blink-cursor e-de-cursor-animation'\n });\n this.viewer.viewerContainer.appendChild(this.caret);\n };\n /**\n * Updates caret position.\n * @private\n */\n Selection.prototype.updateCaretPosition = function () {\n var caretPosition = this.end.location;\n var page = this.getSelectionPage(this.end);\n if (page) {\n this.caret.style.left = page.boundingRectangle.x + (Math.round(caretPosition.x) * this.viewer.zoomFactor) + 'px';\n var caretInfo = this.updateCaretSize(this.owner.selection.end);\n var topMargin = caretInfo.topMargin;\n var caretHeight = caretInfo.height;\n var viewer = this.viewer;\n // tslint:disable-next-line:max-line-length\n var pageTop = (page.boundingRectangle.y - viewer.pageGap * (this.viewer.pages.indexOf(page) + 1)) * this.viewer.zoomFactor + viewer.pageGap * (this.viewer.pages.indexOf(page) + 1);\n this.caret.style.top = pageTop + (Math.round(caretPosition.y + topMargin) * this.viewer.zoomFactor) + 'px';\n if (this.owner.selection.characterFormat.baselineAlignment === 'Subscript') {\n this.caret.style.top = parseFloat(this.caret.style.top) + (parseFloat(this.caret.style.height) / 2) + 'px';\n }\n if (this.viewer.isTouchInput || this.viewer.touchStart.style.display !== 'none') {\n // tslint:disable-next-line:max-line-length\n this.viewer.touchStart.style.left = page.boundingRectangle.x + (Math.round(caretPosition.x) * this.viewer.zoomFactor - 14) + 'px';\n this.viewer.touchStart.style.top = pageTop + ((caretPosition.y + caretInfo.height) * this.viewer.zoomFactor) + 'px';\n // tslint:disable-next-line:max-line-length\n this.viewer.touchEnd.style.left = page.boundingRectangle.x + (Math.round(caretPosition.x) * this.viewer.zoomFactor - 14) + 'px';\n this.viewer.touchEnd.style.top = pageTop + ((caretPosition.y + caretInfo.height) * this.viewer.zoomFactor) + 'px';\n }\n }\n };\n /**\n * Gets current selected page\n */\n Selection.prototype.getSelectionPage = function (position) {\n var lineWidget = this.getLineWidgetInternal(position.currentWidget, position.offset, true);\n if (lineWidget) {\n return this.getPage(lineWidget.paragraph);\n }\n return undefined;\n };\n /**\n * Updates caret size.\n * @private\n */\n Selection.prototype.updateCaretSize = function (textPosition, skipUpdate) {\n var topMargin = 0;\n var isItalic = false;\n var caret;\n var index = 0;\n var caretHeight = 0;\n if (this.characterFormat.italic) {\n isItalic = this.characterFormat.italic;\n }\n if (textPosition.paragraph.isEmpty()) {\n var paragraph = textPosition.paragraph;\n var bottomMargin = 0;\n var paragraphInfo = this.getParagraphMarkSize(paragraph, topMargin, bottomMargin);\n topMargin = paragraphInfo.topMargin;\n bottomMargin = paragraphInfo.bottomMargin;\n var height = paragraphInfo.height;\n caretHeight = topMargin < 0 ? topMargin + height : height;\n if (!skipUpdate) {\n this.caret.style.height = caretHeight * this.viewer.zoomFactor + 'px';\n }\n topMargin = 0;\n }\n else {\n var inlineInfo = textPosition.currentWidget.getInline(textPosition.offset, index);\n index = inlineInfo.index;\n var inline = inlineInfo.element;\n if (!isNullOrUndefined(inline)) {\n caret = this.getCaretHeight(inline, index, inline.characterFormat, true, topMargin, isItalic);\n caretHeight = caret.height;\n if (!skipUpdate) {\n this.caret.style.height = caret.height * this.viewer.zoomFactor + 'px';\n }\n }\n }\n if (!skipUpdate) {\n if (isItalic) {\n this.caret.style.transform = 'rotate(13deg)';\n }\n else {\n this.caret.style.transform = '';\n }\n }\n return {\n 'topMargin': topMargin,\n 'height': caretHeight\n };\n };\n /**\n * Updates caret to page.\n * @private\n */\n Selection.prototype.updateCaretToPage = function (startPosition, endPage) {\n if (!isNullOrUndefined(endPage)) {\n this.viewer.selectionEndPage = endPage;\n if (this.owner.selection.isEmpty) {\n this.viewer.selectionStartPage = endPage;\n }\n else {\n // tslint:disable-next-line:max-line-length\n var startLineWidget = this.getLineWidgetParagraph(startPosition.offset, startPosition.paragraph.childWidgets[0]);\n //Gets start page.\n var startPage = this.getPage(startLineWidget.paragraph);\n if (!isNullOrUndefined(startPage)) {\n this.viewer.selectionStartPage = startPage;\n }\n }\n }\n this.checkForCursorVisibility();\n };\n /**\n * Gets caret bottom position.\n * @private\n */\n Selection.prototype.getCaretBottom = function (textPosition, isEmptySelection) {\n var bottom = textPosition.location.y;\n if (textPosition.paragraph.isEmpty()) {\n var paragraph = textPosition.paragraph;\n var topMargin = 0;\n var bottomMargin = 0;\n var sizeInfo = this.getParagraphMarkSize(paragraph, topMargin, bottomMargin);\n topMargin = sizeInfo.topMargin;\n bottomMargin = sizeInfo.bottomMargin;\n bottom += sizeInfo.height;\n bottom += topMargin;\n if (!isEmptySelection) {\n bottom += bottomMargin;\n }\n }\n else {\n var index = 0;\n var inlineInfo = textPosition.paragraph.getInline(textPosition.offset, index);\n var inline = inlineInfo.element;\n index = inlineInfo.index;\n var topMargin = 0;\n var isItalic = false;\n // tslint:disable-next-line:max-line-length\n var caretHeightInfo = this.getCaretHeight(inline, index, inline.characterFormat, false, topMargin, isItalic);\n topMargin = caretHeightInfo.topMargin;\n isItalic = caretHeightInfo.isItalic;\n bottom += caretHeightInfo.height;\n if (isEmptySelection) {\n bottom -= HelperMethods.convertPointToPixel(textPosition.paragraph.paragraphFormat.afterSpacing);\n }\n }\n return bottom;\n };\n /**\n * Checks for cursor visibility.\n * @param isTouch\n * @private\n */\n Selection.prototype.checkForCursorVisibility = function () {\n this.showCaret();\n };\n // caret implementation ends\n /**\n * Keyboard shortcuts\n * @private\n */\n // tslint:disable:max-func-body-length\n Selection.prototype.onKeyDownInternal = function (event, ctrl, shift, alt) {\n var key = event.which || event.keyCode;\n if (ctrl && !shift && !alt) {\n this.viewer.isControlPressed = true;\n switch (key) {\n // case 9:\n // event.preventDefault();\n // if (this.owner.acceptTab) {\n // this.selection.handleTabKey(false, false);\n // }\n // break;\n case 35:\n this.handleControlEndKey();\n break;\n case 36:\n this.handleControlHomeKey();\n break;\n case 37:\n this.handleControlLeftKey();\n break;\n case 38:\n this.handleControlUpKey();\n break;\n case 39:\n this.handleControlRightKey();\n break;\n case 40:\n this.handleControlDownKey();\n break;\n case 65:\n this.owner.selection.selectAll();\n break;\n case 67:\n event.preventDefault();\n this.copy();\n break;\n case 70:\n event.preventDefault();\n if (!isNullOrUndefined(this.owner.optionsPaneModule)) {\n this.owner.optionsPaneModule.showHideOptionsPane(true);\n }\n break;\n }\n }\n else if (shift && !ctrl && !alt) {\n switch (key) {\n case 35:\n this.handleShiftEndKey();\n event.preventDefault();\n break;\n case 36:\n this.handleShiftHomeKey();\n event.preventDefault();\n break;\n case 37:\n this.handleShiftLeftKey();\n event.preventDefault();\n break;\n case 38:\n this.handleShiftUpKey();\n event.preventDefault();\n break;\n case 39:\n this.handleShiftRightKey();\n event.preventDefault();\n break;\n case 40:\n this.handleShiftDownKey();\n event.preventDefault();\n break;\n }\n }\n else if (shift && ctrl && !alt) {\n switch (key) {\n case 35:\n this.handleControlShiftEndKey();\n break;\n case 36:\n this.handleControlShiftHomeKey();\n break;\n case 37:\n this.handleControlShiftLeftKey();\n break;\n case 38:\n this.handleControlShiftUpKey();\n break;\n case 39:\n this.handleControlShiftRightKey();\n break;\n case 40:\n this.handleControlShiftDownKey();\n break;\n }\n }\n else {\n switch (key) {\n // case 9:\n // event.preventDefault();\n // if (this.owner.acceptTab) {\n // this.handleTabKey(true, false);\n // }\n // break; \n case 33:\n event.preventDefault();\n this.viewer.viewerContainer.scrollTop -= this.viewer.visibleBounds.height;\n break;\n case 34:\n event.preventDefault();\n this.viewer.viewerContainer.scrollTop += this.viewer.visibleBounds.height;\n break;\n case 35:\n this.handleEndKey();\n event.preventDefault();\n break;\n case 36:\n this.handleHomeKey();\n event.preventDefault();\n break;\n case 37:\n this.handleLeftKey();\n event.preventDefault();\n break;\n case 38:\n this.handleUpKey();\n event.preventDefault();\n break;\n case 39:\n this.handleRightKey();\n event.preventDefault();\n break;\n case 40:\n this.handleDownKey();\n event.preventDefault();\n break;\n }\n }\n if (!this.owner.isReadOnlyMode) {\n this.owner.editorModule.onKeyDownInternal(event, ctrl, shift, alt);\n }\n if (this.owner.searchModule) {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(this.owner.searchModule.searchHighlighters) && this.owner.searchModule.searchHighlighters.length > 0) {\n this.owner.searchModule.searchResults.clear();\n }\n }\n if (event.keyCode === 27 || event.which === 27) {\n if (!isNullOrUndefined(this.owner.optionsPaneModule)) {\n this.owner.optionsPaneModule.showHideOptionsPane(false);\n }\n if (this.owner.enableHeaderAndFooter) {\n this.disableHeaderFooter();\n }\n }\n };\n //#region Enable or disable Header Footer\n /**\n * @private\n */\n Selection.prototype.checkAndEnableHeaderFooter = function (point, pagePoint) {\n var page = this.viewer.currentPage;\n if (this.isCursorInsidePageRect(point, page)) {\n if (this.isCursorInHeaderRegion(point, page)) {\n if (this.owner.enableHeaderAndFooter) {\n return false;\n }\n return this.enableHeadersFootersRegion(page.headerWidget);\n }\n if (this.isCursorInFooterRegion(point, page)) {\n if (this.owner.enableHeaderAndFooter) {\n return false;\n }\n return this.enableHeadersFootersRegion(page.footerWidget);\n }\n }\n if (this.owner.enableHeaderAndFooter) {\n this.owner.enableHeaderAndFooter = false;\n this.viewer.updateTextPositionForSelection(pagePoint, 1);\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n Selection.prototype.isCursorInsidePageRect = function (point, page) {\n if ((this.viewer.containerLeft + point.x) >= page.boundingRectangle.x &&\n (this.viewer.containerLeft + point.x) <= (page.boundingRectangle.x + (page.boundingRectangle.width * this.viewer.zoomFactor))) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n Selection.prototype.isCursorInHeaderRegion = function (point, page) {\n var pageTop = this.getPageTop(page);\n var headerHeight = 0;\n if (page.headerWidget) {\n headerHeight = (page.headerWidget.y + page.headerWidget.height);\n }\n var height = Math.max(headerHeight, HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.topMargin))\n * this.viewer.zoomFactor;\n if ((this.viewer.containerTop + point.y) >= pageTop && (this.viewer.containerTop + point.y) <= pageTop + height) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n Selection.prototype.isCursorInFooterRegion = function (point, page) {\n var pageRect = page.boundingRectangle;\n var pageTop = this.getPageTop(page);\n var pageBottom = pageTop + (pageRect.height * this.viewer.zoomFactor);\n var footerDistance = HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.footerDistance);\n var footerHeight = 0;\n if (page.footerWidget) {\n footerHeight = page.footerWidget.height;\n }\n // tslint:disable-next-line:max-line-length\n var height = (pageRect.height -\n Math.max(footerHeight + footerDistance, HelperMethods.convertPointToPixel(page.bodyWidgets[0].sectionFormat.bottomMargin))) * this.viewer.zoomFactor;\n if ((this.viewer.containerTop + point.y) <= pageBottom && (this.viewer.containerTop + point.y) >= pageTop + height) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n Selection.prototype.enableHeadersFootersRegion = function (widget) {\n this.owner.enableHeaderAndFooter = true;\n this.updateTextPositionForBlockContainer(widget);\n return true;\n };\n /**\n * @private\n */\n Selection.prototype.updateTextPositionForBlockContainer = function (widget) {\n var block = widget.firstChild;\n if (block instanceof TableWidget) {\n block = this.getFirstBlockInFirstCell(block);\n }\n this.selectParagraph(block, true);\n };\n /**\n * Disable Header footer\n * @private\n */\n Selection.prototype.disableHeaderFooter = function () {\n var page = this.getPage(this.start.paragraph);\n this.updateTextPositionForBlockContainer(page.bodyWidgets[0]);\n this.owner.enableHeaderAndFooter = false;\n };\n //#endregion\n /**\n * @private\n */\n Selection.prototype.destroy = function () {\n if (!isNullOrUndefined(this.contextTypeInternal)) {\n this.contextTypeInternal = undefined;\n }\n this.caret = undefined;\n this.contextTypeInternal = undefined;\n this.upDownSelectionLength = undefined;\n this.viewer = undefined;\n this.owner = undefined;\n };\n /**\n * Navigates to the specified bookmark.\n * @param name\n * @param moveToStart\n * @private\n */\n Selection.prototype.navigateBookmark = function (name, moveToStart) {\n var bookmarks = this.viewer.bookmarks;\n if (bookmarks.containsKey(name)) {\n //bookmark start element\n var bookmrkElmnt = bookmarks.get(name);\n var offset = bookmrkElmnt.line.getOffset(bookmrkElmnt, 1);\n var startPosition = new TextPosition(this.viewer.owner);\n startPosition.setPositionParagraph(bookmrkElmnt.line, offset);\n if (moveToStart) {\n this.viewer.selection.selectRange(startPosition, startPosition);\n }\n else {\n //bookmark end element\n var bookmrkEnd = bookmrkElmnt.reference;\n var endoffset = bookmrkEnd.line.getOffset(bookmrkEnd, 0);\n var endPosition = new TextPosition(this.viewer.owner);\n endPosition.setPositionParagraph(bookmrkEnd.line, endoffset);\n //selects the bookmark range\n this.viewer.selection.selectRange(startPosition, endPosition);\n }\n }\n };\n /**\n * Selects the specified bookmark.\n * @param name\n */\n Selection.prototype.selectBookmark = function (name) {\n this.navigateBookmark(name);\n };\n /**\n * Returns the toc field from the selection.\n * @private\n */\n Selection.prototype.getTocField = function () {\n var paragraph = this.start.paragraph;\n var tocPara = undefined;\n while ((paragraph !== undefined && this.isTocStyle(paragraph))) {\n tocPara = paragraph;\n paragraph = paragraph.previousRenderedWidget;\n }\n if (tocPara !== undefined) {\n var lineWidget = tocPara.childWidgets[0];\n if (lineWidget !== undefined) {\n return lineWidget.children[0];\n }\n }\n return undefined;\n };\n /**\n * Returns true if the paragraph has toc style.\n */\n Selection.prototype.isTocStyle = function (paragraph) {\n var style = paragraph.paragraphFormat.baseStyle;\n return (style !== undefined && (style.name.toLowerCase().indexOf('toc') !== -1));\n };\n return Selection;\n}());\nexport { Selection };\n","import { Dictionary } from '../../base/dictionary';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { TextPosition } from '../selection/selection-helper';\nimport { TextElementBox, ParagraphWidget, ListTextElementBox, FieldElementBox } from '../viewer/page';\n/**\n * @private\n */\nvar TextSearch = /** @class */ (function () {\n function TextSearch(owner) {\n this.wordBefore = '\\\\b';\n this.wordAfter = '\\\\b';\n this.isHeader = false;\n this.isFooter = false;\n this.owner = owner;\n }\n Object.defineProperty(TextSearch.prototype, \"viewer\", {\n get: function () {\n return this.owner.viewer;\n },\n enumerable: true,\n configurable: true\n });\n TextSearch.prototype.find = function (pattern, findOption) {\n return this.findNext(pattern, findOption, '0;0;0');\n };\n // tslint:disable-next-line:max-line-length \n TextSearch.prototype.findNext = function (pattern, findOption, hierarchicalPosition) {\n if (typeof pattern === 'string') {\n pattern = this.stringToRegex(pattern, findOption);\n }\n if (hierarchicalPosition === undefined) {\n hierarchicalPosition = '0;0;0';\n }\n this.owner.searchModule.textSearchResults.clearResults();\n var results = this.owner.searchModule.textSearchResults;\n this.findDocument(results, pattern, true, findOption, hierarchicalPosition);\n return results.length > 0, results.currentSearchResult;\n };\n TextSearch.prototype.stringToRegex = function (textToFind, option) {\n if (textToFind.indexOf('\\\\') > -1) {\n textToFind = textToFind.split('\\\\').join('\\\\\\\\');\n }\n if (textToFind.indexOf('.') > -1) {\n textToFind = '\\\\' + textToFind;\n }\n if (option === 'WholeWord' || option === 'CaseSensitiveWholeWord') {\n textToFind = this.wordBefore + textToFind + this.wordAfter;\n }\n return new RegExp(textToFind, (option === 'CaseSensitive' || option === 'CaseSensitiveWholeWord') ? 'g' : 'ig');\n };\n TextSearch.prototype.isPatternEmpty = function (pattern) {\n var wordEmpty = this.wordBefore + this.wordAfter;\n var patternRegExp = pattern.toString();\n return (patternRegExp.length === 0 || patternRegExp === wordEmpty);\n };\n // tslint:disable-next-line:max-line-length \n TextSearch.prototype.findAll = function (pattern, findOption, hierarchicalPosition) {\n if (typeof pattern === 'string') {\n pattern = this.stringToRegex(pattern, findOption);\n }\n if (hierarchicalPosition === undefined) {\n hierarchicalPosition = '0;0;0';\n }\n this.owner.searchModule.textSearchResults.clearResults();\n var results = this.owner.searchModule.textSearchResults;\n this.findDocument(results, pattern, false, findOption, hierarchicalPosition);\n if (results.length > 0 && results.currentIndex < 0) {\n results.currentIndex = 0;\n }\n if (!isNullOrUndefined(results.currentSearchResult)) {\n this.viewer.owner.trigger('searchResultsChange');\n return results;\n }\n return undefined;\n };\n // tslint:disable-next-line:max-line-length \n TextSearch.prototype.findDocument = function (results, pattern, isFirstMatch, findOption, hierachicalPosition) {\n if (this.isPatternEmpty(pattern)) {\n return;\n }\n if (findOption === undefined) {\n findOption = 'None';\n }\n var inline = undefined;\n var selectionEnd = undefined;\n if (hierachicalPosition !== undefined) {\n selectionEnd = this.owner.selection.end;\n }\n if (hierachicalPosition !== undefined && isFirstMatch && selectionEnd !== undefined && selectionEnd.paragraph !== undefined) {\n if (selectionEnd.paragraph instanceof ParagraphWidget) {\n var indexInInline = 0;\n // tslint:disable-next-line:max-line-length \n // IndexInInline Handled specifically for simple find operation to start from starting point\n var inlineElement = selectionEnd.currentWidget.getInline(this.owner.selection.start.offset, indexInInline);\n inline = inlineElement.element;\n indexInInline = inlineElement.index;\n if (!isNullOrUndefined(inline)) {\n var nextParagraphWidget = undefined;\n // tslint:disable-next-line:max-line-length \n nextParagraphWidget = this.findInline(inline, pattern, findOption, indexInInline, isFirstMatch, results, selectionEnd);\n while (results.length === 0 && !isNullOrUndefined(nextParagraphWidget)) {\n while (!isNullOrUndefined(nextParagraphWidget) && nextParagraphWidget.childWidgets.length === 0) {\n // tslint:disable-next-line:max-line-length \n nextParagraphWidget = this.owner.selection.getNextParagraph(nextParagraphWidget.containerWidget);\n }\n if (isNullOrUndefined(nextParagraphWidget)) {\n break;\n }\n var lineWidget = nextParagraphWidget.childWidgets[0];\n if (lineWidget.children[0] instanceof ListTextElementBox) {\n inline = (lineWidget.children[2] instanceof TextElementBox) ? lineWidget.children[2] : undefined;\n }\n else {\n inline = lineWidget.children[0];\n }\n if (isNullOrUndefined(inline)) {\n break;\n }\n // tslint:disable-next-line:max-line-length \n nextParagraphWidget = this.findInline(inline, pattern, findOption, 0, isFirstMatch, results, selectionEnd);\n }\n if (results.length > 0) {\n return;\n }\n }\n }\n }\n var section;\n section = this.viewer.pages[0].bodyWidgets[0];\n while (!isNullOrUndefined(section) && section.childWidgets.length === 0) {\n section = section.nextWidget;\n }\n if (isNullOrUndefined(section) || section.childWidgets.length === 0) {\n return;\n }\n this.isHeader = false;\n this.isFooter = false;\n this.findInlineText(section, pattern, findOption, isFirstMatch, results, selectionEnd);\n for (var i = 0; i < this.viewer.pages.length; i++) {\n var headerWidget = this.viewer.pages[i].headerWidget;\n if (!isNullOrUndefined(headerWidget)) {\n this.isHeader = true;\n this.isFooter = false;\n this.findInlineText(headerWidget, pattern, findOption, isFirstMatch, results, selectionEnd);\n }\n }\n for (var i = 0; i < this.viewer.pages.length; i++) {\n var footerWidget = this.viewer.pages[i].footerWidget;\n if (!isNullOrUndefined(footerWidget)) {\n this.isHeader = false;\n this.isFooter = true;\n this.findInlineText(footerWidget, pattern, findOption, isFirstMatch, results, selectionEnd);\n }\n }\n if (isFirstMatch && !isNullOrUndefined(results) && results.length > 0) {\n return;\n }\n };\n // tslint:disable-next-line:max-line-length\n TextSearch.prototype.findInlineText = function (section, pattern, findOption, isFirstMatch, results, selectionEnd) {\n var paragraphWidget = this.owner.selection.getFirstParagraphBlock(section.childWidgets[0]);\n // tslint:disable-next-line:max-line-length \n while (!isNullOrUndefined(paragraphWidget) && paragraphWidget.childWidgets.length === 1 && paragraphWidget.childWidgets[0].children.length === 0) {\n paragraphWidget = this.owner.selection.getNextParagraphBlock(paragraphWidget);\n }\n while (!isNullOrUndefined(paragraphWidget) && paragraphWidget.childWidgets.length > 0) {\n var inlineElement = paragraphWidget.childWidgets[0];\n var inlineEle = inlineElement.children[0];\n if (isNullOrUndefined(inlineEle)) {\n break;\n }\n this.findInline(inlineEle, pattern, findOption, 0, isFirstMatch, results, selectionEnd);\n paragraphWidget = this.owner.selection.getNextParagraphBlock(paragraphWidget);\n // tslint:disable-next-line:max-line-length \n while (!isNullOrUndefined(paragraphWidget) && (paragraphWidget.childWidgets.length === 1) && paragraphWidget.childWidgets[0].children.length === 0) {\n paragraphWidget = this.owner.selection.getNextParagraphBlock(paragraphWidget);\n }\n }\n if (isFirstMatch && !isNullOrUndefined(results) && results.length > 0) {\n return;\n }\n };\n // tslint:disable-next-line:max-line-length \n TextSearch.prototype.findInline = function (inlineElement, pattern, option, indexInInline, isFirstMatch, results, selectionEnd) {\n var inlines = inlineElement;\n var stringBuilder = '';\n var spans = new Dictionary();\n //tslint:disable no-constant-condition\n do {\n // tslint:disable-next-line:max-line-length \n if (inlineElement instanceof TextElementBox && (!isNullOrUndefined(inlineElement.text) && inlineElement.text !== '')) {\n spans.add(inlineElement, stringBuilder.length);\n // IndexInInline Handled specifically for simple find operation to start from starting point\n if (inlineElement === inlines) {\n stringBuilder = stringBuilder + (inlineElement.text.substring(indexInInline));\n }\n else {\n stringBuilder = stringBuilder + (inlineElement.text);\n }\n }\n else if (inlineElement instanceof FieldElementBox) {\n var fieldBegin = inlineElement;\n if (!isNullOrUndefined(fieldBegin.fieldEnd)) {\n // tslint:disable-next-line:max-line-length \n inlineElement = isNullOrUndefined(fieldBegin.fieldSeparator) ? fieldBegin.fieldEnd : fieldBegin.fieldSeparator;\n }\n }\n if (!isNullOrUndefined(inlineElement) && isNullOrUndefined(inlineElement.nextNode)) {\n break;\n }\n if (!isNullOrUndefined(inlineElement)) {\n inlineElement = inlineElement.nextNode;\n }\n } while (true);\n var text = stringBuilder.toString();\n var matches = [];\n var matchObject;\n //tslint:disable no-conditional-assignment\n while (!isNullOrUndefined(matchObject = pattern.exec(text))) {\n matches.push(matchObject);\n }\n for (var i = 0; i < matches.length; i++) {\n var match = matches[i];\n var result = results.addResult();\n var spanKeys = spans.keys;\n for (var i_1 = 0; i_1 < spanKeys.length; i_1++) {\n var span = spanKeys[i_1];\n var startIndex = spans.get(span);\n var spanLength = span.length;\n // IndexInInline Handled specifically for simple find operation to start from starting point\n if (span === inlines) {\n spanLength -= indexInInline;\n }\n if (isNullOrUndefined(result.start) && match.index < startIndex + spanLength) {\n var index = match.index - startIndex;\n // IndexInInline Handled specifically for simple find operation to start from starting point\n if (span === inlines) {\n index += indexInInline;\n }\n var offset = (span.line).getOffset(span, index);\n result.start = this.getTextPosition(span.line, offset.toString());\n result.start.location = this.owner.selection.getPhysicalPositionInternal(span.line, offset, true);\n result.start.setPositionParagraph(span.line, offset);\n }\n if (match.index + match[0].length <= startIndex + spanLength) {\n var index = (match.index + match[0].length) - startIndex;\n // IndexInInline Handled specifically for simple find operation to start from starting point\n if (span === inlines) {\n index += indexInInline;\n }\n var offset = (span.line).getOffset(span, index);\n result.end = this.getTextPosition(span.line, offset.toString());\n result.end.location = this.owner.selection.getPhysicalPositionInternal(span.line, offset, true);\n result.end.setPositionParagraph(span.line, offset);\n break;\n }\n }\n result.isHeader = this.isHeader;\n result.isFooter = this.isFooter;\n if (isFirstMatch) {\n results.currentIndex = 0;\n return undefined;\n }\n else if (results.currentIndex < 0 && selectionEnd.isExistBefore(result.start)) {\n results.currentIndex = results.indexOf(result);\n }\n }\n // tslint:disable-next-line:max-line-length\n var paragraphWidget = this.owner.selection.getNextParagraphBlock(inlineElement.line.paragraph);\n return paragraphWidget;\n };\n TextSearch.prototype.getTextPosition = function (lineWidget, hierarchicalIndex) {\n var textPosition = new TextPosition(this.owner);\n var index = textPosition.getHierarchicalIndex(lineWidget, hierarchicalIndex);\n textPosition.setPositionForCurrentIndex(index);\n return textPosition;\n };\n return TextSearch;\n}());\nexport { TextSearch };\n/**\n * @private\n */\nvar SearchWidgetInfo = /** @class */ (function () {\n function SearchWidgetInfo(left, width) {\n this.leftInternal = 0;\n this.widthInternal = 0;\n this.leftInternal = left;\n this.widthInternal = width;\n }\n Object.defineProperty(SearchWidgetInfo.prototype, \"left\", {\n get: function () {\n return this.leftInternal;\n },\n set: function (value) {\n this.leftInternal = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SearchWidgetInfo.prototype, \"width\", {\n get: function () {\n return this.widthInternal;\n },\n set: function (value) {\n this.widthInternal = value;\n },\n enumerable: true,\n configurable: true\n });\n return SearchWidgetInfo;\n}());\nexport { SearchWidgetInfo };\n","/**\n * @private\n */\nvar TextSearchResult = /** @class */ (function () {\n function TextSearchResult(owner) {\n this.startIn = undefined;\n this.endIn = undefined;\n this.owner = owner;\n }\n Object.defineProperty(TextSearchResult.prototype, \"viewer\", {\n get: function () {\n return this.owner.viewer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextSearchResult.prototype, \"start\", {\n get: function () {\n return this.startIn;\n },\n set: function (value) {\n this.startIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextSearchResult.prototype, \"end\", {\n get: function () {\n return this.endIn;\n },\n set: function (value) {\n this.endIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextSearchResult.prototype, \"text\", {\n get: function () {\n return this.viewer.selection.getTextInternal(this.start, this.end, false);\n },\n enumerable: true,\n configurable: true\n });\n TextSearchResult.prototype.destroy = function () {\n this.start = undefined;\n this.end = undefined;\n };\n return TextSearchResult;\n}());\nexport { TextSearchResult };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { TextSearchResult } from './text-search-result';\n/**\n * @private\n */\nvar TextSearchResults = /** @class */ (function () {\n function TextSearchResults(owner) {\n this.currentIndex = -1;\n this.owner = owner;\n }\n Object.defineProperty(TextSearchResults.prototype, \"length\", {\n get: function () {\n if (this.innerList === undefined) {\n return 0;\n }\n return this.innerList.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TextSearchResults.prototype, \"currentSearchResult\", {\n get: function () {\n if (this.innerList === undefined || this.currentIndex < 0 || this.currentIndex >= this.length) {\n return undefined;\n }\n return this.innerList[this.currentIndex];\n },\n enumerable: true,\n configurable: true\n });\n TextSearchResults.prototype.addResult = function () {\n var textSearchResult = new TextSearchResult(this.owner);\n if (isNullOrUndefined(this.innerList)) {\n this.innerList = [];\n }\n this.innerList.push(textSearchResult);\n return textSearchResult;\n };\n TextSearchResults.prototype.clearResults = function () {\n this.currentIndex = -1;\n if (!isNullOrUndefined(this.innerList)) {\n for (var i = this.innerList.length - 1; i >= 0; i--) {\n this.innerList[i].destroy();\n this.innerList.splice(i, 1);\n }\n }\n };\n TextSearchResults.prototype.indexOf = function (result) {\n if (isNullOrUndefined(this.innerList)) {\n return -1;\n }\n return this.innerList.indexOf(result);\n };\n TextSearchResults.prototype.destroy = function () {\n if (!isNullOrUndefined(this.innerList)) {\n this.clearResults();\n }\n this.innerList = undefined;\n };\n return TextSearchResults;\n}());\nexport { TextSearchResults };\n","/**\n * Search Result info\n */\nvar SearchResults = /** @class */ (function () {\n /**\n * @private\n */\n function SearchResults(search) {\n this.searchModule = search;\n }\n Object.defineProperty(SearchResults.prototype, \"length\", {\n /**\n * Gets the length of search results.\n */\n get: function () {\n return this.searchModule.textSearchResults.length;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SearchResults.prototype, \"index\", {\n /**\n * Gets the index of current search result.\n */\n get: function () {\n return this.searchModule.textSearchResults.currentIndex;\n },\n /**\n * Set the index of current search result.\n */\n set: function (value) {\n if (this.length === 0 || value < 0 || value > this.searchModule.textSearchResults.length - 1) {\n return;\n }\n this.searchModule.textSearchResults.currentIndex = value;\n this.navigate(value);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Replace text in current search result.\n * @param textToReplace text to replace\n * @private\n */\n SearchResults.prototype.replace = function (textToReplace) {\n if (this.index === -1) {\n return;\n }\n this.searchModule.replaceInternal(textToReplace);\n };\n /**\n * Replace all the instance of search result.\n * @param textToReplace text to replace\n */\n SearchResults.prototype.replaceAll = function (textToReplace) {\n if (this.index === -1) {\n return;\n }\n this.searchModule.replaceAllInternal(textToReplace);\n };\n /**\n * @private\n */\n SearchResults.prototype.navigate = function (index) {\n this.searchModule.navigate(this.searchModule.textSearchResults.currentSearchResult);\n this.searchModule.highlight(this.searchModule.textSearchResults);\n };\n /**\n * Clears all the instance of search result.\n */\n SearchResults.prototype.clear = function () {\n this.searchModule.textSearchResults.clearResults();\n this.searchModule.clearSearchHighlight();\n this.searchModule.viewer.renderVisiblePages();\n };\n return SearchResults;\n}());\nexport { SearchResults };\n","import { Dictionary } from '../../base/dictionary';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { TextPosition } from '../selection/selection-helper';\nimport { TextElementBox, FieldElementBox } from '../viewer/page';\nimport { SearchWidgetInfo } from './text-search';\nimport { TextSearch } from '../search/text-search';\nimport { TextSearchResults } from '../search/text-search-results';\nimport { SearchResults } from './search-results';\n/**\n * Search module\n */\nvar Search = /** @class */ (function () {\n /**\n * @private\n */\n function Search(owner) {\n /**\n * @private\n */\n this.searchHighlighters = undefined;\n this.isHandledOddPageHeader = undefined;\n this.isHandledEvenPageHeader = undefined;\n this.isHandledOddPageFooter = undefined;\n this.isHandledEvenPageFooter = undefined;\n this.owner = owner;\n this.searchHighlighters = new Dictionary();\n this.textSearch = new TextSearch(this.owner);\n this.textSearchResults = new TextSearchResults(this.owner);\n this.searchResultsInternal = new SearchResults(this);\n }\n Object.defineProperty(Search.prototype, \"viewer\", {\n /**\n * @private\n */\n get: function () {\n return this.owner.viewer;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Search.prototype, \"searchResults\", {\n /**\n * Gets the search results object.\n */\n get: function () {\n return this.searchResultsInternal;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Get the module name.\n */\n Search.prototype.getModuleName = function () {\n return 'Search';\n };\n //#region Find & Find All\n /**\n * Finds the immediate occurrence of specified text from cursor position in the document.\n * @param {string} text\n * @param {FindOption} findOption? - Default value of ‘findOptions’ parameter is 'None'.\n * @private\n */\n Search.prototype.find = function (text, findOptions) {\n if (isNullOrUndefined(findOptions)) {\n findOptions = 'None';\n }\n var result = this.textSearch.find(text, findOptions);\n if (!isNullOrUndefined(result)) {\n this.navigate(result);\n }\n };\n /**\n * Finds all occurrence of specified text in the document.\n * @param {string} text\n * @param {FindOption} findOption? - Default value of ‘findOptions’ parameter is 'None'.\n */\n Search.prototype.findAll = function (text, findOptions) {\n if (isNullOrUndefined(text || text === '')) {\n return;\n }\n if (isNullOrUndefined(findOptions)) {\n findOptions = 'None';\n }\n var results = this.textSearch.findAll(text, findOptions);\n if (!isNullOrUndefined(results) && results.length > 0) {\n this.navigate(results.innerList[results.currentIndex]);\n this.highlight(results);\n }\n };\n //#endregion\n //#region Replace and Replace All \n /**\n * Replace the searched string with specified string\n * @param {string} replaceText\n * @param {TextSearchResult} result\n * @param {TextSearchResults} results\n * @private\n */\n Search.prototype.replace = function (replaceText, result, results) {\n if (isNullOrUndefined(this.viewer.owner) || this.viewer.owner.isReadOnlyMode || isNullOrUndefined(results)) {\n return 0;\n }\n if (!isNullOrUndefined(this.viewer)) {\n this.clearSearchHighlight();\n }\n this.navigate(result);\n var endPosition = this.viewer.selection.start;\n var index = results.indexOf(result);\n if (index < 0) {\n return 0;\n }\n this.owner.editorModule.insertText(replaceText, true);\n var endTextPosition = result.end;\n var startPosition = new TextPosition(this.viewer.owner);\n startPosition.setPositionParagraph(endTextPosition.currentWidget, endPosition.offset - replaceText.length);\n this.viewer.selection.selectRange(endPosition, startPosition);\n this.viewer.owner.trigger('searchResultsChange');\n return 1;\n };\n /**\n * Find the textToFind string in current document and replace the specified string.\n * @param {string} textToFind\n * @param {string} textToReplace\n * @param {FindOption} findOptions? - Default value of ‘findOptions’ parameter is FindOption.None.\n * @private\n */\n Search.prototype.replaceInternal = function (textToReplace, findOptions) {\n if ((textToReplace === '' || isNullOrUndefined(textToReplace))) {\n return;\n }\n if (isNullOrUndefined(findOptions)) {\n findOptions = 'None';\n }\n var textToFind = this.textSearchResults.currentSearchResult.text;\n var pattern = this.viewer.owner.searchModule.textSearch.stringToRegex(textToFind, findOptions);\n var index = this.owner.selection.end.getHierarchicalIndexInternal();\n var result = this.viewer.owner.searchModule.textSearch.findNext(pattern, findOptions, index);\n if (!isNullOrUndefined(result)) {\n this.navigate(result);\n this.textSearchResults.addResult();\n this.textSearchResults.innerList[0] = result;\n this.replace(textToReplace, result, this.textSearchResults);\n index = this.owner.selection.end.getHierarchicalIndexInternal();\n result = this.textSearch.findNext(textToFind, findOptions, index);\n if (result) {\n this.textSearchResults.addResult();\n this.textSearchResults.innerList[0] = result;\n this.navigate(result);\n }\n }\n };\n /**\n * Replace all the searched string with specified string\n * @param {string} replaceText\n * @param {TextSearchResults} results\n * @private\n */\n Search.prototype.replaceAll = function (replaceText, results) {\n if (isNullOrUndefined(this.viewer.owner) || this.viewer.owner.isReadOnlyMode || isNullOrUndefined(results)) {\n return 0;\n }\n if (this.owner.editorHistory) {\n this.owner.editorHistory.initComplexHistory(this.owner.selection, 'ReplaceAll');\n }\n var count = results.length;\n this.viewer.owner.isLayoutEnabled = false;\n for (var i = count - 1; i >= 0; i--) {\n this.navigate(results.innerList[i]);\n this.owner.editorModule.insertText(replaceText, true);\n results.innerList[i].destroy();\n }\n if (this.owner.editorHistory && !isNullOrUndefined(this.owner.editorHistory.currentHistoryInfo)) {\n this.owner.editorHistory.updateComplexHistory();\n }\n else {\n this.owner.editorModule.updateComplexWithoutHistory(2);\n }\n this.searchResults.clear();\n return count;\n };\n /**\n * Find the textToFind string in current document and replace the specified string.\n * @param {string} textToFind\n * @param {string} textToReplace\n * @param {FindOption} findOptions? - Default value of ‘findOptions’ parameter is FindOption.None.\n * @private\n */\n Search.prototype.replaceAllInternal = function (textToReplace, findOptions) {\n if ((textToReplace === '' || isNullOrUndefined(textToReplace))) {\n return;\n }\n if (isNullOrUndefined(findOptions)) {\n findOptions = 'None';\n }\n if (this.textSearchResults.length > 0) {\n this.navigate(this.textSearchResults.innerList[this.textSearchResults.currentIndex]);\n this.highlight(this.textSearchResults);\n this.replaceAll(textToReplace, this.textSearchResults);\n }\n };\n //#endregion\n //#region Highlight Search Result\n /**\n * @private\n */\n Search.prototype.navigate = function (textSearchResult) {\n if (textSearchResult) {\n var start = textSearchResult.start;\n var end = textSearchResult.end;\n if (!isNullOrUndefined(this.owner) && !isNullOrUndefined(this.owner.selection) && !isNullOrUndefined(start) &&\n !isNullOrUndefined(end) && !isNullOrUndefined(start.paragraph) && !isNullOrUndefined(end.paragraph)) {\n this.owner.selection.selectRange(start, end);\n }\n }\n };\n /**\n * @private\n */\n Search.prototype.highlight = function (textSearchResults) {\n this.searchHighlighters = new Dictionary();\n for (var i = 0; i < textSearchResults.innerList.length; i++) {\n var result = textSearchResults.innerList[i];\n this.highlightResult(result);\n }\n this.viewer.renderVisiblePages();\n };\n /**\n * @private\n */\n Search.prototype.highlightResult = function (result) {\n this.highlightSearchResult(result.start.paragraph, result.start, result.end);\n };\n /**\n * Highlight search result\n * @private\n */\n Search.prototype.highlightSearchResult = function (paragraph, start, end) {\n var selectionStartIndex = 0;\n var selectionEndIndex = 0;\n var startElement = null;\n var endElement = null;\n // tslint:disable-next-line:max-line-length\n var lineWidget = this.viewer.selection.getStartLineWidget(paragraph, start, startElement, selectionStartIndex);\n selectionStartIndex = lineWidget.index;\n startElement = lineWidget.element;\n var startLineWidget = startElement ? startElement.line : paragraph.childWidgets[0];\n var endLine = this.viewer.selection.getEndLineWidget(end, endElement, selectionEndIndex);\n selectionEndIndex = endLine.index;\n endElement = endLine.element;\n var endLineWidget = endElement ? endElement.line :\n end.paragraph.childWidgets[end.paragraph.childWidgets.length - 1];\n var top = this.viewer.selection.getTop(startLineWidget);\n var left = this.viewer.selection.getLeftInternal(startLineWidget, startElement, selectionStartIndex);\n if (!isNullOrUndefined(startLineWidget) && startLineWidget === endLineWidget) {\n //find result ends in current line.\n var right = this.viewer.selection.getLeftInternal(endLineWidget, endElement, selectionEndIndex);\n this.createHighlightBorder(startLineWidget, right - left, left, top);\n }\n else {\n if (!isNullOrUndefined(startLineWidget)) {\n if (paragraph !== startLineWidget.paragraph) {\n paragraph = startLineWidget.paragraph;\n }\n // tslint:disable-next-line:max-line-length\n this.createHighlightBorder(startLineWidget, this.viewer.selection.getWidth(startLineWidget, true) - (left - startLineWidget.paragraph.x), left, top);\n var lineIndex = startLineWidget.paragraph.childWidgets.indexOf(startLineWidget);\n //Iterates to last item of paragraph or search result end.\n var startParagraphWidget = void 0;\n for (var i = 0; i < paragraph.childWidgets.length; i++) {\n if (paragraph === startLineWidget.paragraph) {\n lineIndex += 1;\n }\n this.highlightSearchResultParaWidget(paragraph, lineIndex, endLineWidget, endElement, selectionEndIndex);\n if (paragraph === endLineWidget.paragraph) {\n return;\n }\n else {\n lineIndex = 0;\n }\n }\n }\n }\n };\n /**\n * @private\n */\n Search.prototype.createHighlightBorder = function (lineWidget, width, left, top) {\n var findHighLight = this.addSearchHighlightBorder(lineWidget);\n var page = this.viewer.owner.selection.getPage(lineWidget.paragraph);\n var pageTop = page.boundingRectangle.y;\n var pageLeft = page.boundingRectangle.x;\n findHighLight.left = Math.ceil(left);\n top = Math.ceil(top);\n findHighLight.width = Math.floor(width);\n var height = Math.floor(lineWidget.height);\n var context = this.viewer.containerContext;\n };\n /**\n * Adds search highlight border.\n * @private\n */\n Search.prototype.addSearchHighlightBorder = function (lineWidget) {\n var highlighters = undefined;\n if (this.searchHighlighters.containsKey(lineWidget)) {\n highlighters = this.searchHighlighters.get(lineWidget);\n }\n else {\n highlighters = [];\n this.searchHighlighters.add(lineWidget, highlighters);\n }\n var searchHighlight = new SearchWidgetInfo(0, 0);\n highlighters.push(searchHighlight);\n return searchHighlight;\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Search.prototype.highlightSearchResultParaWidget = function (widget, startIndex, endLine, endElement, endIndex) {\n var top = 0;\n for (var j = startIndex; j < widget.childWidgets.length; j++) {\n var lineWidget = widget.childWidgets[j];\n if (j === startIndex) {\n top = this.viewer.selection.getTop(lineWidget);\n }\n var left = this.viewer.selection.getLeft(lineWidget);\n if (lineWidget === endLine) {\n //Search result ends in current line.\n var right = this.viewer.selection.getLeftInternal(endLine, endElement, endIndex);\n this.createHighlightBorder(lineWidget, right - left, left, top);\n return;\n }\n this.createHighlightBorder(lineWidget, this.viewer.selection.getWidth(lineWidget, true) - (left - widget.x), left, top);\n top += lineWidget.height;\n }\n };\n //#endregion\n //#region Get find result view\n /**\n * @private\n */\n Search.prototype.addSearchResultItems = function (result) {\n if (isNullOrUndefined(result) || result === '') {\n return;\n }\n if (isNullOrUndefined(this.owner.findResultsList)) {\n this.owner.findResultsList = [];\n }\n this.owner.findResultsList.push(result);\n };\n /**\n * @private\n */\n Search.prototype.addFindResultView = function (textSearchResults) {\n for (var i = 0; i < textSearchResults.innerList.length; i++) {\n var result = textSearchResults.innerList[i];\n this.addFindResultViewForSearch(result);\n }\n this.isHandledOddPageHeader = true;\n this.isHandledOddPageFooter = true;\n this.isHandledEvenPageHeader = true;\n this.isHandledEvenPageFooter = true;\n };\n /**\n * @private\n */\n // tslint:disable:max-func-body-length\n Search.prototype.addFindResultViewForSearch = function (result) {\n if (result.start != null && result.end != null && result.start.paragraph != null && result.end.paragraph != null) {\n var prefixText = void 0;\n var suffixtext = void 0;\n var currentText = void 0;\n var startIndex = 0;\n var inlineObj = result.start.currentWidget.getInline(result.start.offset, startIndex);\n var inline = inlineObj.element;\n startIndex = inlineObj.index;\n var prefix = '';\n var lastIndex = 0;\n if (inline instanceof FieldElementBox) {\n var elementInfo = this.owner.selection.getRenderedInline(inline, startIndex);\n if (elementInfo.element.nextNode instanceof TextElementBox) {\n inline = elementInfo.element.nextNode;\n startIndex = elementInfo.index;\n }\n else {\n inline = elementInfo.element;\n startIndex = elementInfo.index;\n }\n }\n var boxObj = this.owner.selection.getElementBoxInternal(inline, startIndex);\n var box = boxObj.element;\n startIndex = boxObj.index;\n if (box != null) {\n if (box instanceof TextElementBox && startIndex > 0) {\n prefix = box.text.substring(0, startIndex);\n }\n var boxIndex = box.line.children.indexOf(box);\n // tslint:disable-next-line:max-line-length\n lastIndex = prefix.lastIndexOf(' ');\n while (lastIndex < 0 && boxIndex > 0 && box.line.children[boxIndex - 1] instanceof TextElementBox) {\n prefix = box.line.children[boxIndex - 1].text + prefix;\n boxIndex--;\n lastIndex = prefix.lastIndexOf(' ');\n }\n }\n var shiftIndex = prefix.lastIndexOf('\\v');\n if (shiftIndex > 0) {\n prefix = prefix.substring(0, shiftIndex);\n }\n else {\n lastIndex = prefix.lastIndexOf(' ');\n prefixText = lastIndex < 0 ? prefix : prefix.substring(lastIndex + 1);\n }\n currentText = result.text;\n var endIndex = 0;\n var endInlineObj = result.end.currentWidget.getInline(result.end.offset, endIndex);\n var endInline = endInlineObj.element;\n endIndex = endInlineObj.index;\n suffixtext = '';\n //Checks prefix element box is empty\n if (boxObj != null) {\n // Gets the element box using endIndex of the text and set as suffix\n boxObj = this.owner.selection.getElementBoxInternal(endInline, endIndex);\n box = boxObj.element;\n endIndex = boxObj.index;\n }\n //Checks suffix element box is empty.\n if (box != null) {\n if (box instanceof TextElementBox && endIndex < box.length) {\n suffixtext = box.text.substring(endIndex);\n }\n var boxIndex = box.line.children.indexOf(box);\n // tslint:disable-next-line:max-line-length\n while (boxIndex + 1 < box.line.children.length && (box.line.children[boxIndex + 1] instanceof TextElementBox) || (box.line.children[boxIndex + 1] instanceof FieldElementBox)) {\n if (box.line.children[boxIndex + 1] instanceof FieldElementBox) {\n boxIndex = boxIndex + 2;\n }\n else {\n suffixtext = suffixtext + box.line.children[boxIndex + 1].text;\n boxIndex = boxIndex + 1;\n }\n }\n }\n lastIndex = suffixtext.lastIndexOf(' ');\n suffixtext = suffixtext === '\\v' ? suffixtext = '' : suffixtext;\n var headerFooterString = '';\n if (result.isHeader) {\n headerFooterString = '';\n }\n else if (result.isFooter) {\n headerFooterString = '';\n }\n else {\n headerFooterString = '';\n headerFooterString = '';\n this.isHandledOddPageHeader = true;\n this.isHandledEvenPageHeader = true;\n this.isHandledOddPageFooter = true;\n this.isHandledEvenPageFooter = true;\n }\n var listElement = '';\n var page = result.viewer.selection.getPage(result.start.paragraph);\n if (isNullOrUndefined(this.isHandledEvenPageHeader) && isNullOrUndefined(this.isHandledEvenPageFooter)) {\n this.isHandledEvenPageHeader = true;\n this.isHandledEvenPageFooter = true;\n }\n else if (isNullOrUndefined(this.isHandledOddPageHeader) && isNullOrUndefined(this.isHandledOddPageFooter)) {\n this.isHandledOddPageHeader = true;\n this.isHandledOddPageFooter = true;\n }\n if (result.isHeader) {\n if (page.headerWidget.headerFooterType === 'FirstPageHeader' && page.bodyWidgets[0].sectionFormat.differentFirstPage) {\n // tslint:disable-next-line:max-line-length\n listElement = '' + headerFooterString + prefix + '' + result.text + ' ' + suffixtext + ' ';\n }\n else if (page.headerWidget.headerFooterType === 'EvenHeader' && this.isHandledEvenPageHeader) {\n // tslint:disable-next-line:max-line-length\n listElement = '' + headerFooterString + prefix + '' + result.text + ' ' + suffixtext + ' ';\n this.isHandledEvenPageHeader = false;\n // tslint:disable-next-line:max-line-length\n }\n else if (page.headerWidget.headerFooterType === 'OddHeader' && this.isHandledOddPageHeader) {\n listElement = '' + headerFooterString + prefix + '' + result.text + ' ' + suffixtext + ' ';\n this.isHandledOddPageHeader = false;\n }\n }\n else if (result.isFooter) {\n if (page.footerWidget.headerFooterType === 'FirstPageFooter' && page.bodyWidgets[0].sectionFormat.differentFirstPage) {\n // tslint:disable-next-line:max-line-length\n listElement = '' + headerFooterString + prefix + '' + result.text + ' ' + suffixtext + ' ';\n }\n else if (page.footerWidget.headerFooterType === 'EvenFooter' && this.isHandledEvenPageFooter) {\n // tslint:disable-next-line:max-line-length\n listElement = '' + headerFooterString + prefix + '' + result.text + ' ' + suffixtext + ' ';\n this.isHandledEvenPageFooter = false;\n // tslint:disable-next-line:max-line-length\n }\n else if (page.footerWidget.headerFooterType === 'OddFooter' && this.isHandledOddPageFooter) {\n listElement = '' + headerFooterString + prefix + '' + result.text + ' ' + suffixtext + ' ';\n this.isHandledOddPageFooter = false;\n }\n // tslint:disable-next-line:max-line-length\n }\n else if (!result.isHeader && !result.isFooter) {\n listElement = '' + headerFooterString + prefix + '' + result.text + ' ' + suffixtext + ' ';\n }\n this.addSearchResultItems(listElement);\n }\n };\n //#endregion\n /**\n * Clears search highlight.\n * @private\n */\n Search.prototype.clearSearchHighlight = function () {\n if (!isNullOrUndefined(this.searchHighlighters)) {\n this.searchHighlighters.clear();\n this.searchHighlighters = undefined;\n }\n this.viewer.owner.trigger('searchResultsChange');\n };\n /**\n * @private\n */\n Search.prototype.destroy = function () {\n if (this.textSearchResults) {\n this.textSearchResults.destroy();\n }\n };\n return Search;\n}());\nexport { Search };\n","import { createElement, isNullOrUndefined, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { HelperMethods } from '../editor/editor-helper';\nimport { CheckBox } from '@syncfusion/ej2-buttons';\nimport { Tab } from '@syncfusion/ej2-navigations';\n/**\n * Options Pane class.\n */\nvar OptionsPane = /** @class */ (function () {\n /**\n * Constructor for Options pane module\n * @param {LayoutViewer} layoutViewer\n * @private\n */\n function OptionsPane(layoutViewer) {\n var _this = this;\n /**\n * @private\n */\n this.isOptionsPaneShow = false;\n this.findOption = 'None';\n this.matchCase = undefined;\n this.wholeWord = undefined;\n // private regular: CheckBox = undefined;\n this.searchText = 'Navigation';\n this.resultsText = 'Results';\n this.messageDivText = 'No matches';\n this.replaceButtonText = 'Replace';\n this.replaceAllButtonText = 'Replace All';\n this.focusedIndex = -1;\n this.focusedElement = [];\n this.isOptionsPane = true;\n this.replacePaneText = 'Replace';\n this.findPaneText = 'Find';\n this.matchDivReplaceText = 'No matches';\n /**\n * @private\n */\n this.tabInstance = undefined;\n /**\n * @private\n */\n this.isReplace = false;\n /**\n * Gets selected tab item which tab is selected.\n * @param {SelectEventArgs} args - Specifies which tab will be opened.\n * @private\n */\n this.selectedTabItem = function (args) {\n if (args.previousIndex !== args.selectedIndex) {\n var previousTab = document.querySelector('#e-content_' + args.previousIndex);\n var nextTab = document.querySelector('#e-content_' + args.selectedIndex);\n nextTab.insertBefore(previousTab.firstElementChild, nextTab.firstChild);\n }\n if (args.selectedIndex === 0 && !isNullOrUndefined(document.querySelector('#e-content_' + args.selectedIndex))) {\n _this.isOptionsPane = true;\n _this.onFindPane();\n }\n if (args.selectedIndex === 1 && !isNullOrUndefined(document.querySelector('#e-content_' + args.selectedIndex))) {\n _this.isOptionsPane = false;\n _this.onReplacePane();\n }\n };\n this.searchOptionChange = function () {\n _this.clearSearchResultItems();\n _this.viewer.owner.searchModule.clearSearchHighlight();\n var inputText = _this.searchInput.value;\n if (inputText === '') {\n return;\n }\n var pattern = _this.viewer.owner.searchModule.textSearch.stringToRegex(inputText, _this.findOption);\n var endSelection = _this.viewer.selection.end;\n var selectionIndex = endSelection.getHierarchicalIndexInternal();\n _this.results = _this.viewer.owner.searchModule.textSearch.findAll(pattern, _this.findOption, selectionIndex);\n if (_this.results != null && _this.results.length > 0) {\n _this.navigateSearchResult();\n }\n else {\n _this.viewer.renderVisiblePages();\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('No matches');\n _this.resultContainer.style.display = 'block';\n _this.resultsListBlock.style.display = 'none';\n _this.clearFocusElement();\n _this.resultsListBlock.innerHTML = '';\n }\n };\n /**\n * Apply find option based on whole words value.\n * @param {ChangeEventArgs} args - Specifies the search options value.\n * @private\n */\n this.wholeWordsChange = function (args) {\n if (_this.matchInput.checked && _this.wholeInput.checked) {\n _this.findOption = 'CaseSensitiveWholeWord';\n }\n else if (_this.matchInput.checked && !(_this.wholeInput.checked)) {\n _this.findOption = 'CaseSensitive';\n }\n else if (!(_this.matchInput.checked) && _this.wholeInput.checked) {\n _this.findOption = 'WholeWord';\n }\n else {\n _this.findOption = 'None';\n }\n _this.searchOptionChange();\n };\n /**\n * Apply find option based on match value.\n * @param {ChangeEventArgs} args - Specifies the search options value.\n * @private\n */\n this.matchChange = function (args) {\n if (_this.matchInput.checked && _this.wholeInput.checked) {\n _this.findOption = 'CaseSensitiveWholeWord';\n }\n else if (!(_this.matchInput.checked) && _this.wholeInput.checked) {\n _this.findOption = 'WholeWord';\n }\n else if (_this.matchInput.checked && !(_this.wholeInput.checked)) {\n _this.findOption = 'CaseSensitive';\n }\n else {\n _this.findOption = 'None';\n }\n _this.searchOptionChange();\n };\n /**\n * Apply find options based on regular value.\n * @param {ChangeEventArgs} args - Specifies the search options value.\n * @private\n */\n // public regularChange = (args: ChangeEventArgs): void => {\n // if (args.checked) {\n // this.matchCase.element.parentElement.parentElement.classList.add('e-checkbox-disabled');\n // this.wholeWord.element.parentElement.parentElement.classList.add('e-checkbox-disabled');\n // this.matchCase.checked = false;\n // this.wholeWord.checked = false;\n // this.findOption = 'None';\n // this.onKeyDownInternal();\n // } else {\n // this.matchCase.element.parentElement.parentElement.classList.remove('e-checkbox-disabled');\n // this.wholeWord.element.parentElement.parentElement.classList.remove('e-checkbox-disabled');\n // }\n // }\n // tslint:enable:no-any \n /**\n * Binding events from the element when optins pane creation.\n * @private\n */\n this.onWireEvents = function () {\n _this.searchIcon.addEventListener('click', _this.searchIconClickInternal);\n _this.navigateToNextResult.addEventListener('click', _this.navigateNextResultButtonClick);\n _this.navigateToPreviousResult.addEventListener('click', _this.navigatePreviousResultButtonClick);\n _this.searchInput.addEventListener('keydown', _this.onKeyDown);\n _this.searchInput.addEventListener('keyup', _this.onEnableDisableReplaceButton);\n _this.resultsListBlock.addEventListener('click', _this.resultListBlockClick);\n _this.closeButton.addEventListener('click', _this.close);\n _this.replaceButton.addEventListener('click', _this.onReplaceButtonClick);\n _this.replaceAllButton.addEventListener('click', _this.onReplaceAllButtonClick);\n };\n /**\n * Enable find pane only.\n * @private\n */\n this.onFindPane = function () {\n _this.replaceDiv.style.display = 'none';\n _this.occurrenceDiv.style.display = 'none';\n if (!isNullOrUndefined(_this.results) && _this.results.length === 0) {\n _this.resultsListBlock.innerHTML = '';\n _this.resultsListBlock.style.display = 'none';\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('No matches');\n }\n _this.resultsListBlock.style.height = _this.resultsListBlock.offsetHeight + _this.replaceTabContentDiv.offsetHeight + 'px';\n _this.replaceTabContentDiv.style.display = 'none';\n _this.findDiv.style.display = 'block';\n _this.messageDiv.style.display = 'block';\n _this.focusedElement = [];\n // tslint:disable-next-line:max-line-length\n _this.focusedElement.push(_this.closeButton, _this.findTabButtonHeader, _this.replaceTabButtonHeader, _this.searchInput, _this.searchIcon, _this.navigateToPreviousResult, _this.navigateToNextResult, _this.matchInput, _this.wholeInput);\n _this.focusedIndex = 3;\n _this.searchInput.select();\n _this.getMessageDivHeight();\n };\n this.onEnableDisableReplaceButton = function () {\n if (_this.searchInput.value.length !== 0) {\n _this.replaceButton.disabled = false;\n _this.replaceAllButton.disabled = false;\n }\n else {\n _this.replaceButton.disabled = true;\n _this.replaceAllButton.disabled = true;\n }\n };\n /**\n * Enable replace pane only.\n * @private\n */\n this.onReplacePane = function () {\n _this.findDiv.style.display = 'block';\n _this.replaceDiv.style.display = 'block';\n _this.replaceTabContentDiv.style.display = 'block';\n _this.resultsListBlock.style.height = _this.resultsListBlock.offsetHeight - _this.replaceTabContentDiv.offsetHeight + 'px';\n _this.isOptionsPane = false;\n if (_this.searchInput.value.length !== 0) {\n _this.replaceButton.disabled = false;\n _this.replaceAllButton.disabled = false;\n }\n else {\n _this.replaceButton.disabled = true;\n _this.replaceAllButton.disabled = true;\n }\n _this.focusedElement = [];\n // tslint:disable-next-line:max-line-length\n _this.focusedElement.push(_this.closeButton, _this.findTabButtonHeader, _this.replaceTabButtonHeader, _this.searchInput, _this.searchIcon, _this.navigateToPreviousResult, _this.navigateToNextResult, _this.matchInput, _this.wholeInput, _this.replaceWith, _this.replaceButton, _this.replaceAllButton);\n _this.focusedIndex = 9;\n if (_this.searchInput.value === '') {\n _this.searchInput.select();\n }\n else {\n _this.replaceWith.select();\n }\n _this.getMessageDivHeight();\n };\n /**\n * Fires on key down on options pane.\n * @param {KeyboardEvent} event - Specifies the focus of current element.\n * @private\n */\n this.onKeyDownOnOptionPane = function (event) {\n // if (event.keyCode === 70) {\n // event.preventDefault();\n // return;\n // }\n if (event.keyCode === 9) {\n event.preventDefault();\n var focusIndex = undefined;\n if (event.shiftKey) {\n focusIndex = (_this.focusedIndex === 0 || isNullOrUndefined(_this.focusedIndex)) ?\n _this.focusedElement.length - 1 : _this.focusedIndex - 1;\n }\n else {\n focusIndex = (_this.focusedElement.length - 1 === _this.focusedIndex || isNullOrUndefined(_this.focusedIndex)) ?\n 0 : _this.focusedIndex + 1;\n }\n var element = _this.focusedElement[focusIndex];\n element.focus();\n if (element instanceof HTMLInputElement) {\n element.select();\n }\n _this.focusedIndex = focusIndex;\n if (element instanceof HTMLLIElement) {\n _this.scrollToPosition(element);\n }\n }\n else if (event.keyCode === 13) {\n // tslint:disable-next-line:max-line-length\n if (event.target !== _this.searchInput && event.target !== _this.closeButton) {\n event.preventDefault();\n var index = _this.focusedElement.indexOf(event.target);\n if (index !== -1) {\n var list = _this.focusedElement[index];\n list.click();\n list.focus();\n _this.focusedIndex = index;\n }\n }\n }\n else if (event.keyCode === 40 || event.keyCode === 38) {\n if (_this.resultsListBlock.style.display !== 'none') {\n var index = void 0;\n var element = void 0;\n if (event.keyCode === 40) {\n if (_this.focusedIndex > 7) {\n if (_this.focusedIndex + 1 < _this.focusedElement.length) {\n element = _this.focusedElement[_this.focusedIndex + 1];\n element.focus();\n _this.focusedIndex = _this.focusedIndex + 1;\n }\n }\n else {\n index = (_this.focusedElement.length - _this.resultsListBlock.children.length) + _this.results.currentIndex + 1;\n if (index < _this.focusedElement.length) {\n element = _this.focusedElement[index];\n element.focus();\n _this.focusedIndex = index;\n }\n }\n }\n else {\n if (_this.focusedIndex > 8) {\n index = _this.focusedIndex - 1;\n element = _this.focusedElement[index];\n element.focus();\n _this.focusedIndex = index;\n }\n }\n }\n }\n };\n /**\n * Fires on replace.\n * @private\n */\n this.onReplaceButtonClick = function () {\n var optionsPane = _this.optionsPane;\n var findText = _this.searchInput.value;\n var replaceText = _this.replaceWith.value;\n var results = _this.viewer.owner.searchModule.textSearchResults;\n if (findText !== '' && !isNullOrUndefined(findText)) {\n if (_this.viewer.owner.selection != null) {\n var selectionText = _this.viewer.owner.selection.text;\n if (!_this.viewer.owner.selection.isEmpty) {\n if (_this.viewer.owner.selection.isForward) {\n _this.viewer.owner.selection.selectContent(_this.viewer.owner.selection.start, true);\n }\n else {\n _this.viewer.owner.selection.selectContent(_this.viewer.owner.selection.end, true);\n }\n }\n if (!isNullOrUndefined(results) && !isNullOrUndefined(results.currentSearchResult)) {\n var result = results.currentSearchResult;\n _this.viewer.owner.searchModule.navigate(result);\n if (result.text === selectionText) {\n var replace = isNullOrUndefined(replaceText) ? '' : replaceText;\n _this.viewer.owner.searchModule.replace(replace, result, results);\n var pattern = _this.viewer.owner.searchModule.textSearch.stringToRegex(findText, _this.findOption);\n var endSelection = _this.viewer.selection.end;\n var index = endSelection.getHierarchicalIndexInternal();\n // tslint:disable-next-line:max-line-length\n _this.viewer.owner.searchModule.textSearchResults = _this.viewer.owner.searchModule.textSearch.findAll(pattern, _this.findOption, index);\n _this.results = _this.viewer.owner.searchModule.textSearchResults;\n if (!isNullOrUndefined(_this.results) && !isNullOrUndefined(_this.results.currentSearchResult)) {\n _this.viewer.owner.searchModule.navigate(_this.results.currentSearchResult);\n }\n else {\n _this.messageDiv.style.display = 'block';\n _this.messageDiv.innerHTML = _this.localeValue.getConstant(_this.matchDivReplaceText);\n }\n _this.viewer.owner.findResultsList = [];\n if (!isNullOrUndefined(_this.results) && _this.results.innerList.length > 0) {\n _this.navigateSearchResult();\n }\n else {\n _this.resultsListBlock.innerHTML = '';\n }\n }\n }\n else {\n _this.messageDiv.style.display = 'block';\n _this.messageDiv.innerHTML = _this.localeValue.getConstant(_this.matchDivReplaceText);\n }\n }\n }\n };\n /**\n * Fires on replace all.\n * @private\n */\n this.onReplaceAllButtonClick = function () {\n _this.replaceAll();\n _this.resultsListBlock.style.display = 'none';\n _this.messageDiv.innerHTML = '';\n };\n /**\n * Fires on search icon.\n * @private\n */\n this.searchIconClickInternal = function () {\n // tslint:disable:no-any \n var inputElement = document.getElementById(_this.viewer.owner.containerId + '_option_search_text_box');\n // tslint:enable:no-any\n var text = inputElement.value;\n if (text === '') {\n return;\n }\n if (_this.searchIcon.classList.contains('e-de-op-search-close-icon')) {\n _this.searchIcon.classList.add('e-de-op-search-icon');\n _this.searchIcon.classList.remove('e-de-op-search-close-icon');\n inputElement.value = '';\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('No matches');\n _this.resultContainer.style.display = 'block';\n _this.resultsListBlock.style.display = 'none';\n _this.matchDiv.style.display = 'none';\n _this.occurrenceDiv.style.display = 'none';\n _this.onEnableDisableReplaceButton();\n _this.clearFocusElement();\n _this.resultsListBlock.innerHTML = '';\n _this.clearSearchResultItems();\n _this.viewer.owner.searchModule.clearSearchHighlight();\n _this.viewer.renderVisiblePages();\n return;\n }\n if (_this.searchIcon.classList.contains('e-de-op-search-icon') && text.length >= 1) {\n _this.searchIcon.classList.add('e-de-op-search-close-icon');\n _this.searchIcon.classList.remove('e-de-op-search-icon');\n _this.onEnableDisableReplaceButton();\n }\n _this.clearSearchResultItems();\n _this.viewer.owner.searchModule.clearSearchHighlight();\n var patterns = _this.viewer.owner.searchModule.textSearch.stringToRegex(text, _this.findOption);\n var endSelection = _this.viewer.selection.end;\n var index = endSelection.getHierarchicalIndexInternal();\n _this.results = _this.viewer.owner.searchModule.textSearch.findAll(patterns, _this.findOption, index);\n if (_this.results != null && _this.results.length > 0) {\n _this.navigateSearchResult();\n _this.getMessageDivHeight();\n var resultsContainerHeight = _this.viewer.owner.getDocumentEditorElement().offsetHeight - 215;\n _this.resultsListBlock.style.height = resultsContainerHeight + 'px';\n }\n else {\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('No matches');\n _this.resultContainer.style.display = 'block';\n _this.resultsListBlock.style.display = 'none';\n _this.clearFocusElement();\n _this.resultsListBlock.innerHTML = '';\n }\n };\n /**\n * Fires on getting next results.\n * @private\n */\n this.navigateNextResultButtonClick = function () {\n if (document.getElementById(_this.viewer.owner.containerId + '_list_box_container') != null &&\n document.getElementById(_this.viewer.owner.containerId + '_list_box_container').style.display !== 'none') {\n if (_this.results.currentIndex < _this.results.length - 1) {\n _this.results.currentIndex = _this.results.currentIndex + 1;\n var currentelement = _this.results.innerList[_this.results.currentIndex];\n // tslint:disable-next-line:max-line-length\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('Result') + ' ' + (_this.results.currentIndex + 1) + ' ' + _this.localeValue.getConstant('of') + ' ' + _this.resultsListBlock.children.length;\n for (var i = 0; i < _this.resultsListBlock.children.length; i++) {\n var list = _this.resultsListBlock.children[i];\n if (list.classList.contains('e-de-search-result-hglt')) {\n list.classList.remove('e-de-search-result-hglt');\n list.children[0].classList.remove('e-de-op-search-word-text');\n list.classList.add('e-de-search-result-item');\n }\n }\n var listElement = _this.resultsListBlock.children[_this.results.currentIndex];\n if (listElement.classList.contains('e-de-search-result-item')) {\n listElement.classList.remove('e-de-search-result-item');\n listElement.classList.add('e-de-search-result-hglt');\n listElement.children[0].classList.add('e-de-op-search-word-text');\n _this.scrollToPosition(listElement);\n }\n _this.viewer.owner.searchModule.navigate(currentelement);\n _this.viewer.owner.searchModule.highlight(_this.results);\n }\n else {\n var currentelement = _this.results.innerList[0];\n _this.results.currentIndex = 0;\n // tslint:disable-next-line:max-line-length\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('Result') + ' ' + (_this.results.currentIndex + 1) + ' ' + _this.localeValue.getConstant('of') + ' ' + _this.resultsListBlock.children.length;\n for (var j = 0; j < _this.resultsListBlock.children.length; j++) {\n var lists = _this.resultsListBlock.children[j];\n if (lists.classList.contains('e-de-search-result-hglt')) {\n lists.classList.remove('e-de-search-result-hglt');\n lists.children[0].classList.remove('e-de-op-search-word-text');\n lists.classList.add('e-de-search-result-item');\n }\n }\n var listElementsDiv = _this.resultsListBlock.children[_this.results.currentIndex];\n if (listElementsDiv.classList.contains('e-de-search-result-item')) {\n listElementsDiv.classList.remove('e-de-search-result-item');\n listElementsDiv.classList.add('e-de-search-result-hglt');\n listElementsDiv.children[0].classList.add('e-de-op-search-word-text');\n _this.scrollToPosition(listElementsDiv);\n }\n _this.viewer.owner.searchModule.navigate(currentelement);\n _this.viewer.owner.searchModule.highlight(_this.results);\n }\n _this.focusedIndex = _this.focusedElement.indexOf(_this.navigateToNextResult);\n }\n };\n /**\n * Fires on getting previous results.\n * @private\n */\n this.navigatePreviousResultButtonClick = function () {\n if (document.getElementById(_this.viewer.owner.containerId + '_list_box_container') != null &&\n document.getElementById(_this.viewer.owner.containerId + '_list_box_container').style.display !== 'none') {\n if (_this.results.currentIndex === 0) {\n _this.results.currentIndex = _this.results.length - 1;\n // tslint:disable-next-line:max-line-length\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('Result') + ' ' + (_this.results.length) + ' ' + _this.localeValue.getConstant('of') + ' ' + _this.resultsListBlock.children.length;\n for (var index = 0; index < _this.resultsListBlock.children.length; index++) {\n var list = _this.resultsListBlock.children[index];\n if (list.classList.contains('e-de-search-result-hglt')) {\n list.classList.remove('e-de-search-result-hglt');\n list.children[0].classList.remove('e-de-op-search-word-text');\n list.classList.add('e-de-search-result-item');\n }\n }\n var liElement = _this.resultsListBlock.children[_this.results.currentIndex];\n if (liElement.classList.contains('e-de-search-result-item')) {\n liElement.classList.remove('e-de-search-result-item');\n liElement.classList.add('e-de-search-result-hglt');\n liElement.children[0].classList.add('e-de-op-search-word-text');\n _this.scrollToPosition(liElement);\n }\n var currentelement = _this.results.innerList[_this.results.currentIndex];\n _this.viewer.owner.searchModule.navigate(currentelement);\n _this.viewer.owner.searchModule.highlight(_this.results);\n }\n else {\n // tslint:disable-next-line:max-line-length\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('Result') + ' ' + (_this.results.currentIndex) + ' ' + _this.localeValue.getConstant('of') + ' ' + _this.resultsListBlock.children.length;\n _this.results.currentIndex = _this.results.currentIndex - 1;\n for (var j = 0; j < _this.resultsListBlock.children.length; j++) {\n var list = _this.resultsListBlock.children[j];\n if (list.classList.contains('e-de-search-result-hglt')) {\n list.classList.remove('e-de-search-result-hglt');\n list.children[0].classList.remove('e-de-op-search-word-text');\n list.classList.add('e-de-search-result-item');\n }\n }\n var listElements = _this.resultsListBlock.children[_this.results.currentIndex];\n if (listElements.classList.contains('e-de-search-result-item')) {\n listElements.classList.remove('e-de-search-result-item');\n listElements.classList.add('e-de-search-result-hglt');\n listElements.children[0].classList.add('e-de-op-search-word-text');\n _this.scrollToPosition(listElements);\n }\n var currentelement = _this.results.innerList[_this.results.currentIndex];\n _this.viewer.owner.searchModule.navigate(currentelement);\n _this.viewer.owner.searchModule.highlight(_this.results);\n }\n _this.focusedIndex = _this.focusedElement.indexOf(_this.navigateToPreviousResult);\n }\n };\n /**\n * Fires on key down\n * @param {KeyboardEvent} event - Speficies key down actions.\n * @private\n */\n this.onKeyDown = function (event) {\n var code = event.which || event.keyCode;\n if (code === 13 && event.keyCode !== 9 && event.keyCode !== 40) {\n event.preventDefault();\n _this.findDiv.style.height = '';\n _this.onKeyDownInternal();\n }\n else if (code === 8 && (_this.searchInput.value.length === 0)) {\n _this.resultContainer.style.display = 'block';\n }\n else if (event.keyCode !== 9 && event.keyCode !== 40 && event.keyCode !== 27) {\n _this.viewer.owner.searchModule.clearSearchHighlight();\n _this.clearSearchResultItems();\n _this.viewer.renderVisiblePages();\n _this.resultsListBlock.style.display = 'none';\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('No matches');\n _this.resultContainer.style.display = 'none';\n _this.clearFocusElement();\n _this.resultsListBlock.innerHTML = '';\n if (_this.searchIcon.classList.contains('e-de-op-search-close-icon')) {\n _this.searchIcon.classList.add('e-de-op-search-icon');\n _this.searchIcon.classList.remove('e-de-op-search-close-icon');\n }\n }\n else if (code === 27 && event.keyCode === 27) {\n _this.showHideOptionsPane(false);\n }\n };\n /**\n * Close the optios pane.\n * @private\n */\n this.close = function () {\n _this.clearFocusElement();\n _this.showHideOptionsPane(false);\n _this.resultsListBlock.innerHTML = '';\n _this.focusedIndex = 1;\n _this.isOptionsPane = true;\n };\n /**\n * Fires on results list block.\n * @param {MouseEvent} args - Specifies which list was clicked.\n * @private\n */\n this.resultListBlockClick = function (args) {\n var currentlist = args.target;\n var element = _this.resultsListBlock.children;\n var index = 0;\n for (var i = 0; i < element.length; i++) {\n var list_1 = element[i];\n if (list_1.classList.contains('e-de-search-result-hglt')) {\n list_1.classList.remove('e-de-search-result-hglt');\n list_1.children[0].classList.remove('e-de-op-search-word-text');\n list_1.classList.add('e-de-search-result-item');\n }\n }\n var list;\n for (var i = 0; i < element.length; i++) {\n if (currentlist === element[i]) {\n index = i;\n list = element[i];\n if (list.classList.contains('e-de-search-result-item')) {\n list.classList.remove('e-de-search-result-item');\n list.classList.add('e-de-search-result-hglt');\n list.children[0].classList.add('e-de-op-search-word-text');\n _this.focusedIndex = _this.focusedElement.indexOf(list);\n }\n }\n }\n var currentelement = _this.results.innerList[index];\n _this.results.currentIndex = index;\n // tslint:disable-next-line:max-line-length\n _this.messageDiv.innerHTML = _this.localeValue.getConstant('Result') + ' ' + (index + 1) + ' ' + _this.localeValue.getConstant('of') + ' ' + _this.resultsListBlock.children.length;\n _this.viewer.owner.searchModule.navigate(currentelement);\n _this.viewer.owner.searchModule.highlight(_this.results);\n list.focus();\n };\n this.viewer = layoutViewer;\n }\n /**\n * Get the module name.\n */\n OptionsPane.prototype.getModuleName = function () {\n return 'OptionsPane';\n };\n /**\n * Initialize the options pane.\n * @param {L10n} localeValue - Specifies the localization based on culture.\n * @private\n */\n // tslint:disable:max-func-body-length\n OptionsPane.prototype.initOptionsPane = function (localeValue) {\n var viewer = this.viewer;\n this.localeValue = localeValue;\n this.optionsPane = createElement('div', { className: 'e-de-op', styles: 'display:none;' });\n this.optionsPane.addEventListener('keydown', this.onKeyDownOnOptionPane);\n this.searchDiv = createElement('div', {\n className: this.viewer.owner.containerId + '_searchDiv e-de-op-header',\n innerHTML: localeValue.getConstant(this.searchText)\n });\n this.optionsPane.appendChild(this.searchDiv);\n // tslint:disable-next-line:max-line-length\n this.closeButton = createElement('button', { className: 'e-de-op-close-button e-de-op-icon-btn e-btn e-flat e-icon-btn', id: 'close' });\n this.optionsPane.appendChild(this.closeButton);\n var closeSpan = createElement('span', { className: 'e-de-op-close-icon e-btn-icon e-icons' });\n this.closeButton.appendChild(closeSpan);\n this.focusedElement.push(this.closeButton);\n this.findTab = createElement('div', { id: this.viewer.owner.containerId + '_findTabDiv', className: 'e-de-op-tab' });\n this.optionsPane.appendChild(this.findTab);\n var tabHeader = createElement('div', { className: 'e-tab-header' });\n this.findTab.appendChild(tabHeader);\n this.findTabButton = createElement('div', { innerHTML: localeValue.getConstant(this.findPaneText) });\n this.focusedElement.push(this.findTabButtonHeader);\n tabHeader.appendChild(this.findTabButton);\n this.replaceTabButton = createElement('div', { innerHTML: localeValue.getConstant(this.replacePaneText) });\n this.focusedElement.push(this.replaceTabButtonHeader);\n tabHeader.appendChild(this.replaceTabButton);\n var tabContent = createElement('div', { className: 'e-content' });\n var findTabContent = createElement('div', { id: 'findTabContent' });\n tabContent.appendChild(findTabContent);\n this.findTabContentDiv = createElement('div', { className: 'e-de-search-tab-content' });\n this.searchTextBoxContainer = createElement('div', { className: 'e-input-group e-de-op-input-group' });\n this.findTabContentDiv.appendChild(this.searchTextBoxContainer);\n // tslint:disable-next-line:max-line-length\n this.searchInput = createElement('input', { className: 'e-input e-de-search-input', id: this.viewer.owner.containerId + '_option_search_text_box', attrs: { placeholder: 'Search for' }, styles: 'font-size:14px;' });\n this.searchTextBoxContainer.appendChild(this.searchInput);\n this.searchIcon = createElement('span', {\n className: 'e-de-op-icon e-de-op-search-icon e-input-group-icon e-icon',\n id: this.viewer.owner.containerId + '_search-icon'\n });\n this.searchIcon.tabIndex = 0;\n this.searchTextBoxContainer.appendChild(this.searchIcon);\n this.focusedElement.push(this.searchIcon);\n // tslint:disable-next-line:max-line-length\n this.navigateToPreviousResult = createElement('span', { className: 'e-de-op-icon e-de-op-nav-btn e-arrow-up e-spin-up e-btn-icon e-icon e-input-group-icon' });\n this.navigateToPreviousResult.tabIndex = 0;\n this.searchTextBoxContainer.appendChild(this.navigateToPreviousResult);\n this.focusedElement.push(this.navigateToPreviousResult);\n // tslint:disable-next-line:max-line-length\n this.navigateToNextResult = createElement('span', { className: 'e-de-op-icon e-de-op-nav-btn e-arrow-down e-spin-down e-btn-icon e-icon e-input-group-icon' });\n this.navigateToNextResult.tabIndex = 0;\n this.searchTextBoxContainer.appendChild(this.navigateToNextResult);\n this.focusedElement.push(this.navigateToNextResult);\n var div = createElement('div', { className: 'e-de-op-more-less' });\n this.matchInput = createElement('input', {\n attrs: { type: 'checkbox' },\n id: this.viewer.owner.containerId + '_matchCase'\n });\n div.appendChild(this.matchInput);\n this.matchCase = new CheckBox({ label: 'Match case', checked: false, change: this.matchChange });\n this.matchCase.appendTo(this.matchInput);\n this.focusedElement.push(this.matchInput);\n this.matchInput.tabIndex = 0;\n this.wholeInput = createElement('input', {\n attrs: { type: 'checkbox' },\n id: this.viewer.owner.containerId + '_wholeWord',\n });\n div.appendChild(this.wholeInput);\n this.wholeWord = new CheckBox({ label: 'Whole words', checked: false, change: this.wholeWordsChange });\n this.wholeWord.appendTo(this.wholeInput);\n this.focusedElement.push(this.wholeInput);\n this.wholeInput.tabIndex = 0;\n this.findTabContentDiv.appendChild(div);\n var replaceTabContent = createElement('div');\n tabContent.appendChild(replaceTabContent);\n this.replaceTabContentDiv = createElement('div', { className: 'e-de-op-replacetabcontentdiv', styles: 'display:none;' });\n tabContent.appendChild(this.replaceTabContentDiv);\n this.findTabContentDiv.appendChild(this.replaceTabContentDiv);\n this.createReplacePane();\n this.findDiv = createElement('div', { className: 'findDiv', styles: 'height:250px;display:block;' });\n findTabContent.appendChild(this.findTabContentDiv);\n this.resultContainer = createElement('div', { styles: 'width:85%;display:block;', className: 'e-de-op-result-container' });\n this.findDiv.appendChild(this.resultContainer);\n // tslint:disable-next-line:max-line-length\n this.messageDiv = createElement('div', { className: this.viewer.owner.containerId + '_messageDiv e-de-op-msg', innerHTML: this.localeValue.getConstant(this.messageDivText), id: this.viewer.owner.containerId + '_search_status' });\n this.resultContainer.appendChild(this.messageDiv);\n // tslint:disable-next-line:max-line-length\n this.resultsListBlock = createElement('div', { id: this.viewer.owner.containerId + '_list_box_container', styles: 'display:none;width:270px;list-style:none;padding-right:5px;overflow:auto;', className: 'e-de-result-list-block' });\n this.findDiv.appendChild(this.resultsListBlock);\n this.findTabContentDiv.appendChild(this.findDiv);\n this.findTab.appendChild(tabContent);\n this.tabInstance = new Tab({ selected: this.selectedTabItem });\n this.tabInstance.appendTo(this.findTab);\n var findHeader = this.tabInstance.element.getElementsByClassName('e-item e-toolbar-item')[0];\n this.findTabButtonHeader = findHeader.getElementsByClassName('e-tab-wrap')[0];\n this.findTabButtonHeader.classList.add('e-de-op-find-tab-header');\n this.findTabButtonHeader.tabIndex = 0;\n var replaceHeader = this.tabInstance.element.getElementsByClassName('e-item e-toolbar-item')[1];\n this.replaceTabButtonHeader = replaceHeader.getElementsByClassName('e-tab-wrap')[0];\n this.replaceTabButtonHeader.classList.add('e-de-op-replace-tab-header');\n this.replaceTabButtonHeader.tabIndex = 0;\n this.onWireEvents();\n };\n /**\n * Create replace pane instances.\n */\n OptionsPane.prototype.createReplacePane = function () {\n this.replaceDiv = createElement('div');\n this.replaceTabContentDiv.appendChild(this.replaceDiv);\n this.replaceWith = createElement('input', {\n className: 'e-de-op-replacewith e-input', styles: 'font-size:14px;',\n attrs: { placeholder: 'Replace with' }\n });\n this.replaceDiv.appendChild(this.replaceWith);\n var replaceButtonDiv = createElement('div', { styles: 'text-align:right;', className: 'e-de-op-dlg-footer' });\n this.replaceDiv.appendChild(replaceButtonDiv);\n this.replaceButton = createElement('button', {\n className: 'e-control e-btn e-flat e-replace',\n styles: 'font-size:12px;margin-right:10px;',\n innerHTML: this.localeValue.getConstant(this.replaceButtonText)\n });\n replaceButtonDiv.appendChild(this.replaceButton);\n this.replaceAllButton = createElement('button', {\n className: 'e-control e-btn e-flat e-replaceall',\n styles: 'font-size:12px;',\n innerHTML: this.localeValue.getConstant(this.replaceAllButtonText)\n });\n replaceButtonDiv.appendChild(this.replaceAllButton);\n this.matchDiv = createElement('div', { styles: 'display:none;padding-top:10px;' });\n this.replaceDiv.appendChild(this.matchDiv);\n var emptyDiv6 = createElement('div', { className: 'e-de-op-search-replacediv' });\n this.replaceDiv.appendChild(emptyDiv6);\n this.occurrenceDiv = createElement('div', { styles: 'display:none;' });\n this.replaceDiv.appendChild(this.occurrenceDiv);\n };\n OptionsPane.prototype.navigateSearchResult = function () {\n this.viewer.owner.searchModule.navigate(this.results.innerList[this.results.currentIndex]);\n this.viewer.owner.searchModule.highlight(this.results);\n this.viewer.owner.searchModule.addFindResultView(this.results);\n this.resultsListBlock.style.display = 'block';\n this.resultContainer.style.display = 'block';\n var lists = this.viewer.owner.findResultsList;\n var text = '';\n for (var i = 0; i < lists.length; i++) {\n text += lists[i];\n }\n this.clearFocusElement();\n this.resultsListBlock.innerHTML = text;\n for (var i = 0; i < this.resultsListBlock.children.length; i++) {\n this.focusedElement.push(this.resultsListBlock.children[i]);\n }\n var currentIndexValue = this.results.currentIndex;\n // tslint:disable-next-line:max-line-length\n this.messageDiv.innerHTML = this.localeValue.getConstant('Result') + ' ' + (currentIndexValue + 1) + ' ' + this.localeValue.getConstant('of') + ' ' + this.resultsListBlock.children.length;\n var listElement = this.resultsListBlock.children[currentIndexValue];\n if (listElement.classList.contains('e-de-search-result-item')) {\n listElement.classList.remove('e-de-search-result-item');\n listElement.classList.add('e-de-search-result-hglt');\n listElement.children[0].classList.add('e-de-op-search-word-text');\n this.scrollToPosition(listElement);\n }\n };\n /**\n * Fires on key down actions done.\n * @private\n */\n OptionsPane.prototype.onKeyDownInternal = function () {\n // tslint:disable-next-line:max-line-length\n var inputElement = document.getElementById(this.viewer.owner.containerId + '_option_search_text_box');\n inputElement.blur();\n var text = inputElement.value;\n if (text === '') {\n return;\n }\n if (text.length >= 1 && this.searchIcon.classList.contains('e-de-op-search-icon')) {\n this.searchIcon.classList.add('e-de-op-search-close-icon');\n this.searchIcon.classList.remove('e-de-op-search-icon');\n }\n var resultsContainerHeight = this.viewer.owner.getDocumentEditorElement().offsetHeight - 215;\n this.clearSearchResultItems();\n this.viewer.owner.searchModule.clearSearchHighlight();\n var pattern = this.viewer.owner.searchModule.textSearch.stringToRegex(text, this.findOption);\n var endSelection = this.viewer.selection.end;\n var index = endSelection.getHierarchicalIndexInternal();\n this.results = this.viewer.owner.searchModule.textSearch.findAll(pattern, this.findOption, index);\n var results = this.results;\n if (isNullOrUndefined(results)) {\n this.viewer.renderVisiblePages();\n }\n if (results != null && results.length > 0) {\n if ((this.focusedElement.indexOf(this.navigateToPreviousResult) === -1) && this.isOptionsPane) {\n this.focusedElement.push(this.navigateToPreviousResult);\n }\n if ((this.focusedElement.indexOf(this.navigateToNextResult) === -1) && this.isOptionsPane) {\n this.focusedElement.push(this.navigateToNextResult);\n }\n this.viewer.owner.searchModule.navigate(this.results.innerList[this.results.currentIndex]);\n this.viewer.owner.searchModule.highlight(results);\n this.viewer.owner.searchModule.addFindResultView(results);\n // if (this.isOptionsPane) {\n this.resultsListBlock.style.display = 'block';\n this.resultsListBlock.style.height = resultsContainerHeight + 'px';\n this.resultContainer.style.display = 'block';\n var list = this.viewer.owner.findResultsList;\n var text_1 = '';\n this.clearFocusElement();\n this.resultsListBlock.innerHTML = '';\n for (var i = 0; i < list.length; i++) {\n text_1 += list[i];\n }\n this.resultsListBlock.innerHTML = text_1;\n for (var i = 0; i < this.resultsListBlock.children.length; i++) {\n this.focusedElement.push(this.resultsListBlock.children[i]);\n }\n var lists = this.resultsListBlock.children;\n var currentIndex = this.results.currentIndex;\n // tslint:disable-next-line:max-line-length\n this.messageDiv.innerHTML = this.localeValue.getConstant('Result') + ' ' + (currentIndex + 1) + ' ' + this.localeValue.getConstant('of') + ' ' + this.resultsListBlock.children.length;\n var listElement = this.resultsListBlock.children[currentIndex];\n if (listElement.classList.contains('e-de-search-result-item')) {\n listElement.classList.remove('e-de-search-result-item');\n listElement.classList.add('e-de-search-result-hglt');\n listElement.children[0].classList.add('e-de-op-search-word-text');\n }\n this.navigateToNextResult.focus();\n this.focusedIndex = 6;\n this.getMessageDivHeight();\n // } else {\n //this.focusedIndex = 4;\n // }\n }\n else {\n this.messageDiv.innerHTML = this.localeValue.getConstant('No matches');\n this.resultContainer.style.display = 'block';\n this.resultsListBlock.style.display = 'none';\n this.clearFocusElement();\n this.resultsListBlock.innerHTML = '';\n }\n };\n OptionsPane.prototype.getMessageDivHeight = function () {\n if (!this.isOptionsPane && this.messageDiv.classList.contains('e-de-op-msg')) {\n this.messageDiv.classList.add('e-de-op-replace-messagediv');\n this.messageDiv.classList.remove('e-de-op-msg');\n }\n else if (this.isOptionsPane && this.messageDiv.classList.contains('e-de-op-replace-messagediv')) {\n this.messageDiv.classList.add('e-de-op-msg');\n this.messageDiv.classList.remove('e-de-op-replace-messagediv');\n }\n };\n /**\n * Replace all.\n * @private\n */\n OptionsPane.prototype.replaceAll = function () {\n var optionsPane = this.optionsPane;\n var findText = this.searchInput.value;\n var replaceText = this.replaceWith.value;\n if (findText !== '' && !isNullOrUndefined(findText)) {\n var pattern = this.viewer.owner.searchModule.textSearch.stringToRegex(findText, this.findOption);\n var endSelection = this.viewer.selection.end;\n var index = endSelection.getHierarchicalIndexInternal();\n var results = this.viewer.owner.searchModule.textSearch.findAll(pattern, this.findOption, index);\n var replace = isNullOrUndefined(replaceText) ? '' : replaceText;\n var count = isNullOrUndefined(results) ? 0 : results.length;\n this.viewer.owner.searchModule.replaceAll(replace, results);\n this.matchDiv.style.display = 'block';\n this.matchDiv.innerHTML = this.localeValue.getConstant('All Done') + '!';\n this.occurrenceDiv.style.display = 'block';\n // tslint:disable-next-line:max-line-length\n this.occurrenceDiv.innerHTML = this.localeValue.getConstant('We replaced all') + ' ' + count + ' ' + this.localeValue.getConstant('instances') + ' ' + this.localeValue.getConstant('of') + ' \"' + findText + '\" ' + this.localeValue.getConstant('with') + ' \"' + replaceText + '\" ';\n }\n };\n /**\n * Scrolls to position.\n * @param {HTMLElement} list - Specifies the list element.\n * @private\n */\n OptionsPane.prototype.scrollToPosition = function (list) {\n var rect = list.getBoundingClientRect();\n var top;\n if (rect.top > 0) {\n top = rect.top - list.parentElement.getBoundingClientRect().top;\n if ((list.parentElement.offsetHeight - top) <= list.offsetHeight) {\n if (Math.ceil(top + list.offsetHeight) === list.parentElement.scrollHeight) {\n list.parentElement.scrollTop = top;\n }\n list.parentElement.scrollTop = list.parentElement.scrollTop + (list.parentElement.offsetHeight / 100) * 30;\n }\n else if (top < 0) {\n list.parentElement.scrollTop = list.parentElement.scrollTop - (list.parentElement.offsetHeight / 100) * 30;\n }\n }\n else {\n list.parentElement.scrollTop = 0;\n }\n };\n /**\n * Clear the focus elements.\n * @private\n */\n OptionsPane.prototype.clearFocusElement = function () {\n for (var i = 0; i < this.resultsListBlock.children.length; i++) {\n var index = this.focusedElement.indexOf(this.resultsListBlock.children[i]);\n if (index !== -1) {\n this.focusedElement.splice(index, 1);\n }\n }\n this.focusedIndex = 0;\n };\n /**\n * Show or hide option pane based on boolean value.\n * @param {boolean} show - Specifies showing or hiding the options pane.\n * @private\n */\n OptionsPane.prototype.showHideOptionsPane = function (show) {\n if (!isNullOrUndefined(this.viewer.owner.selectionModule)) {\n if (show) {\n this.localeValue = new L10n('documenteditor', this.viewer.owner.defaultLocale);\n this.localeValue.setLocale(this.viewer.owner.locale);\n setCulture(this.viewer.owner.locale);\n if (isNullOrUndefined(this.optionsPane)) {\n this.initOptionsPane(this.localeValue);\n //Add Option Pane\n var element = document.getElementById(this.viewer.owner.element.id);\n var optionPaneContainer = document.createElement('div');\n optionPaneContainer.className = 'e-documenteditor-optionspane';\n optionPaneContainer.setAttribute('style', 'display:inline-flex');\n optionPaneContainer.appendChild(this.viewer.owner.optionsPaneModule.optionsPane);\n this.viewer.owner.getDocumentEditorElement().appendChild(optionPaneContainer);\n optionPaneContainer.appendChild(this.viewer.viewerContainer);\n element.appendChild(optionPaneContainer);\n }\n this.optionsPane.style.display = 'block';\n if (this.viewer.owner.isReadOnlyMode) {\n this.tabInstance.hideTab(1);\n }\n else {\n this.tabInstance.hideTab(1, false);\n }\n if (this.isReplace && !this.viewer.owner.isReadOnlyMode) {\n this.tabInstance.select(1);\n this.isReplace = false;\n this.isOptionsPane = false;\n }\n else {\n this.tabInstance.select(0);\n }\n this.searchDiv.innerHTML = this.localeValue.getConstant(this.searchText);\n this.isOptionsPaneShow = true;\n // tslint:disable-next-line:max-line-length\n var textBox = document.getElementById(this.viewer.owner.getDocumentEditorElement().id + '_option_search_text_box');\n var selectedText = this.viewer.owner.selection.text;\n if (!isNullOrUndefined(selectedText)) {\n var char = ['\\v', '\\r'];\n var index = HelperMethods.indexOfAny(selectedText, char);\n selectedText = index < 0 ? selectedText : selectedText.substring(0, index);\n }\n textBox.value = selectedText;\n textBox.select();\n this.messageDiv.innerHTML = '';\n if (this.searchIcon.classList.contains('e-de-op-search-close-icon')) {\n this.searchIcon.classList.add('e-de-op-search-icon');\n this.searchIcon.classList.remove('e-de-op-search-close-icon');\n }\n this.viewer.selection.caret.style.display = 'none';\n this.focusedIndex = 3;\n this.focusedElement = [];\n if (this.isOptionsPane) {\n // tslint:disable-next-line:max-line-length\n this.focusedElement.push(this.closeButton, this.findTabButtonHeader, this.replaceTabButtonHeader, this.searchInput, this.searchIcon, this.navigateToPreviousResult, this.navigateToNextResult, this.matchInput, this.wholeInput);\n }\n else {\n // tslint:disable-next-line:max-line-length\n this.focusedElement.push(this.closeButton, this.findTabButtonHeader, this.replaceTabButtonHeader, this.searchInput, this.searchIcon, this.navigateToPreviousResult, this.navigateToNextResult, this.matchInput, this.wholeInput, this.replaceWith, this.replaceButton, this.replaceAllButton);\n }\n this.viewer.updateViewerSize();\n }\n else {\n if (!isNullOrUndefined(this.optionsPane)) {\n this.clearSearchResultItems();\n this.viewer.owner.searchModule.clearSearchHighlight();\n this.isOptionsPaneShow = false;\n var resultListBox = document.getElementById(this.viewer.owner.containerId + '_list_box_container');\n var message = document.getElementById(this.viewer.owner.containerId + '_search_status');\n if (!isNullOrUndefined(resultListBox) && !isNullOrUndefined(message)) {\n resultListBox.style.display = 'none';\n this.clearFocusElement();\n resultListBox.innerHTML = '';\n message.innerHTML = this.localeValue.getConstant('No matches');\n }\n }\n this.viewer.updateViewerSize();\n if (!isNullOrUndefined(this.optionsPane)) {\n if (this.optionsPane.style.display !== 'none') {\n this.viewer.selection.updateCaretPosition();\n this.optionsPane.style.display = 'none';\n }\n }\n this.viewer.updateFocus();\n this.viewer.selection.caret.style.display = 'block';\n }\n }\n };\n /**\n * Clears search results.\n * @private\n */\n OptionsPane.prototype.clearSearchResultItems = function () {\n if (!isNullOrUndefined(this.viewer.owner.findResultsList)) {\n this.viewer.owner.findResultsList = [];\n }\n };\n /**\n * Dispose the internal objects which are maintained.\n * @private\n */\n OptionsPane.prototype.destroy = function () {\n if (this.optionsPane) {\n this.optionsPane.innerHTML = '';\n this.optionsPane = undefined;\n }\n if (this.resultsListBlock) {\n this.resultsListBlock.innerHTML = '';\n this.resultsListBlock = undefined;\n }\n if (this.messageDiv) {\n this.messageDiv.innerHTML = '';\n this.messageDiv = undefined;\n }\n if (this.resultContainer) {\n this.resultContainer.innerHTML = '';\n }\n this.resultContainer = undefined;\n if (this.searchInput) {\n this.searchInput.value = '';\n this.searchInput = undefined;\n }\n if (this.searchDiv) {\n this.searchDiv.innerHTML = '';\n this.searchDiv = undefined;\n }\n if (this.searchTextBoxContainer) {\n this.searchTextBoxContainer.innerHTML = '';\n this.searchTextBoxContainer = undefined;\n }\n if (this.replaceWith) {\n this.replaceWith.innerHTML = '';\n this.replaceWith = undefined;\n }\n if (this.findDiv) {\n this.findDiv.innerHTML = '';\n this.findDiv = undefined;\n }\n if (this.replaceButton) {\n this.replaceButton.innerHTML = '';\n this.replaceButton = undefined;\n }\n if (this.replaceAllButton) {\n this.replaceAllButton.innerHTML = '';\n this.replaceAllButton = undefined;\n }\n if (this.matchInput) {\n this.matchInput.innerHTML = '';\n this.matchCase = undefined;\n }\n if (this.wholeInput) {\n this.wholeInput.innerHTML = '';\n this.wholeWord = undefined;\n }\n // if (this.regularInput) {\n // this.regularInput.innerHTML = '';\n // this.regular = undefined;\n // }\n if (!isNullOrUndefined(this.results)) {\n this.results.destroy();\n }\n if (this.focusedElement) {\n this.focusedElement = [];\n }\n this.focusedElement = undefined;\n this.destroyInternal();\n };\n /**\n * Dispose the internal objects which are maintained.\n */\n OptionsPane.prototype.destroyInternal = function () {\n if (this.searchText) {\n this.searchText = undefined;\n }\n if (this.resultsText) {\n this.resultsText = undefined;\n }\n if (this.messageDivText) {\n this.messageDivText = undefined;\n }\n if (this.replaceButtonText) {\n this.replaceButtonText = undefined;\n }\n if (this.replaceAllButtonText) {\n this.replaceAllButtonText = undefined;\n }\n };\n return OptionsPane;\n}());\nexport { OptionsPane };\n","import { TableWidget } from '../index';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Point, HelperMethods } from './editor-helper';\n/**\n * @private\n */\nvar TableResizer = /** @class */ (function () {\n /**\n * @private\n */\n function TableResizer(node) {\n this.resizeNode = 0;\n this.resizerPosition = 0;\n this.currentResizingTable = undefined;\n this.owner = node;\n this.startingPoint = new Point(0, 0);\n }\n Object.defineProperty(TableResizer.prototype, \"viewer\", {\n /**\n * @private\n */\n get: function () {\n return this.owner.viewer;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets module name.\n */\n TableResizer.prototype.getModuleName = function () {\n return 'TableResizer';\n };\n /**\n * @private\n */\n TableResizer.prototype.updateResizingHistory = function (touchPoint) {\n if (this.owner.editorHistory) {\n this.owner.editorHistory.updateResizingHistory(touchPoint, this);\n }\n this.viewer.isRowOrCellResizing = false;\n this.resizerPosition = -1;\n };\n TableResizer.prototype.handleResize = function (point) {\n this.owner.viewer.isRowOrCellResizing = true;\n this.startingPoint.x = point.x;\n this.startingPoint.y = point.y;\n //Initialize resizing history.\n this.owner.editorHistory.initResizingHistory(point, this);\n };\n //Table Resizing implementation starts\n /**\n * @private\n */\n TableResizer.prototype.isInRowResizerArea = function (touchPoint) {\n var position = this.getRowReSizerPosition(undefined, touchPoint);\n if (position === -1) {\n return false;\n }\n else {\n this.resizeNode = 1;\n this.resizerPosition = position;\n return true;\n }\n };\n TableResizer.prototype.isInCellResizerArea = function (touchPoint) {\n var position = this.getCellReSizerPosition(touchPoint);\n if (position === -1) {\n return false;\n }\n else {\n this.resizeNode = 0;\n this.resizerPosition = position;\n return true;\n }\n };\n /**\n * Gets cell resizer position.\n * @param {Point} point\n * @private\n */\n TableResizer.prototype.getCellReSizerPosition = function (touchPoint) {\n var position = -1;\n var resizerBoundaryWidth = 2;\n var tableWidget = this.getTableWidget(touchPoint);\n var cellWidget = this.getTableCellWidget(touchPoint);\n var cellSpacing = isNullOrUndefined(tableWidget) ? 0 : tableWidget.tableFormat.cellSpacing;\n if (tableWidget && cellSpacing > 0) {\n this.currentResizingTable = tableWidget;\n // tslint:disable-next-line:max-line-length\n if (this.viewer.isInsideRect(tableWidget.x - HelperMethods.convertPointToPixel(tableWidget.leftBorderWidth) - 0.25, tableWidget.y, HelperMethods.convertPointToPixel(tableWidget.leftBorderWidth) + 0.5, tableWidget.height, touchPoint)) {\n return position = 0;\n }\n var startingPointX = tableWidget.x;\n for (var i = 0; i < tableWidget.tableHolder.columns.length; i++) {\n var preferredWidth = HelperMethods.convertPointToPixel(tableWidget.tableHolder.columns[i].preferredWidth);\n // tslint:disable-next-line:max-line-length\n if ((this.viewer.isInsideRect(startingPointX - 1, tableWidget.y, tableWidget.leftBorderWidth + resizerBoundaryWidth, tableWidget.height, touchPoint))) {\n return position = i > 0 ? i : 0;\n // tslint:disable-next-line:max-line-length\n }\n else if (i > 0 && (this.viewer.isInsideRect(startingPointX + preferredWidth - resizerBoundaryWidth / 2, tableWidget.y, resizerBoundaryWidth, tableWidget.height, touchPoint))) {\n return position = (i + 1);\n }\n startingPointX = startingPointX + preferredWidth;\n }\n }\n else {\n if (!isNullOrUndefined(cellWidget)) {\n this.currentResizingTable = cellWidget.ownerTable;\n // tslint:disable-next-line:max-line-length\n if (this.viewer.isInsideRect(cellWidget.x - cellWidget.margin.left - resizerBoundaryWidth / 2, cellWidget.y - cellWidget.margin.top, resizerBoundaryWidth, cellWidget.height, touchPoint)) {\n return position = cellWidget.columnIndex;\n // tslint:disable-next-line:max-line-length\n }\n else if (isNullOrUndefined(cellWidget.nextRenderedWidget)\n && this.viewer.isInsideRect(cellWidget.x + cellWidget.margin.right + cellWidget.width - resizerBoundaryWidth / 2, cellWidget.y - cellWidget.margin.top, resizerBoundaryWidth, cellWidget.height, touchPoint)) {\n return position = (cellWidget.columnIndex + cellWidget.cellFormat.columnSpan);\n }\n else if (cellWidget.childWidgets.length > 0) {\n return this.getCellReSizerPositionInternal(cellWidget, touchPoint); // Gets the nested table resizer position.\n }\n }\n }\n return position;\n };\n /**\n * Gets cell resizer position.\n * @param {TableCellWidget} cellWidget\n * @param {Point} touchPoint\n */\n TableResizer.prototype.getCellReSizerPositionInternal = function (cellWidget, touchPoint) {\n var position = -1;\n var childTableWidget = this.getTableWidgetFromWidget(touchPoint, cellWidget);\n var childCellWidget = undefined;\n if (!isNullOrUndefined(childTableWidget) && childTableWidget.tableFormat.cellSpacing > 0) {\n this.currentResizingTable = childTableWidget;\n // tslint:disable-next-line:max-line-length\n if (this.viewer.isInsideRect(childTableWidget.x - childTableWidget.leftBorderWidth - 0.25, childTableWidget.y, childTableWidget.leftBorderWidth + 0.5, childTableWidget.height, touchPoint)) {\n return position = 0;\n }\n var startingPointX = childTableWidget.x;\n for (var i = 0; i < childTableWidget.tableHolder.columns.length; i++) {\n // tslint:disable-next-line:max-line-length\n var preferredWidth = HelperMethods.convertPointToPixel(childTableWidget.tableHolder.columns[i].preferredWidth);\n // tslint:disable-next-line:max-line-length\n if ((this.viewer.isInsideRect(startingPointX - 1, childTableWidget.y, childTableWidget.leftBorderWidth + 2, childTableWidget.height, touchPoint))) {\n return position = i > 0 ? i : 0;\n // tslint:disable-next-line:max-line-length\n }\n else if (i > 0 && (this.viewer.isInsideRect(startingPointX + preferredWidth - 1, childTableWidget.y, 2, childTableWidget.height, touchPoint))) {\n return position = (i + 1);\n }\n startingPointX = startingPointX + preferredWidth;\n }\n }\n else {\n if (!isNullOrUndefined(childTableWidget)) {\n childCellWidget = childTableWidget.getTableCellWidget(touchPoint);\n }\n if (!isNullOrUndefined(childCellWidget)) {\n this.currentResizingTable = childCellWidget.ownerTable;\n // tslint:disable-next-line:max-line-length\n if (this.viewer.isInsideRect(childCellWidget.x - childCellWidget.margin.left - 1, childCellWidget.y - childCellWidget.margin.top, 2, childCellWidget.height, touchPoint)) {\n return position = childCellWidget.columnIndex;\n }\n else if (isNullOrUndefined(childCellWidget.nextRenderedWidget)\n // tslint:disable-next-line:max-line-length\n && this.viewer.isInsideRect(childCellWidget.x + childCellWidget.margin.right + childCellWidget.width - 1, childCellWidget.y - childCellWidget.margin.top, 2, childCellWidget.height, touchPoint)) {\n return position = (childCellWidget.columnIndex + childCellWidget.cellFormat.columnSpan);\n }\n else if (childCellWidget.childWidgets.length > 0) {\n return this.getCellReSizerPositionInternal(childCellWidget, touchPoint);\n }\n }\n }\n return position;\n };\n TableResizer.prototype.getRowReSizerPosition = function (widget, touchPoint) {\n var tableWidget = undefined;\n var cellWidget = undefined;\n if (isNullOrUndefined(widget)) {\n tableWidget = this.getTableWidget(touchPoint);\n cellWidget = this.getTableCellWidget(touchPoint);\n }\n else {\n tableWidget = this.getTableWidgetFromWidget(touchPoint, widget);\n }\n var cellSpacing = isNullOrUndefined(tableWidget) ? 0 : tableWidget.tableFormat.cellSpacing;\n if (tableWidget && cellSpacing > 0) {\n this.currentResizingTable = tableWidget;\n // tslint:disable-next-line:max-line-length\n if (this.owner.viewer.isInsideRect(tableWidget.x, tableWidget.y + tableWidget.height - cellSpacing, this.getActualWidth(tableWidget.lastChild), (isNullOrUndefined(tableWidget.nextSplitWidget) ? tableWidget.bottomBorderWidth + cellSpacing : 0), touchPoint)) {\n return tableWidget.lastChild.rowIndex;\n }\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n //Need to consider for splitted widgets\n var rowWidget = tableWidget.childWidgets[i];\n if (tableWidget.childWidgets.indexOf(rowWidget) > -1\n // tslint:disable-next-line:max-line-length\n && (this.owner.viewer.isInsideRect(rowWidget.x, rowWidget.y + rowWidget.height + cellSpacing / 2, this.getActualWidth(rowWidget), cellSpacing / 2, touchPoint))) {\n return rowWidget.rowIndex;\n }\n }\n }\n else {\n if (tableWidget && cellWidget) {\n cellWidget = this.getTableCellWidget(touchPoint);\n }\n if (cellWidget) {\n var rowWidget = cellWidget.containerWidget;\n var height = 0;\n if (rowWidget.rowIndex === rowWidget.ownerTable.childWidgets.length - 1) {\n height = rowWidget.bottomBorderWidth + 2;\n }\n else {\n height = rowWidget.nextRenderedWidget.topBorderWidth + 2;\n }\n // tslint:disable-next-line:max-line-length\n if (this.owner.viewer.isInsideRect(rowWidget.x, rowWidget.y + rowWidget.height - height, rowWidget.width, height * 2, touchPoint)) {\n this.currentResizingTable = rowWidget.ownerTable;\n return rowWidget.rowIndex;\n }\n else {\n if (cellWidget.childWidgets.length > 0) {\n return this.getRowReSizerPosition(cellWidget, touchPoint);\n }\n }\n }\n }\n return -1;\n };\n /**\n * To handle Table Row and cell resize\n * @param touchPoint\n * @private\n */\n TableResizer.prototype.handleResizing = function (touchPoint) {\n var dragValue = 0;\n if (this.resizeNode === 0) {\n dragValue = touchPoint.x - this.startingPoint.x;\n this.resizeTableCellColumn(dragValue);\n }\n else {\n dragValue = touchPoint.y - this.startingPoint.y;\n this.resizeTableRow(dragValue);\n }\n };\n TableResizer.prototype.resizeTableRow = function (dragValue) {\n var table = this.currentResizingTable;\n if (isNullOrUndefined(table) || dragValue === 0) {\n return;\n }\n var selection = this.owner.selection;\n if (table.isInsideTable) {\n this.owner.isLayoutEnabled = false; //Layouting is disabled to skip the child table layouting. \n }\n if (this.resizerPosition > -1) {\n var row = table.childWidgets[this.resizerPosition];\n this.updateRowHeight(row, dragValue);\n selection.selectPosition(selection.start, selection.end);\n }\n if (table.isInsideTable) {\n var parentTable = this.owner.viewer.layout.getParentTable(table);\n this.owner.isLayoutEnabled = true; //layouting is enabled to layout the parent table of the nested table.\n table = parentTable;\n }\n this.startingPoint.y += HelperMethods.convertPointToPixel(dragValue);\n this.owner.viewer.layout.reLayoutTable(table);\n this.owner.editorModule.reLayout(this.owner.selection);\n };\n /**\n * Gets the table widget from given cursor point\n * @param cursorPoint\n */\n TableResizer.prototype.getTableWidget = function (cursorPoint) {\n var widget = undefined;\n var currentPage = this.owner.viewer.currentPage;\n if (!isNullOrUndefined(currentPage)) {\n for (var i = 0; i < currentPage.bodyWidgets.length; i++) {\n var bodyWidget = currentPage.bodyWidgets[i];\n widget = this.getTableWidgetFromWidget(cursorPoint, bodyWidget);\n if (!isNullOrUndefined(widget)) {\n break;\n }\n }\n }\n return widget;\n };\n TableResizer.prototype.getTableWidgetFromWidget = function (point, widget) {\n for (var j = 0; j < widget.childWidgets.length; j++) {\n if (widget.childWidgets[j] instanceof TableWidget) {\n var childWidget = widget.childWidgets[j];\n if (childWidget.y <= point.y && (childWidget.y + childWidget.height) >= point.y) {\n return childWidget;\n }\n }\n }\n return undefined;\n };\n /**\n * Return the table cell widget from the given cursor point\n * @param cursorPoint\n * @private\n */\n TableResizer.prototype.getTableCellWidget = function (cursorPoint) {\n var widget = undefined;\n var currentPage = this.owner.viewer.currentPage;\n if (!isNullOrUndefined(currentPage)) {\n for (var i = 0; i < currentPage.bodyWidgets.length; i++) {\n var bodyWidget = currentPage.bodyWidgets[i];\n widget = bodyWidget.getTableCellWidget(cursorPoint);\n if (!isNullOrUndefined(widget)) {\n break;\n }\n }\n }\n return widget;\n };\n TableResizer.prototype.updateRowHeight = function (row, dragValue) {\n var rowFormat = row.rowFormat;\n if (rowFormat.heightType === 'Auto') {\n rowFormat.heightType = 'AtLeast';\n var row_1 = rowFormat.ownerBase;\n var currentHeight = this.owner.viewer.layout.getRowHeight(row_1, [row_1]);\n //the minimum height of the Row in MS word is 2.7 points which is equal to 3.6 pixel.\n if (currentHeight + dragValue >= 2.7 && rowFormat.height !== currentHeight + dragValue) {\n rowFormat.height = currentHeight + dragValue;\n }\n }\n else {\n //the minimum height of the Row in MS word is 2.7 points which is equal to 3.6 pixel.\n if (rowFormat.height + dragValue >= 2.7 && rowFormat.height !== rowFormat.height + dragValue) {\n rowFormat.height = rowFormat.height + dragValue;\n }\n }\n };\n //Resize Table cell\n TableResizer.prototype.resizeTableCellColumn = function (dragValue) {\n var table = this.currentResizingTable;\n if (isNullOrUndefined(table) || dragValue === 0 || isNullOrUndefined(table.childWidgets)) {\n return;\n }\n var selectionFlag = true;\n var selection = this.owner.selection;\n this.owner.editor.setOffsetValue(selection);\n table = table.combineWidget(this.viewer);\n this.owner.isLayoutEnabled = false;\n // table.PreserveGrid = true;\n this.setPreferredWidth(table);\n var containerWidth = table.getOwnerWidth(true);\n var newIndent = table.leftIndent;\n var tableAlignment = table.tableFormat.tableAlignment;\n if (!selection.isEmpty) {\n selectionFlag = this.resizeColumnWithSelection(selection, table, dragValue);\n }\n if (!selectionFlag) {\n this.owner.isLayoutEnabled = true;\n return;\n }\n if (this.resizerPosition === 0) {\n // Todo: need to handle the resizing of first column and table indent.\n var columnIndex = this.resizerPosition;\n var rightColumn = table.tableHolder.columns[columnIndex];\n var width = rightColumn.preferredWidth;\n if (dragValue > 0) {\n var prevDragValue = 0;\n while (dragValue !== prevDragValue) {\n var newWidth = HelperMethods.round(rightColumn.preferredWidth - dragValue, 1);\n if (newWidth >= rightColumn.minWidth) {\n rightColumn.preferredWidth = newWidth;\n newIndent = table.leftIndent + dragValue;\n newIndent = newIndent >= -1440 ? (newIndent <= 1440 ? newIndent : 1440) : -1440;\n prevDragValue = dragValue;\n }\n else {\n prevDragValue = dragValue;\n dragValue += newWidth - rightColumn.minWidth;\n }\n }\n }\n else {\n var prevDragValue = 0;\n while (dragValue !== prevDragValue) {\n var newWidth = HelperMethods.round(rightColumn.preferredWidth - dragValue, 1);\n if (newWidth <= 2112) {\n rightColumn.preferredWidth = newWidth;\n newIndent = table.leftIndent + dragValue;\n newIndent = newIndent >= -1440 ? (newIndent <= 1440 ? newIndent : 1440) : -1440;\n prevDragValue = dragValue;\n }\n else {\n prevDragValue = dragValue;\n dragValue -= newWidth - 2112;\n }\n }\n }\n var dragOffset = dragValue;\n // tslint:disable-next-line:max-line-length\n if (tableAlignment !== 'Left' && (table.tableHolder.getTotalWidth() > containerWidth) && table.tableFormat.preferredWidthType === 'Auto') {\n if (table.tableHolder.isFitColumns(containerWidth, table.tableHolder.tableWidth, table.tableFormat.preferredWidthType === 'Auto')) {\n // tslint:disable-next-line:max-line-length\n table.tableHolder.fitColumns(containerWidth, table.tableHolder.tableWidth, table.tableFormat.preferredWidthType === 'Auto');\n }\n else {\n rightColumn.preferredWidth = width;\n }\n dragOffset = 0;\n }\n if (tableAlignment === 'Center'\n && (table.tableHolder.getTotalWidth() < containerWidth || table.tableFormat.preferredWidthType !== 'Auto')) {\n dragOffset = dragOffset / 2;\n }\n table.tableFormat.leftIndent = tableAlignment === 'Left' ? newIndent : 0;\n table.tableHolder.tableWidth = table.tableHolder.getTotalWidth();\n this.updateCellPreferredWidths(table);\n this.updateGridValue(table, true, dragOffset);\n }\n else if (table !== null && this.resizerPosition === table.tableHolder.columns.length) {\n // Todo: need to handle the resizing of last column and table width.\n this.resizeColumnAtLastColumnIndex(table, dragValue, containerWidth);\n }\n else {\n if (this.resizerPosition === -1) {\n this.owner.isLayoutEnabled = true;\n return;\n }\n this.resizeCellAtMiddle(table, dragValue);\n }\n // table.PreserveGrid = false;\n this.owner.isLayoutEnabled = true;\n selection.selectPosition(selection.start, selection.end);\n };\n /**\n * Resize Selected Cells\n */\n TableResizer.prototype.resizeColumnWithSelection = function (selection, table, dragValue) {\n var newIndent = table.leftIndent;\n var cellwidget = this.getTableCellWidget(this.startingPoint);\n if (cellwidget && (selection.selectedWidgets.containsKey(cellwidget) || (cellwidget.previousWidget\n && selection.selectedWidgets.containsKey((cellwidget.previousWidget))))) {\n var selectedCells = selection.getSelectedCells();\n if (this.resizerPosition === 0) {\n this.resizeColumnAtStart(table, dragValue, selectedCells);\n }\n else if (table !== null && this.resizerPosition === table.tableHolder.columns.length) {\n var leftColumnCollection = this.getColumnCells(table, this.resizerPosition, true);\n for (var i = 0; i < leftColumnCollection.length; i++) {\n var cell = leftColumnCollection[i];\n if (selectedCells.indexOf(cell) !== -1) {\n this.increaseOrDecreaseWidth(cell, dragValue, true);\n }\n }\n //Updates the grid after value for all the rows.\n this.updateRowsGridAfterWidth(table);\n table.updateWidth(dragValue);\n this.updateGridValue(table, true, dragValue);\n }\n else {\n if (this.resizerPosition === -1) {\n return false;\n }\n var columnIndex = this.resizerPosition;\n var leftColumnCollection = this.getColumnCells(table, columnIndex, true);\n var rightColumnCollection = this.getColumnCells(table, columnIndex, false);\n var isColumnResizing = this.isColumnSelected(table, columnIndex);\n if (leftColumnCollection.length > 0 && !isColumnResizing) {\n for (var i = 0; i < leftColumnCollection.length; i++) {\n if (selectedCells.indexOf(leftColumnCollection[i]) === -1) {\n leftColumnCollection.splice(i, 1);\n i--;\n }\n }\n }\n if (rightColumnCollection.length > 0 && !isColumnResizing) {\n for (var i = 0; i < rightColumnCollection.length; i++) {\n if (selectedCells.indexOf(rightColumnCollection[i]) === -1) {\n rightColumnCollection.splice(i, 1);\n i--;\n }\n }\n }\n //Getting the adjacent cell collections for left side selected cells in the right column collection.\n if (leftColumnCollection.length === 0 && rightColumnCollection.length > 0) {\n for (var i = 0; i < rightColumnCollection.length; i++) {\n var cell = rightColumnCollection[i];\n if (cell.previousWidget) {\n leftColumnCollection.push(cell.previousWidget);\n }\n }\n }\n else if (rightColumnCollection.length === 0 && leftColumnCollection.length > 0) {\n for (var i = 0; i < leftColumnCollection.length; i++) {\n var cell = leftColumnCollection[i];\n if (cell.nextWidget) {\n rightColumnCollection.push(cell.nextWidget);\n }\n }\n }\n this.changeWidthOfCells(table, leftColumnCollection, rightColumnCollection, dragValue, true);\n this.updateGridValue(table, true, dragValue);\n }\n selection.selectPosition(selection.start, selection.end);\n }\n return false;\n };\n /**\n * Resize selected cells at resizer position 0\n */\n TableResizer.prototype.resizeColumnAtStart = function (table, dragValue, selectedCells) {\n var newIndent = table.leftIndent;\n var rightColumnCollection = this.getColumnCells(table, this.resizerPosition, false);\n var offset = 0;\n var selectedRow = selectedCells[0].ownerRow;\n var rowFormat = selectedRow.rowFormat;\n if (rowFormat.beforeWidth > 0) {\n var newGridBefore = rowFormat.beforeWidth + dragValue;\n if (newGridBefore > 0) {\n this.updateGridBefore(selectedRow, dragValue);\n }\n else {\n var leastGridBefore = this.getLeastGridBefore(table, selectedRow);\n if (newGridBefore < leastGridBefore && offset !== newGridBefore) {\n newIndent = table.leftIndent + newGridBefore;\n table.tableFormat.leftIndent = newIndent >= -1440 ? (newIndent <= 1440 ? newIndent : 1440) : -1440;\n for (var i = 0; i < table.childWidgets.length; i++) {\n var tableRow = table.childWidgets[i];\n if (selectedRow !== tableRow) {\n this.updateGridBefore(tableRow, -newGridBefore);\n }\n }\n }\n }\n }\n else {\n if (dragValue < 0) {\n newIndent = table.leftIndent + dragValue;\n table.tableFormat.leftIndent = newIndent >= -1440 ? (newIndent <= 1440 ? newIndent : 1440) : -1440;\n this.updateWidthForCells(table, selectedCells, dragValue);\n }\n else {\n var leastGridBefore = this.getLeastGridBefore(table, selectedRow);\n var currentTableIndent = table.tableFormat.leftIndent;\n if (currentTableIndent === 0) {\n for (var i = 0; i < table.childWidgets.length; i++) {\n var tableRow = table.childWidgets[i];\n if (selectedCells.indexOf(tableRow.childWidgets[0]) !== -1) {\n this.updateGridBefore(tableRow, dragValue);\n this.increaseOrDecreaseWidth(tableRow.childWidgets[0], dragValue, false);\n }\n }\n }\n else {\n var difference = leastGridBefore - dragValue;\n if (difference > 0) {\n newIndent = table.leftIndent + dragValue;\n table.tableFormat.leftIndent = newIndent >= -1440 ? (newIndent <= 1440 ? newIndent : 1440) : -1440;\n this.updateWidthForCells(table, selectedCells, dragValue);\n }\n else {\n newIndent = table.leftIndent + leastGridBefore;\n table.tableFormat.leftIndent = newIndent >= -1440 ? (newIndent <= 1440 ? newIndent : 1440) : -1440;\n for (var i = 0; i < table.childWidgets.length; i++) {\n var tableRow = table.childWidgets[i];\n if (selectedCells.indexOf(tableRow.childWidgets[0]) !== -1) {\n this.increaseOrDecreaseWidth(tableRow.childWidgets[0], dragValue, false);\n this.updateGridBefore(tableRow, dragValue - leastGridBefore);\n }\n else {\n this.updateGridBefore(tableRow, -leastGridBefore);\n }\n }\n }\n }\n }\n }\n this.updateGridValue(table, true, dragValue);\n };\n TableResizer.prototype.updateWidthForCells = function (table, selectedCells, dragValue) {\n for (var i = 0; i < table.childWidgets.length; i++) {\n var tableRow = table.childWidgets[i];\n if (selectedCells.indexOf(tableRow.childWidgets[0]) !== -1) {\n this.increaseOrDecreaseWidth(tableRow.childWidgets[0], dragValue, false);\n }\n else {\n this.updateGridBefore(tableRow, -dragValue);\n }\n }\n };\n /**\n * Resize selected cells at last column\n */\n TableResizer.prototype.resizeColumnAtLastColumnIndex = function (table, dragValue, containerWidth) {\n var tableAlignment = table.tableFormat.tableAlignment;\n var preferredWidth = table.tableFormat.preferredWidth;\n var hasTableWidth = preferredWidth;\n var columnIndex = this.resizerPosition;\n var leftColumn = table.tableHolder.columns[columnIndex - 1];\n var prevDragValue = 0;\n while (dragValue !== prevDragValue) {\n var newWidth = HelperMethods.round(leftColumn.preferredWidth + dragValue, 1);\n if (newWidth >= leftColumn.minWidth) {\n leftColumn.preferredWidth = newWidth;\n prevDragValue = dragValue;\n }\n else {\n prevDragValue = dragValue;\n dragValue -= newWidth - leftColumn.minWidth;\n }\n }\n this.updateCellPreferredWidths(table);\n if (hasTableWidth || table.tableHolder.getTotalWidth() > containerWidth) {\n table.updateWidth(dragValue);\n table.tableHolder.tableWidth = table.tableHolder.getTotalWidth();\n }\n var dragOffset = dragValue;\n if (tableAlignment === 'Right') {\n dragOffset = 0;\n }\n else if (tableAlignment === 'Center') {\n dragOffset = dragOffset / 2;\n }\n this.updateGridValue(table, true, dragOffset);\n };\n /**\n * Resize selected cells at middle column\n */\n TableResizer.prototype.resizeCellAtMiddle = function (table, dragValue) {\n var columnIndex = this.resizerPosition;\n var leftColumn = table.tableHolder.columns[columnIndex - 1];\n var rightColumn = table.tableHolder.columns[columnIndex];\n if (dragValue > 0) {\n var isContinue = true;\n while (isContinue) {\n var newWidth = HelperMethods.round(rightColumn.preferredWidth - dragValue, 1);\n if (newWidth >= rightColumn.minWidth) {\n rightColumn.preferredWidth = newWidth;\n leftColumn.preferredWidth = leftColumn.preferredWidth + dragValue;\n isContinue = false;\n }\n else {\n dragValue += newWidth - rightColumn.minWidth;\n }\n }\n }\n else {\n var isContinue = true;\n while (isContinue) {\n var newWidth = HelperMethods.round(leftColumn.preferredWidth + dragValue, 1);\n if (newWidth >= leftColumn.minWidth) {\n leftColumn.preferredWidth = newWidth;\n rightColumn.preferredWidth = rightColumn.preferredWidth - dragValue;\n isContinue = false;\n }\n else {\n dragValue -= newWidth - leftColumn.minWidth;\n }\n }\n }\n // Update the cell widths based on the columns preferred width\n this.updateCellPreferredWidths(table);\n // table.tableFormat.AllowAutoFit = false;\n table.tableHolder.tableWidth = table.tableHolder.getTotalWidth();\n this.updateGridValue(table, true, dragValue);\n };\n TableResizer.prototype.updateGridValue = function (table, isUpdate, dragValue) {\n if (isUpdate) {\n table.calculateGrid();\n table.isGridUpdated = false;\n }\n table.buildTableColumns();\n table.isGridUpdated = true;\n this.viewer.owner.isLayoutEnabled = true;\n if (table.isInsideTable) {\n var parentTable = this.viewer.layout.getParentTable(table);\n this.viewer.layout.reLayoutTable(parentTable); // Need to optmize this.\n }\n else {\n this.viewer.layout.reLayoutTable(table);\n }\n this.owner.editor.getOffsetValue(this.viewer.selection);\n this.owner.editorModule.reLayout(this.owner.selection);\n if (dragValue) {\n this.startingPoint.x += HelperMethods.convertPointToPixel(dragValue);\n this.resizerPosition = this.getCellReSizerPosition(this.startingPoint);\n }\n };\n TableResizer.prototype.getColumnCells = function (table, columnIndex, isLeftSideCollection) {\n var cells = [];\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n if (isLeftSideCollection) {\n if (cell.columnIndex + cell.cellFormat.columnSpan === columnIndex) {\n cells.push(cell);\n }\n }\n else {\n if (cell.columnIndex === columnIndex) {\n cells.push(cell);\n }\n }\n }\n }\n return cells;\n };\n TableResizer.prototype.updateGridBefore = function (row, offset) {\n if (row.rowFormat.beforeWidth + offset !== row.rowFormat.beforeWidth) {\n row.rowFormat.beforeWidth = row.rowFormat.beforeWidth + offset;\n row.rowFormat.gridBeforeWidth = row.rowFormat.beforeWidth;\n }\n };\n TableResizer.prototype.getLeastGridBefore = function (table, ignoreRow) {\n var gridBefore = 0;\n var flag = 0;\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row !== ignoreRow) {\n if (flag === 0) {\n gridBefore = row.rowFormat.beforeWidth;\n flag++;\n }\n if (row.rowFormat.beforeWidth <= gridBefore) {\n gridBefore = row.rowFormat.beforeWidth;\n }\n }\n }\n return gridBefore;\n };\n TableResizer.prototype.increaseOrDecreaseWidth = function (cell, dragValue, isIncrease) {\n var preferredWidth = cell.cellFormat.preferredWidth;\n if (cell.cellFormat.preferredWidthType === 'Auto') {\n preferredWidth = cell.cellFormat.cellWidth;\n cell.cellFormat.preferredWidthType = 'Point';\n }\n var minimumWidth = cell.ownerColumn.minWidth;\n if (cell.cellFormat.preferredWidthType === 'Percent') {\n minimumWidth = cell.convertPointToPercent(minimumWidth);\n }\n // Margins properties usedd for internal purpose.\n if (isIncrease) {\n cell.cellFormat.preferredWidth = preferredWidth + dragValue > minimumWidth ? preferredWidth + dragValue : minimumWidth;\n }\n else {\n cell.cellFormat.preferredWidth = preferredWidth - dragValue > minimumWidth ? preferredWidth - dragValue : minimumWidth;\n }\n };\n // tslint:disable-next-line:max-line-length\n TableResizer.prototype.changeWidthOfCells = function (table, leftColumnCollection, rightColumnCollection, dragValue, isSelection) {\n if (leftColumnCollection.length > 0) {\n var flag = false;\n for (var i = 0; i < leftColumnCollection.length; i++) {\n var cell = leftColumnCollection[i];\n this.increaseOrDecreaseWidth(cell, dragValue, true);\n if (cell.cellIndex === cell.ownerRow.childWidgets.length - 1) {\n flag = true;\n }\n }\n if (flag) {\n this.updateRowsGridAfterWidth(table);\n }\n }\n if (rightColumnCollection.length > 0) {\n var diff = 0;\n for (var i = 0; i < rightColumnCollection.length; i++) {\n var cell = rightColumnCollection[i];\n if (cell.cellIndex === 0) {\n var newGridBefore = cell.ownerRow.rowFormat.beforeWidth + dragValue;\n if (newGridBefore >= 0) {\n this.updateGridBefore(cell.ownerRow, dragValue);\n }\n else {\n if (diff !== newGridBefore) {\n diff = newGridBefore;\n }\n cell.ownerRow.rowFormat.gridBeforeWidth = 0;\n cell.ownerRow.rowFormat.gridBeforeWidthType = 'Auto';\n }\n }\n this.increaseOrDecreaseWidth(cell, dragValue, false);\n }\n if (diff !== 0) {\n var newIndent = table.leftIndent + diff;\n table.tableFormat.leftIndent = newIndent >= -1440 ? (newIndent <= 1440 ? newIndent : 1440) : -1440;\n for (var j = 0; j < table.childWidgets.length; j++) {\n var row = table.childWidgets[j];\n if (rightColumnCollection.indexOf(row.childWidgets[0]) === -1) {\n this.updateGridBefore(row, diff > 0 ? diff : -diff);\n }\n }\n }\n }\n };\n TableResizer.prototype.updateRowsGridAfterWidth = function (table) {\n var maxRowWidth = this.getMaxRowWidth(table, true);\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n var currentRowWidth = this.getRowWidth(row, true);\n if (maxRowWidth >= currentRowWidth && row.rowFormat.afterWidth !== maxRowWidth - currentRowWidth) {\n var value = maxRowWidth - currentRowWidth;\n row.rowFormat.gridAfterWidth = value;\n row.rowFormat.afterWidth = value;\n }\n }\n };\n TableResizer.prototype.getRowWidth = function (row, toUpdateGridAfter) {\n var rowWidth = 0;\n if (toUpdateGridAfter) {\n rowWidth = rowWidth + row.rowFormat.beforeWidth;\n }\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n rowWidth += cell.cellFormat.cellWidth;\n }\n return rowWidth;\n };\n TableResizer.prototype.getMaxRowWidth = function (table, toUpdateGridAfter) {\n var width = 0;\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n var rowWidth = 0;\n if (toUpdateGridAfter) {\n rowWidth = rowWidth + row.rowFormat.beforeWidth;\n }\n for (var i_1 = 0; i_1 < row.childWidgets.length; i_1++) {\n var cell = row.childWidgets[i_1];\n rowWidth += cell.cellFormat.cellWidth;\n }\n if (width < rowWidth) {\n width = rowWidth;\n }\n }\n return width;\n };\n TableResizer.prototype.isColumnSelected = function (table, columnIndex) {\n var selection = this.owner.selection;\n var selectedCells = selection.getSelectedCells();\n var leftColumnCells = this.getColumnCells(table, columnIndex, true);\n var rightColumnCells = this.getColumnCells(table, columnIndex, false);\n var isColumnSelected = false;\n for (var i = 0; i < leftColumnCells.length; i++) {\n var columnCell = leftColumnCells[i];\n isColumnSelected = selectedCells.indexOf(columnCell) !== -1 ? true : false;\n }\n if (!isColumnSelected) {\n for (var i = 0; i < rightColumnCells.length; i++) {\n var columnCell = rightColumnCells[i];\n isColumnSelected = selectedCells.indexOf(columnCell) !== -1 ? true : false;\n }\n }\n return isColumnSelected;\n };\n TableResizer.prototype.applyProperties = function (table, tableHistoryInfo) {\n if (isNullOrUndefined(tableHistoryInfo)) {\n return;\n }\n table = table;\n // PreserveGrid = true;\n if (tableHistoryInfo.tableHolder) {\n table.tableHolder = tableHistoryInfo.tableHolder.clone();\n }\n if (tableHistoryInfo.tableFormat !== null) {\n table.tableFormat.leftIndent = tableHistoryInfo.tableFormat.leftIndent;\n table.tableFormat.preferredWidth = tableHistoryInfo.tableFormat.preferredWidth;\n table.tableFormat.preferredWidthType = tableHistoryInfo.tableFormat.preferredWidthType;\n }\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n var rowFormat = tableHistoryInfo.rows[i];\n row.rowFormat.gridBefore = rowFormat.gridBefore;\n row.rowFormat.gridBeforeWidth = rowFormat.gridBeforeWidth;\n row.rowFormat.gridBeforeWidthType = rowFormat.gridBeforeWidthType;\n row.rowFormat.gridAfter = rowFormat.gridAfter;\n row.rowFormat.gridAfterWidth = rowFormat.gridAfterWidth;\n row.rowFormat.gridAfterWidthType = rowFormat.gridAfterWidthType;\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n var cellFormat = rowFormat.cells[j];\n cell.columnIndex = cellFormat.columnIndex;\n cell.cellFormat.columnSpan = cellFormat.columnSpan;\n cell.cellFormat.preferredWidth = cellFormat.preferredWidth;\n cell.cellFormat.preferredWidthType = cellFormat.preferredWidthType;\n }\n }\n var containerWidth = table.getOwnerWidth(true);\n var tableWidth = table.getTableClientWidth(containerWidth);\n //Sets the width to cells\n table.setWidthToCells(tableWidth, table.tableFormat.preferredWidthType === 'Auto');\n // PreserveGrid = false;\n };\n /**\n * Return table row width\n */\n TableResizer.prototype.getActualWidth = function (row) {\n var width = 0;\n if (row.childWidgets.length > 0) {\n for (var i = 0; i < row.childWidgets.length; i++) {\n width += row.childWidgets[i].cellFormat.cellWidth;\n }\n }\n return width;\n };\n TableResizer.prototype.setPreferredWidth = function (table) {\n for (var i = 0; i < table.childWidgets.length; i++) {\n var rw = table.childWidgets[i];\n var rowFormat = rw.rowFormat;\n if (rowFormat.gridBefore > 0) {\n rowFormat.gridBeforeWidth = rowFormat.beforeWidth;\n rowFormat.gridBeforeWidthType = 'Point';\n }\n for (var j = 0; j < rw.childWidgets.length; j++) {\n var cell = rw.childWidgets[j];\n cell.cellFormat.preferredWidth = cell.cellFormat.cellWidth;\n cell.cellFormat.preferredWidthType = 'Point';\n }\n if (rowFormat.gridAfter > 0) {\n rowFormat.gridAfterWidth = rowFormat.afterWidth;\n rowFormat.gridAfterWidthType = 'Point';\n }\n }\n };\n TableResizer.prototype.updateCellPreferredWidths = function (table) {\n var tableWidth = table.tableHolder.tableWidth;\n var isAutoFit = table.tableFormat.preferredWidthType === 'Auto';\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row.rowFormat.gridBefore > 0) {\n var width = table.tableHolder.getCellWidth(0, row.rowFormat.gridBefore, tableWidth, isAutoFit);\n this.updateGridBeforeWidth(width, row);\n }\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n cell.updateWidth(table.tableHolder.getCellWidth(cell.columnIndex, cell.cellFormat.columnSpan, tableWidth, isAutoFit));\n }\n if (row.rowFormat.gridAfter > 0) {\n // tslint:disable-next-line:max-line-length\n this.updateGridAfterWidth(table.tableHolder.getCellWidth(row.childWidgets.length, row.rowFormat.gridAfter, tableWidth, isAutoFit), row);\n }\n }\n };\n /**\n * Update grid before width value\n */\n TableResizer.prototype.updateGridBeforeWidth = function (width, row) {\n var rowFormat = row.rowFormat;\n if (width !== rowFormat.beforeWidth) {\n rowFormat.beforeWidth = width;\n if (rowFormat.gridBeforeWidthType === 'Auto') {\n rowFormat.gridBeforeWidthType = 'Point';\n }\n if (rowFormat.gridBeforeWidthType === 'Point') {\n rowFormat.gridBeforeWidth = rowFormat.beforeWidth;\n }\n else {\n // The value is calculated from the pixel values hence, its converted to percent using method. \n var ownerWidth = row.ownerTable.getTableClientWidth(row.ownerTable.getOwnerWidth(true));\n var value = row.ownerTable.convertPointToPercent(rowFormat.beforeWidth, ownerWidth);\n rowFormat.gridBeforeWidth = value;\n }\n }\n };\n /**\n * Update grid after width value\n */\n TableResizer.prototype.updateGridAfterWidth = function (width, row) {\n var rowFormat = row.rowFormat;\n if (width !== rowFormat.afterWidth) {\n rowFormat.afterWidth = width;\n }\n if (rowFormat.gridAfterWidthType === 'Auto') {\n rowFormat.gridAfterWidthType = 'Point';\n }\n if (rowFormat.gridAfterWidthType === 'Point') {\n rowFormat.gridAfterWidth = rowFormat.afterWidth;\n }\n else {\n // The value is calculated from the pixel values hence, its converted to percent using method. \n var ownerWidth = row.ownerTable.getTableClientWidth(row.ownerTable.getOwnerWidth(true));\n var value = row.ownerTable.convertPointToPercent(rowFormat.afterWidth, ownerWidth);\n rowFormat.gridAfterWidth = value;\n }\n };\n return TableResizer;\n}());\nexport { TableResizer };\n","import { TextPosition, ImageFormat } from '../selection/selection-helper';\nimport { ParagraphWidget, LineWidget, ElementBox, TextElementBox, Margin, ImageElementBox, BlockWidget, BlockContainer, BodyWidget, TableWidget, TableCellWidget, TableRowWidget, Widget, ListTextElementBox, BookmarkElementBox, HeaderFooterWidget, FieldTextElementBox, TabElementBox } from '../viewer/page';\nimport { WCharacterFormat } from '../format/character-format';\nimport { HelperMethods } from './editor-helper';\nimport { isNullOrUndefined, Browser, classList } from '@syncfusion/ej2-base';\nimport { WParagraphFormat, WSectionFormat, WListFormat, WTableFormat, WRowFormat, WCellFormat, WBorder, WBorders, WTabStop } from '../index';\nimport { WList } from '../list/list';\nimport { WAbstractList } from '../list/abstract-list';\nimport { WListLevel } from '../list/list-level';\nimport { WLevelOverride } from '../list/level-override';\nimport { FieldElementBox } from '../viewer/page';\nimport { WCharacterStyle } from '../format/style';\nimport { TableResizer } from './table-resizer';\nimport { WParagraphStyle } from '../format/style';\n/**\n * Editor module\n */\nvar Editor = /** @class */ (function () {\n /**\n * Initialize the editor module\n * @param {LayoutViewer} viewer\n * @private\n */\n function Editor(viewer) {\n var _this = this;\n this.nodes = [];\n this.editHyperlinkInternal = false;\n this.startParagraph = undefined;\n this.endParagraph = undefined;\n /**\n * @private\n */\n this.isHandledComplex = false;\n /**\n * @private\n */\n this.tableResize = undefined;\n /**\n * @private\n */\n this.tocStyles = {};\n this.refListNumber = undefined;\n this.incrementListNumber = -1;\n this.removedBookmarkElements = [];\n /**\n * @private\n */\n this.tocBookmarkId = 0;\n /**\n * @private\n */\n this.copiedData = undefined;\n this.pageRefFields = {};\n /**\n * @private\n */\n this.isInsertingTOC = false;\n /**\n * @private\n */\n this.isBordersAndShadingDialog = false;\n /**\n * @private\n */\n this.onTextInputInternal = function (event) {\n if (Browser.isDevice) {\n var viewer = _this.viewer;\n var nbsp = new RegExp(String.fromCharCode(160), 'g');\n var lineFeed = new RegExp(String.fromCharCode(10), 'g');\n viewer.prefix = viewer.prefix.replace(nbsp, ' ').replace(lineFeed, ' ');\n var text = viewer.editableDiv.textContent.replace(nbsp, ' ').replace(lineFeed, ' ');\n var textBoxText = text.substring(2);\n if (viewer.isCompositionStart && viewer.isCompositionUpdated) {\n viewer.isCompositionUpdated = false;\n if (!viewer.owner.isReadOnlyMode && viewer.owner.isDocumentLoaded) {\n if (viewer.prefix.substring(2) !== textBoxText) {\n if (_this.selection.isEmpty) {\n // tslint:disable-next-line:max-line-length\n _this.selection.start.setPositionForLineWidget(viewer.selection.start.currentWidget, _this.selection.start.offset - (viewer.prefix.length - 2));\n _this.handleTextInput(textBoxText);\n viewer.prefix = '@' + String.fromCharCode(160) + textBoxText;\n }\n else {\n _this.handleTextInput(textBoxText);\n viewer.prefix = '@' + String.fromCharCode(160) + textBoxText;\n }\n }\n }\n return;\n }\n else if (viewer.isCompositionStart && viewer.isCompositionEnd && viewer.suffix === '') {\n if (viewer.prefix.substring(2) !== textBoxText) {\n if (_this.selection.isEmpty && viewer.isCompositionStart) {\n viewer.isCompositionStart = false;\n // tslint:disable-next-line:max-line-length\n _this.selection.start.setPositionForLineWidget(viewer.selection.start.currentWidget, _this.selection.start.offset - viewer.prefix.substring(2).length);\n _this.selection.retrieveCurrentFormatProperties();\n if (viewer.suffix === '' || textBoxText === '') {\n _this.handleTextInput(textBoxText);\n }\n }\n else if (!_this.selection.isEmpty) {\n viewer.isCompositionStart = false;\n _this.handleTextInput(textBoxText);\n }\n }\n else if (textBoxText === '') {\n viewer.isCompositionStart = false;\n _this.handleBackKey();\n }\n else if (viewer.prefix.substring(2) === textBoxText && viewer.suffix === '') {\n viewer.isCompositionStart = false;\n _this.handleTextInput(' ');\n }\n viewer.isCompositionEnd = false;\n return;\n }\n else if (viewer.isCompositionEnd || viewer.isCompositionStart && !viewer.compositionUpdated) {\n if (textBoxText.length < viewer.prefix.length &&\n textBoxText === viewer.prefix.substring(2, viewer.prefix.length - 1) || viewer.editableDiv.innerText.length < 2) {\n _this.handleBackKey();\n return;\n }\n else if (viewer.suffix !== '' &&\n viewer.editableDiv.innerText[viewer.editableDiv.innerText.length - 1] !== String.fromCharCode(160)) {\n viewer.isCompositionStart = false;\n //When cursor is placed in between a word and chosen a word from predicted words.\n // tslint:disable-next-line:max-line-length\n _this.selection.start.setPositionForLineWidget(viewer.selection.start.currentWidget, _this.selection.start.offset - (viewer.prefix.length - 2));\n _this.selection.end.setPositionForLineWidget(viewer.selection.end.currentWidget, _this.selection.end.offset + viewer.suffix.length);\n //Retrieve the character format properties. Since the selection was changed manually.\n _this.selection.retrieveCurrentFormatProperties();\n _this.handleTextInput(textBoxText);\n return;\n }\n }\n // tslint:disable-next-line:max-line-length\n if (text !== '\\r' && text !== '\\b' && text !== '\\u001B' && !viewer.owner.isReadOnlyMode && viewer.isControlPressed === false) {\n if (text === '@' || text[0] !== '@' || text === '' || text.length < viewer.prefix.length &&\n textBoxText === viewer.prefix.substring(2, viewer.prefix.length - 1)) {\n _this.handleBackKey();\n if (viewer.editableDiv.innerText.length < 2) {\n _this.predictText();\n }\n }\n else if (text.indexOf(viewer.prefix) === 0 && text.length > viewer.prefix.length) {\n _this.handleTextInput(text.substring(viewer.prefix.length));\n }\n else if (text.indexOf(viewer.prefix) === -1 && text[text.length - 1] !== String.fromCharCode(160)\n && text[text.length - 1] !== ' ') {\n if ((textBoxText.charAt(0).toLowerCase() + textBoxText.slice(1)) === viewer.prefix.substring(2)) {\n // tslint:disable-next-line:max-line-length\n _this.selection.start.setPositionParagraph(viewer.selection.start.currentWidget, _this.selection.start.offset - (viewer.prefix.length - 2));\n }\n _this.handleTextInput(textBoxText);\n }\n else if (text.length !== 2) {\n _this.handleTextInput(' ');\n }\n }\n }\n else {\n var text = _this.viewer.editableDiv.innerText;\n if (text !== String.fromCharCode(160)) {\n // tslint:disable-next-line:max-line-length\n if (text !== '\\r' && text !== '\\b' && text !== '\\u001B' && !_this.owner.isReadOnlyMode && _this.viewer.isControlPressed === false) {\n _this.handleTextInput(text);\n }\n }\n else {\n _this.handleTextInput(' ');\n }\n _this.viewer.editableDiv.innerText = '';\n }\n };\n /**\n * Fired on paste.\n * @param {ClipboardEvent} event\n * @private\n */\n this.onPaste = function (event) {\n if (!_this.owner.isReadOnlyMode) {\n _this.pasteInternal(event);\n }\n event.preventDefault();\n };\n this.viewer = viewer;\n this.tableResize = new TableResizer(this.viewer.owner);\n }\n Object.defineProperty(Editor.prototype, \"editorHistory\", {\n get: function () {\n return this.viewer.owner.editorHistory;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Editor.prototype, \"selection\", {\n get: function () {\n if (this.viewer) {\n return this.viewer.selection;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Editor.prototype, \"owner\", {\n get: function () {\n return this.viewer.owner;\n },\n enumerable: true,\n configurable: true\n });\n Editor.prototype.getModuleName = function () {\n return 'Editor';\n };\n Editor.prototype.insertField = function (code, result) {\n var fieldCode = code;\n if (isNullOrUndefined(result)) {\n fieldCode = HelperMethods.trimStart(fieldCode);\n if (fieldCode.substring(0, 10) === 'MERGEFIELD') {\n fieldCode = fieldCode.substring(10).trim();\n var index = fieldCode.indexOf('\\\\*');\n result = '«' + fieldCode.substring(0, index).trim() + '»';\n }\n }\n var paragraph = new ParagraphWidget();\n var line = new LineWidget(paragraph);\n var fieldBegin = new FieldElementBox(0);\n line.children.push(fieldBegin);\n var fieldCodeSpan = new TextElementBox();\n fieldCodeSpan.text = code;\n line.children.push(fieldCodeSpan);\n var fieldSeparator = new FieldElementBox(2);\n fieldSeparator.fieldBegin = fieldBegin;\n fieldBegin.fieldSeparator = fieldSeparator;\n line.children.push(fieldSeparator);\n var fieldResultSpan = new TextElementBox();\n fieldResultSpan.text = result;\n line.children.push(fieldResultSpan);\n var fieldEnd = new FieldElementBox(1);\n fieldEnd.fieldSeparator = fieldSeparator;\n fieldEnd.fieldBegin = fieldBegin;\n fieldBegin.fieldEnd = fieldEnd;\n fieldSeparator.fieldEnd = fieldEnd;\n line.children.push(fieldEnd);\n fieldBegin.line = line;\n paragraph.childWidgets.push(line);\n this.viewer.fields.push(fieldBegin);\n var widgets = [];\n widgets.push(paragraph);\n this.pasteContentsInternal(widgets);\n };\n /**\n * To update style for paragraph\n * @param style - style name\n * @param clearDirectFormatting - Removes manual formatting (formatting not applied using a style)\n * from the selected text, to match the formatting of the applied style. Default value is false.\n */\n Editor.prototype.applyStyle = function (style, clearDirectFormatting) {\n clearDirectFormatting = isNullOrUndefined(clearDirectFormatting) ? false : clearDirectFormatting;\n if (clearDirectFormatting) {\n this.initComplexHistory('ApplyStyle');\n this.clearFormatting();\n }\n var styleObj = this.viewer.styles.findByName(style);\n if (styleObj !== undefined) {\n this.onApplyParagraphFormat('styleName', styleObj, false, true);\n }\n else {\n // tslint:disable-next-line:max-line-length\n this.viewer.owner.parser.parseStyle(JSON.parse(this.getCompleteStyles()), JSON.parse(this.viewer.preDefinedStyles.get(style)), this.viewer.styles);\n this.applyStyle(style);\n }\n if (this.editorHistory && this.editorHistory.currentHistoryInfo && this.editorHistory.currentHistoryInfo.action === 'ApplyStyle') {\n this.editorHistory.updateComplexHistory();\n }\n };\n // Public Implementation Starts\n /**\n * Moves the selected content in the document editor control to clipboard.\n */\n Editor.prototype.cut = function () {\n if (this.owner.isReadOnlyMode || this.selection.isEmpty) {\n return;\n }\n this.selection.copySelectedContent(true);\n };\n /**\n * Notify content change event\n * @private\n */\n Editor.prototype.fireContentChange = function () {\n if (this.viewer.owner.isLayoutEnabled && !this.viewer.owner.isShiftingEnabled) {\n this.viewer.owner.fireContentChange();\n }\n };\n /**\n * Update physical location for text position\n * @private\n */\n Editor.prototype.updateSelectionTextPosition = function (isSelectionChanged) {\n this.getOffsetValue(this.selection);\n this.selection.start.updatePhysicalPosition(true);\n if (this.selection.isEmpty) {\n this.selection.end.setPositionInternal(this.selection.start);\n }\n else {\n this.selection.end.updatePhysicalPosition(true);\n }\n this.selection.upDownSelectionLength = this.selection.end.location.x;\n this.selection.fireSelectionChanged(isSelectionChanged);\n };\n /**\n * Predict text\n * @private\n */\n Editor.prototype.predictText = function () {\n this.viewer.suffix = '';\n if (this.selection.start.paragraph.isEmpty() || this.selection.start.offset === 0 &&\n this.selection.start.currentWidget.isFirstLine() || this.selection.end.offset === 0 &&\n this.selection.end.currentWidget.isFirstLine()) {\n this.viewer.prefix = '';\n }\n else {\n this.getPrefixAndSuffix();\n }\n this.viewer.prefix = '@' + String.fromCharCode(160) + this.viewer.prefix; // \n this.viewer.editableDiv.innerText = this.viewer.prefix;\n this.viewer.selection.setEditableDivCaretPosition(this.viewer.prefix.length);\n };\n /**\n * Gets prefix and suffix.\n * @private\n */\n /* tslint:disable:max-func-body-length */\n Editor.prototype.getPrefixAndSuffix = function () {\n var viewer = this.viewer;\n if (this.selection.text !== '') {\n viewer.prefix = '';\n return;\n }\n else {\n var startIndex = 0;\n var inlineInfo = this.selection.start.currentWidget.getInline(this.selection.start.offset, startIndex);\n var inline = inlineInfo.element;\n startIndex = inlineInfo.index;\n if (inline !== undefined) {\n var boxInfo = this.selection.getElementBoxInternal(inline, startIndex);\n var box = boxInfo.element;\n startIndex = boxInfo.index;\n var spaceIndex = 0;\n if (!isNullOrUndefined(box)) {\n var prefixAdded = false;\n if (box instanceof TextElementBox && startIndex > 0 && box.line.isFirstLine()) {\n viewer.prefix = '';\n }\n if (!(inline instanceof TextElementBox)) {\n inline = this.selection.getPreviousTextElement(inline);\n }\n /* tslint:disable:no-conditional-assignment */\n while ((spaceIndex = viewer.prefix.lastIndexOf(' ')) < 0 && inline instanceof TextElementBox) {\n if (inline.previousNode instanceof TextElementBox && viewer.prefix.indexOf(' ') === -1) {\n if (!prefixAdded) {\n viewer.prefix = inline.text.substring(0, startIndex);\n prefixAdded = true;\n }\n else {\n viewer.prefix = inline.text + viewer.prefix;\n }\n inline = inline.previousNode;\n // If the line has no elements then break the loop to avoid the exception.\n if (inline instanceof ListTextElementBox) {\n break;\n }\n if (!(inline instanceof TextElementBox)) {\n inline = this.selection.getPreviousTextElement(inline);\n }\n }\n else if (!(inline.previousNode instanceof TextElementBox)) {\n if (!prefixAdded) {\n viewer.prefix = inline.text.substring(0, startIndex);\n prefixAdded = true;\n }\n else {\n viewer.prefix = inline.text + viewer.prefix;\n }\n break;\n }\n }\n if (!(viewer.prefix.length > 1 && viewer.prefix[viewer.prefix.length - 1] === ' ' &&\n viewer.prefix[viewer.prefix.length - 2] === '.')) {\n spaceIndex = viewer.prefix.lastIndexOf(' ');\n }\n else {\n spaceIndex = -1;\n viewer.prefix = '';\n }\n viewer.prefix = spaceIndex < 0 ? viewer.prefix : viewer.prefix.substring(spaceIndex);\n if (viewer.prefix.indexOf(' ') === 0 && viewer.prefix.length >= 1) {\n viewer.prefix = viewer.prefix.substring(1);\n }\n // suffix text prediction\n var endIndex = 0;\n var endInlineInfo = this.selection.end.currentWidget.getInline(this.selection.end.offset, endIndex);\n var endInline = endInlineInfo.element;\n endIndex = endInlineInfo.index;\n boxInfo = this.selection.getElementBoxInternal(endInline, endIndex);\n box = boxInfo.element;\n endIndex = boxInfo.index;\n if (box) {\n var suffixAdded = false;\n if (box instanceof TextElementBox && endIndex < box.length) {\n viewer.suffix = '';\n }\n // boxIndex = renderedElements.get(endInline).indexOf(box);\n while ((spaceIndex = viewer.suffix.indexOf(' ')) < 0 && endInline instanceof TextElementBox) {\n if (endInline.nextNode instanceof TextElementBox && viewer.suffix.indexOf(' ') === -1) {\n if (!suffixAdded) {\n viewer.suffix = box.text.substring(endIndex);\n suffixAdded = true;\n }\n else {\n viewer.suffix = viewer.suffix + endInline.text;\n }\n endInline = endInline.nextNode;\n }\n else if (!(endInline.nextNode instanceof TextElementBox)) {\n if (!suffixAdded) {\n viewer.suffix = box.text.substring(endIndex);\n suffixAdded = true;\n }\n else {\n viewer.suffix = viewer.suffix + endInline.text;\n }\n break;\n }\n }\n spaceIndex = viewer.suffix.indexOf(' ');\n viewer.suffix = spaceIndex < 0 ? viewer.suffix : viewer.suffix.substring(0, spaceIndex);\n }\n }\n }\n }\n };\n /**\n * key action\n * @private\n */\n // tslint:disable:max-func-body-length\n Editor.prototype.onKeyDownInternal = function (event, ctrl, shift, alt) {\n var key = event.which || event.keyCode;\n if (ctrl && !shift && !alt) {\n this.viewer.isControlPressed = true;\n switch (key) {\n case 9:\n event.preventDefault();\n if (this.owner.acceptTab) {\n this.selection.handleTabKey(false, false);\n }\n break;\n case 48:\n event.preventDefault();\n this.onApplyParagraphFormat('beforeSpacing', 0, false, false);\n break;\n case 49:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.onApplyParagraphFormat('lineSpacing', 1, false, false);\n }\n break;\n case 50:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.onApplyParagraphFormat('lineSpacing', 2, false, false);\n }\n break;\n case 53:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.onApplyParagraphFormat('lineSpacing', 1.5, false, false);\n }\n break;\n case 66:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.toggleBold();\n }\n break;\n case 68:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode && this.owner.fontDialogModule) {\n this.owner.fontDialogModule.showFontDialog();\n }\n break;\n case 69:\n if (!this.owner.isReadOnlyMode) {\n this.toggleTextAlignment('Center');\n }\n event.preventDefault();\n break;\n case 72:\n event.preventDefault();\n if (!this.owner.isReadOnly && this.owner.optionsPaneModule) {\n this.owner.optionsPaneModule.isReplace = true;\n this.owner.optionsPaneModule.showHideOptionsPane(true);\n }\n break;\n case 73:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.toggleItalic();\n }\n break;\n case 74:\n if (!this.owner.isReadOnlyMode) {\n this.toggleTextAlignment('Justify');\n }\n event.preventDefault();\n break;\n case 75:\n event.preventDefault();\n if (this.owner.hyperlinkDialogModule && !this.owner.isReadOnlyMode) {\n this.owner.hyperlinkDialogModule.show();\n }\n break;\n case 76:\n if (!this.owner.isReadOnlyMode) {\n this.toggleTextAlignment('Left');\n }\n event.preventDefault();\n break;\n case 77:\n if (!this.owner.isReadOnlyMode) {\n this.owner.selection.increaseIndent();\n }\n event.preventDefault();\n break;\n case 78:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.owner.openBlank();\n }\n break;\n case 82:\n if (!this.owner.isReadOnlyMode) {\n this.toggleTextAlignment('Right');\n }\n event.preventDefault();\n break;\n case 85:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.owner.selection.toggleUnderline('Single');\n }\n break;\n case 88:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.owner.editor.cut();\n }\n break;\n case 89:\n if (this.owner.enableEditorHistory) {\n this.editorHistory.redo();\n event.preventDefault();\n }\n break;\n case 90:\n if (this.owner.enableEditorHistory) {\n this.editorHistory.undo();\n event.preventDefault();\n }\n break;\n case 219:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.onApplyCharacterFormat('fontSize', 'decrement', true);\n }\n break;\n case 221:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.onApplyCharacterFormat('fontSize', 'increment', true);\n }\n break;\n case 187:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.toggleBaselineAlignment('Subscript');\n }\n break;\n }\n }\n else if (shift && !ctrl && !alt) {\n switch (key) {\n case 9:\n event.preventDefault();\n if (this.owner.acceptTab) {\n this.selection.handleTabKey(false, true);\n }\n break;\n case 13:\n this.handleShiftEnter();\n event.preventDefault();\n break;\n }\n }\n else if (shift && ctrl && !alt) {\n switch (key) {\n case 68:\n if (!this.owner.isReadOnlyMode) {\n this.owner.selection.toggleUnderline('Double');\n }\n break;\n case 77:\n if (!this.owner.isReadOnlyMode) {\n this.owner.selection.decreaseIndent();\n }\n event.preventDefault();\n break;\n case 188:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.onApplyCharacterFormat('fontSize', 'decrement', true);\n }\n break;\n case 190:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.onApplyCharacterFormat('fontSize', 'increment', true);\n }\n break;\n case 187:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode) {\n this.toggleBaselineAlignment('Superscript');\n }\n }\n }\n else if (!shift && ctrl && alt) {\n switch (key) {\n case 72:\n event.preventDefault();\n if (!this.owner.isReadOnlyMode && this.owner.isDocumentLoaded) {\n this.toggleHighlightColor();\n }\n break;\n }\n }\n else {\n switch (key) {\n case 8:\n event.preventDefault();\n this.handleBackKey();\n break;\n case 9:\n event.preventDefault();\n if (this.owner.acceptTab) {\n this.selection.handleTabKey(true, false);\n }\n break;\n case 13:\n event.preventDefault();\n this.handleEnterKey();\n break;\n case 46:\n this.handleDelete();\n event.preventDefault();\n break;\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.handleShiftEnter = function () {\n if (!this.owner.isReadOnlyMode) {\n this.handleTextInput('\\v');\n }\n this.selection.checkForCursorVisibility();\n };\n /**\n * Handles back key.\n * @private\n */\n Editor.prototype.handleBackKey = function () {\n if (!this.owner.isReadOnlyMode) {\n this.owner.editorModule.onBackSpace();\n }\n this.selection.checkForCursorVisibility();\n };\n /**\n * Handles delete\n * @private\n */\n Editor.prototype.handleDelete = function () {\n if (!this.owner.isReadOnlyMode) {\n this.owner.editorModule.onDelete();\n }\n this.selection.checkForCursorVisibility();\n };\n /**\n * Handles enter key.\n * @private\n */\n Editor.prototype.handleEnterKey = function () {\n if (!this.owner.isReadOnlyMode) {\n if (Browser.isDevice) {\n this.viewer.isCompositionStart = false;\n }\n this.owner.editorModule.onEnter();\n }\n this.selection.checkForCursorVisibility();\n };\n /**\n * @private\n */\n Editor.prototype.handleTextInput = function (text) {\n var _this = this;\n if (!this.owner.isReadOnlyMode) {\n if (this.animationTimer) {\n clearTimeout(this.animationTimer);\n }\n classList(this.selection.caret, [], ['e-de-cursor-animation']);\n this.owner.editorModule.insertText(text, false);\n /* tslint:disable:align */\n this.animationTimer = setTimeout(function () {\n if (_this.animationTimer) {\n clearTimeout(_this.animationTimer);\n }\n if (_this.selection && _this.selection.caret) {\n classList(_this.selection.caret, ['e-de-cursor-animation'], []);\n }\n }, 600);\n }\n this.selection.checkForCursorVisibility();\n };\n /**\n * Copies to format.\n * @param {WCharacterFormat} format\n * @private\n */\n Editor.prototype.copyInsertFormat = function (format, copy) {\n var insertFormat = new WCharacterFormat();\n var sFormat = this.selection.characterFormat;\n if (copy) {\n insertFormat.copyFormat(format);\n }\n if (!isNullOrUndefined(sFormat.bold) && format.bold !== sFormat.bold) {\n insertFormat.bold = sFormat.bold;\n }\n if (!isNullOrUndefined(sFormat.italic) && format.italic !== sFormat.italic) {\n insertFormat.italic = sFormat.italic;\n }\n if (sFormat.fontSize > 0 && format.fontSize !== sFormat.fontSize) {\n insertFormat.fontSize = sFormat.fontSize;\n }\n if (!isNullOrUndefined(sFormat.fontFamily) && format.fontFamily !== sFormat.fontFamily) {\n insertFormat.fontFamily = sFormat.fontFamily;\n }\n if (!isNullOrUndefined(sFormat.highlightColor) && format.highlightColor !== sFormat.highlightColor) {\n insertFormat.highlightColor = sFormat.highlightColor;\n }\n if (!isNullOrUndefined(sFormat.baselineAlignment) && format.baselineAlignment !== sFormat.baselineAlignment) {\n insertFormat.baselineAlignment = sFormat.baselineAlignment;\n }\n if (!isNullOrUndefined(sFormat.fontColor) && format.fontColor !== sFormat.fontColor) {\n insertFormat.fontColor = sFormat.fontColor;\n }\n if (!isNullOrUndefined(sFormat.underline) && format.underline !== sFormat.underline) {\n insertFormat.underline = sFormat.underline;\n }\n if (!isNullOrUndefined(sFormat.strikethrough) && format.strikethrough !== sFormat.strikethrough) {\n insertFormat.strikethrough = sFormat.strikethrough;\n }\n return insertFormat;\n };\n /**\n * Inserts the specified text at cursor position\n * @param {string} text\n * @param {boolean} isReplace\n * @private\n */\n //tslint:disable: max-func-body-length\n Editor.prototype.insertText = function (text, isReplace) {\n var selection = this.viewer.selection;\n var insertPosition;\n var isRemoved = true;\n this.isListTextSelected();\n this.initHistory('Insert');\n var paragraphInfo = this.getParagraphInfo(selection.start);\n this.viewer.selection.editPosition = this.getHierarchicalIndex(paragraphInfo.paragraph, paragraphInfo.offset.toString());\n if ((!selection.isEmpty && !this.viewer.selection.isImageSelected) ||\n this.viewer.isListTextSelected && selection.contextType === 'List') {\n selection.isSkipLayouting = true;\n selection.skipFormatRetrieval = true;\n isRemoved = this.removeSelectedContents(selection);\n selection.skipFormatRetrieval = false;\n selection.isSkipLayouting = false;\n }\n paragraphInfo = this.getParagraphInfo(selection.start);\n if (isRemoved) {\n selection.owner.isShiftingEnabled = true;\n this.updateInsertPosition();\n insertPosition = selection.start;\n if (insertPosition.paragraph.isEmpty()) {\n var span = new TextElementBox();\n var insertFormat = this.copyInsertFormat(insertPosition.paragraph.characterFormat, true);\n span.characterFormat.copyFormat(insertFormat);\n span.text = text;\n span.line = insertPosition.paragraph.childWidgets[0];\n span.margin = new Margin(0, 0, 0, 0);\n span.line.children.push(span);\n if ((insertPosition.paragraph.paragraphFormat.textAlignment === 'Center'\n || insertPosition.paragraph.paragraphFormat.textAlignment === 'Right') &&\n insertPosition.paragraph.paragraphFormat.listFormat.listId === -1) {\n insertPosition.paragraph.x = this.viewer.clientActiveArea.x;\n }\n this.viewer.layout.reLayoutParagraph(insertPosition.paragraph, 0, 0);\n }\n else {\n var indexInInline = 0;\n var inlineObj = insertPosition.currentWidget.getInline(insertPosition.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n // Todo: compare selection format\n var insertFormat = this.copyInsertFormat(inline.characterFormat, true);\n if (insertFormat.isSameFormat(inline.characterFormat)) {\n this.insertTextInline(inline, selection, text, indexInInline);\n }\n else {\n var tempSpan = new TextElementBox();\n tempSpan.text = text;\n tempSpan.line = inline.line;\n tempSpan.characterFormat.copyFormat(insertFormat);\n var insertIndex = inline.indexInOwner;\n if (indexInInline === inline.length) {\n inline.line.children.splice(insertIndex + 1, 0, tempSpan);\n }\n else if (indexInInline === 0) {\n inline.line.children.splice(insertIndex, 0, tempSpan);\n }\n else {\n if (inline instanceof TextElementBox) {\n var splittedSpan = new TextElementBox();\n splittedSpan.line = inline.line;\n splittedSpan.characterFormat.copyFormat(inline.characterFormat);\n splittedSpan.text = inline.text.substring(indexInInline);\n inline.text = inline.text.slice(0, indexInInline);\n inline.line.children.splice(insertIndex + 1, 0, splittedSpan);\n }\n inline.line.children.splice(insertIndex + 1, 0, tempSpan);\n }\n this.viewer.layout.reLayoutParagraph(insertPosition.paragraph, inline.line.indexInOwner, 0);\n }\n }\n this.setPositionParagraph(paragraphInfo.paragraph, paragraphInfo.offset + text.length, true);\n this.updateEndPosition();\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(this.editorHistory) && !isNullOrUndefined(this.editorHistory.currentHistoryInfo) && (this.editorHistory.currentHistoryInfo.action === 'ListSelect') &&\n this.viewer.isListTextSelected) {\n this.editorHistory.updateHistory();\n this.editorHistory.updateComplexHistory();\n }\n // if (!isNullOrUndefined(selection.currentHistoryInfo) && (selection.currentHistoryInfo.action === 'MultiSelection')) {\n // this.updateComplexHistory();\n // } else { \n this.reLayout(selection);\n // }\n }\n else {\n // selection.selectContent(selection.start, true);\n }\n // insertFormat.destroy();\n if (!isReplace && isRemoved && (text === ' ' || text === '\\t' || text === '\\v')) {\n var hyperlinkField = selection.getHyperlinkField();\n var isSelectionOnHyperlink = !isNullOrUndefined(hyperlinkField);\n var isList = false;\n if (!(text === '\\v')) {\n isList = this.checkAndConvertList(selection, text === '\\t');\n }\n if (isSelectionOnHyperlink) {\n return;\n }\n if (!isList) {\n //Checks if the previous text is URL, then it is auto formatted to hyperlink.\n this.checkAndConvertToHyperlink(selection, false);\n }\n }\n };\n //Auto convert List\n Editor.prototype.checkAndConvertList = function (selection, isTab) {\n var list = selection.paragraphFormat.getList();\n if (!isNullOrUndefined(list)) {\n return false;\n }\n var convertList = false;\n var isLeadingZero = false;\n var indexInInline = 0;\n var inlineObj = selection.start.currentWidget.getInline(selection.start.offset - 1, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!(inline instanceof TextElementBox)) {\n return false;\n }\n var span = inline;\n var text = span.text.substring(0, indexInInline);\n var tabValue = 0;\n var length = 0;\n while (!isNullOrUndefined(span.previousNode)) {\n // tslint:disable-next-line:max-line-length\n if (span.previousNode instanceof TextElementBox && (span.previousNode.text === '\\t' || span.previousNode.text.trim().length === 0)) {\n (span.previousNode.text === '\\t') ? tabValue += 36 : length = span.previousNode.text.length * 2.5;\n span = span.previousNode;\n continue;\n }\n return false;\n }\n span = inline;\n var index = 0;\n var tabIndex = text.lastIndexOf('\\t');\n index = (tabIndex >= 0) ? tabIndex + 1 : text.lastIndexOf(' ') + 1;\n while (span.previousNode instanceof TextElementBox && index === 0) {\n span = span.previousNode;\n var previousText = span.text;\n tabIndex = previousText.lastIndexOf('\\t');\n index = (tabIndex >= 0) ? tabIndex + 1 : previousText.lastIndexOf(' ') + 1;\n text = span.text + text;\n text = text.substring(index);\n }\n text = HelperMethods.trimStart(text);\n var numberFormat = text.substring(1, 2);\n var listLevelPattern = this.getListLevelPattern(text.substring(0, 1));\n if (listLevelPattern !== 'None' && this.checkNumberFormat(numberFormat, listLevelPattern === 'Bullet', text)) {\n convertList = true;\n }\n else if (this.checkLeadingZero(text)) {\n isLeadingZero = true;\n convertList = true;\n }\n if (convertList) {\n this.initComplexHistory('AutoList');\n var paragraph = inline.paragraph;\n // tslint:disable-next-line:max-line-length\n selection.start.setPositionParagraph(paragraph.childWidgets[0], paragraph.childWidgets[0].getOffset(inline, indexInInline + 1));\n selection.end.setPositionParagraph(paragraph.childWidgets[0], 0);\n this.initHistory('Delete');\n this.deleteSelectedContents(selection, false);\n this.reLayout(selection, false);\n var followCharacter = isTab ? 'Tab' : 'Space';\n numberFormat = !isLeadingZero ? '%1' + numberFormat : '%1' + text.substring(text.length - 1, text.length);\n var leadingZeroText = text.substring(text.length - 3, text.length - 1);\n listLevelPattern = !isLeadingZero ? listLevelPattern : this.getListLevelPattern(leadingZeroText);\n var listLevel = new WListLevel(undefined);\n listLevel.listLevelPattern = listLevelPattern;\n if (listLevelPattern === 'Bullet') {\n if (text === '*') {\n listLevel.numberFormat = '\\uf0b7';\n listLevel.characterFormat.fontFamily = 'Symbol';\n }\n else if (text === '-') {\n listLevel.numberFormat = '-';\n }\n }\n else {\n listLevel.numberFormat = numberFormat;\n }\n listLevel.followCharacter = followCharacter;\n var leftIndent = selection.paragraphFormat.leftIndent;\n if (tabValue !== 0 || length !== 0) {\n listLevel.paragraphFormat.leftIndent = leftIndent + 18 + tabValue + length;\n }\n else if (indexInInline > 2) {\n listLevel.paragraphFormat.leftIndent = leftIndent + (indexInInline - 2) * 2.5 + 18;\n }\n else if (leftIndent > 0) {\n listLevel.paragraphFormat.leftIndent = leftIndent + 18;\n }\n else {\n listLevel.paragraphFormat.leftIndent = 36;\n }\n listLevel.paragraphFormat.firstLineIndent = -18;\n if ((!isLeadingZero && text.substring(0, 1) === '0') || leadingZeroText === '00') {\n listLevel.startAt = 0;\n }\n else {\n listLevel.startAt = 1;\n }\n this.autoConvertList(selection, listLevel);\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentHistoryInfo)) {\n this.editorHistory.updateComplexHistory();\n }\n else {\n this.reLayout(selection);\n }\n }\n return convertList;\n };\n Editor.prototype.getListLevelPattern = function (value) {\n switch (value) {\n case '0':\n case '1':\n return 'Arabic';\n case 'I':\n return 'UpRoman';\n case 'i':\n return 'LowRoman';\n case 'A':\n return 'UpLetter';\n case 'a':\n return 'LowLetter';\n case '*':\n case '-':\n return 'Bullet';\n case '00':\n case '01':\n return 'LeadingZero';\n default:\n return 'None';\n }\n };\n Editor.prototype.autoConvertList = function (selection, listLevel) {\n var start = selection.start;\n if (!selection.isForward) {\n start = selection.end;\n }\n var newList = new WList();\n if (this.viewer.lists.length > 0) {\n newList.listId = this.viewer.lists[this.viewer.lists.length - 1].listId + 1;\n }\n else {\n newList.listId = 0;\n }\n var newAbstractList = new WAbstractList();\n var layout = this.viewer;\n if (layout.abstractLists.length > 0) {\n newAbstractList.abstractListId = layout.abstractLists[layout.abstractLists.length - 1].abstractListId + 1;\n }\n else {\n newAbstractList.abstractListId = 0;\n }\n newList.abstractListId = newAbstractList.abstractListId;\n layout.abstractLists.push(newAbstractList);\n newAbstractList.levels.push(listLevel);\n listLevel.ownerBase = newAbstractList;\n selection.paragraphFormat.setList(newList);\n selection.paragraphFormat.listLevelNumber = 0;\n };\n Editor.prototype.checkNumberFormat = function (numberFormat, isBullet, text) {\n if (isBullet) {\n return numberFormat === '';\n }\n else {\n var index = text.indexOf(numberFormat);\n return (numberFormat === '.' || numberFormat === ')'\n || numberFormat === '>' || numberFormat === '-') && text.substring(index, text.length - 1) === '';\n }\n };\n Editor.prototype.checkLeadingZero = function (text) {\n var j;\n var isZero = false;\n for (var i = 0; i <= text.length - 1; i++) {\n if (text.charAt(i) === '0') {\n isZero = true;\n continue;\n }\n j = i;\n break;\n }\n var numberFormat = undefined;\n if (text.charAt(j) === '1') {\n numberFormat = text.charAt(j + 1);\n }\n else {\n numberFormat = text.charAt(j);\n }\n return isZero && this.checkNumberFormat(numberFormat, false, text);\n };\n Editor.prototype.getPageFromBlockWidget = function (block) {\n var page = undefined;\n if (block.containerWidget instanceof BodyWidget) {\n page = block.containerWidget.page;\n }\n else if (block.containerWidget instanceof HeaderFooterWidget) {\n page = block.containerWidget.page;\n }\n else if (block.containerWidget instanceof TableCellWidget) {\n page = block.containerWidget.bodyWidget.page;\n }\n return page;\n };\n /**\n * @private\n */\n Editor.prototype.insertTextInline = function (element, selection, text, index) {\n if (element instanceof TextElementBox) {\n element.text = HelperMethods.insert(element.text, index, text);\n var paragraph = element.line.paragraph;\n var lineIndex = paragraph.childWidgets.indexOf(element.line);\n var elementIndex = element.line.children.indexOf(element);\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, elementIndex);\n }\n else if (element instanceof ImageElementBox) {\n this.insertImageText(element, selection, text, index);\n }\n else if (element instanceof FieldElementBox) {\n if (element.fieldType === 0) {\n this.insertFieldBeginText(element, selection, text, index);\n }\n else if (element.fieldType === 2) {\n this.insertFieldSeparatorText(element, selection, text, index);\n }\n else {\n this.insertFieldEndText(element, selection, text, index);\n }\n }\n else if (element instanceof BookmarkElementBox) {\n this.insertBookMarkText(element, selection, text, index);\n }\n };\n Editor.prototype.insertFieldBeginText = function (fieldBegin, selection, text, index) {\n var spanObj = new TextElementBox();\n spanObj.text = text;\n var lineIndex = fieldBegin.line.paragraph.childWidgets.indexOf(fieldBegin.line);\n var spanIndex = fieldBegin.line.children.indexOf(fieldBegin);\n spanObj.characterFormat.copyFormat(fieldBegin.characterFormat);\n fieldBegin.line.children.splice(spanIndex, 0, spanObj);\n spanObj.line = fieldBegin.line;\n this.viewer.layout.reLayoutParagraph(fieldBegin.line.paragraph, lineIndex, spanIndex);\n };\n Editor.prototype.insertBookMarkText = function (element, selection, text, index) {\n var spanObj = new TextElementBox();\n spanObj.text = text;\n var lineIndex = element.line.paragraph.childWidgets.indexOf(element.line);\n var spanIndex = element.line.children.indexOf(element);\n spanObj.characterFormat.copyFormat(element.characterFormat);\n element.line.children.splice(spanIndex, 0, spanObj);\n spanObj.line = element.line;\n this.viewer.layout.reLayoutParagraph(element.line.paragraph, lineIndex, spanIndex);\n };\n Editor.prototype.insertFieldSeparatorText = function (fieldSeparator, selection, text, index) {\n var previousInline = selection.getPreviousTextInline(fieldSeparator);\n var nextInline = selection.getNextTextInline(fieldSeparator);\n var span = new TextElementBox();\n span.text = text;\n var spanIndex = fieldSeparator.line.children.indexOf(fieldSeparator);\n if (index === fieldSeparator.length) {\n spanIndex++;\n }\n if (isNullOrUndefined(previousInline) && isNullOrUndefined(nextInline)) {\n span.characterFormat.copyFormat(fieldSeparator.line.paragraph.characterFormat);\n }\n else if (isNullOrUndefined(previousInline)) {\n span.characterFormat.copyFormat(nextInline.characterFormat);\n }\n else {\n span.characterFormat.copyFormat(previousInline.characterFormat);\n }\n fieldSeparator.line.children.splice(spanIndex, 0, span);\n span.line = fieldSeparator.line;\n var lineIndex = fieldSeparator.line.paragraph.childWidgets.indexOf(fieldSeparator.line);\n this.viewer.layout.reLayoutParagraph(fieldSeparator.line.paragraph, lineIndex, spanIndex);\n };\n Editor.prototype.insertFieldEndText = function (fieldEnd, selection, text, index) {\n var span = new TextElementBox();\n span.text = text;\n var spanIndex = fieldEnd.line.children.indexOf(fieldEnd);\n span.characterFormat.copyFormat(fieldEnd.characterFormat);\n fieldEnd.line.children.splice(spanIndex + 1, 0, span);\n span.line = fieldEnd.line;\n var lineIndex = fieldEnd.line.paragraph.childWidgets.indexOf(fieldEnd.line);\n this.viewer.layout.reLayoutParagraph(fieldEnd.line.paragraph, lineIndex, spanIndex);\n };\n Editor.prototype.insertImageText = function (image, selection, text, index) {\n var previousInlineObj = selection.getPreviousTextInline(image);\n var nextInlineObj = selection.getNextTextInline(image);\n var line = image.line;\n var element = new TextElementBox();\n var paragraph = line.paragraph;\n var lineIndex = paragraph.childWidgets.indexOf(line);\n element.text = text;\n var spanIndex = line.children.indexOf(image);\n if (index === image.length) {\n spanIndex++;\n }\n if (isNullOrUndefined(previousInlineObj) && isNullOrUndefined(nextInlineObj)) {\n element.characterFormat.copyFormat(paragraph.characterFormat);\n }\n else if (isNullOrUndefined(previousInlineObj)) {\n element.characterFormat.copyFormat(nextInlineObj.characterFormat);\n }\n else {\n element.characterFormat.copyFormat(previousInlineObj.characterFormat);\n }\n line.children.splice(spanIndex, 0, element);\n element.line = line;\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, spanIndex);\n };\n /**\n * @private\n */\n Editor.prototype.isListTextSelected = function () {\n if (this.viewer.isListTextSelected) {\n this.initComplexHistory('ListSelect');\n // tslint:disable-next-line:max-line-length\n if (this.viewer.selection.start.paragraph.paragraphFormat.listFormat && this.viewer.selection.start.paragraph.paragraphFormat.listFormat.listId !== -1) {\n this.onApplyList(undefined);\n }\n }\n };\n //Auto Format and insert Hyperlink Implementation starts\n Editor.prototype.checkAndConvertToHyperlink = function (selection, isEnter, paragraph) {\n var text;\n var span;\n if (isEnter) {\n span = paragraph.lastChild.children[paragraph.lastChild.children.length - 1];\n text = span.text;\n }\n else {\n var indexInInline = 0;\n var inlineObj = selection.start.currentWidget.getInline(selection.start.offset - 1, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!(inline instanceof TextElementBox)) {\n return;\n }\n span = inline;\n text = span.text.substring(0, indexInInline);\n }\n var index = 0;\n var tabCharIndex = text.lastIndexOf('\\t');\n index = (tabCharIndex >= 0) ? tabCharIndex + 1 : text.lastIndexOf(' ') + 1;\n while (span.previousNode instanceof TextElementBox && index === 0) {\n span = span.previousNode;\n var previousText = span.text;\n tabCharIndex = previousText.lastIndexOf('\\t');\n index = (tabCharIndex >= 0) ? tabCharIndex + 1 : previousText.lastIndexOf(' ') + 1;\n text = span.text + text;\n }\n text = text.substring(index);\n var lowerCaseText = text.toLowerCase();\n var containsURL = false;\n if (lowerCaseText.substring(0, 8) === 'file:///'\n || (lowerCaseText.substring(0, 7) === 'http://' && lowerCaseText.length > 7)\n || (lowerCaseText.substring(0, 8) === 'https://' && lowerCaseText.length > 8)\n || (lowerCaseText.substring(0, 4) === 'www.' && lowerCaseText.length > 4)\n || (lowerCaseText.substring(0, 3) === '\\\\' && lowerCaseText.length > 3)\n || (lowerCaseText.substring(0, 7) === 'mailto:' && lowerCaseText.length > 7)) {\n containsURL = true;\n if (lowerCaseText.substring(0, 4) === 'www.' && lowerCaseText.length > 4) {\n text = 'http://' + text;\n }\n }\n else {\n var atIndex = text.indexOf('@');\n var dotIndex = text.indexOf('.');\n if (atIndex > 0 && atIndex < dotIndex && dotIndex < text.length - 1) {\n containsURL = true;\n text = 'mailto:' + text;\n }\n }\n if (containsURL) {\n var startPos = new TextPosition(this.viewer.owner);\n startPos.setPositionParagraph(span.line, span.line.getOffset(span, index));\n var endPos = new TextPosition(this.viewer.owner);\n if (isEnter) {\n endPos.setPositionParagraph(span.line, span.line.getEndOffset());\n }\n else {\n if (selection.end.currentWidget.children.length === 0 && selection.end.offset === 0) {\n var prevLine = selection.end.currentWidget.previousLine;\n endPos.setPositionParagraph(prevLine, prevLine.getEndOffset());\n }\n else {\n endPos.setPositionParagraph(selection.end.currentWidget, selection.end.offset - 1);\n }\n }\n this.autoFormatHyperlink(selection, text, startPos, endPos);\n }\n };\n Editor.prototype.autoFormatHyperlink = function (selection, url, startPosition, endPosition) {\n this.initComplexHistory('AutoFormatHyperlink');\n var blockInfo = this.getParagraphInfo(startPosition);\n var start = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n if (this.editorHistory && this.editorHistory.currentHistoryInfo) {\n this.editorHistory.currentHistoryInfo.insertPosition = start;\n }\n // Moves the selection to URL text start and end position.\n selection.start.setPositionInternal(startPosition);\n selection.end.setPositionInternal(endPosition);\n // Preserves the character format for hyperlink field.\n var temp = this.getCharacterFormat(selection);\n var format = new WCharacterFormat();\n format.copyFormat(temp);\n var fieldEnd = this.createHyperlinkElement(url, startPosition, endPosition, format);\n // Moves the selection to the end of field end position.\n selection.start.setPositionParagraph(fieldEnd.line, (fieldEnd.line).getOffset(fieldEnd, 1));\n // Moves to next text position. (To achieve common behavior for space and enter).\n selection.start.moveNextPosition();\n selection.end.setPositionInternal(selection.start);\n blockInfo = this.getParagraphInfo(selection.end);\n var end = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n if (this.editorHistory && this.editorHistory.currentHistoryInfo) {\n this.editorHistory.currentHistoryInfo.endPosition = end;\n this.editorHistory.updateComplexHistory();\n this.reLayout(selection);\n }\n else {\n this.updateComplexWithoutHistory(0, start, end);\n }\n };\n Editor.prototype.appylingHyperlinkFormat = function (selection) {\n this.initHistory('Underline');\n this.updateCharacterFormatWithUpdate(selection, 'underline', 'Single', false);\n if (this.editorHistory) {\n this.editorHistory.updateHistory();\n }\n this.reLayout(selection, false);\n // Applies font color for field result.\n this.initHistory('FontColor');\n this.updateCharacterFormatWithUpdate(selection, 'fontColor', '#0563c1', false);\n if (this.editorHistory) {\n this.editorHistory.updateHistory();\n }\n this.reLayout(selection, false);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.createHyperlinkElement = function (url, startPosition, endPosition, format) {\n var selection = this.selection;\n this.viewer.layout.allowLayout = false;\n this.appylingHyperlinkFormat(selection);\n this.viewer.layout.allowLayout = true;\n // Adds the field end at the URL text end position.\n var fieldEnd = new FieldElementBox(1);\n fieldEnd.characterFormat.copyFormat(format);\n fieldEnd.line = selection.end.currentWidget;\n selection.start.setPositionInternal(selection.end);\n // this.insertElementInCurrentLine(selection, fieldEnd, true);\n this.initInsertInline(fieldEnd);\n // Moves the selection to URL text start position. \n selection.start.setPositionInternal(startPosition);\n selection.end.setPositionInternal(selection.start);\n // Adds field begin, field code and field separator at the URL text start position.\n var begin = this.insertHyperlinkfield(selection, format, url);\n var lineIndex = selection.start.paragraph.childWidgets.indexOf(begin.line);\n var index = begin.line.children.indexOf(begin);\n fieldEnd.linkFieldCharacter(this.viewer);\n this.viewer.layout.reLayoutParagraph(selection.start.paragraph, lineIndex, index);\n return fieldEnd;\n };\n Editor.prototype.insertHyperlinkfield = function (selection, format, url, isBookmark) {\n // Adds field begin, field code and field separator at the URL text start position.\n var begin = new FieldElementBox(0);\n begin.characterFormat.copyFormat(format);\n begin.line = selection.start.currentWidget;\n this.initInsertInline(begin);\n var span = new TextElementBox();\n span.characterFormat.copyFormat(format);\n if (isBookmark) {\n span.text = ' HYPERLINK \\\\l \\\"' + url + '\\\" ';\n }\n else {\n span.text = ' HYPERLINK \\\"' + url + '\\\" ';\n }\n span.line = selection.start.currentWidget;\n this.initInsertInline(span);\n var separator = new FieldElementBox(2);\n separator.characterFormat.copyFormat(format);\n separator.line = selection.start.currentWidget;\n this.initInsertInline(separator);\n return begin;\n };\n Editor.prototype.unLinkFieldCharacter = function (inline) {\n if (inline instanceof FieldElementBox && inline.fieldType === 0) {\n if (inline.fieldEnd) {\n if (this.viewer) {\n this.viewer.fieldToLayout = inline;\n this.viewer.fieldEndParagraph = inline.line.paragraph;\n }\n // inline.line.paragraph.addFieldCharacter(inline.fieldEnd);\n inline.fieldEnd = undefined;\n }\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 2) {\n if (!isNullOrUndefined(inline.fieldEnd)) {\n if (this.viewer) {\n this.viewer.fieldToLayout = inline.fieldBegin;\n this.viewer.fieldEndParagraph = inline.line.paragraph;\n }\n inline.fieldBegin.fieldSeparator = undefined;\n inline.fieldEnd.fieldSeparator = undefined;\n }\n }\n else if (inline instanceof FieldElementBox && inline.fieldType === 1) {\n if (inline.fieldBegin) {\n if (!isNullOrUndefined(this.viewer)) {\n this.viewer.fieldToLayout = inline.fieldBegin;\n this.viewer.fieldEndParagraph = inline.line.paragraph;\n }\n var fieldIndex = this.viewer.fields.indexOf(inline.fieldBegin);\n if (fieldIndex !== -1) {\n this.viewer.fields.splice(fieldIndex, 1);\n }\n inline.fieldBegin = undefined;\n }\n }\n };\n Editor.prototype.getCharacterFormat = function (selection) {\n if (selection.start.paragraph.isEmpty()) {\n return selection.start.paragraph.characterFormat;\n }\n else {\n var info = selection.start.currentWidget.getInline(selection.start.offset, 0);\n return info.element.characterFormat;\n }\n };\n /**\n * Insert Hyperlink\n * @param {string} url\n * @param {string} displayText\n * @param {boolean} remove\n * @private\n */\n Editor.prototype.insertHyperlink = function (url, displayText, remove, isBookmark) {\n var selection = this.viewer.selection;\n if (selection.start.paragraph.associatedCell !== selection.end.paragraph.associatedCell) {\n return;\n }\n if (remove) {\n //Empty selection Hyperlink insert\n this.insertHyperlinkInternal(selection, url, displayText, isBookmark);\n }\n else {\n //Non-Empty Selection- change the selected text to Field \n // this.preservedFontCol = this.getFontColor();\n var startPosition = selection.start;\n var endPosition = selection.end;\n if (!selection.isForward) {\n startPosition = selection.end;\n endPosition = selection.start;\n }\n var fieldStartPosition = new TextPosition(this.viewer.owner);\n fieldStartPosition.setPositionInternal(startPosition);\n var temp = this.getCharacterFormat(selection);\n var format = new WCharacterFormat(undefined);\n format.copyFormat(temp);\n this.initComplexHistory('InsertHyperlink');\n var blockInfo = this.getParagraphInfo(startPosition);\n var start = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n if (this.editorHistory && this.editorHistory.currentHistoryInfo) {\n // tslint:disable-next-line:max-line-length\n this.editorHistory.currentHistoryInfo.insertPosition = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n }\n this.appylingHyperlinkFormat(selection);\n this.viewer.layout.allowLayout = true;\n startPosition.setPositionInternal(endPosition);\n // Adds the field end at the URL text end position.\n var fieldEnd = new FieldElementBox(1);\n fieldEnd.characterFormat.copyFormat(format);\n fieldEnd.line = selection.end.currentWidget;\n startPosition.setPositionInternal(endPosition);\n // this.insertElementInCurrentLine(selection, fieldEnd, true);\n this.initInsertInline(fieldEnd);\n // Moves the selection to URL text start position. \n startPosition.setPositionInternal(fieldStartPosition);\n endPosition.setPositionInternal(startPosition);\n // Adds field begin, field code and field separator at the URL text start position.\n var begin = this.insertHyperlinkfield(selection, format, url, isBookmark);\n fieldEnd.linkFieldCharacter(this.viewer);\n var lineIndex = selection.start.paragraph.childWidgets.indexOf(begin.line);\n var index = begin.line.children.indexOf(begin);\n this.viewer.layout.reLayoutParagraph(selection.start.paragraph, lineIndex, index);\n var lineWidget = fieldEnd.line;\n selection.selects(lineWidget, lineWidget.getOffset(fieldEnd, fieldEnd.length), true);\n blockInfo = this.getParagraphInfo(endPosition);\n var end = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n if (this.editorHistory && this.editorHistory.currentHistoryInfo) {\n // tslint:disable-next-line:max-line-length\n this.editorHistory.currentHistoryInfo.endPosition = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n this.editorHistory.updateComplexHistory();\n }\n else {\n this.updateComplexWithoutHistory(1, start, end);\n }\n }\n };\n Editor.prototype.insertHyperlinkInternal = function (selection, url, displayText, isBookmark) {\n if (isNullOrUndefined(selection.start)) {\n return;\n }\n if (this.editHyperlink(selection, url, displayText)) {\n return;\n }\n this.initHistory('InsertHyperlink');\n var isRemoved = true;\n if (!selection.isEmpty) {\n isRemoved = this.removeSelectedContents(selection);\n }\n if (isRemoved) {\n // Preserves the character format for hyperlink field.\n var temp = this.getCharacterFormat(selection);\n var format = new WCharacterFormat();\n format.copyFormat(temp);\n this.insertHyperlinkByFormat(selection, url, displayText, format, isBookmark);\n }\n //else\n // this.Select(Start, true);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.insertHyperlinkByFormat = function (selection, url, displayText, format, isBookmark) {\n this.updateInsertPosition();\n selection.owner.isShiftingEnabled = true;\n var indexInInline = 0;\n var initial = indexInInline;\n var element = [];\n var fieldBegin = new FieldElementBox(0);\n element.push(fieldBegin);\n var span = new TextElementBox();\n if (isBookmark) {\n span.text = ' HYPERLINK \\\\l \\\"' + url + '\\\" ';\n }\n else {\n span.text = ' HYPERLINK \\\"' + url + '\\\" ';\n }\n element.push(span);\n var fieldSeparator = new FieldElementBox(2);\n element.push(fieldSeparator);\n if (!isNullOrUndefined(displayText) && displayText !== '') {\n span = new TextElementBox();\n span.characterFormat.underline = 'Single';\n span.characterFormat.fontColor = '#0563c1';\n span.text = displayText;\n element.push(span);\n }\n var fieldEnd = new FieldElementBox(1);\n element.push(fieldEnd);\n this.insertElement(element);\n var paragraph = selection.start.paragraph;\n fieldEnd.linkFieldCharacter(this.viewer);\n if (this.viewer.fields.indexOf(fieldBegin) === -1) {\n this.viewer.fields.push(fieldBegin);\n }\n var offset = fieldEnd.line.getOffset(fieldEnd, 1);\n selection.selects(fieldEnd.line, fieldEnd.line.getOffset(fieldEnd, fieldEnd.length), true);\n this.updateEndPosition();\n this.reLayout(selection, true);\n };\n Editor.prototype.initInsertInline = function (element, insertHyperlink) {\n this.initHistory('InsertInline');\n this.insertInlineInSelection(this.viewer.selection, element);\n if (this.editorHistory) {\n this.editorHistory.updateHistory();\n }\n };\n /**\n * @private\n */\n Editor.prototype.insertElementInCurrentLine = function (selection, inline, isReLayout) {\n if (this.checkIsNotRedoing()) {\n selection.owner.isShiftingEnabled = true;\n }\n if (!selection.isEmpty) {\n this.removeSelectedContents(selection);\n }\n this.updateInsertPosition();\n this.insertElement([inline]);\n if (this.checkEndPosition(selection)) {\n this.updateHistoryPosition(selection.start, false);\n }\n this.fireContentChange();\n };\n /**\n * Edit Hyperlink\n * @param {Selection} selection\n * @param {string} url\n * @param {string} displayText\n * @private\n */\n Editor.prototype.editHyperlink = function (selection, url, displayText, isBookmark) {\n var fieldBegin = selection.getHyperlinkField();\n if (isNullOrUndefined(fieldBegin)) {\n return false;\n }\n this.initHistory('InsertHyperlink');\n this.editHyperlinkInternal = isNullOrUndefined(this.editorHistory)\n || (this.editorHistory && isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo));\n var fieldResult = '';\n var isNestedField = false;\n // Preserves the character format for hyperlink field.\n var temp = this.getCharacterFormat(selection);\n var format = new WCharacterFormat();\n format.copyFormat(temp);\n var fieldSeparator = undefined;\n if (!isNullOrUndefined(fieldBegin.fieldSeparator)) {\n fieldSeparator = fieldBegin.fieldSeparator;\n // tslint:disable-next-line:max-line-length\n var fieldObj = selection.getHyperlinkDisplayText(fieldBegin.fieldSeparator.line.paragraph, fieldBegin.fieldSeparator, fieldBegin.fieldEnd, isNestedField, format);\n fieldResult = fieldObj.displayText;\n isNestedField = fieldObj.isNestedField;\n format = fieldObj.format;\n }\n var offset = fieldBegin.line.getOffset(fieldBegin, 0);\n selection.start.setPositionParagraph(fieldBegin.line, offset);\n offset = fieldBegin.fieldEnd.line.getOffset(fieldBegin.fieldEnd, 1);\n selection.end.setPositionParagraph(fieldBegin.fieldEnd.line, offset);\n this.deleteSelectedContents(selection, false);\n if (!isNestedField && fieldResult !== displayText || isNullOrUndefined(fieldSeparator)) {\n this.insertHyperlinkByFormat(selection, url, displayText, format, isBookmark);\n }\n else {\n //Modify the new hyperlink url. Inserts field begin, url and field separator.\n this.updateInsertPosition();\n var newFieldBegin = new FieldElementBox(0);\n newFieldBegin.characterFormat.copyFormat(fieldBegin.characterFormat);\n newFieldBegin.line = selection.start.currentWidget;\n this.insertInlineInternal(newFieldBegin);\n var span = new TextElementBox();\n span.characterFormat.copyFormat(fieldBegin.characterFormat);\n if (isBookmark) {\n span.text = ' HYPERLINK \\\\l \\\"' + url + '\\\" ';\n }\n else {\n span.text = ' HYPERLINK \\\"' + url + '\\\" ';\n }\n span.line = selection.start.currentWidget;\n this.insertInlineInternal(span);\n var nodes = this.editorHistory && this.editorHistory.currentBaseHistoryInfo ?\n this.editorHistory.currentBaseHistoryInfo.removedNodes : this.nodes;\n this.insertClonedFieldResult(selection, nodes, fieldSeparator);\n var fieldEnd = selection.end.currentWidget.getInline(selection.end.offset, 0).element;\n fieldEnd.linkFieldCharacter(this.viewer);\n var paragraph = newFieldBegin.line.paragraph;\n var lineIndex = newFieldBegin.line.paragraph.childWidgets.indexOf(newFieldBegin.line);\n var elementIndex = newFieldBegin.line.children.indexOf(newFieldBegin);\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, elementIndex);\n selection.selects(newFieldBegin.fieldEnd.line, offset, true);\n this.updateEndPosition();\n this.reLayout(selection, true);\n }\n this.editHyperlinkInternal = false;\n this.nodes = [];\n return true;\n };\n /* tslint:disable:no-any */\n Editor.prototype.insertClonedFieldResult = function (selection, nodes, fieldSeparator) {\n var fieldEnd;\n var isStarted = false;\n for (var i = nodes.length - 1; i > -1; i--) {\n var node = nodes[i];\n /* tslint:enable:no-any */\n if (!isStarted) {\n if (fieldSeparator === node) {\n isStarted = true;\n }\n else {\n if (node instanceof ParagraphWidget && node === fieldSeparator.line.paragraph) {\n isStarted = true;\n var paragraph = undefined;\n if (i === nodes.length - 1) {\n paragraph = selection.start.paragraph;\n var fieldParagraph = fieldSeparator.line.paragraph;\n this.getClonedFieldResultWithSel(fieldParagraph, selection, fieldSeparator);\n }\n else {\n paragraph = this.getClonedFieldResult(fieldSeparator.line.paragraph, fieldSeparator);\n this.insertParagraph(paragraph, true);\n }\n selection.selectParagraph(selection.getNextParagraphBlock(paragraph), true);\n }\n continue;\n }\n }\n if (node instanceof ElementBox) {\n this.insertInlineInternal(node.clone());\n }\n else if (node instanceof BlockWidget) {\n this.insertBlock(node.clone());\n }\n // else if (node instanceof WSection)\n // editor.insertSection((node as WSection)._Clone());\n }\n };\n Editor.prototype.getClonedFieldResultWithSel = function (paragraph, selection, fieldSeparator) {\n var lineIndex = paragraph.childWidgets.indexOf(fieldSeparator.line);\n var elementIndex = paragraph.childWidgets[lineIndex].children.indexOf(fieldSeparator);\n for (var j = lineIndex; j < paragraph.childWidgets.length; j++) {\n var lineWidget = paragraph.childWidgets[j];\n if (j !== lineIndex) {\n elementIndex = 0;\n }\n for (var i = elementIndex; i < lineWidget.children.length; i++) {\n this.insertInlineInternal(lineWidget.children[i].clone());\n }\n }\n };\n Editor.prototype.getClonedFieldResult = function (curParagraph, fieldSeparator) {\n var paragraph = new ParagraphWidget();\n paragraph.characterFormat.copyFormat(curParagraph.characterFormat);\n paragraph.paragraphFormat.copyFormat(curParagraph.paragraphFormat);\n var lineIndex = curParagraph.childWidgets.indexOf(fieldSeparator.line);\n var elementIndex = curParagraph.childWidgets[lineIndex].children.indexOf(fieldSeparator);\n for (var j = lineIndex; j < curParagraph.childWidgets.length; j++) {\n var lineWidget = curParagraph.childWidgets[j];\n if (j !== lineIndex) {\n elementIndex = 0;\n }\n for (var i = elementIndex; i < lineWidget.children.length; i++) {\n paragraph.childWidgets[0].children.push(lineWidget.children[i]);\n }\n }\n return paragraph;\n };\n /**\n * Removes the hyperlink if selection is within hyperlink.\n */\n Editor.prototype.removeHyperlink = function () {\n if (this.owner.isReadOnlyMode) {\n return;\n }\n var selection = this.selection;\n var fieldBegin = selection.getHyperlinkField();\n if (isNullOrUndefined(fieldBegin)) {\n return;\n }\n var fieldEnd = fieldBegin.fieldEnd;\n var fieldSeparator = fieldBegin.fieldSeparator;\n var fieldStartPosition = new TextPosition(selection.owner);\n // tslint:disable-next-line:max-line-length\n fieldStartPosition.setPositionParagraph(fieldBegin.line, (fieldBegin.line).getOffset(fieldBegin, 0));\n var fieldSeparatorPosition = new TextPosition(selection.owner);\n // tslint:disable-next-line:max-line-length\n fieldSeparatorPosition.setPositionParagraph(fieldSeparator.line, (fieldSeparator.line).getOffset(fieldSeparator, fieldSeparator.length));\n this.initComplexHistory('RemoveHyperlink');\n selection.start.setPositionParagraph(fieldEnd.line, (fieldEnd.line).getOffset(fieldEnd, 0));\n selection.end.setPositionInternal(selection.start);\n this.onDelete();\n selection.start.setPositionInternal(fieldSeparatorPosition);\n this.initHistory('Underline');\n this.updateCharacterFormatWithUpdate(selection, 'underline', 'None', false);\n if (this.editorHistory) {\n this.editorHistory.updateHistory();\n }\n // Applies font color for field result.\n this.initHistory('FontColor');\n this.updateCharacterFormatWithUpdate(selection, 'fontColor', undefined, false);\n if (this.editorHistory) {\n this.editorHistory.updateHistory();\n }\n this.reLayout(selection, false);\n selection.end.setPositionInternal(selection.start);\n selection.start.setPositionInternal(fieldStartPosition);\n this.initHistory('Delete');\n this.deleteSelectedContents(selection, false);\n this.reLayout(selection, true);\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentHistoryInfo)) {\n this.editorHistory.updateComplexHistory();\n }\n };\n //Paste Implementation starts\n /**\n * Paste copied clipboard content on Paste event\n * @param {ClipboardEvent} event\n * @param {any} pasteWindow?\n * @private\n */\n /* tslint:disable:no-any */\n Editor.prototype.pasteInternal = function (event, pasteWindow) {\n if (this.viewer.owner.enableLocalPaste) {\n this.pasteLocal();\n }\n else {\n if (isNullOrUndefined(pasteWindow)) {\n pasteWindow = window;\n }\n /* tslint:enable:no-any */\n var textContent = '';\n var clipbordData = pasteWindow.clipboardData ? pasteWindow.clipboardData : event.clipboardData;\n textContent = clipbordData.getData('Text');\n if (textContent !== '') {\n this.pasteContents(textContent);\n this.viewer.editableDiv.innerHTML = '';\n }\n }\n this.viewer.updateFocus();\n };\n /**\n * Pastes the data present in local clipboard if any.\n */\n Editor.prototype.pasteLocal = function () {\n /* tslint:disable:no-any */\n if (this.copiedData && this.owner.enableLocalPaste) {\n var document_1 = JSON.parse(this.copiedData);\n this.pasteContents(document_1);\n }\n };\n Editor.prototype.getBlocks = function (pasteContent) {\n var widgets = [];\n if (typeof (pasteContent) === 'string') {\n var startParagraph = this.selection.start.paragraph;\n if (!this.selection.isForward) {\n startParagraph = this.selection.end.paragraph;\n }\n var arr = [];\n var txt = pasteContent;\n txt = txt.replace(/\\r\\n/g, '\\r');\n arr = txt.split('\\r');\n for (var i = 0; i < arr.length; i++) {\n var insertFormat = this.copyInsertFormat(startParagraph.characterFormat, false);\n var insertParaFormat = this.viewer.selection.copySelectionParagraphFormat();\n var paragraph = new ParagraphWidget();\n paragraph.paragraphFormat.copyFormat(insertParaFormat);\n var line = new LineWidget(paragraph);\n if (arr[i].length > 0) {\n var textElement = new TextElementBox();\n textElement.characterFormat.copyFormat(insertFormat);\n textElement.text = arr[i];\n line.children.push(textElement);\n textElement.line = line;\n }\n paragraph.childWidgets.push(line);\n widgets.push(paragraph);\n }\n }\n else {\n for (var i = 0; i < pasteContent.sections.length; i++) {\n this.viewer.owner.parser.parseBody(pasteContent.sections[i].blocks, widgets);\n }\n }\n return widgets;\n };\n Editor.prototype.pasteContents = function (content) {\n this.pasteContentsInternal(this.getBlocks(content));\n };\n Editor.prototype.pasteContentsInternal = function (widgets) {\n /* tslint:enable:no-any */\n var selection = this.viewer.selection;\n var isRemoved = true;\n this.initComplexHistory('Paste');\n if (this.viewer.isListTextSelected) {\n var paragraph = selection.start.paragraph;\n if (paragraph.paragraphFormat.listFormat && paragraph.paragraphFormat.listFormat.listId !== -1) {\n this.onApplyList(undefined);\n }\n }\n this.initHistory('Paste');\n if (!selection.isEmpty || this.viewer.isListTextSelected) {\n isRemoved = this.removeSelectedContentInternal(selection, selection.start, selection.end);\n }\n if (isRemoved) {\n this.pasteContent(widgets);\n }\n else if (this.editorHistory) {\n this.editorHistory.currentBaseHistoryInfo = undefined;\n }\n if (this.editorHistory && this.editorHistory.currentHistoryInfo) {\n this.editorHistory.updateHistory();\n this.editorHistory.updateComplexHistory();\n }\n else {\n this.reLayout(selection, selection.isEmpty);\n }\n };\n /* tslint:disable:no-any */\n Editor.prototype.pasteContent = function (widgets) {\n /* tslint:enable:no-any */\n this.viewer.owner.isShiftingEnabled = true;\n this.updateInsertPosition();\n this.viewer.owner.isLayoutEnabled = true;\n this.viewer.owner.isPastingContent = true;\n this.pasteCopiedData(widgets);\n this.updateEndPosition();\n this.viewer.owner.isPastingContent = false;\n this.viewer.selection.fireSelectionChanged(true);\n };\n Editor.prototype.pasteCopiedData = function (widgets) {\n for (var j = 0; j < widgets.length; j++) {\n var widget = widgets[j];\n if (widget instanceof ParagraphWidget && widget.childWidgets.length === 0) {\n widget.childWidgets[0] = new LineWidget(widget);\n }\n if (j === widgets.length - 1 && widget instanceof ParagraphWidget) {\n var newParagraph = widget;\n if (newParagraph.childWidgets.length > 0\n && newParagraph.childWidgets[0].children.length > 0) {\n this.insertElement(newParagraph.childWidgets[0].children);\n }\n }\n else if (widget instanceof BlockWidget) {\n var startParagraph = this.selection.start.paragraph;\n if (widget instanceof TableWidget && startParagraph.isInsideTable) {\n var table = widget;\n //Handled to resize table based on parent cell width.\n var clientWidth = startParagraph.getContainerWidth();\n table.fitCellsToClientArea(clientWidth);\n }\n if (widget instanceof TableWidget && startParagraph.isEmpty()\n && startParagraph.previousWidget instanceof TableWidget) {\n this.insertTableRows(widget, startParagraph.previousWidget);\n }\n else {\n this.insertBlockInternal(widget);\n }\n }\n }\n };\n /**\n * Insert Table on undo\n * @param {WTable} table\n * @param {WTable} newTable\n * @param {boolean} moveRows\n * @private\n */\n Editor.prototype.insertTableInternal = function (table, newTable, moveRows) {\n //Gets the index of current table.\n var insertIndex = table.getIndex();\n if (moveRows) {\n //Moves the rows to table.\n for (var i = 0, index = 0; i < table.childWidgets.length; i++, index++) {\n var row = table.childWidgets[i];\n newTable.childWidgets.splice(index, 0, row);\n row.containerWidget = newTable;\n table.childWidgets.splice(i, 1);\n i--;\n }\n }\n var owner = table.containerWidget;\n this.removeBlock(table);\n //Inserts table in the current table position. \n var blockAdvCollection = owner.childWidgets;\n blockAdvCollection.splice(insertIndex, 0, newTable);\n newTable.index = table.index;\n table.containerWidget = undefined;\n newTable.containerWidget = owner;\n newTable.isGridUpdated = false;\n newTable.buildTableColumns();\n newTable.isGridUpdated = true;\n this.viewer.layout.clearTableWidget(newTable, true, true);\n this.updateNextBlocksIndex(newTable, true);\n this.viewer.layout.linkFieldInTable(newTable);\n this.viewer.layout.layoutBodyWidgetCollection(newTable.index, owner, newTable, false);\n };\n /**\n * Insert Table on undo\n * @param {Selection} selection\n * @param {WBlock} block\n * @param {WTable} table\n * @private\n */\n Editor.prototype.insertBlockTable = function (selection, block, table) {\n var offset = selection.start.offset;\n var lineIndex = selection.start.paragraph.childWidgets.indexOf(selection.start.currentWidget);\n if (block instanceof ParagraphWidget && offset > 0) {\n //Moves the inline items before selection start to the inserted paragraph.\n // tslint:disable-next-line:max-line-length\n this.moveInlines(selection.start.paragraph, block, 0, 0, selection.start.paragraph.firstChild, offset, selection.start.currentWidget);\n selection.selectParagraph(selection.start.paragraph, true);\n if (this.checkInsertPosition(selection)) {\n this.updateHistoryPosition(this.getHierarchicalIndex(block, offset.toString()), true);\n }\n }\n if (offset > 0 && this.checkInsertPosition(selection)) {\n this.updateHistoryPosition(selection.start, true);\n }\n var index = table.indexInOwner;\n table.containerWidget.childWidgets.splice(index, 0, block);\n block.containerWidget = table.containerWidget;\n block.index = table.index;\n this.updateNextBlocksIndex(block, true);\n this.viewer.layout.layoutBodyWidgetCollection(block.index, block.containerWidget, block, false);\n if (this.checkInsertPosition(selection)) {\n var paragraph = undefined;\n if (block instanceof ParagraphWidget) {\n paragraph = block;\n }\n if (block instanceof TableWidget) {\n paragraph = selection.getFirstParagraphInFirstCell(block);\n }\n this.updateHistoryPosition(this.getHierarchicalIndex(paragraph, '0'), true);\n }\n };\n /**\n * On cut handle selected content remove and relayout\n * @param {Selection} selection\n * @param {TextPosition} startPosition\n * @param {TextPosition} endPosition\n * @private\n */\n Editor.prototype.handleCut = function (selection) {\n var startPosition = selection.start;\n var endPosition = selection.end;\n if (!selection.isForward) {\n startPosition = selection.end;\n endPosition = selection.start;\n }\n // this.owner.isShiftingEnabled = true;\n var blockInfo = this.getParagraphInfo(startPosition);\n selection.editPosition = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n var image = undefined;\n if (startPosition.paragraph === endPosition.paragraph && startPosition.offset + 1 === endPosition.offset) {\n //Gets selected image and copy image to clipboard.\n var index = 0;\n var currentInline = startPosition.paragraph.getInline(endPosition.offset, index);\n var inline = currentInline.element;\n image = inline;\n }\n this.initHistory('Cut');\n selection.owner.isShiftingEnabled = true;\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n if (this.checkInsertPosition(selection)) {\n this.updateHistoryPosition(selection.editPosition, true);\n }\n }\n this.deleteSelectedContent(endPosition.paragraph, selection, startPosition, endPosition, 3);\n var textPosition = new TextPosition(selection.owner);\n this.setPositionForCurrentIndex(textPosition, selection.editPosition);\n selection.selectContent(textPosition, true);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n if (this.checkEndPosition(selection)) {\n this.updateHistoryPosition(selection.end, false);\n }\n }\n this.reLayout(selection);\n };\n Editor.prototype.insertInlineInternal = function (element) {\n var selection = this.selection;\n var length = element.length;\n var paragraphInfo = this.getParagraphInfo(selection.start);\n if (selection.start.paragraph.isEmpty()) {\n var paragraph = selection.start.paragraph;\n if ((paragraph.paragraphFormat.textAlignment === 'Center' || paragraph.paragraphFormat.textAlignment === 'Right')\n && paragraph.paragraphFormat.listFormat.listId === -1) {\n paragraph.x = this.viewer.clientActiveArea.x;\n }\n paragraph.childWidgets[0].children.push(element);\n element.line = paragraph.childWidgets[0];\n element.linkFieldCharacter(this.viewer);\n this.viewer.layout.reLayoutParagraph(paragraph, 0, 0);\n }\n else {\n var indexInInline = 0;\n var inlineObj = selection.start.currentWidget.getInline(selection.start.offset, indexInInline);\n var curInline = inlineObj.element;\n indexInInline = inlineObj.index;\n this.insertElementInternal(curInline, element, indexInInline, true);\n }\n this.setPositionParagraph(paragraphInfo.paragraph, paragraphInfo.offset + length, true);\n };\n Editor.prototype.insertElement = function (element) {\n var selection = this.selection;\n var length = 0;\n var paragraph = undefined;\n var lineIndex = -1;\n var lineWidget = undefined;\n var insertIndex = 0;\n var paragraphInfo = this.getParagraphInfo(selection.start);\n if (selection.start.paragraph.isEmpty()) {\n paragraph = selection.start.paragraph;\n lineWidget = paragraph.childWidgets[0];\n lineIndex = 0;\n }\n else {\n var indexInInline = 0;\n var inlineObj = selection.start.currentWidget.getInline(selection.start.offset, indexInInline);\n var curInline = inlineObj.element;\n indexInInline = inlineObj.index;\n paragraph = curInline.line.paragraph;\n lineIndex = paragraph.childWidgets.indexOf(curInline.line);\n insertIndex = curInline.indexInOwner;\n lineWidget = curInline.line;\n if (indexInInline === curInline.length) {\n insertIndex++;\n }\n else if (indexInInline === 0) {\n if (isNullOrUndefined(curInline.previousNode)) {\n insertIndex = 0;\n }\n }\n else {\n insertIndex++;\n var prevElement = new TextElementBox();\n prevElement.characterFormat.copyFormat(curInline.characterFormat);\n prevElement.text = curInline.text.substring(indexInInline);\n curInline.text = curInline.text.substr(0, indexInInline);\n lineWidget.children.splice(insertIndex, 0, prevElement);\n prevElement.line = curInline.line;\n }\n }\n for (var i = 0; i < element.length; i++) {\n length += element[i].length;\n lineWidget.children.splice(insertIndex, 0, element[i]);\n element[i].line = lineWidget;\n element[i].linkFieldCharacter(this.viewer);\n insertIndex++;\n }\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, 0);\n this.setPositionParagraph(paragraphInfo.paragraph, paragraphInfo.offset + length, true);\n };\n Editor.prototype.insertElementInternal = function (element, newElement, index, relayout) {\n var line = element.line;\n var paragraph = line.paragraph;\n var lineIndex = line.indexInOwner;\n var insertIndex = element.indexInOwner;\n if (index === element.length) {\n insertIndex++;\n line.children.splice(insertIndex, 0, newElement);\n }\n else if (index === 0) {\n if (isNullOrUndefined(element.previousNode)) {\n element.line.children.splice(0, 0, newElement);\n insertIndex = 0;\n }\n else {\n element.line.children.splice(insertIndex, 0, newElement);\n }\n }\n else {\n insertIndex++;\n var textElement = new TextElementBox();\n textElement.characterFormat.copyFormat(element.characterFormat);\n textElement.text = element.text.substring(index);\n element.text = element.text.substr(0, index);\n line.children.splice(insertIndex, 0, textElement);\n textElement.line = element.line;\n //Inserts the new inline.\n line.children.splice(insertIndex, 0, newElement);\n insertIndex -= 1;\n }\n newElement.line = element.line;\n newElement.linkFieldCharacter(this.viewer);\n if (relayout) {\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, insertIndex);\n }\n };\n /**\n * Insert Block on undo\n * @param {Selection} selection\n * @param {WBlock} block\n * @private\n */\n Editor.prototype.insertBlock = function (block) {\n var isRemoved = true;\n var selection = this.selection;\n if (!selection.isEmpty) {\n isRemoved = this.removeSelectedContents(selection);\n }\n if (!isRemoved) {\n selection.selectContent(selection.start, false);\n }\n this.insertBlockInternal(block);\n if (this.checkInsertPosition(selection)) {\n var paragraph = undefined;\n if (block instanceof ParagraphWidget) {\n paragraph = block;\n }\n else {\n paragraph = this.selection.getFirstParagraphInFirstCell(block);\n }\n // tslint:disable-next-line:max-line-length\n this.updateHistoryPosition(this.getHierarchicalIndex(paragraph, '0'), true);\n }\n this.fireContentChange();\n };\n /**\n * Insert new Block on specific index\n * @param {Selection} selection\n * @param {BlockWidget} block\n * @private\n */\n Editor.prototype.insertBlockInternal = function (block) {\n var selection = this.selection;\n var isRemoved = true;\n var startPara = this.selection.start.paragraph;\n if (!selection.start.isAtParagraphStart) {\n if (block instanceof ParagraphWidget) {\n this.insertNewParagraphWidget(block, false);\n return;\n }\n this.updateInsertPosition();\n startPara = startPara.combineWidget(this.viewer);\n // tslint:disable-next-line:max-line-length\n this.splitParagraph(startPara, startPara.firstChild, 0, selection.start.currentWidget, selection.start.offset, false);\n selection.selectParagraph(this.selection.start.paragraph, true);\n }\n var bodyWidget = selection.start.paragraph.containerWidget;\n var blockIndex = selection.start.paragraph.index;\n var insertIndex = bodyWidget.childWidgets.indexOf(selection.start.paragraph);\n if (!isNullOrUndefined(bodyWidget)) {\n bodyWidget.childWidgets.splice(insertIndex, 0, block);\n block.containerWidget = bodyWidget;\n block.index = blockIndex;\n block.height = 0;\n if (block instanceof TableWidget) {\n block.isGridUpdated = false;\n block.buildTableColumns();\n block.isGridUpdated = true;\n }\n this.updateNextBlocksIndex(block, true);\n this.viewer.layout.layoutBodyWidgetCollection(blockIndex, bodyWidget, block, false);\n }\n };\n /**\n * Inserts the image with specified size at cursor position in the document editor.\n * @param {string} imageString Base64 string, web URL or file URL.\n * @param {number} width? Image width\n * @param {number} height? Image height\n */\n Editor.prototype.insertImage = function (imageString, width, height) {\n if (this.owner.isReadOnlyMode) {\n return;\n }\n if (isNullOrUndefined(width)) {\n width = 100;\n }\n if (isNullOrUndefined(height)) {\n height = 100;\n }\n this.insertPicture(imageString, width, height);\n };\n /**\n * Inserts a table of specified size at cursor position\n * in the document editor.\n * @param {number} rows Default value of ‘rows’ parameter is 1.\n * @param {number} columns Default value of ‘columns’ parameter is 1.\n */\n Editor.prototype.insertTable = function (rows, columns) {\n var startPos = this.selection.start;\n if (this.owner.isReadOnlyMode) {\n return;\n }\n rows = rows || 1;\n columns = columns || 1;\n var table = this.createTable(rows, columns);\n var clientWidth = startPos.paragraph.getContainerWidth();\n table.splitWidthToTableCells(clientWidth);\n var prevBlock = startPos.paragraph.previousWidget;\n if (startPos.currentWidget.isFirstLine() && startPos.offset === 0 && prevBlock instanceof TableWidget) {\n this.insertTableRows(table, prevBlock);\n table.destroy();\n return;\n }\n else {\n this.initHistory('InsertTable');\n this.viewer.owner.isShiftingEnabled = true;\n this.insertBlock(table);\n }\n var startLine = this.selection.getFirstParagraphInFirstCell(table).childWidgets[0];\n startPos.setPosition(startLine, true);\n this.selection.end.setPositionInternal(startPos);\n var lastParagraph = this.selection.getLastParagraphInLastCell(table);\n var endOffset = lastParagraph.getLength() + 1;\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n // tslint:disable-next-line:max-line-length\n this.editorHistory.currentBaseHistoryInfo.endPosition = this.getHierarchicalIndex(lastParagraph, endOffset.toString());\n }\n this.reLayout(this.selection);\n };\n /**\n * Inserts the specified number of rows to the table above or below to the row at cursor position.\n * @param {boolean} above The above parameter is optional and if omitted,\n * it takes the value as false and inserts below the row at cursor position.\n * @param {number} count The count parameter is optional and if omitted, it takes the value as 1.\n */\n Editor.prototype.insertRow = function (above, count) {\n var rowPlacement = above ? 'Above' : 'Below';\n if (this.owner.isReadOnlyMode) {\n return;\n }\n var startPos = this.selection.isForward ? this.selection.start : this.selection.end;\n var endPos = this.selection.isForward ? this.selection.end : this.selection.start;\n if (startPos.paragraph.isInsideTable) {\n if (this.checkIsNotRedoing()) {\n this.initHistory(rowPlacement === 'Above' ? 'InsertRowAbove' : 'InsertRowBelow');\n }\n this.viewer.owner.isShiftingEnabled = true;\n var startCell = this.getOwnerCell(this.selection.isForward).getSplitWidgets()[0];\n var endCell = this.getOwnerCell(!this.selection.isForward).getSplitWidgets()[0];\n var table = startCell.ownerTable.combineWidget(this.viewer);\n var row = rowPlacement === 'Below' ? endCell.ownerRow : startCell.ownerRow;\n if (this.editorHistory) {\n var clonedTable = this.cloneTableToHistoryInfo(table);\n }\n var rowCount = count ? count : this.getRowCountToInsert();\n var rows = [];\n var index = row.rowIndex;\n if (rowPlacement === 'Below') {\n index++;\n var isAffectedByRowSpannedCell = isNullOrUndefined(endCell.previousWidget)\n || endCell.columnIndex === endCell.previousWidget.columnIndex + 1;\n var isRowSpanEnd = endCell.cellIndex !== endCell.columnIndex && isAffectedByRowSpannedCell\n && row.rowIndex + startCell.cellFormat.rowSpan - 1 === endCell.ownerRow.rowIndex;\n if (!isRowSpanEnd) {\n if (endCell.cellFormat.rowSpan > 1) {\n if (!isNullOrUndefined(row.nextWidget) && row.nextWidget instanceof TableRowWidget) {\n endCell.cellFormat.rowSpan += rowCount;\n row = row.nextWidget;\n }\n }\n }\n }\n for (var i = 0; i < rowCount; i++) {\n var cellCountInfo = this.updateRowspan(row, rowPlacement === 'Below' ? endCell : startCell, rowPlacement);\n var newRow = this.createRowAndColumn(cellCountInfo.count, i);\n newRow.rowFormat.copyFormat(row.rowFormat);\n this.updateCellFormatForInsertedRow(newRow, cellCountInfo.cellFormats);\n rows.push(newRow);\n }\n table.insertTableRowsInternal(rows, index);\n var cell = undefined;\n var paragraph = undefined;\n if ((table.childWidgets[index] instanceof TableRowWidget)) {\n cell = table.childWidgets[index].firstChild;\n paragraph = this.selection.getFirstParagraph(cell);\n }\n else {\n var widget = undefined;\n while (!(widget instanceof TableWidget)) {\n widget = table.nextRenderedWidget;\n }\n paragraph = this.selection.getFirstParagraphInFirstCell(widget);\n }\n this.viewer.layout.reLayoutTable(table);\n this.selection.selectParagraph(paragraph, true);\n }\n this.reLayout(this.selection, true);\n };\n Editor.prototype.updateCellFormatForInsertedRow = function (newRow, cellFormats) {\n for (var i = 0; i < newRow.childWidgets.length; i++) {\n newRow.childWidgets[i].cellFormat.copyFormat(cellFormats[i]);\n newRow.childWidgets[i].cellFormat.rowSpan = 1;\n }\n };\n Editor.prototype.updateRowspan = function (row, startCell, rowPlacement) {\n var spannedCells = row.getPreviousRowSpannedCells(true);\n var count = 0;\n var cellFormats = [];\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n var isCellIncluded = false;\n // Need to check with all the row spanned cells. if the start cell contains rowspan greater than 1, \n // and when inserting below, need to increment rowspan for all row spanned cells by 1 except\n // if the spanned cells is placed in the same column or cell to be cloned has the same row index of cloned cell row index.\n // and when inserting above, if cloned cell placed in the same row of start cell or\n // if the cloned cell has equal column index, need to skip updating rowspan value of cloned cell.\n // else update row span value for spanned cell except \n // if the spanned cells is placed in the same column or cell to be cloned has the same row index of cloned cell row index.\n var isRowSpanned = (isNullOrUndefined(cell.previousWidget)\n || cell.columnIndex !== cell.previousWidget.columnIndex + 1);\n for (var j = 0; j < spannedCells.length; j++) {\n if (isRowSpanned) {\n var spannedCell = spannedCells[j];\n var clonedRowIndex = spannedCell.ownerRow.rowIndex + spannedCell.cellFormat.rowSpan - 1;\n if (cell.columnIndex < spannedCell.columnIndex && cell.cellIndex !== cell.columnIndex) {\n isCellIncluded = true;\n count++;\n cellFormats.push(cell.cellFormat);\n }\n if (startCell.cellFormat.rowSpan === 1) {\n // Need to check whether cell is affected by a row spanned cell. if cell is placed on the row where it is affected \n // by row spanned cell, then if we are inserting row below, need to add new cell with spanned cell width\n // or if we are inserting above, need to update row span value of the spanned cell.\n // if cell is placed inbetween the spanned cell , \n // then if we are inserting below, need to update row span value of spanned cell or\n // if we are inserting above, need to skip updating row span value except\n // if start cell is placed on the same row of spanned cell or if start cell placed in the same column.\n if (clonedRowIndex > cell.ownerRow.rowIndex) {\n if (rowPlacement === 'Above'\n && spannedCell.ownerRow === startCell.ownerRow) {\n continue;\n }\n else {\n spannedCell.cellFormat.rowSpan += 1;\n spannedCells.splice(j, 1);\n j--;\n }\n }\n else if (cell.cellIndex !== cell.columnIndex && isRowSpanned && clonedRowIndex === cell.ownerRow.rowIndex) {\n if (rowPlacement === 'Above') {\n spannedCell.cellFormat.rowSpan += 1;\n spannedCells.splice(j, 1);\n j--;\n }\n else {\n count++;\n cellFormats.push(spannedCell.cellFormat);\n spannedCells.splice(j, 1);\n j--;\n }\n }\n }\n else {\n if (spannedCell !== startCell) {\n if (rowPlacement === 'Above'\n && (spannedCell.ownerRow === startCell.ownerRow || spannedCell.columnIndex === startCell.columnIndex)) {\n continue;\n }\n else {\n if (spannedCell.columnIndex !== startCell.columnIndex\n && spannedCell.ownerRow.rowIndex !== cell.ownerRow.rowIndex\n && (clonedRowIndex > startCell.ownerRow.rowIndex\n || (rowPlacement === 'Above' && clonedRowIndex === startCell.ownerRow.rowIndex))) {\n spannedCell.cellFormat.rowSpan += 1;\n spannedCells.splice(j, 1);\n j--;\n }\n }\n }\n }\n }\n }\n if (spannedCells.indexOf(cell) === -1 && cell.cellFormat.rowSpan > 1) {\n isCellIncluded = true;\n }\n if (!isCellIncluded) {\n count++;\n cellFormats.push(cell.cellFormat);\n }\n }\n return { count: count, cellFormats: cellFormats };\n };\n Editor.prototype.insertTableRows = function (table, prevBlock) {\n this.initHistory('InsertRowBelow');\n table.containerWidget = prevBlock.containerWidget;\n prevBlock = prevBlock.combineWidget(this.viewer);\n if (this.editorHistory) {\n var clonedTable = this.cloneTableToHistoryInfo(prevBlock);\n }\n var row = prevBlock.childWidgets[prevBlock.childWidgets.length - 1];\n prevBlock.insertTableRowsInternal(table.childWidgets, prevBlock.childWidgets.length);\n var paragraph = this.selection.getFirstParagraph(row.nextWidget.childWidgets[0]);\n this.viewer.layout.reLayoutTable(prevBlock);\n this.selection.selectParagraph(paragraph, true);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.updateHistoryPosition(this.selection.start, true);\n this.updateHistoryPosition(this.selection.end, false);\n }\n this.reLayout(this.selection);\n };\n /**\n * Inserts the specified number of columns to the table left or right to the column at cursor position.\n * @param {number} left The left parameter is optional and if omitted, it takes the value as false and\n * inserts to the right of column at cursor position.\n * @param {number} count The count parameter is optional and if omitted, it takes the value as 1.\n */\n Editor.prototype.insertColumn = function (left, count) {\n if (this.owner.isReadOnlyMode) {\n return;\n }\n var columnPlacement = left ? 'Left' : 'Right';\n if (this.selection.start.paragraph.isInsideTable) {\n if (this.checkIsNotRedoing()) {\n this.initHistory(columnPlacement === 'Left' ? 'InsertColumnLeft' : 'InsertColumnRight');\n }\n this.selection.owner.isShiftingEnabled = true;\n var startCell = this.getOwnerCell(this.selection.isForward);\n var endCell = this.getOwnerCell(!this.selection.isForward);\n var table = startCell.ownerRow.ownerTable.combineWidget(this.viewer);\n if (this.editorHistory) {\n //Clones the entire table to preserve in history.\n var clonedTable = this.cloneTableToHistoryInfo(table);\n }\n this.selection.owner.isLayoutEnabled = false;\n var cellIndex = startCell.columnIndex;\n if (columnPlacement === 'Right') {\n cellIndex = endCell.columnIndex + endCell.cellFormat.columnSpan;\n }\n var startParagraph = undefined;\n var newCell = undefined;\n var columnCount = count ? count : this.getColumnCountToInsert();\n var rowSpannedCells = [];\n var rowSpanCellIndex = cellIndex;\n for (var i = 0; i < columnCount; i++) {\n for (var j = 0; j < table.childWidgets.length; j++) {\n var row = table.childWidgets[j];\n newCell = this.createColumn(this.selection.getLastParagraph(startCell));\n newCell.index = j;\n newCell.rowIndex = row.rowIndex;\n newCell.containerWidget = row;\n newCell.cellFormat.copyFormat(startCell.cellFormat);\n newCell.cellFormat.rowSpan = 1;\n if (isNullOrUndefined(startParagraph)) {\n startParagraph = this.selection.getFirstParagraph(newCell);\n }\n if (cellIndex === 0) {\n row.childWidgets.splice(cellIndex, 0, newCell);\n }\n else {\n var isCellInserted = false;\n for (var j_1 = 0; j_1 < row.childWidgets.length; j_1++) {\n var rowCell = row.childWidgets[j_1];\n // Add the row spanned cells to colection for adding column before / after row spnned cells.\n if (rowCell.cellFormat.rowSpan > 1) {\n rowSpannedCells.push(rowCell);\n }\n if (rowCell.columnIndex + rowCell.cellFormat.columnSpan === cellIndex) {\n row.childWidgets.splice(rowCell.cellIndex + 1, 0, newCell);\n isCellInserted = true;\n }\n else if (cellIndex > rowCell.columnIndex && rowCell.columnIndex + rowCell.cellFormat.columnSpan > cellIndex\n && cellIndex < rowCell.columnIndex + rowCell.cellFormat.columnSpan) {\n row.childWidgets.splice(rowCell.cellIndex, 0, newCell);\n isCellInserted = true;\n }\n if (isCellInserted) {\n break;\n }\n }\n // If the cell is not inserted for row, then check for row spanned cells.\n if (!isCellInserted) {\n if (rowSpannedCells.length > 0) {\n for (var k = 0; k < rowSpannedCells.length; k++) {\n var rowSpannedCell = rowSpannedCells[k];\n if (rowSpannedCell.ownerRow !== row\n && row.rowIndex <= rowSpannedCell.ownerRow.rowIndex + rowSpannedCell.cellFormat.rowSpan - 1) {\n if (rowSpannedCell.columnIndex + rowSpannedCell.cellFormat.columnSpan === cellIndex) {\n if (rowSpannedCell.cellIndex > row.childWidgets.length) {\n row.childWidgets.push(newCell);\n }\n else {\n row.childWidgets.splice(rowSpannedCell.cellIndex, 0, newCell);\n }\n isCellInserted = true;\n }\n else if (cellIndex > rowSpannedCell.columnIndex &&\n rowSpannedCell.columnIndex + rowSpannedCell.cellFormat.columnSpan > cellIndex\n && cellIndex < rowSpannedCell.columnIndex + rowSpannedCell.cellFormat.columnSpan) {\n row.childWidgets.splice(rowSpannedCell.columnIndex, 0, newCell);\n isCellInserted = true;\n }\n }\n if (isCellInserted) {\n break;\n }\n }\n }\n }\n }\n }\n }\n table.updateRowIndex(0);\n var parentTable = this.viewer.layout.getParentTable(table);\n if (parentTable) {\n parentTable.fitChildToClientArea();\n }\n else {\n table.fitChildToClientArea();\n }\n this.selection.owner.isLayoutEnabled = true;\n table.isGridUpdated = false;\n table.buildTableColumns();\n table.isGridUpdated = true;\n this.viewer.layout.reLayoutTable(table);\n this.selection.start.setPosition(startParagraph.firstChild, true);\n this.selection.end.setPosition(this.selection.getLastParagraph(newCell).firstChild, false);\n if (this.checkIsNotRedoing() || isNullOrUndefined(this.editorHistory)) {\n this.reLayout(this.selection);\n }\n }\n };\n /**\n * Creates table with specified rows and columns.\n * @private\n */\n Editor.prototype.createTable = function (rows, columns) {\n var startPara = this.selection.start.paragraph;\n var table = new TableWidget();\n table.tableFormat = new WTableFormat(table);\n table.tableFormat.preferredWidthType = 'Auto';\n table.tableFormat.initializeTableBorders();\n var index = 0;\n while (index < rows) {\n var tableRow = this.createRowAndColumn(columns, index);\n tableRow.rowFormat.heightType = 'Auto';\n tableRow.containerWidget = table;\n table.childWidgets.push(tableRow);\n index++;\n }\n return table;\n };\n Editor.prototype.createRowAndColumn = function (columns, rowIndex) {\n var startPara = this.selection.start.paragraph;\n var tableRow = new TableRowWidget();\n tableRow.rowFormat = new WRowFormat(tableRow);\n tableRow.index = rowIndex;\n for (var i = 0; i < columns; i++) {\n var tableCell = this.createColumn(startPara);\n tableCell.index = i;\n tableCell.rowIndex = rowIndex;\n tableCell.containerWidget = tableRow;\n tableRow.childWidgets.push(tableCell);\n }\n return tableRow;\n };\n Editor.prototype.createColumn = function (paragraph) {\n var tableCell = new TableCellWidget();\n var para = new ParagraphWidget();\n para.paragraphFormat.copyFormat(paragraph.paragraphFormat);\n para.characterFormat.copyFormat(paragraph.characterFormat);\n para.containerWidget = tableCell;\n tableCell.childWidgets.push(para);\n tableCell.cellFormat = new WCellFormat(tableCell);\n return tableCell;\n };\n Editor.prototype.getColumnCountToInsert = function () {\n var count = 1;\n var start = this.selection.start;\n var end = this.selection.end;\n if (!this.selection.isForward) {\n start = this.selection.end;\n end = this.selection.start;\n }\n if (start && end && this.selection.getTable(start, end)) {\n if (start.paragraph.associatedCell === end.paragraph.associatedCell) {\n return count = 1;\n }\n if (start.paragraph.associatedCell.ownerRow === end.paragraph.associatedCell.ownerRow) {\n return count = count + end.paragraph.associatedCell.cellIndex - start.paragraph.associatedCell.cellIndex;\n }\n else {\n count = 0;\n // tslint:disable-next-line:max-line-length\n var selectedCells = start.paragraph.associatedCell.ownerTable.getColumnCellsForSelection(start.paragraph.associatedCell, end.paragraph.associatedCell);\n for (var i = 0; i < selectedCells.length; i++) {\n if (start.paragraph.associatedCell.ownerRow === selectedCells[i].ownerRow) {\n count++;\n }\n }\n }\n }\n return count === 0 ? 1 : count;\n };\n Editor.prototype.getRowCountToInsert = function () {\n var count = 1;\n var start = this.selection.start;\n var end = this.selection.end;\n if (!this.selection.isForward) {\n start = this.selection.end;\n end = this.selection.start;\n }\n if (!isNullOrUndefined(start) && !isNullOrUndefined(end) && !isNullOrUndefined(this.selection.getTable(start, end))) {\n if (start.paragraph.associatedCell === end.paragraph.associatedCell ||\n start.paragraph.associatedCell.ownerRow === end.paragraph.associatedCell.ownerRow) {\n return count = 1;\n }\n else {\n return count = count +\n this.getOwnerRow(!this.selection.isForward).rowIndex - this.getOwnerRow(this.selection.isForward).rowIndex;\n }\n }\n return count === 0 ? 1 : count;\n };\n Editor.prototype.getOwnerCell = function (isStart) {\n var cell = undefined;\n var startCell = isStart ? this.selection.start.paragraph.associatedCell\n : this.selection.end.paragraph.associatedCell;\n var endCell = isStart ? this.selection.end.paragraph.associatedCell\n : this.selection.start.paragraph.associatedCell;\n cell = startCell;\n var owner = cell.ownerTable;\n while (!isNullOrUndefined(owner) && owner.containerWidget instanceof TableCellWidget && owner !== endCell.ownerTable) {\n cell = owner.containerWidget;\n owner = cell.ownerTable;\n }\n return cell;\n };\n Editor.prototype.getOwnerRow = function (isStart) {\n var row;\n var startRow = isStart ? this.selection.start.paragraph.associatedCell.ownerRow\n : this.selection.end.paragraph.associatedCell.ownerRow;\n var endRow = isStart ? this.selection.end.paragraph.associatedCell.ownerRow\n : this.selection.start.paragraph.associatedCell.ownerRow;\n row = startRow;\n var owner = row.ownerTable;\n while (!isNullOrUndefined(owner) && owner.containerWidget instanceof TableCellWidget && owner !== endRow.ownerTable) {\n row = owner.containerWidget.ownerRow;\n owner = row.ownerTable;\n }\n return row;\n };\n Editor.prototype.getOwnerTable = function (isStart) {\n var table = undefined;\n var startTable = this.selection.start.paragraph.associatedCell.ownerTable;\n var endTable = this.selection.end.paragraph.associatedCell.ownerTable;\n table = isStart ? startTable : endTable;\n while (table.containerWidget instanceof TableCellWidget && table !== (isStart ? endTable : startTable)) {\n table = table.containerWidget.ownerTable;\n }\n return table;\n };\n /**\n * Merge Selected cells\n * @private\n */\n Editor.prototype.mergeSelectedCellsInTable = function () {\n if (!this.canMergeCells()) {\n return;\n }\n if (this.checkIsNotRedoing()) {\n this.initHistory('MergeCells');\n }\n this.selection.owner.isShiftingEnabled = true;\n var startPosition = this.selection.start;\n var endPosition = this.selection.end;\n if (!this.selection.isForward) {\n startPosition = this.selection.end;\n endPosition = this.selection.start;\n }\n var startOwnerCell = this.getOwnerCell(this.selection.isForward);\n var endOwnerCell = this.getOwnerCell(!this.selection.isForward);\n var containerCell = this.selection.getContainerCellOf(startOwnerCell, endOwnerCell);\n if (containerCell.ownerTable.contains(endOwnerCell)) {\n if (!this.selection.containsCell(containerCell, endOwnerCell)) {\n //Start and End are in different cells. \n var table = startOwnerCell.ownerTable.combineWidget(this.viewer);\n startOwnerCell = this.selection.getSelectedCell(startOwnerCell, containerCell);\n endOwnerCell = this.selection.getSelectedCell(endOwnerCell, containerCell);\n //Merges the selected cells. \n var mergedCell = this.mergeSelectedCells(table, startOwnerCell, endOwnerCell);\n var lastParagraph = this.selection.getLastParagraph(mergedCell);\n endPosition.setPosition(lastParagraph.lastChild, false);\n }\n }\n if (this.checkIsNotRedoing() || isNullOrUndefined(this.editorHistory)) {\n this.reLayout(this.selection, false);\n }\n };\n Editor.prototype.mergeSelectedCells = function (table, startCell, endCell) {\n //Clones the entire table to preserve in history.\n var clonedTable = this.cloneTableToHistoryInfo(table);\n this.selection.owner.isLayoutEnabled = false;\n //Merges the selected cells.\n var start = this.selection.getCellLeft(startCell.ownerRow, startCell);\n var end = start + startCell.cellFormat.cellWidth;\n var endCellLeft = this.selection.getCellLeft(endCell.ownerRow, endCell);\n var endCellRight = endCellLeft + endCell.cellFormat.cellWidth;\n var cellInfo = this.updateSelectedCellsInTable(start, end, endCellLeft, endCellRight);\n start = cellInfo.start;\n end = cellInfo.end;\n var count = table.childWidgets.indexOf(endCell.ownerRow);\n var rowStartIndex = table.childWidgets.indexOf(startCell.ownerRow);\n var mergedCell = undefined;\n for (var i = rowStartIndex; i <= count; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n var cellStart = this.selection.getCellLeft(row, cell);\n if (HelperMethods.round(start, 2) <= HelperMethods.round(cellStart, 2)\n && HelperMethods.round(cellStart, 2) < HelperMethods.round(end, 2)) {\n if (isNullOrUndefined(mergedCell)) {\n mergedCell = cell;\n }\n else {\n if (i === rowStartIndex) {\n mergedCell.cellFormat.preferredWidth += cell.cellFormat.preferredWidth;\n mergedCell.cellFormat.columnSpan += cell.cellFormat.columnSpan;\n this.mergeBorders(mergedCell, cell);\n }\n for (var k = 0; k < cell.childWidgets.length; k++) {\n var block = cell.childWidgets[k];\n if (cell.childWidgets.length === 1 && block instanceof ParagraphWidget\n && block.childWidgets.length === 0) {\n break;\n }\n mergedCell.childWidgets.push(block.clone());\n }\n row.childWidgets.splice(j, 1);\n cell.destroy();\n j--;\n }\n }\n }\n if (row.childWidgets.length === 0) {\n var rowIndex = table.childWidgets.indexOf(row);\n row.updateRowBySpannedCells();\n table.childWidgets.splice(rowIndex, 1);\n row.destroy();\n count--;\n i--;\n }\n }\n if (!isNullOrUndefined(mergedCell) && rowStartIndex < count) {\n mergedCell.cellFormat.rowSpan = count - rowStartIndex + 1;\n }\n this.updateBlockIndexAfterMerge(mergedCell);\n table.updateRowIndex(0);\n table.calculateGrid();\n table.isGridUpdated = false;\n table.buildTableColumns();\n table.isGridUpdated = true;\n this.viewer.layout.reLayoutTable(table);\n //Layouts the table after merging cells.\n this.selection.owner.isLayoutEnabled = true;\n return mergedCell;\n };\n Editor.prototype.mergeBorders = function (mergedCell, tableCell) {\n var mergedCellborders = undefined;\n var cellBorders = null;\n if (!isNullOrUndefined(mergedCell.cellFormat.borders)) {\n mergedCellborders = mergedCell.cellFormat.borders;\n }\n if (!isNullOrUndefined(tableCell.cellFormat.borders)) {\n cellBorders = tableCell.cellFormat.borders;\n }\n if (isNullOrUndefined(mergedCellborders) && isNullOrUndefined(cellBorders)) {\n return;\n }\n if (isNullOrUndefined(mergedCellborders)) {\n mergedCellborders = new WBorders(mergedCell.cellFormat);\n mergedCellborders.copyFormat(cellBorders);\n }\n else if (isNullOrUndefined(cellBorders)) {\n return;\n }\n else {\n if (mergedCell.ownerRow.rowIndex === tableCell.ownerRow.rowIndex) {\n mergedCellborders.top = mergedCell.getBorderBasedOnPriority(mergedCellborders.top, cellBorders.bottom);\n mergedCellborders.bottom = mergedCell.getBorderBasedOnPriority(mergedCellborders.bottom, cellBorders.bottom);\n }\n }\n };\n Editor.prototype.updateBlockIndexAfterMerge = function (cell) {\n for (var i = 0; i < cell.childWidgets.length; i++) {\n cell.childWidgets[i].index = i;\n }\n };\n /**\n * Determines whether merge cell operation can be done.\n */\n Editor.prototype.canMergeCells = function () {\n if (this.selection.isEmpty || !this.selection.start.paragraph.isInsideTable || !this.selection.end.paragraph.isInsideTable) {\n return false;\n }\n var startPos = this.selection.start;\n var endPos = this.selection.end;\n if (!this.selection.isForward) {\n startPos = this.selection.end;\n endPos = this.selection.start;\n }\n var startCell = this.getOwnerCell(this.selection.isForward);\n var endCell = this.getOwnerCell(!this.selection.isForward);\n var containerCell = this.selection.getContainerCellOf(startCell, endCell);\n if (containerCell.ownerTable.contains(endCell)) {\n if (!this.selection.containsCell(containerCell, endCell)) {\n startCell = this.selection.getSelectedCell(startCell, containerCell);\n endCell = this.selection.getSelectedCell(endCell, containerCell);\n var rowSpan = 1;\n if (startCell.ownerRow === endCell.ownerRow) {\n var startCellIndex = startCell.ownerRow.childWidgets.indexOf(startCell);\n for (var i = startCellIndex; i <= startCell.ownerRow.childWidgets.indexOf(endCell); i++) {\n var cell = startCell.ownerRow.childWidgets[i];\n var prevCell = cell.previousWidget;\n if (i !== startCellIndex) {\n if (cell.cellFormat.rowSpan !== rowSpan) {\n return false;\n }\n if (!isNullOrUndefined(prevCell)\n && cell.columnIndex !== (prevCell.cellFormat.columnSpan + prevCell.columnIndex)) {\n return false;\n }\n }\n rowSpan = cell.cellFormat.rowSpan;\n }\n return true;\n }\n return this.canMergeSelectedCellsInTable(startCell.ownerTable, startCell, endCell);\n }\n }\n return false;\n };\n Editor.prototype.canMergeSelectedCellsInTable = function (table, startCell, endCell) {\n var count = table.childWidgets.indexOf(endCell.ownerRow);\n var rowStartIndex = table.childWidgets.indexOf(startCell.ownerRow);\n var startLeft = this.selection.getCellLeft(startCell.ownerRow, startCell);\n var endLeft = startLeft + startCell.cellFormat.cellWidth;\n var endCellLeft = this.selection.getCellLeft(endCell.ownerRow, endCell);\n var endCellRight = endCellLeft + endCell.cellFormat.cellWidth;\n var cellInfo = this.updateSelectedCellsInTable(startLeft, endLeft, endCellLeft, endCellRight);\n startLeft = cellInfo.start;\n endLeft = cellInfo.end;\n var selectionLeft = 0;\n var selectionRight = 0;\n var isRowLeftWithinSel = false;\n var isRowRightWithinSel = false;\n var rowSpannedCells = [];\n for (var i = rowStartIndex; i <= count; i++) {\n var row = table.childWidgets[i];\n var rowLeft = 0;\n var rowRight = 0;\n var isStarted = false;\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n var cellStart = this.selection.getCellLeft(row, cell);\n if (this.checkCellWithInSelection(startLeft, endLeft, cellStart)) {\n isRowLeftWithinSel = false;\n isRowRightWithinSel = false;\n if (cell.cellFormat.rowSpan > 1) {\n rowSpannedCells.push(cell);\n }\n if (!isStarted) {\n rowLeft = cellStart;\n rowRight = cellStart;\n isStarted = true;\n }\n var prevCell = cell.previousWidget;\n if (rowRight !== 0 && HelperMethods.round(rowRight, 0) !== HelperMethods.round(cellStart, 0)) {\n rowRight = cellStart;\n }\n rowRight += HelperMethods.convertPointToPixel(cell.cellFormat.cellWidth);\n var isPrevCellWithinSel = this.checkPrevOrNextCellIsWithinSel(startLeft, endLeft, cell, true);\n var isNextCellWithinSel = this.checkPrevOrNextCellIsWithinSel(startLeft, endLeft, cell, false);\n // When selected cell not having row spanned cells and column index is not having immediate cell index value,\n // then returned false.\n var isNoRowSpan = rowSpannedCells.length === 0 || rowSpannedCells.length === 1 && rowSpannedCells[0] === cell;\n // checks whether current cell is with in selection.\n var isCellWithInSel = this.checkCurrentCell(rowSpannedCells, cell, isPrevCellWithinSel, isNextCellWithinSel);\n // when last selected row not having equal row span then returned false.\n if (i === count && !isNullOrUndefined(prevCell) && cell.cellFormat.rowSpan > prevCell.cellFormat.rowSpan\n && !isCellWithInSel) {\n return false;\n }\n if (i !== rowStartIndex) {\n for (var m = 0; m < rowSpannedCells.length; m++) {\n {\n var rowSpan = (rowSpannedCells[m].ownerRow.rowIndex + rowSpannedCells[m].cellFormat.rowSpan) - 1;\n if (rowSpan >= row.rowIndex) {\n if (rowSpannedCells[m].columnIndex > cell.columnIndex) {\n isRowRightWithinSel = true;\n }\n else {\n isRowLeftWithinSel = true;\n }\n if (i === count && rowSpannedCells[m] !== cell\n && rowSpan > (cell.ownerRow.rowIndex + cell.cellFormat.rowSpan - 1)) {\n return false;\n }\n if (rowSpan === row.rowIndex && !this.checkPrevOrNextCellIsWithinSel(startLeft, endLeft, cell, false)) {\n rowSpannedCells.splice(rowSpannedCells.indexOf(rowSpannedCells[m]), 1);\n }\n }\n }\n }\n }\n if (isPrevCellWithinSel && !isNullOrUndefined(prevCell)\n && isNoRowSpan\n && (cell.columnIndex !== prevCell.columnIndex + 1 && this.checkCellWidth(cell))) {\n return false;\n }\n }\n }\n if (i === rowStartIndex) {\n selectionLeft = rowLeft;\n selectionRight = rowRight;\n }\n else {\n if (rowRight > 0 && rowLeft > 0) {\n if (!((isRowLeftWithinSel || Math.round(selectionLeft) === Math.round(rowLeft))\n && (isRowRightWithinSel || Math.round(selectionRight) === Math.round(rowRight)))) {\n return false;\n }\n }\n if (i === count) {\n return true;\n }\n }\n }\n return false;\n };\n Editor.prototype.checkCellWidth = function (cell) {\n var prevCell = cell.previousWidget;\n var cellLeft = this.viewer.selection.getCellLeft(cell.ownerRow, cell);\n var prevCellLeft = this.viewer.selection.getCellLeft(cell.ownerRow, prevCell);\n var left = prevCellLeft + HelperMethods.convertPointToPixel(prevCell.cellFormat.cellWidth);\n if (HelperMethods.round(left, 2) !== HelperMethods.round(cellLeft, 2)) {\n return true;\n }\n return false;\n };\n ;\n Editor.prototype.checkCellWithInSelection = function (startLeft, endLeft, cellStart) {\n if (HelperMethods.round(startLeft, 2) <= HelperMethods.round(cellStart, 2)\n && HelperMethods.round(cellStart, 2) < HelperMethods.round(endLeft, 2)) {\n return true;\n }\n return false;\n };\n ;\n Editor.prototype.checkPrevOrNextCellIsWithinSel = function (startLeft, endLeft, cell, isPrev) {\n var prevOrNextCell = isPrev ? cell.previousWidget : cell.nextWidget;\n var cellStart = 0;\n if (isNullOrUndefined(prevOrNextCell)) {\n return false;\n }\n cellStart = this.viewer.selection.getCellLeft(prevOrNextCell.ownerRow, prevOrNextCell);\n return this.checkCellWithInSelection(startLeft, endLeft, cellStart);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.checkCurrentCell = function (rowSpannedCells, cell, isPrevCellWithInSel, isNextCellWithinSel) {\n var cellOwner = cell.ownerRow;\n if (rowSpannedCells.length > 0) {\n for (var i = 0; i < rowSpannedCells.length; i++) {\n var spannedCellOwner = rowSpannedCells[i].ownerRow;\n var rowSpan = (spannedCellOwner.rowIndex + rowSpannedCells[i].cellFormat.rowSpan) - 1;\n if (rowSpannedCells[i] === cell && (rowSpannedCells.length === 1 || this.checkRowSpannedCells(rowSpannedCells, cell))\n && !(isNextCellWithinSel || isPrevCellWithInSel)) {\n return true;\n }\n if (rowSpannedCells[i] !== cell && spannedCellOwner.rowIndex < cellOwner.rowIndex\n && rowSpan === (cellOwner.rowIndex + cell.cellFormat.rowSpan - 1)) {\n return true;\n }\n }\n }\n return false;\n };\n Editor.prototype.checkRowSpannedCells = function (rowSpannedCells, cell) {\n for (var i = 0; i < rowSpannedCells.length; i++) {\n if (rowSpannedCells[i] !== cell && rowSpannedCells[i].columnIndex === cell.columnIndex) {\n return true;\n }\n }\n return false;\n };\n /**\n * @private\n */\n Editor.prototype.insertNewParagraphWidget = function (newParagraph, insertAfter) {\n this.updateInsertPosition();\n this.insertParagraph(newParagraph, insertAfter);\n if (!insertAfter) {\n var nextParagraph = void 0;\n var currentParagraph = newParagraph;\n do {\n nextParagraph = this.selection.getNextParagraphBlock(currentParagraph);\n currentParagraph = nextParagraph;\n } while (nextParagraph && nextParagraph.equals(newParagraph));\n if (!isNullOrUndefined(nextParagraph)) {\n this.selection.selectParagraph(nextParagraph, true);\n }\n else {\n this.selection.selectParagraph(newParagraph, true);\n }\n }\n this.fireContentChange();\n };\n Editor.prototype.insertParagraph = function (newParagraph, insertAfter) {\n var lineWidget = this.selection.start.currentWidget;\n var offset = this.selection.start.offset;\n var currentParagraph = this.selection.start.paragraph;\n currentParagraph = currentParagraph.combineWidget(this.viewer);\n if (insertAfter) {\n // tslint:disable-next-line:max-line-length\n var length_1 = this.selection.getLineLength(currentParagraph.lastChild);\n var insertIndex_1 = newParagraph.firstChild ? newParagraph.firstChild.children.length : 0;\n // tslint:disable-next-line:max-line-length\n this.moveInlines(currentParagraph, newParagraph, insertIndex_1, offset, lineWidget, length_1, currentParagraph.lastChild);\n }\n else if (offset > 0) {\n this.moveInlines(currentParagraph, newParagraph, 0, 0, currentParagraph.firstChild, offset, lineWidget);\n }\n var splittedWidget = currentParagraph.getSplitWidgets();\n currentParagraph = insertAfter ? splittedWidget[splittedWidget.length - 1] : splittedWidget[0];\n var insertIndex = currentParagraph.containerWidget.childWidgets.indexOf(currentParagraph);\n if (insertAfter) {\n insertIndex++;\n }\n var bodyWidget = currentParagraph.containerWidget;\n newParagraph.index = currentParagraph.index;\n newParagraph.containerWidget = bodyWidget;\n bodyWidget.childWidgets.splice(insertIndex, 0, newParagraph);\n this.updateNextBlocksIndex(insertAfter ? currentParagraph : newParagraph, true);\n newParagraph.height = 0;\n this.viewer.layout.layoutBodyWidgetCollection(newParagraph.index, bodyWidget, newParagraph, false);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.moveInlines = function (currentParagraph, newParagraph, insertIndex, startOffset, startLine, endOffset, endLine) {\n if (newParagraph.childWidgets.length === 0) {\n var line = new LineWidget(newParagraph);\n newParagraph.childWidgets.push(line);\n }\n var isMoved = false;\n this.viewer.layout.clearListElementBox(currentParagraph);\n this.viewer.layout.clearListElementBox(newParagraph);\n for (var j = 0; j < currentParagraph.childWidgets.length; j++) {\n var lineWidget = currentParagraph.childWidgets[j];\n if (startLine === lineWidget && endLine === lineWidget) {\n insertIndex = this.moveContent(lineWidget, startOffset, endOffset, insertIndex, newParagraph);\n break;\n }\n if (endLine === lineWidget) {\n insertIndex = this.moveContent(lineWidget, 0, endOffset, insertIndex, newParagraph);\n break;\n }\n else if (startLine === lineWidget) {\n isMoved = true;\n // tslint:disable-next-line:max-line-length\n insertIndex = this.moveContent(lineWidget, startOffset, this.viewer.selection.getLineLength(lineWidget), insertIndex, newParagraph);\n }\n else if (isMoved) {\n insertIndex = this.moveContent(lineWidget, 0, this.viewer.selection.getLineLength(lineWidget), insertIndex, newParagraph);\n }\n }\n this.removeEmptyLine(currentParagraph);\n if (!currentParagraph.isInsideTable) {\n this.viewer.layout.reLayoutParagraph(currentParagraph, 0, 0);\n }\n };\n /**\n * @private\n */\n //tslint:disable-next-line:max-line-length\n Editor.prototype.moveContent = function (lineWidget, startOffset, endOffset, insertIndex, paragraph) {\n var count = 0;\n var lineIndex = lineWidget.paragraph.childWidgets.indexOf(lineWidget);\n for (var i = 0; i < lineWidget.children.length; i++) {\n var inline = lineWidget.children[i];\n if (startOffset >= count + inline.length || inline instanceof ListTextElementBox) {\n if (!(inline instanceof ListTextElementBox)) {\n count += inline.length;\n }\n continue;\n }\n var startIndex = 0;\n if (startOffset > count) {\n startIndex = startOffset - count;\n }\n var endIndex = endOffset - count;\n if (endIndex > inline.length) {\n endIndex = inline.length;\n }\n if (startIndex > 0) {\n count += startIndex;\n }\n if (startIndex === 0 && endIndex === inline.length) {\n paragraph.firstChild.children.splice(insertIndex, 0, inline);\n inline.line = paragraph.firstChild;\n insertIndex++;\n // if (editAction < 4) {\n // this.unLinkFieldCharacter(inline);\n lineWidget.children.splice(i, 1);\n i--;\n // }\n }\n else if (inline instanceof TextElementBox) {\n // if (editAction < 4) {\n var span = new TextElementBox();\n span.characterFormat.copyFormat(inline.characterFormat);\n span.text = inline.text.substr(startIndex, endIndex - startIndex);\n paragraph.firstChild.children.splice(insertIndex, 0, span);\n span.line = paragraph.firstChild;\n insertIndex++;\n inline.text = inline.text.slice(0, startIndex) + inline.text.slice(endIndex);\n }\n if (endOffset <= count + endIndex - startIndex) {\n break;\n }\n count += endIndex - startIndex;\n }\n return insertIndex;\n };\n /**\n * update complex changes when history is not preserved\n * @param {number} action?\n * @param {string} start?\n * @param {string} end?\n * @private\n */\n Editor.prototype.updateComplexWithoutHistory = function (action, start, end) {\n var selection = this.viewer.selection;\n if (action === 0) {\n var startPosition = new TextPosition(selection.owner);\n this.setPositionForCurrentIndex(startPosition, start);\n this.viewer.layout.reLayoutParagraph(startPosition.paragraph, 0, 0);\n this.setPositionForCurrentIndex(selection.start, end);\n this.setPositionForCurrentIndex(selection.end, end);\n }\n if (action === 1) {\n var startPosition = new TextPosition(selection.owner);\n this.setPositionForCurrentIndex(startPosition, start);\n var endPosition = new TextPosition(selection.owner);\n this.setPositionForCurrentIndex(endPosition, end);\n this.viewer.layout.reLayoutParagraph(startPosition.paragraph, 0, 0);\n if (endPosition.paragraph !== startPosition.paragraph) {\n this.viewer.layout.reLayoutParagraph(endPosition.paragraph, 0, 0);\n }\n }\n if (selection.owner.isShiftingEnabled) {\n this.viewer.layout.shiftLayoutedItems();\n if (this.viewer.owner.enableHeaderAndFooter) {\n this.updateHeaderFooterWidget();\n }\n }\n selection.owner.isShiftingEnabled = false;\n selection.start.updatePhysicalPosition(true);\n if (selection.isEmpty) {\n selection.end.setPositionInternal(selection.start);\n }\n else {\n selection.end.updatePhysicalPosition(true);\n }\n selection.upDownSelectionLength = selection.end.location.x;\n selection.fireSelectionChanged(true);\n this.viewer.updateFocus();\n this.viewer.updateScrollBars();\n this.fireContentChange();\n this.isHandledComplex = true;\n };\n /**\n * reLayout\n * @param selection\n * @param isSelectionChanged\n * @private\n */\n Editor.prototype.reLayout = function (selection, isSelectionChanged) {\n if (this.editorHistory && this.editorHistory.isHandledComplexHistory()) {\n if (isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)\n || (this.editorHistory.currentBaseHistoryInfo\n && !(this.editorHistory.currentBaseHistoryInfo.action === 'ClearCharacterFormat'\n || this.editorHistory.currentBaseHistoryInfo.action === 'ClearParagraphFormat'))) {\n this.startParagraph = undefined;\n this.endParagraph = undefined;\n }\n this.isHandledComplex = false;\n return;\n }\n if (isNullOrUndefined(this.viewer.blockToShift)) {\n this.viewer.removeEmptyPages();\n this.viewer.layout.updateFieldElements();\n this.viewer.updateScrollBars();\n if (!selection.owner.isShiftingEnabled) {\n selection.fireSelectionChanged(true);\n this.startParagraph = undefined;\n this.endParagraph = undefined;\n }\n }\n if (isNullOrUndefined(isSelectionChanged)) {\n isSelectionChanged = selection.isEmpty;\n }\n if (selection.owner.isShiftingEnabled) {\n selection.owner.isShiftingEnabled = false;\n selection.owner.isLayoutEnabled = true;\n this.viewer.layout.shiftLayoutedItems();\n if (this.viewer.owner.enableHeaderAndFooter) {\n this.updateHeaderFooterWidget();\n }\n this.getOffsetValue(selection);\n selection.upDownSelectionLength = selection.end.location.x;\n selection.fireSelectionChanged(true);\n this.viewer.updateFocus();\n this.startParagraph = undefined;\n this.endParagraph = undefined;\n this.viewer.layout.allowLayout = true;\n }\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo &&\n ((this.editorHistory.currentBaseHistoryInfo.action !== 'RowResizing'\n && this.editorHistory.currentBaseHistoryInfo.action !== 'CellResizing')\n || (this.editorHistory.isUndoing || this.editorHistory.isRedoing))) {\n if (this.editorHistory.currentBaseHistoryInfo.modifiedProperties.length > 0) {\n this.editorHistory.currentBaseHistoryInfo.updateSelection();\n }\n this.editorHistory.updateHistory();\n }\n this.fireContentChange();\n };\n /**\n * @private\n */\n Editor.prototype.updateHeaderFooterWidget = function () {\n this.updateHeaderFooterWidgetToPage(this.selection.start.paragraph.bodyWidget);\n this.shiftPageContent(this.selection.start.paragraph.bodyWidget);\n };\n /**\n * @private\n */\n Editor.prototype.updateHeaderFooterWidgetToPage = function (node) {\n var currentPage = node.page;\n node = this.viewer.layout.updateHeaderFooterToParent(node);\n var isEvenPage = (node.headerFooterType === 'EvenHeader' || node.headerFooterType === 'EvenFooter');\n for (var i = 0; i < this.viewer.pages.length; i++) {\n var page = this.viewer.pages[i];\n if ((i + 1 === 1) && page.bodyWidgets[0].sectionFormat.differentFirstPage &&\n node.headerFooterType.indexOf('FirstPage') !== -1) {\n return;\n }\n if (page.index === 0 && page.bodyWidgets[0].sectionFormat.differentFirstPage &&\n node.headerFooterType.indexOf('FirstPage') === -1) {\n continue;\n }\n if (currentPage !== page) {\n if (page.bodyWidgets[0].sectionFormat.differentOddAndEvenPages) {\n if (isEvenPage && (i + 1) % 2 === 0) {\n this.updateHeaderFooterWidgetToPageInternal(page, node, node.headerFooterType.indexOf('Header') !== -1);\n }\n else if ((!isEvenPage && (i + 1) % 2 !== 0)) {\n if (page.bodyWidgets[0].sectionFormat.differentFirstPage && (i + 1 !== 1)) {\n this.updateHeaderFooterWidgetToPageInternal(page, node, node.headerFooterType.indexOf('Header') !== -1);\n }\n }\n }\n else {\n this.updateHeaderFooterWidgetToPageInternal(page, node, node.headerFooterType.indexOf('Header') !== -1);\n }\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.updateHeaderFooterWidgetToPageInternal = function (page, widget, isHeader) {\n if (widget.page !== page) {\n var hfWidget = widget.clone();\n hfWidget.page = page;\n this.viewer.updateHFClientArea(hfWidget.sectionFormat, isHeader);\n hfWidget = this.viewer.layout.layoutHeaderFooterItems(this.viewer, hfWidget);\n var headerOrFooter = void 0;\n if (isHeader) {\n headerOrFooter = page.headerWidget;\n page.headerWidget = hfWidget;\n }\n else {\n headerOrFooter = page.footerWidget;\n page.footerWidget = hfWidget;\n }\n this.removeFieldInWidget(headerOrFooter);\n headerOrFooter.destroy();\n }\n };\n /**\n * @private\n */\n Editor.prototype.removeFieldInWidget = function (widget) {\n for (var i = 0; i < widget.childWidgets.length; i++) {\n this.removeFieldInBlock(widget.childWidgets[i]);\n }\n };\n /**\n * @private\n */\n Editor.prototype.removeFieldInBlock = function (block) {\n if (block instanceof TableWidget) {\n this.removeFieldTable(block);\n }\n else {\n this.removeField(block);\n }\n };\n /**\n * @private\n */\n Editor.prototype.removeFieldTable = function (table) {\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n this.removeFieldInWidget(row.childWidgets[j]);\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.shiftPageContent = function (headerFooter) {\n var type = headerFooter.headerFooterType;\n var pageIndex;\n if (type === 'FirstPageHeader' || type === 'FirstPageFooter') {\n pageIndex = 0;\n }\n else if (headerFooter.sectionFormat.differentOddAndEvenPages) {\n if (headerFooter.sectionFormat.differentFirstPage) {\n pageIndex = (type === 'EvenHeader' || type === 'EvenFooter') ? 1 : 2;\n }\n else {\n pageIndex = (type.indexOf('Even') === -1) ? 0 : 1;\n }\n }\n else {\n pageIndex = headerFooter.sectionFormat.differentFirstPage ? 1 : 0;\n if (pageIndex === 1 && this.viewer.pages.length === 1) {\n pageIndex = 0;\n }\n }\n var page = this.viewer.pages[pageIndex];\n if (type.indexOf('Header') !== -1) {\n var firstBlock = page.bodyWidgets[0].firstChild;\n var top_1 = HelperMethods.convertPointToPixel(headerFooter.sectionFormat.topMargin);\n var headerDistance = HelperMethods.convertPointToPixel(headerFooter.sectionFormat.headerDistance);\n top_1 = Math.max(headerDistance + page.headerWidget.height, top_1);\n if (firstBlock.y !== top_1) {\n this.viewer.updateClientArea(page.bodyWidgets[0].sectionFormat, page);\n firstBlock = firstBlock.combineWidget(this.viewer);\n var prevWidget = firstBlock.previousRenderedWidget;\n if (prevWidget) {\n this.viewer.cutFromTop(prevWidget.y + prevWidget.height);\n if (firstBlock.containerWidget !== prevWidget.containerWidget) {\n // tslint:disable-next-line:max-line-length\n this.viewer.layout.updateContainerWidget(firstBlock, prevWidget.containerWidget, prevWidget.indexInOwner + 1, false);\n }\n }\n this.viewer.blockToShift = firstBlock;\n }\n }\n else {\n this.checkAndShiftFromBottom(page, headerFooter);\n }\n if (this.viewer.blockToShift) {\n this.viewer.renderedLists.clear();\n this.viewer.layout.shiftLayoutedItems();\n }\n };\n /**\n * @private\n */\n Editor.prototype.checkAndShiftFromBottom = function (page, footerWidget) {\n var bodyWidget = page.bodyWidgets[0];\n var blockToShift;\n for (var i = 0; i < bodyWidget.childWidgets.length; i++) {\n var block = bodyWidget.childWidgets[i];\n if (block.y + block.height > footerWidget.y) {\n blockToShift = block;\n break;\n }\n if (bodyWidget.childWidgets.length - 1 === i && block.y + block.height < footerWidget.y) {\n blockToShift = block;\n break;\n }\n }\n this.viewer.updateClientArea(bodyWidget.sectionFormat, page);\n this.viewer.cutFromTop(blockToShift.y);\n this.viewer.blockToShift = blockToShift;\n };\n //Paste Implementation ends\n //Character Format apply implementation starts\n /**\n * Change HighlightColor\n * @param {HighlightColor} highlightColor\n * Applies character format for selection.\n * @param {string} property\n * @param {Object} value\n * @param {boolean} update\n * @private\n */\n Editor.prototype.onApplyCharacterFormat = function (property, value, update) {\n var selection = this.viewer.selection;\n if (selection.owner.isReadOnlyMode || !selection.owner.isDocumentLoaded) {\n return;\n }\n update = isNullOrUndefined(update) ? false : update;\n var action = (property[0].toUpperCase() + property.slice(1));\n var paragraph = selection.start.paragraph;\n var lastLine = paragraph.childWidgets[paragraph.childWidgets.length - 1];\n if (selection.isEmpty && selection.contextType !== 'List') {\n selection.skipFormatRetrieval = true;\n if (selection.end.isAtParagraphEnd) {\n this.initHistory(action);\n this.viewer.owner.isShiftingEnabled = true;\n this.applyCharFormatValue(paragraph.characterFormat, property, value, update);\n this.reLayout(this.viewer.selection);\n this.viewer.updateFocus();\n }\n else {\n selection.fireSelectionChanged(true);\n }\n selection.skipFormatRetrieval = false;\n return;\n }\n this.setOffsetValue(selection);\n this.initHistory(action);\n // Todo: Complete Microsoft Word behavior on apply formatting in empty selection\n // if (selection.isEmpty) {\n // this.viewer.owner.isShiftingEnabled = true;\n // this.applyCharFormatValue(paragraph.characterFormat, property, value, update);\n // this.reLayout(this.viewer.selection);\n // this.viewer.updateFocus();\n // return;\n // }\n if (selection.contextType === 'List') {\n // this.updateCharacterFormatForListText(selection, action, value, update);\n this.applyCharacterFormatForListText(selection, property, value, update);\n }\n else {\n //Iterate and update format.\n this.updateSelectionCharacterFormatting(property, value, update);\n }\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharacterFormatForListText = function (selection, property, values, update) {\n var listLevel = this.getListLevel(selection.start.paragraph);\n if (isNullOrUndefined(listLevel)) {\n return;\n }\n var characterFormat = listLevel.characterFormat;\n switch (property) {\n case 'bold':\n this.applyListCharacterFormatByValue(selection, characterFormat, 'bold', !(characterFormat.bold));\n break;\n case 'italic':\n this.applyListCharacterFormatByValue(selection, characterFormat, 'italic', !(characterFormat.italic));\n break;\n case 'fontColor':\n this.applyListCharacterFormatByValue(selection, characterFormat, 'fontColor', values);\n break;\n case 'fontFamily':\n this.applyListCharacterFormatByValue(selection, characterFormat, 'fontFamily', values);\n break;\n case 'fontSize':\n this.applyListCharacterFormatByValue(selection, characterFormat, 'fontSize', values);\n break;\n case 'highlightColor':\n this.applyListCharacterFormatByValue(selection, characterFormat, 'highlightColor', values);\n break;\n case 'baselineAlignment':\n if (characterFormat.baselineAlignment === values) {\n values = 'Normal';\n }\n this.applyListCharacterFormatByValue(selection, characterFormat, 'baselineAlignment', values);\n break;\n case 'strikethrough':\n if (characterFormat.strikethrough === values) {\n values = 'None';\n }\n this.applyListCharacterFormatByValue(selection, characterFormat, 'strikethrough', values);\n break;\n case 'underline':\n if (characterFormat.underline === values) {\n values = 'None';\n }\n this.applyListCharacterFormatByValue(selection, characterFormat, 'underline', values);\n break;\n case 'characterFormat':\n this.applyListCharacterFormatByValue(selection, characterFormat, undefined, values);\n break;\n }\n };\n Editor.prototype.applyListCharacterFormatByValue = function (selection, format, property, value) {\n this.initHistory('ListCharacterFormat');\n this.applyCharFormatValue(format, property, value, false);\n this.editorHistory.updateHistory();\n this.reLayout(selection);\n this.fireContentChange();\n };\n /**\n * @private\n */\n Editor.prototype.updateListCharacterFormat = function (selection, property, value) {\n this.updateListTextSelRange(selection, property, value, false);\n };\n Editor.prototype.updateListTextSelRange = function (selection, property, value, update) {\n this.viewer.owner.isShiftingEnabled = true;\n var startPositionInternal = selection.start;\n var endPositionInternal = selection.end;\n if (!selection.isForward) {\n startPositionInternal = selection.end;\n endPositionInternal = selection.start;\n }\n this.initHistoryPosition(selection, startPositionInternal);\n var listLevel = this.getListLevel(selection.start.paragraph);\n this.applyCharFormatValue(listLevel.characterFormat, property, value, update);\n this.startSelectionReLayouting(startPositionInternal.paragraph, selection, startPositionInternal, endPositionInternal);\n };\n /**\n * @private\n */\n Editor.prototype.getListLevel = function (paragraph) {\n var currentList = undefined;\n var listLevelNumber = 0;\n if (!isNullOrUndefined(paragraph.paragraphFormat) && !isNullOrUndefined(paragraph.paragraphFormat.listFormat)) {\n currentList = this.viewer.getListById(paragraph.paragraphFormat.listFormat.listId);\n listLevelNumber = paragraph.paragraphFormat.listFormat.listLevelNumber;\n }\n if (!isNullOrUndefined(currentList) &&\n !isNullOrUndefined(this.viewer.getAbstractListById(currentList.abstractListId))\n // && !isNullOrUndefined(this.viewer.getAbstractListById(currentList.abstractListId).levels.getItem(listLevelNumber))) {\n && !isNullOrUndefined(this.viewer.getAbstractListById(currentList.abstractListId).levels)) {\n return this.viewer.layout.getListLevel(currentList, listLevelNumber);\n }\n return undefined;\n };\n Editor.prototype.updateInsertPosition = function () {\n var selection = this.viewer.selection;\n var position = selection.start;\n if (!selection.isForward) {\n position = selection.end;\n }\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)\n && !isNullOrUndefined(position)) {\n if (isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo.insertPosition)) {\n this.updateHistoryPosition(position, true);\n }\n }\n };\n /**\n * preserve paragraph and offset value for selection\n * @private\n */\n Editor.prototype.setOffsetValue = function (selection) {\n var info = this.getParagraphInfo(selection.start);\n this.startParagraph = info.paragraph;\n this.startOffset = info.offset;\n info = this.getParagraphInfo(selection.end);\n this.endParagraph = info.paragraph;\n this.endOffset = info.offset;\n };\n /**\n * Toggles the highlight color property of selected contents.\n * @param {HighlightColor} highlightColor Default value of ‘underline’ parameter is Yellow.\n */\n Editor.prototype.toggleHighlightColor = function (highlightColor) {\n var selection = this.viewer.selection;\n if (isNullOrUndefined(highlightColor) || highlightColor === 'NoColor') {\n highlightColor = 'Yellow';\n }\n //In Ms Word the highlight color is took from the ribbon. So we Have given yellow as constant.\n if (selection.characterFormat.highlightColor === highlightColor) {\n highlightColor = 'NoColor';\n }\n this.selection.characterFormat.highlightColor = highlightColor;\n };\n /**\n * Toggles the subscript formatting of selected contents.\n */\n Editor.prototype.toggleSubscript = function () {\n if (!this.owner.isReadOnlyMode) {\n var value = this.selection.characterFormat.baselineAlignment === 'Subscript' ? 'Normal' : 'Subscript';\n this.selection.characterFormat.baselineAlignment = value;\n }\n };\n /**\n * Toggles the superscript formatting of selected contents.\n */\n Editor.prototype.toggleSuperscript = function () {\n if (!this.owner.isReadOnlyMode) {\n var value = this.selection.characterFormat.baselineAlignment === 'Superscript' ? 'Normal' : 'Superscript';\n this.selection.characterFormat.baselineAlignment = value;\n }\n };\n /**\n * Toggles the text alignment property of selected contents.\n * @param {TextAlignment} textAlignment Default value of ‘textAlignment parameter is TextAlignment.Left.\n */\n /**\n * Increases the left indent of selected paragraphs to a factor of 36 points.\n */\n Editor.prototype.increaseIndent = function () {\n if (!this.owner.isReadOnlyMode) {\n this.onApplyParagraphFormat('leftIndent', this.viewer.defaultTabWidth, true, false);\n }\n };\n /**\n * Decreases the left indent of selected paragraphs to a factor of 36 points.\n */\n Editor.prototype.decreaseIndent = function () {\n if (!this.owner.isReadOnlyMode) {\n this.onApplyParagraphFormat('leftIndent', -this.viewer.defaultTabWidth, true, false);\n }\n };\n /**\n * Clears the list format for selected paragraphs.\n */\n Editor.prototype.clearList = function () {\n this.selection.owner.editorModule.onApplyList(undefined);\n };\n /**\n * Applies the bullet list to selected paragraphs.\n * @param {string} bullet Bullet character\n * @param {string} fontFamily Bullet font family\n */\n Editor.prototype.applyBullet = function (bullet, fontFamily) {\n if (!this.owner.isReadOnlyMode) {\n this.applyBulletOrNumbering(bullet, 'Bullet', fontFamily);\n }\n };\n /**\n * Applies the numbering list to selected paragraphs.\n * @param numberFormat “%n” representations in ‘numberFormat’ parameter will be replaced by respective list level’s value.\n * `“%1)” will be displayed as “1)” `\n * @param listLevelPattern Default value of ‘listLevelPattern’ parameter is ListLevelPattern.Arabic\n */\n Editor.prototype.applyNumbering = function (numberFormat, listLevelPattern) {\n if (!this.owner.isReadOnlyMode) {\n this.applyBulletOrNumbering(numberFormat, listLevelPattern, 'Verdana');\n }\n };\n /**\n * Toggles the baseline alignment property of selected contents.\n * @param {Selection} selection\n * @param {BaselineAlignment} baseAlignment\n */\n Editor.prototype.toggleBaselineAlignment = function (baseAlignment) {\n this.updateProperty(2, baseAlignment);\n };\n /**\n * Clears the formatting.\n */\n Editor.prototype.clearFormatting = function () {\n var selection = this.viewer.selection;\n this.initComplexHistory('ClearFormat');\n // let startIndex: string = selection.start.getHierarchicalIndexInternal();\n // let endIndex: string = selection.end.getHierarchicalIndexInternal();\n if (selection.isEmpty) {\n selection.start.moveToParagraphStartInternal(selection, false);\n selection.end.moveToParagraphEndInternal(selection, false);\n }\n this.setOffsetValue(selection);\n if (this.editorHistory) {\n this.editorHistory.initializeHistory('ClearCharacterFormat');\n }\n this.updateSelectionCharacterFormatting('ClearCharacterFormat', undefined, false);\n this.getOffsetValue(selection);\n if (this.editorHistory) {\n this.editorHistory.updateHistory();\n }\n this.setOffsetValue(selection);\n if (this.editorHistory) {\n this.editorHistory.initializeHistory('ClearParagraphFormat');\n }\n this.updateParagraphFormatInternal('ClearParagraphFormat', undefined, false);\n if (this.editorHistory) {\n this.editorHistory.updateHistory();\n }\n this.getOffsetValue(selection);\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentHistoryInfo)) {\n this.editorHistory.updateComplexHistory();\n }\n this.startParagraph = undefined;\n this.endParagraph = undefined;\n // else {\n // this.checkAndUpdatedSelection(startIndex, endIndex);\n // }\n };\n /**\n * Toggles the specified property. If property is assigned already. Then property will be changed\n * @param {Selection} selection\n * @param {number} type\n * @param {Object} value\n * @private\n */\n Editor.prototype.updateProperty = function (type, value) {\n var selection = this.selection;\n if (selection.owner.isReadOnlyMode || !selection.owner.isDocumentLoaded) {\n return;\n }\n var startPosition = selection.start;\n var endPosition = selection.end;\n if (!selection.isForward) {\n startPosition = selection.end;\n endPosition = selection.start;\n }\n var indexInInline = 0;\n var inlineObj = startPosition.currentWidget.getInline(startPosition.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n var paragraph = startPosition.paragraph;\n if (!isNullOrUndefined(inline) && inline.length === indexInInline && !this.selection.isEmpty) {\n inline = inline.nextNode;\n }\n if (type === 1) {\n var currentUnderline = 'None';\n if (!isNullOrUndefined(inline)) {\n currentUnderline = inline.characterFormat.underline;\n }\n else if (!isNullOrUndefined(paragraph)) {\n currentUnderline = paragraph.characterFormat.underline;\n }\n this.selection.characterFormat.underline = value === currentUnderline ? 'None' : value;\n }\n else {\n var script = 'Normal';\n if (!isNullOrUndefined(inline)) {\n script = inline.characterFormat.baselineAlignment;\n }\n else if (!isNullOrUndefined(paragraph)) {\n script = paragraph.characterFormat.baselineAlignment;\n }\n if (script === value) {\n value = 'Normal';\n }\n this.selection.characterFormat.baselineAlignment = value;\n }\n };\n Editor.prototype.getCompleteStyles = function () {\n var completeStylesString = '{\"styles\":[';\n for (var _i = 0, _a = this.viewer.preDefinedStyles.getItem(); _i < _a.length; _i++) {\n var name_1 = _a[_i];\n completeStylesString += (this.viewer.preDefinedStyles.get(name_1) + ',');\n }\n return completeStylesString.slice(0, -1) + ']}';\n };\n /**\n * Initialize default styles\n * @private\n */\n Editor.prototype.intializeDefaultStyles = function () {\n var existingStyles = this.owner.getStyleNames('Paragraph');\n var defaultStyleNames = ['Normal', 'Heading 1', 'Heading 2', 'Heading 3', 'Heading 4', 'Heading 5', 'Heading 6'];\n var styleNames = defaultStyleNames.filter(function (val) {\n return existingStyles.indexOf(val) === -1;\n });\n for (var _i = 0, styleNames_1 = styleNames; _i < styleNames_1.length; _i++) {\n var name_2 = styleNames_1[_i];\n this.createStyle(this.viewer.preDefinedStyles.get(name_2));\n }\n };\n /**\n * Creates a new instance of Style.\n */\n Editor.prototype.createStyle = function (styleString) {\n this.createStyleIn(styleString);\n };\n /**\n * Create a Style.\n * @private\n */\n Editor.prototype.createStyleIn = function (styleString) {\n /* tslint:disable:no-any */\n var style = JSON.parse(styleString);\n var styleObj = this.viewer.styles.findByName(style.name);\n if (styleObj !== undefined) {\n //Create a new style with new name and add it to collection.\n style.name = this.getUniqueStyleName(style.name);\n }\n this.viewer.owner.parser.parseStyle(JSON.parse(this.getCompleteStyles()), style, this.viewer.styles);\n return this.viewer.styles.findByName(style.name);\n };\n /**\n * @private\n */\n Editor.prototype.getUniqueStyleName = function (name) {\n var uniqueName = this.getUniqueName(name);\n var style = this.viewer.styles.findByName(uniqueName);\n while (!isNullOrUndefined(style)) {\n uniqueName = this.getUniqueStyleName(style.name);\n style = this.viewer.styles.findByName(uniqueName);\n }\n return uniqueName;\n };\n Editor.prototype.getUniqueName = function (name) {\n var matchArray = name.match(/\\d+$/);\n var returnName;\n if (!isNullOrUndefined(matchArray) && matchArray.length > 0) {\n return name.replace(matchArray[0], (parseInt(matchArray[0], 10) + 1).toString());\n }\n else {\n return name + '_1';\n }\n };\n /**\n * Update Character format for selection\n * @private\n */\n Editor.prototype.updateSelectionCharacterFormatting = function (property, values, update) {\n if (isNullOrUndefined(property)) {\n property = 'CharacterFormat';\n }\n switch (property) {\n case 'bold':\n this.updateCharacterFormat('bold', values);\n break;\n case 'italic':\n this.updateCharacterFormat('italic', values);\n break;\n case 'fontColor':\n this.updateCharacterFormat('fontColor', values);\n break;\n case 'fontFamily':\n this.updateCharacterFormat('fontFamily', values);\n break;\n case 'fontSize':\n this.updateCharacterFormatWithUpdate(this.viewer.selection, 'fontSize', values, update);\n break;\n case 'highlightColor':\n this.updateCharacterFormat('highlightColor', values);\n break;\n case 'baselineAlignment':\n this.updateCharacterFormat('baselineAlignment', values);\n break;\n case 'strikethrough':\n this.updateCharacterFormat('strikethrough', values);\n break;\n case 'underline':\n this.updateCharacterFormat('underline', values);\n break;\n case 'styleName':\n this.updateCharacterFormatWithUpdate(this.viewer.selection, 'styleName', values, true);\n break;\n case 'CharacterFormat':\n this.updateCharacterFormat(undefined, values);\n break;\n case 'ClearCharacterFormat':\n this.updateCharacterFormat(undefined, values);\n break;\n }\n this.reLayout(this.viewer.selection);\n };\n /**\n * Update character format for selection range\n * @param {SelectionRange} selectionRange\n * @param {string} property\n * @param {Object} value\n * @returns void\n * @private\n */\n Editor.prototype.updateCharacterFormat = function (property, value) {\n this.updateCharacterFormatWithUpdate(this.viewer.selection, property, value, false);\n };\n Editor.prototype.updateCharacterFormatWithUpdate = function (selection, property, value, update) {\n this.viewer.owner.isShiftingEnabled = true;\n var startPosition = selection.start;\n var endPosition = selection.end;\n if (!selection.isForward) {\n startPosition = selection.end;\n endPosition = selection.start;\n }\n this.applyCharFormatSelectedContent(startPosition.paragraph, selection, startPosition, endPosition, property, value, update);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatSelectedContent = function (paragraph, selection, start, end, property, value, update) {\n //Selection start in cell.\n if (start.paragraph.isInsideTable && (!end.paragraph.isInsideTable\n || start.paragraph.associatedCell !== end.paragraph.associatedCell\n || selection.isCellSelected(start.paragraph.associatedCell, start, end))) {\n var cell = void 0;\n start.paragraph.associatedCell.ownerTable.combineWidget(this.viewer);\n if (this.checkInsertPosition(selection)) {\n this.updateHistoryPosition(start, true);\n }\n cell = start.paragraph.associatedCell;\n this.applyCharFormatCell(cell, selection, start, end, property, value, update);\n var table = cell.ownerTable;\n // tslint:disable-next-line:max-line-length\n this.viewer.layout.layoutBodyWidgetCollection(table.index, table.containerWidget, table, false);\n }\n else {\n this.applyCharFormat(paragraph, selection, start, end, property, value, update);\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatForSelectedPara = function (paragraph, selection, property, value, update) {\n for (var i = 0; i < paragraph.childWidgets.length; i++) {\n var line = paragraph.childWidgets[i];\n for (var j = 0; j < line.children.length; j++) {\n var element = line.children[j];\n this.applyCharFormatValue(element.characterFormat, property, value, update);\n }\n }\n this.applyCharFormatValue(paragraph.characterFormat, property, value, update);\n };\n Editor.prototype.splittedLastParagraph = function (paragraph) {\n var splittedWidets = paragraph.getSplitWidgets();\n return splittedWidets[splittedWidets.length - 1];\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.getNextParagraphForCharacterFormatting = function (block, start, end, property, value, update) {\n var widgetCollection = block.getSplitWidgets();\n block = widgetCollection[widgetCollection.length - 1];\n block = this.viewer.selection.getNextRenderedBlock(block);\n if (!isNullOrUndefined(block)) {\n if (block instanceof ParagraphWidget) {\n this.applyCharFormat(block, this.viewer.selection, start, end, property, value, update);\n }\n else {\n this.applyCharFormatForTable(0, block, this.viewer.selection, start, end, property, value, update);\n }\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormat = function (paragraph, selection, start, end, property, value, update) {\n paragraph = paragraph.combineWidget(this.viewer);\n var startOffset = 0;\n var length = selection.getParagraphLength(paragraph);\n var startLineWidget = paragraph.childWidgets.indexOf(start.currentWidget) !== -1 ?\n paragraph.childWidgets.indexOf(start.currentWidget) : 0;\n var endOffset = end.offset;\n var endLineWidget = paragraph.childWidgets.indexOf(end.currentWidget) !== -1 ?\n paragraph.childWidgets.indexOf(end.currentWidget) : paragraph.childWidgets.length - 1;\n if (!isNullOrUndefined(selection)) {\n if (paragraph === start.paragraph) {\n startOffset = start.offset;\n }\n }\n if (!paragraph.equals(end.paragraph)) {\n this.applyCharFormatValue(paragraph.characterFormat, property, value, update);\n endOffset = length;\n }\n else {\n var lastLine = paragraph.childWidgets[paragraph.childWidgets.length - 1];\n if (selection.isParagraphLastLine(lastLine) && end.currentWidget === lastLine\n && ((endOffset === selection.getLineLength(lastLine) + 1) || (selection.isEmpty && selection.end.isAtParagraphEnd))) {\n this.applyCharFormatValue(paragraph.characterFormat, property, value, update);\n }\n }\n // let count: number = 0;\n for (var i = startLineWidget; i <= endLineWidget; i++) {\n var line = paragraph.childWidgets[i];\n if (i !== startLineWidget) {\n startOffset = selection.getStartLineOffset(line);\n }\n if (line === end.currentWidget) {\n endOffset = end.offset;\n }\n else {\n endOffset = selection.getLineLength(line);\n }\n var count = 0;\n for (var j = 0; j < line.children.length; j++) {\n var inlineObj = line.children[j];\n if (inlineObj instanceof ListTextElementBox) {\n continue;\n }\n if (startOffset >= count + inlineObj.length) {\n count += inlineObj.length;\n continue;\n }\n var startIndex = 0;\n if (startOffset > count) {\n startIndex = startOffset - count;\n }\n var endIndex = endOffset - count;\n var inlineLength = inlineObj.length;\n if (endIndex > inlineLength) {\n endIndex = inlineLength;\n }\n j += this.applyCharFormatInline(inlineObj, selection, startIndex, endIndex, property, value, update);\n if (endOffset <= count + inlineLength) {\n break;\n }\n count += inlineLength;\n }\n }\n var endParagraph = end.paragraph;\n this.viewer.layout.reLayoutParagraph(paragraph, startLineWidget, 0);\n if (paragraph.equals(endParagraph)) {\n return;\n }\n this.getNextParagraphForCharacterFormatting(paragraph, start, end, property, value, update);\n };\n /**\n * Toggles the bold property of selected contents.\n */\n Editor.prototype.toggleBold = function () {\n if (this.viewer.owner.isReadOnlyMode) {\n return;\n }\n var value = this.getCurrentSelectionValue('bold');\n this.selection.characterFormat.bold = value;\n };\n /**\n * Toggles the bold property of selected contents.\n */\n Editor.prototype.toggleItalic = function () {\n if (this.viewer.owner.isReadOnlyMode) {\n return;\n }\n var value = this.getCurrentSelectionValue('italic');\n this.selection.characterFormat.italic = value;\n };\n Editor.prototype.getCurrentSelectionValue = function (property) {\n var value = false;\n if ((property === 'bold' || property === 'italic')) {\n var index = 0;\n var start = this.selection.start;\n if (!this.selection.isForward) {\n start = this.selection.end;\n }\n var lineWidget = start.currentWidget;\n var inlineObj = lineWidget.getInline(start.offset, index);\n var inline = inlineObj.element;\n // inline.ownerBase\n index = inlineObj.index;\n var characterFormat = lineWidget.paragraph.characterFormat;\n if (!isNullOrUndefined(inline)) {\n if (!this.selection.isEmpty && index === inline.length) {\n characterFormat = isNullOrUndefined(inline.nextNode) ? lineWidget.paragraph.characterFormat\n : inline.nextNode.characterFormat;\n }\n else {\n characterFormat = inline.characterFormat;\n }\n }\n if (property === 'bold') {\n value = !(characterFormat.bold);\n }\n if (property === 'italic') {\n value = !(characterFormat.italic);\n }\n }\n return value;\n };\n /**\n * Toggles the underline property of selected contents.\n * @param underline Default value of ‘underline’ parameter is Single.\n */\n Editor.prototype.toggleUnderline = function (underline) {\n if (!this.owner.isReadOnlyMode) {\n this.updateProperty(1, underline);\n }\n };\n /**\n * Toggles the strike through property of selected contents.\n * @param {Strikethrough} strikethrough Default value of strikethrough parameter is SingleStrike.\n */\n Editor.prototype.toggleStrikethrough = function (strikethrough) {\n if (!this.owner.isReadOnlyMode) {\n var value = void 0;\n if (isNullOrUndefined(strikethrough)) {\n value = this.selection.characterFormat.strikethrough === 'SingleStrike' ? 'None' : 'SingleStrike';\n }\n else {\n value = strikethrough;\n }\n this.selection.characterFormat.strikethrough = value;\n }\n };\n Editor.prototype.updateFontSize = function (format, value) {\n if (typeof (value) === 'number' && !(value < 0 && format.fontSize === 1)) {\n return format.fontSize + value;\n }\n var fontsizeCollection = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 26, 28, 36, 48, 72];\n if (typeof (value) === 'string' && value === 'increment') {\n if (format.fontSize < 8) {\n return format.fontSize + 1;\n }\n else if (format.fontSize >= 72 && format.fontSize < 80) {\n return 80;\n }\n else if (format.fontSize >= 80) {\n return format.fontSize + 10;\n }\n else {\n for (var i = 0; i < fontsizeCollection.length; i++) {\n if (format.fontSize < fontsizeCollection[i]) {\n return fontsizeCollection[i];\n }\n }\n }\n }\n else if (typeof (value) === 'string' && value === 'decrement' && format.fontSize > 1) {\n if (format.fontSize <= 8) {\n return format.fontSize - 1;\n }\n else if (format.fontSize > 72 && format.fontSize <= 80) {\n return 72;\n }\n else if (format.fontSize > 80) {\n return format.fontSize - 10;\n }\n else {\n for (var i = 0; i < fontsizeCollection.length; i++) {\n if (format.fontSize <= fontsizeCollection[i]) {\n return fontsizeCollection[i - 1];\n }\n }\n }\n }\n return format.fontSize;\n };\n // Inline\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatInline = function (inline, selection, startIndex, endIndex, property, value, update) {\n if (startIndex === 0 && endIndex === inline.length) {\n this.applyCharFormatValue(inline.characterFormat, property, value, update);\n return 0;\n }\n else if (inline instanceof TextElementBox) {\n return this.formatInline(inline, selection, startIndex, endIndex, property, value, update);\n }\n return 0;\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.formatInline = function (inline, selection, startIndex, endIndex, property, value, update) {\n var x = 0;\n var node = inline;\n var index = inline.line.children.indexOf(node);\n var paragraph = inline.paragraph;\n var lineIndex = paragraph.childWidgets.indexOf(inline.line);\n var textElement;\n if (startIndex > 0) {\n textElement = new TextElementBox();\n textElement.characterFormat.copyFormat(inline.characterFormat);\n textElement.line = inline.line;\n textElement.text = inline.text.substr(startIndex, endIndex - startIndex);\n this.applyCharFormatValue(textElement.characterFormat, property, value, update);\n index++;\n node.line.children.splice(index, 0, textElement);\n x++;\n // this.addToLinkedFields(span); \n }\n if (endIndex < node.length) {\n textElement = new TextElementBox();\n textElement.characterFormat.copyFormat(inline.characterFormat);\n textElement.text = node.text.substring(endIndex);\n textElement.line = inline.line;\n index++;\n node.line.children.splice(index, 0, textElement);\n x++;\n // this.addToLinkedFields(span); \n }\n if (startIndex === 0) {\n inline.text = inline.text.substr(0, endIndex);\n this.applyCharFormatValue(inline.characterFormat, property, value, update);\n }\n else {\n inline.text = inline.text.substr(0, startIndex);\n }\n return x;\n };\n // Cell\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatCell = function (cell, selection, start, end, property, value, update) {\n if (end.paragraph.isInsideTable) {\n var containerCell = selection.getContainerCellOf(cell, end.paragraph.associatedCell);\n if (containerCell.ownerTable.contains(end.paragraph.associatedCell)) {\n var startCell = selection.getSelectedCell(cell, containerCell);\n var endCell = selection.getSelectedCell(end.paragraph.associatedCell, containerCell);\n if (selection.containsCell(containerCell, end.paragraph.associatedCell)) {\n //Selection end is in container cell.\n if (selection.isCellSelected(containerCell, start, end)) {\n value = this.getCharacterFormatValueOfCell(cell, selection, value, property);\n this.applyCharFormatForSelectedCell(containerCell, selection, property, value, update);\n }\n else {\n if (startCell === containerCell) {\n this.applyCharFormat(start.paragraph, selection, start, end, property, value, update);\n }\n else {\n this.applyCharFormatRow(startCell.ownerRow, selection, start, end, property, value, update);\n }\n }\n }\n else {\n this.applyCharFormatForTableCell(containerCell.ownerTable, selection, containerCell, endCell, property, value, update);\n }\n }\n else {\n this.applyCharFormatRow(containerCell.ownerRow, selection, start, end, property, value, update);\n }\n }\n else {\n var tableCell = selection.getContainerCell(cell);\n this.applyCharFormatRow(tableCell.ownerRow, selection, start, end, property, value, update);\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatForSelectedCell = function (cell, selection, property, value, update) {\n for (var i = 0; i < cell.childWidgets.length; i++) {\n var block = cell.childWidgets[i];\n if (block instanceof ParagraphWidget) {\n this.applyCharFormatForSelectedPara(block, selection, property, value, update);\n }\n else {\n this.applyCharFormatForSelTable(block, selection, property, value, update);\n }\n }\n };\n // Row\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatRow = function (row, selection, start, end, property, value, update) {\n value = this.getCharacterFormatValueOfCell(row.childWidgets[0], selection, value, property);\n this.applyCharFormatForTable(row.rowIndex, row.ownerTable, selection, start, end, property, value, update);\n };\n // Table\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatForTable = function (index, table, selection, start, end, property, value, update) {\n table = table.combineWidget(this.viewer);\n for (var i = index; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n this.applyCharFormatForSelectedCell(row.childWidgets[j], selection, property, value, update);\n }\n if (end.paragraph.isInsideTable && selection.containsRow(row, end.paragraph.associatedCell)) {\n this.viewer.layout.layoutBodyWidgetCollection(table.index, table.containerWidget, table, false);\n return;\n }\n }\n this.viewer.layout.layoutBodyWidgetCollection(table.index, table.containerWidget, table, false);\n this.getNextParagraphForCharacterFormatting(table, start, end, property, value, update);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatForSelTable = function (tableWidget, selection, property, value, update) {\n for (var i = 0; i < tableWidget.childWidgets.length; i++) {\n var row = tableWidget.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n this.applyCharFormatForSelectedCell(row.childWidgets[j], selection, property, value, update);\n }\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyCharFormatForTableCell = function (table, selection, startCell, endCell, property, value, update) {\n var startCellLeft = selection.getCellLeft(startCell.ownerRow, startCell);\n var startCellRight = startCellLeft + startCell.cellFormat.cellWidth;\n var endCellLeft = selection.getCellLeft(endCell.ownerRow, endCell);\n var endCellRight = endCellLeft + endCell.cellFormat.cellWidth;\n var cellInfo = this.updateSelectedCellsInTable(startCellLeft, startCellRight, endCellLeft, endCellRight);\n startCellLeft = cellInfo.start;\n startCellRight = cellInfo.end;\n var count = table.childWidgets.indexOf(endCell.ownerRow);\n var isStarted = false;\n for (var i = table.childWidgets.indexOf(startCell.ownerRow); i <= count; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var left = selection.getCellLeft(row, row.childWidgets[j]);\n if (HelperMethods.round(startCellLeft, 2) <= HelperMethods.round(left, 2) &&\n HelperMethods.round(left, 2) < HelperMethods.round(startCellRight, 2)) {\n if (!isStarted) {\n value = this.getCharacterFormatValueOfCell(row.childWidgets[j], selection, value, property);\n isStarted = true;\n }\n this.applyCharFormatForSelectedCell(row.childWidgets[j], selection, property, value, update);\n }\n }\n }\n };\n Editor.prototype.updateSelectedCellsInTable = function (start, end, endCellLeft, endCellRight) {\n var selection = this.viewer.selection;\n if (start > endCellLeft) {\n start = endCellLeft;\n }\n if (end < endCellRight) {\n end = endCellRight;\n }\n if (start > selection.upDownSelectionLength) {\n start = selection.upDownSelectionLength;\n }\n if (end < selection.upDownSelectionLength) {\n end = selection.upDownSelectionLength;\n }\n return { start: start, end: end };\n };\n Editor.prototype.getCharacterFormatValueOfCell = function (cell, selection, value, property) {\n if (typeof (value) === 'boolean' || (value === undefined && (property === 'bold' || property === 'italic'))) {\n var firstParagraph = selection.getFirstParagraph(cell);\n var format = firstParagraph.characterFormat;\n if (firstParagraph.childWidgets.length > 0 && firstParagraph.childWidgets[0].children.length > 0) {\n format = firstParagraph.childWidgets[0].children[0].characterFormat;\n }\n value = !format.getPropertyValue(property);\n }\n return value;\n };\n /**\n * Apply Character format for selection\n * @private\n */\n Editor.prototype.applyCharFormatValueInternal = function (selection, format, property, value) {\n this.applyCharFormatValue(format, property, value, false);\n };\n Editor.prototype.copyInlineCharacterFormat = function (sourceFormat, destFormat) {\n destFormat.uniqueCharacterFormat = sourceFormat.uniqueCharacterFormat;\n destFormat.baseCharStyle = sourceFormat.baseCharStyle;\n };\n Editor.prototype.applyCharFormatValue = function (format, property, value, update) {\n if (update && property === 'fontSize') {\n value = this.updateFontSize(format, value);\n }\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n value = this.editorHistory.currentBaseHistoryInfo.addModifiedProperties(format, property, value);\n }\n if (value instanceof WCharacterFormat) {\n if (this.editorHistory && (this.editorHistory.isUndoing || this.editorHistory.isRedoing)) {\n this.copyInlineCharacterFormat(value, format);\n }\n else {\n format.copyFormat(value);\n }\n return;\n }\n if (isNullOrUndefined(value)) {\n format.clearFormat();\n return;\n }\n if (property === 'bold') {\n format.bold = value;\n }\n else if (property === 'italic') {\n format.italic = value;\n }\n else if (property === 'fontColor') {\n format.fontColor = value;\n }\n else if (property === 'fontFamily') {\n format.fontFamily = value;\n }\n else if (property === 'fontSize') {\n format.fontSize = value;\n }\n else if (property === 'highlightColor') {\n format.highlightColor = value;\n }\n else if (property === 'baselineAlignment') {\n format.baselineAlignment = value;\n }\n else if (property === 'strikethrough') {\n format.strikethrough = value;\n }\n else if (property === 'underline') {\n format.underline = value;\n }\n else if (property === 'styleName') {\n format.baseCharStyle = value;\n }\n };\n /**\n * @private\n */\n Editor.prototype.onImageFormat = function (elementBox, width, height) {\n var modifiedFormat = new ImageFormat(elementBox);\n if (this.editorHistory) {\n this.editorHistory.initializeHistory('ImageResizing');\n this.editorHistory.currentBaseHistoryInfo.modifiedProperties.push(modifiedFormat);\n }\n this.setOffsetValue(this.selection);\n elementBox.width = width;\n elementBox.height = height;\n // tslint:disable-next-line:max-line-length\n this.viewer.layout.reLayoutParagraph(elementBox.line.paragraph, elementBox.line.indexInOwner, 0);\n this.reLayout(this.selection, false);\n if (this.viewer.owner.imageResizerModule) {\n this.viewer.owner.imageResizerModule.positionImageResizer(elementBox);\n }\n };\n /**\n * Toggles the text alignment of selected paragraphs.\n * @param {TextAlignment} textAlignment\n */\n Editor.prototype.toggleTextAlignment = function (textAlignment) {\n if (this.viewer.owner.isReadOnlyMode || !this.viewer.owner.isDocumentLoaded) {\n return;\n }\n // Toggle performed based on current selection format similar to MS word behavior.\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(this.viewer.selection.paragraphFormat.textAlignment) && this.viewer.selection.paragraphFormat.textAlignment === textAlignment) {\n if (textAlignment === 'Left') {\n this.onApplyParagraphFormat('textAlignment', 'Justify', false, true);\n }\n else {\n this.onApplyParagraphFormat('textAlignment', 'Left', false, true);\n }\n }\n else {\n this.onApplyParagraphFormat('textAlignment', textAlignment, false, true);\n }\n };\n /**\n * Applies paragraph format for the selection ranges.\n * @param {string} property\n * @param {Object} value\n * @param {boolean} update\n * @param {boolean} isSelectionChanged\n * @private\n */\n Editor.prototype.onApplyParagraphFormat = function (property, value, update, isSelectionChanged) {\n var action = (property[0].toUpperCase() + property.slice(1));\n this.viewer.owner.isShiftingEnabled = true;\n var selection = this.viewer.selection;\n this.initHistory(action);\n if (this.viewer.owner.isReadOnlyMode || !this.viewer.owner.isDocumentLoaded) {\n return;\n }\n if (property === 'leftIndent') {\n if (selection.paragraphFormat.listId !== -1 && update) {\n this.updateListLevel(value > 0);\n return;\n }\n }\n if (selection.isEmpty) {\n this.setOffsetValue(selection);\n if (update && property === 'leftIndent') {\n value = this.getIndentIncrementValue(selection.start.paragraph, value);\n }\n var para = selection.start.paragraph.combineWidget(this.viewer);\n this.applyParaFormatProperty(para, property, value, update);\n this.layoutItemBlock(para, false);\n }\n else {\n //Iterate and update formatting's. \n this.setOffsetValue(selection);\n this.updateSelectionParagraphFormatting(property, value, update);\n }\n this.reLayout(selection);\n };\n /**\n * Update the list level\n * @param {boolean} increaseLevel\n * @private\n */\n Editor.prototype.updateListLevel = function (increaseLevel) {\n // Increment or Decrement list level for Multilevel lists.\n var viewer = this.viewer;\n var listFormat = this.viewer.selection.start.paragraph.paragraphFormat.listFormat;\n var paragraphFormat = this.viewer.selection.start.paragraph.paragraphFormat;\n var list = viewer.getListById(paragraphFormat.listFormat.listId);\n var listLevel = viewer.layout.getListLevel(list, paragraphFormat.listFormat.listLevelNumber);\n var levelNumber;\n if (increaseLevel) {\n levelNumber = paragraphFormat.listFormat.listLevelNumber + 1;\n }\n else {\n levelNumber = paragraphFormat.listFormat.listLevelNumber - 1;\n }\n var nextListLevel = viewer.layout.getListLevel(list, levelNumber);\n if (!isNullOrUndefined(nextListLevel)) {\n this.onApplyListInternal(list, levelNumber);\n viewer.selection.start.updatePhysicalPosition(true);\n viewer.selection.end.updatePhysicalPosition(true);\n viewer.selection.updateCaretPosition();\n }\n };\n /**\n * Applies list\n * @param {WList} list\n * @param {number} listLevelNumber\n * @private\n */\n Editor.prototype.onApplyListInternal = function (list, listLevelNumber) {\n var selection = this.viewer.selection;\n var listFormat = new WListFormat();\n if (!isNullOrUndefined(list) && listLevelNumber >= 0 && listLevelNumber < 9) {\n listFormat.listId = list.listId;\n listFormat.listLevelNumber = listLevelNumber;\n }\n this.onApplyParagraphFormat('listFormat', listFormat, false, false);\n };\n /**\n * Apply paragraph format to selection range\n * @private\n */\n Editor.prototype.updateSelectionParagraphFormatting = function (property, value, update) {\n var selection = this.viewer.selection;\n if (property === 'leftIndent' && update) {\n if (!isNullOrUndefined(selection.start) && selection.start.isExistBefore(selection.end)) {\n value = this.getIndentIncrementValue(selection.start.paragraph, value);\n }\n else {\n value = this.getIndentIncrementValue(selection.end.paragraph, value);\n }\n }\n this.updateParagraphFormatInternal(property, value, update);\n };\n Editor.prototype.getIndentIncrementValue = function (currentParagraph, incrementFactor) {\n var currentParagraphIndent = currentParagraph.paragraphFormat.leftIndent;\n if (currentParagraphIndent < 0) {\n // In MS Word, if the current paragraph left indent is lesser that or equal to 0\n // then performing decrement indent will set left indent to 0. \n if (incrementFactor < 0 || currentParagraphIndent + incrementFactor >= 0) {\n return -currentParagraphIndent;\n }\n else {\n var incrementValue = -this.getIndentIncrementValueInternal(-currentParagraphIndent, -incrementFactor);\n return incrementValue % incrementFactor === 0 ? incrementValue : incrementValue + incrementFactor;\n }\n }\n else {\n return this.getIndentIncrementValueInternal(currentParagraphIndent, incrementFactor);\n }\n };\n Editor.prototype.getIndentIncrementValueInternal = function (position, incrementFactor) {\n var tabValue = Math.abs(incrementFactor);\n if (position === 0 || tabValue === 0) {\n return incrementFactor > 0 ? tabValue : 0;\n }\n else {\n var diff = ((Math.round(position) * 100) % (Math.round(tabValue) * 100)) / 100;\n var cnt = (Math.round(position) - diff) / Math.round(tabValue);\n var fPosition = cnt * tabValue;\n if (incrementFactor > 0) {\n fPosition += tabValue;\n }\n return (fPosition - position) === 0 ? incrementFactor : fPosition - position;\n }\n };\n Editor.prototype.updateParagraphFormatInternal = function (property, value, update) {\n if (isNullOrUndefined(property)) {\n property = 'ParagraphFormat';\n }\n switch (property) {\n case 'afterSpacing':\n this.updateParagraphFormat('afterSpacing', value, false);\n break;\n case 'beforeSpacing':\n this.updateParagraphFormat('beforeSpacing', value, false);\n break;\n case 'rightIndent':\n this.updateParagraphFormat('rightIndent', value, false);\n break;\n case 'leftIndent':\n this.updateParagraphFormat('leftIndent', value, update);\n break;\n case 'firstLineIndent':\n this.updateParagraphFormat('firstLineIndent', value, false);\n break;\n case 'lineSpacing':\n this.updateParagraphFormat('lineSpacing', value, false);\n break;\n case 'lineSpacingType':\n this.updateParagraphFormat('lineSpacingType', value, false);\n break;\n case 'textAlignment':\n this.updateParagraphFormat('textAlignment', value, false);\n break;\n case 'listFormat':\n this.updateParagraphFormat('listFormat', value, false);\n break;\n case 'ParagraphFormat':\n this.updateParagraphFormat(undefined, value, false);\n break;\n case 'styleName':\n this.updateParagraphFormat('styleName', value, false);\n break;\n case 'ClearParagraphFormat':\n // this.initializeHistory('ClearParagraphFormat', selectionRange);\n this.updateParagraphFormat(undefined, value, false);\n break;\n }\n };\n /**\n * Update paragraph format on undo\n * @param {SelectionRange} selectionRange\n * @param {string} property\n * @param {Object} value\n * @param {boolean} update\n * @private\n */\n Editor.prototype.updateParagraphFormat = function (property, value, update) {\n var selection = this.viewer.selection;\n var startPosition = selection.start;\n var endPosition = selection.end;\n if (!selection.isForward) {\n startPosition = selection.end;\n endPosition = selection.start;\n }\n // this.updateInsertPosition(selection, startPosition);\n this.applyParaFormatSelectedContent(startPosition, endPosition, property, value, update);\n // this.startSelectionReLayouting(startPosition.paragraph, selection, startPosition, endPosition);\n };\n Editor.prototype.applyParaFormatSelectedContent = function (start, end, property, value, update) {\n var selection = this.viewer.selection;\n if (start.paragraph.isInsideTable && (!end.paragraph.isInsideTable\n || start.paragraph.associatedCell !== end.paragraph.associatedCell\n || selection.isCellSelected(start.paragraph.associatedCell, start, end))) {\n var cell = void 0;\n start.paragraph.associatedCell.ownerTable.combineWidget(this.viewer);\n if (this.checkInsertPosition(selection)) {\n this.updateHistoryPosition(start, true);\n }\n cell = start.paragraph.associatedCell;\n this.applyParaFormatInCell(cell, start, end, property, value, update);\n var table = cell.ownerTable;\n this.viewer.layout.layoutBodyWidgetCollection(table.index, table.containerWidget, table, false);\n }\n else {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(value) && !this.selection.isEmpty && property === 'styleName' && this.applyCharacterStyle(start.paragraph, start, end, property, value, update)) {\n return;\n }\n else {\n this.applyParaFormat(start.paragraph, start, end, property, value, update);\n }\n }\n };\n /**\n * Apply Paragraph format\n * @private\n */\n Editor.prototype.applyParaFormatProperty = function (paragraph, property, value, update) {\n var format = paragraph.paragraphFormat;\n if (update && property === 'leftIndent') {\n value = format.leftIndent + value;\n }\n if (property === 'listFormat' && value instanceof WListFormat) {\n var listFormat = value;\n if (!listFormat.hasValue('listLevelNumber')) {\n listFormat.listLevelNumber = format.listFormat.listLevelNumber;\n }\n }\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n value = this.editorHistory.currentBaseHistoryInfo.addModifiedPropertiesForParagraphFormat(format, property, value);\n }\n if (value instanceof WParagraphFormat) {\n if (isNullOrUndefined(property)) {\n if (this.editorHistory && (this.editorHistory.isUndoing || this.editorHistory.isRedoing)) {\n this.copyParagraphFormat(value, format);\n }\n else {\n format.copyFormat(value);\n }\n }\n else if (property === 'listFormat') {\n format.listFormat = value.listFormat;\n // this.handleListFormat(format, value as WParagraphFormat);\n }\n }\n if (isNullOrUndefined(value)) {\n format.clearFormat();\n this.viewer.layout.reLayoutParagraph(format.ownerBase, 0, 0);\n return;\n }\n if (property === 'afterSpacing') {\n format.afterSpacing = value;\n }\n else if (property === 'beforeSpacing') {\n format.beforeSpacing = value;\n }\n else if (property === 'leftIndent') {\n format.leftIndent = value;\n }\n else if (property === 'lineSpacingType') {\n format.lineSpacingType = value;\n }\n else if (property === 'lineSpacing') {\n format.lineSpacing = value;\n }\n else if (property === 'rightIndent') {\n format.rightIndent = value;\n }\n else if (property === 'firstLineIndent') {\n format.firstLineIndent = value;\n }\n else if (property === 'textAlignment') {\n format.textAlignment = value;\n this.viewer.layout.allowLayout = false;\n }\n else if (property === 'styleName') {\n if (typeof (value) === 'string') {\n value = this.viewer.styles.findByName(value);\n }\n format.ApplyStyle(value);\n }\n else if (property === 'listFormat') {\n if (value instanceof WParagraphFormat) {\n this.copyFromListLevelParagraphFormat(format, value);\n value = value.listFormat;\n }\n format.listFormat.copyFormat(value);\n this.viewer.layout.clearListElementBox(format.ownerBase);\n this.onListFormatChange(format.ownerBase, value, format);\n this.layoutItemBlock(format.ownerBase, false);\n return;\n }\n };\n Editor.prototype.copyParagraphFormat = function (sourceFormat, destFormat) {\n destFormat.uniqueParagraphFormat = sourceFormat.uniqueParagraphFormat;\n destFormat.listFormat = sourceFormat.listFormat;\n destFormat.baseStyle = sourceFormat.baseStyle;\n };\n Editor.prototype.onListFormatChange = function (paragraph, listFormat, paraFormat) {\n if (listFormat instanceof WListFormat) {\n var currentFormat = listFormat;\n // currentFormat.setOwnerBase(paraFormat);\n this.updateListParagraphFormat(paragraph, listFormat);\n }\n };\n Editor.prototype.updateListParagraphFormat = function (paragraph, listFormat) {\n var list = this.viewer.getListById(listFormat.listId);\n var listlevel = undefined;\n if (!isNullOrUndefined(list)) {\n listlevel = this.viewer.layout.getListLevel(list, listFormat.listLevelNumber);\n }\n var isUpdateIndent = !this.editorHistory || (this.editorHistory && !this.editorHistory.isUndoing);\n if (isUpdateIndent) {\n if (paragraph instanceof ParagraphWidget && !isNullOrUndefined(listlevel)\n && !isNullOrUndefined(listlevel.paragraphFormat) && !isNullOrUndefined(paragraph.containerWidget)) {\n this.copyFromListLevelParagraphFormat(paragraph.paragraphFormat, listlevel.paragraphFormat);\n }\n else if (isNullOrUndefined(list)) {\n paragraph.paragraphFormat.leftIndent = undefined;\n paragraph.paragraphFormat.firstLineIndent = undefined;\n }\n }\n };\n /**\n * Copies list level paragraph format\n * @param {WParagraphFormat} oldFormat\n * @param {WParagraphFormat} newFormat\n * @private\n */\n Editor.prototype.copyFromListLevelParagraphFormat = function (oldFormat, newFormat) {\n if (!isNullOrUndefined(newFormat.leftIndent)) {\n oldFormat.leftIndent = newFormat.leftIndent;\n }\n if (!isNullOrUndefined(newFormat.firstLineIndent)) {\n oldFormat.firstLineIndent = newFormat.firstLineIndent;\n }\n };\n /**\n * @private\n */\n Editor.prototype.applyContinueNumbering = function (selection) {\n this.editorHistory.initializeHistory('ContinueNumbering');\n this.applyContinueNumberingInternal(selection);\n };\n /**\n * @private\n */\n Editor.prototype.applyContinueNumberingInternal = function (selection) {\n var paragraph = selection.start.paragraph;\n var numberingInfo = this.getContinueNumberingInfo(paragraph);\n var paraFormat = this.getParagraphFormat(paragraph, numberingInfo.listLevelNumber, numberingInfo.listPattern);\n this.changeListId(numberingInfo.currentList, paragraph, paraFormat, numberingInfo.listLevelNumber, numberingInfo.listPattern);\n this.reLayout(selection, false);\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.editorHistory.updateHistory();\n }\n this.viewer.updateFocus();\n };\n /**\n * @private\n */\n Editor.prototype.getContinueNumberingInfo = function (paragraph) {\n var currentList = undefined;\n var listLevelNumber = 0;\n var listPattern = 'None';\n if (!isNullOrUndefined(paragraph.paragraphFormat)\n && !isNullOrUndefined(paragraph.paragraphFormat.listFormat)) {\n currentList = this.viewer.getListById(paragraph.paragraphFormat.listFormat.listId);\n listLevelNumber = paragraph.paragraphFormat.listFormat.listLevelNumber;\n }\n var viewer = this.viewer;\n if (listLevelNumber !== 0 && !isNullOrUndefined(currentList) &&\n !isNullOrUndefined(viewer.getAbstractListById(currentList.abstractListId))\n && !isNullOrUndefined(viewer.getAbstractListById(currentList.abstractListId).levels[listLevelNumber])) {\n var listLevel = this.viewer.layout.getListLevel(currentList, listLevelNumber);\n if (!isNullOrUndefined(listLevel)) {\n listPattern = listLevel.listLevelPattern;\n }\n }\n return {\n currentList: currentList,\n listLevelNumber: listLevelNumber,\n listPattern: listPattern\n };\n };\n /**\n * @private\n */\n Editor.prototype.revertContinueNumbering = function (selection, format) {\n var paragraph = selection.start.paragraph;\n var numberingInfo = this.getContinueNumberingInfo(paragraph);\n this.changeListId(numberingInfo.currentList, paragraph, format, numberingInfo.listLevelNumber, numberingInfo.listPattern);\n this.reLayout(selection, false);\n if (!isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.editorHistory.updateHistory();\n }\n };\n Editor.prototype.changeListId = function (list, block, format, levelNum, listType) {\n if (isNullOrUndefined(block)) {\n return;\n }\n if (block instanceof ParagraphWidget) {\n if (list.listId === block.paragraphFormat.listFormat.listId\n && levelNum === block.paragraphFormat.listFormat.listLevelNumber) {\n var baseHistoryInfo = this.editorHistory.currentBaseHistoryInfo;\n if (!isNullOrUndefined(baseHistoryInfo)) {\n format = baseHistoryInfo.addModifiedPropertiesForContinueNumbering(block.paragraphFormat, format);\n }\n block.paragraphFormat.copyFormat(format);\n this.viewer.layout.reLayoutParagraph(block, 0, 0);\n }\n }\n return this.changeListId(list, block.nextRenderedWidget, format, levelNum, listType);\n };\n Editor.prototype.getParagraphFormat = function (paragraph, levelNumber, listType) {\n if (!isNullOrUndefined(paragraph.previousRenderedWidget)) {\n if (paragraph.previousRenderedWidget instanceof ParagraphWidget) {\n if (!isNullOrUndefined(paragraph.previousRenderedWidget.paragraphFormat.listFormat)\n && paragraph.previousRenderedWidget.paragraphFormat.listFormat.listId !== -1) {\n var listLevel = this.getListLevel(paragraph.previousRenderedWidget);\n if (levelNumber === 0) {\n return paragraph.previousRenderedWidget.paragraphFormat;\n }\n else if (listType === listLevel.listLevelPattern\n || this.checkNumberArabic(listType, listLevel.listLevelPattern)) {\n return paragraph.previousRenderedWidget.paragraphFormat;\n }\n else {\n return this.getParagraphFormat(paragraph.previousRenderedWidget, levelNumber, listType);\n }\n }\n else {\n return this.getParagraphFormat(paragraph.previousRenderedWidget, levelNumber, listType);\n }\n }\n }\n return undefined;\n };\n Editor.prototype.checkNumberArabic = function (listType, levelPattern) {\n if ((listType === 'Number' && levelPattern === 'Arabic')\n || (levelPattern === 'Number' && listType === 'Arabic')) {\n return true;\n }\n return false;\n };\n /**\n * @private\n */\n Editor.prototype.applyRestartNumbering = function (selection) {\n this.editorHistory.initializeHistory('RestartNumbering');\n this.restartListAt(selection);\n };\n /**\n * @private\n */\n Editor.prototype.restartListAt = function (selection) {\n var currentListLevel = this.getListLevel(selection.start.paragraph);\n var list = new WList();\n list.listId = this.viewer.lists[(this.viewer.lists.length - 1)].listId + 1;\n var abstractList = new WAbstractList();\n abstractList.abstractListId = this.viewer.abstractLists[(this.viewer.abstractLists.length - 1)].abstractListId + 1;\n list.abstractListId = abstractList.abstractListId;\n this.viewer.abstractLists.push(abstractList);\n this.createListLevels(abstractList, currentListLevel, list);\n this.viewer.lists.push(list);\n this.restartListAtInternal(selection, list.listId);\n };\n /**\n * @private\n */\n Editor.prototype.restartListAtInternal = function (selection, listId) {\n var numberingInfo = this.getContinueNumberingInfo(selection.start.paragraph);\n this.changeRestartNumbering(numberingInfo.currentList, selection.start.paragraph, listId);\n this.reLayout(selection, false);\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.editorHistory.updateHistory();\n }\n this.incrementListNumber = -1;\n this.refListNumber = undefined;\n this.viewer.updateFocus();\n };\n Editor.prototype.changeRestartNumbering = function (list, block, listId) {\n if (isNullOrUndefined(block)) {\n return;\n }\n if (block instanceof ParagraphWidget) {\n if (list.listId === block.paragraphFormat.listFormat.listId) {\n var baseHistoryInfo = this.editorHistory.currentBaseHistoryInfo;\n if (!isNullOrUndefined(baseHistoryInfo)) {\n listId = baseHistoryInfo.addModifiedPropertiesForRestartNumbering(block.paragraphFormat.listFormat, listId);\n }\n block.paragraphFormat.listFormat.listId = listId;\n if (this.refListNumber !== block.paragraphFormat.listFormat.listLevelNumber) {\n this.incrementListNumber += 1;\n this.refListNumber = block.paragraphFormat.listFormat.listLevelNumber;\n }\n block.paragraphFormat.listFormat.listLevelNumber = this.incrementListNumber;\n this.viewer.layout.reLayoutParagraph(block, 0, 0);\n }\n }\n return this.changeRestartNumbering(list, block.nextRenderedWidget, listId);\n };\n Editor.prototype.createListLevels = function (abstractList, currentListLevel, list) {\n var levelPattern = currentListLevel.listLevelPattern;\n var levelPatterns = [];\n var currentAbstractList = currentListLevel.ownerBase;\n for (var i = 0; i < 3; i++) {\n var listLevel = currentAbstractList.levels[i];\n if (!isNullOrUndefined(listLevel)) {\n levelPatterns.push(listLevel.listLevelPattern);\n }\n }\n var indexOfLevelPattern = levelPatterns.indexOf(levelPattern) === -1 ? 0 : levelPatterns.indexOf(levelPattern);\n for (var i = 0; i < currentAbstractList.levels.length; i++) {\n var listLevel = new WListLevel(abstractList);\n if (i === 0) {\n listLevel.listLevelPattern = levelPattern;\n }\n else {\n if (indexOfLevelPattern === 0 || indexOfLevelPattern < levelPatterns.length - 1) {\n indexOfLevelPattern++;\n }\n else {\n indexOfLevelPattern = 0;\n }\n listLevel.listLevelPattern = levelPatterns[indexOfLevelPattern];\n }\n listLevel.numberFormat = '%' + (i + 1) + '.';\n listLevel.startAt = 1;\n listLevel.characterFormat.copyFormat(currentListLevel.characterFormat);\n listLevel.paragraphFormat.copyFormat(currentListLevel.paragraphFormat);\n listLevel.restartLevel = i;\n abstractList.levels.push(listLevel);\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyParaFormat = function (paragraph, start, end, property, value, update) {\n this.setOffsetValue(this.selection);\n paragraph = paragraph.combineWidget(this.viewer);\n //Apply Paragraph Format for spitted paragraph\n this.applyParaFormatProperty(paragraph, property, value, update);\n this.layoutItemBlock(paragraph, false);\n this.getOffsetValue(this.selection);\n if (paragraph.equals(end.paragraph)) {\n return;\n }\n this.getNextParagraphForFormatting(paragraph, start, end, property, value, update);\n };\n /* tslint:disable-next-line:max-line-length */\n Editor.prototype.applyCharacterStyle = function (paragraph, start, end, property, value, update) {\n var paragraphWidget = paragraph.getSplitWidgets();\n if ((end.paragraph === paragraph || paragraphWidget.indexOf(end.paragraph) !== -1)) {\n if (((value.type === 'Paragraph') && ((value.link) instanceof WCharacterStyle)) || (value.type === 'Character')) {\n var obj = (value.type === 'Character') ? value : value.link;\n this.updateSelectionCharacterFormatting(property, obj, update);\n return true;\n }\n }\n return false;\n };\n // Cell\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyParaFormatInCell = function (cell, start, end, property, value, update) {\n var selection = this.viewer.selection;\n if (end.paragraph.isInsideTable) {\n var cellContainer = selection.getContainerCellOf(cell, end.paragraph.associatedCell);\n if (cellContainer.ownerTable.contains(end.paragraph.associatedCell)) {\n var startCell = selection.getSelectedCell(cell, cellContainer);\n var endCell = selection.getSelectedCell(end.paragraph.associatedCell, cellContainer);\n if (selection.containsCell(cellContainer, end.paragraph.associatedCell)) {\n //Selection end is in container cell.\n if (selection.isCellSelected(cellContainer, start, end)) {\n value = this.getParaFormatValueInCell(cellContainer, property, value);\n this.applyParaFormatCellInternal(cellContainer, property, value, update);\n }\n else {\n if (startCell === cellContainer) {\n this.applyParaFormat(start.paragraph, start, end, property, value, update);\n }\n else {\n this.applyParagraphFormatRow(startCell.ownerRow, start, end, property, value, update);\n }\n }\n }\n else {\n //Format other selected cells in current table.\n this.applyParaFormatTableCell(cellContainer.ownerTable, cellContainer, endCell, property, value, update);\n }\n }\n else {\n this.applyParagraphFormatRow(cellContainer.ownerRow, start, end, property, value, update);\n }\n }\n else {\n var wCell = selection.getContainerCell(cell);\n this.applyParagraphFormatRow(wCell.ownerRow, start, end, property, value, update);\n }\n };\n Editor.prototype.applyParaFormatCellInternal = function (cell, property, value, update) {\n for (var i = 0; i < cell.childWidgets.length; i++) {\n var block = cell.childWidgets[i];\n if (block instanceof ParagraphWidget) {\n this.applyParaFormatProperty(block, property, value, update);\n }\n else {\n this.applyParagraphFormatTableInternal(block, property, value, update);\n }\n }\n };\n Editor.prototype.getParaFormatValueInCell = function (cell, property, value) {\n if (typeof value === 'boolean') {\n var firstPara = this.viewer.selection.getFirstParagraph(cell);\n value = !firstPara.paragraphFormat.getPropertyValue(property);\n }\n return value;\n };\n // Row\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyParagraphFormatRow = function (wRow, start, end, property, value, update) {\n value = this.getParaFormatValueInCell(wRow.childWidgets[0], property, value);\n for (var i = wRow.rowIndex; i < wRow.ownerTable.childWidgets.length; i++) {\n var row = wRow.ownerTable.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n this.applyParaFormatCellInternal(row.childWidgets[j], property, value, update);\n }\n if (end.paragraph.isInsideTable && this.viewer.selection.containsRow(row, end.paragraph.associatedCell)) {\n return;\n }\n }\n this.getNextParagraphForFormatting(wRow.ownerTable, start, end, property, value, update);\n };\n // Table\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyParaFormatTableCell = function (table, startCell, endCell, property, value, update) {\n var selection = this.viewer.selection;\n var startValue = selection.getCellLeft(startCell.ownerRow, startCell);\n var endValue = startValue + startCell.cellFormat.cellWidth;\n var endCellLeft = selection.getCellLeft(endCell.ownerRow, endCell);\n var endCellRight = endCellLeft + endCell.cellFormat.cellWidth;\n var cellInfo = this.updateSelectedCellsInTable(startValue, endValue, endCellLeft, endCellRight);\n startValue = cellInfo.start;\n endValue = cellInfo.end;\n var count = table.childWidgets.indexOf(endCell.ownerRow);\n var isStarted = false;\n for (var m = table.childWidgets.indexOf(startCell.ownerRow); m <= count; m++) {\n var row = table.childWidgets[m];\n for (var j = 0; j < row.childWidgets.length; j++) {\n var left = selection.getCellLeft(row, row.childWidgets[j]);\n if (Math.round(startValue) <= Math.round(left) && Math.round(left) < Math.round(endValue)) {\n if (!isStarted) {\n value = this.getParaFormatValueInCell(row.childWidgets[j], property, value);\n isStarted = true;\n }\n this.applyParaFormatCellInternal(row.childWidgets[j], property, value, update);\n }\n }\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyParaFormatTable = function (table, start, end, property, value, update) {\n table = table.combineWidget(this.viewer);\n var selection = this.viewer.selection;\n for (var m = 0; m < table.childWidgets.length; m++) {\n var tableRow = table.childWidgets[m];\n for (var k = 0; k < tableRow.childWidgets.length; k++) {\n this.applyParaFormatCellInternal(tableRow.childWidgets[k], property, value, update);\n }\n if (end.paragraph.isInsideTable && selection.containsRow(tableRow, end.paragraph.associatedCell)) {\n this.viewer.layout.layoutBodyWidgetCollection(table.index, table.containerWidget, table, false);\n return;\n }\n }\n this.viewer.layout.layoutBodyWidgetCollection(table.index, table.containerWidget, table, false);\n this.getNextParagraphForFormatting(table, start, end, property, value, update);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.getNextParagraphForFormatting = function (block, start, end, property, value, update) {\n var widgetCollection = block.getSplitWidgets();\n block = widgetCollection[widgetCollection.length - 1];\n block = this.viewer.selection.getNextRenderedBlock(block);\n if (!isNullOrUndefined(block)) {\n if (block instanceof ParagraphWidget) {\n this.applyParaFormat(block, start, end, property, value, update);\n }\n else {\n this.applyParaFormatTable(block, start, end, property, value, update);\n }\n }\n };\n Editor.prototype.applyParagraphFormatTableInternal = function (table, property, value, update) {\n for (var x = 0; x < table.childWidgets.length; x++) {\n var row = table.childWidgets[x];\n for (var y = 0; y < row.childWidgets.length; y++) {\n this.applyParaFormatCellInternal(row.childWidgets[y], property, value, update);\n }\n }\n };\n //Paragraph Format apply implementation Ends\n // Apply Selection Section Format Option Implementation Starts\n /**\n * Apply section format selection changes\n * @param {string} property\n * @param {Object} value\n * @private\n */\n Editor.prototype.onApplySectionFormat = function (property, value) {\n if (!isNullOrUndefined(property)) {\n var action = (property[0].toUpperCase() + property.slice(1));\n this.initHistory(action);\n }\n else {\n this.initHistory('SectionFormat');\n }\n this.updateSectionFormat(property, value);\n };\n /**\n * Update section format\n * @param {string} property\n * @param {Object} value\n * @returns TextPosition\n * @private\n */\n Editor.prototype.updateSectionFormat = function (property, value) {\n var selection = this.viewer.selection;\n selection.owner.isShiftingEnabled = true;\n var startPosition = selection.start;\n var endPosition = selection.end;\n if (!selection.isForward) {\n startPosition = selection.end;\n endPosition = selection.start;\n }\n var startPageIndex;\n var endPageIndex;\n this.viewer.clearContent();\n var startSectionIndex = startPosition.paragraph.containerWidget.index;\n var endSectionIndex = endPosition.paragraph.containerWidget.index;\n for (var i = 0; i < this.viewer.pages.length; i++) {\n if (this.viewer.pages[i].bodyWidgets[0].index === startSectionIndex) {\n startPageIndex = i;\n break;\n }\n }\n for (var i = startPageIndex; i < this.viewer.pages.length; i++) {\n var bodyWidget = this.viewer.pages[i].bodyWidgets[0];\n endPageIndex = i;\n if ((bodyWidget.index === startSectionIndex)) {\n continue;\n }\n else if ((bodyWidget.index >= startSectionIndex) && bodyWidget.index <= endSectionIndex) {\n continue;\n }\n else {\n endPageIndex = i - 1;\n break;\n }\n }\n // let startPageIndex: number = this.viewer.pages.indexOf((selection.start.paragraph.containerWidget as BodyWidget).page);\n // let endPageIndex: number = this.viewer.pages.indexOf((selection.end.paragraph.containerWidget as BodyWidget).page);\n var update = true;\n var index = 0;\n for (var i = startPageIndex; i <= endPageIndex; i++) {\n if (index !== this.viewer.pages[i].bodyWidgets[0].index && !update) {\n update = true;\n }\n this.applyPropertyValueForSection(this.viewer.pages[i].bodyWidgets[0].sectionFormat, property, value, update);\n index = this.viewer.pages[i].bodyWidgets[0].index;\n update = false;\n }\n this.layoutWholeDocument();\n this.fireContentChange();\n };\n //Apply Selection Table Format option implementation starts\n /**\n * Apply table format property changes\n * @param {string} property\n * @param {Object} value\n * @private\n */\n Editor.prototype.onApplyTableFormat = function (property, value) {\n var action = this.getTableFormatAction(property);\n this.viewer.owner.isShiftingEnabled = true;\n var selection = this.viewer.selection;\n var table = selection.start.paragraph.associatedCell.ownerTable;\n table = table.combineWidget(this.viewer);\n if (selection.isEmpty) {\n this.initHistory(action);\n this.applyTablePropertyValue(selection, property, value, table);\n }\n else {\n this.updateSelectionTableFormat(this.selection, action, value);\n }\n table.calculateGrid();\n this.selection.owner.isLayoutEnabled = true;\n this.viewer.layout.reLayoutTable(table);\n this.reLayout(selection, false);\n };\n Editor.prototype.getTableFormatAction = function (property) {\n switch (property) {\n case 'tableAlignment':\n return 'TableAlignment';\n case 'leftIndent':\n return 'TableLeftIndent';\n case 'leftMargin':\n return 'DefaultCellLeftMargin';\n case 'rightMargin':\n return 'DefaultCellRightMargin';\n case 'bottomMargin':\n return 'DefaultCellBottomMargin';\n case 'topMargin':\n return 'DefaultCellTopMargin';\n case 'preferredWidth':\n return 'TablePreferredWidth';\n case 'preferredWidthType':\n return 'TablePreferredWidthType';\n case 'shading':\n return 'Shading';\n default:\n return 'DefaultCellSpacing';\n }\n };\n // Apply Selection Row Format Option Implementation Starts\n /**\n * Apply table row format property changes\n * @param {string} property\n * @param {Object} value\n * @private\n */\n Editor.prototype.onApplyTableRowFormat = function (property, value) {\n var action = this.getRowAction(property);\n this.viewer.owner.isShiftingEnabled = true;\n var selection = this.viewer.selection;\n if (selection.isEmpty) {\n this.initHistory(action);\n var table = selection.start.paragraph.associatedCell.ownerRow.ownerTable;\n this.applyRowPropertyValue(selection, property, value, selection.start.paragraph.associatedCell.ownerRow);\n }\n else {\n this.updateSelectionTableFormat(this.selection, action, value);\n }\n this.reLayout(selection, false);\n };\n Editor.prototype.getRowAction = function (property) {\n switch (property) {\n case 'height':\n return 'RowHeight';\n case 'heightType':\n return 'RowHeightType';\n case 'isHeader':\n return 'RowHeader';\n default:\n return 'AllowBreakAcrossPages';\n }\n };\n /**\n * Apply table cell property changes\n * @param {string} property\n * @param {Object} value\n * @private\n */\n Editor.prototype.onApplyTableCellFormat = function (property, value) {\n var action = this.getTableCellAction(property);\n this.viewer.owner.isShiftingEnabled = true;\n var selection = this.viewer.selection;\n var table = selection.start.paragraph.associatedCell.ownerTable;\n table = table.combineWidget(this.viewer);\n if (selection.isEmpty) {\n this.initHistory(action);\n this.applyCellPropertyValue(selection, property, value, selection.start.paragraph.associatedCell.cellFormat);\n table.calculateGrid();\n this.selection.owner.isLayoutEnabled = true;\n this.viewer.layout.reLayoutTable(table);\n }\n else {\n this.updateSelectionTableFormat(this.selection, action, value);\n }\n this.reLayout(selection, false);\n };\n Editor.prototype.getTableCellAction = function (property) {\n switch (property) {\n case 'verticalAlignment':\n return 'CellContentVerticalAlignment';\n case 'leftMargin':\n return 'CellLeftMargin';\n case 'rightMargin':\n return 'CellRightMargin';\n case 'bottomMargin':\n return 'CellBottomMargin';\n case 'topMargin':\n return 'CellTopMargin';\n case 'preferredWidth':\n return 'CellPreferredWidth';\n case 'shading':\n return 'Shading';\n default:\n return 'CellPreferredWidthType';\n }\n };\n Editor.prototype.applyPropertyValueForSection = function (sectionFormat, property, value, update) {\n var selection = this.viewer.selection;\n if (update && this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n value = this.editorHistory.currentBaseHistoryInfo.addModifiedPropertiesForSection(sectionFormat, property, value);\n }\n if (isNullOrUndefined(value)) {\n return;\n }\n if (value instanceof WSectionFormat) {\n if (isNullOrUndefined(property)) {\n sectionFormat.copyFormat(value, this.editorHistory);\n }\n return;\n }\n if (property === 'pageHeight') {\n sectionFormat.pageHeight = value;\n }\n else if (property === 'pageWidth') {\n sectionFormat.pageWidth = value;\n }\n else if (property === 'leftMargin') {\n sectionFormat.leftMargin = value;\n }\n else if (property === 'rightMargin') {\n sectionFormat.rightMargin = value;\n }\n else if (property === 'topMargin') {\n sectionFormat.topMargin = value;\n }\n else if (property === 'bottomMargin') {\n sectionFormat.bottomMargin = value;\n }\n else if (property === 'differentFirstPage') {\n sectionFormat.differentFirstPage = value;\n }\n else if (property === 'differentOddAndEvenPages') {\n sectionFormat.differentOddAndEvenPages = value;\n }\n else if (property === 'headerDistance') {\n sectionFormat.headerDistance = value;\n }\n else if (property === 'footerDistance') {\n sectionFormat.footerDistance = value;\n }\n };\n /**\n * @private\n */\n Editor.prototype.layoutWholeDocument = function () {\n var startPosition = this.viewer.selection.start;\n var endPosition = this.viewer.selection.end;\n if (startPosition.isExistAfter(endPosition)) {\n startPosition = this.viewer.selection.end;\n endPosition = this.viewer.selection.start;\n }\n var startInfo = this.getParagraphInfo(startPosition);\n var endInfo = this.getParagraphInfo(startPosition);\n var startIndex = this.getHierarchicalIndex(startInfo.paragraph, startInfo.offset.toString());\n var endIndex = this.getHierarchicalIndex(endInfo.paragraph, endInfo.offset.toString());\n this.viewer.renderedLists.clear();\n // this.viewer.owner.isLayoutEnabled = true;\n var sections = this.combineSection();\n this.viewer.clearContent();\n this.viewer.layout.layoutItems(sections);\n this.viewer.owner.isShiftingEnabled = false;\n this.setPositionForCurrentIndex(startPosition, startIndex);\n this.setPositionForCurrentIndex(endPosition, endIndex);\n this.viewer.selection.selectPosition(startPosition, endPosition);\n this.reLayout(this.viewer.selection);\n };\n Editor.prototype.combineSection = function () {\n var sections = [];\n var nextSection = this.viewer.pages[0].bodyWidgets[0];\n do {\n nextSection = this.combineSectionChild(nextSection, sections);\n } while (nextSection);\n return sections;\n };\n Editor.prototype.combineSectionChild = function (bodyWidget, sections) {\n var previousBodyWidget = bodyWidget;\n var temp = new BodyWidget();\n temp.sectionFormat = bodyWidget.sectionFormat;\n temp.index = previousBodyWidget.index;\n do {\n previousBodyWidget = bodyWidget;\n if (bodyWidget.lastChild) {\n bodyWidget.lastChild.combineWidget(this.viewer);\n }\n bodyWidget = bodyWidget.nextRenderedWidget;\n for (var j = 0; j < previousBodyWidget.childWidgets.length; j++) {\n var block = previousBodyWidget.childWidgets[j];\n if (block instanceof TableWidget) {\n this.viewer.layout.clearTableWidget(block, true, true);\n }\n else {\n block.x = 0;\n block.y = 0;\n block.width = 0;\n block.height = 0;\n }\n temp.childWidgets.push(block);\n previousBodyWidget.childWidgets.splice(j, 1);\n j--;\n block.containerWidget = temp;\n }\n this.viewer.pages.splice(previousBodyWidget.page.index, 1);\n } while (bodyWidget && previousBodyWidget.equals(bodyWidget));\n sections.push(temp);\n return bodyWidget;\n };\n Editor.prototype.updateSelectionTableFormat = function (selection, action, value) {\n switch (action) {\n case 'TableAlignment':\n this.editorHistory.initializeHistory('TableAlignment');\n this.updateTableFormat(selection, 'tableAlignment', value);\n break;\n case 'TableLeftIndent':\n this.editorHistory.initializeHistory('TableLeftIndent');\n this.updateTableFormat(selection, 'leftIndent', value);\n break;\n case 'DefaultCellSpacing':\n this.editorHistory.initializeHistory('DefaultCellSpacing');\n this.updateTableFormat(selection, 'cellSpacing', value);\n break;\n case 'DefaultCellLeftMargin':\n this.editorHistory.initializeHistory('DefaultCellLeftMargin');\n this.updateTableFormat(selection, 'leftMargin', value);\n break;\n case 'DefaultCellRightMargin':\n this.editorHistory.initializeHistory('DefaultCellRightMargin');\n this.updateTableFormat(selection, 'rightMargin', value);\n break;\n case 'DefaultCellTopMargin':\n this.editorHistory.initializeHistory('DefaultCellTopMargin');\n this.updateTableFormat(selection, 'topMargin', value);\n break;\n case 'TablePreferredWidth':\n this.editorHistory.initializeHistory('TablePreferredWidth');\n this.updateTableFormat(selection, 'preferredWidth', value);\n break;\n case 'TablePreferredWidthType':\n this.editorHistory.initializeHistory('TablePreferredWidthType');\n this.updateTableFormat(selection, 'preferredWidthType', value);\n break;\n case 'DefaultCellBottomMargin':\n this.editorHistory.initializeHistory('DefaultCellBottomMargin');\n this.updateTableFormat(selection, 'bottomMargin', value);\n break;\n case 'CellContentVerticalAlignment':\n this.editorHistory.initializeHistory('CellContentVerticalAlignment');\n this.updateCellFormat(selection, 'verticalAlignment', value);\n break;\n case 'CellLeftMargin':\n this.editorHistory.initializeHistory('CellLeftMargin');\n this.updateCellFormat(selection, 'leftMargin', value);\n break;\n case 'CellRightMargin':\n this.editorHistory.initializeHistory('CellRightMargin');\n this.updateCellFormat(selection, 'rightMargin', value);\n break;\n case 'CellTopMargin':\n this.editorHistory.initializeHistory('CellTopMargin');\n this.updateCellFormat(selection, 'topMargin', value);\n break;\n case 'CellBottomMargin':\n this.editorHistory.initializeHistory('CellBottomMargin');\n this.updateCellFormat(selection, 'bottomMargin', value);\n break;\n case 'CellPreferredWidth':\n this.editorHistory.initializeHistory('CellPreferredWidth');\n this.updateCellFormat(selection, 'preferredWidth', value);\n break;\n case 'CellPreferredWidthType':\n this.editorHistory.initializeHistory('CellPreferredWidthType');\n this.updateCellFormat(selection, 'preferredWidthType', value);\n break;\n case 'Shading':\n this.editorHistory.initializeHistory('Shading');\n this.updateCellFormat(selection, 'shading', value);\n break;\n case 'RowHeight':\n this.editorHistory.initializeHistory('RowHeight');\n this.updateRowFormat(selection, 'height', value);\n break;\n case 'RowHeightType':\n this.editorHistory.initializeHistory('RowHeightType');\n this.updateRowFormat(selection, 'heightType', value);\n break;\n case 'RowHeader':\n this.editorHistory.initializeHistory('RowHeader');\n this.updateRowFormat(selection, 'isHeader', value);\n break;\n case 'AllowBreakAcrossPages':\n this.editorHistory.initializeHistory('AllowBreakAcrossPages');\n this.updateRowFormat(selection, 'allowBreakAcrossPages', value);\n break;\n }\n };\n // Update Table Properties\n /**\n * Update Table Format on undo\n * @param {Selection} selection\n * @param {SelectionRange} selectionRange\n * @param {string} property\n * @param {object} value\n * @private\n */\n Editor.prototype.updateTableFormat = function (selection, property, value) {\n var tableStartPosition = selection.start;\n var tableEndPosition = selection.end;\n if (!selection.isForward) {\n tableStartPosition = selection.end;\n tableEndPosition = selection.start;\n }\n this.initHistoryPosition(selection, tableStartPosition);\n // tslint:disable-next-line:max-line-length\n this.applyTablePropertyValue(selection, property, value, tableStartPosition.paragraph.associatedCell.ownerTable);\n };\n /**\n * update cell format on undo\n * @param {Selection} selection\n * @param {SelectionRange} selectionRange\n * @param {string} property\n * @param {Object} value\n * @private\n */\n Editor.prototype.updateCellFormat = function (selection, property, value) {\n selection.owner.isShiftingEnabled = true;\n var newStartPosition = selection.start;\n var newEndPosition = selection.end;\n if (!selection.isForward) {\n newStartPosition = selection.end;\n newEndPosition = selection.start;\n }\n this.initHistoryPosition(selection, newStartPosition);\n this.updateFormatForCell(selection, property, value);\n };\n /**\n * update row format on undo\n * @param {Selection} selection\n * @param {SelectionRange} selectionRange\n * @param {string} property\n * @param {Object} value\n * @private\n */\n Editor.prototype.updateRowFormat = function (selection, property, value) {\n var rowStartPosition = selection.start;\n var rowEndPosition = selection.end;\n if (!selection.isForward) {\n rowStartPosition = selection.end;\n rowEndPosition = selection.start;\n }\n this.initHistoryPosition(selection, rowStartPosition);\n // tslint:disable-next-line:max-line-length\n this.applyRowFormat(rowStartPosition.paragraph.associatedCell.ownerRow, rowStartPosition, rowEndPosition, property, value);\n };\n Editor.prototype.initHistoryPosition = function (selection, position) {\n if (this.viewer.owner.editorHistoryModule && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n if (!isNullOrUndefined(position)) {\n if (isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo.insertPosition)) {\n this.editorHistory.currentBaseHistoryInfo.insertPosition = position.getHierarchicalIndexInternal();\n }\n }\n else if (isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo.insertPosition)) {\n this.editorHistory.currentBaseHistoryInfo.insertPosition = selection.start.getHierarchicalIndexInternal();\n }\n }\n };\n Editor.prototype.startSelectionReLayouting = function (paragraph, selection, start, end) {\n selection.owner.isLayoutEnabled = true;\n if (start.paragraph.isInsideTable) {\n var table = start.paragraph.associatedCell.ownerTable;\n while (table.isInsideTable) {\n table = table.associatedCell.ownerTable;\n }\n this.reLayoutSelectionOfTable(table, selection, start, end);\n }\n else {\n this.reLayoutSelection(paragraph, selection, start, end);\n }\n };\n Editor.prototype.reLayoutSelectionOfTable = function (table, selection, start, end) {\n var isEnded = false;\n this.viewer.layout.layoutBodyWidgetCollection(table.index, table.containerWidget, table, false);\n // If the selection ends in the current table, need to stop relayouting.\n if (!isNullOrUndefined(end.paragraph.associatedCell) && table.contains(end.paragraph.associatedCell)) {\n return true;\n }\n var block = selection.getNextRenderedBlock(table);\n // Relayout the next block.\n if (!isNullOrUndefined(block)) {\n isEnded = this.reLayoutSelectionOfBlock(block, selection, start, end);\n }\n return isEnded;\n };\n Editor.prototype.reLayoutSelection = function (paragraph, selection, start, end) {\n if (start.paragraph === paragraph) {\n var startOffset = start.offset;\n var length_2 = selection.getParagraphLength(paragraph);\n var indexInInline = 0;\n var index = 0;\n var inlineObj = paragraph.getInline(start.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (!isNullOrUndefined(inline)) {\n if (indexInInline === inline.length && !isNullOrUndefined(inline.nextNode)) {\n inline = inline.nextNode;\n }\n index = inline.line.children.indexOf(inline);\n }\n var lineIndex = 0;\n if (start.currentWidget.paragraph === paragraph) {\n lineIndex = paragraph.childWidgets.indexOf(start.currentWidget);\n index = start.currentWidget.children.indexOf(inline);\n }\n // If selection start inline is at new inline, need to relayout from the previous inline.\n if (inline instanceof TextElementBox && !inline.line && index > 0) {\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, index - 1);\n }\n else {\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, index);\n }\n }\n else {\n this.viewer.layout.reLayoutParagraph(paragraph, 0, 0);\n }\n // If the selection ends at the current paragraph, need to stop relayouting.\n if (end.paragraph === paragraph) {\n return true;\n }\n // _Relayout the next block.\n var block = selection.getNextRenderedBlock(paragraph);\n if (!isNullOrUndefined(block)) {\n return this.reLayoutSelectionOfBlock(block, selection, start, end);\n }\n return false;\n };\n //Relayouting Start \n Editor.prototype.reLayoutSelectionOfBlock = function (block, selection, start, end) {\n if (block instanceof ParagraphWidget) {\n return this.reLayoutSelection(block, selection, start, end);\n }\n else {\n return undefined;\n // return this.reLayoutSelectionOfTable(block as TableWidget, selection, start, end);\n }\n };\n /**\n * @private\n */\n Editor.prototype.layoutItemBlock = function (block, shiftNextWidget) {\n var section = undefined;\n if (block.containerWidget instanceof BlockContainer) {\n section = block.containerWidget;\n var index = section.childWidgets.indexOf(block);\n if (!isNullOrUndefined(this.viewer.owner)\n && this.viewer.owner.isLayoutEnabled) {\n // tslint:disable-next-line:max-line-length\n this.viewer.layout.layoutBodyWidgetCollection(block.index, section, block, false);\n }\n }\n else if (block.containerWidget instanceof TableCellWidget) {\n var cell = block.containerWidget;\n cell = this.viewer.selection.getContainerCell(cell);\n if (!isNullOrUndefined(this.viewer.owner)\n && this.viewer.owner.isLayoutEnabled) {\n this.viewer.layout.reLayoutTable(block);\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.removeSelectedContents = function (selection) {\n return this.removeSelectedContentInternal(selection, selection.start, selection.end);\n };\n Editor.prototype.removeSelectedContentInternal = function (selection, startPosition, endPosition) {\n var startPos = startPosition;\n var endPos = endPosition;\n if (!startPosition.isExistBefore(endPosition)) {\n startPos = endPosition;\n endPos = startPosition;\n }\n // tslint:disable-next-line:max-line-length\n if (startPos.paragraph === endPos.paragraph && startPos.paragraph.childWidgets.indexOf(startPos.currentWidget) === startPos.paragraph.childWidgets.length - 1 &&\n startPos.offset === selection.getParagraphLength(startPos.paragraph) && startPos.offset + 1 === endPos.offset) {\n selection.owner.isShiftingEnabled = true;\n selection.selectContent(startPos, true);\n return true;\n }\n var paragraphInfo = this.getParagraphInfo(startPos);\n selection.editPosition = this.getHierarchicalIndex(paragraphInfo.paragraph, paragraphInfo.offset.toString());\n var isRemoved = this.removeSelectedContent(endPos.paragraph, selection, startPos, endPos);\n var textPosition = new TextPosition(selection.owner);\n this.setPositionForCurrentIndex(textPosition, selection.editPosition);\n selection.selectContent(textPosition, true);\n return isRemoved;\n };\n Editor.prototype.removeSelectedContent = function (paragraph, selection, start, end) {\n //If end is not table end and start is outside the table, then skip removing the contents and move caret to start position.\n if (end.paragraph.isInsideTable\n && end.paragraph !== selection.getLastParagraphInLastCell(end.paragraph.associatedCell.ownerTable)\n && (!start.paragraph.isInsideTable || start.paragraph.associatedCell.ownerTable !== end.paragraph.associatedCell.ownerTable)) {\n return false;\n }\n selection.owner.isShiftingEnabled = true;\n this.deleteSelectedContent(paragraph, selection, start, end, 2);\n return true;\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.deleteSelectedContent = function (paragraph, selection, start, end, editAction) {\n var indexInInline = 0;\n var inlineObj = start.currentWidget.getInline(start.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n // if (!isNullOrUndefined(inline)) {\n // inline = selection.getNextRenderedInline(inline, indexInInline);\n // }\n // if (inline instanceof WFieldBegin && !isNullOrUndefined((inline as WFieldBegin).fieldEnd)) {\n // tslint:disable-next-line:max-line-length\n // let fieldEndOffset: number = ((inline as WFieldBegin).fieldEnd.owner as WParagraph).getOffset((inline as WFieldBegin).fieldEnd, 1);\n // let fieldEndIndex: string = WordDocument.getHierarchicalIndexOf((inline as WFieldBegin).fieldEnd.owner as WParagraph, fieldEndOffset.toString());\n // let selectionEndIndex: string = end.getHierarchicalIndexInternal();\n // if (!TextPosition.isForwardSelection(fieldEndIndex, selectionEndIndex)) {\n // //If selection end is after field begin, moves selection start to field separator.\n // start.moveToInline((inline as WFieldBegin).fieldSeparator, 1);\n // selection.editPosition = start.getHierarchicalIndexInternal();\n // if (!isNullOrUndefined(selection.currentBaseHistoryInfo)) {\n // selection.currentBaseHistoryInfo.insertPosition = selection.editPosition;\n // }\n // }\n // }\n indexInInline = 0;\n inlineObj = end.currentWidget.getInline(end.offset, indexInInline);\n inline = inlineObj.element;\n indexInInline = inlineObj.index;\n // if (!isNullOrUndefined(inline)) {\n // inline = selection.getNextRenderedInline(inline, indexInInline);\n // }\n // if (inline instanceof WFieldEnd && !isNullOrUndefined((inline as WFieldEnd).fieldBegin)) {\n // tslint:disable-next-line:max-line-length\n // let fieldBeginOffset: number = ((inline as WFieldEnd).fieldBegin.owner as WParagraph).getOffset((inline as WFieldEnd).fieldBegin, 0);\n // let fieldBeginIndex: string = WordDocument.getHierarchicalIndexOf((inline as WFieldEnd).fieldBegin.owner as WParagraph, fieldBeginOffset.toString());\n // let selectionStartIndex: string = start.getHierarchicalIndexInternal();\n // if (!TextPosition.isForwardSelection(selectionStartIndex, fieldBeginIndex)) {\n // //If field begin is before selection start, move selection end to inline item before field end.\n // let prevInline: WInline = selection.getPreviousTextInline(inline);\n // if (isNullOrUndefined(prevInline)) {\n // end.moveBackward();\n // } else {\n // end.moveToInline(prevInline, prevInline.length);\n // }\n // }\n // }\n if (end.paragraph !== paragraph) {\n this.deleteSelectedContent(end.paragraph, selection, start, end, editAction);\n return;\n }\n // Selection start in cell.\n if (end.paragraph.isInsideTable && (!start.paragraph.isInsideTable\n || start.paragraph.associatedCell !== end.paragraph.associatedCell\n || selection.isCellSelected(end.paragraph.associatedCell, start, end))) {\n end.paragraph.associatedCell.ownerTable.combineWidget(this.viewer);\n this.deleteTableCell(end.paragraph.associatedCell, selection, start, end, editAction);\n }\n else {\n this.deletePara(paragraph, start, end, editAction);\n }\n };\n /**\n * Merge the selected cells.\n */\n Editor.prototype.mergeCells = function () {\n if (this.owner.isReadOnlyMode || !this.owner.isDocumentLoaded) {\n return;\n }\n if (!isNullOrUndefined(this.viewer) && !this.selection.isEmpty) {\n this.mergeSelectedCellsInTable();\n }\n };\n /**\n * Deletes the entire table at selection.\n */\n Editor.prototype.deleteTable = function () {\n if (this.owner.isReadOnlyMode) {\n return;\n }\n var startPos = this.selection.isForward ? this.selection.start : this.selection.end;\n if (startPos.paragraph.isInsideTable) {\n var table = this.getOwnerTable(this.selection.isForward).combineWidget(this.viewer);\n this.selection.owner.isShiftingEnabled = true;\n if (this.checkIsNotRedoing()) {\n this.initHistory('DeleteTable');\n //Sets the insert position in history info as current table. \n this.updateHistoryPosition(startPos, true);\n }\n var paragraph = this.getParagraphForSelection(table);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.editorHistory.currentBaseHistoryInfo.removedNodes.push(table.clone());\n }\n this.removeBlock(table);\n this.selection.selectParagraph(paragraph, true);\n if (this.checkIsNotRedoing() || isNullOrUndefined(this.editorHistory)) {\n this.reLayout(this.selection);\n }\n }\n };\n /**\n * Deletes the selected column(s).\n */\n Editor.prototype.deleteColumn = function () {\n if (this.owner.isReadOnlyMode) {\n return;\n }\n var startPos = this.selection.isForward ? this.selection.start : this.selection.end;\n var endPos = this.selection.isForward ? this.selection.end : this.selection.start;\n if (startPos.paragraph.isInsideTable) {\n this.selection.owner.isShiftingEnabled = true;\n if (this.checkIsNotRedoing()) {\n this.initHistory('DeleteColumn');\n }\n var startCell = this.getOwnerCell(this.selection.isForward);\n var endCell = this.getOwnerCell(!this.selection.isForward);\n var table = startCell.ownerTable.combineWidget(this.viewer);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.cloneTableToHistoryInfo(table);\n }\n var paragraph = undefined;\n if (endCell.nextWidget) {\n var nextCell = endCell.nextWidget;\n paragraph = this.selection.getFirstParagraph(nextCell);\n }\n else if (startCell.previousWidget) {\n var previousCell = startCell.previousWidget;\n paragraph = this.selection.getFirstParagraph(previousCell);\n }\n if (isNullOrUndefined(paragraph)) {\n paragraph = this.getParagraphForSelection(table);\n }\n //retrieve the cell collection based on start and end cell to remove. \n var deleteCells = table.getColumnCellsForSelection(startCell, endCell);\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row.childWidgets.length === 1) {\n if (deleteCells.indexOf(row.childWidgets[0]) >= 0) {\n table.childWidgets.splice(table.childWidgets.indexOf(row), 1);\n row.destroy();\n i--;\n }\n }\n else {\n for (var j = 0; j < row.childWidgets.length; j++) {\n var tableCell = row.childWidgets[j];\n if (deleteCells.indexOf(tableCell) >= 0) {\n row.childWidgets.splice(j, 1);\n tableCell.destroy();\n j--;\n }\n }\n if (row.childWidgets.length === 0) {\n table.childWidgets.splice(table.childWidgets.indexOf(row), 1);\n row.destroy();\n i--;\n }\n }\n }\n if (table.childWidgets.length === 0) {\n // Before disposing table reset the paragrph.\n paragraph = this.getParagraphForSelection(table);\n this.removeBlock(table);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.editorHistory.currentBaseHistoryInfo.action = 'DeleteTable';\n }\n table.destroy();\n }\n else {\n table.isGridUpdated = false;\n table.buildTableColumns();\n table.isGridUpdated = true;\n this.viewer.layout.reLayoutTable(table);\n }\n this.selection.selectParagraph(paragraph, true);\n if (isNullOrUndefined(this.editorHistory) || this.checkIsNotRedoing()) {\n this.reLayout(this.selection, true);\n }\n }\n };\n /**\n * Deletes the selected row(s).\n */\n Editor.prototype.deleteRow = function () {\n if (this.owner.isReadOnlyMode) {\n return;\n }\n var startPos = !this.selection.isForward ? this.selection.end : this.selection.start;\n var endPos = !this.selection.isForward ? this.selection.start : this.selection.end;\n if (startPos.paragraph.isInsideTable) {\n var startCell = this.getOwnerCell(this.selection.isForward);\n var endCell = this.getOwnerCell(!this.selection.isForward);\n if (this.checkIsNotRedoing()) {\n this.initHistory('DeleteRow');\n }\n this.selection.owner.isShiftingEnabled = true;\n var table = startCell.ownerTable.combineWidget(this.viewer);\n var row = this.getOwnerRow(true);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.cloneTableToHistoryInfo(table);\n }\n var paragraph = undefined;\n if (row.nextWidget) {\n var nextCell = row.nextWidget.childWidgets[0];\n paragraph = this.selection.getFirstParagraph(nextCell);\n }\n if (isNullOrUndefined(paragraph)) {\n paragraph = this.getParagraphForSelection(table);\n }\n if (!this.selection.isEmpty) {\n //tslint:disable-next-line:max-line-length\n var containerCell = this.selection.getContainerCellOf(startCell, endCell);\n if (containerCell.ownerTable.contains(endCell)) {\n startCell = this.selection.getSelectedCell(startCell, containerCell);\n endCell = this.selection.getSelectedCell(endCell, containerCell);\n if (this.selection.containsCell(containerCell, endCell)) {\n row = startCell.ownerRow;\n this.removeRow(row);\n }\n else {\n row = startCell.ownerRow;\n var endRow = endCell.ownerRow;\n //Update the selection paragraph.\n paragraph = undefined;\n if (endRow.nextWidget) {\n var nextCell = endRow.nextWidget.childWidgets[0];\n paragraph = this.selection.getFirstParagraph(nextCell);\n }\n if (isNullOrUndefined(paragraph)) {\n paragraph = this.getParagraphForSelection(table);\n }\n for (var i = 0; i < table.childWidgets.length; i++) {\n var tableRow = table.childWidgets[i];\n if (tableRow.rowIndex >= row.rowIndex && tableRow.rowIndex <= endRow.rowIndex) {\n table.childWidgets.splice(i, 1);\n tableRow.destroy();\n i--;\n }\n }\n if (table.childWidgets.length === 0) {\n this.removeBlock(table);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.editorHistory.currentBaseHistoryInfo.action = 'DeleteTable';\n }\n table.destroy();\n }\n else {\n this.updateTable(table);\n }\n }\n }\n }\n else {\n this.removeRow(row);\n }\n this.selection.selectParagraph(paragraph, true);\n if (isNullOrUndefined(this.editorHistory) || this.checkIsNotRedoing()) {\n this.reLayout(this.selection, true);\n }\n }\n };\n Editor.prototype.removeRow = function (row) {\n var table = row.ownerTable;\n if (table.childWidgets.length === 1) {\n this.removeBlock(table);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n this.editorHistory.currentBaseHistoryInfo.action = 'Delete';\n }\n table.destroy();\n }\n else {\n table.childWidgets.splice(table.childWidgets.indexOf(row), 1);\n row.destroy();\n this.updateTable(table);\n }\n };\n Editor.prototype.updateTable = function (table) {\n table.updateRowIndex(0);\n table.isGridUpdated = false;\n table.buildTableColumns();\n table.isGridUpdated = true;\n this.viewer.layout.reLayoutTable(table);\n };\n Editor.prototype.getParagraphForSelection = function (table) {\n var paragraph = undefined;\n var nextWidget = table.nextWidget ? table.nextWidget : table.nextRenderedWidget;\n var previousWidget = table.previousWidget ? table.previousWidget : table.previousRenderedWidget;\n if (nextWidget) {\n paragraph = nextWidget instanceof ParagraphWidget ? nextWidget\n : this.selection.getFirstParagraphInFirstCell(nextWidget);\n }\n else if (previousWidget) {\n paragraph = previousWidget instanceof ParagraphWidget ? previousWidget\n : this.selection.getLastParagraphInLastCell(previousWidget);\n }\n return paragraph;\n };\n Editor.prototype.deletePara = function (paragraph, start, end, editAction) {\n paragraph = paragraph.combineWidget(this.viewer);\n var selection = this.viewer.selection;\n var paragraphStart = selection.getStartOffset(paragraph);\n var endParagraphStartOffset = selection.getStartOffset(end.paragraph);\n var startOffset = paragraphStart;\n var endOffset = 0;\n var isCombineNextParagraph = false;\n var lastLinelength = this.selection.getLineLength(paragraph.lastChild);\n var currentParagraph = paragraph;\n var section = paragraph.bodyWidget instanceof BodyWidget ? paragraph.containerWidget : undefined;\n var startLine = undefined;\n var endLineWidget = undefined;\n if (paragraph === start.paragraph) {\n startOffset = start.offset;\n startLine = start.currentWidget;\n if (end.paragraph.isInsideTable) {\n isCombineNextParagraph = this.isEndInAdjacentTable(paragraph, end.paragraph);\n }\n }\n else {\n startLine = paragraph.firstChild;\n }\n if (paragraph !== start.paragraph && selection.isSkipLayouting) {\n selection.isSkipLayouting = false;\n }\n if (paragraph === end.paragraph) {\n endLineWidget = end.currentWidget;\n endOffset = end.offset;\n }\n else {\n endLineWidget = paragraph.lastChild;\n endOffset = this.viewer.selection.getLineLength(paragraph.lastChild);\n }\n var block = paragraph.previousRenderedWidget;\n if (startOffset > paragraphStart && start.currentWidget === paragraph.lastChild &&\n startOffset === lastLinelength && (paragraph === end.paragraph && end.offset === startOffset + 1 ||\n paragraph.nextRenderedWidget === end.paragraph && end.offset === endParagraphStartOffset)) {\n isCombineNextParagraph = true;\n }\n if (end.paragraph === paragraph && end.currentWidget !== paragraph.lastChild ||\n (end.currentWidget === paragraph.lastChild && end.offset <= selection.getLineLength(paragraph.lastChild))) {\n var isStartParagraph = start.paragraph === paragraph;\n if (end.currentWidget.isFirstLine() && end.offset > paragraphStart || !end.currentWidget.isFirstLine()) {\n //If selection end with this paragraph and selection doesnot include paragraph mark. \n this.removeInlines(paragraph, startLine, startOffset, endLineWidget, endOffset, editAction);\n //Removes the splitted paragraph.\n }\n if (!isNullOrUndefined(block) && !isStartParagraph) {\n var nextSection = block.bodyWidget instanceof BodyWidget ? block.bodyWidget : undefined;\n // if (section !== nextSection) {\n // this.deleteSection(selection, section, nextSection, editAction);\n // }\n this.deleteBlock(block, selection, start, end, editAction);\n }\n }\n else if (start.paragraph === paragraph && (start.currentWidget !== paragraph.firstChild ||\n (start.currentWidget === paragraph.firstChild && startOffset > paragraphStart))) {\n // If selection start is after paragraph start\n //And selection does not end with this paragraph Or selection include paragraph mark.\n if (editAction === 4) {\n return;\n }\n else {\n currentParagraph = this.splitParagraph(paragraph, paragraph.firstChild, 0, startLine, startOffset, true);\n this.insertParagraphPaste(paragraph, currentParagraph, start, end, isCombineNextParagraph, editAction);\n this.addRemovedNodes(paragraph);\n return;\n }\n }\n else {\n var newParagraph = undefined;\n var previousBlock = paragraph.previousWidget;\n var prevParagraph = (previousBlock instanceof ParagraphWidget) ? previousBlock : undefined;\n var nextWidget = paragraph.nextRenderedWidget;\n if (editAction < 4) {\n //Checks whether this is last paragraph of owner text body and previousBlock is not paragraph.\n newParagraph = this.checkAndInsertBlock(paragraph, start, end, editAction, prevParagraph);\n this.removeBlock(paragraph);\n if (this.viewer.blockToShift === paragraph) {\n this.viewer.blockToShift = undefined;\n }\n this.addRemovedNodes(paragraph);\n if (!isNullOrUndefined(newParagraph)) {\n selection.editPosition = this.getHierarchicalIndex(newParagraph, '0');\n var offset = selection.getParagraphLength(newParagraph) + 1;\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n //tslint:disable-next-line:max-line-length\n this.editorHistory.currentBaseHistoryInfo.endPosition = this.getHierarchicalIndex(newParagraph, offset.toString());\n }\n }\n else if (paragraph === start.paragraph && isNullOrUndefined(nextWidget) && !isNullOrUndefined(prevParagraph)) {\n var offset = this.selection.getParagraphLength(prevParagraph);\n // if (isNullOrUndefined(block)) {\n selection.editPosition = this.getHierarchicalIndex(prevParagraph, offset.toString());\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.updateHistoryPosition(selection.editPosition, true);\n this.editorHistory.currentBaseHistoryInfo.endPosition = selection.editPosition;\n }\n // } else {\n // let offset: number = selection.getParagraphLength(paragraph) + 1;\n // if (block instanceof ParagraphWidget) {\n // prevParagraph = block as ParagraphWidget;\n // }\n // // if (block instanceof WTable) {\n // // prevParagraph = (block as WTable).getFirstParagraphInFirstCell();\n // // }\n // selection.editPosition = prevLineWidget.getHierarchicalIndex('0');\n // }\n }\n }\n if (start.paragraph !== paragraph && !isNullOrUndefined(block)) {\n var nextSection = block.bodyWidget instanceof BodyWidget ? block.bodyWidget : undefined;\n // if (section !== nextSection) {\n // this.deleteSection(selection, section, nextSection, editAction);\n // }\n this.deleteBlock(block, selection, start, end, editAction);\n }\n }\n this.insertParagraphPaste(paragraph, currentParagraph, start, end, isCombineNextParagraph, editAction);\n };\n //tslint:disable:max-line-length\n /**\n * @private\n */\n Editor.prototype.checkAndInsertBlock = function (block, start, end, editAction, previousParagraph) {\n if (block instanceof ParagraphWidget && block === start.paragraph || block instanceof TableWidget) {\n var newParagraph = void 0; //Adds an empty paragraph, to ensure minimal content.\n if (isNullOrUndefined(block.nextWidget) && (isNullOrUndefined(previousParagraph) || previousParagraph.nextRenderedWidget instanceof TableWidget)) {\n newParagraph = new ParagraphWidget();\n if (editAction === 1 && block instanceof ParagraphWidget) {\n newParagraph.characterFormat.copyFormat(block.characterFormat);\n newParagraph.paragraphFormat.copyFormat(block.paragraphFormat);\n }\n newParagraph.index = block.index + 1;\n newParagraph.containerWidget = block.containerWidget;\n this.viewer.layout.layoutBodyWidgetCollection(newParagraph.index, newParagraph.bodyWidget, newParagraph, false);\n if (block.containerWidget instanceof Widget) {\n block.containerWidget.childWidgets.push(newParagraph);\n }\n }\n return newParagraph;\n }\n return undefined;\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.splitParagraph = function (paragraphAdv, startLine, startOffset, endLine, endOffset, removeBlock) {\n var paragraph = new ParagraphWidget();\n paragraph.paragraphFormat = new WParagraphFormat(paragraph);\n paragraph.characterFormat = new WCharacterFormat(paragraph);\n paragraph.paragraphFormat.copyFormat(paragraphAdv.paragraphFormat);\n paragraph.characterFormat.copyFormat(paragraphAdv.characterFormat);\n var lineWidget = new LineWidget(paragraph);\n paragraph.childWidgets.push(lineWidget);\n var blockIndex = paragraphAdv.index;\n var insertIndex = paragraphAdv.indexInOwner;\n this.moveInlines(paragraphAdv, paragraph, 0, startOffset, startLine, endOffset, endLine);\n //Inserts new paragraph in the current text position.\n paragraphAdv.containerWidget.childWidgets.splice(insertIndex, 0, paragraph);\n paragraph.index = blockIndex;\n paragraph.containerWidget = paragraphAdv.containerWidget;\n this.updateNextBlocksIndex(paragraph, true);\n if (removeBlock) {\n this.removeBlock(paragraphAdv);\n }\n // tslint:disable-next-line:max-line-length\n this.viewer.layout.layoutBodyWidgetCollection(blockIndex, paragraph.containerWidget, paragraph, false);\n return paragraph;\n };\n /**\n * @private\n */\n Editor.prototype.removeBlock = function (block) {\n var index;\n var blockCollection;\n var containerWidget;\n this.removeFieldInBlock(block);\n if (block.isInsideTable) {\n containerWidget = block.associatedCell;\n index = block.associatedCell.childWidgets.indexOf(block);\n blockCollection = block.associatedCell.childWidgets;\n this.updateNextBlocksIndex(block, false);\n block.associatedCell.childWidgets.splice(index, 1);\n block.containerWidget = undefined;\n this.viewer.layout.layoutBodyWidgetCollection(block.index, containerWidget, block, false);\n }\n else {\n containerWidget = block.containerWidget;\n index = containerWidget.childWidgets.indexOf(block);\n blockCollection = containerWidget.childWidgets;\n this.updateNextBlocksIndex(block, false);\n containerWidget.childWidgets.splice(index, 1);\n block.containerWidget = undefined;\n containerWidget.height -= block.height;\n this.viewer.layout.layoutBodyWidgetCollection(block.index, containerWidget, block, false);\n }\n };\n Editor.prototype.removeField = function (block) {\n for (var i = 0; i < this.viewer.fields.length; i++) {\n var field = this.viewer.fields[i];\n if (field.line.paragraph === block) {\n this.viewer.fields.splice(i, 1);\n i--;\n }\n }\n };\n Editor.prototype.addRemovedNodes = function (node) {\n if (node instanceof FieldElementBox && node.fieldType === 0) {\n if (this.viewer.fields.indexOf(node) !== -1) {\n this.viewer.fields.splice(this.viewer.fields.indexOf(node), 1);\n }\n }\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.editorHistory.currentBaseHistoryInfo.removedNodes.push(node);\n }\n else if (this.editHyperlinkInternal) {\n this.nodes.push(node);\n }\n };\n Editor.prototype.deleteBlock = function (block, selection, start, end, editAction) {\n if (block instanceof ParagraphWidget) {\n this.deletePara(block, start, end, editAction);\n }\n else {\n this.deleteTableBlock(block, selection, start, end, editAction);\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.deleteTableCell = function (cellAdv, selection, start, end, editAction) {\n var deletePreviousBlock = !(start.paragraph.isInsideTable && cellAdv.ownerTable.contains(start.paragraph.associatedCell));\n var previousBlock = cellAdv.ownerTable.previousRenderedWidget;\n if (start.paragraph.isInsideTable) {\n var containerCell = selection.getContainerCellOf(cellAdv, start.paragraph.associatedCell);\n if (containerCell.ownerTable.contains(start.paragraph.associatedCell)) {\n var startCell = selection.getSelectedCell(cellAdv, containerCell);\n var endCell = selection.getSelectedCell(start.paragraph.associatedCell, containerCell);\n if (selection.containsCell(containerCell, start.paragraph.associatedCell)) {\n //Selection end is in container cell.\n if (selection.isCellSelected(containerCell, start, end)) {\n //Container cell is completely selected.\n this.updateEditPosition(containerCell, selection);\n if (editAction === 1) {\n //Specifically handled for backspace. Delete selected cell in current table.\n this.deleteCellsInTable(cellAdv.ownerRow.ownerTable, selection, start, end, editAction);\n }\n else {\n //Delete contents within table cell or Copy contents within table cell to clipboard.\n var isCellCleared = this.deleteCell(containerCell, selection, editAction, true);\n if (!isCellCleared && editAction !== 2 && this.editorHistory) {\n this.editorHistory.currentBaseHistoryInfo = undefined;\n }\n }\n }\n else {\n if (startCell === containerCell) {\n this.deletePara(end.paragraph, start, end, editAction);\n }\n else {\n this.deleteContainer(startCell, selection, start, end, editAction);\n }\n }\n }\n else {\n if (editAction === 2) {\n //Delete contents within table cell.\n this.deleteCell(cellAdv, selection, 2, false);\n }\n else {\n //Delete other selected cells in current table.\n this.deleteCellsInTable(containerCell.ownerTable, selection, start, end, editAction);\n }\n }\n }\n else {\n //Selection end is different table.\n this.deleteContainer(containerCell, selection, start, end, editAction);\n }\n }\n else {\n //Selection end is outside table.\n var cell = selection.getContainerCell(cellAdv);\n this.deleteContainer(cell, selection, start, end, editAction);\n }\n if (deletePreviousBlock) {\n var sectionAdv = previousBlock.bodyWidget instanceof BodyWidget ? previousBlock.bodyWidget : undefined;\n // this.deleteContent(cellAdv.ownerTable, selection, editAction);\n if (!isNullOrUndefined(previousBlock)) {\n // let nextSection: WSection = blockAdv.section instanceof WSection ? blockAdv.section as WSection : undefined;\n // if (sectionAdv !== nextSection) {\n // this.deleteSection(selection, sectionAdv, nextSection, editAction);\n // }\n //Goto the next block.\n this.deleteBlock(previousBlock, selection, start, end, editAction);\n }\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.deleteCellsInTable = function (table, selection, start, end, editAction) {\n var clonedTable = undefined;\n var isDeleteCells = false;\n var action = 'Delete';\n var startCell = start.paragraph.associatedCell;\n var endCell = end.paragraph.associatedCell;\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n action = this.editorHistory.currentBaseHistoryInfo.action;\n //tslint:disable-next-line:max-line-length\n isDeleteCells = this.editorHistory.currentBaseHistoryInfo.action === 'BackSpace' || this.editorHistory.currentBaseHistoryInfo.action === 'DeleteCells'\n || this.editorHistory.currentBaseHistoryInfo.action === 'InsertTable' || (isNullOrUndefined(startCell.ownerRow.previousWidget)\n && isNullOrUndefined(endCell.ownerRow.nextWidget) && this.editorHistory.currentBaseHistoryInfo.action === 'Cut');\n this.editorHistory.currentBaseHistoryInfo.action = isDeleteCells ? 'DeleteCells' : 'ClearCells';\n clonedTable = this.cloneTableToHistoryInfo(table);\n selection.owner.isLayoutEnabled = false;\n }\n var startColumnIndex = startCell.columnIndex;\n var endColumnIndex = endCell.columnIndex + endCell.cellFormat.columnSpan - 1;\n var startRowIndex = startCell.rowIndex;\n var endRowIndex = endCell.rowIndex;\n var cells = [];\n var isStarted = false;\n var isCellCleared = false;\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row.index >= startRowIndex && row.index <= endRowIndex) {\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n if (cell.columnIndex >= startColumnIndex && cell.columnIndex <= endColumnIndex) {\n if (!isStarted) {\n this.updateEditPosition(cell, selection);\n isStarted = true;\n }\n if (isDeleteCells) {\n //Specific for Backspace and Cut if selection includes all rows.\n var cell_1 = row.childWidgets[j];\n this.updateNextBlocksIndex(cell_1, false);\n row.childWidgets.splice(j, 1);\n j--;\n }\n else if (editAction < 4) {\n isCellCleared = this.deleteCell(cell, selection, editAction, false);\n }\n }\n }\n if (row.childWidgets.length === 0) {\n this.updateNextBlocksIndex(table.childWidgets[i], false);\n table.childWidgets.splice(i, 1);\n i--;\n endRowIndex--;\n }\n }\n }\n //Layouts the table after delete cells.\n selection.owner.isLayoutEnabled = true;\n if (table.childWidgets.length === 0) {\n selection.editPosition = this.getHierarchicalIndex(table, '0');\n this.setActionInternal(selection, action);\n this.removeBlock(table);\n }\n else {\n // Before lay outing need to update table grid.\n table.isGridUpdated = false;\n table.buildTableColumns();\n table.isGridUpdated = true;\n this.viewer.layout.reLayoutTable(table);\n }\n };\n Editor.prototype.deleteCell = function (cell, selection, editAction, copyChildToClipboard) {\n //Checks whether this is last paragraph of owner textbody.\n var block = cell.childWidgets[0];\n if (cell.childWidgets.length === 1 && block instanceof ParagraphWidget && block.isEmpty()) {\n return false;\n }\n for (var i = 0; i < cell.childWidgets.length; i++) {\n block = cell.childWidgets[i];\n if (editAction < 4) {\n //Checks whether this is last paragraph of owner textbody.\n if (block instanceof ParagraphWidget && cell.childWidgets.length === 1) {\n //Preserves empty paragraph, to ensure minimal content.\n var paragraph = block;\n //Removes all the inlines in the paragraph.\n for (var j = 0; j < paragraph.childWidgets.length; j++) {\n var inline = paragraph.childWidgets[j];\n for (var k = 0; k < inline.children.length; k++) {\n var element = inline.children[k];\n this.unLinkFieldCharacter(element);\n inline.children.splice(k, 1);\n // this.layoutInlineCollection(true, paragraph.inlines.indexOf(inline), paragraph.inlines, inline);\n k--;\n if (this.checkClearCells(selection)) {\n this.addRemovedNodes(element);\n }\n }\n if (paragraph.childWidgets.length > 1) {\n paragraph.childWidgets.splice(j, 1);\n j--;\n }\n }\n if (this.checkClearCells(selection)) {\n //Add Index for line Widget\n selection.editPosition = this.getHierarchicalIndex(paragraph, '0');\n this.updateHistoryPosition(selection.editPosition, true);\n }\n break;\n }\n this.removeBlock(block);\n i--;\n if (this.checkClearCells(selection)) {\n this.addRemovedNodes(block);\n }\n }\n }\n return true;\n };\n Editor.prototype.deleteContainer = function (cell, selection, start, end, editAction) {\n var ownerTable = cell.ownerTable;\n if (selection.containsRow(ownerTable.lastChild, end.paragraph.associatedCell)) {\n this.deleteContent(ownerTable, selection, editAction);\n }\n else {\n for (var i = 0; i < ownerTable.childWidgets.length; i++) {\n var row = ownerTable.childWidgets[i];\n if (editAction < 4) {\n this.updateNextBlocksIndex(row, false);\n ownerTable.childWidgets.splice(i, 1);\n this.addRemovedNodes(row);\n i--;\n }\n if (end.paragraph.isInsideTable && selection.containsRow(row, end.paragraph.associatedCell)) {\n this.viewer.layout.reLayoutTable(ownerTable);\n return;\n }\n }\n }\n };\n Editor.prototype.deleteTableBlock = function (table, selection, start, end, editAction) {\n table = table.combineWidget(this.viewer);\n if (start.paragraph.isInsideTable && table.contains(start.paragraph.associatedCell)) {\n var block = table.previousRenderedWidget;\n // tslint:disable-next-line:max-line-length\n var previousBlock = this.checkAndInsertBlock(table, start, end, editAction, block instanceof ParagraphWidget ? block : undefined);\n if (selection.containsRow(table.firstChild, start.paragraph.associatedCell)) {\n this.deleteContent(table, selection, editAction);\n }\n else {\n var newTable = this.splitTable(table, start.paragraph.associatedCell.ownerRow);\n this.deleteContent(table, selection, editAction);\n this.viewer.layout.layoutBodyWidgetCollection(newTable.index, newTable.containerWidget, newTable, false);\n }\n if (!isNullOrUndefined(previousBlock)) {\n selection.editPosition = this.getHierarchicalIndex(previousBlock, '0');\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.editorHistory.currentBaseHistoryInfo.endPosition = selection.editPosition;\n }\n }\n }\n else {\n var blockAdv = table.previousRenderedWidget;\n var sectionAdv = table.bodyWidget instanceof BodyWidget ? table.bodyWidget : undefined;\n this.deleteContent(table, selection, editAction);\n if (!isNullOrUndefined(blockAdv)) {\n // let nextSection: WSection = blockAdv.section instanceof WSection ? blockAdv.section as WSection : undefined;\n // if (sectionAdv !== nextSection) {\n // this.deleteSection(selection, sectionAdv, nextSection, editAction);\n // }\n //Goto the next block.\n this.deleteBlock(blockAdv, selection, start, end, editAction);\n }\n }\n };\n Editor.prototype.splitTable = function (table, splitEndRow) {\n var newTable = new TableWidget();\n newTable.tableFormat.copyFormat(table.tableFormat);\n newTable.index = table.index;\n //Moves the rows to new table.\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n if (row === splitEndRow) {\n break;\n }\n newTable.childWidgets.push(row);\n row.containerWidget = newTable;\n table.childWidgets.splice(i, 1);\n i--;\n }\n //Inserts new table in the current text position.\n var insertIndex = table.getIndex();\n table.containerWidget.childWidgets.splice(insertIndex, 0, newTable);\n newTable.containerWidget = table.containerWidget;\n this.updateNextBlocksIndex(newTable, true);\n return newTable;\n };\n Editor.prototype.updateEditPosition = function (cell, selection) {\n var firstParagraph = selection.getFirstParagraphInCell(cell);\n selection.editPosition = this.getHierarchicalIndex(firstParagraph, '0');\n };\n /**\n * @private\n */\n Editor.prototype.deleteContent = function (table, selection, editAction) {\n if (editAction < 4) {\n this.removeBlock(table);\n this.addRemovedNodes(table);\n }\n };\n Editor.prototype.setActionInternal = function (selection, action) {\n if (this.viewer.owner.enableHistoryMode && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.editorHistory.currentBaseHistoryInfo.action = action;\n }\n };\n Editor.prototype.checkClearCells = function (selection) {\n // tslint:disable-next-line:max-line-length\n return this.editorHistory && this.editorHistory.currentBaseHistoryInfo && this.editorHistory.currentBaseHistoryInfo.action !== 'ClearCells';\n };\n Editor.prototype.isEndInAdjacentTable = function (paragraph, endParagraph) {\n var start = this.getHierarchicalIndex(paragraph, '');\n var end = this.getHierarchicalIndex(endParagraph, '');\n var selectionStart = start.split(';');\n var selectionEnd = end.split(';');\n return selectionStart.length < selectionEnd.length;\n };\n Editor.prototype.cloneTableToHistoryInfo = function (table) {\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n //Clones the entire table to preserve in history.\n var clonedTable = table.clone();\n //Preserves the cloned table in history info, for future undo operation.\n this.editorHistory.currentBaseHistoryInfo.removedNodes.push(clonedTable);\n //Sets the insert position in history info as current table.\n if (this.viewer.selection.start.paragraph.isInsideTable &&\n this.viewer.selection.start.paragraph.associatedCell.ownerTable === table) {\n this.updateHistoryPosition(this.getHierarchicalIndex(table, '0'), true);\n }\n return clonedTable;\n }\n return undefined;\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.insertParagraphPaste = function (paragraph, currentParagraph, start, end, isCombineNextParagraph, editAction) {\n if (this.editorHistory && (this.editorHistory.isUndoing || this.editorHistory.isRedoing) && this.editorHistory.currentBaseHistoryInfo.action === 'Paste') {\n var nextParagraph = this.selection.getNextParagraphBlock(currentParagraph);\n if (nextParagraph) {\n if (start.offset > 0 && nextParagraph === end.paragraph && paragraph === start.paragraph\n && this.editorHistory.currentBaseHistoryInfo.action === 'Paste') {\n //Combines the current paragraph with end paragraph specific for undo/redo paste action.\n var insertIndex = 0;\n this.removeBlock(currentParagraph);\n this.viewer.layout.clearListElementBox(nextParagraph);\n this.viewer.layout.clearListElementBox(currentParagraph);\n for (var i = 0; i < currentParagraph.childWidgets.length; i++) {\n var line = currentParagraph.childWidgets[i];\n nextParagraph.childWidgets.splice(insertIndex, 0, line);\n currentParagraph.childWidgets.splice(i, 1);\n i--;\n insertIndex++;\n line.paragraph = nextParagraph;\n }\n this.viewer.layout.reLayoutParagraph(nextParagraph, 0, 0);\n isCombineNextParagraph = false;\n var offset = this.selection.editPosition.substring(this.selection.editPosition.lastIndexOf(';') + 1);\n this.selection.editPosition = this.getHierarchicalIndex(nextParagraph, offset);\n }\n }\n }\n if (isCombineNextParagraph) {\n this.deleteParagraphMark(currentParagraph, this.selection, editAction);\n }\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.removeInlines = function (paragraph, startLine, startOffset, endLine, endOffset, editAction) {\n var isRemoved = false;\n this.viewer.layout.clearListElementBox(paragraph);\n var startIndex = paragraph.childWidgets.indexOf(startLine);\n for (var i = paragraph.childWidgets.length - 1; i >= 0; i--) {\n var lineWidget = paragraph.childWidgets[i];\n if (startLine === lineWidget && endLine === lineWidget) {\n this.removeContent(lineWidget, startOffset, endOffset);\n isRemoved = true;\n break;\n }\n if (endLine === lineWidget) {\n isRemoved = true;\n this.removeContent(lineWidget, 0, endOffset);\n }\n else if (startLine === lineWidget) {\n this.removeContent(lineWidget, startOffset, this.viewer.selection.getLineLength(lineWidget));\n break;\n }\n else if (isRemoved) {\n this.removeContent(lineWidget, 0, this.viewer.selection.getLineLength(lineWidget));\n }\n }\n if (isRemoved) {\n this.removeEmptyLine(paragraph);\n this.viewer.layout.reLayoutParagraph(paragraph, 0, 0);\n }\n };\n /**\n * @private\n */\n Editor.prototype.removeContent = function (lineWidget, startOffset, endOffset) {\n var count = this.selection.getLineLength(lineWidget);\n for (var i = lineWidget.children.length - 1; i >= 0; i--) {\n var inline = lineWidget.children[i];\n if (endOffset <= count - inline.length) {\n count -= inline.length;\n continue;\n }\n var endIndex = inline.length;\n if (count > endOffset && (count - endIndex < endOffset)) {\n endIndex = endOffset - (count - inline.length);\n }\n var startIndex = 0;\n if (count - inline.length < startOffset) {\n startIndex = startOffset - (count - inline.length);\n }\n if (count > endOffset) {\n count -= (inline.length - endIndex);\n }\n if (startIndex === 0 && endIndex === inline.length) {\n if (!(this.editorHistory && (this.editorHistory.isUndoing || this.editorHistory.isRedoing))) {\n if (inline instanceof BookmarkElementBox) {\n this.removedBookmarkElements.push(inline);\n }\n }\n // if (editAction < 4) {\n this.unLinkFieldCharacter(inline);\n this.addRemovedNodes(lineWidget.children[i]);\n lineWidget.children.splice(i, 1);\n // }\n }\n else if (inline instanceof TextElementBox) {\n // if (editAction < 4) {\n var span = new TextElementBox();\n span.characterFormat.copyFormat(inline.characterFormat);\n span.text = inline.text.substr(startIndex, endIndex - startIndex);\n this.addRemovedNodes(span);\n inline.text = inline.text.slice(0, startIndex) + inline.text.slice(endIndex);\n }\n if (startOffset >= count - (endIndex - startIndex)) {\n break;\n }\n count -= (endIndex - startIndex);\n }\n };\n /**\n * @private\n */\n Editor.prototype.removeEmptyLine = function (paragraph) {\n if (paragraph.childWidgets.length > 1) {\n for (var i = 0; i < paragraph.childWidgets.length; i++) {\n var lineWidget = paragraph.childWidgets[i];\n if (lineWidget.children.length === 0 && paragraph.childWidgets.length > 1) {\n paragraph.childWidgets.splice(i, 1);\n i--;\n }\n }\n }\n };\n //#endregion\n /**\n * clone the list level\n * @param {WListLevel} source\n * @private\n */\n Editor.prototype.cloneListLevel = function (source) {\n var listLevel = new WListLevel(undefined);\n this.copyListLevel(listLevel, source);\n return listLevel;\n };\n /**\n * Copies the list level\n * @param {WListLevel} destination\n * @param {WListLevel} listLevel\n * @private\n */\n Editor.prototype.copyListLevel = function (destination, listLevel) {\n if (!isNullOrUndefined(listLevel.paragraphFormat)) {\n destination.paragraphFormat = new WParagraphFormat(destination);\n destination.paragraphFormat.copyFormat(listLevel.paragraphFormat);\n }\n if (!isNullOrUndefined(listLevel.characterFormat)) {\n destination.characterFormat = new WCharacterFormat(destination);\n destination.characterFormat.copyFormat(listLevel.characterFormat);\n }\n if (!isNullOrUndefined(listLevel.followCharacter)) {\n destination.followCharacter = listLevel.followCharacter;\n }\n if (!isNullOrUndefined(listLevel.listLevelPattern)) {\n destination.listLevelPattern = listLevel.listLevelPattern;\n }\n if (!isNullOrUndefined(listLevel.numberFormat)) {\n destination.numberFormat = listLevel.numberFormat;\n }\n if (!isNullOrUndefined(listLevel.restartLevel)) {\n destination.restartLevel = listLevel.restartLevel;\n }\n if (!isNullOrUndefined(listLevel.startAt)) {\n destination.startAt = listLevel.startAt;\n }\n };\n /**\n * Clone level override\n * @param {WLevelOverride} source\n * @private\n */\n Editor.prototype.cloneLevelOverride = function (source) {\n var levelOverride = new WLevelOverride();\n if (!isNullOrUndefined(source.startAt)) {\n levelOverride.startAt = source.startAt;\n }\n if (!isNullOrUndefined(source.overrideListLevel)) {\n levelOverride.overrideListLevel = source.overrideListLevel;\n }\n if (!isNullOrUndefined(source.levelNumber)) {\n levelOverride.levelNumber = source.levelNumber;\n }\n return levelOverride;\n };\n /**\n * Update List Paragraph\n * @private\n */\n Editor.prototype.updateListParagraphs = function () {\n this.viewer.listParagraphs = [];\n for (var j = 0; j < this.viewer.pages.length; j++) {\n var bodyWidget = this.viewer.pages[j].bodyWidgets[0];\n for (var i = 0; i < bodyWidget.childWidgets.length; i++) {\n this.updateListParagraphsInBlock(bodyWidget.childWidgets[i]);\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.updateListParagraphsInBlock = function (block) {\n if (block instanceof ParagraphWidget) {\n if (!isNullOrUndefined(block.paragraphFormat)\n && !isNullOrUndefined(block.paragraphFormat.listFormat)\n && !isNullOrUndefined(block.paragraphFormat.listFormat.listId)) {\n if (isNullOrUndefined(this.viewer.listParagraphs)) {\n this.viewer.listParagraphs = [];\n }\n this.viewer.listParagraphs.push(block);\n }\n }\n else if (block instanceof TableWidget) {\n for (var i = 0; i < block.childWidgets.length; i++) {\n for (var j = 0; j < block.childWidgets[i].childWidgets.length; j++) {\n var cell = block.childWidgets[i].childWidgets[j];\n for (var k = 0; k < cell.childWidgets.length; k++) {\n this.updateListParagraphsInBlock(cell.childWidgets[k]);\n }\n }\n }\n }\n };\n /**\n * Applies list format\n * @param {WList} list\n * @private\n */\n Editor.prototype.onApplyList = function (list) {\n var selection = this.viewer.selection;\n this.setOffsetValue(this.viewer.selection);\n this.initHistory('ListFormat');\n var format = new WListFormat();\n if (!isNullOrUndefined(list)) {\n format.listId = list.listId;\n }\n this.viewer.owner.isShiftingEnabled = true;\n if (selection.isEmpty) {\n this.applyParaFormatProperty(selection.start.paragraph, 'listFormat', format, false);\n this.layoutItemBlock(selection.start.paragraph, false);\n }\n else {\n this.updateSelectionParagraphFormatting('listFormat', format, false);\n }\n this.reLayout(selection);\n };\n /**\n * Applies bullets or numbering list\n * @param {string} format\n * @param {ListLevelPattern} listLevelPattern\n * @param {string} fontFamily\n * @private\n */\n Editor.prototype.applyBulletOrNumbering = function (format, listLevelPattern, fontFamily) {\n var selection = this.viewer.selection;\n var list = selection.paragraphFormat.getList();\n var isUpdate = false;\n var start = selection.start;\n if (!selection.isForward) {\n start = selection.end;\n }\n var currentParagraph = start.paragraph;\n if (isNullOrUndefined(list)) {\n while (!isNullOrUndefined(currentParagraph.previousWidget) && currentParagraph.previousWidget instanceof ParagraphWidget\n && currentParagraph.previousWidget.isEmpty() && currentParagraph.previousWidget.paragraphFormat.listFormat.listId === -1) {\n currentParagraph = currentParagraph.previousWidget;\n }\n if (currentParagraph.previousWidget && currentParagraph.previousWidget instanceof ParagraphWidget\n && currentParagraph.previousWidget.paragraphFormat.listFormat.listId !== -1) {\n currentParagraph = currentParagraph.previousWidget;\n list = this.viewer.getListById(currentParagraph.paragraphFormat.listFormat.listId);\n isUpdate = true;\n }\n }\n var startListLevel = undefined;\n if (!isNullOrUndefined(list)) {\n var tempList = this.viewer.getListById(currentParagraph.paragraphFormat.listFormat.listId);\n startListLevel = this.viewer.layout.getListLevel(tempList, currentParagraph.paragraphFormat.listFormat.listLevelNumber);\n }\n if (isNullOrUndefined(list) || (!isNullOrUndefined(list) && ((startListLevel.listLevelPattern !== listLevelPattern) ||\n startListLevel.numberFormat !== format || (startListLevel.characterFormat.fontFamily !== fontFamily\n && startListLevel.listLevelPattern === 'Bullet')))) {\n isUpdate = false;\n list = new WList();\n if (this.viewer.lists.length > 0) {\n list.listId = this.viewer.lists[this.viewer.lists.length - 1].listId + 1;\n }\n else {\n list.listId = 0;\n }\n var abstractList = new WAbstractList();\n if (this.viewer.abstractLists.length > 0) {\n abstractList.abstractListId = this.viewer.abstractLists[this.viewer.abstractLists.length - 1].abstractListId + 1;\n }\n else {\n abstractList.abstractListId = 0;\n }\n list.abstractListId = abstractList.abstractListId;\n this.viewer.abstractLists.push(abstractList);\n if (format === 'bullet' || format === 'multiLevel' || format === 'numbering') {\n this.addListLevels(abstractList, format, selection);\n }\n else {\n var listLevel = new WListLevel(abstractList);\n listLevel.listLevelPattern = listLevelPattern;\n listLevel.numberFormat = format;\n if (listLevelPattern !== 'Bullet') {\n listLevel.startAt = 1;\n }\n else {\n listLevel.characterFormat.fontFamily = fontFamily;\n }\n listLevel.paragraphFormat.leftIndent = 36;\n listLevel.paragraphFormat.firstLineIndent = -18;\n abstractList.levels.push(listLevel);\n selection.paragraphFormat.listLevelNumber = 0;\n }\n selection.paragraphFormat.setList(list);\n }\n else if (!isNullOrUndefined(list) && isUpdate) {\n selection.paragraphFormat.setList(list);\n }\n else {\n selection.paragraphFormat.setList(undefined);\n }\n };\n Editor.prototype.addListLevels = function (abstractListAdv, listName, selection) {\n var bulletCharacters = ['\\uf076', '\\uf0d8', '\\uf0a7', '\\uf0b7', '\\uf0a8'];\n for (var i = abstractListAdv.levels.length; i < 9; i++) {\n var listLevel = new WListLevel(abstractListAdv);\n if (listName.match('bullet')) {\n listLevel.listLevelPattern = 'Bullet';\n listLevel.numberFormat = bulletCharacters[i < 5 ? i % 5 : i % 5 + 1];\n listLevel.characterFormat.fontFamily = i < 3 || i === 5 ? 'Wingdings' : 'Symbol';\n }\n else {\n if (listName.match('multiLevel')) {\n for (var j = 0; j < i + 1; j++) {\n listLevel.numberFormat += '%' + (j + 1).toString() + '.';\n }\n listLevel.listLevelPattern = 'Number';\n }\n else {\n listLevel.numberFormat = '%' + (i + 1).toString() + ')';\n listLevel.listLevelPattern = i % 3 === 0 ? 'Number'\n : i % 3 === 1 ? 'LowLetter' : 'LowRoman';\n }\n listLevel.startAt = 1;\n listLevel.restartLevel = i;\n }\n if (i === 0) {\n listLevel.paragraphFormat.leftIndent = 36;\n }\n else {\n listLevel.paragraphFormat.leftIndent = 36 * i;\n }\n listLevel.paragraphFormat.firstLineIndent = -18;\n abstractListAdv.levels.push(listLevel);\n selection.paragraphFormat.listLevelNumber = i;\n }\n };\n /**\n * @private\n */\n Editor.prototype.onEnter = function () {\n var selection = this.viewer.selection;\n if (selection.isEmpty) {\n //ToDo: Need to handle the CTRL + Enter (Page Break) and SHIFT + Enter (Line Break) behavior.\n var hyperlinkField = selection.getHyperlinkField();\n var isSelectionOnHyperlink = !isNullOrUndefined(hyperlinkField);\n if (isSelectionOnHyperlink) {\n selection.fireRequestNavigate(hyperlinkField);\n return;\n }\n var paragraph = selection.start.paragraph;\n if (paragraph.isEmpty() && paragraph.paragraphFormat.listFormat.listId !== -1) {\n // tslint:disable-next-line:max-line-length\n this.onApplyListInternal(this.viewer.getListById(paragraph.paragraphFormat.listFormat.listId), paragraph.paragraphFormat.listFormat.listLevelNumber - 1);\n return;\n }\n }\n this.initHistory('Enter');\n var isRemoved = true;\n if (!selection.isEmpty) {\n // this.initHistoryWithSelection(selection, 'Enter');\n isRemoved = this.removeSelectedContents(selection);\n }\n if (isRemoved) {\n selection.owner.isShiftingEnabled = true;\n this.updateInsertPosition();\n var blockInfo = this.getParagraphInfo(selection.start);\n var initialStart = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n this.splitParagraphInternal(selection, selection.start.paragraph, selection.start.currentWidget, selection.start.offset);\n this.setPositionForCurrentIndex(selection.start, initialStart);\n var nextNode = selection.start.paragraph.nextWidget;\n if (isNullOrUndefined(nextNode)) {\n nextNode = selection.getNextRenderedBlock(selection.start.paragraph);\n }\n selection.selectParagraph(nextNode, true);\n this.updateEndPosition();\n // if (!isNullOrUndefined(selection.currentHistoryInfo)) {\n // this.updateComplexHistory();\n // } else {\n this.reLayout(selection);\n // }\n var paragraph = selection.start.paragraph.previousWidget;\n if (!isNullOrUndefined(paragraph) && !paragraph.isEmpty() &&\n // tslint:disable-next-line:max-line-length\n paragraph.lastChild.children[paragraph.lastChild.children.length - 1] instanceof TextElementBox) {\n this.checkAndConvertToHyperlink(selection, true, paragraph);\n }\n }\n };\n Editor.prototype.splitParagraphInternal = function (selection, paragraphAdv, currentLine, offset) {\n var insertIndex = 0;\n var blockIndex = paragraphAdv.index;\n var paragraph = new ParagraphWidget();\n var lineWidget = new LineWidget(paragraph);\n paragraph.childWidgets.push(lineWidget);\n //Copies the format to new paragraph.\n paragraph.paragraphFormat.ownerBase = paragraph;\n if (currentLine === paragraphAdv.lastChild && offset === selection.getLineLength(currentLine)) {\n // tslint:disable-next-line:max-line-length\n if (paragraphAdv.paragraphFormat.baseStyle\n && paragraphAdv.paragraphFormat.baseStyle.name !== 'Normal' && paragraphAdv.paragraphFormat.baseStyle.next instanceof WParagraphStyle) {\n paragraph.paragraphFormat.baseStyle = paragraphAdv.paragraphFormat.baseStyle.next;\n if (paragraphAdv.paragraphFormat.baseStyle.name === 'List Paragraph') {\n paragraph.paragraphFormat.listFormat.copyFormat(paragraphAdv.paragraphFormat.listFormat);\n }\n this.selection.skipFormatRetrieval = false;\n }\n else {\n paragraph.paragraphFormat.copyFormat(paragraphAdv.paragraphFormat);\n paragraph.characterFormat.copyFormat(paragraphAdv.characterFormat);\n }\n //ToDo in future: Need to skip copying formattings to new paragraph, if the style for following paragraph is same style.\n insertIndex++;\n blockIndex++;\n }\n else {\n paragraph.paragraphFormat.copyFormat(paragraphAdv.paragraphFormat);\n paragraph.characterFormat.copyFormat(paragraphAdv.characterFormat);\n paragraphAdv = paragraphAdv.combineWidget(this.viewer);\n if (offset > 0 || !currentLine.isFirstLine()) {\n this.moveInlines(paragraphAdv, paragraph, 0, 0, paragraphAdv.firstChild, offset, currentLine);\n }\n var paragraphs = paragraphAdv.getSplitWidgets();\n paragraphAdv = paragraphs[0];\n }\n insertIndex += paragraphAdv.getIndex();\n var container = paragraphAdv.containerWidget;\n var childNodes = container.childWidgets;\n childNodes.splice(insertIndex, 0, paragraph);\n paragraph.containerWidget = container;\n paragraph.index = blockIndex;\n this.updateNextBlocksIndex(paragraph, true);\n // tslint:disable-next-line:max-line-length\n this.viewer.layout.layoutBodyWidgetCollection(blockIndex, container, paragraph, false);\n };\n /**\n * @private\n */\n Editor.prototype.updateNextBlocksIndex = function (block, increaseIndex) {\n var nextIndex = block.containerWidget.childWidgets.indexOf(block) + 1;\n if (block.containerWidget instanceof BodyWidget) {\n var currentSectionIndex = block.containerWidget.index;\n for (var j = this.viewer.pages.indexOf(block.containerWidget.page); j < this.viewer.pages.length; j++) {\n var page = this.viewer.pages[j];\n if (page.bodyWidgets[0].index === currentSectionIndex) {\n for (var k = nextIndex; k < page.bodyWidgets[0].childWidgets.length; k++) {\n var childWidget = page.bodyWidgets[0].childWidgets[k];\n this.updateIndex(childWidget, increaseIndex);\n }\n nextIndex = 0;\n }\n else {\n return;\n }\n }\n }\n else if (block.containerWidget instanceof TableCellWidget) {\n var cells = block.containerWidget.getSplitWidgets();\n var currentCellIndex = cells.indexOf(block.containerWidget);\n for (var x = currentCellIndex; x < cells.length; x++) {\n var blocks = cells[x].childWidgets;\n for (var y = nextIndex; y < blocks.length; y++) {\n this.updateIndex(blocks[y], increaseIndex);\n }\n currentCellIndex = 0;\n nextIndex = 0;\n }\n }\n else if (block.containerWidget instanceof TableRowWidget) {\n for (var i = nextIndex; i < block.containerWidget.childWidgets.length; i++) {\n var cell = block.containerWidget.childWidgets[i];\n if (cell.rowIndex === block.containerWidget.index) {\n this.updateIndex(cell, increaseIndex);\n }\n }\n }\n else if (block.containerWidget instanceof TableWidget) {\n for (var i = nextIndex; i < block.containerWidget.childWidgets.length; i++) {\n var row = block.containerWidget.childWidgets[i];\n this.updateIndex(row, increaseIndex);\n for (var j = 0; j < row.childWidgets.length; j++) {\n row.childWidgets[j].rowIndex = row.index;\n }\n }\n //update Row index of all the cell\n }\n else if (block.containerWidget instanceof HeaderFooterWidget) {\n for (var i = nextIndex; i < block.containerWidget.childWidgets.length; i++) {\n var nextBlock = block.containerWidget.childWidgets[i];\n this.updateIndex(nextBlock, increaseIndex);\n }\n }\n };\n Editor.prototype.updateIndex = function (widget, increment) {\n if (increment) {\n widget.index++;\n }\n else {\n widget.index--;\n }\n };\n Editor.prototype.updateEndPosition = function () {\n var selection = this.viewer.selection;\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.updateHistoryPosition(selection.start, false);\n }\n };\n /**\n * @private\n */\n Editor.prototype.onBackSpace = function () {\n var selection = this.viewer.selection;\n if (selection.isEmpty) {\n this.singleBackspace(selection, false);\n }\n else {\n this.initHistory('BackSpace');\n var skipBackSpace = this.deleteSelectedContents(selection, true);\n if (this.editorHistory && this.editorHistory.currentBaseHistoryInfo) {\n if (skipBackSpace) {\n this.editorHistory.currentBaseHistoryInfo = undefined;\n }\n else {\n if (this.checkEndPosition(selection)) {\n this.updateHistoryPosition(selection.end, false);\n }\n this.reLayout(selection);\n }\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.insertRemoveBookMarkElements = function () {\n var isHandledComplexHistory = false;\n for (var i = 0; i < this.removedBookmarkElements.length; i++) {\n var bookMark = this.removedBookmarkElements[i];\n if (bookMark.bookmarkType === 0) {\n var bookMarkStart = bookMark;\n if (bookMarkStart && bookMarkStart.reference && this.removedBookmarkElements.indexOf(bookMarkStart.reference) !== -1) {\n var endIndex = this.removedBookmarkElements.indexOf(bookMarkStart.reference);\n var startIndex = this.removedBookmarkElements.indexOf(bookMarkStart);\n this.removedBookmarkElements.splice(endIndex, 1);\n this.removedBookmarkElements.splice(startIndex, 1);\n }\n else {\n this.initComplexHistory(this.editorHistory.currentBaseHistoryInfo.action);\n this.editorHistory.updateHistory();\n this.initInsertInline(bookMarkStart.clone());\n this.editorHistory.updateComplexHistory();\n isHandledComplexHistory = true;\n }\n }\n else {\n var bookMarkEnd = bookMark;\n if (bookMarkEnd && bookMarkEnd.reference && this.removedBookmarkElements.indexOf(bookMarkEnd.reference) !== -1) {\n var endIndex = this.removedBookmarkElements.indexOf(bookMarkEnd.reference);\n var startIndex = this.removedBookmarkElements.indexOf(bookMarkEnd);\n this.removedBookmarkElements.splice(endIndex, 1);\n this.removedBookmarkElements.splice(startIndex, 1);\n }\n else {\n this.initComplexHistory(this.editorHistory.currentBaseHistoryInfo.action);\n this.editorHistory.updateHistory();\n this.initInsertInline(bookMarkEnd.clone());\n this.editorHistory.updateComplexHistory();\n isHandledComplexHistory = true;\n }\n }\n }\n this.removedBookmarkElements = [];\n return isHandledComplexHistory;\n };\n /**\n * @private\n */\n Editor.prototype.deleteSelectedContents = function (selection, isBackSpace) {\n var skipBackSpace = this.deleteSelectedContentInternal(selection, isBackSpace, selection.start, selection.end);\n var textPosition = new TextPosition(selection.owner);\n var blockInfo = this.getParagraph({ index: selection.editPosition });\n var lineInfo = this.getLineInfo(blockInfo.paragraph, blockInfo.offset);\n textPosition.setPositionForLineWidget(lineInfo.line, lineInfo.offset);\n selection.selectContent(textPosition, true);\n return skipBackSpace;\n };\n /**\n * @private\n */\n Editor.prototype.singleBackspace = function (selection, isRedoing) {\n var history = this.editorHistory;\n // If backspace is pressed after auto format to hyperlink is done, need to undo auto format.\n if (history && !isRedoing && !history.canRedo() && history.canUndo()) {\n var historyInfo = history.undoStack[history.undoStack.length - 1];\n var startBlockInfo = this.getParagraphInfo(selection.start);\n var endBlockInfo = this.getParagraphInfo(selection.end);\n // tslint:disable-next-line:max-line-length\n if (historyInfo.action === 'AutoFormatHyperlink' && historyInfo.insertPosition === this.getHierarchicalIndex(startBlockInfo.paragraph, startBlockInfo.offset.toString()) &&\n historyInfo.endPosition === this.getHierarchicalIndex(endBlockInfo.paragraph, endBlockInfo.offset.toString())) {\n history.undo();\n return;\n }\n }\n var paragraph = selection.start.paragraph;\n var currentLineWidget = selection.start.currentWidget;\n var offset = selection.start.offset;\n var indexInInline = 0;\n var inlineObj = currentLineWidget.getInline(offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n var previousInline = inline;\n if (inline instanceof FieldElementBox && inline.fieldType === 2) {\n if (HelperMethods.isLinkedFieldCharacter(inline)) {\n var begin = inline.fieldBegin;\n var end = inline.fieldEnd;\n selection.start.setPositionParagraph(begin.line, begin.line.getOffset(begin, 0));\n selection.end.setPositionParagraph(end.line, end.line.getOffset(end, 0) + 1);\n selection.fireSelectionChanged(true);\n return;\n }\n }\n if (inline instanceof FieldElementBox && inline.fieldType === 1) {\n var prevInline = selection.getPreviousValidElement(inline);\n if (prevInline instanceof FieldElementBox) {\n inline = prevInline.fieldBegin;\n paragraph = inline.line.paragraph;\n offset = inline.line.getOffset(inline, 0);\n selection.end.setPositionParagraph(inline.line, offset); //Selects the entire field.\n selection.fireSelectionChanged(true);\n return;\n }\n else if (prevInline !== inline) {\n inline = prevInline; //Updates the offset to delete next content.\n paragraph = inline.line.paragraph;\n offset = inline.line.getOffset(inline, inline.length);\n }\n }\n if (inline && (inline instanceof BookmarkElementBox && inline.bookmarkType === 1\n || inline.previousNode instanceof BookmarkElementBox)) {\n if (inline instanceof BookmarkElementBox) {\n inline = inline.previousNode;\n paragraph = inline.line.paragraph;\n offset = inline.line.getOffset(inline, inline.length);\n }\n if (inline.length === 1 && inline.nextNode instanceof BookmarkElementBox && inline.previousNode instanceof BookmarkElementBox) {\n var begin = inline.previousNode;\n var end = inline.nextNode;\n selection.start.setPositionParagraph(begin.line, begin.line.getOffset(begin, 0));\n selection.end.setPositionParagraph(end.line, end.line.getOffset(end, 0) + 1);\n this.initHistory('BackSpace');\n this.deleteSelectedContents(selection, true);\n if (this.checkEndPosition(selection)) {\n this.updateHistoryPosition(selection.end, false);\n }\n this.reLayout(selection);\n return;\n }\n }\n if (!isRedoing) {\n this.initHistory('BackSpace');\n }\n if (offset === selection.getStartOffset(paragraph) && selection.start.currentWidget.isFirstLine()) {\n if (paragraph.paragraphFormat.listFormat && paragraph.paragraphFormat.listFormat.listId !== -1) {\n this.onApplyList(undefined);\n return;\n }\n if (paragraph.paragraphFormat.firstLineIndent !== 0) {\n this.onApplyParagraphFormat('firstLineIndent', 0, false, false);\n return;\n }\n if (paragraph.paragraphFormat.leftIndent !== 0) {\n this.onApplyParagraphFormat('leftIndent', 0, false, false);\n return;\n }\n if (paragraph.paragraphFormat.textAlignment !== 'Left') {\n this.onApplyParagraphFormat('textAlignment', 'Left', false, true);\n return;\n }\n if (paragraph.previousRenderedWidget instanceof ParagraphWidget) {\n selection.owner.isShiftingEnabled = true;\n var previousParagraph = paragraph.previousRenderedWidget;\n // if (isNullOrUndefined(previousParagraph)) {\n // previousParagraph = this.viewer.selection.getPreviousBlock(paragraph) as ParagraphWidget;\n // }\n if (previousParagraph.isEmpty()) {\n this.removeBlock(previousParagraph);\n this.addRemovedNodes(previousParagraph);\n }\n else {\n this.removeBlock(paragraph);\n var endOffset = this.viewer.selection.getLineLength(previousParagraph.lastChild);\n var previousIndex = previousParagraph.childWidgets.length - 1;\n var lineWidget = void 0;\n if (!paragraph.isEmpty()) {\n for (var i = 0; i < paragraph.childWidgets.length; i++) {\n lineWidget = paragraph.childWidgets[i];\n previousParagraph.childWidgets.push(lineWidget);\n paragraph.childWidgets.splice(i, 1);\n i--;\n lineWidget.paragraph = previousParagraph;\n }\n }\n this.viewer.layout.reLayoutParagraph(previousParagraph, previousIndex, 0);\n selection.selects(previousParagraph.childWidgets[previousIndex], endOffset, true);\n this.addRemovedNodes(paragraph);\n }\n this.setPositionForHistory();\n // if (!isRedoing) {\n this.reLayout(selection);\n // }\n }\n else {\n if (this.editorHistory) {\n this.editorHistory.currentBaseHistoryInfo = undefined;\n }\n }\n }\n else {\n if (!isRedoing) {\n selection.owner.isShiftingEnabled = true;\n }\n var paragraphInfo = this.getParagraphInfo(selection.start);\n var lineWidget = selection.start.currentWidget;\n var removeOffset = offset - 1;\n if (removeOffset < 0) {\n lineWidget = lineWidget.previousLine;\n removeOffset = this.viewer.selection.getLineLength(lineWidget) + removeOffset;\n }\n this.removeAtOffset(lineWidget, selection, removeOffset);\n this.setPositionParagraph(paragraphInfo.paragraph, paragraphInfo.offset - 1, false);\n this.setPositionForHistory();\n if (!isRedoing) {\n this.reLayout(selection);\n }\n else {\n this.fireContentChange();\n }\n }\n };\n Editor.prototype.setPositionForHistory = function (editPosition) {\n var selection = this.viewer.selection;\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n if (isNullOrUndefined(editPosition)) {\n this.updateHistoryPosition(selection.start, true);\n this.editorHistory.currentBaseHistoryInfo.endPosition = this.editorHistory.currentBaseHistoryInfo.insertPosition;\n }\n else {\n this.editorHistory.currentBaseHistoryInfo.insertPosition = editPosition;\n this.editorHistory.currentBaseHistoryInfo.endPosition = editPosition;\n }\n }\n };\n Editor.prototype.removeAtOffset = function (lineWidget, selection, offset) {\n var count = 0;\n var lineIndex = lineWidget.paragraph.childWidgets.indexOf(lineWidget);\n for (var i = 0; i < lineWidget.children.length; i++) {\n var inline = lineWidget.children[i];\n if (inline instanceof ListTextElementBox) {\n continue;\n }\n if (offset < count + inline.length) {\n var indexInInline = offset - count;\n if (offset === count && inline.length === 1) {\n this.unLinkFieldCharacter(inline);\n lineWidget.children.splice(i, 1);\n this.viewer.layout.reLayoutParagraph(lineWidget.paragraph, lineIndex, i);\n this.addRemovedNodes(inline);\n }\n else {\n var span = new TextElementBox();\n span.characterFormat.copyFormat(inline.characterFormat);\n span.text = inline.text.substr(indexInInline, 1);\n inline.text = HelperMethods.remove(inline.text, indexInInline, 1);\n this.viewer.layout.reLayoutParagraph(lineWidget.paragraph, lineIndex, i);\n this.addRemovedNodes(span);\n }\n break;\n }\n count += inline.length;\n }\n };\n /**\n * @private\n */\n Editor.prototype.onDelete = function () {\n var selection = this.viewer.selection;\n if (selection.isEmpty) {\n this.singleDelete(selection, false);\n }\n else {\n // this.initComplexHistory('MultiSelection');\n // for (let i: number = 0; i < selection.selectionRanges.length; i++) {\n // let selectionRange: SelectionRange = selection.selectionRanges.getRange(i);\n this.initHistory('Delete');\n this.deleteSelectedContentInternal(selection, false, selection.start, selection.end);\n var textPosition = new TextPosition(selection.owner);\n this.setPositionForCurrentIndex(textPosition, selection.editPosition);\n selection.selectContent(textPosition, true);\n // if (this.viewer.owner.enableEditorHistory) {\n this.reLayout(selection);\n // }\n // this.updateSelectionRangeOffSet(selection.start, selection.end);\n // }\n // let textPosition: TextPosition = new TextPosition(selection.owner, this.viewer);\n // this.setPositionForCurrentIndex(textPosition,selection.editPosition);\n // selection.selectContent(textPosition, true);\n // if (!isNullOrUndefined(selection.currentHistoryInfo)) {\n // this.updateComplexHistory();\n // } else {\n // this.updateComplexWithoutHistory();\n // }\n }\n };\n /**\n * Remove single character on right of cursor position\n * @param {Selection} selection\n * @param {boolean} isRedoing\n * @private\n */\n Editor.prototype.singleDelete = function (selection, isRedoing) {\n // tslint:disable-next-line:max-line-length\n var paragraph = selection.start.paragraph;\n var offset = selection.start.offset;\n var indexInInline = 0;\n var inlineObj = paragraph.getInline(selection.start.offset, indexInInline);\n var inline = inlineObj.element;\n indexInInline = inlineObj.index;\n if (paragraph.paragraphFormat.listFormat && paragraph.paragraphFormat.listFormat.listId !== -1 &&\n this.viewer.isListTextSelected && selection.contextType === 'List') {\n this.onApplyList(undefined);\n return;\n }\n if (!isNullOrUndefined(inline) && indexInInline === inline.length && !isNullOrUndefined(inline.nextNode)) {\n inline = inline.nextNode;\n indexInInline = 0;\n }\n if (!isNullOrUndefined(inline)) {\n var nextRenderedInline = undefined;\n var nextInline = selection.getNextValidElement(inline);\n if (nextInline instanceof ElementBox) {\n nextRenderedInline = nextInline;\n }\n if (!isNullOrUndefined(nextRenderedInline) && nextRenderedInline instanceof FieldElementBox\n && nextRenderedInline.fieldType === 0) {\n inline = nextRenderedInline.fieldEnd;\n paragraph = inline.line.paragraph;\n offset = inline.line.getOffset(inline, 1);\n selection.end.setPositionParagraph(inline.line, offset);\n selection.fireSelectionChanged(true);\n return;\n }\n else if (inline !== nextRenderedInline) {\n inline = nextRenderedInline;\n paragraph = inline.line.paragraph;\n offset = inline.line.getOffset(inline, 0);\n if (inline instanceof FieldElementBox && inline.fieldType === 1) {\n offset++;\n }\n }\n }\n if (inline && (inline instanceof BookmarkElementBox && inline.bookmarkType === 0\n || inline.nextNode instanceof BookmarkElementBox)) {\n if (inline instanceof BookmarkElementBox) {\n inline = inline.nextNode;\n paragraph = inline.line.paragraph;\n offset = inline.line.getOffset(inline, 0);\n }\n if (inline.length === 1 && inline.nextNode instanceof BookmarkElementBox\n && inline.previousNode instanceof BookmarkElementBox) {\n var bookMarkBegin = inline.previousNode;\n var bookMarkEnd = inline.nextNode;\n selection.start.setPositionParagraph(bookMarkBegin.line, bookMarkBegin.line.getOffset(bookMarkBegin, 0));\n selection.end.setPositionParagraph(bookMarkEnd.line, bookMarkEnd.line.getOffset(bookMarkEnd, 0) + 1);\n this.initHistory('Delete');\n this.deleteSelectedContentInternal(selection, false, selection.start, selection.end);\n var textPosition = new TextPosition(selection.owner);\n this.setPositionForCurrentIndex(textPosition, selection.editPosition);\n selection.selectContent(textPosition, true);\n this.reLayout(selection);\n return;\n }\n }\n if (selection.start.currentWidget.isLastLine() && offset === this.viewer.selection.getLineLength(selection.start.currentWidget)) {\n if (paragraph.isInsideTable && isNullOrUndefined(paragraph.nextWidget)) {\n return;\n }\n var previousParagraph = undefined;\n var newParagraph = undefined;\n var nextParagraph = selection.getNextParagraphBlock(paragraph);\n if (isNullOrUndefined(nextParagraph)) {\n if (offset > 0) {\n return;\n }\n else {\n if (paragraph.previousWidget instanceof ParagraphWidget) {\n previousParagraph = paragraph.previousWidget;\n }\n if (paragraph.previousWidget instanceof TableWidget) {\n return;\n }\n if (isNullOrUndefined(previousParagraph)) {\n return;\n //Adds an empty paragraph, to ensure minimal content.\n }\n }\n }\n if (!isRedoing) {\n this.initHistory('Delete');\n }\n var blockInfo = this.getParagraphInfo(selection.start);\n selection.editPosition = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n if (this.checkInsertPosition(selection)) {\n this.setPositionForHistory(selection.editPosition);\n }\n selection.owner.isShiftingEnabled = true;\n if (paragraph.isEmpty()) {\n this.removeBlock(paragraph);\n this.addRemovedNodes(paragraph);\n if (isNullOrUndefined(nextParagraph)) {\n if (isNullOrUndefined(previousParagraph)) {\n // selection.selectParagraph(newParagraph, true, true);\n var paraEndOffset = selection.getParagraphLength(newParagraph) + 1;\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n this.updateHistoryPosition(selection.start, true);\n //tslint:disable-next-line:max-line-length\n this.editorHistory.currentBaseHistoryInfo.endPosition = this.getHierarchicalIndex(newParagraph, paraEndOffset.toString());\n }\n }\n else {\n selection.selectParagraph(previousParagraph, false);\n this.setPositionForHistory();\n }\n }\n else {\n selection.selectParagraph(nextParagraph, true);\n }\n }\n else {\n paragraph = paragraph.combineWidget(this.viewer);\n // tslint:disable-next-line:max-line-length\n var currentParagraph = this.splitParagraph(paragraph, paragraph.firstChild, 0, selection.start.currentWidget, selection.start.offset, true);\n this.deleteParagraphMark(currentParagraph, selection, 0);\n this.addRemovedNodes(paragraph);\n this.setPositionForCurrentIndex(selection.start, selection.editPosition);\n selection.selectContent(selection.start, true);\n }\n // if (!isRedoing) {\n this.reLayout(selection);\n // }\n }\n else {\n this.singleDeleteInternal(selection, isRedoing, paragraph);\n }\n };\n Editor.prototype.singleDeleteInternal = function (selection, isRedoing, paragraph) {\n if (!isRedoing) {\n selection.owner.isShiftingEnabled = true;\n this.initHistory('Delete');\n }\n if (this.checkInsertPosition(selection)) {\n this.updateHistoryPosition(selection.start, true);\n this.editorHistory.currentBaseHistoryInfo.endPosition = this.editorHistory.currentBaseHistoryInfo.insertPosition;\n }\n var paragraphInfo = this.getParagraphInfo(selection.start);\n var lineWidget = selection.start.currentWidget;\n var removeOffset = selection.start.offset;\n var lineLength = selection.getLineLength(selection.start.currentWidget);\n if (removeOffset >= lineLength) {\n lineWidget = lineWidget.nextLine;\n removeOffset = removeOffset - lineLength;\n }\n this.removeAtOffset(lineWidget, selection, removeOffset);\n this.setPositionParagraph(paragraphInfo.paragraph, paragraphInfo.offset, false);\n if (!isRedoing) {\n this.reLayout(selection);\n }\n else {\n this.fireContentChange();\n }\n };\n Editor.prototype.deleteParagraphMark = function (paragraph, selection, editAction) {\n if (isNullOrUndefined(paragraph.containerWidget)) {\n return;\n }\n paragraph = paragraph.combineWidget(this.viewer);\n var nextParagraph = selection.getNextParagraphBlock(paragraph);\n if (paragraph.isInsideTable && isNullOrUndefined(paragraph.nextWidget) || isNullOrUndefined(nextParagraph)) {\n return;\n }\n //BodyWidget\n var section = paragraph.containerWidget instanceof BodyWidget ? paragraph.containerWidget : undefined;\n var table = undefined;\n if (selection.getNextRenderedBlock(paragraph) instanceof TableWidget) {\n table = selection.getNextRenderedBlock(paragraph);\n }\n else {\n table = undefined;\n }\n if (nextParagraph.isInsideTable && !isNullOrUndefined(table) && table.contains(nextParagraph.associatedCell)) {\n if (editAction < 4) {\n // let nextSection: BodyWidget = table.containerWidget instanceof BodyWidget ? table.containerWidget : undefined;\n // if (section !== nextSection) {\n // this.combineSection(section, selection, nextSection);\n // }\n var offset = 0;\n this.removeBlock(paragraph);\n this.viewer.layout.clearListElementBox(nextParagraph);\n this.viewer.layout.clearListElementBox(paragraph);\n for (var i = paragraph.childWidgets.length - 1; i >= 0; i--) {\n var line = paragraph.childWidgets[i];\n for (var j = line.children.length - 1; j >= 0; j--) {\n var element = line.children[j];\n offset += element.length;\n nextParagraph.firstChild.children.unshift(element);\n element.line = nextParagraph.firstChild;\n // this.layoutInlineCollection(false, 0, nextParagraph.inlines, inline);\n }\n }\n this.viewer.layout.reLayoutParagraph(nextParagraph, 0, 0);\n if (offset > 0) {\n selection.editPosition = this.getHierarchicalIndex(nextParagraph, offset.toString());\n }\n }\n }\n else {\n if (editAction < 4) {\n // let nextSection: WSection = nextParagraph.section instanceof WSection ? nextParagraph.section as WSection : undefined;\n // if (section !== nextSection) {\n // this.combineSection(section, selection, nextSection);\n // }\n var prevLength = paragraph.childWidgets.length - 1;\n var nextPara = nextParagraph.getSplitWidgets();\n nextParagraph = nextParagraph.combineWidget(this.viewer);\n this.viewer.layout.clearListElementBox(nextParagraph);\n this.viewer.layout.clearListElementBox(paragraph);\n this.updateEditPositionOnMerge(paragraph, nextParagraph);\n for (var i = 0; i < nextParagraph.childWidgets.length; i++) {\n var inline = nextParagraph.childWidgets[i];\n nextParagraph.childWidgets.splice(i, 1);\n paragraph.childWidgets.push(inline);\n inline.paragraph = paragraph;\n i--;\n }\n if (nextParagraph.childWidgets.length === 0) {\n nextParagraph.childWidgets.push(new LineWidget(nextParagraph));\n }\n this.removeBlock(nextParagraph);\n this.viewer.layout.reLayoutParagraph(paragraph, 0, 0);\n this.addRemovedNodes(nextParagraph);\n }\n }\n };\n Editor.prototype.updateEditPositionOnMerge = function (currentParagraph, nextParagraph) {\n if (this.viewer.selection.editPosition === this.getHierarchicalIndex(nextParagraph, '0') &&\n nextParagraph.nextRenderedWidget === undefined) {\n // tslint:disable-next-line:max-line-length\n this.viewer.selection.editPosition = this.getHierarchicalIndex(currentParagraph, this.viewer.selection.getLineLength(currentParagraph.lastChild).toString());\n }\n };\n Editor.prototype.checkEndPosition = function (selection) {\n return (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)\n && isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo.endPosition));\n };\n Editor.prototype.checkInsertPosition = function (selection) {\n return (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)\n && isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo.insertPosition));\n };\n Editor.prototype.checkIsNotRedoing = function () {\n return this.viewer.owner.enableHistoryMode && !this.editorHistory.isRedoing;\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.deleteSelectedContentInternal = function (selection, isBackSpace, startPosition, endPosition) {\n var startPos = startPosition;\n var endPos = endPosition;\n if (!startPosition.isExistBefore(endPosition)) {\n startPos = endPosition;\n endPos = startPosition;\n }\n var blockInfo = this.getParagraphInfo(startPos);\n selection.editPosition = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n var skipBackSpace = false;\n if (isBackSpace && startPos.isInSameParagraph(endPos)) {\n //Handled specifically to skip removal of contents, if selection is only paragraph mark and next rendered block is table.\n if (startPos.offset < endPos.offset && startPos.offset === selection.getParagraphLength(endPos.paragraph)) {\n var nextBlock = selection.getNextRenderedBlock(startPos.paragraph);\n skipBackSpace = nextBlock instanceof TableWidget;\n }\n //Handled specifically to remove paragraph completely (Delete behavior), if the selected paragraph is empty.\n if (endPos.offset === 1 && endPos.offset > selection.getParagraphLength(endPos.paragraph)\n && !(endPos.paragraph.isInsideTable && isNullOrUndefined(endPos.paragraph.nextWidget))) {\n isBackSpace = false;\n }\n }\n if (!skipBackSpace) {\n selection.owner.isShiftingEnabled = true;\n if (this.checkInsertPosition(selection)) {\n this.editorHistory.currentBaseHistoryInfo.insertPosition = selection.editPosition;\n }\n var editAction = (isBackSpace ? 1 : 0);\n this.deleteSelectedContent(endPos.paragraph, selection, startPos, endPos, editAction);\n }\n return skipBackSpace;\n };\n /**\n * Init EditorHistory\n * @private\n */\n Editor.prototype.initHistory = function (action) {\n if (this.viewer.owner.enableHistoryMode) {\n this.editorHistory.initializeHistory(action);\n }\n };\n /**\n * Init Complex EditorHistory\n * @private\n */\n Editor.prototype.initComplexHistory = function (action) {\n if (this.viewer.owner.enableHistoryMode) {\n this.editorHistory.initComplexHistory(this.viewer.selection, action);\n }\n };\n //Insert Picture implementation starts\n /**\n * Insert image\n * @param {string} base64String\n * @param {number} width\n * @param {number} height\n * @private\n */\n Editor.prototype.insertPicture = function (base64String, width, height) {\n var imageElementBox = new ImageElementBox(true);\n imageElementBox.imageString = base64String;\n imageElementBox.width = width;\n imageElementBox.height = height;\n this.insertPictureInternal(imageElementBox);\n };\n Editor.prototype.insertPictureInternal = function (imageElementBox) {\n var selection = this.viewer.selection;\n this.initHistory('InsertInline');\n this.fitImageToPage(selection, imageElementBox);\n this.insertInlineInSelection(selection, imageElementBox);\n this.reLayout(selection);\n };\n Editor.prototype.fitImageToPage = function (selection, imageElementBox) {\n var section = selection.start.paragraph.bodyWidget;\n var pageWidth = section.sectionFormat.pageWidth - section.sectionFormat.leftMargin - section.sectionFormat.rightMargin;\n var pageHeight = section.sectionFormat.pageHeight - section.sectionFormat.topMargin - section.sectionFormat.topMargin;\n //Resizes image to page size.\n if (imageElementBox.width > pageWidth) {\n imageElementBox.height = imageElementBox.height * pageWidth / imageElementBox.width;\n imageElementBox.width = pageWidth;\n }\n if (imageElementBox.height > pageHeight) {\n imageElementBox.width = imageElementBox.width * pageHeight / imageElementBox.height;\n imageElementBox.height = pageHeight;\n }\n };\n //Insert Picture implementation ends\n /**\n * @private\n */\n Editor.prototype.insertInlineInSelection = function (selection, elementBox) {\n if (this.checkIsNotRedoing()) {\n selection.owner.isShiftingEnabled = true;\n }\n if (!selection.isEmpty) {\n this.removeSelectedContents(selection);\n }\n this.updateInsertPosition();\n this.insertInlineInternal(elementBox);\n if (this.checkEndPosition(selection)) {\n this.updateHistoryPosition(selection.start, false);\n }\n this.fireContentChange();\n };\n /**\n * @private\n */\n Editor.prototype.onPortrait = function () {\n var sectionFormat = new WSectionFormat();\n var width = this.viewer.selection.sectionFormat.pageWidth;\n var height = this.viewer.selection.sectionFormat.pageHeight;\n if (width > height) {\n sectionFormat.pageWidth = height;\n sectionFormat.pageHeight = width;\n }\n this.onApplySectionFormat(undefined, sectionFormat);\n };\n /**\n * @private\n */\n Editor.prototype.onLandscape = function () {\n var sectionFormat = new WSectionFormat();\n var width = this.viewer.selection.sectionFormat.pageWidth;\n var height = this.viewer.selection.sectionFormat.pageHeight;\n if (width < height) {\n sectionFormat.pageWidth = height;\n sectionFormat.pageHeight = width;\n }\n this.onApplySectionFormat(undefined, sectionFormat);\n };\n Editor.prototype.copyValues = function () {\n var format = new WSectionFormat();\n format.bottomMargin = this.viewer.selection.sectionFormat.bottomMargin;\n format.topMargin = this.viewer.selection.sectionFormat.topMargin;\n format.leftMargin = this.viewer.selection.sectionFormat.leftMargin;\n format.rightMargin = this.viewer.selection.sectionFormat.rightMargin;\n format.pageHeight = this.viewer.selection.sectionFormat.pageHeight;\n format.pageWidth = this.viewer.selection.sectionFormat.pageWidth;\n format.footerDistance = this.viewer.selection.sectionFormat.footerDistance;\n format.headerDistance = this.viewer.selection.sectionFormat.headerDistance;\n return format;\n };\n /**\n * @private\n */\n Editor.prototype.changeMarginValue = function (property) {\n var sectionFormat = this.copyValues();\n if (property === 'lastCustomSetting' || property === 'normal') {\n sectionFormat.topMargin = 72;\n sectionFormat.bottomMargin = 72;\n sectionFormat.leftMargin = 72;\n sectionFormat.rightMargin = 72;\n }\n else if (property === 'narrow') {\n sectionFormat.topMargin = 36;\n sectionFormat.bottomMargin = 36;\n sectionFormat.leftMargin = 36;\n sectionFormat.rightMargin = 36;\n }\n else if (property === 'moderate') {\n sectionFormat.topMargin = 72;\n sectionFormat.bottomMargin = 72;\n sectionFormat.leftMargin = 54;\n sectionFormat.rightMargin = 54;\n }\n else if (property === 'wide') {\n sectionFormat.topMargin = 72;\n sectionFormat.bottomMargin = 72;\n sectionFormat.leftMargin = 144;\n sectionFormat.rightMargin = 144;\n }\n else if (property === 'mirrored') {\n sectionFormat.topMargin = 72;\n sectionFormat.bottomMargin = 72;\n sectionFormat.leftMargin = 90;\n sectionFormat.rightMargin = 72;\n }\n else if (property === 'office2003Default') {\n sectionFormat.topMargin = 72;\n sectionFormat.bottomMargin = 72;\n sectionFormat.leftMargin = 90;\n sectionFormat.rightMargin = 90;\n }\n this.onApplySectionFormat(undefined, sectionFormat);\n };\n /**\n * @private\n */\n Editor.prototype.onPaperSize = function (property) {\n var sectionFormat = this.copyValues();\n var width = this.viewer.selection.sectionFormat.pageWidth;\n var height = this.viewer.selection.sectionFormat.pageHeight;\n if (property === 'letter') {\n if (width < height) {\n sectionFormat.pageWidth = 611.9;\n sectionFormat.pageHeight = 791.9;\n }\n else {\n sectionFormat.pageWidth = 791.9;\n sectionFormat.pageHeight = 611.9;\n }\n }\n else if (property === 'tabloid') {\n if (width < height) {\n sectionFormat.pageWidth = 791.9;\n sectionFormat.pageHeight = 1223.9;\n }\n else {\n sectionFormat.pageWidth = 1223.9;\n sectionFormat.pageHeight = 791.9;\n }\n }\n else if (property === 'legal') {\n if (width < height) {\n sectionFormat.pageWidth = 611.9;\n sectionFormat.pageHeight = 1007.9;\n }\n else {\n sectionFormat.pageWidth = 1007.9;\n sectionFormat.pageHeight = 611.9;\n }\n }\n else if (property === 'statement') {\n if (width < height) {\n sectionFormat.pageWidth = 396;\n sectionFormat.pageHeight = 611.9;\n }\n else {\n sectionFormat.pageWidth = 611.9;\n sectionFormat.pageHeight = 396;\n }\n }\n else if (property === 'executive') {\n if (width < height) {\n sectionFormat.pageWidth = 521.9;\n sectionFormat.pageHeight = 755.9;\n }\n else {\n sectionFormat.pageWidth = 755.9;\n sectionFormat.pageHeight = 521.9;\n }\n }\n else if (property === 'a3') {\n if (width < height) {\n sectionFormat.pageWidth = 841.8;\n sectionFormat.pageHeight = 1190.4;\n }\n else {\n sectionFormat.pageWidth = 1190.4;\n sectionFormat.pageHeight = 841.8;\n }\n }\n else if (property === 'a4') {\n if (width < height) {\n sectionFormat.pageWidth = 595.2;\n sectionFormat.pageHeight = 841.8;\n }\n else {\n sectionFormat.pageWidth = 841.8;\n sectionFormat.pageHeight = 595.2;\n }\n }\n else if (property === 'a5') {\n if (width < height) {\n sectionFormat.pageWidth = 419.5;\n sectionFormat.pageHeight = 595.2;\n }\n else {\n sectionFormat.pageWidth = 595.2;\n sectionFormat.pageHeight = 419.5;\n }\n }\n else if (property === 'b4') {\n if (width < height) {\n sectionFormat.pageWidth = 728.4;\n sectionFormat.pageHeight = 1031.7;\n }\n else {\n sectionFormat.pageWidth = 1031.7;\n sectionFormat.pageHeight = 728.4;\n }\n }\n else if (property === 'b5') {\n if (width < height) {\n sectionFormat.pageWidth = 515.8;\n sectionFormat.pageHeight = 728.4;\n }\n else {\n sectionFormat.pageWidth = 728.4;\n sectionFormat.pageHeight = 515.8;\n }\n }\n this.onApplySectionFormat(undefined, sectionFormat);\n };\n //Update List Items\n /**\n * @private\n */\n Editor.prototype.updateListItemsTillEnd = function (blockAdv, updateNextBlockList) {\n var block = updateNextBlockList ? this.viewer.selection.getNextRenderedBlock(blockAdv) : blockAdv;\n while (!isNullOrUndefined(block)) {\n //Updates the list value of the rendered paragraph. \n this.updateRenderedListItems(block);\n block = block.getSplitWidgets().pop().nextRenderedWidget;\n }\n };\n /**\n * @private\n */\n Editor.prototype.updateWholeListItems = function (block) {\n this.viewer.renderedLists.clear();\n var sectionIndex = block.bodyWidget.index;\n var currentBlock;\n for (var j = 0; j < this.viewer.pages.length; j++) {\n var page = this.viewer.pages[j];\n if (page.bodyWidgets[0].index === sectionIndex) {\n currentBlock = page.bodyWidgets[0].firstChild;\n break;\n }\n }\n var isListUpdated = false;\n do {\n isListUpdated = this.updateListItems(currentBlock, block);\n if (isListUpdated) {\n break;\n }\n currentBlock = currentBlock.getSplitWidgets().pop().nextRenderedWidget;\n } while (currentBlock);\n };\n Editor.prototype.updateListItems = function (blockAdv, block) {\n var isListUpdated = false;\n if (blockAdv instanceof ParagraphWidget) {\n isListUpdated = this.updateListItemsForPara(blockAdv, block);\n }\n else {\n isListUpdated = this.updateListItemsForTable(blockAdv, block);\n }\n return isListUpdated;\n };\n Editor.prototype.updateListItemsForTable = function (table, block) {\n if (block instanceof TableWidget && table.equals(block)) {\n return true;\n }\n var row = table.firstChild;\n do {\n var isListUpdated = this.updateListItemsForRow(row, block);\n if (isListUpdated) {\n return true;\n }\n row = row.getSplitWidgets().pop().nextRenderedWidget;\n } while (row);\n return false;\n };\n Editor.prototype.updateListItemsForRow = function (row, block) {\n if (block.isInsideTable && row.childWidgets.indexOf(this.viewer.selection.getContainerCell(block.associatedCell)) !== -1) {\n //Returns as list updated, inorder to start list numbering from first list paragraph of this row.\n return true;\n }\n var cell = row.firstChild;\n do {\n this.updateListItemsForCell(cell, block);\n cell = cell.nextRenderedWidget;\n } while (cell);\n return false;\n };\n Editor.prototype.updateListItemsForCell = function (cell, block) {\n if (cell.childWidgets.length === 0) {\n return;\n }\n var currentBlock = cell.firstChild;\n do {\n this.updateListItems(currentBlock, block);\n currentBlock = currentBlock.getSplitWidgets().pop().nextRenderedWidget;\n } while (currentBlock);\n };\n // public abstract updateListParagraphs(): void;\n /**\n * @private\n */\n Editor.prototype.updateRenderedListItems = function (block) {\n if (block instanceof ParagraphWidget) {\n this.updateRenderedListItemsForPara(block);\n }\n else {\n this.updateRenderedListItemsForTable(block);\n }\n };\n Editor.prototype.updateRenderedListItemsForTable = function (table) {\n var row = table.firstChild;\n do {\n this.updateRenderedListItemsForRow(row);\n row = row.getSplitWidgets().pop().nextRenderedWidget;\n } while (row);\n };\n Editor.prototype.updateRenderedListItemsForRow = function (row) {\n var cell = row.firstChild;\n do {\n this.updateRenderedListItemsForCell(cell);\n cell = cell.nextRenderedWidget;\n } while (cell);\n };\n Editor.prototype.updateRenderedListItemsForCell = function (cell) {\n if (cell.childWidgets.length === 0) {\n return;\n }\n var currentBlock = cell.firstChild;\n do {\n this.updateRenderedListItems(currentBlock);\n currentBlock = currentBlock.getSplitWidgets().pop().nextRenderedWidget;\n } while (currentBlock);\n };\n Editor.prototype.updateListItemsForPara = function (paragraph, block) {\n if (paragraph.equals(block)) {\n return true;\n }\n else {\n var currentList = undefined;\n var listLevelNumber = 0;\n if (!isNullOrUndefined(paragraph.paragraphFormat) && !isNullOrUndefined(paragraph.paragraphFormat.listFormat)) {\n currentList = this.viewer.getListById(paragraph.paragraphFormat.listFormat.listId);\n listLevelNumber = paragraph.paragraphFormat.listFormat.listLevelNumber;\n }\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(currentList) && !isNullOrUndefined(this.viewer.getAbstractListById(currentList.abstractListId))\n // tslint:disable-next-line:max-line-length\n && !isNullOrUndefined(this.viewer.getAbstractListById(currentList.abstractListId).levels[listLevelNumber])) {\n var currentListLevel = this.viewer.layout.getListLevel(currentList, listLevelNumber);\n //Updates the list numbering from document start for reLayouting.\n if (currentListLevel.listLevelPattern !== 'Bullet') {\n this.viewer.layout.getListNumber(paragraph.paragraphFormat.listFormat);\n }\n }\n }\n return false;\n };\n Editor.prototype.updateRenderedListItemsForPara = function (paragraph) {\n if (!isNullOrUndefined(this.viewer.getListById(paragraph.paragraphFormat.listFormat.listId))) {\n var currentList = this.viewer.getListById(paragraph.paragraphFormat.listFormat.listId);\n var listLevelNumber = paragraph.paragraphFormat.listFormat.listLevelNumber;\n if (!isNullOrUndefined(currentList) && !isNullOrUndefined(this.viewer.getAbstractListById(currentList.abstractListId))\n // tslint:disable-next-line:max-line-length\n && !isNullOrUndefined(this.viewer.getAbstractListById(currentList.abstractListId).levels[paragraph.paragraphFormat.listFormat.listLevelNumber])) {\n var currentListLevel = this.viewer.layout.getListLevel(currentList, listLevelNumber);\n //Updates the list numbering from document start for reLayouting.\n if (currentListLevel.listLevelPattern !== 'Bullet') {\n var element = undefined;\n if (paragraph.childWidgets.length > 0) {\n var lineWidget = paragraph.childWidgets[0];\n if (lineWidget.children.length > 0) {\n element = lineWidget.children[0];\n }\n }\n if (!isNullOrUndefined(element)) {\n element.text = this.viewer.layout.getListNumber(paragraph.paragraphFormat.listFormat);\n }\n }\n }\n }\n };\n /**\n * Get logical offset of paragraph.\n * @private\n */\n Editor.prototype.getParagraphInfo = function (position) {\n return this.getParagraphInfoInternal(position.currentWidget, position.offset);\n };\n /**\n * @private\n */\n Editor.prototype.getParagraphInfoInternal = function (line, lineOffset) {\n var paragraph = line.paragraph;\n var offset = this.selection.getParagraphLength(paragraph, line) + lineOffset;\n var previous = paragraph.previousSplitWidget;\n while (previous instanceof ParagraphWidget) {\n paragraph = previous;\n offset += this.viewer.selection.getParagraphLength(paragraph);\n previous = paragraph.previousSplitWidget;\n }\n return { 'paragraph': paragraph, 'offset': offset };\n };\n /**\n * Get offset value to update in selection\n * @private\n */\n Editor.prototype.getOffsetValue = function (selection) {\n if (this.startParagraph) {\n var lineInfo = this.getLineInfo(this.startParagraph, this.startOffset);\n selection.start.setPositionFromLine(lineInfo.line, lineInfo.offset);\n }\n selection.start.updatePhysicalPosition(true);\n if (selection.isEmpty) {\n selection.end.setPositionInternal(selection.start);\n }\n else {\n if (this.endParagraph) {\n var lineInfo = this.getLineInfo(this.endParagraph, this.endOffset);\n selection.end.setPositionFromLine(lineInfo.line, lineInfo.offset);\n }\n selection.end.updatePhysicalPosition(true);\n }\n };\n /**\n * Get offset value to update in selection\n * @private\n */\n Editor.prototype.getLineInfo = function (paragraph, offset) {\n var position = undefined;\n var element = undefined;\n var length = this.selection.getParagraphLength(paragraph);\n var next = paragraph.nextSplitWidget;\n if (offset > length + 1 && isNullOrUndefined(next)) {\n offset = length;\n }\n while (offset > length && next instanceof ParagraphWidget) {\n offset -= length;\n paragraph = next;\n length = this.selection.getParagraphLength(paragraph);\n next = paragraph.nextSplitWidget;\n }\n return this.selection.getLineInfo(paragraph, offset);\n };\n /**\n * @private\n */\n Editor.prototype.setPositionParagraph = function (paragraph, offset, skipSelectionChange) {\n var selection = this.viewer.selection;\n var lineInfo = this.getLineInfo(paragraph, offset);\n selection.start.setPositionFromLine(lineInfo.line, lineInfo.offset);\n selection.end.setPositionInternal(selection.start);\n if (!skipSelectionChange) {\n selection.fireSelectionChanged(true);\n }\n };\n /**\n * @private\n */\n Editor.prototype.setPositionForCurrentIndex = function (textPosition, editPosition) {\n var blockInfo = this.getParagraph({ index: editPosition });\n var lineInfo = this.getLineInfo(blockInfo.paragraph, blockInfo.offset);\n textPosition.setPositionForLineWidget(lineInfo.line, lineInfo.offset);\n };\n /**\n * @private\n */\n Editor.prototype.insertPageNumber = function (numberFormat) {\n if (isNullOrUndefined(numberFormat)) {\n numberFormat = '';\n }\n else {\n numberFormat = ' \\\\*' + numberFormat;\n }\n var fieldCode = 'PAGE ' + numberFormat + ' \\\\* MERGEFORMAT';\n this.createFields(fieldCode);\n };\n /**\n * @private\n */\n Editor.prototype.insertPageCount = function (numberFormat) {\n if (isNullOrUndefined(numberFormat)) {\n numberFormat = '';\n }\n else {\n numberFormat = ' \\*' + numberFormat;\n }\n var fieldCode = 'NUMPAGES ' + numberFormat + ' \\* MERGEFORMAT';\n this.createFields(fieldCode);\n };\n Editor.prototype.createFields = function (fieldCode) {\n var paragraph = new ParagraphWidget();\n var line = new LineWidget(paragraph);\n var fieldBegin = new FieldElementBox(0);\n line.children.push(fieldBegin);\n var fieldtext = new FieldTextElementBox();\n fieldtext.fieldBegin = fieldBegin;\n fieldtext.text = '1';\n var text = new TextElementBox();\n text.text = fieldCode;\n line.children.push(text);\n var fieldSeparator = new FieldElementBox(2);\n fieldSeparator.fieldBegin = fieldBegin;\n fieldBegin.fieldSeparator = fieldSeparator;\n line.children.push(fieldSeparator);\n line.children.push(fieldtext);\n var fieldEnd = new FieldElementBox(1);\n fieldEnd.fieldBegin = fieldBegin;\n fieldEnd.fieldSeparator = fieldSeparator;\n fieldSeparator.fieldEnd = fieldEnd;\n fieldBegin.fieldEnd = fieldEnd;\n line.children.push(fieldEnd);\n fieldBegin.line = line;\n paragraph.childWidgets.push(line);\n var widgets = [];\n widgets.push(paragraph);\n this.viewer.fields.push(fieldBegin);\n this.pasteContentsInternal(widgets);\n };\n /**\n * @private\n */\n Editor.prototype.insertBookmark = function (name) {\n var bookmark = new BookmarkElementBox(0);\n bookmark.name = name;\n var bookmarkEnd = new BookmarkElementBox(1);\n bookmarkEnd.name = name;\n bookmark.reference = bookmarkEnd;\n bookmarkEnd.reference = bookmark;\n this.viewer.bookmarks.add(name, bookmark);\n this.initComplexHistory('InsertBookmark');\n this.insertElements([bookmarkEnd], [bookmark]);\n if (this.editorHistory) {\n this.editorHistory.updateComplexHistoryInternal();\n }\n this.selection.start.setPositionForSelection(bookmark.line, bookmark, 1, this.selection.start.location);\n this.selection.end.setPositionForSelection(bookmarkEnd.line, bookmarkEnd, 0, this.selection.end.location);\n this.selection.fireSelectionChanged(true);\n this.fireContentChange();\n };\n /**\n * @private\n */\n Editor.prototype.deleteBookmark = function (bookmarkName) {\n var bookmarks = this.viewer.bookmarks;\n var bookmark = bookmarks.get(bookmarkName);\n if (bookmark instanceof BookmarkElementBox) {\n var bookmarkEnd = bookmark.reference;\n this.initHistory('DeleteBookmark');\n if (this.editorHistory) {\n this.editorHistory.currentBaseHistoryInfo.setBookmarkInfo(bookmark);\n this.editorHistory.updateHistory();\n }\n this.deleteBookmarkInternal(bookmark);\n }\n this.fireContentChange();\n };\n /**\n * @private\n */\n Editor.prototype.deleteBookmarkInternal = function (bookmark) {\n this.viewer.bookmarks.remove(bookmark.name);\n bookmark.line.children.splice(bookmark.indexInOwner, 1);\n bookmark.reference.line.children.splice(bookmark.reference.indexInOwner, 1);\n };\n /**\n * @private\n */\n Editor.prototype.getSelectionInfo = function () {\n var start = this.selection.start;\n var end = this.selection.end;\n var isEmpty = this.selection.isEmpty;\n if (!this.selection.isForward) {\n start = this.selection.end;\n end = this.selection.start;\n }\n var startElementInfo = start.currentWidget.getInline(start.offset, 0);\n var endElementInfo = end.currentWidget.getInline(end.offset, 0);\n // tslint:disable-next-line:max-line-length\n return { 'start': start.clone(), 'end': end.clone(), 'startElementInfo': startElementInfo, 'endElementInfo': endElementInfo, 'isEmpty': isEmpty };\n };\n /**\n * @private\n */\n Editor.prototype.insertElements = function (endElements, startElements) {\n var info = this.getSelectionInfo();\n if (!isNullOrUndefined(startElements)) {\n this.insertElementsInternal(info.start, startElements);\n }\n if (!isNullOrUndefined(endElements)) {\n this.insertElementsInternal(info.end, endElements);\n }\n };\n /**\n * @private\n */\n Editor.prototype.insertElementsInternal = function (position, elements) {\n this.selection.selectPosition(position, position);\n this.initHistory('InsertElements');\n this.updateInsertPosition();\n var indexInInline = 0;\n var paragraphInfo = this.getParagraphInfo(this.selection.start);\n if (this.selection.start.paragraph.isEmpty()) {\n var paragraph = this.selection.start.paragraph;\n paragraph.childWidgets[0].children.push(elements[0]);\n elements[0].line = paragraph.childWidgets[0];\n elements[0].linkFieldCharacter(this.viewer);\n this.viewer.layout.reLayoutParagraph(paragraph, 0, 0);\n this.setPositionParagraph(paragraphInfo.paragraph, paragraphInfo.offset + length, true);\n position.setPositionForSelection(elements[0].line, elements[0], elements[0].length, this.selection.start.location);\n this.selection.selectPosition(position, position);\n }\n else {\n var inlineObj = this.selection.start.currentWidget.getInline(this.viewer.selection.start.offset, indexInInline);\n var curInline = inlineObj.element;\n indexInInline = inlineObj.index;\n var firstElement = elements[0];\n this.insertElementInternal(curInline, firstElement, indexInInline, true);\n var index = firstElement.indexInOwner;\n var lastElement = firstElement;\n for (var i = 1; i < elements.length; i++) {\n lastElement = elements[i];\n firstElement.line.children.splice(index + i, 0, lastElement);\n }\n position.setPositionForSelection(lastElement.line, lastElement, lastElement.length, this.selection.start.location);\n this.selection.selectPosition(position, position);\n }\n if (this.editorHistory) {\n if (this.checkEndPosition()) {\n this.updateHistoryPosition(this.selection.start, false);\n }\n this.editorHistory.updateHistory();\n }\n };\n /**\n * @private\n */\n Editor.prototype.getHierarchicalIndex = function (block, offset) {\n var index;\n if (block) {\n if (block instanceof HeaderFooterWidget) {\n var hfString = block.headerFooterType.indexOf('Header') !== -1 ? 'H' : 'F';\n var pageIndex = block.page.index.toString();\n var headerFooterIndex = this.viewer.getHeaderFooter(block.headerFooterType).toString();\n var sectionIndex = block.page.sectionIndex;\n index = sectionIndex + ';' + hfString + ';' + pageIndex + ';' + offset;\n }\n else {\n index = block.index + ';' + offset;\n }\n if (block.containerWidget) {\n if (block instanceof TableCellWidget && block.rowIndex !== block.containerWidget.index) {\n index = block.rowIndex + ';' + index;\n block = block.containerWidget;\n }\n return this.getHierarchicalIndex(block.containerWidget, index);\n }\n }\n return index;\n };\n /**\n * @private\n */\n Editor.prototype.getBlock = function (position) {\n var bodyWidget = this.getBodyWidget(position);\n return this.getBlockInternal(bodyWidget, position);\n };\n /**\n * Return Block relative to position\n * @private\n */\n Editor.prototype.getBlockInternal = function (widget, position) {\n if (position.index === '' || isNullOrUndefined(position)) {\n return undefined;\n }\n var index = position.index.indexOf(';');\n var value = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n var node = widget;\n // if (node instanceof WSection && value === 'HF') {\n // //Gets the block in Header footers.\n // let blockObj: BlockInfo = this.getBlock((node as WSection).headerFooters, position);\n // tslint:disable-next-line:max-line-length\n // return { 'node': (!isNullOrUndefined(blockObj)) ? blockObj.node : undefined, 'position': (!isNullOrUndefined(blockObj)) ? blockObj.position : undefined };\n // }\n index = parseInt(value, 10);\n var childWidget = this.getBlockByIndex(widget, index);\n if (childWidget) {\n var child = childWidget;\n if (position.index.indexOf(';') >= 0) {\n if (child instanceof ParagraphWidget) {\n if (position.index.indexOf(';') >= 0) {\n position.index = '0';\n }\n return { 'node': child, 'position': position };\n }\n if (child instanceof Widget) {\n var blockObj = this.getBlockInternal(child, position);\n // tslint:disable-next-line:max-line-length\n return { 'node': (!isNullOrUndefined(blockObj)) ? blockObj.node : undefined, 'position': (!isNullOrUndefined(blockObj)) ? blockObj.position : undefined };\n }\n }\n else {\n return { 'node': child, 'position': position };\n }\n }\n else {\n return { 'node': node, 'position': position };\n }\n return { 'node': node, 'position': position };\n };\n /**\n * @private\n */\n Editor.prototype.getParagraph = function (position) {\n var paragraph = this.getParagraphInternal(this.getBodyWidget(position), position);\n return { paragraph: paragraph, offset: parseInt(position.index, 10) };\n };\n /**\n * Get paragraph relative to position\n * @private\n */\n Editor.prototype.getParagraphInternal = function (container, position) {\n if (isNullOrUndefined(position.index)) {\n return undefined;\n }\n // let ins: Widget = container;\n var index = position.index.indexOf(';');\n var value = '0';\n if (index >= 0) {\n value = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n }\n // if (container instanceof BodyWidget && value === 'HF') {\n // return this.getParagraph(container.headerFooters, position);\n // }\n index = parseInt(value, 10);\n if (container instanceof TableRowWidget && index >= container.childWidgets.length) {\n position.index = '0;0';\n index = container.childWidgets.length - 1;\n }\n var childWidget = this.getBlockByIndex(container, index);\n if (childWidget) {\n var child = childWidget;\n if (child instanceof ParagraphWidget) {\n if (position.index.indexOf(';') > 0) {\n position.index = '0';\n }\n return child;\n }\n if (child instanceof Widget) {\n if (position.index.indexOf(';') > 0) {\n return this.getParagraphInternal(child, position);\n }\n else {\n //If table is shifted to previous text position then return the first paragraph within table.\n if (child instanceof TableWidget) {\n return this.viewer.selection.getFirstParagraphInFirstCell(child);\n }\n return undefined;\n }\n }\n }\n else if (container) {\n var nextWidget = container.getSplitWidgets().pop().nextRenderedWidget;\n if (nextWidget instanceof Widget) {\n position.index = '0';\n if (nextWidget instanceof TableWidget) {\n return this.viewer.selection.getFirstParagraphInFirstCell(nextWidget);\n }\n return nextWidget;\n }\n }\n return undefined;\n };\n Editor.prototype.getBodyWidget = function (position) {\n var index = position.index.indexOf(';');\n var value = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n var sectionIndex = parseInt(value, 10);\n index = parseInt(value, 10);\n index = position.index.indexOf(';');\n value = position.index.substring(0, index);\n // position = position.substring(index).replace(';', '');\n if (value === 'H' || value === 'F') {\n return this.getHeaderFooterWidget(position);\n }\n index = parseInt(value, 10);\n return this.getBodyWidgetInternal(sectionIndex, index);\n };\n Editor.prototype.getHeaderFooterWidget = function (position) {\n //HEADER OR FOOTER WIDGET\n var index = position.index.indexOf(';');\n var value = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n var isHeader = value === 'H';\n index = position.index.indexOf(';');\n value = position.index.substring(0, index);\n position.index = position.index.substring(index).replace(';', '');\n index = parseInt(value, 10);\n var page = this.viewer.pages[index];\n if (isHeader) {\n return page.headerWidget;\n }\n else {\n return page.footerWidget;\n }\n };\n Editor.prototype.getBodyWidgetInternal = function (sectionIndex, blockIndex) {\n for (var i = 0; i < this.viewer.pages.length; i++) {\n var bodyWidget = this.viewer.pages[i].bodyWidgets[0];\n if (bodyWidget.index === sectionIndex) {\n if (bodyWidget.firstChild.index <= blockIndex && bodyWidget.lastChild.index >= blockIndex) {\n return bodyWidget;\n }\n }\n if (bodyWidget.index > sectionIndex) {\n break;\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n Editor.prototype.getBlockByIndex = function (container, blockIndex) {\n var childWidget;\n if (container) {\n for (var j = 0; j < container.childWidgets.length; j++) {\n if (container.childWidgets[j].index === blockIndex) {\n childWidget = container.childWidgets[j];\n break;\n }\n }\n if (!childWidget && !(container instanceof HeaderFooterWidget)) {\n return this.getBlockByIndex(container.nextSplitWidget, blockIndex);\n }\n }\n return childWidget;\n };\n /**\n * @private\n */\n Editor.prototype.updateHistoryPosition = function (position, isInsertPosition) {\n if (this.editorHistory && !isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n var hierarchicalIndex = void 0;\n if (position instanceof TextPosition) {\n var blockInfo = this.getParagraphInfo(position);\n hierarchicalIndex = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n }\n else {\n hierarchicalIndex = position;\n }\n if (isInsertPosition) {\n this.editorHistory.currentBaseHistoryInfo.insertPosition = hierarchicalIndex;\n }\n else {\n this.editorHistory.currentBaseHistoryInfo.endPosition = hierarchicalIndex;\n }\n }\n };\n /**\n * Applies the borders based on given settings.\n * @param {BorderSettings} settings\n */\n Editor.prototype.applyBorders = function (settings) {\n this.initHistory('Borders');\n var startPos = this.selection.isForward ? this.selection.start : this.selection.end;\n var endPos = this.selection.isForward ? this.selection.end : this.selection.start;\n var table = startPos.paragraph.associatedCell.ownerTable;\n table = table.combineWidget(this.viewer);\n if (this.editorHistory) {\n var clonedTable = this.cloneTableToHistoryInfo(table);\n }\n var startCell = startPos.paragraph.associatedCell;\n var endCell = endPos.paragraph.associatedCell;\n var cells;\n var border = this.getBorder(settings.borderColor, settings.lineWidth, settings.borderStyle);\n if (this.selection.isEmpty) {\n //Apply borders for current selected cell initially. \n if (settings.type === 'OutsideBorders' || settings.type === 'AllBorders' ||\n settings.type === 'LeftBorder') {\n endCell.cellFormat.borders.left.copyFormat(border);\n }\n if (settings.type === 'OutsideBorders' || settings.type === 'AllBorders' ||\n settings.type === 'TopBorder') {\n endCell.cellFormat.borders.top.copyFormat(border);\n }\n if (settings.type === 'OutsideBorders' || settings.type === 'AllBorders' ||\n settings.type === 'RightBorder') {\n endCell.cellFormat.borders.right.copyFormat(border);\n }\n if (settings.type === 'OutsideBorders' || settings.type === 'AllBorders' ||\n settings.type === 'BottomBorder') {\n endCell.cellFormat.borders.bottom.copyFormat(border);\n }\n if (settings.type === 'AllBorders' || settings.type === 'InsideBorders'\n || settings.type === 'InsideVerticalBorder') {\n endCell.cellFormat.borders.vertical.copyFormat(border);\n }\n if (settings.type === 'AllBorders' || settings.type === 'InsideBorders'\n || settings.type === 'InsideHorizontalBorder') {\n endCell.cellFormat.borders.horizontal.copyFormat(border);\n }\n if (settings.type === 'NoBorder') {\n this.clearAllBorderValues(endCell.cellFormat.borders);\n }\n }\n else {\n if (settings.type === 'OutsideBorders' || settings.type === 'TopBorder') {\n var selectedCell = this.getTopBorderCellsOnSelection();\n for (var i = 0; i < selectedCell.length; i++) {\n selectedCell[i].cellFormat.borders.top.copyFormat(border);\n }\n }\n if (settings.type === 'OutsideBorders' || settings.type === 'LeftBorder') {\n var selectedCell = this.getLeftBorderCellsOnSelection();\n for (var i = 0; i < selectedCell.length; i++) {\n selectedCell[i].cellFormat.borders.left.copyFormat(border);\n }\n }\n if (settings.type === 'OutsideBorders' || settings.type === 'RightBorder') {\n var selectedCell = this.getRightBorderCellsOnSelection();\n for (var i = 0; i < selectedCell.length; i++) {\n selectedCell[i].cellFormat.borders.right.copyFormat(border);\n }\n }\n if (settings.type === 'OutsideBorders' || settings.type === 'BottomBorder') {\n var selectedCell = this.getBottomBorderCellsOnSelection();\n for (var i = 0; i < selectedCell.length; i++) {\n selectedCell[i].cellFormat.borders.bottom.copyFormat(border);\n }\n }\n }\n //Apply Only borders property to selected cells \n if (settings.type === 'BottomBorder' || settings.type === 'AllBorders' || settings.type === 'OutsideBorders'\n || settings.type === 'NoBorder') {\n cells = this.getAdjacentCellToApplyBottomBorder();\n for (var i = 0; i < cells.length; i++) {\n var cell = cells[i];\n if (settings.type === 'NoBorder') {\n cell.cellFormat.borders.top.copyFormat(this.clearBorder());\n }\n else {\n cell.cellFormat.borders.top.copyFormat(border);\n }\n }\n }\n if (settings.type === 'AllBorders' || settings.type === 'OutsideBorders' || settings.type === 'RightBorder'\n || settings.type === 'NoBorder') {\n cells = this.getAdjacentCellToApplyRightBorder();\n for (var i = 0; i < cells.length; i++) {\n var cell = cells[i];\n if (settings.type === 'NoBorder') {\n cell.cellFormat.borders.left.copyFormat(this.clearBorder());\n }\n else {\n cell.cellFormat.borders.left.copyFormat(border);\n }\n }\n }\n if (settings.type === 'AllBorders' || settings.type === 'NoBorder') {\n this.applyAllBorders(border, settings.type);\n }\n if (settings.type === 'InsideBorders' || settings.type === 'InsideVerticalBorder'\n || settings.type === 'InsideHorizontalBorder' || settings.type === 'NoBorder') {\n this.applyInsideBorders(border, settings.type, table);\n }\n this.updateGridForTableDialog(table, false);\n this.reLayout(this.selection, false);\n this.editorHistory.updateHistory();\n };\n Editor.prototype.applyAllBorders = function (border, borderType) {\n var cells = this.selection.getSelectedCells();\n for (var i = 0; i < cells.length; i++) {\n if (borderType === 'NoBorder') {\n cells[i].cellFormat.borders.left.copyFormat(this.clearBorder());\n cells[i].cellFormat.borders.right.copyFormat(this.clearBorder());\n cells[i].cellFormat.borders.top.copyFormat(this.clearBorder());\n cells[i].cellFormat.borders.bottom.copyFormat(this.clearBorder());\n }\n else {\n cells[i].cellFormat.borders.left.copyFormat(border);\n cells[i].cellFormat.borders.right.copyFormat(border);\n cells[i].cellFormat.borders.top.copyFormat(border);\n cells[i].cellFormat.borders.bottom.copyFormat(border);\n }\n }\n };\n Editor.prototype.applyInsideBorders = function (border, borderType, table) {\n var cells = this.selection.getSelectedCells();\n for (var i = 0; i < cells.length; i++) {\n var cell = cells[i];\n var isLastSelectedRow = cell.ownerRow === cells[cells.length - 1].ownerRow;\n var isLastRightCell = (cell.columnIndex + cell.cellFormat.columnSpan - 1) === cells[cells.length - 1].columnIndex;\n if (borderType === 'NoBorder') {\n cell.cellFormat.borders.right.copyFormat(this.clearBorder());\n cell.cellFormat.borders.bottom.copyFormat(this.clearBorder());\n }\n else {\n if (!isLastRightCell && borderType !== 'InsideHorizontalBorder') {\n cell.cellFormat.borders.right.copyFormat(border);\n }\n if (!isLastSelectedRow && borderType !== 'InsideVerticalBorder') {\n cell.cellFormat.borders.bottom.copyFormat(border);\n }\n }\n if (!isLastSelectedRow && borderType !== 'InsideVerticalBorder') {\n // Apply adjacent bottom borders.\n var nextRowIndex = cell.ownerRow.rowIndex + cell.cellFormat.rowSpan;\n var nextRow = table.childWidgets[nextRowIndex];\n if (nextRow) {\n var selectedCells = this.getAdjacentBottomBorderOnEmptyCells(nextRow, cell, true);\n for (var j = 0; j < selectedCells.length; j++) {\n if (borderType === 'NoBorder') {\n selectedCells[j].cellFormat.borders.top.copyFormat(this.clearBorder());\n }\n else {\n selectedCells[j].cellFormat.borders.top.copyFormat(border);\n }\n }\n }\n }\n if (!isLastRightCell && borderType !== 'InsideHorizontalBorder') {\n // Apply adjacent right borders.\n var rightBorderCells = this.getSelectedCellsNextWidgets(cell, table);\n for (var k = 0; k < rightBorderCells.length; k++) {\n if (borderType === 'NoBorder') {\n rightBorderCells[k].cellFormat.borders.left.copyFormat(this.clearBorder());\n }\n else {\n rightBorderCells[k].cellFormat.borders.left.copyFormat(border);\n }\n }\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.getTopBorderCellsOnSelection = function () {\n var startPos = this.selection.isForward ? this.selection.start : this.selection.end;\n var startCell = startPos.paragraph.associatedCell;\n var topBorderCells = [];\n var cells = this.selection.getSelectedCells();\n for (var i = 0; i < cells.length; i++) {\n if (cells[i].ownerRow === startCell.ownerRow) {\n topBorderCells.push(cells[i]);\n }\n }\n return topBorderCells;\n };\n /**\n * @private\n */\n Editor.prototype.getLeftBorderCellsOnSelection = function () {\n var startPos = this.selection.isForward ? this.selection.start : this.selection.end;\n var startCell = startPos.paragraph.associatedCell;\n var cells = this.selection.getSelectedCells();\n var leftBorderCells = [];\n for (var i = 0; i < cells.length; i++) {\n if (cells[i].columnIndex === startCell.columnIndex) {\n leftBorderCells.push(cells[i]);\n }\n }\n return leftBorderCells;\n };\n /**\n * @private\n */\n Editor.prototype.getRightBorderCellsOnSelection = function () {\n var cells = this.selection.getSelectedCells();\n var rightBorderCells = [];\n for (var i = 0; i < cells.length; i++) {\n if ((cells[i].columnIndex + cells[i].cellFormat.columnSpan - 1) === cells[cells.length - 1].columnIndex) {\n rightBorderCells.push(cells[i]);\n }\n }\n return rightBorderCells;\n };\n /**\n * @private\n */\n Editor.prototype.getBottomBorderCellsOnSelection = function () {\n var endPos = this.selection.isForward ? this.selection.end : this.selection.start;\n var endCell = endPos.paragraph.associatedCell;\n var cells = this.selection.getSelectedCells();\n var bottomBorderCells = [];\n for (var i = 0; i < cells.length; i++) {\n if (cells[i].ownerRow === endCell.ownerRow) {\n bottomBorderCells.push(cells[i]);\n }\n }\n return bottomBorderCells;\n };\n /**\n * @private\n */\n Editor.prototype.clearAllBorderValues = function (borders) {\n var border = this.clearBorder();\n borders.bottom.copyFormat(border);\n borders.left.copyFormat(border);\n borders.right.copyFormat(border);\n borders.top.copyFormat(border);\n borders.vertical.copyFormat(border);\n borders.horizontal.copyFormat(border);\n };\n Editor.prototype.clearBorder = function () {\n var border = new WBorder();\n border.lineStyle = 'Cleared';\n return border;\n };\n /**\n * @private\n */\n Editor.prototype.getAdjacentCellToApplyBottomBorder = function () {\n var cells = [];\n var startPos = this.selection.start;\n var endPos = this.selection.end;\n if (!this.selection.isForward) {\n startPos = this.selection.end;\n endPos = this.selection.start;\n }\n var table = startPos.paragraph.associatedCell.ownerTable;\n table = table.combineWidget(this.viewer);\n var startCell = startPos.paragraph.associatedCell;\n var endCell = endPos.paragraph.associatedCell;\n var nextRowIndex = endCell.ownerRow.rowIndex + endCell.cellFormat.rowSpan;\n var nextRow = table.childWidgets[nextRowIndex];\n if (nextRow) {\n if (endCell.cellFormat.columnSpan > 1) {\n for (var i = endCell.columnIndex; i < endCell.columnIndex + endCell.cellFormat.columnSpan; i++) {\n cells.push(nextRow.childWidgets[i]);\n }\n }\n else {\n cells = this.getAdjacentBottomBorderOnEmptyCells(nextRow, endCell);\n if (!this.selection.isEmpty) {\n for (var i = 0; i < nextRow.childWidgets.length; i++) {\n var nextCellColIndex = nextRow.childWidgets[i].columnIndex;\n if (nextCellColIndex >= startCell.columnIndex && nextCellColIndex <= endCell.columnIndex) {\n cells.push(nextRow.childWidgets[i]);\n }\n }\n }\n }\n }\n return cells;\n };\n Editor.prototype.getAdjacentBottomBorderOnEmptyCells = function (nextRow, cell, isSingleCell) {\n var cells = [];\n if (cell.cellFormat.columnSpan > 1) {\n for (var i = cell.columnIndex; i < cell.columnIndex + cell.cellFormat.columnSpan; i++) {\n cells.push(nextRow.childWidgets[i]);\n }\n }\n else {\n if (this.selection.isEmpty || isSingleCell) {\n for (var i = 0; i < nextRow.childWidgets.length; i++) {\n if (nextRow.childWidgets[i].columnIndex === cell.columnIndex) {\n cells.push(nextRow.childWidgets[i]);\n }\n }\n }\n }\n return cells;\n };\n /**\n * @private\n */\n Editor.prototype.getAdjacentCellToApplyRightBorder = function () {\n var cells = [];\n var startPosIn = this.selection.start;\n var endPosIn = this.selection.end;\n if (!this.selection.isForward) {\n startPosIn = this.selection.end;\n endPosIn = this.selection.start;\n }\n var table = startPosIn.paragraph.associatedCell.ownerTable;\n table = table.combineWidget(this.viewer);\n var startCell = startPosIn.paragraph.associatedCell;\n var endCell = endPosIn.paragraph.associatedCell;\n if (this.selection.isEmpty) {\n var selectedCell = startPosIn.paragraph.associatedCell;\n cells = this.getSelectedCellsNextWidgets(selectedCell, table);\n }\n else {\n // tslint:disable-next-line:max-line-length\n var selectedCells = this.getRightBorderCellsOnSelection();\n for (var i = 0; i < selectedCells.length; i++) {\n var cell = selectedCells[i];\n cells = cells.concat(this.getSelectedCellsNextWidgets(cell, table));\n }\n }\n return cells;\n };\n Editor.prototype.getSelectedCellsNextWidgets = function (selectedCell, table) {\n var cells = [];\n if (selectedCell.nextWidget) {\n cells.push(selectedCell.nextWidget);\n }\n if (selectedCell.cellFormat.rowSpan > 1) {\n var nextRowIndex = selectedCell.ownerRow.rowIndex + selectedCell.cellFormat.rowSpan;\n for (var i = selectedCell.ownerRow.rowIndex + 1; i < nextRowIndex; i++) {\n var nextRow = table.childWidgets[i];\n if (nextRow) {\n for (var j = 0; j < nextRow.childWidgets.length; j++) {\n if (nextRow.childWidgets[j].columnIndex ===\n selectedCell.nextWidget.columnIndex) {\n cells.push(nextRow.childWidgets[j]);\n }\n }\n }\n }\n }\n return cells;\n };\n /**\n * @private\n */\n Editor.prototype.getBorder = function (borderColor, lineWidth, borderStyle) {\n var border = new WBorder();\n border.color = borderColor || '#000000';\n border.lineWidth = lineWidth || 1;\n border.lineStyle = borderStyle || 'Single';\n return border;\n };\n /**\n * Applies borders\n * @param {WBorders} sourceBorders\n * @param {WBorders} applyBorders\n * @private\n */\n Editor.prototype.applyBordersInternal = function (sourceBorders, applyBorders) {\n if (!isNullOrUndefined(sourceBorders) && !isNullOrUndefined(sourceBorders)) {\n if (!isNullOrUndefined(sourceBorders.top)) {\n this.applyBorder(sourceBorders.top, applyBorders.top);\n }\n if (!isNullOrUndefined(sourceBorders.bottom)) {\n this.applyBorder(sourceBorders.bottom, applyBorders.bottom);\n }\n if (!isNullOrUndefined(sourceBorders.left)) {\n this.applyBorder(sourceBorders.left, applyBorders.left);\n }\n if (!isNullOrUndefined(sourceBorders.right)) {\n this.applyBorder(sourceBorders.right, applyBorders.right);\n }\n if (!isNullOrUndefined(sourceBorders.horizontal)) {\n this.applyBorder(sourceBorders.horizontal, applyBorders.horizontal);\n }\n if (!isNullOrUndefined(sourceBorders.vertical)) {\n this.applyBorder(sourceBorders.vertical, applyBorders.vertical);\n }\n if (!isNullOrUndefined(sourceBorders.diagonalUp)) {\n this.applyBorder(sourceBorders.diagonalUp, applyBorders.diagonalUp);\n }\n if (!isNullOrUndefined(sourceBorders.diagonalDown)) {\n this.applyBorder(sourceBorders.diagonalDown, applyBorders.diagonalDown);\n }\n }\n };\n /**\n * Apply shading to table\n * @param {WShading} sourceShading\n * @param {WShading} applyShading\n * @private\n */\n Editor.prototype.applyShading = function (sourceShading, applyShading) {\n if (!isNullOrUndefined(applyShading) && !isNullOrUndefined(sourceShading)) {\n if (!isNullOrUndefined(applyShading.backgroundColor)\n && sourceShading.backgroundColor !== applyShading.backgroundColor) {\n sourceShading.backgroundColor = applyShading.backgroundColor;\n }\n if (!isNullOrUndefined(applyShading.foregroundColor)\n && sourceShading.foregroundColor !== applyShading.foregroundColor) {\n sourceShading.foregroundColor = applyShading.foregroundColor;\n }\n if (!isNullOrUndefined(applyShading.textureStyle)\n && sourceShading.textureStyle !== applyShading.textureStyle) {\n sourceShading.textureStyle = applyShading.textureStyle;\n }\n }\n };\n Editor.prototype.applyBorder = function (sourceBorder, applyBorder) {\n if (!isNullOrUndefined(sourceBorder) && !isNullOrUndefined(applyBorder)) {\n if (!isNullOrUndefined(applyBorder.color)\n && sourceBorder.color !== applyBorder.color) {\n sourceBorder.color = applyBorder.color;\n }\n if (!isNullOrUndefined(applyBorder.lineStyle)\n && sourceBorder.lineStyle !== applyBorder.lineStyle) {\n sourceBorder.lineStyle = applyBorder.lineStyle;\n }\n if (!isNullOrUndefined(applyBorder.lineWidth)\n && sourceBorder.lineWidth !== applyBorder.lineWidth) {\n sourceBorder.lineWidth = applyBorder.lineWidth;\n }\n if (!isNullOrUndefined(applyBorder.shadow)\n && sourceBorder.shadow !== applyBorder.shadow) {\n sourceBorder.shadow = applyBorder.shadow;\n }\n if (!isNullOrUndefined(applyBorder.space)\n && sourceBorder.space !== applyBorder.space) {\n sourceBorder.space = applyBorder.space;\n }\n }\n };\n /**\n * Apply Table Format changes\n * @param {Selection} selection\n * @param {WTableFormat} format\n * @private\n */\n Editor.prototype.onTableFormat = function (format) {\n if (!isNullOrUndefined(this.selection.tableFormat)) {\n this.viewer.owner.isShiftingEnabled = true;\n this.editorHistory.initializeHistory('TableFormat');\n var table = this.selection.start.paragraph.associatedCell.ownerTable.combineWidget(this.viewer);\n this.applyTableFormat(table, undefined, format);\n this.reLayout(this.selection, false);\n }\n };\n /**\n * @private\n */\n Editor.prototype.applyTableFormat = function (table, property, value) {\n this.applyTablePropertyValue(this.viewer.selection, undefined, value, table);\n };\n // tslint:disable-next-line:max-line-length\n Editor.prototype.applyTablePropertyValue = function (selection, property, value, table) {\n var sourceFormat = table.tableFormat;\n if (!isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n value = this.editorHistory.currentBaseHistoryInfo.addModifiedTableProperties(sourceFormat, property, value);\n }\n if (value instanceof WTableFormat) {\n if (isNullOrUndefined(property)) {\n this.handleTableFormat(sourceFormat, value);\n }\n return;\n }\n if (property === 'preferredWidth') {\n sourceFormat.preferredWidth = value;\n }\n else if (property === 'leftIndent') {\n sourceFormat.leftIndent = value;\n }\n else if (property === 'tableAlignment') {\n sourceFormat.tableAlignment = value;\n }\n else if (property === 'cellSpacing') {\n sourceFormat.cellSpacing = value;\n }\n else if (property === 'leftMargin') {\n sourceFormat.leftMargin = value;\n }\n else if (property === 'rightMargin') {\n sourceFormat.rightMargin = value;\n }\n else if (property === 'topMargin') {\n sourceFormat.topMargin = value;\n }\n else if (property === 'bottomMargin') {\n sourceFormat.bottomMargin = value;\n }\n else if (property === 'preferredWidthType') {\n sourceFormat.preferredWidthType = value;\n }\n if (property === 'shading') {\n sourceFormat.shading = value;\n }\n else if (property === 'borders') {\n sourceFormat.borders = value;\n }\n // if (!isNullOrUndefined(table)) {\n // this.layoutItemBlock(table, true);\n // }\n };\n Editor.prototype.handleTableFormat = function (tableFormat, applyFormat) {\n if (this.isBordersAndShadingDialog || this.editorHistory.isUndoing\n || this.editorHistory.isRedoing) {\n if (!isNullOrUndefined(tableFormat.borders)) {\n this.applyBordersInternal(tableFormat.borders, applyFormat.borders);\n }\n if (!isNullOrUndefined(tableFormat.shading)) {\n this.applyShading(tableFormat.shading, applyFormat.shading);\n }\n }\n if (!this.isBordersAndShadingDialog) {\n if (applyFormat.hasValue('preferredWidth') && applyFormat.preferredWidth !== tableFormat.preferredWidth) {\n tableFormat.preferredWidth = applyFormat.preferredWidth;\n }\n if (applyFormat.hasValue('preferredWidthType') && applyFormat.preferredWidthType !== tableFormat.preferredWidthType) {\n tableFormat.preferredWidthType = applyFormat.preferredWidthType;\n }\n if (applyFormat.hasValue('tableAlignment') && applyFormat.tableAlignment !== tableFormat.tableAlignment) {\n tableFormat.tableAlignment = applyFormat.tableAlignment;\n }\n if (applyFormat.hasValue('leftIndent') && applyFormat.leftIndent !== tableFormat.leftIndent) {\n tableFormat.leftIndent = applyFormat.leftIndent;\n }\n }\n this.updateGridForTableDialog(tableFormat.ownerBase, false);\n };\n Editor.prototype.updateGridForTableDialog = function (table, shiftNextItem) {\n if (table.tableHolder) {\n table.updateRowIndex(0);\n table.calculateGrid();\n table.isGridUpdated = false;\n }\n this.viewer.layout.reLayoutTable(table);\n };\n /**\n * Applies Row Format Changes\n * @param {Selection} selection\n * @param {WRowFormat} format\n * @param {WRow} row\n * @private\n */\n Editor.prototype.onRowFormat = function (format) {\n if (isNullOrUndefined(this.selection) || isNullOrUndefined(format)) {\n return;\n }\n this.editorHistory.initializeHistory('RowFormat');\n this.viewer.owner.isShiftingEnabled = true;\n var rowStartPos = this.selection.isForward ? this.selection.start : this.selection.end;\n var rowEndPos = this.selection.isForward ? this.selection.end : this.selection.start;\n var table = rowStartPos.paragraph.associatedCell.ownerTable.combineWidget(this.viewer);\n this.applyRowFormat(rowStartPos.paragraph.associatedCell.ownerRow, rowStartPos, rowEndPos, undefined, format);\n this.reLayout(this.selection, false);\n };\n Editor.prototype.applyRowFormat = function (row, start, end, property, value) {\n this.applyRowPropertyValue(this.viewer.selection, property, value, row);\n if (end.paragraph.associatedCell.ownerRow === row) {\n return;\n }\n var newRow = row.nextWidget;\n if (!isNullOrUndefined(newRow)) {\n this.applyRowFormat(newRow, start, end, property, value);\n }\n };\n Editor.prototype.applyRowPropertyValue = function (selection, property, value, row) {\n var applyFormat = row.rowFormat;\n if (!isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n value = this.editorHistory.currentBaseHistoryInfo.addModifiedRowProperties(applyFormat, property, value);\n }\n if (value instanceof WRowFormat) {\n if (isNullOrUndefined(property)) {\n this.handleRowFormat(value, applyFormat);\n }\n return;\n }\n if (property === 'heightType') {\n applyFormat.heightType = value;\n }\n else if (property === 'height') {\n applyFormat.height = value;\n }\n else if (property === 'isHeader') {\n applyFormat.isHeader = value;\n }\n else if (property === 'allowBreakAcrossPages') {\n applyFormat.allowBreakAcrossPages = value;\n }\n if (!isNullOrUndefined(row.ownerTable)) {\n this.layoutItemBlock(row.ownerTable, true);\n }\n };\n Editor.prototype.handleRowFormat = function (format, applyFormat) {\n if (format.hasValue('allowBreakAcrossPages') && format.allowBreakAcrossPages !== applyFormat.allowBreakAcrossPages) {\n applyFormat.allowBreakAcrossPages = format.allowBreakAcrossPages;\n }\n if (format.hasValue('isHeader') && format.isHeader !== applyFormat.isHeader) {\n applyFormat.isHeader = format.isHeader;\n }\n if (format.hasValue('heightType') && format.heightType !== applyFormat.heightType) {\n applyFormat.heightType = format.heightType;\n }\n if (format.hasValue('height') && format.height !== applyFormat.height) {\n applyFormat.height = format.height;\n }\n this.updateGridForTableDialog(applyFormat.ownerBase.ownerTable, true);\n };\n /**\n * Applies Cell Format changes\n * @param {Selection} selection\n * @param {WCellFormat} format\n * @param {WCell} cell\n * @private\n */\n Editor.prototype.onCellFormat = function (format) {\n if (isNullOrUndefined(this.selection) || isNullOrUndefined(format)) {\n return;\n }\n this.editorHistory.initializeHistory('CellFormat');\n this.updateFormatForCell(this.selection, undefined, format);\n this.reLayout(this.selection, false);\n };\n /**\n * @private\n */\n Editor.prototype.updateCellMargins = function (selection, value) {\n var cellStartPosition = selection.start;\n var cellEndPosition = selection.end;\n if (!selection.isForward) {\n cellStartPosition = selection.end;\n cellEndPosition = selection.start;\n }\n this.initHistoryPosition(selection, cellStartPosition);\n // tslint:disable-next-line:max-line-length\n this.viewer.owner.cellOptionsDialogModule.applyCellmarginsValue(cellStartPosition.paragraph.associatedCell.ownerRow, cellStartPosition, cellEndPosition, value);\n };\n /**\n * @private\n */\n Editor.prototype.updateFormatForCell = function (selection, property, value) {\n var start = selection.start;\n var end = selection.end;\n if (!selection.isForward) {\n start = selection.end;\n end = selection.start;\n }\n var startCell = start.paragraph.associatedCell;\n var endCell = end.paragraph.associatedCell;\n var cells;\n var table = startCell.ownerTable.combineWidget(this.viewer);\n var appliedFormat;\n for (var k = startCell.columnIndex; k <= endCell.columnIndex; k++) {\n cells = this.getSelectedCellInColumn(startCell.ownerTable, startCell.ownerRow.rowIndex, k, endCell.ownerRow.rowIndex);\n for (var i = 0; i < cells.length; i++) {\n appliedFormat = this.applyCellPropertyValue(this.viewer.selection, property, value, cells[i].cellFormat);\n }\n }\n this.updateGridForTableDialog(table, false);\n };\n /**\n * @private\n */\n Editor.prototype.getSelectedCellInColumn = function (table, rowStartIndex, columnIndex, rowEndIndex) {\n var cells = [];\n for (var i = rowStartIndex; i <= rowEndIndex; i++) {\n var row = table.childWidgets[i];\n for (var j = 0; j < row.childWidgets.length; j++) {\n if (row.childWidgets[j].columnIndex === columnIndex) {\n cells.push(row.childWidgets[j]);\n }\n }\n }\n return cells;\n };\n Editor.prototype.getColumnCells = function (table, columnIndex, isLeftSideCollection) {\n var cells = [];\n for (var k = 0; k < table.childWidgets.length; k++) {\n var row = table.childWidgets[k];\n for (var i = 0; i < row.childWidgets.length; i++) {\n var cell = row.childWidgets[i];\n if (isLeftSideCollection) {\n if (cell.columnIndex + cell.cellFormat.columnSpan === columnIndex) {\n cells.push(cell);\n }\n }\n else {\n if (cell.columnIndex === columnIndex) {\n cells.push(cell);\n }\n }\n }\n }\n return cells;\n };\n /**\n * @private\n */\n Editor.prototype.getTableWidth = function (table) {\n if (table.tableFormat.preferredWidth !== 0 || table.tableFormat.preferredWidthType === 'Percent') {\n if (table.tableFormat.preferredWidthType === 'Auto' || table.tableFormat.preferredWidthType === 'Point') {\n return table.tableFormat.preferredWidth;\n }\n else {\n if (table.tableFormat.preferredWidth === 0) {\n return 0;\n }\n else {\n return HelperMethods.convertPixelToPoint(this.viewer.clientArea.width) / 100 * table.tableFormat.preferredWidth;\n }\n }\n }\n return HelperMethods.convertPixelToPoint(this.viewer.layout.getTableWidth(table));\n };\n Editor.prototype.applyCellPropertyValue = function (selection, property, value, applyFormat) {\n if (!isNullOrUndefined(this.editorHistory.currentBaseHistoryInfo)) {\n value = this.editorHistory.currentBaseHistoryInfo.addModifiedCellProperties(applyFormat, property, value);\n }\n if (value instanceof WCellFormat) {\n if (isNullOrUndefined(property)) {\n this.handleCellFormat(value, applyFormat);\n }\n return value;\n }\n if (property === 'leftMargin') {\n applyFormat.leftMargin = value;\n }\n else if (property === 'topMargin') {\n applyFormat.topMargin = value;\n }\n else if (property === 'rightMargin') {\n applyFormat.rightMargin = value;\n }\n else if (property === 'bottomMargin') {\n applyFormat.bottomMargin = value;\n }\n else if (property === 'preferredWidth') {\n applyFormat.preferredWidth = value;\n applyFormat.cellWidth = value;\n }\n else if (property === 'cellWidth') {\n applyFormat.cellWidth = value;\n }\n else if (property === 'columnSpan') {\n applyFormat.columnSpan = value;\n }\n else if (property === 'rowSpan') {\n applyFormat.rowSpan = value;\n }\n else if (property === 'preferredWidthType') {\n applyFormat.preferredWidthType = value;\n }\n else if (property === 'verticalAlignment') {\n applyFormat.verticalAlignment = value;\n }\n if (property === 'shading') {\n applyFormat.shading = value;\n }\n else if (property === 'borders') {\n applyFormat.borders = value;\n }\n return undefined;\n };\n Editor.prototype.handleCellFormat = function (cellFormat, applyFormat) {\n if (!isNullOrUndefined(cellFormat) && !isNullOrUndefined(applyFormat)) {\n if (this.isBordersAndShadingDialog) {\n if (!isNullOrUndefined(cellFormat.borders)) {\n this.applyBordersInternal(applyFormat.borders, cellFormat.borders);\n }\n if (!isNullOrUndefined(cellFormat.shading)) {\n this.applyShading(applyFormat.shading, cellFormat.shading);\n }\n // this.layoutRow((applyFormat.ownerBase as TableCellWidget).ownerRow, this.viewer, false);\n }\n else {\n if (cellFormat.hasValue('preferredWidth') && applyFormat.preferredWidth !== cellFormat.preferredWidth) {\n applyFormat.preferredWidth = cellFormat.preferredWidth;\n }\n if (cellFormat.hasValue('preferredWidthType') && applyFormat.preferredWidthType !== cellFormat.preferredWidthType) {\n applyFormat.preferredWidthType = cellFormat.preferredWidthType;\n }\n if (cellFormat.hasValue('verticalAlignment') && applyFormat.verticalAlignment !== cellFormat.verticalAlignment) {\n applyFormat.verticalAlignment = cellFormat.verticalAlignment;\n }\n }\n }\n };\n /**\n * @private\n */\n Editor.prototype.destroy = function () {\n this.viewer = undefined;\n this.nodes = [];\n };\n Editor.prototype.isTocField = function (element) {\n if (element instanceof FieldElementBox) {\n var nextElement = element.nextNode;\n if (element instanceof FieldElementBox && element.fieldType === 0 && nextElement instanceof TextElementBox\n && nextElement.text.trim().toLowerCase().indexOf('toc') === 0) {\n return true;\n }\n }\n return false;\n };\n /**\n * Updates the table of contents.\n * @private\n */\n Editor.prototype.updateToc = function (tocField) {\n if (isNullOrUndefined(tocField)) {\n tocField = this.selection.getTocFieldInternal();\n }\n if (!this.isTocField(tocField)) {\n return;\n }\n // Decode field code to get parameters\n var code = this.selection.getFieldCode(tocField);\n if (code.toLocaleLowerCase().indexOf('toc') !== -1) {\n this.insertTableOfContents(this.validateTocSettings(this.getTocSettings(code, tocField)));\n }\n };\n Editor.prototype.getTocSettings = function (code, tocField) {\n var tocSettings = {};\n tocSettings.includePageNumber = true;\n tocSettings.rightAlign = true;\n // Decode field code to get parameters\n if (code.toLowerCase() === 'toc \\\\mergeformat') {\n tocSettings.startLevel = 1;\n tocSettings.endLevel = 3;\n }\n else {\n var swtiches = code.split('\\\\');\n for (var i = 0; i < swtiches.length; i++) {\n var swtch = swtiches[i];\n if (swtch.length === 0) {\n continue;\n }\n switch (swtch[0]) {\n case 'o':\n if (!isNullOrUndefined(swtch.match(/\\d+/g))) {\n var levels = swtch.match(/\\d+/g).map(Number);\n tocSettings.startLevel = levels[0];\n tocSettings.endLevel = levels[1];\n }\n else {\n tocSettings.startLevel = 1;\n tocSettings.endLevel = 9;\n }\n break;\n case 'h':\n tocSettings.includeHyperlink = true;\n break;\n case 'n':\n tocSettings.includePageNumber = false;\n break;\n case 'p':\n tocSettings.rightAlign = false;\n break;\n case 'u':\n tocSettings.includeOutlineLevels = true;\n break;\n case 't':\n this.decodeTSwitch(tocSettings, swtch);\n break;\n }\n }\n }\n //assigns tab leader.\n var tabs = tocField.paragraph.paragraphFormat.getUpdatedTabs();\n if (tabs.length > 0) {\n tocSettings.tabLeader = tabs[tabs.length - 1].tabLeader;\n }\n if (tocSettings.rightAlign && isNullOrUndefined(tocSettings.tabLeader)) {\n tocSettings.tabLeader = 'Dot';\n }\n return tocSettings;\n };\n Editor.prototype.decodeTSwitch = function (tocSettings, tSwitch) {\n tocSettings.levelSettings = {};\n tSwitch = tSwitch.replace('t', '');\n tSwitch = tSwitch.replace('\"', '');\n tSwitch = tSwitch.replace('\"', '');\n tSwitch = tSwitch.trim();\n var levels = tSwitch.split(',');\n for (var index = 0; index < levels.length; index++) {\n tocSettings.levelSettings[levels[index]] = parseInt(levels[index + 1], 10);\n index++;\n }\n };\n /**\n * Inserts, modifies or updates the table of contents based on given settings.\n * @param {TableOfContentsSettings} tableOfContentsSettings\n */\n Editor.prototype.insertTableOfContents = function (tableOfContentsSettings) {\n this.isInsertingTOC = true;\n this.initComplexHistory('TOC');\n if (isNullOrUndefined(tableOfContentsSettings)) {\n //Initializes with default value.\n tableOfContentsSettings = {};\n tableOfContentsSettings.startLevel = 1;\n tableOfContentsSettings.endLevel = 3;\n tableOfContentsSettings.includeHyperlink = true;\n tableOfContentsSettings.includeOutlineLevels = true;\n tableOfContentsSettings.includePageNumber = true;\n tableOfContentsSettings.rightAlign = true;\n tableOfContentsSettings.tabLeader = 'Dot';\n }\n var tocField = undefined;\n var code = undefined;\n if (this.selection.contextType === 'TableOfContents') {\n tocField = this.selection.getTocFieldInternal();\n }\n if (tocField instanceof FieldElementBox) {\n this.selection.start.setPositionForSelection(tocField.line, tocField, 0, this.selection.start.location);\n this.selection.end.setPositionForSelection(tocField.fieldEnd.line, tocField.fieldEnd, 2, this.selection.end.location);\n this.onDelete();\n }\n // Build TOC field code based on parameter\n code = this.constructTocFieldCode(tableOfContentsSettings);\n var isStartParagraph = this.selection.start.isAtParagraphStart;\n var blockInfo = this.getParagraphInfo(this.selection.start);\n var initialStart = this.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n // Build TOC fields\n // tslint:disable-next-line:max-line-length\n var widgets = this.buildToc(this.validateTocSettings(tableOfContentsSettings), code, true, isStartParagraph);\n if (widgets.length > 0) {\n var tocLastPara = new ParagraphWidget();\n var tocLastLine = new LineWidget(tocLastPara);\n tocLastPara.childWidgets.push(tocLastLine);\n var index = 0;\n if (!isStartParagraph) {\n index = 1;\n }\n var line = widgets[index].childWidgets[0];\n var fieldBegin = line.children[0];\n this.appendEndField(fieldBegin, tocLastLine);\n widgets.push(tocLastPara);\n this.appendEmptyPara(widgets);\n }\n this.setPositionForCurrentIndex(this.selection.start, initialStart);\n this.selection.end.setPositionInternal(this.selection.start);\n this.pasteContentsInternal(widgets);\n this.isInsertingTOC = false;\n this.updatePageRef();\n if (this.editorHistory) {\n this.editorHistory.updateComplexHistoryInternal();\n }\n };\n Editor.prototype.appendEmptyPara = function (widgets) {\n var emptyPara = new ParagraphWidget();\n var emptyLine = new LineWidget(emptyPara);\n emptyPara.childWidgets.push(emptyLine);\n widgets.push(emptyPara);\n };\n Editor.prototype.constructTocFieldCode = function (tocSettings) {\n var tocFieldCode = 'TOC';\n //appends styles level\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(tocSettings.startLevel) && tocSettings.startLevel !== 0 && !isNullOrUndefined(tocSettings.endLevel) && tocSettings.endLevel !== 0) {\n tocFieldCode = tocFieldCode + ' \\\\o \"' + tocSettings.startLevel + '-' + tocSettings.endLevel + '\"';\n }\n if (tocSettings.includePageNumber && !tocSettings.rightAlign) {\n tocFieldCode = tocFieldCode + ' \\\\p \" \"';\n }\n if (!tocSettings.includePageNumber) {\n tocFieldCode = tocFieldCode + ' \\\\n';\n }\n if (tocSettings.includeHyperlink) {\n tocFieldCode = tocFieldCode + ' \\\\h \\\\z';\n }\n if (tocSettings.includeOutlineLevels) {\n tocFieldCode = tocFieldCode + ' \\\\u';\n }\n var tSwitch = this.constructTSwitch(tocSettings);\n if (tSwitch.length > 6) {\n tocFieldCode = tocFieldCode + tSwitch;\n }\n return tocFieldCode;\n };\n Editor.prototype.constructTSwitch = function (tocSettings) {\n var tSwitch = '';\n var prefix = ' \\\\t ';\n if (!isNullOrUndefined(tocSettings.levelSettings)) {\n for (var _i = 0, _a = Object.keys(tocSettings.levelSettings); _i < _a.length; _i++) {\n var key = _a[_i];\n tSwitch = tSwitch + key + ',' + tocSettings.levelSettings[key].toString() + ',';\n }\n }\n tSwitch = tSwitch.slice(0, -1);\n tSwitch = prefix + '\"' + tSwitch + '\"';\n return tSwitch;\n };\n /**\n * Appends the end filed to the given line.\n */\n Editor.prototype.appendEndField = function (fieldBegin, lineWidget) {\n var fieldEnd = new FieldElementBox(1);\n fieldEnd.fieldSeparator = fieldBegin.fieldSeparator;\n fieldBegin.fieldSeparator.fieldEnd = fieldEnd;\n fieldEnd.fieldBegin = fieldBegin;\n fieldEnd.fieldBegin.fieldEnd = fieldEnd;\n fieldEnd.line = lineWidget;\n lineWidget.children.push(fieldEnd);\n };\n Editor.prototype.validateTocSettings = function (tocSettings) {\n if (isNullOrUndefined(tocSettings.startLevel) || tocSettings.startLevel < 1) {\n tocSettings.startLevel = 1;\n }\n if (isNullOrUndefined(tocSettings.endLevel) || tocSettings.endLevel < tocSettings.endLevel) {\n tocSettings.endLevel = tocSettings.startLevel > 3 ? tocSettings.startLevel : 3;\n }\n if (isNullOrUndefined(tocSettings.includeHyperlink)) {\n tocSettings.includeHyperlink = false;\n }\n if (isNullOrUndefined(tocSettings.includePageNumber)) {\n tocSettings.includePageNumber = false;\n }\n if (isNullOrUndefined(tocSettings.rightAlign)) {\n tocSettings.rightAlign = false;\n }\n if (isNullOrUndefined(tocSettings.levelSettings)) {\n tocSettings.levelSettings = {};\n }\n return tocSettings;\n };\n /**\n * Builds the TOC\n * @private\n */\n // tslint:disable-next-line:max-line-length\n Editor.prototype.buildToc = function (tocSettings, fieldCode, isFirstPara, isStartParagraph) {\n var tocDomBody = this.viewer.pages[0].bodyWidgets[0];\n var widgets = [];\n this.createHeadingLevels(tocSettings);\n if (tocSettings.includeOutlineLevels) {\n this.createOutlineLevels(tocSettings);\n }\n var widget = tocDomBody.childWidgets[0];\n while (widget !== undefined) {\n // tslint:disable-next-line:max-line-length\n if (widget instanceof ParagraphWidget && (this.isHeadingStyle(widget) || (tocSettings.includeOutlineLevels && this.isOutlineLevelStyle(widget)))) {\n var bookmarkName = this.insertTocBookmark(widget);\n // tslint:disable-next-line:max-line-length\n this.createTOCWidgets(widget, widgets, fieldCode, bookmarkName, tocSettings, isFirstPara, isStartParagraph);\n isFirstPara = false;\n }\n widget = this.selection.getNextParagraphBlock(widget);\n }\n this.tocStyles = {};\n return widgets;\n };\n Editor.prototype.createOutlineLevels = function (settings) {\n for (var i = settings.startLevel; i <= settings.endLevel; i++) {\n var levelStyle = 'Level' + i.toString();\n if (isNullOrUndefined(this.tocStyles[levelStyle])) {\n this.tocStyles[levelStyle] = i;\n }\n }\n };\n /**\n * Creates TOC heading styles\n * @param start - lower heading level\n * @param end - higher heading level\n */\n Editor.prototype.createHeadingLevels = function (settings) {\n var normalStyle = 'Normal';\n for (var i = settings.startLevel; i <= settings.endLevel; i++) {\n var headingStyle = 'Heading ' + i.toString();\n if (isNullOrUndefined(this.tocStyles[headingStyle])) {\n this.tocStyles[headingStyle] = i;\n }\n }\n if (!isNullOrUndefined(settings.levelSettings)) {\n for (var _i = 0, _a = Object.keys(settings.levelSettings); _i < _a.length; _i++) {\n var key = _a[_i];\n this.tocStyles[key] = settings.levelSettings[key];\n }\n }\n };\n /**\n * Checks the current style is heading style.\n */\n Editor.prototype.isHeadingStyle = function (para) {\n var style = para.paragraphFormat.baseStyle;\n if (style !== undefined) {\n return isNullOrUndefined(this.tocStyles[style.name]) ? false : true;\n }\n return false;\n };\n Editor.prototype.isOutlineLevelStyle = function (para) {\n var styleName = para.paragraphFormat.outlineLevel;\n return isNullOrUndefined(this.tocStyles[styleName]) ? false : true;\n };\n /**\n * Creates TOC field element.\n */\n Editor.prototype.createTocFieldElement = function (lineWidget, fieldCode) {\n //begin\n var fieldBegin = new FieldElementBox(0);\n fieldBegin.hasFieldEnd = true;\n fieldBegin.line = lineWidget;\n lineWidget.children.push(fieldBegin);\n //format toc\n var textElement = new TextElementBox();\n textElement.text = fieldCode;\n textElement.line = lineWidget;\n lineWidget.children.push(textElement);\n //field separator\n var fieldSeparator = new FieldElementBox(2);\n fieldSeparator.fieldBegin = fieldBegin;\n fieldSeparator.fieldBegin.fieldSeparator = fieldSeparator;\n fieldSeparator.line = lineWidget;\n lineWidget.children.push(fieldSeparator);\n return fieldBegin;\n };\n /**\n * Updates TOC para\n */\n // tslint:disable-next-line:max-line-length\n Editor.prototype.createTOCWidgets = function (widget, widgets, fieldCode, bookmarkName, tocSettings, isFirstPara, isStartParagraph) {\n var fieldBegin = undefined;\n var tocPara = undefined;\n var tocLine = undefined;\n // tslint:disable-next-line:max-line-length\n if (widgets.length === 1 && widgets[0].childWidgets[0].children.length === 3 && !isNullOrUndefined(isFirstPara) && !isFirstPara) {\n tocLine = widgets[0].childWidgets[0];\n }\n else {\n tocPara = new ParagraphWidget();\n var styleName = undefined;\n //Adds toc syles into paragraph\n var headingStyleName = widget.paragraphFormat.baseStyle.name;\n if (tocSettings.includeOutlineLevels && isNullOrUndefined(this.tocStyles[headingStyleName])) {\n styleName = widget.paragraphFormat.outlineLevel;\n }\n else {\n styleName = headingStyleName;\n }\n var tocStyleName = 'Toc' + this.tocStyles[styleName];\n var paraStyle = this.viewer.styles.findByName(tocStyleName, 'Paragraph');\n if (isNullOrUndefined(paraStyle)) {\n // tslint:disable-next-line:max-line-length\n this.viewer.owner.parser.parseStyle(JSON.parse(this.getCompleteStyles()), JSON.parse(this.viewer.preDefinedStyles.get(tocStyleName)), this.viewer.styles);\n paraStyle = this.viewer.styles.findByName(tocStyleName, 'Paragraph');\n }\n tocPara.paragraphFormat.ApplyStyle(paraStyle);\n //Creates right tab for page number.\n if (tocSettings.rightAlign && tocSettings.includePageNumber) {\n var tabStop = new WTabStop();\n tabStop.position = HelperMethods.convertPixelToPoint(this.viewer.clientArea.width);\n tabStop.tabLeader = tocSettings.tabLeader;\n tabStop.deletePosition = 0;\n tabStop.tabJustification = 'Right';\n tocPara.paragraphFormat.tabs.push(tabStop);\n }\n tocLine = new LineWidget(tocPara);\n tocPara.childWidgets.push(tocLine);\n }\n //creates toc field element if it is insert\n if ((isFirstPara !== undefined) && isFirstPara) {\n if (!isNullOrUndefined(isStartParagraph) && !isStartParagraph) {\n this.appendEmptyPara(widgets);\n }\n this.createTocFieldElement(tocLine, fieldCode);\n }\n var text = '';\n for (var lineIndex = 0; lineIndex < widget.childWidgets.length; lineIndex++) {\n var lineWidget = widget.childWidgets[lineIndex];\n for (var elementIndex = 0; elementIndex < lineWidget.children.length; elementIndex++) {\n var element = lineWidget.children[elementIndex];\n if (element instanceof TextElementBox || element instanceof ListTextElementBox) {\n var temp = element.text;\n var tabChar = '\\t';\n if (temp.indexOf(tabChar) !== -1) {\n temp = temp.replace(new RegExp(tabChar, 'g'), ' ');\n }\n text = text + temp;\n }\n }\n }\n if (text !== '') {\n // inserts hyperlink\n if (tocSettings.includeHyperlink && (bookmarkName !== undefined)) {\n fieldBegin = this.insertTocHyperlink(tocLine, bookmarkName, text);\n }\n else {\n var span = new TextElementBox();\n span.text = text;\n span.line = tocLine;\n tocLine.children.push(span);\n }\n //inserts page number\n if (tocSettings.includePageNumber && (bookmarkName !== undefined)) {\n if (tocSettings.rightAlign) {\n var tabText = new TabElementBox();\n tabText.text = '\\t';\n tabText.line = tocLine;\n tocLine.children.push(tabText);\n }\n var pageField = this.insertTocPageNumber(bookmarkName, tocLine, tocSettings.rightAlign, widget);\n this.appendEndField(pageField, tocLine);\n }\n if (tocSettings.includeHyperlink && fieldBegin !== undefined) {\n this.appendEndField(fieldBegin, tocLine);\n }\n }\n if (!isNullOrUndefined(tocPara) && (text !== '' || isFirstPara)) {\n widgets.push(tocPara);\n }\n };\n /**\n * Inserts toc hyperlink.\n */\n Editor.prototype.insertTocHyperlink = function (lineWidget, bookmarkName, text) {\n var fieldCode = ' HYPERLINK \\\\l \\\"' + bookmarkName + '\\\" ';\n var fieldBegin = this.createTocFieldElement(lineWidget, fieldCode);\n //text element.\n var span = new TextElementBox();\n span.text = text;\n span.line = lineWidget;\n lineWidget.children.push(span);\n return fieldBegin;\n };\n /**\n * Inserts toc page number.\n */\n // tslint:disable-next-line:max-line-length\n Editor.prototype.insertTocPageNumber = function (bookMarkname, lineWidget, isRightAlign, widget) {\n var fieldCode = ' PAGEREF' + bookMarkname + ' \\\\h ';\n var fieldBegin = this.createTocFieldElement(lineWidget, fieldCode);\n var text = (this.viewer.pages.indexOf(widget.bodyWidget.page) + 1).toString();\n //text element.\n var span = new FieldTextElementBox();\n span.fieldBegin = fieldBegin;\n if (!isRightAlign) {\n text = ' ' + text;\n }\n span.text = text;\n span.line = lineWidget;\n lineWidget.children.push(span);\n this.pageRefFields[bookMarkname] = span;\n return fieldBegin;\n };\n Editor.prototype.updatePageRef = function () {\n for (var _i = 0, _a = Object.keys(this.pageRefFields); _i < _a.length; _i++) {\n var key = _a[_i];\n var bookmark = this.viewer.bookmarks.get(key);\n var pageRef = (bookmark.paragraph.bodyWidget.page.index + 1).toString();\n var span = this.pageRefFields[key];\n if (pageRef !== span.text) {\n span.text = pageRef;\n var paragraph = span.paragraph;\n var lineIndex = paragraph.childWidgets.indexOf(span.line);\n var elementIndex = span.line.children.indexOf(span);\n this.viewer.layout.reLayoutParagraph(paragraph, lineIndex, elementIndex);\n }\n }\n };\n /**\n * Inserts toc bookmark.\n */\n Editor.prototype.insertTocBookmark = function (widget) {\n var bookmarkName = undefined;\n var lineLength = widget.childWidgets.length;\n if (lineLength > 0) {\n var startLine = widget.childWidgets[0];\n var endLine = widget.childWidgets[lineLength - 1];\n if ((startLine !== undefined) && (endLine !== undefined)) {\n var startElement = startLine.children[0];\n //Returns the bookmark if already present for paragraph.\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(startElement) && startElement instanceof BookmarkElementBox && startElement.bookmarkType === 0 && (startElement.name.toLowerCase().match('^_toc'))) {\n return startElement.name;\n }\n var endElement = endLine.children[endLine.children.length - 1];\n if ((startElement !== undefined) && (endElement !== undefined)) {\n this.selection.start.setPositionForSelection(startLine, startElement, 0, this.selection.start.location);\n this.selection.end.setPositionForSelection(endLine, endElement, endElement.length, this.selection.end.location);\n bookmarkName = this.generateBookmarkName();\n this.insertBookmark(bookmarkName);\n }\n }\n }\n return bookmarkName;\n };\n /**\n * Generates bookmark id.\n */\n Editor.prototype.generateBookmarkName = function () {\n this.tocBookmarkId++;\n var count = 10 - this.tocBookmarkId.toString().length;\n var formatString = '';\n while (count - 1 > 0) {\n formatString = '0' + formatString;\n count--;\n }\n var bookmarkName = '_Toc' + formatString + this.tocBookmarkId;\n return bookmarkName;\n };\n /**\n * Change cell content alignment\n * @private\n */\n Editor.prototype.onCellContentAlignment = function (verticalAlignment, textAlignment) {\n this.owner.isShiftingEnabled = true;\n var selection = this.owner.selection;\n if (selection.isEmpty && selection.start.paragraph.isInsideTable) {\n if (this.owner.editorHistory) {\n this.owner.editorHistory.initComplexHistory(selection, 'MultiSelection');\n }\n //Selecting the table cell to update the all the paragraph format.\n selection.selectTableCell();\n this.initHistory('CellContentVerticalAlignment');\n var cellFormat = selection.start.paragraph.associatedCell.cellFormat;\n this.applyCellPropertyValue(selection, 'verticalAlignment', verticalAlignment, cellFormat);\n this.reLayout(selection, false);\n this.initHistory('TextAlignment');\n this.updateParagraphFormat('textAlignment', textAlignment, false);\n this.reLayout(this.owner.selection, false);\n if (this.owner.editorHistory) {\n this.owner.editorHistory.updateComplexHistory();\n }\n }\n else {\n if (this.owner.editorHistory) {\n this.owner.editorHistory.initComplexHistory(selection, 'MultiSelection');\n }\n if (!isNullOrUndefined(selection.getTable(selection.start, selection.end))) {\n //Table cell vertical alignment.\n this.updateSelectionTableFormat(selection, 'CellContentVerticalAlignment', verticalAlignment);\n this.reLayout(this.owner.selection, false);\n this.initHistory('TextAlignment');\n //Paragraph text alignment.\n this.updateSelectionParagraphFormatting('textAlignment', textAlignment, false);\n this.reLayout(selection, false);\n }\n if (this.owner.editorHistory) {\n this.owner.editorHistory.updateComplexHistory();\n }\n }\n };\n return Editor;\n}());\nexport { Editor };\n","import { WTableHolder } from '../viewer/page';\n/**\n * @private\n */\nvar ModifiedLevel = /** @class */ (function () {\n function ModifiedLevel(owner, modified) {\n this.ownerListLevelIn = undefined;\n this.modifiedListLevelIn = undefined;\n this.ownerListLevel = owner;\n this.modifiedListLevel = modified;\n }\n Object.defineProperty(ModifiedLevel.prototype, \"ownerListLevel\", {\n /**\n * @private\n */\n get: function () {\n return this.ownerListLevelIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.ownerListLevelIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ModifiedLevel.prototype, \"modifiedListLevel\", {\n /**\n * @private\n */\n get: function () {\n return this.modifiedListLevelIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.modifiedListLevelIn = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n ModifiedLevel.prototype.destroy = function () {\n this.ownerListLevel = undefined;\n this.modifiedListLevel = undefined;\n };\n return ModifiedLevel;\n}());\nexport { ModifiedLevel };\n/**\n * @private\n */\nvar ModifiedParagraphFormat = /** @class */ (function () {\n function ModifiedParagraphFormat(ownerFormat, modifiedFormat) {\n this.ownerFormatIn = undefined;\n this.modifiedFormatIn = undefined;\n this.ownerFormat = ownerFormat;\n this.modifiedFormat = modifiedFormat;\n }\n Object.defineProperty(ModifiedParagraphFormat.prototype, \"ownerFormat\", {\n /**\n * @private\n */\n get: function () {\n return this.ownerFormatIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.ownerFormatIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ModifiedParagraphFormat.prototype, \"modifiedFormat\", {\n /**\n * hidden\n */\n get: function () {\n return this.modifiedFormatIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.modifiedFormatIn = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n ModifiedParagraphFormat.prototype.destroy = function () {\n this.ownerFormat = undefined;\n this.modifiedFormat.destroy();\n this.modifiedFormat = undefined;\n };\n return ModifiedParagraphFormat;\n}());\nexport { ModifiedParagraphFormat };\n/**\n * @private\n */\nvar RowHistoryFormat = /** @class */ (function () {\n function RowHistoryFormat(startingPoint, rowFormat) {\n this.startingPoint = startingPoint;\n this.rowFormat = rowFormat;\n this.rowHeightType = rowFormat.heightType;\n }\n RowHistoryFormat.prototype.revertChanges = function (isRedo, owner) {\n //backup current format values.\n var currentRowHeightType = this.rowFormat.heightType;\n //Restore old values.\n owner.editorModule.tableResize.updateRowHeight(this.rowFormat.ownerBase, isRedo ? this.displacement : (-this.displacement));\n owner.viewer.layout.reLayoutTable(this.rowFormat.ownerBase.ownerTable);\n if (this.rowFormat.heightType !== this.rowHeightType) {\n this.rowFormat.heightType = this.rowHeightType;\n }\n //backup the current format values for redo.\n this.rowHeightType = currentRowHeightType;\n };\n return RowHistoryFormat;\n}());\nexport { RowHistoryFormat };\n/**\n * @private\n */\nvar TableHistoryInfo = /** @class */ (function () {\n function TableHistoryInfo(table, owner) {\n this.tableHolder = new WTableHolder();\n this.tableFormat = new TableFormatHistoryInfo();\n this.rows = [];\n this.owner = owner;\n this.copyProperties(table);\n }\n TableHistoryInfo.prototype.copyProperties = function (table) {\n if (table.tableHolder) {\n this.tableHolder = table.tableHolder.clone();\n }\n if (table.tableFormat) {\n this.tableFormat.leftIndent = table.tableFormat.leftIndent;\n this.tableFormat.preferredWidth = table.tableFormat.preferredWidth;\n this.tableFormat.preferredWidthType = table.tableFormat.preferredWidthType;\n }\n for (var i = 0; i < table.childWidgets.length; i++) {\n var row = table.childWidgets[i];\n var rowFormat = new RowFormatHistoryInfo();\n rowFormat.gridBefore = row.rowFormat.gridBefore;\n rowFormat.gridBeforeWidth = row.rowFormat.gridBeforeWidth;\n rowFormat.gridBeforeWidthType = row.rowFormat.gridBeforeWidthType;\n rowFormat.gridAfter = row.rowFormat.gridAfter;\n rowFormat.gridAfterWidth = row.rowFormat.gridAfterWidth;\n rowFormat.gridAfterWidthType = row.rowFormat.gridAfterWidthType;\n for (var j = 0; j < row.childWidgets.length; j++) {\n var cell = row.childWidgets[j];\n var cellFormat = new CellFormatHistoryInfo();\n cellFormat.columnIndex = cell.columnIndex;\n cellFormat.columnSpan = cell.cellFormat.columnSpan;\n cellFormat.preferredWidth = cell.cellFormat.preferredWidth;\n cellFormat.preferredWidthType = cell.cellFormat.preferredWidthType;\n rowFormat.cells.push(cellFormat);\n }\n this.rows.push(rowFormat);\n }\n this.tableHierarchicalIndex = this.owner.editorModule.getHierarchicalIndex(table, '0');\n };\n TableHistoryInfo.prototype.destroy = function () {\n this.tableHierarchicalIndex = undefined;\n if (this.tableHolder) {\n this.tableHolder.destroy();\n this.tableHolder = undefined;\n }\n if (this.tableFormat) {\n this.tableFormat = null;\n }\n if (this.rows) {\n this.rows = [];\n this.rows = undefined;\n }\n };\n return TableHistoryInfo;\n}());\nexport { TableHistoryInfo };\n/**\n * @private\n */\nvar TableFormatHistoryInfo = /** @class */ (function () {\n function TableFormatHistoryInfo() {\n /* tslint:disable:no-empty */\n }\n return TableFormatHistoryInfo;\n}());\nexport { TableFormatHistoryInfo };\n/**\n * @private\n */\nvar RowFormatHistoryInfo = /** @class */ (function () {\n function RowFormatHistoryInfo() {\n this.cells = [];\n }\n return RowFormatHistoryInfo;\n}());\nexport { RowFormatHistoryInfo };\n/**\n * @private\n */\nvar CellFormatHistoryInfo = /** @class */ (function () {\n function CellFormatHistoryInfo() {\n /* tslint:disable:no-empty */\n }\n return CellFormatHistoryInfo;\n}());\nexport { CellFormatHistoryInfo };\n/**\n * @private\n */\nvar CellHistoryFormat = /** @class */ (function () {\n function CellHistoryFormat(point) {\n this.startingPoint = point; // starting point preserved to calculate the displacement on after cell resizing finished.\n }\n return CellHistoryFormat;\n}());\nexport { CellHistoryFormat };\n","import { WParagraphFormat } from '../format/paragraph-format';\nimport { WSectionFormat } from '../format/section-format';\nimport { WCharacterFormat } from '../format/character-format';\nimport { WListFormat } from '../format/list-format';\nimport { ModifiedLevel, RowHistoryFormat, TableHistoryInfo } from './history-helper';\nimport { BlockWidget, ParagraphWidget, BodyWidget, TableCellWidget, TableWidget, TableRowWidget, HeaderFooterWidget } from '../viewer/page';\nimport { Dictionary } from '../../base/dictionary';\nimport { TextPosition, ImageFormat } from '../index';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { ElementBox } from '../viewer/page';\nimport { WTableFormat, WRowFormat, WCellFormat, WParagraphStyle } from '../format/index';\n/**\n * @private\n */\nvar BaseHistoryInfo = /** @class */ (function () {\n function BaseHistoryInfo(node) {\n this.ownerIn = node;\n this.viewer = node.viewer;\n this.modifiedPropertiesIn = [];\n this.modifiedNodeLength = [];\n this.removedNodesIn = [];\n }\n Object.defineProperty(BaseHistoryInfo.prototype, \"owner\", {\n //Properties\n //gets owner control\n /**\n * gets the owner control\n * @private\n */\n get: function () { return this.ownerIn; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"editorHistory\", {\n /**\n * gets or sets action\n * @private\n */\n get: function () {\n return this.owner.editorHistory;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"action\", {\n /**\n * gets or sets action\n * @private\n */\n get: function () { return this.actionIn; },\n set: function (value) { this.actionIn = value; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"modifiedProperties\", {\n /**\n * gets modified properties\n * @returns Object\n * @private\n */\n get: function () { return this.modifiedPropertiesIn; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"removedNodes\", {\n /**\n * @private\n */\n get: function () {\n return this.removedNodesIn;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"selectionStart\", {\n /**\n * Gets or Sets the selection start\n * @private\n */\n //gets or sets selection start\n get: function () { return this.selectionStartIn; },\n set: function (value) { this.selectionStartIn = value; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"selectionEnd\", {\n /**\n * Gets or Sets the selection end\n * @private\n */\n get: function () { return this.selectionEndIn; },\n set: function (value) { this.selectionEndIn = value; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"insertPosition\", {\n /**\n * Gets or sets the insert position\n * @private\n */\n get: function () { return this.insertPositionIn; },\n set: function (value) { this.insertPositionIn = value; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BaseHistoryInfo.prototype, \"endPosition\", {\n /**\n * Gets or sets end position\n * @private\n */\n get: function () { return this.endPositionIn; },\n set: function (value) { this.endPositionIn = value; },\n enumerable: true,\n configurable: true\n });\n /**\n * Update the selection\n * @param selection\n * @private\n */\n BaseHistoryInfo.prototype.updateSelection = function () {\n var blockInfo = this.owner.editorModule.getParagraphInfo(this.owner.selection.start);\n this.selectionStart = this.owner.editorModule.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n blockInfo = this.owner.editorModule.getParagraphInfo(this.owner.selection.end);\n this.selectionEnd = this.owner.editorModule.getHierarchicalIndex(blockInfo.paragraph, blockInfo.offset.toString());\n };\n BaseHistoryInfo.prototype.setBookmarkInfo = function (bookmark) {\n this.removedNodes.push({ 'bookmark': bookmark, 'startIndex': bookmark.indexInOwner, 'endIndex': bookmark.reference.indexInOwner });\n };\n BaseHistoryInfo.prototype.revertBookmark = function () {\n var bookmarkInfo = this.removedNodes[0];\n var bookmark = bookmarkInfo.bookmark;\n if (this.editorHistory.isUndoing) {\n this.viewer.bookmarks.add(bookmark.name, bookmark);\n bookmark.line.children.splice(bookmarkInfo.startIndex, 0, bookmark);\n bookmark.reference.line.children.splice(bookmarkInfo.endIndex, 0, bookmark.reference);\n this.editorHistory.recordChanges(this);\n }\n else {\n this.owner.editorModule.deleteBookmarkInternal(bookmark);\n this.editorHistory.undoStack.push(this);\n }\n };\n /**\n * Reverts this instance\n * @private\n */\n // tslint:disable: max-func-body-length\n BaseHistoryInfo.prototype.revert = function () {\n if (this.action === 'DeleteBookmark') {\n this.revertBookmark();\n return;\n }\n this.owner.isShiftingEnabled = true;\n var selectionStartTextPosition = undefined;\n var selectionEndTextPosition = undefined;\n var start = this.selectionStart;\n var end = this.selectionEnd;\n var isForwardSelection = TextPosition.isForwardSelection(start, end);\n if (this.modifiedProperties.length > 0 || this.action === 'Selection' || this.action === 'ClearCharacterFormat'\n || this.action === 'ClearParagraphFormat') {\n selectionStartTextPosition = this.getTextPosition(start);\n selectionEndTextPosition = this.getTextPosition(end);\n this.revertModifiedProperties(selectionStartTextPosition, selectionEndTextPosition);\n }\n else {\n var deletedNodes = this.removedNodes;\n this.removedNodesIn = [];\n var isForward = TextPosition.isForwardSelection(this.insertPosition, this.endPosition);\n var insertTextPosition = this.getTextPosition(isForward ? this.insertPosition : this.endPosition);\n var endTextPosition = this.getTextPosition(isForward ? this.endPosition : this.insertPosition);\n if (insertTextPosition.isAtSamePosition(endTextPosition)) {\n this.owner.selection.selectContent(insertTextPosition, true);\n }\n else {\n this.owner.selection.selectPosition(insertTextPosition, endTextPosition);\n }\n if (this.action === 'InsertHyperlink' && this.editorHistory.isRedoing) {\n var fieldBegin = this.owner.selection.getHyperlinkField();\n if (!isNullOrUndefined(fieldBegin)) {\n var offset = (fieldBegin.line).getOffset(fieldBegin, 0);\n insertTextPosition.setPositionParagraph(fieldBegin.line, offset);\n this.owner.selection.start.setPositionInternal(insertTextPosition);\n offset = fieldBegin.fieldEnd.line.getOffset(fieldBegin.fieldEnd, 1);\n endTextPosition.setPositionParagraph(fieldBegin.fieldEnd.line, offset);\n }\n }\n this.editorHistory.currentBaseHistoryInfo = this;\n this.selectionStart = this.insertPosition;\n this.insertPosition = undefined;\n this.selectionEnd = this.endPosition;\n this.endPosition = undefined;\n var isRemoveContent = false;\n if (!insertTextPosition.isAtSamePosition(endTextPosition)) {\n isRemoveContent = this.action === 'BackSpace' || this.action === 'Delete' || this.action === 'ClearCells'\n || this.action === 'DeleteCells';\n if (!(isRemoveContent) && this.action !== 'MergeCells' && this.action !== 'InsertRowAbove'\n && this.action !== 'InsertRowBelow' && this.action !== 'InsertColumnLeft'\n && this.action !== 'InsertColumnRight' && this.action !== 'Borders'\n && this.action !== 'DeleteTable' && this.action !== 'DeleteColumn' && this.action !== 'DeleteRow') {\n this.owner.selection.end.setPositionInternal(endTextPosition);\n if (!this.owner.selection.isEmpty) {\n if (this.editorHistory.isRedoing) {\n this.owner.editorModule.removeSelectedContents(this.owner.selection);\n }\n else {\n this.owner.editorModule.deleteSelectedContents(this.owner.selection, true);\n }\n }\n }\n }\n var isRedoAction = this.editorHistory.isRedoing && !isRemoveContent;\n this.revertModifiedNodes(deletedNodes, isRedoAction, isForwardSelection ? start : end, start === end);\n if (isRemoveContent) {\n this.removeContent(insertTextPosition, endTextPosition);\n }\n //this.owner.editorModule.reLayout(this.viewer.selection);\n }\n var isSelectionChanged = false;\n if ((this.editorHistory.isUndoing && isNullOrUndefined(this.editorHistory.currentHistoryInfo)) ||\n ((this.action === 'InsertRowAbove' || this.action === 'Borders' || this.action === 'InsertRowBelow'\n || this.action === 'InsertColumnLeft'\n || this.action === 'InsertColumnRight') && (this.editorHistory.isRedoing\n || this.editorHistory.currentHistoryInfo.action === 'Paste'))) {\n selectionStartTextPosition = this.getTextPosition(start);\n selectionEndTextPosition = this.getTextPosition(end);\n this.owner.selection.selectRange(selectionStartTextPosition, selectionEndTextPosition);\n isSelectionChanged = true;\n }\n // Updates insert position of history info instance.\n this.insertPosition = start;\n this.endPosition = end;\n this.owner.editorModule.reLayout(this.owner.selection, this.owner.selection.isEmpty);\n if (isSelectionChanged) {\n this.viewer.scrollToPosition(this.owner.selection.start, this.owner.selection.end);\n }\n this.highlightListText();\n };\n BaseHistoryInfo.prototype.highlightListText = function () {\n if (!isNullOrUndefined(this.editorHistory.currentHistoryInfo)) {\n // tslint:disable-next-line:max-line-length\n if (this.action === 'ListCharacterFormat' || (this.editorHistory.currentHistoryInfo.action === 'ListSelect' && this.action === 'ListFormat')) {\n var selectionStartTextPosition = this.getTextPosition(this.selectionStart);\n var widget = selectionStartTextPosition.currentWidget;\n this.viewer.selection.highlightListText(widget);\n }\n }\n };\n BaseHistoryInfo.prototype.removeContent = function (insertTextPosition, endTextPosition) {\n //If the base parent of the insert text position and end text position is null \n //then the paragraphs already removed.\n //Example scenario: In table editing that is delete cells operation \n // we will backed up the entire table ad it will be replaced on undo operation.\n //At that time if the positions are in table \n //which is already replaced in undo (revert modified nodes method) then the base parent of the paragraph will be null.\n //So again, selecting the content and deleting is unnecessary\n // and it will cause improper position updates and null reference exceptions. \n if ((!isNullOrUndefined(insertTextPosition.paragraph.containerWidget) &&\n insertTextPosition.paragraph.containerWidget instanceof BodyWidget &&\n (!isNullOrUndefined(endTextPosition.paragraph.containerWidget)\n && endTextPosition.paragraph.containerWidget instanceof BodyWidget))\n || (!isNullOrUndefined(insertTextPosition.paragraph.containerWidget)\n && !isNullOrUndefined(endTextPosition.paragraph.containerWidget)\n && insertTextPosition.paragraph.containerWidget instanceof TableCellWidget\n && endTextPosition.paragraph.containerWidget instanceof TableCellWidget\n && !isNullOrUndefined(insertTextPosition.paragraph.bodyWidget))) {\n //Removes if any empty paragraph is added while delete.\n this.owner.selection.selectRange(insertTextPosition, endTextPosition);\n var isDelete = (this.action === 'BackSpace') ? true : false;\n this.owner.editorModule.deleteSelectedContents(this.owner.selection, isDelete);\n }\n };\n BaseHistoryInfo.prototype.revertModifiedProperties = function (start, end) {\n if (this.action === 'CellFormat' || this.action === 'CellOptions' || this.action === 'TableOptions') {\n this.owner.isShiftingEnabled = false;\n }\n this.owner.selection.selectRange(start, end);\n if (this.action === 'RowResizing' || this.action === 'CellResizing') {\n this.revertResizing();\n }\n else if (this.action === 'CellOptions' || this.action === 'TableOptions') {\n this.revertTableDialogProperties(this.action);\n }\n else if (this.action !== 'Selection') {\n this.revertProperties();\n }\n };\n // Redoes the Action\n BaseHistoryInfo.prototype.redoAction = function () {\n var editor = this.owner.editorModule;\n switch (this.action) {\n case 'BackSpace':\n editor.singleBackspace(this.owner.selection, true);\n break;\n case 'Delete':\n editor.singleDelete(this.owner.selection, true);\n break;\n case 'DeleteTable':\n editor.deleteTable();\n break;\n case 'DeleteColumn':\n editor.deleteColumn();\n break;\n case 'DeleteRow':\n editor.deleteRow();\n break;\n case 'MergeCells':\n editor.mergeSelectedCellsInTable();\n break;\n case 'InsertRowAbove':\n editor.insertRow(true);\n break;\n case 'InsertRowBelow':\n editor.insertRow(false);\n break;\n case 'InsertColumnLeft':\n editor.insertColumn(true);\n break;\n case 'InsertColumnRight':\n editor.insertColumn(true);\n break;\n }\n };\n /**\n * Revert the modified nodes\n * @param {WNode[]} deletedNodes\n * @param {boolean} isRedoAction\n * @param {string} start\n * @param {boolean} isEmptySelection\n */\n BaseHistoryInfo.prototype.revertModifiedNodes = function (deletedNodes, isRedoAction, start, isEmptySelection) {\n if (isRedoAction && (this.action === 'BackSpace' || this.action === 'Delete' || this.action === 'DeleteTable'\n || this.action === 'DeleteColumn' || this.action === 'DeleteRow' || this.action === 'InsertRowAbove' ||\n this.action === 'InsertRowBelow' || this.action === 'InsertColumnLeft' || this.action === 'InsertColumnRight'\n || this.action === 'MergeCells')) {\n this.redoAction();\n }\n if (deletedNodes.length > 0) {\n if ((this.editorHistory.isUndoing && (this.action === 'DeleteCells' || this.action === 'DeleteColumn'\n || this.action === 'DeleteRow' || this.action === 'MergeCells'))\n || (this.action === 'InsertRowAbove' || this.action === 'InsertRowBelow' || this.action === 'InsertColumnLeft'\n || this.action === 'ClearCells' || this.action === 'InsertColumnRight' || this.action === 'Borders')) {\n var insertIndex = this.selectionStart;\n var block = this.owner.editorModule.getBlock({ index: insertIndex }).node;\n var lastNode = deletedNodes[deletedNodes.length - 1];\n if ((block instanceof TableWidget || block.previousRenderedWidget instanceof TableWidget || block.isInsideTable)\n && lastNode instanceof TableWidget) {\n if (block instanceof ParagraphWidget && !block.isInsideTable) {\n block = block.previousRenderedWidget;\n }\n block = block.combineWidget(this.viewer);\n this.owner.editorModule.insertTableInternal(block, lastNode, false);\n deletedNodes.splice(deletedNodes.indexOf(lastNode), 1);\n }\n else if (lastNode instanceof TableWidget) {\n this.owner.editorModule.insertBlock(lastNode);\n }\n }\n else {\n var initialStart = start;\n var block = this.owner.editorModule.getBlock({ index: initialStart }).node;\n // initialStart = blockObj.position;\n if (deletedNodes.length > 0 && (this.action === 'BackSpace' && isEmptySelection\n || (!(block instanceof TableWidget) && !(block instanceof HeaderFooterWidget)))) {\n var lastNode = deletedNodes[0];\n if (lastNode instanceof ParagraphWidget && this.owner.selection.start.offset > 0) {\n this.owner.editorModule.insertNewParagraphWidget(lastNode, true);\n deletedNodes.splice(deletedNodes.indexOf(lastNode), 1);\n if (isNullOrUndefined(block)) {\n // tslint:disable-next-line:max-line-length\n var nextBlock = this.viewer.selection.getNextParagraphBlock(lastNode.getSplitWidgets().pop());\n this.owner.selection.getNextRenderedBlock(lastNode);\n if (isNullOrUndefined(nextBlock)) {\n //Sets the selection as starting of last paragraph.\n this.owner.selection.selectParagraph(lastNode, true);\n }\n }\n }\n if (lastNode instanceof TableWidget && this.owner.selection.start.offset > 0) {\n var firstBlock = deletedNodes[deletedNodes.length - 1];\n if (firstBlock instanceof ParagraphWidget) {\n this.owner.editorModule.insertNewParagraphWidget(firstBlock, true);\n deletedNodes.splice(deletedNodes.indexOf(firstBlock), 1);\n if (isNullOrUndefined(block)) {\n // tslint:disable-next-line:max-line-length\n var nextBlock = this.viewer.selection.getNextParagraphBlock(firstBlock.getSplitWidgets().pop());\n if (isNullOrUndefined(nextBlock)) {\n //Sets the selection as starting of last paragraph.\n this.owner.selection.selectParagraph(firstBlock, true);\n }\n }\n }\n }\n }\n if (deletedNodes.length > 0) {\n var firstNode = deletedNodes[deletedNodes.length - 1];\n if (block instanceof TableWidget) {\n block = block.combineWidget(this.viewer);\n if (firstNode instanceof TableWidget) {\n this.owner.editorModule.insertTableInternal(block, firstNode, true);\n deletedNodes.splice(deletedNodes.indexOf(firstNode), 1);\n this.insertPosition = start;\n var nextWidget = firstNode.getSplitWidgets().pop();\n if (nextWidget.nextRenderedWidget instanceof TableWidget) {\n block = nextWidget.nextRenderedWidget;\n }\n else {\n initialStart = start;\n block = this.owner.editorModule.getBlock({ index: initialStart }).node;\n }\n }\n }\n //Checks if first node is paragraph and current insert position is paragraph end.\n // tslint:disable-next-line:max-line-length\n if (firstNode instanceof ParagraphWidget && this.owner.selection.start.offset > 0\n && this.owner.selection.start.offset === this.owner.selection.getLineLength(this.owner.selection.start.paragraph.lastChild)) {\n var editor = this.owner.editorModule;\n editor.insertNewParagraphWidget(firstNode, false);\n deletedNodes.splice(deletedNodes.indexOf(firstNode), 1);\n //Removes the intermediate empty paragraph instance.\n if (this.action !== 'Paste') {\n editor.removeBlock(this.owner.selection.start.paragraph);\n }\n // tslint:disable-next-line:max-line-length\n var paragraph = this.viewer.selection.getNextParagraphBlock(firstNode.getSplitWidgets().pop());\n if (!isNullOrUndefined(paragraph)) {\n this.owner.selection.selectParagraph(paragraph, true);\n }\n }\n else if (deletedNodes[0] instanceof TableWidget && deletedNodes.length !== 1) {\n var nextNode = deletedNodes[1];\n if (nextNode instanceof ParagraphWidget && nextNode.isEmpty()) {\n deletedNodes.splice(deletedNodes.indexOf(nextNode), 1);\n }\n }\n }\n if (deletedNodes.length > 0) {\n if (block instanceof TableWidget) {\n block = block.combineWidget(this.viewer);\n }\n this.insertRemovedNodes(deletedNodes, block);\n }\n }\n }\n };\n BaseHistoryInfo.prototype.insertRemovedNodes = function (deletedNodes, block) {\n for (var i = deletedNodes.length - 1, index = 0; i > -1; i--) {\n var node = deletedNodes[i];\n if (node instanceof ElementBox) {\n this.owner.editorModule.insertInlineInSelection(this.owner.selection, node);\n }\n else if (node instanceof BlockWidget) {\n if (node instanceof TableRowWidget) {\n if (block instanceof TableWidget) {\n block.childWidgets.splice(index, 0, node);\n this.owner.editorModule.updateNextBlocksIndex(node, true);\n if (i === 0 || !(deletedNodes[i - 1] instanceof TableRowWidget)) {\n // tslint:disable-next-line:max-line-length\n this.viewer.layout.layoutBodyWidgetCollection(block.index, block.containerWidget, block, false);\n }\n }\n }\n else if (block instanceof TableWidget) {\n this.owner.editorModule.insertBlockTable(this.owner.selection, node, block);\n }\n else {\n this.owner.editorModule.insertBlock(node);\n }\n }\n }\n deletedNodes = [];\n };\n BaseHistoryInfo.prototype.revertResizing = function () {\n this.editorHistory.currentBaseHistoryInfo = this;\n if (this.action === 'RowResizing') {\n if (this.modifiedProperties[0] instanceof RowHistoryFormat) {\n // tslint:disable-next-line:max-line-length\n this.modifiedProperties[0].revertChanges(this.editorHistory.isRedoing, this.owner);\n }\n }\n else {\n if (this.modifiedProperties[0] instanceof TableHistoryInfo) {\n //selected cell resizing the condition checks done based on the selected widgets only. so need to highlight the selection.\n if (this.owner.selection.selectedWidgets.length === 0) {\n this.owner.selection.highlightSelection(true);\n }\n var prevTableHistoryInfo = this.modifiedProperties[0];\n var position = prevTableHistoryInfo.tableHierarchicalIndex;\n var block = this.owner.editorModule.getBlock({ index: position }).node;\n if (block instanceof TableWidget) {\n var tableResize = this.owner.editorModule.tableResize;\n this.owner.editor.setOffsetValue(this.owner.selection);\n block = block.combineWidget(this.owner.viewer);\n tableResize.currentResizingTable = block;\n this.modifiedProperties.splice(0, 1);\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n var tableHistoryInfoCurrent = new TableHistoryInfo(block, this.owner);\n this.modifiedProperties.splice(0, 0, tableHistoryInfoCurrent);\n this.owner.isLayoutEnabled = false;\n tableResize.applyProperties(tableResize.currentResizingTable, prevTableHistoryInfo);\n tableResize.currentResizingTable.isGridUpdated = true;\n this.owner.isLayoutEnabled = true;\n tableResize.updateGridValue(tableResize.currentResizingTable, false);\n prevTableHistoryInfo.destroy();\n prevTableHistoryInfo = undefined;\n }\n }\n }\n }\n };\n BaseHistoryInfo.prototype.revertTableDialogProperties = function (action) {\n this.owner.isShiftingEnabled = false;\n this.editorHistory.currentBaseHistoryInfo = this;\n this.currentPropertyIndex = 0;\n if (action === 'CellOptions') {\n var selection = this.owner.selection;\n var cellFormat = this.modifiedProperties[0];\n this.owner.editorModule.updateCellMargins(selection, cellFormat);\n }\n else if (action === 'TableOptions') {\n this.owner.tableOptionsDialogModule.applyTableOptionsHelper(this.modifiedProperties[0]);\n }\n this.currentPropertyIndex = 0;\n this.owner.isShiftingEnabled = true;\n };\n BaseHistoryInfo.prototype.getTextPosition = function (hierarchicalIndex) {\n var textPosition = new TextPosition(this.owner);\n var blockInfo = this.owner.editorModule.getParagraph({ index: hierarchicalIndex });\n var lineInfo = this.owner.editorModule.getLineInfo(blockInfo.paragraph, blockInfo.offset);\n textPosition.setPositionForLineWidget(lineInfo.line, lineInfo.offset);\n return textPosition;\n };\n /**\n * Add modified properties for section format\n * @param {WSectionFormat} format\n * @param {string} property\n * @param {Object} value\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedPropertiesForSection = function (format, property, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n var modifiedProperties = this.modifiedProperties;\n var previousFormat = (this.currentPropertyIndex < modifiedProperties.length ?\n modifiedProperties[this.currentPropertyIndex] : modifiedProperties[modifiedProperties.length - 1]);\n if (isNullOrUndefined(property)) {\n value = previousFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = format.cloneFormat();\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = format.cloneFormat();\n }\n }\n else {\n value = previousFormat.getPropertyValue(property);\n previousFormat.copyFormat(format);\n }\n this.currentPropertyIndex++;\n }\n else {\n if (isNullOrUndefined(property)) {\n this.modifiedProperties.push(format.cloneFormat());\n }\n else {\n var currentFormat = new WSectionFormat();\n currentFormat.copyFormat(format);\n this.modifiedProperties.push(currentFormat);\n }\n }\n return value;\n };\n /**\n * Add the modified properties for character format\n * @param {WCharacterFormat} format\n * @param {string} property\n * @param {Object} value\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedProperties = function (format, property, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length \n var previousFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n var skipRemove = false;\n if (format.ownerBase instanceof ElementBox) {\n var prevLength = this.modifiedNodeLength[this.currentPropertyIndex];\n if (format.ownerBase.length < prevLength) {\n skipRemove = true;\n this.modifiedNodeLength[this.currentPropertyIndex] = format.ownerBase.length;\n this.modifiedNodeLength.splice(this.currentPropertyIndex + 1, 0, prevLength - format.ownerBase.length);\n //Adds a copy of character format at next position for splitted inline.\n var nextFormat = new WCharacterFormat(undefined);\n nextFormat.copyFormat(previousFormat);\n this.modifiedProperties.splice(this.currentPropertyIndex + 1, 0, nextFormat);\n }\n }\n if (this.action === 'ClearCharacterFormat') {\n if (this.editorHistory.isUndoing) {\n value = previousFormat;\n if (!skipRemove) {\n this.modifiedProperties.splice(this.currentPropertyIndex, 1);\n this.currentPropertyIndex--;\n }\n }\n else {\n this.modifiedProperties.push(format.cloneFormat());\n }\n }\n else {\n value = previousFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = format.cloneFormat();\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = format.cloneFormat();\n }\n }\n this.currentPropertyIndex++;\n }\n else {\n if (isNullOrUndefined(property)) {\n this.modifiedProperties.push(format.cloneFormat());\n }\n else {\n var currentFormat = new WCharacterFormat(undefined);\n currentFormat.copyFormat(format);\n this.modifiedProperties.push(currentFormat);\n }\n if (format.ownerBase instanceof ElementBox) {\n this.modifiedNodeLength.push(format.ownerBase.length);\n }\n else {\n this.modifiedNodeLength.push(0);\n }\n }\n return value;\n };\n /**\n * Add the modified properties for paragraph format\n * @param {WParagraphFormat} format\n * @param {string} property\n * @param {Object} value\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedPropertiesForParagraphFormat = function (format, property, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var previousFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n if (this.action === 'ClearParagraphFormat') {\n if (this.editorHistory.isUndoing) {\n value = previousFormat;\n this.modifiedProperties.splice(this.currentPropertyIndex, 1);\n this.currentPropertyIndex--;\n }\n else {\n this.modifiedProperties.push(format.cloneFormat());\n }\n this.currentPropertyIndex++;\n return value;\n }\n if (isNullOrUndefined(property)) {\n value = previousFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = format.cloneFormat();\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = format.cloneFormat();\n }\n this.currentPropertyIndex++;\n return value;\n }\n if (property === 'listFormat') {\n value = new WParagraphFormat(undefined);\n value.copyFormat(previousFormat);\n previousFormat.listFormat = new WListFormat();\n previousFormat.listFormat.copyFormat(format.listFormat);\n this.currentPropertyIndex++;\n return value;\n }\n if (property === 'styleName') {\n if (!isNullOrUndefined(previousFormat.baseStyle)) {\n value = new WParagraphStyle();\n value.copyStyle(previousFormat.baseStyle);\n this.currentPropertyIndex++;\n return value;\n }\n else {\n return undefined;\n }\n }\n value = previousFormat.getPropertyValue(property);\n previousFormat.copyFormat(format);\n this.currentPropertyIndex++;\n }\n else {\n if (isNullOrUndefined(property)) {\n this.modifiedProperties.push(format.cloneFormat());\n }\n else {\n var currentFormat = new WParagraphFormat(undefined);\n currentFormat.copyFormat(format);\n this.modifiedProperties.push(currentFormat);\n }\n }\n return value;\n };\n /**\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedPropertiesForContinueNumbering = function (paragraphFormat, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var previousFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n value = previousFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = paragraphFormat.cloneFormat();\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = paragraphFormat.cloneFormat();\n }\n this.currentPropertyIndex++;\n return value;\n }\n else {\n var currentFormat = new WParagraphFormat();\n currentFormat.copyFormat(paragraphFormat);\n this.modifiedProperties.push(currentFormat);\n }\n return value;\n };\n /**\n * @param listFormat\n * @param value\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedPropertiesForRestartNumbering = function (listFormat, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var listId = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n value = listId;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = listFormat.listId;\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = listFormat.listId;\n }\n this.currentPropertyIndex++;\n return value;\n }\n else {\n this.modifiedProperties.push(listFormat.listId);\n }\n return value;\n };\n /**\n * Add modified properties for list format\n * @param {WListLevel} listLevel\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedPropertiesForList = function (listLevel) {\n var value;\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var previousLevel = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n value = previousLevel;\n previousLevel = new ModifiedLevel(listLevel, this.owner.editorModule.cloneListLevel(listLevel));\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = previousLevel;\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = previousLevel;\n }\n this.currentPropertyIndex++;\n }\n else {\n this.modifiedProperties.push(new ModifiedLevel(listLevel, this.owner.editorModule.cloneListLevel(listLevel)));\n value = listLevel;\n }\n return value;\n };\n /**\n * Revert the properties\n * @param {SelectionRange} selectionRange\n */\n BaseHistoryInfo.prototype.revertProperties = function () {\n this.editorHistory.currentBaseHistoryInfo = this;\n this.currentPropertyIndex = 0;\n var property = this.getProperty();\n this.viewer.owner.editorModule.setOffsetValue(this.viewer.selection);\n if (this.action === 'ClearCharacterFormat' || this.modifiedProperties[0] instanceof WCharacterFormat) {\n if (this.action === 'ListCharacterFormat') {\n this.owner.editorModule.updateListCharacterFormat(this.viewer.selection, property, undefined);\n return;\n }\n this.owner.editorModule.updateSelectionCharacterFormatting(property, undefined, false);\n }\n else if (this.action === 'ClearParagraphFormat' || this.modifiedProperties[0] instanceof WParagraphFormat) {\n if (this.action === 'ContinueNumbering') {\n // tslint:disable-next-line:max-line-length\n this.owner.editorModule.revertContinueNumbering(this.owner.selection, this.modifiedProperties[0]);\n return;\n }\n if (this.action === 'StyleName' && this.modifiedProperties[0] instanceof WParagraphFormat) {\n // tslint:disable-next-line:max-line-length\n this.owner.editorModule.updateSelectionParagraphFormatting(property, this.modifiedProperties[0].baseStyle, false);\n return;\n }\n this.owner.editorModule.updateSelectionParagraphFormatting(property, undefined, false);\n }\n else if (this.modifiedProperties[0] instanceof WSectionFormat) {\n this.owner.editorModule.updateSectionFormat(property, undefined);\n }\n else if (this.action === 'RestartNumbering') {\n this.owner.editorModule.restartListAtInternal(this.owner.selection, this.modifiedProperties[0]);\n return;\n }\n else if (this.modifiedProperties[0] instanceof ImageFormat) {\n this.owner.selection.updateImageSize(this.modifiedProperties[0]);\n }\n else if (this.modifiedProperties[0] instanceof ModifiedLevel) {\n var modified = new Dictionary();\n for (var i = 0; i < this.modifiedProperties.length; i++) {\n var modifiedLevel = this.modifiedProperties[i];\n // modified.modifiedLevels.add(modifiedLevel.ownerListLevel.levelNumber, modifiedLevel);\n modified.add(i, modifiedLevel);\n }\n this.editorHistory.updateListChanges(modified);\n modified.destroy();\n modified = undefined;\n }\n else if (this.modifiedProperties[0] instanceof WTableFormat) {\n this.owner.editorModule.updateTableFormat(this.owner.selection, property, undefined);\n }\n else if (this.modifiedProperties[0] instanceof WCellFormat) {\n this.owner.isShiftingEnabled = true;\n this.owner.editorModule.updateCellFormat(this.owner.selection, property, undefined);\n }\n else if (this.modifiedProperties[0] instanceof WRowFormat) {\n this.owner.editorModule.updateRowFormat(this.owner.selection, property, undefined);\n }\n this.currentPropertyIndex = 0;\n if (this.action === 'ClearCharacterFormat' || this.action === 'ClearParagraphFormat') {\n this.owner.editorModule.getOffsetValue(this.viewer.selection);\n }\n };\n /**\n * Add modified properties for cell options dialog\n * @param {WCellFormat} format\n * @param {WTable} table\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedCellOptions = function (applyFormat, format, table) {\n var currentFormat;\n if (isNullOrUndefined(applyFormat.bottomMargin) && isNullOrUndefined(applyFormat.topMargin)\n && isNullOrUndefined(applyFormat.rightMargin) && isNullOrUndefined(applyFormat.leftMargin)) {\n currentFormat = this.copyCellOptions(table.tableFormat);\n }\n else {\n currentFormat = this.copyCellOptions(applyFormat);\n }\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var previousFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n format = previousFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = this.copyCellOptions(applyFormat);\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = this.copyCellOptions(applyFormat);\n }\n this.currentPropertyIndex++;\n return format;\n }\n else {\n this.modifiedProperties.push(currentFormat);\n }\n return format;\n };\n BaseHistoryInfo.prototype.copyCellOptions = function (format) {\n var cellFormat = new WCellFormat();\n cellFormat.topMargin = format.topMargin;\n cellFormat.rightMargin = format.rightMargin;\n cellFormat.bottomMargin = format.bottomMargin;\n cellFormat.leftMargin = format.leftMargin;\n return cellFormat;\n };\n /**\n * Add modified properties for cell options dialog\n * @param {WTableFormat} format\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedTableOptions = function (format) {\n var currentFormat = this.copyTableOptions(format);\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length \n var previousFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties.splice(this.currentPropertyIndex, 1, currentFormat);\n }\n else {\n this.modifiedProperties.splice(this.modifiedProperties.length - 1, 1, currentFormat);\n }\n this.currentPropertyIndex++;\n }\n else {\n this.modifiedProperties.push(currentFormat);\n }\n };\n BaseHistoryInfo.prototype.copyTableOptions = function (format) {\n var tableFormat = new WTableFormat();\n tableFormat.topMargin = format.topMargin;\n tableFormat.rightMargin = format.rightMargin;\n tableFormat.bottomMargin = format.bottomMargin;\n tableFormat.leftMargin = format.leftMargin;\n tableFormat.cellSpacing = format.cellSpacing;\n return tableFormat;\n };\n BaseHistoryInfo.prototype.getProperty = function () {\n switch (this.action) {\n case 'Bold':\n return 'bold';\n case 'Italic':\n return 'italic';\n case 'FontColor':\n return 'fontColor';\n case 'FontFamily':\n return 'fontFamily';\n case 'FontSize':\n return 'fontSize';\n case 'HighlightColor':\n return 'highlightColor';\n case 'BaselineAlignment':\n return 'baselineAlignment';\n case 'Strikethrough':\n return 'strikethrough';\n case 'Underline':\n return 'underline';\n case 'AfterSpacing':\n return 'afterSpacing';\n case 'BeforeSpacing':\n return 'beforeSpacing';\n case 'LeftIndent':\n return 'leftIndent';\n case 'RightIndent':\n return 'rightIndent';\n case 'FirstLineIndent':\n return 'firstLineIndent';\n case 'LineSpacingType':\n return 'lineSpacingType';\n case 'LineSpacing':\n return 'lineSpacing';\n case 'TextAlignment':\n return 'textAlignment';\n case 'ListFormat':\n return 'listFormat';\n case 'PageHeight':\n return 'pageHeight';\n case 'PageWidth':\n return 'pageWidth';\n case 'TableAlignment':\n return 'tableAlignment';\n case 'TableLeftIndent':\n return 'leftIndent';\n case 'DefaultCellSpacing':\n return 'cellSpacing';\n case 'LeftMargin':\n case 'CellLeftMargin':\n case 'DefaultCellLeftMargin':\n return 'leftMargin';\n case 'RightMargin':\n case 'CellRightMargin':\n case 'DefaultCellRightMargin':\n return 'rightMargin';\n case 'TopMargin':\n case 'CellTopMargin':\n case 'DefaultCellTopMargin':\n return 'topMargin';\n case 'BottomMargin':\n case 'CellBottomMargin':\n case 'DefaultCellBottomMargin':\n return 'bottomMargin';\n case 'CellContentVerticalAlignment':\n return 'verticalAlignment';\n case 'RowHeight':\n return 'height';\n case 'RowHeightType':\n return 'heightType';\n case 'RowHeader':\n return 'isHeader';\n case 'AllowBreakAcrossPages':\n return 'allowBreakAcrossPages';\n case 'TablePreferredWidth':\n case 'CellPreferredWidth':\n return 'preferredWidth';\n case 'TablePreferredWidthType':\n case 'CellPreferredWidthType':\n return 'preferredWidthType';\n case 'Shading':\n return 'shading';\n case 'StyleName':\n return 'styleName';\n }\n return undefined;\n };\n BaseHistoryInfo.prototype.getCharacterPropertyValue = function (property, modifiedProperty) {\n var value;\n if (property === 'bold') {\n value = modifiedProperty.bold;\n }\n else if (property === 'italic') {\n value = modifiedProperty.italic;\n }\n else if (property === 'fontColor') {\n value = modifiedProperty.fontColor;\n }\n else if (property === 'fontFamily') {\n value = modifiedProperty.fontFamily;\n }\n else if (property === 'fontSize') {\n value = modifiedProperty.fontSize;\n }\n else if (property === 'highlightColor') {\n value = modifiedProperty.highlightColor;\n }\n else if (property === 'baselineAlignment') {\n value = modifiedProperty.baselineAlignment;\n }\n else if (property === 'strikethrough') {\n value = modifiedProperty.strikethrough;\n }\n else if (property === 'underline') {\n value = modifiedProperty.underline;\n }\n return value;\n };\n /**\n * Add modified properties for table format\n * @param {WTableFormat} format\n * @param {string} property\n * @param {Object} value\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedTableProperties = function (format, property, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var previousTableFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n if (isNullOrUndefined(property)) {\n value = previousTableFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = format.cloneFormat();\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = format.cloneFormat();\n }\n this.currentPropertyIndex++;\n return value;\n }\n if (property === 'shading') {\n value = previousTableFormat.shading;\n }\n else {\n value = previousTableFormat.getPropertyValue(property);\n }\n previousTableFormat.copyFormat(format);\n this.currentPropertyIndex++;\n }\n else {\n var currentFormat = new WTableFormat();\n currentFormat.copyFormat(format);\n this.modifiedProperties.push(currentFormat);\n }\n return value;\n };\n /**\n * Add modified properties for row format\n * @param {WRowFormat} rowFormat\n * @param {string} property\n * @param {Object} value\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedRowProperties = function (rowFormat, property, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var previousFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n if (isNullOrUndefined(property)) {\n value = previousFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = rowFormat.cloneFormat();\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = rowFormat.cloneFormat();\n }\n this.currentPropertyIndex++;\n return value;\n }\n value = previousFormat.getPropertyValue(property);\n previousFormat.copyFormat(rowFormat);\n this.currentPropertyIndex++;\n }\n else {\n var currentFormat = new WRowFormat();\n currentFormat.copyFormat(rowFormat);\n this.modifiedProperties.push(currentFormat);\n }\n return value;\n };\n /**\n * Add modified properties for cell format\n * @param {WCellFormat} cellFormat\n * @param {string} property\n * @param {Object} value\n * @private\n */\n BaseHistoryInfo.prototype.addModifiedCellProperties = function (cellFormat, property, value) {\n if (this.editorHistory.isUndoing || this.editorHistory.isRedoing) {\n // tslint:disable-next-line:max-line-length\n var previousFormat = (this.currentPropertyIndex < this.modifiedProperties.length ? this.modifiedProperties[this.currentPropertyIndex] : this.modifiedProperties[this.modifiedProperties.length - 1]);\n if (isNullOrUndefined(property)) {\n value = previousFormat;\n if (this.currentPropertyIndex < this.modifiedProperties.length) {\n this.modifiedProperties[this.currentPropertyIndex] = cellFormat.cloneFormat();\n }\n else {\n this.modifiedProperties[this.modifiedProperties.length - 1] = cellFormat.cloneFormat();\n }\n this.currentPropertyIndex++;\n return value;\n }\n if (property === 'shading') {\n value = previousFormat.shading;\n }\n else {\n value = previousFormat.getPropertyValue(property);\n }\n previousFormat.copyFormat(cellFormat);\n this.currentPropertyIndex++;\n }\n else {\n var currentFormat = new WCellFormat();\n currentFormat.copyFormat(cellFormat);\n this.modifiedProperties.push(currentFormat);\n }\n return value;\n };\n /**\n * @private\n */\n BaseHistoryInfo.prototype.destroy = function () {\n this.selectionStart = undefined;\n this.selectionEnd = undefined;\n this.insertPosition = undefined;\n this.endPosition = undefined;\n if (!isNullOrUndefined(this.modifiedNodeLength)) {\n this.modifiedNodeLength = [];\n this.modifiedNodeLength = undefined;\n }\n if (!isNullOrUndefined(this.modifiedProperties)) {\n for (var i = 0; i < this.modifiedProperties.length; i++) {\n var property = this.modifiedProperties[i];\n if (property instanceof WCharacterFormat) {\n property.destroy();\n }\n else if (property instanceof WParagraphFormat) {\n property.destroy();\n }\n else if (property instanceof WSectionFormat) {\n property.destroy();\n }\n else if (property instanceof ModifiedLevel) {\n property.destroy();\n }\n this.modifiedProperties.splice(this.modifiedProperties.indexOf(property), 1);\n i--;\n }\n this.modifiedPropertiesIn = undefined;\n }\n if (!isNullOrUndefined(this.removedNodes)) {\n for (var i = 0; i < this.removedNodes.length; i++) {\n var node = this.removedNodes[i];\n if (node instanceof ParagraphWidget) {\n node.destroyInternal(this.viewer);\n }\n else if (node instanceof ElementBox) {\n node.destroy();\n }\n this.removedNodes.splice(this.removedNodes.indexOf(node), 1);\n i--;\n }\n this.removedNodesIn = undefined;\n }\n this.ownerIn = undefined;\n };\n return BaseHistoryInfo;\n}());\nexport { BaseHistoryInfo };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { PageLayoutViewer } from '../index';\nimport { Dictionary } from '../../base/dictionary';\nimport { ImageFormat } from '../selection/selection-helper';\nimport { Point, HelperMethods } from './editor-helper';\nimport { BaseHistoryInfo } from '../editor-history/base-history-info';\n/**\n * Image resizer implementation.\n */\nvar ImageResizer = /** @class */ (function () {\n /**\n * Constructor for image resizer module.\n * @param {DocumentEditor} node\n * @param {LayoutViewer} viewer\n * @private\n */\n function ImageResizer(node, viewer) {\n /**\n * @private\n */\n this.resizeContainerDiv = undefined;\n /**\n * @private\n */\n this.topLeftRect = undefined;\n /**\n * @private\n */\n this.topMiddleRect = undefined;\n /**\n * @private\n */\n this.topRightRect = undefined;\n /**\n * @private\n */\n this.bottomLeftRect = undefined;\n /**\n * @private\n */\n this.bottomMiddleRect = undefined;\n /**\n * @private\n */\n this.bottomRightRect = undefined;\n /**\n * @private\n */\n this.leftMiddleRect = undefined;\n /**\n * @private\n */\n this.rightMiddleRect = undefined;\n /**\n * @private\n */\n this.topLeftRectParent = undefined;\n /**\n * @private\n */\n this.topMiddleRectParent = undefined;\n /**\n * @private\n */\n this.topRightRectParent = undefined;\n /**\n * @private\n */\n this.bottomLeftRectParent = undefined;\n /**\n * @private\n */\n this.bottomMiddleRectParent = undefined;\n /**\n * @private\n */\n this.bottomRightRectParent = undefined;\n /**\n * @private\n */\n this.leftMiddleRectParent = undefined;\n /**\n * @private\n */\n this.rightMiddleRectParent = undefined;\n /**\n * @private\n */\n this.resizeMarkSizeIn = 7;\n /**\n * @private\n */\n this.selectedImageWidget = undefined;\n /**\n * @private\n */\n this.baseHistoryInfo = undefined;\n /**\n * @private\n */\n this.isImageResizing = false;\n /**\n * @private\n */\n this.isImageResizerVisible = false;\n /**\n * @private\n */\n this.isImageMoveToNextPage = false;\n /**\n * @private\n */\n this.selectedResizeElement = undefined;\n /**\n * @private\n */\n this.topValue = undefined;\n /**\n * @private\n */\n this.leftValue = undefined;\n this.owner = node;\n this.selectedImageWidget = new Dictionary();\n this.viewer = viewer;\n this.imageResizerPoints = new ImageResizingPoints();\n if (isNullOrUndefined(this.imageResizerDiv) && this.viewer && this.viewer.pageContainer) {\n this.initializeImageResizer();\n }\n }\n Object.defineProperty(ImageResizer.prototype, \"currentImageElementBox\", {\n /**\n * Gets or Sets the current image element box.\n * @private\n */\n get: function () {\n return this.currentImageElementBoxIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.currentImageElementBoxIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ImageResizer.prototype, \"resizeMarkSize\", {\n /**\n * Gets or Sets the resize mark size.\n * @private\n */\n get: function () {\n return this.resizeMarkSizeIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.resizeMarkSizeIn = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Gets module name.\n */\n ImageResizer.prototype.getModuleName = function () {\n return 'ImageResizer';\n };\n //Image Resizing Methods\n /**\n * Sets image resizer position.\n * @param {number} x - Specifies for image resizer left value.\n * @param {number} y - Specifies for image resizer top value.\n * @param {number} width - Specifies for image resizer width value.\n * @param {number} height - Specifies for image resizer height value.\n * @private\n */\n ImageResizer.prototype.setImageResizerPositions = function (x, y, width, height) {\n this.imageResizerDivElement.style.top = y.toString() + 'px';\n this.imageResizerDivElement.style.left = x.toString() + 'px';\n this.imageResizerDivElement.style.borderWidth = '0px';\n this.imageResizerDivElement.style.height = height + 'px';\n this.imageResizerDivElement.style.width = width + 'px';\n this.imageResizerDivElement.style.backgroundColor = 'transparent';\n this.imageResizerDivElement.style.overflow = 'hidden';\n this.imageResizerDivElement.style.position = 'absolute';\n };\n /**\n * Creates image resizer DOM element.\n * @private\n */\n ImageResizer.prototype.initializeImageResizer = function () {\n this.imageResizerDivElement = document.createElement('div');\n this.imageResizerDivElement.style.zIndex = '1';\n this.imageResizerDivElement.style.display = 'none';\n this.viewer.pageContainer.appendChild(this.imageResizerDivElement);\n };\n /**\n * Position an image resizer\n * @param {ImageElementBox} elementBox - Specifies the image position.\n * @private\n */\n ImageResizer.prototype.positionImageResizer = function (elementBox) {\n this.selectedImageWidget.clear();\n // Initializes the image resizer on demand, i.e at the time of selecting an image for the first time.\n var resizeDiv;\n if (!isNullOrUndefined(this.viewer.currentPage)) {\n resizeDiv = this.imageResizerDivElement;\n }\n if (!isNullOrUndefined(resizeDiv) && !resizeDiv.contains(this.imageResizerDiv)) {\n this.imageResizerDiv = this.initResizeMarks(resizeDiv, this);\n }\n this.imageResizerDiv.style.width = (elementBox.width) + 'px';\n this.imageResizerDiv.style.height = (elementBox.height) + 'px';\n this.currentImageElementBox = elementBox;\n var lineWidget = elementBox.line;\n var top = this.viewer.selection.getTop(lineWidget) + elementBox.margin.top;\n var left = this.viewer.selection.getLeftInternal(lineWidget, elementBox, 0);\n var page = this.viewer.selection.getPage(lineWidget.paragraph);\n this.currentPage = page;\n var x = 0;\n var y = 0;\n if (!isNullOrUndefined(resizeDiv)) {\n this.imageResizerDivElement.style.display = 'block';\n resizeDiv.style.width = page.boundingRectangle.width + 'px';\n resizeDiv.style.height = page.boundingRectangle.height + 'px';\n resizeDiv.style.left = page.boundingRectangle.x + 'px';\n resizeDiv.style.top = page.boundingRectangle.y + 'px';\n resizeDiv.style.borderWidth = '0px';\n resizeDiv.style.backgroundColor = 'transparent';\n resizeDiv.style.overflow = 'hidden';\n resizeDiv.style.position = 'absolute';\n }\n var horizontalWidth = 0;\n var pageWidth = this.viewer.getPageWidth(page);\n var pagelayout = this.viewer;\n // tslint:disable-next-line:max-line-length\n horizontalWidth = parseFloat(this.imageResizerDivElement.style.width);\n x = (this.viewer.visibleBounds.width - horizontalWidth * this.viewer.zoomFactor) / 2;\n if (x < 30) {\n x = 30;\n }\n if (pageWidth < horizontalWidth) {\n x += (horizontalWidth - pageWidth) * this.viewer.zoomFactor / 2;\n }\n // tslint:disable-next-line:max-line-length \n y = page.boundingRectangle.y * this.viewer.zoomFactor + (this.viewer.pages.indexOf(page) + 1) * 20 * (1 - this.viewer.zoomFactor);\n var currentPageDiv = this.imageResizerDivElement;\n var currentPageDivWidth = parseFloat(currentPageDiv.style.width);\n var currentPageDivHeight = parseFloat(currentPageDiv.style.height);\n var imageResizerDivWidth = parseFloat(this.imageResizerDiv.style.width);\n var imageResizerDivHeight = parseFloat(this.imageResizerDiv.style.height);\n var margin = (this.resizeMarkSize - 1) / 2;\n var width = imageResizerDivWidth + 2 * margin;\n var height = imageResizerDivHeight + 2 * margin;\n if (width > (currentPageDivWidth - left) * this.viewer.zoomFactor + margin) {\n width = (currentPageDivWidth - left) * this.viewer.zoomFactor;\n }\n if (height > (currentPageDivHeight - top) * this.viewer.zoomFactor + margin) {\n height = (currentPageDivHeight - top) * this.viewer.zoomFactor;\n }\n // if (width < imageResizerDivHeight + margin || height < imageResizerDivHeight + margin) {\n // }\n // tslint:disable-next-line:max-line-length\n this.imageResizerDivElement.style.width = parseInt(this.imageResizerDivElement.style.width.replace('px', ''), 10) * this.viewer.zoomFactor + 'px';\n this.imageResizerDivElement.style.height = parseInt(this.imageResizerDivElement.style.height.replace('px', ''), 10) * this.viewer.zoomFactor + 'px';\n height = this.viewer.render.getScaledValue(elementBox.height);\n width = this.viewer.render.getScaledValue(elementBox.width);\n left = this.viewer.render.getScaledValue(left);\n top = this.viewer.render.getScaledValue(top);\n this.setImageResizerPosition(left, top, width, height, this);\n if (!this.selectedImageWidget.containsKey(lineWidget)) {\n var selectedImageInfo = new SelectedImageInfo(elementBox.height, elementBox.width);\n this.selectedImageWidget.add(lineWidget, selectedImageInfo);\n }\n };\n /**\n * Shows the image resizer.\n * @private\n */\n ImageResizer.prototype.showImageResizer = function () {\n if (!isNullOrUndefined(this.imageResizerDivElement)) {\n this.imageResizerDivElement.style.display = '';\n }\n if (!isNullOrUndefined(this.resizeContainerDiv)) {\n this.resizeContainerDiv.style.display = '';\n }\n if (!isNullOrUndefined(this.bottomLeftRect)) {\n this.bottomLeftRect.style.display = '';\n this.bottomLeftRectParent.style.display = '';\n }\n if (!isNullOrUndefined(this.bottomRightRect)) {\n this.bottomRightRect.style.display = '';\n this.bottomRightRectParent.style.display = '';\n }\n if (!isNullOrUndefined(this.bottomMiddleRect)) {\n this.bottomMiddleRect.style.display = '';\n this.bottomMiddleRectParent.style.display = '';\n }\n if (!isNullOrUndefined(this.rightMiddleRect)) {\n this.rightMiddleRect.style.display = '';\n this.rightMiddleRectParent.style.display = '';\n }\n if (!isNullOrUndefined(this.topRightRect)) {\n this.topRightRect.style.display = '';\n this.topRightRectParent.style.display = '';\n }\n if (!isNullOrUndefined(this.topLeftRect)) {\n this.topLeftRect.style.display = '';\n this.topLeftRectParent.style.display = '';\n }\n if (!isNullOrUndefined(this.leftMiddleRect)) {\n this.leftMiddleRect.style.display = '';\n this.leftMiddleRectParent.style.display = '';\n }\n if (!isNullOrUndefined(this.topMiddleRect)) {\n this.topMiddleRect.style.display = '';\n this.topMiddleRectParent.style.display = '';\n }\n this.isImageResizerVisible = true;\n };\n /**\n * Hides the image resizer.\n * @private\n */\n ImageResizer.prototype.hideImageResizer = function () {\n if (!isNullOrUndefined(this.imageResizerDivElement)) {\n this.imageResizerDivElement.style.display = 'none';\n }\n if (!isNullOrUndefined(this.resizeContainerDiv)) {\n this.resizeContainerDiv.style.display = 'none';\n }\n if (!isNullOrUndefined(this.bottomLeftRect)) {\n this.bottomLeftRect.style.display = 'none';\n this.bottomLeftRectParent.style.display = 'none';\n }\n if (!isNullOrUndefined(this.bottomRightRect)) {\n this.bottomRightRect.style.display = 'none';\n this.bottomRightRectParent.style.display = 'none';\n }\n if (!isNullOrUndefined(this.bottomMiddleRect)) {\n this.bottomMiddleRect.style.display = 'none';\n this.bottomMiddleRectParent.style.display = 'none';\n }\n if (!isNullOrUndefined(this.rightMiddleRect)) {\n this.rightMiddleRect.style.display = 'none';\n this.rightMiddleRectParent.style.display = 'none';\n }\n if (!isNullOrUndefined(this.topRightRect)) {\n this.topRightRect.style.display = 'none';\n this.topRightRectParent.style.display = 'none';\n }\n if (!isNullOrUndefined(this.topLeftRect)) {\n this.topLeftRect.style.display = 'none';\n this.topLeftRectParent.style.display = 'none';\n }\n if (!isNullOrUndefined(this.leftMiddleRect)) {\n this.leftMiddleRect.style.display = 'none';\n this.leftMiddleRectParent.style.display = 'none';\n }\n if (!isNullOrUndefined(this.topMiddleRect)) {\n this.topMiddleRect.style.display = 'none';\n this.topMiddleRectParent.style.display = 'none';\n }\n this.isImageResizerVisible = false;\n this.currentPage = undefined;\n };\n /**\n * Initialize the resize marks.\n * @param {HTMLElement} resizeDiv - Specifies to appending resizer container div element.\n * @param {ImageResizer} imageResizer - Specifies to creating div element of each position.\n * @private\n */\n // tslint:disable:max-func-body-length\n ImageResizer.prototype.initResizeMarks = function (resizeDiv, imageResizer) {\n this.initResizeContainerDiv(imageResizer);\n resizeDiv.appendChild(imageResizer.resizeContainerDiv);\n imageResizer.topRightRectParent = document.createElement('div');\n imageResizer.topRightRectParent.style.cursor = 'ne-resize';\n imageResizer.topRightRectParent.id = this.viewer.owner.containerId + '_TopRightRectParent';\n this.applyProperties(imageResizer.topRightRectParent);\n imageResizer.topRightRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.topRightRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.topRightRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.topRightRectParent);\n imageResizer.topRightRect = document.createElement('div');\n imageResizer.topRightRect.id = this.viewer.owner.containerId + '_TopRightRect';\n imageResizer.topRightRect.style.cursor = 'ne-resize';\n this.applyProperties(imageResizer.topRightRect);\n resizeDiv.appendChild(imageResizer.topRightRect);\n imageResizer.topLeftRectParent = document.createElement('div');\n imageResizer.topLeftRectParent.style.cursor = 'nw-resize';\n imageResizer.topLeftRectParent.id = this.viewer.owner.containerId + '_TopLeftRectParent';\n this.applyProperties(imageResizer.topLeftRectParent);\n imageResizer.topLeftRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.topLeftRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.topLeftRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.topLeftRectParent);\n imageResizer.topLeftRect = document.createElement('div');\n imageResizer.topLeftRect.id = this.viewer.owner.containerId + '_TopLeftRect';\n imageResizer.topLeftRect.style.cursor = 'nw-resize';\n this.applyProperties(imageResizer.topLeftRect);\n resizeDiv.appendChild(imageResizer.topLeftRect);\n imageResizer.topMiddleRectParent = document.createElement('div');\n imageResizer.topMiddleRectParent.style.cursor = 'n-resize';\n imageResizer.topMiddleRectParent.id = this.viewer.owner.containerId + '_TopMiddleRectParent';\n this.applyProperties(imageResizer.topMiddleRectParent);\n imageResizer.topMiddleRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.topMiddleRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.topMiddleRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.topMiddleRectParent);\n imageResizer.topMiddleRect = document.createElement('div');\n imageResizer.topMiddleRect.id = this.viewer.owner.containerId + '_TopMiddleRect';\n imageResizer.topMiddleRect.style.cursor = 'n-resize';\n this.applyProperties(imageResizer.topMiddleRect);\n resizeDiv.appendChild(imageResizer.topMiddleRect);\n imageResizer.bottomRightRectParent = document.createElement('div');\n imageResizer.bottomRightRectParent.style.cursor = 'se-resize';\n imageResizer.bottomRightRectParent.id = this.viewer.owner.containerId + '_BottomRightRectParent';\n this.applyProperties(imageResizer.bottomRightRectParent);\n imageResizer.bottomRightRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.bottomRightRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.bottomRightRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.bottomRightRectParent);\n imageResizer.bottomRightRect = document.createElement('div');\n imageResizer.bottomRightRect.id = this.viewer.owner.containerId + '_BottomRightRect';\n imageResizer.bottomRightRect.style.cursor = 'se-resize';\n this.applyProperties(imageResizer.bottomRightRect);\n resizeDiv.appendChild(imageResizer.bottomRightRect);\n imageResizer.bottomLeftRectParent = document.createElement('div');\n imageResizer.bottomLeftRectParent.style.cursor = 'sw-resize';\n imageResizer.bottomLeftRectParent.id = this.viewer.owner.containerId + '_BottomLeftRectParent';\n this.applyProperties(imageResizer.bottomLeftRectParent);\n imageResizer.bottomLeftRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.bottomLeftRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.bottomLeftRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.bottomLeftRectParent);\n imageResizer.bottomLeftRect = document.createElement('div');\n imageResizer.bottomLeftRect.id = this.viewer.owner.containerId + '_BottomLeftRect';\n imageResizer.bottomLeftRect.style.cursor = 'sw-resize';\n this.applyProperties(imageResizer.bottomLeftRect);\n resizeDiv.appendChild(imageResizer.bottomLeftRect);\n imageResizer.bottomMiddleRectParent = document.createElement('div');\n imageResizer.bottomMiddleRectParent.style.cursor = 's-resize';\n imageResizer.bottomMiddleRectParent.id = this.viewer.owner.containerId + '_BottomMiddleRectParent';\n this.applyProperties(imageResizer.bottomMiddleRectParent);\n imageResizer.bottomMiddleRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.bottomMiddleRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.bottomMiddleRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.bottomMiddleRectParent);\n imageResizer.bottomMiddleRect = document.createElement('div');\n imageResizer.bottomMiddleRect.id = this.viewer.owner.containerId + '_BottomMiddleRect';\n imageResizer.bottomMiddleRect.style.cursor = 's-resize';\n this.applyProperties(imageResizer.bottomMiddleRect);\n resizeDiv.appendChild(imageResizer.bottomMiddleRect);\n imageResizer.rightMiddleRectParent = document.createElement('div');\n imageResizer.rightMiddleRectParent.style.cursor = 'e-resize';\n imageResizer.rightMiddleRectParent.id = this.viewer.owner.containerId + '_RightMiddleRectParent';\n this.applyProperties(imageResizer.rightMiddleRectParent);\n imageResizer.rightMiddleRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.rightMiddleRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.rightMiddleRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.rightMiddleRectParent);\n imageResizer.rightMiddleRect = document.createElement('div');\n imageResizer.rightMiddleRect.id = this.viewer.owner.containerId + '_RightMiddleRect';\n imageResizer.rightMiddleRect.style.cursor = 'e-resize';\n this.applyProperties(imageResizer.rightMiddleRect);\n resizeDiv.appendChild(imageResizer.rightMiddleRect);\n imageResizer.leftMiddleRectParent = document.createElement('div');\n imageResizer.leftMiddleRectParent.style.cursor = 'w-resize';\n imageResizer.leftMiddleRectParent.id = this.viewer.owner.containerId + '_LeftMiddleRectParent';\n this.applyProperties(imageResizer.leftMiddleRectParent);\n imageResizer.leftMiddleRectParent.style.width = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.leftMiddleRectParent.style.height = !this.viewer.isTouchInput ? '14px' : '30px';\n imageResizer.leftMiddleRectParent.style.opacity = '-1';\n resizeDiv.appendChild(imageResizer.leftMiddleRectParent);\n imageResizer.leftMiddleRect = document.createElement('div');\n imageResizer.leftMiddleRect.id = this.viewer.owner.containerId + '_LeftMiddleRect';\n imageResizer.leftMiddleRect.style.cursor = 'w-resize';\n this.applyProperties(imageResizer.leftMiddleRect);\n resizeDiv.appendChild(imageResizer.leftMiddleRect);\n return imageResizer.resizeContainerDiv;\n };\n /**\n * Sets the image resizer position.\n * @param {number} left - Specifies for image resizer left value.\n * @param {number} top - Specifies for image resizer top value.\n * @param {number} width - Specifies for image resizer width value.\n * @param {number} height - Specifies for image resizer height value.\n * @param {ImageResizer} imageResizer - Specifies for image resizer.\n * @private\n */\n ImageResizer.prototype.setImageResizerPosition = function (left, top, width, height, imageResizer) {\n //Positions Updating For Image Resize Div\n imageResizer.resizeContainerDiv.style.width = width + 'px';\n imageResizer.resizeContainerDiv.style.height = height + 'px';\n imageResizer.resizeContainerDiv.style.left = left - 1 + 'px';\n imageResizer.resizeContainerDiv.style.top = top + 'px';\n //Positions Updating For Image Resizing Points\n imageResizer.topRightRect.style.left = ((left + width) - 5) + 'px';\n imageResizer.topRightRect.style.top = (top - 4) + 'px';\n imageResizer.topLeftRect.style.left = (left - 5) + 'px';\n imageResizer.topLeftRect.style.top = (top - 4) + 'px';\n imageResizer.topMiddleRect.style.left = ((parseFloat(imageResizer.topLeftRect.style.left) + (width / 2)) - 4) + 'px';\n imageResizer.topMiddleRect.style.top = (top - 4) + 'px';\n imageResizer.bottomRightRect.style.left = imageResizer.topRightRect.style.left;\n imageResizer.bottomRightRect.style.top = (parseFloat(imageResizer.topRightRect.style.top) + height) + 'px';\n imageResizer.bottomLeftRect.style.left = imageResizer.topLeftRect.style.left;\n imageResizer.bottomLeftRect.style.top = (parseFloat(imageResizer.topLeftRect.style.top) + height) + 'px';\n imageResizer.bottomMiddleRect.style.left = imageResizer.topMiddleRect.style.left;\n imageResizer.bottomMiddleRect.style.top = (parseFloat(imageResizer.topMiddleRect.style.top) + height) + 'px';\n imageResizer.rightMiddleRect.style.left = ((left + width) - 4) + 'px';\n imageResizer.rightMiddleRect.style.top = (parseFloat(imageResizer.topRightRect.style.top) + (height / 2)) + 'px';\n imageResizer.leftMiddleRect.style.left = imageResizer.topLeftRect.style.left;\n imageResizer.leftMiddleRect.style.top = (parseFloat(imageResizer.topLeftRect.style.top) + (height / 2)) + 'px';\n imageResizer.topRightRectParent.style.left = !this.viewer.isTouchInput ? ((left + width) - 8) + 'px' : ((left + width) - 15) + 'px';\n imageResizer.topRightRectParent.style.top = !this.viewer.isTouchInput ? (top - 7) + 'px' : (top - 15) + 'px';\n imageResizer.topLeftRectParent.style.left = !this.viewer.isTouchInput ? (left - 8) + 'px' : (left - 15) + 'px';\n imageResizer.topLeftRectParent.style.top = !this.viewer.isTouchInput ? (top - 7) + 'px' : (top - 15) + 'px';\n imageResizer.topMiddleRectParent.style.left = ((parseFloat(imageResizer.topLeftRectParent.style.left) + (width / 2)) - 4) + 'px';\n imageResizer.topMiddleRectParent.style.top = !this.viewer.isTouchInput ? (top - 7) + 'px' : (top - 15) + 'px';\n imageResizer.bottomRightRectParent.style.left = imageResizer.topRightRectParent.style.left;\n imageResizer.bottomRightRectParent.style.top = (parseFloat(imageResizer.topRightRectParent.style.top) + height) + 'px';\n imageResizer.bottomLeftRectParent.style.left = imageResizer.topLeftRectParent.style.left;\n imageResizer.bottomLeftRectParent.style.top = (parseFloat(imageResizer.topLeftRectParent.style.top) + height) + 'px';\n imageResizer.bottomMiddleRectParent.style.left = imageResizer.topMiddleRectParent.style.left;\n imageResizer.bottomMiddleRectParent.style.top = (parseFloat(imageResizer.topMiddleRectParent.style.top) + height) + 'px';\n // tslint:disable-next-line:max-line-length \n imageResizer.rightMiddleRectParent.style.left = !this.viewer.isTouchInput ? ((left + width) - 7) + 'px' : ((left + width) - 15) + 'px';\n imageResizer.rightMiddleRectParent.style.top = (parseFloat(imageResizer.topRightRectParent.style.top) + (height / 2)) + 'px';\n imageResizer.leftMiddleRectParent.style.left = imageResizer.topLeftRectParent.style.left;\n imageResizer.leftMiddleRectParent.style.top = (parseFloat(imageResizer.topLeftRectParent.style.top) + (height / 2)) + 'px';\n this.setImageResizingPoints(imageResizer);\n if (this.viewer.isTouchInput) {\n this.applyPropertiesForTouch();\n }\n else {\n this.applyPropertiesForMouse();\n }\n };\n /**\n * Sets the image resizing points.\n * @param {ImageResizer} imageResizer - Specifies for position of each resizing elements.\n * @private\n */\n ImageResizer.prototype.setImageResizingPoints = function (imageResizer) {\n this.imageResizerPoints.resizeContainerDiv.x = parseFloat(imageResizer.resizeContainerDiv.style.left);\n this.imageResizerPoints.resizeContainerDiv.y = parseFloat(imageResizer.resizeContainerDiv.style.top);\n this.imageResizerPoints.bottomLeftRectParent.x = parseFloat(imageResizer.bottomLeftRectParent.style.left);\n this.imageResizerPoints.bottomLeftRectParent.y = parseFloat(imageResizer.bottomLeftRectParent.style.top);\n this.imageResizerPoints.bottomRightRectParent.x = parseFloat(imageResizer.bottomRightRectParent.style.left);\n this.imageResizerPoints.bottomRightRectParent.y = parseFloat(imageResizer.bottomRightRectParent.style.top);\n this.imageResizerPoints.bottomMiddleRectParent.x = parseFloat(imageResizer.bottomMiddleRectParent.style.left);\n this.imageResizerPoints.bottomMiddleRectParent.y = parseFloat(imageResizer.bottomMiddleRectParent.style.top);\n this.imageResizerPoints.topLeftRectParent.x = parseFloat(imageResizer.topLeftRectParent.style.left);\n this.imageResizerPoints.topLeftRectParent.y = parseFloat(imageResizer.topLeftRectParent.style.top);\n this.imageResizerPoints.topRightRectParent.x = parseFloat(imageResizer.topRightRectParent.style.left);\n this.imageResizerPoints.topRightRectParent.y = parseFloat(imageResizer.topRightRectParent.style.top);\n this.imageResizerPoints.topMiddleRectParent.x = parseFloat(imageResizer.topMiddleRectParent.style.left);\n this.imageResizerPoints.topMiddleRectParent.y = parseFloat(imageResizer.topMiddleRectParent.style.top);\n this.imageResizerPoints.leftMiddleRectParent.x = parseFloat(imageResizer.leftMiddleRectParent.style.left);\n this.imageResizerPoints.leftMiddleRectParent.y = parseFloat(imageResizer.leftMiddleRectParent.style.top);\n this.imageResizerPoints.rightMiddleRectParent.x = parseFloat(imageResizer.rightMiddleRectParent.style.left);\n this.imageResizerPoints.rightMiddleRectParent.y = parseFloat(imageResizer.rightMiddleRectParent.style.top);\n };\n /**\n * Initialize the resize container div element.\n * @param {ImageResizer} imageResizer - Specifies for creating resize container div element.\n * @private\n */\n ImageResizer.prototype.initResizeContainerDiv = function (imageResizer) {\n imageResizer.resizeContainerDiv = document.createElement('div');\n imageResizer.resizeContainerDiv.id = this.viewer.owner.containerId + '_ResizeDivElement';\n imageResizer.resizeContainerDiv.style.position = 'absolute';\n imageResizer.resizeContainerDiv.style.border = '1px solid #bfbfbf';\n imageResizer.resizeContainerDiv.style.zIndex = '30';\n imageResizer.resizeContainerDiv.style.backgroundColor = 'transparent';\n imageResizer.resizeContainerDiv.style.display = 'block';\n };\n /**\n * Apply the properties of each resize rectangle element.\n * @param {HTMLDivElement} resizeRectElement - Specifies for applying properties to resize rectangle element.\n * @private\n */\n ImageResizer.prototype.applyProperties = function (resizeRectElement) {\n resizeRectElement.style.position = 'absolute';\n resizeRectElement.style.width = '8px';\n resizeRectElement.style.height = '8px';\n resizeRectElement.style.fontSize = '0px';\n resizeRectElement.style.zIndex = ' 551';\n resizeRectElement.style.backgroundColor = '#ffffff';\n resizeRectElement.style.border = '1px solid #bfbfbf';\n resizeRectElement.style.boxShadow = '0 1px 2px 0 #bfbfbf 0.35';\n resizeRectElement.style.color = '#000000';\n };\n /**\n * Handles an image resizing.\n * @param {number} x - Specifies for left value while resizing.\n * @param {number} y - Specifies for top value while resizing.\n */\n ImageResizer.prototype.handleImageResizing = function (touchPoint, prevX, prevY) {\n prevX = prevX / this.viewer.zoomFactor;\n prevY = prevY / this.viewer.zoomFactor;\n this.leftValue = isNullOrUndefined(this.leftValue) ? prevX : this.leftValue;\n this.topValue = isNullOrUndefined(this.topValue) ? prevY : this.topValue;\n var points;\n switch (this.selectedResizeElement.id.split('_')[1]) {\n case 'TopRightRectParent':\n points = this.topRightResizing(touchPoint);\n prevX = points.left;\n prevY = points.top;\n break;\n case 'TopLeftRectParent':\n points = this.topLeftResizing(touchPoint);\n prevX = -points.left;\n prevY = -points.top;\n break;\n case 'TopMiddleRectParent':\n prevX = 0;\n prevY = this.topMiddleResizing(touchPoint);\n break;\n case 'BottomRightRectParent':\n points = this.bottomRightResizing(touchPoint);\n prevX = points.left;\n prevY = points.top;\n break;\n case 'BottomLeftRectParent':\n points = this.bottomLeftResizing(touchPoint);\n prevX = -points.left;\n prevY = -points.top;\n break;\n case 'BottomMiddleRectParent':\n prevY = touchPoint.y - prevY;\n prevX = 0;\n break;\n case 'RightMiddleRectParent':\n prevX = touchPoint.x - prevX;\n prevY = 0;\n break;\n case 'LeftMiddleRectParent':\n prevX = this.leftMiddleResizing(touchPoint);\n prevY = 0;\n break;\n default:\n break;\n }\n if (prevX !== 0 || prevY !== 0) {\n var widget = this.currentImageElementBox.line.paragraph;\n var image = this.currentImageElementBox;\n if (!isNullOrUndefined(widget) && widget.isInsideTable) {\n var cellWidget = widget.containerWidget;\n if (!isNullOrUndefined(cellWidget)) {\n var rowWidget = cellWidget.containerWidget;\n var imageHeight = HelperMethods.convertPointToPixel(image.height);\n var widgetHeight = rowWidget.height - imageHeight;\n if (prevY > 0 && rowWidget.y + widgetHeight + imageHeight + prevY > this.viewer.clientArea.bottom) {\n this.isImageMoveToNextPage = true;\n }\n }\n }\n // tslint:disable-next-line:max-line-length \n if (this.owner.enableHistoryMode) {\n this.initHistoryForImageResizer(this.currentImageElementBox);\n }\n if (!isNullOrUndefined(this.currentImageElementBox)) {\n // tslint:disable-next-line:max-line-length \n var width = this.currentImageElementBox.width + prevX > 10 ? this.currentImageElementBox.width + prevX : 10;\n // tslint:disable-next-line:max-line-length \n var height = this.currentImageElementBox.height + prevY > 10 ? this.currentImageElementBox.height + prevY : 10;\n if (this.selectedResizeElement.id.split('_')[1] === 'BottomRightRectParent'\n || this.selectedResizeElement.id.split('_')[1] === 'TopRightRectParent'\n || this.selectedResizeElement.id.split('_')[1] === 'BottomLeftRectParent'\n || this.selectedResizeElement.id.split('_')[1] === 'TopLeftRectParent') {\n height = this.currentImageElementBox.height / this.currentImageElementBox.width * width;\n width = this.currentImageElementBox.width / this.currentImageElementBox.height * height;\n }\n this.currentImageElementBox.width = width;\n this.currentImageElementBox.height = height;\n var owner = this.currentImageElementBox.line.paragraph;\n this.positionImageResizer(this.currentImageElementBox);\n }\n this.isImageResizing = true;\n }\n };\n /**\n * Handles image resizing on mouse.\n * @param {MouseEvent} event - Specifies for image resizing using mouse event.\n * @private\n */\n ImageResizer.prototype.handleImageResizingOnMouse = function (event) {\n if (!isNullOrUndefined(this.selectedResizeElement)) {\n var prevX = parseFloat(this.selectedResizeElement.style.left);\n var prevY = parseFloat(this.selectedResizeElement.style.top);\n var cursorPoint = new Point(event.offsetX, event.offsetY);\n var touchPoint = this.viewer.findFocusedPage(cursorPoint, true);\n this.handleImageResizing(touchPoint, prevX, prevY);\n }\n };\n ImageResizer.prototype.topMiddleResizing = function (touchPoint) {\n var prevY;\n if (this.topValue >= touchPoint.y) {\n prevY = this.topValue / touchPoint.y;\n this.topValue = touchPoint.y;\n if (this.viewer instanceof PageLayoutViewer) {\n if (this.topValue <= this.viewer.pageGap) {\n prevY = 1;\n }\n }\n }\n else {\n prevY = -(touchPoint.y / this.topValue);\n this.topValue = touchPoint.y;\n if (this.topValue === 0) {\n prevY = -1;\n }\n }\n return prevY;\n };\n ImageResizer.prototype.leftMiddleResizing = function (touchPoint) {\n var prevX;\n if (this.leftValue >= touchPoint.x) {\n prevX = this.leftValue / touchPoint.x;\n this.leftValue = touchPoint.x;\n if (this.leftValue === 0) {\n prevX = 1;\n this.leftValue = parseFloat(this.selectedResizeElement.style.left);\n }\n }\n else {\n prevX = -(touchPoint.x / this.leftValue);\n this.leftValue = touchPoint.x;\n }\n return prevX;\n };\n ImageResizer.prototype.topRightResizing = function (touchPoint) {\n var points;\n if (this.leftValue <= touchPoint.x && this.topValue >= touchPoint.y) {\n points = this.getOuterResizingPoint(touchPoint);\n }\n else {\n points = this.getInnerResizingPoint(touchPoint);\n }\n return points;\n };\n ImageResizer.prototype.topLeftResizing = function (touchPoint) {\n var points;\n if (this.leftValue >= touchPoint.x && this.topValue >= touchPoint.y) {\n points = this.getOuterResizingPoint(touchPoint);\n }\n else {\n points = this.getInnerResizingPoint(touchPoint);\n }\n return points;\n };\n ImageResizer.prototype.bottomRightResizing = function (touchPoint) {\n var points;\n if (this.leftValue <= touchPoint.x && this.topValue <= touchPoint.y) {\n points = this.getOuterResizingPoint(touchPoint);\n }\n else {\n points = this.getInnerResizingPoint(touchPoint);\n }\n return points;\n };\n ImageResizer.prototype.bottomLeftResizing = function (touchPoint) {\n var points;\n if (this.leftValue >= touchPoint.x && this.topValue <= touchPoint.y) {\n points = this.getOuterResizingPoint(touchPoint);\n }\n else {\n points = this.getInnerResizingPoint(touchPoint);\n }\n return points;\n };\n ImageResizer.prototype.getOuterResizingPoint = function (touchPoint) {\n var prevX;\n var prevY;\n prevX = touchPoint.x - this.leftValue;\n this.leftValue = touchPoint.x;\n prevY = touchPoint.y - this.topValue;\n this.topValue = touchPoint.y;\n return { left: prevX, top: prevY };\n };\n ImageResizer.prototype.getInnerResizingPoint = function (touchPoint) {\n var prevX;\n var prevY;\n prevX = -(this.leftValue - touchPoint.x);\n this.leftValue = touchPoint.x;\n prevY = -(this.topValue - touchPoint.y);\n this.topValue = touchPoint.y;\n return { left: prevX, top: prevY };\n };\n /**\n * Handles image resizing on touch.\n * @param {TouchEvent} touchEvent - Specifies for image resizing using touch event.\n * @private\n */\n ImageResizer.prototype.handleImageResizingOnTouch = function (touchEvent) {\n if (!isNullOrUndefined(this.selectedResizeElement)) {\n var prevX = parseFloat(this.selectedResizeElement.style.left) + 24;\n var prevY = parseFloat(this.selectedResizeElement.style.top) + 24;\n var touch = touchEvent.touches;\n var cursorPoint = new Point(touch[0].clientX, touch[0].clientY);\n var touchPoint = this.viewer.findFocusedPage(cursorPoint, true);\n if (isNullOrUndefined(this.currentImageElementBox) || isNullOrUndefined(this.currentImageElementBox)) {\n return;\n }\n this.handleImageResizing(touchPoint, prevX, prevY);\n }\n };\n /**\n * Gets the image point of mouse.\n * @param {Point} touchPoint - Specifies for resizer cursor position.\n * @private\n */\n ImageResizer.prototype.getImagePoint = function (touchPoint) {\n var x = this.viewer.render.getScaledValue(touchPoint.x, 1);\n var y = this.viewer.render.getScaledValue(touchPoint.y, 2);\n touchPoint = new Point(x, y);\n var imageResizingPoints = this.imageResizerPoints;\n var resizePosition = '';\n var selectedElement = undefined;\n var bottomMiddle = imageResizingPoints.bottomMiddleRectParent;\n var bottomRight = imageResizingPoints.bottomRightRectParent;\n var bottomLeft = imageResizingPoints.bottomLeftRectParent;\n var topMiddle = imageResizingPoints.topMiddleRectParent;\n var topRight = imageResizingPoints.topRightRectParent;\n var topLeft = imageResizingPoints.topLeftRectParent;\n var rightMiddle = imageResizingPoints.rightMiddleRectParent;\n var leftMiddle = imageResizingPoints.leftMiddleRectParent;\n if (!isNullOrUndefined(this.bottomMiddleRectParent) && this.bottomMiddleRectParent.style.display !== 'none') {\n // tslint:disable-next-line:max-line-length \n if ((touchPoint.x > bottomMiddle.x && touchPoint.x <= bottomMiddle.x + 15) && (touchPoint.y > bottomMiddle.y && touchPoint.y <= bottomMiddle.y + 15)) {\n selectedElement = this.bottomMiddleRectParent;\n resizePosition = 's-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoint.x > bottomRight.x && touchPoint.x <= bottomRight.x + 15) && (touchPoint.y > bottomRight.y && touchPoint.y <= bottomRight.y + 15)) {\n selectedElement = this.bottomRightRectParent;\n resizePosition = 'se-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoint.x > bottomLeft.x && touchPoint.x <= bottomLeft.x + 15) && (touchPoint.y > bottomLeft.y && touchPoint.y <= bottomLeft.y + 15)) {\n selectedElement = this.bottomLeftRectParent;\n resizePosition = 'sw-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoint.x > topMiddle.x && touchPoint.x <= topMiddle.x + 15) && (touchPoint.y > topMiddle.y && touchPoint.y <= topMiddle.y + 15)) {\n selectedElement = this.topMiddleRectParent;\n resizePosition = 'n-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoint.x > topRight.x && touchPoint.x <= topRight.x + 15) && (touchPoint.y > topRight.y && touchPoint.y <= topRight.y + 15)) {\n selectedElement = this.topRightRectParent;\n resizePosition = 'ne-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoint.x > topLeft.x && touchPoint.x <= topLeft.x + 15) && (touchPoint.y > topLeft.y && touchPoint.y <= topLeft.y + 15)) {\n selectedElement = this.topLeftRectParent;\n resizePosition = 'nw-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoint.x > leftMiddle.x && touchPoint.x <= leftMiddle.x + 15) && (touchPoint.y > leftMiddle.y && touchPoint.y <= leftMiddle.y + 15)) {\n selectedElement = this.leftMiddleRectParent;\n resizePosition = 'w-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoint.x > rightMiddle.x && touchPoint.x <= rightMiddle.x + 15) && (touchPoint.y > rightMiddle.y && touchPoint.y <= rightMiddle.y + 15)) {\n selectedElement = this.rightMiddleRectParent;\n resizePosition = 'e-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if (!isNullOrUndefined(this.resizeContainerDiv) && (touchPoint.x > parseFloat(this.resizeContainerDiv.style.left)\n && touchPoint.x <= (parseFloat(this.resizeContainerDiv.style.left) + parseFloat(this.resizeContainerDiv.style.width)))\n && (touchPoint.y > parseFloat(this.resizeContainerDiv.style.top)\n // tslint:disable-next-line:max-line-length \n && touchPoint.y <= (parseFloat(this.resizeContainerDiv.style.top) + parseFloat(this.resizeContainerDiv.style.height)))) {\n resizePosition = 'move';\n }\n }\n return { 'selectedElement': selectedElement, 'resizePosition': resizePosition };\n };\n ImageResizer.prototype.applyPropertiesForMouse = function () {\n if (!isNullOrUndefined(this.bottomLeftRectParent)) {\n this.bottomMiddleRectParent.style.width = '14px';\n this.bottomMiddleRectParent.style.height = '14px';\n this.bottomRightRectParent.style.width = '14px';\n this.bottomRightRectParent.style.height = '14px';\n this.bottomLeftRectParent.style.width = '14px';\n this.bottomLeftRectParent.style.height = '14px';\n this.topMiddleRectParent.style.width = '14px';\n this.topMiddleRectParent.style.height = '14px';\n this.topRightRectParent.style.width = '14px';\n this.topRightRectParent.style.height = '14px';\n this.topLeftRectParent.style.width = '14px';\n this.topLeftRectParent.style.height = '14px';\n this.leftMiddleRectParent.style.width = '14px';\n this.leftMiddleRectParent.style.height = '14px';\n this.rightMiddleRectParent.style.width = '14px';\n this.rightMiddleRectParent.style.height = '14px';\n }\n };\n /**\n * Gets the image point of touch.\n * @param {Point} touchPoints - Specifies for resizer cursor position.\n * @private\n */\n ImageResizer.prototype.getImagePointOnTouch = function (touchPoints) {\n var x = this.viewer.render.getScaledValue(touchPoints.x, 1);\n var y = this.viewer.render.getScaledValue(touchPoints.y, 2);\n touchPoints = new Point(x, y);\n var imageResizingPointsOnTouch = this.imageResizerPoints;\n var resizePosition = '';\n var selectedElements = undefined;\n var bottomMiddle = imageResizingPointsOnTouch.bottomMiddleRectParent;\n var bottomRight = imageResizingPointsOnTouch.bottomRightRectParent;\n var bottomLeft = imageResizingPointsOnTouch.bottomLeftRectParent;\n var topMiddle = imageResizingPointsOnTouch.topMiddleRectParent;\n var topRight = imageResizingPointsOnTouch.topRightRectParent;\n var topLeft = imageResizingPointsOnTouch.topLeftRectParent;\n var rightMiddle = imageResizingPointsOnTouch.rightMiddleRectParent;\n var leftMiddle = imageResizingPointsOnTouch.leftMiddleRectParent;\n if (!isNullOrUndefined(this.bottomMiddleRectParent) && this.bottomMiddleRectParent.style.display !== 'none') {\n // tslint:disable-next-line:max-line-length \n if ((touchPoints.x > bottomMiddle.x && touchPoints.x <= bottomMiddle.x + 25) && (touchPoints.y > bottomMiddle.y && touchPoints.y <= bottomMiddle.y + 25)) {\n selectedElements = this.bottomMiddleRectParent;\n resizePosition = 's-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoints.x > bottomRight.x && touchPoints.x <= bottomRight.x + 25) && (touchPoints.y > bottomRight.y && touchPoints.y <= bottomRight.y + 25)) {\n selectedElements = this.bottomRightRectParent;\n resizePosition = 'se-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoints.x > bottomLeft.x && touchPoints.x <= bottomLeft.x + 25) && (touchPoints.y > bottomLeft.y && touchPoints.y <= bottomLeft.y + 25)) {\n selectedElements = this.bottomLeftRectParent;\n resizePosition = 'sw-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoints.x > topMiddle.x && touchPoints.x <= topMiddle.x + 25) && (touchPoints.y > topMiddle.y && touchPoints.y <= topMiddle.y + 25)) {\n selectedElements = this.topMiddleRectParent;\n resizePosition = 'n-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoints.x > topRight.x && touchPoints.x <= topRight.x + 25) && (touchPoints.y > topRight.y && touchPoints.y <= topRight.y + 25)) {\n selectedElements = this.topRightRectParent;\n resizePosition = 'ne-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoints.x > topLeft.x && touchPoints.x <= topLeft.x + 25) && (touchPoints.y > topLeft.y && touchPoints.y <= topLeft.y + 25)) {\n selectedElements = this.topLeftRectParent;\n resizePosition = 'nw-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoints.x > leftMiddle.x && touchPoints.x <= leftMiddle.x + 25) && (touchPoints.y > leftMiddle.y && touchPoints.y <= leftMiddle.y + 25)) {\n selectedElements = this.leftMiddleRectParent;\n resizePosition = 'w-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if ((touchPoints.x > rightMiddle.x && touchPoints.x <= rightMiddle.x + 25) && (touchPoints.y > rightMiddle.y && touchPoints.y <= rightMiddle.y + 25)) {\n selectedElements = this.rightMiddleRectParent;\n resizePosition = 'e-resize';\n // tslint:disable-next-line:max-line-length \n }\n else if (!isNullOrUndefined(this.resizeContainerDiv) && (touchPoints.x > parseFloat(this.resizeContainerDiv.style.left)\n && touchPoints.x <= (parseFloat(this.resizeContainerDiv.style.left) + parseFloat(this.resizeContainerDiv.style.width)))\n && (touchPoints.y > parseFloat(this.resizeContainerDiv.style.top)\n // tslint:disable-next-line:max-line-length \n && touchPoints.y <= (parseFloat(this.resizeContainerDiv.style.top) + parseFloat(this.resizeContainerDiv.style.height)))) {\n resizePosition = 'move';\n }\n }\n return { 'selectedElement': selectedElements, 'resizePosition': resizePosition };\n };\n ImageResizer.prototype.applyPropertiesForTouch = function () {\n if (!isNullOrUndefined(this.bottomLeftRectParent)) {\n this.bottomMiddleRectParent.style.width = '30px';\n this.bottomMiddleRectParent.style.height = '30px';\n this.bottomRightRectParent.style.width = '30px';\n this.bottomRightRectParent.style.height = '30px';\n this.bottomLeftRectParent.style.width = '30px';\n this.bottomLeftRectParent.style.height = '30px';\n this.topMiddleRectParent.style.width = '30px';\n this.topMiddleRectParent.style.height = '30px';\n this.topRightRectParent.style.width = '30px';\n this.topRightRectParent.style.height = '30px';\n this.topLeftRectParent.style.width = '30px';\n this.topLeftRectParent.style.height = '30px';\n this.leftMiddleRectParent.style.width = '30px';\n this.leftMiddleRectParent.style.height = '30px';\n this.rightMiddleRectParent.style.width = '30px';\n this.rightMiddleRectParent.style.height = '30px';\n }\n };\n /**\n * @private\n */\n ImageResizer.prototype.mouseUpInternal = function () {\n this.currentImageElementBox.width = parseFloat(this.imageResizerDiv.style.width) / this.viewer.zoomFactor;\n this.currentImageElementBox.height = parseFloat(this.imageResizerDiv.style.height) / this.viewer.zoomFactor;\n this.owner.isShiftingEnabled = true;\n this.owner.editorModule.setOffsetValue(this.owner.selection);\n this.viewer.layout.reLayoutParagraph(this.currentImageElementBox.line.paragraph, 0, 0);\n this.owner.editorModule.reLayout(this.owner.selection, true);\n this.viewer.updateScrollBars();\n };\n /**\n * Initialize history for image resizer.\n * @param {ImageResizer} imageResizer - Specifies for image resizer.\n * @param {WImage} imageContainer - Specifies for an image.\n * @private\n */\n ImageResizer.prototype.initHistoryForImageResizer = function (imageContainer) {\n if (!isNullOrUndefined(this.owner) && isNullOrUndefined(this.baseHistoryInfo)) {\n this.baseHistoryInfo = new BaseHistoryInfo(this.owner);\n this.baseHistoryInfo.action = 'ImageResizing';\n this.baseHistoryInfo.updateSelection();\n this.baseHistoryInfo.modifiedProperties.push(new ImageFormat(imageContainer));\n }\n };\n /**\n * Updates histroy for image resizer.\n * @private\n */\n ImageResizer.prototype.updateHistoryForImageResizer = function () {\n if (!isNullOrUndefined(this.owner) && !isNullOrUndefined(this.baseHistoryInfo)) {\n var imageFormat = this.baseHistoryInfo.modifiedProperties[0];\n if (this.currentImageElementBox.width === imageFormat.width\n && this.currentImageElementBox.height === imageFormat.height) {\n this.baseHistoryInfo.modifiedProperties.pop();\n }\n else {\n //Records the image size modifications\n this.owner.editorHistory.recordChanges(this.baseHistoryInfo);\n }\n //Fires the content changed event for the image size modifications\n this.baseHistoryInfo = undefined;\n }\n };\n /**\n * Updates image resize container when applying zooming\n * @private\n */\n ImageResizer.prototype.updateImageResizerPosition = function () {\n if (!isNullOrUndefined(this.currentImageElementBox)) {\n var elementBox = this.currentImageElementBox;\n var lineWidget = elementBox.line;\n var top_1 = this.viewer.selection.getTop(lineWidget) + elementBox.margin.top;\n var left = this.viewer.selection.getLeftInternal(lineWidget, elementBox, 0);\n var topValue = top_1 * this.viewer.zoomFactor;\n var leftValue = left * this.viewer.zoomFactor;\n var height = this.viewer.render.getScaledValue(elementBox.height, 2);\n var width = this.viewer.render.getScaledValue(elementBox.width, 1);\n this.setImageResizerPosition(leftValue, topValue, width, height, this);\n }\n };\n /**\n * Dispose the internal objects which are maintained.\n * @private\n */\n ImageResizer.prototype.destroy = function () {\n if (!isNullOrUndefined(this.resizeContainerDiv)) {\n this.resizeContainerDiv.innerHTML = '';\n }\n if (!isNullOrUndefined(this.topLeftRect)) {\n this.topLeftRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.topMiddleRect)) {\n this.topMiddleRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.topRightRect)) {\n this.topRightRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.bottomLeftRect)) {\n this.bottomLeftRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.bottomMiddleRect)) {\n this.bottomMiddleRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.bottomRightRect)) {\n this.bottomRightRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.leftMiddleRect)) {\n this.leftMiddleRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.rightMiddleRect)) {\n this.rightMiddleRect.innerHTML = '';\n }\n if (!isNullOrUndefined(this.imageResizerDiv)) {\n this.imageResizerDiv.innerHTML = '';\n }\n if (!isNullOrUndefined(this.selectedImageWidget)) {\n this.selectedImageWidget.destroy();\n }\n if (!isNullOrUndefined(this.imageResizerDivElement)) {\n this.imageResizerDivElement.innerHTML = '';\n }\n this.imageResizerDivElement = undefined;\n this.resizeContainerDiv = undefined;\n this.topLeftRect = undefined;\n this.topMiddleRect = undefined;\n this.topRightRect = undefined;\n this.bottomLeftRect = undefined;\n this.bottomMiddleRect = undefined;\n this.bottomRightRect = undefined;\n this.leftMiddleRect = undefined;\n this.rightMiddleRect = undefined;\n this.imageResizerDiv = undefined;\n this.selectedImageWidget = undefined;\n this.isImageResizing = false;\n this.isImageResizerVisible = false;\n this.currentImageElementBoxIn = undefined;\n //this.baseHistoryInfo = undefined;\n this.resizeMarkSizeIn = undefined;\n this.viewer = undefined;\n this.owner = undefined;\n };\n return ImageResizer;\n}());\nexport { ImageResizer };\n/**\n * @private\n */\nvar ImageResizingPoints = /** @class */ (function () {\n /**\n * Constructor for image resizing points class.\n */\n function ImageResizingPoints() {\n /**\n * @private\n */ this.resizeContainerDiv = new Point(0, 0);\n /**\n * @private\n */\n this.topLeftRectParent = new Point(0, 0);\n /**\n * @private\n */\n this.topMiddleRectParent = new Point(0, 0);\n /**\n * @private\n */\n this.topRightRectParent = new Point(0, 0);\n /**\n * @private\n */\n this.bottomLeftRectParent = new Point(0, 0);\n /**\n * @private\n */\n this.bottomMiddleRectParent = new Point(0, 0);\n /**\n * @private\n */\n this.bottomRightRectParent = new Point(0, 0);\n /**\n * @private\n */\n this.leftMiddleRectParent = new Point(0, 0);\n /**\n * @private\n */\n this.rightMiddleRectParent = new Point(0, 0);\n var text = 'DocumentEditor';\n }\n return ImageResizingPoints;\n}());\nexport { ImageResizingPoints };\n/**\n * @private\n */\nvar SelectedImageInfo = /** @class */ (function () {\n /**\n * Constructor for selected image info class.\n * @param {number} height - Specifies for height value.\n * @param {number} width - Specifies for width value.\n */\n function SelectedImageInfo(height, width) {\n this.heightIn = 0;\n this.widthIn = 0;\n this.heightIn = height;\n this.widthIn = width;\n }\n Object.defineProperty(SelectedImageInfo.prototype, \"height\", {\n /**\n * Gets or Sets the height value.\n * @private\n */\n get: function () {\n return this.heightIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.heightIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(SelectedImageInfo.prototype, \"width\", {\n /**\n * Gets or Sets the width value.\n * @private\n */\n get: function () {\n return this.widthIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.widthIn = value;\n },\n enumerable: true,\n configurable: true\n });\n return SelectedImageInfo;\n}());\nexport { SelectedImageInfo };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { BaseHistoryInfo } from './base-history-info';\n/**\n * EditorHistory preservation class\n */\n/**\n * @private\n */\nvar HistoryInfo = /** @class */ (function (_super) {\n __extends(HistoryInfo, _super);\n function HistoryInfo(node, isChild) {\n var _this = _super.call(this, node) || this;\n _this.isChildHistoryInfo = false;\n _this.isChildHistoryInfo = isChild;\n return _this;\n }\n Object.defineProperty(HistoryInfo.prototype, \"hasAction\", {\n /**\n * @private\n */\n get: function () {\n return !isNullOrUndefined(this.modifiedActions);\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Adds the modified actions\n * @param {BaseHistoryInfo} baseHistoryInfo\n * @private\n */\n HistoryInfo.prototype.addModifiedAction = function (baseHistoryInfo) {\n // For complex actions such as Replace text, Insert/Remove Hyperlink etc.\n if (!(this.editorHistory.isUndoing || this.editorHistory.isRedoing)) {\n if (isNullOrUndefined(this.modifiedActions)) {\n this.modifiedActions = [];\n }\n this.modifiedActions.push(baseHistoryInfo);\n }\n };\n /**\n * Reverts this instance\n * @private\n */\n HistoryInfo.prototype.revert = function () {\n this.editorHistory.currentHistoryInfo = this;\n if (this.action === 'BordersAndShading') {\n this.owner.editorModule.isBordersAndShadingDialog = true;\n }\n if (!isNullOrUndefined(this.modifiedActions)) {\n if (this.editorHistory.isUndoing) {\n var i = this.modifiedActions.length;\n while (i > 0) {\n var baseHistoryInfo = this.modifiedActions[i - 1];\n baseHistoryInfo.revert();\n i = i - 1;\n }\n }\n else {\n var i = 0;\n while (i < this.modifiedActions.length) {\n var baseHistoryInfo = this.modifiedActions[i];\n baseHistoryInfo.revert();\n i = i + 1;\n }\n }\n }\n if (!this.isChildHistoryInfo) {\n this.editorHistory.updateComplexHistory();\n }\n else {\n this.editorHistory.updateComplexHistoryInternal();\n }\n };\n /**\n * @private\n */\n HistoryInfo.prototype.destroy = function () {\n if (!isNullOrUndefined(this.modifiedActions)) {\n while (this.modifiedActions.length > 0) {\n var baseHistoryInfo = this.modifiedActions[this.modifiedActions.length - 1];\n baseHistoryInfo.destroy();\n this.modifiedActions.splice(this.modifiedActions.indexOf(baseHistoryInfo), 1);\n }\n this.modifiedActions = undefined;\n }\n _super.prototype.destroy.call(this);\n };\n return HistoryInfo;\n}(BaseHistoryInfo));\nexport { HistoryInfo };\n","import { Dictionary } from '../../base/dictionary';\nimport { TextPosition } from '../selection/selection-helper';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { BaseHistoryInfo, } from './base-history-info';\nimport { ModifiedParagraphFormat, ModifiedLevel, RowHistoryFormat, TableHistoryInfo } from './history-helper';\nimport { HistoryInfo } from './history-info';\nimport { WParagraphFormat } from '../format/paragraph-format';\nimport { HelperMethods } from '../editor/editor-helper';\n/**\n * `EditorHistory` Module class is used to handle history preservation\n */\nvar EditorHistory = /** @class */ (function () {\n /**\n * @private\n */\n function EditorHistory(node) {\n //Fields\n this.undoStackIn = [];\n this.redoStackIn = [];\n this.historyInfoStack = [];\n /**\n * @private\n */\n this.isUndoing = false;\n /**\n * @private\n */\n this.isRedoing = false;\n this.owner = node;\n this.viewer = node.viewer;\n this.modifiedParaFormats = new Dictionary();\n this.undoLimitIn = 500;\n this.redoLimitIn = 500;\n }\n Object.defineProperty(EditorHistory.prototype, \"currentHistoryInfo\", {\n /**\n * @private\n */\n get: function () {\n return this.historyInfoStack && this.historyInfoStack.length > 0 ?\n this.historyInfoStack[this.historyInfoStack.length - 1] : undefined;\n },\n set: function (value) {\n if (value instanceof HistoryInfo) {\n this.historyInfoStack.push(value);\n }\n else {\n this.historyInfoStack.pop();\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EditorHistory.prototype, \"undoStack\", {\n //Properties\n /**\n * gets undo stack\n * @private\n */\n get: function () { return this.undoStackIn; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EditorHistory.prototype, \"redoStack\", {\n /**\n * gets redo stack\n * @private\n */\n get: function () { return this.redoStackIn; },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EditorHistory.prototype, \"undoLimit\", {\n /**\n * Gets or Sets the limit of undo operations can be done.\n */\n get: function () {\n return isNullOrUndefined(this.undoLimitIn) ? 0 : this.undoLimitIn;\n },\n set: function (value) {\n if (value < 0) {\n throw new Error('The limit should be greater than or equal to zero.');\n }\n this.undoLimitIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(EditorHistory.prototype, \"redoLimit\", {\n /**\n * Gets or Sets the limit of redo operations can be done.\n */\n get: function () {\n return isNullOrUndefined(this.redoLimitIn) ? 0 : this.redoLimitIn;\n },\n set: function (value) {\n if (value < 0) {\n throw new Error('The limit should be greater than or equal to zero.');\n }\n this.redoLimitIn = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n EditorHistory.prototype.getModuleName = function () {\n return 'EditorHistory';\n };\n /**\n * Determines whether undo operation can be done.\n * @returns boolean\n */\n EditorHistory.prototype.canUndo = function () {\n return !isNullOrUndefined(this.undoStack) && this.undoStack.length > 0;\n };\n /**\n * Determines whether redo operation can be done.\n * @returns boolean\n */\n EditorHistory.prototype.canRedo = function () {\n return !isNullOrUndefined(this.redoStack) && this.redoStack.length > 0;\n };\n //EditorHistory Initialization \n /**\n * initialize EditorHistory\n * @param {Selection} selection\n * @param {Action} action\n * @param {SelectionRange} selectionRange\n * @private\n */\n EditorHistory.prototype.initializeHistory = function (action) {\n this.currentBaseHistoryInfo = new BaseHistoryInfo(this.owner);\n this.currentBaseHistoryInfo.action = action;\n this.currentBaseHistoryInfo.updateSelection();\n };\n /**\n * Initialize complex history\n * @param {Selection} selection\n * @param {Action} action\n * @private\n */\n EditorHistory.prototype.initComplexHistory = function (selection, action) {\n this.currentHistoryInfo = new HistoryInfo(selection.owner, !isNullOrUndefined(this.currentHistoryInfo));\n this.currentHistoryInfo.action = action;\n this.currentHistoryInfo.updateSelection();\n };\n /**\n * @private\n */\n EditorHistory.prototype.initResizingHistory = function (startingPoint, tableResize) {\n if (tableResize.resizeNode === 1) {\n this.initializeHistory('RowResizing');\n if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {\n // tslint:disable-next-line:max-line-length\n this.currentBaseHistoryInfo.modifiedProperties.push(new RowHistoryFormat(startingPoint, tableResize.currentResizingTable.childWidgets[tableResize.resizerPosition].rowFormat));\n }\n }\n else {\n this.initializeHistory('CellResizing');\n if (this.currentBaseHistoryInfo) {\n tableResize.currentResizingTable = tableResize.currentResizingTable.combineWidget(this.viewer);\n var tableHistoryInfo = new TableHistoryInfo(tableResize.currentResizingTable, this.owner);\n tableHistoryInfo.startingPoint = startingPoint;\n this.currentBaseHistoryInfo.modifiedProperties.push(tableHistoryInfo);\n }\n }\n };\n /**\n * Update resizing history\n * @param {Point} point\n * @param {Selection} selection\n * @private\n */\n EditorHistory.prototype.updateResizingHistory = function (point, tableResize) {\n if (tableResize.resizeNode === 1) {\n if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {\n var rowHistoryFormat = this.currentBaseHistoryInfo.modifiedProperties[0];\n if (rowHistoryFormat.startingPoint.y === point.y) {\n this.currentBaseHistoryInfo.modifiedProperties.length = 0;\n }\n else {\n rowHistoryFormat.displacement = HelperMethods.convertPixelToPoint(point.y - rowHistoryFormat.startingPoint.y);\n this.recordChanges(this.currentBaseHistoryInfo);\n this.currentBaseHistoryInfo = undefined;\n }\n }\n }\n else {\n if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {\n var cellHistoryFormat = this.currentBaseHistoryInfo.modifiedProperties[0];\n if (cellHistoryFormat.startingPoint.x === point.x) {\n this.currentBaseHistoryInfo.modifiedProperties.length = 0;\n }\n else {\n cellHistoryFormat.displacement = HelperMethods.convertPixelToPoint(point.x - cellHistoryFormat.startingPoint.x);\n cellHistoryFormat.endIndex = tableResize.getCellReSizerPosition(point);\n this.owner.editorHistory.recordChanges(this.currentBaseHistoryInfo);\n this.currentBaseHistoryInfo = undefined;\n }\n }\n }\n };\n /**\n * Record the changes\n * @param {BaseHistoryInfo} baseHistoryInfo\n * @private\n */\n EditorHistory.prototype.recordChanges = function (baseHistoryInfo) {\n if (!this.owner.enableHistoryMode) {\n return;\n }\n if (this.isUndoing) {\n if (isNullOrUndefined(this.redoStack)) {\n this.redoStackIn = [];\n }\n if (this.redoStack.length === this.redoLimit && this.redoLimit > 0) {\n var count = this.undoLimit > 20 ? 10 : 1;\n this.redoStackIn.splice(0, count);\n }\n if (this.redoStack.length < this.redoLimit) {\n this.redoStack.push(baseHistoryInfo);\n }\n }\n else {\n if (!this.isRedoing) {\n this.clearRedoStack();\n }\n if (isNullOrUndefined(this.undoStack)) {\n this.undoStackIn = [];\n }\n if (this.undoStack.length === this.undoLimit && this.undoLimit > 0) {\n var count = this.undoLimit > 20 ? 10 : 1;\n this.undoStackIn.splice(0, count);\n }\n if (this.undoStack.length < this.undoLimit) {\n this.undoStackIn.push(baseHistoryInfo);\n }\n }\n };\n /**\n * update EditorHistory\n * @private\n */\n EditorHistory.prototype.updateHistory = function () {\n if (this.viewer.owner.enableHistoryMode && !isNullOrUndefined(this.currentBaseHistoryInfo)) {\n //Updates the current end position\n if (!isNullOrUndefined(this.currentBaseHistoryInfo)\n && isNullOrUndefined(this.currentBaseHistoryInfo.endPosition)) {\n this.currentBaseHistoryInfo.endPosition = this.currentBaseHistoryInfo.insertPosition;\n }\n if (!isNullOrUndefined(this.currentHistoryInfo)) {\n this.currentHistoryInfo.addModifiedAction(this.currentBaseHistoryInfo);\n }\n else {\n this.recordChanges(this.currentBaseHistoryInfo);\n }\n this.currentBaseHistoryInfo = undefined;\n }\n };\n /**\n * @private\n */\n EditorHistory.prototype.isHandledComplexHistory = function () {\n var isHandledComplexHistory = false;\n if (!(this.isUndoing || this.isRedoing)) {\n isHandledComplexHistory = this.owner.editorModule.insertRemoveBookMarkElements();\n }\n if (this.viewer.owner.enableHistoryMode && !isNullOrUndefined(this.currentHistoryInfo)) {\n this.updateHistory();\n isHandledComplexHistory = true;\n }\n else if (this.owner.editorModule.isHandledComplex) {\n isHandledComplexHistory = true;\n }\n return isHandledComplexHistory;\n };\n /**\n * Update complex history\n * @private\n */\n EditorHistory.prototype.updateComplexHistory = function () {\n var selection = this.viewer.selection;\n if (this.currentHistoryInfo.hasAction) {\n if (this.currentHistoryInfo.action === 'AutoFormatHyperlink') {\n var startPosition = new TextPosition(selection.owner);\n this.owner.editorModule.setPositionForCurrentIndex(startPosition, this.currentHistoryInfo.insertPosition);\n // this.reLayoutParagraph(startPosition.paragraph, 0);\n if (selection.owner.editorHistory.isUndoing) {\n this.owner.editorModule.setPositionForCurrentIndex(selection.start, this.currentHistoryInfo.selectionStart);\n this.owner.editorModule.setPositionForCurrentIndex(selection.end, this.currentHistoryInfo.selectionEnd);\n }\n else {\n this.owner.editorModule.setPositionForCurrentIndex(selection.start, this.currentHistoryInfo.endPosition);\n this.owner.editorModule.setPositionForCurrentIndex(selection.end, this.currentHistoryInfo.endPosition);\n }\n }\n if (this.currentHistoryInfo.action === 'InsertHyperlink') {\n var startPosition = new TextPosition(selection.owner);\n this.owner.editorModule.setPositionForCurrentIndex(startPosition, this.currentHistoryInfo.insertPosition);\n var endPosition = new TextPosition(selection.owner);\n this.owner.editorModule.setPositionForCurrentIndex(endPosition, this.currentHistoryInfo.endPosition);\n this.viewer.layout.reLayoutParagraph(startPosition.paragraph, 0, 0);\n if (endPosition.paragraph !== startPosition.paragraph) {\n this.viewer.layout.reLayoutParagraph(endPosition.paragraph, 0, 0);\n }\n }\n if (this.currentHistoryInfo.action === 'ReplaceAll') {\n this.owner.editorModule.layoutWholeDocument();\n }\n else if (selection.owner.isShiftingEnabled) {\n this.viewer.layout.shiftLayoutedItems();\n if (this.owner.enableHeaderAndFooter) {\n this.owner.editorModule.updateHeaderFooterWidget();\n }\n }\n }\n selection.owner.isShiftingEnabled = false;\n selection.owner.isLayoutEnabled = true;\n // // selection.addMultipleSelectionRanges();\n selection.start.updatePhysicalPosition(true);\n if (selection.isEmpty) {\n selection.end.setPositionInternal(selection.start);\n }\n else {\n selection.end.updatePhysicalPosition(true);\n }\n selection.upDownSelectionLength = selection.end.location.x;\n this.viewer.updateScrollBars();\n selection.fireSelectionChanged(true);\n this.viewer.updateFocus();\n this.updateComplexHistoryInternal();\n this.owner.editorModule.fireContentChange();\n };\n /**\n * @private\n */\n EditorHistory.prototype.updateComplexHistoryInternal = function () {\n if (!isNullOrUndefined(this.currentHistoryInfo)) {\n //Updates the current end position\n if (isNullOrUndefined(this.currentHistoryInfo.endPosition)) {\n this.currentHistoryInfo.endPosition = this.currentHistoryInfo.insertPosition;\n }\n if (this.historyInfoStack.length > 1) {\n var historyInfo = this.historyInfoStack[this.historyInfoStack.length - 2];\n historyInfo.addModifiedAction(this.currentHistoryInfo);\n }\n else {\n this.recordChanges(this.currentHistoryInfo);\n }\n this.currentHistoryInfo = undefined;\n }\n };\n //List history preservation undo API\n /**\n * update list changes for history preservation\n * @param {Selection} selection\n * @param {WAbstractList} currentAbstractList\n * @param {WList} list\n * @private\n */\n EditorHistory.prototype.updateListChangesInHistory = function (currentAbstractList, list) {\n this.currentBaseHistoryInfo = new BaseHistoryInfo(this.viewer.owner);\n this.currentBaseHistoryInfo.action = 'List';\n this.currentBaseHistoryInfo.updateSelection();\n var collection = new Dictionary();\n for (var i = 0; i < currentAbstractList.levels.length; i++) {\n var levels = this.viewer.getAbstractListById(list.abstractListId).levels[i];\n var value = this.currentBaseHistoryInfo.addModifiedPropertiesForList(levels);\n var modifiedLevel = new ModifiedLevel(levels, currentAbstractList.levels[i]);\n if (!isNullOrUndefined(levels)) {\n this.viewer.owner.editorModule.copyListLevel(levels, currentAbstractList.levels[i]);\n }\n collection.add(i, modifiedLevel);\n }\n return collection;\n };\n /**\n * Apply list changes\n * @param {Selection} selection\n * @param {Dictionary} modifiedLevelsInternal\n * @private\n */\n EditorHistory.prototype.applyListChanges = function (selection, modifiedLevelsInternal) {\n if (isNullOrUndefined(this.modifiedParaFormats)) {\n this.modifiedParaFormats = new Dictionary();\n }\n var collection = [];\n for (var i = 0; i < this.viewer.listParagraphs.length; i++) {\n var paragraph = this.viewer.listParagraphs[i];\n var paraFormat = paragraph.paragraphFormat;\n var currentList = this.viewer.getListById(paraFormat.listFormat.listId);\n var listLevel = this.viewer.layout.getListLevel(currentList, paraFormat.listFormat.listLevelNumber);\n // tslint:disable-next-line:max-line-length\n if (modifiedLevelsInternal.containsKey(paraFormat.listFormat.listLevelNumber)\n && modifiedLevelsInternal.get(paraFormat.listFormat.listLevelNumber).ownerListLevel === listLevel) {\n var modifiedFormat = new WParagraphFormat(null);\n modifiedFormat.leftIndent = paraFormat.leftIndent;\n modifiedFormat.firstLineIndent = paraFormat.firstLineIndent;\n var modified = new ModifiedParagraphFormat(paraFormat, modifiedFormat);\n collection.push(modified);\n this.owner.editorModule.copyFromListLevelParagraphFormat(paraFormat, listLevel.paragraphFormat);\n }\n }\n this.modifiedParaFormats.add(this.currentBaseHistoryInfo, collection);\n };\n /**\n * Update list changes\n * @param {Dictionary} modifiedCollection\n * @param {Selection} selection\n * @private\n */\n EditorHistory.prototype.updateListChanges = function (modifiedCollection) {\n this.viewer.owner.isLayoutEnabled = false;\n this.owner.editorModule.updateListParagraphs();\n for (var i = 0; i < modifiedCollection.keys.length; i++) {\n var levelNumber = modifiedCollection.keys[0];\n var modifiedLevel = modifiedCollection.get(levelNumber);\n if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {\n // tslint:disable-next-line:max-line-length\n modifiedLevel = this.currentBaseHistoryInfo.addModifiedPropertiesForList(modifiedLevel.ownerListLevel);\n }\n this.owner.editorModule.copyListLevel(modifiedLevel.ownerListLevel, modifiedLevel.modifiedListLevel);\n }\n this.revertListChanges();\n this.viewer.owner.isLayoutEnabled = true;\n this.viewer.renderedLists.clear();\n this.viewer.pages = [];\n this.viewer.layout.layout();\n var selection = this.viewer.selection;\n selection.start.updatePhysicalPosition(true);\n if (selection.isEmpty) {\n selection.end.setPositionInternal(selection.start);\n }\n else {\n selection.end.updatePhysicalPosition(true);\n }\n selection.upDownSelectionLength = selection.end.location.x;\n selection.fireSelectionChanged(false);\n this.updateHistory();\n };\n /**\n * Revert list changes\n * @param {Selection} selection\n */\n EditorHistory.prototype.revertListChanges = function () {\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(this.currentBaseHistoryInfo)\n && this.viewer.owner.editorHistory.modifiedParaFormats.containsKey(this.currentBaseHistoryInfo)) {\n // tslint:disable-next-line:max-line-length\n var collection = this.modifiedParaFormats.get(this.currentBaseHistoryInfo);\n for (var i = 0; i < collection.length; i++) {\n var modified = new WParagraphFormat(null);\n modified.leftIndent = collection[i].ownerFormat.leftIndent;\n modified.firstLineIndent = collection[i].ownerFormat.firstLineIndent;\n collection[i].ownerFormat.copyFormat(collection[i].modifiedFormat);\n collection[i].modifiedFormat.leftIndent = modified.leftIndent;\n collection[i].modifiedFormat.firstLineIndent = modified.firstLineIndent;\n }\n }\n };\n /**\n * Reverts the last editing action.\n */\n EditorHistory.prototype.undo = function () {\n if (this.owner.isReadOnlyMode || !this.canUndo() || !this.owner.enableHistoryMode) {\n return;\n }\n //this.owner.ClearTextSearchResults();\n var historyInfo = this.undoStack.pop();\n this.isUndoing = true;\n historyInfo.revert();\n this.isUndoing = false;\n this.owner.selection.checkForCursorVisibility();\n this.owner.editorModule.isBordersAndShadingDialog = false;\n };\n /**\n * Performs the last reverted action.\n */\n EditorHistory.prototype.redo = function () {\n if (this.owner.isReadOnlyMode || !this.canRedo() || !this.owner.enableHistoryMode) {\n return;\n }\n //this.owner.ClearTextSearchResults();\n var historyInfo = this.redoStack.pop();\n if (historyInfo.action === 'BordersAndShading') {\n this.owner.editorModule.isBordersAndShadingDialog = true;\n }\n this.isRedoing = true;\n historyInfo.revert();\n this.isRedoing = false;\n this.owner.selection.checkForCursorVisibility();\n this.owner.editorModule.isBordersAndShadingDialog = false;\n };\n /**\n * @private\n */\n EditorHistory.prototype.destroy = function () {\n this.clearHistory();\n this.undoStackIn = undefined;\n this.redoStackIn = undefined;\n };\n EditorHistory.prototype.clearHistory = function () {\n this.clearUndoStack();\n this.clearRedoStack();\n };\n EditorHistory.prototype.clearUndoStack = function () {\n if (this.canUndo()) {\n while (this.undoStack.length > 0) {\n var historyInfo = this.undoStack.pop();\n historyInfo.destroy();\n historyInfo = undefined;\n }\n }\n };\n EditorHistory.prototype.clearRedoStack = function () {\n if (this.canRedo()) {\n while (this.redoStack.length > 0) {\n var historyInfo = this.redoStack.pop();\n historyInfo.destroy();\n historyInfo = undefined;\n }\n }\n };\n return EditorHistory;\n}());\nexport { EditorHistory };\n","import { ZipArchive, ZipArchiveItem } from '@syncfusion/ej2-compression';\nimport { XmlWriter } from '@syncfusion/ej2-file-utils';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Dictionary } from '../../index';\n/**\n * Exports the document to Word format.\n */\nvar WordExport = /** @class */ (function () {\n function WordExport() {\n //Part path\n this.documentPath = 'word/document.xml';\n this.stylePath = 'word/styles.xml';\n this.numberingPath = 'word/numbering.xml';\n this.settingsPath = 'word/settings.xml';\n this.headerPath = 'word/header';\n this.footerPath = 'word/footer';\n //private commentsPath: string = 'word/comments.xml';\n this.imagePath = 'word/media/image';\n // private footnotesPath: string = 'word/footnotes.xml';\n // private endnotesPath: string = 'word/endnotes.xml';\n this.appPath = 'docProps/app.xml';\n this.corePath = 'docProps/core.xml';\n // private CustomPath: string = 'docProps/custom.xml';\n // private FontTablePath: string = 'word/fontTable.xml';\n this.contentTypesPath = '[Content_Types].xml';\n // private ChartsPath: string = 'word/charts/';\n // private DefaultEmbeddingPath: string = 'word/embeddings/';\n // private EmbeddingPath:string = 'word\\embeddings\\';\n // private DrawingPath:string = 'word\\drawings\\';\n // private ThemePath: string = 'word/theme/theme1.xml';\n // private FontsPath:string = 'word\\fonts\\';\n // private DiagramPath:string = \"word/diagrams/';\n // private ControlPath:string = \"word/activeX/';\n // private VbaProject: string = 'vbaProject.bin';\n // private VbaData: string = 'vbaData.xml';\n // private VbaProjectPath: string = 'word/vbaProject.bin';\n // private VbaDataPath: string = 'word/vbaData.xml';\n // private CustomXMLPath:string = 'customXml\\';\n //Relationship path\n this.generalRelationPath = '_rels/.rels';\n this.wordRelationPath = 'word/_rels/document.xml.rels';\n // private FontRelationPath: string = 'word/_rels/fontTable.xml.rels';\n // private CommentsRelationPath: string = 'word/_rels/comments.xml.rels';\n // private FootnotesRelationPath: string = 'word/_rels/footnotes.xml.rels';\n // private EndnotesRelationPath: string = 'word/_rels/endnotes.xml.rels';\n // private NumberingRelationPath: string = 'word/_rels/numbering.xml.rels';\n this.headerRelationPath = 'word/_rels/header';\n this.footerRelationPath = 'word/_rels/footer';\n // private SettingsRelationpath: string = 'word/_rels/settings.xml.rels';\n // private VbaProjectRelsPath: string = 'word/_rels/vbaProject.bin.rels';\n //Content type of the parts\n this.xmlContentType = 'application/xml';\n this.fontContentType = 'application/vnd.openxmlformats-officedocument.obfuscatedFont';\n this.documentContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml';\n // private TemplateContentType: string = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml';\n // private CommentsContentType: string = 'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml';\n this.settingsContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml';\n // private EndnoteContentType: string = 'application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml';\n // private FontTableContentType: string = 'application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml';\n this.footerContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml';\n // private FootnoteContentType: string = 'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml';\n // private GlossaryDocumentContentType: string = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml';\n this.headerContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml';\n this.numberingContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml';\n this.stylesContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml';\n this.webSettingsContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml';\n this.appContentType = 'application/vnd.openxmlformats-officedocument.extended-properties+xml';\n this.coreContentType = 'application/vnd.openxmlformats-package.core-properties+xml';\n this.customContentType = 'application/vnd.openxmlformats-officedocument.custom-properties+xml';\n this.customXmlContentType = 'application/vnd.openxmlformats-officedocument.customXmlProperties+xml';\n this.relationContentType = 'application/vnd.openxmlformats-package.relationships+xml';\n // private DiagramColor: string = 'application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml';\n // private DiagramData: string = 'application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml';\n // private DiagramLayout: string = 'application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml';\n // private DiagramStyle: string = 'application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml';\n // private ChartsContentType: string = 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml';\n // private ThemeContentType: string = 'application/vnd.openxmlformats-officedocument.theme+xml';\n // private ChartDrawingContentType: string = 'application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml';\n // private ActiveXContentType: string = 'application/vnd.ms-office.activeX+xml';\n // private ActiveXBinContentType: string = 'application/vnd.ms-office.activeX';\n this.tableStyleContentType = 'application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml';\n // private ChartStyleContentType: string = 'application/vnd.ms-office.chartstyle+xml';\n // private ChartColorStyleContentType: string = 'application/vnd.ms-office.chartcolorstyle+xml';\n // private VbaProjectContentType: string = 'application/vnd.ms-office.vbaProject';\n // private VbaDataContentType: string = 'application/vnd.ms-word.vbaData+xml';\n // private MacroDocumentContentType: string = 'application/vnd.ms-word.document.macroEnabled.main+xml';\n // private MacroTemplateContentType: string = 'application/vnd.ms-word.template.macroEnabledTemplate.main+xml';\n // private OleObjectContentType: string = 'application/vnd.openxmlformats-officedocument.oleObject';\n // Relationship types of document parts\n // private AltChunkRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk';\n // private CommentsRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments';\n this.settingsRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings';\n // private EndnoteRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes';\n // private FontTableRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable';\n this.footerRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer';\n // private FootnoteRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes';\n this.headerRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/header';\n this.documentRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';\n this.numberingRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering';\n this.stylesRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles';\n // private OleObjectRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject';\n // private ChartRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart';\n // private ThemeRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme';\n this.fontRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/font';\n this.tableStyleRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles';\n this.coreRelType = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';\n this.appRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties';\n this.customRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties';\n this.imageRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image';\n this.hyperlinkRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink';\n this.controlRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/control';\n this.packageRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/package';\n // private VbaProjectRelType: string = 'http://schemas.microsoft.com/office/2006/relationships/vbaProject';\n // private VbaDataRelType: string = 'http://schemas.microsoft.com/office/2006/relationships/wordVbaData';\n this.customXmlRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml';\n this.customUIRelType = 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility';\n this.attachedTemplateRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate';\n // private ChartColorStyleRelType: string = 'http://schemas.microsoft.com/office/2011/relationships/chartColorStyle';\n // private ChartStyleRelType: string = 'http://schemas.microsoft.com/office/2011/relationships/chartStyle';\n // private ChartUserShapesRelType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartUserShapes';\n // private ChartContentType: string = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/package';\n // Namespaces\n // private PKG_namespace: string = 'http://schemas.microsoft.com/office/2006/xmlPackage';\n this.wNamespace = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';\n this.wpNamespace = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing';\n this.pictureNamespace = 'http://schemas.openxmlformats.org/drawingml/2006/picture';\n this.aNamespace = 'http://schemas.openxmlformats.org/drawingml/2006/main';\n this.a14Namespace = 'http://schemas.microsoft.com/office/drawing/2010/main';\n // private SVG_namespace: string = 'http://schemas.microsoft.com/office/drawing/2016/SVG/main';\n this.rNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';\n this.rpNamespace = 'http://schemas.openxmlformats.org/package/2006/relationships';\n this.vNamespace = 'urn:schemas-microsoft-com:vml';\n this.oNamespace = 'urn:schemas-microsoft-com:office:office';\n this.xmlNamespace = 'http://www.w3.org/XML/1998/namespace';\n this.w10Namespace = 'urn:schemas-microsoft-com:office:word';\n this.cpNamespace = 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties';\n this.dcNamespace = 'http://purl.org/dc/elements/1.1/';\n // private DCTERMS_namespace: string = 'http://purl.org/dc/terms/';\n // private XSI_namespace: string = 'http://www.w3.org/2001/XMLSchema-instance';\n this.docPropsNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties';\n this.veNamespace = 'http://schemas.openxmlformats.org/markup-compatibility/2006';\n this.mNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/math';\n this.wneNamespace = 'http://schemas.microsoft.com/office/word/2006/wordml';\n // private DCMI_namespace: string = 'http://purl.org/dc/dcmitype/';\n this.customPropsNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties';\n this.vtNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes';\n this.chartNamespace = 'http://schemas.openxmlformats.org/drawingml/2006/chart';\n this.slNamespace = 'http://schemas.openxmlformats.org/schemaLibrary/2006/main';\n //2003WML namespace\n // private amlNamespace: string = 'http://schemas.microsoft.com/aml/2001/core';\n this.dtNamespace = 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882';\n this.wmlNamespace = 'http://schemas.microsoft.com/office/word/2003/wordml';\n //2010 namespaces\n this.w14Namespace = 'http://schemas.microsoft.com/office/word/2010/wordml';\n this.wpCanvasNamespace = 'http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas';\n this.wpDrawingNamespace = 'http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing';\n this.wpGroupNamespace = 'http://schemas.microsoft.com/office/word/2010/wordprocessingGroup';\n this.wpInkNamespace = 'http://schemas.microsoft.com/office/word/2010/wordprocessingInk';\n this.wpShapeNamespace = 'http://schemas.microsoft.com/office/word/2010/wordprocessingShape';\n //2013 namespaces\n this.w15Namespace = 'http://schemas.microsoft.com/office/word/2012/wordml';\n this.diagramNamespace = 'http://schemas.openxmlformats.org/drawingml/2006/diagram';\n //Encryption namespaces\n this.eNamespace = 'http://schemas.microsoft.com/office/2006/encryption';\n this.pNamespace = 'http://schemas.microsoft.com/office/2006/keyEncryptor/password';\n this.certNamespace = 'http://schemas.microsoft.com/office/2006/keyEncryptor/certificate';\n // Dls xml tags\n this.cRelationshipsTag = 'Relationships';\n this.cRelationshipTag = 'Relationship';\n this.cIdTag = 'Id';\n this.cTypeTag = 'Type';\n this.cTargetTag = 'Target';\n this.cUserShapesTag = 'userShapes';\n this.cExternalData = 'externalData';\n this.twipsInOnePoint = 20;\n this.twentiethOfPoint = 20;\n this.borderMultiplier = 8;\n this.percentageFactor = 50;\n this.emusPerPoint = 12700;\n // private const TOC_SYMBOL:string = (char)0x01;\n // private const FOOTNOTE_SYMBOL:string = (char)0x02;\n // private const PAGENUMBER_SYMBOL:string = (char)0xB;\n // private DEF_FIT_TEXT_TO_SHAPE: string = 'mso-fit-shape-to-text:t';\n // Document tags\n this.cConditionalTableStyleTag = 'tblStylePr';\n this.cTableFormatTag = 'tblPr';\n this.cTowFormatTag = 'trPr';\n this.cCellFormatTag = 'tcPr';\n this.cParagraphFormatTag = 'pPr';\n this.cCharacterFormatTag = 'rPr';\n this.packageType = 'http://schemas.microsoft.com/office/2006/xmlPackage';\n this.relsPartPath = '/_rels/.rels';\n this.documentRelsPartPath = '/word/_rels/document.xml.rels';\n this.webSettingsPath = '/word/webSettings.xml';\n this.wordMLDocumentPath = '/word/document.xml';\n this.wordMLStylePath = '/word/styles.xml';\n this.wordMLNumberingPath = '/word/numbering.xml';\n this.wordMLSettingsPath = '/word/settings.xml';\n this.wordMLHeaderPath = '/word/header';\n this.wordMLFooterPath = '/word/footer';\n this.wordMLCommentsPath = '/word/comments.xml';\n this.wordMLImagePath = '/word/media/image';\n this.wordMLFootnotesPath = '/word/footnotes.xml';\n this.wordMLEndnotesPath = '/word/endnotes.xml';\n this.wordMLAppPath = '/docProps/app.xml';\n this.wordMLCorePath = '/docProps/core.xml';\n this.wordMLCustomPath = '/docProps/custom.xml';\n this.wordMLFontTablePath = '/word/fontTable.xml';\n this.wordMLChartsPath = '/word/charts/';\n this.wordMLDefaultEmbeddingPath = '/word/embeddings/';\n this.wordMLEmbeddingPath = '/word/embeddings/';\n this.wordMLDrawingPath = '/word/drawings/';\n this.wordMLThemePath = '/word/theme/theme1.xml';\n this.wordMLFontsPath = '/word/fonts/';\n this.wordMLDiagramPath = '/word/diagrams/';\n this.wordMLControlPath = '/word/activeX/';\n this.wordMLVbaProject = '/vbaProject.bin';\n this.wordMLVbaData = '/vbaData.xml';\n this.wordMLVbaProjectPath = '/word/vbaProject.bin';\n this.wordMLVbaDataPath = '/word/vbaData.xml';\n // private WordMLCustomXMLPath: string = '/customXml/';\n this.wordMLWebSettingsPath = '/word/webSettings.xml';\n this.wordMLCustomItemProp1Path = '/customXml/itemProps1.xml';\n // private WordMLCustomXMLRelPath: string = '/customXml/_rels/item1.xml.rels';\n this.wordMLFootnoteRelPath = '/word/_rels/footnotes.xml.rels';\n this.wordMLEndnoteRelPath = '/word/_rels/endnotes.xml.rels';\n this.wordMLSettingsRelPath = '/word/_rels/settings.xml.rels';\n this.wordMLNumberingRelPath = '/word/_rels/numbering.xml.rels';\n this.wordMLFontTableRelPath = '/word/_rels/fontTable.xml.rels';\n this.wordMLCustomXmlPropsRelType = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps';\n this.wordMLControlRelType = 'http://schemas.microsoft.com/office/2006/relationships/activeXControlBinary';\n this.wordMLDiagramContentType = 'application/vnd.ms-office.drawingml.diagramDrawing+xml';\n this.lastSection = false;\n this.mRelationShipID = 0;\n this.mDocPrID = 0;\n this.mDifferentFirstPage = false;\n this.mBookmarks = undefined;\n /* tslint:enable:no-any */\n }\n WordExport.prototype.getModuleName = function () {\n return 'WordExport';\n };\n Object.defineProperty(WordExport.prototype, \"bookmarks\", {\n // Gets the bookmark name\n get: function () {\n if (isNullOrUndefined(this.mBookmarks)) {\n this.mBookmarks = [];\n }\n return this.mBookmarks;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WordExport.prototype, \"documentImages\", {\n // Gets the collection of images present in the document body\n get: function () {\n if (this.mDocumentImages === undefined) {\n this.mDocumentImages = new Dictionary();\n }\n return this.mDocumentImages;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WordExport.prototype, \"externalImages\", {\n // Gets the collection of images present in the document body\n get: function () {\n if (this.mExternalLinkImages === undefined) {\n this.mExternalLinkImages = new Dictionary();\n }\n return this.mExternalLinkImages;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WordExport.prototype, \"headerFooterImages\", {\n // Gets the collections of images present in the HeaderFooters\n get: function () {\n if (this.mHeaderFooterImages === undefined) {\n this.mHeaderFooterImages = new Dictionary();\n }\n return this.mHeaderFooterImages;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(WordExport.prototype, \"headersFooters\", {\n /// Gets the HeaderFooter Collection\n get: function () {\n if (this.mHeaderFooterColl === undefined) {\n this.mHeaderFooterColl = new Dictionary();\n }\n return this.mHeaderFooterColl;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n WordExport.prototype.save = function (viewer, fileName) {\n this.serialize(viewer);\n this.mArchive.save(fileName + '.docx').then(function (mArchive) {\n mArchive.destroy();\n });\n this.close();\n };\n /**\n * @private\n */\n WordExport.prototype.saveAsBlob = function (viewer) {\n var _this = this;\n this.serialize(viewer);\n return new Promise(function (resolve, reject) {\n _this.mArchive.saveAsBlob().then(function (blob) {\n _this.mArchive.destroy();\n blob = new Blob([blob], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });\n resolve(blob);\n });\n });\n };\n /**\n * @private\n */\n WordExport.prototype.destroy = function () {\n this.clearDocument();\n this.mRelationShipID = undefined;\n this.mDocPrID = undefined;\n this.mDifferentFirstPage = undefined;\n if (this.mArchive) {\n this.mArchive.destroy();\n this.mArchive = undefined;\n }\n };\n // Saves the word document in the stream\n WordExport.prototype.serialize = function (viewer) {\n /* tslint:disable:no-any */\n var document = viewer.owner.sfdtExportModule.write();\n this.setDocument(document);\n this.mArchive = new ZipArchive();\n this.mArchive.compressionLevel = 'Normal';\n this.mVerticalMerge = new Dictionary();\n this.mGridSpans = new Dictionary();\n var contenttype;\n //document.xml\n this.serializeDocument();\n //Styles.xml\n this.serializeStyles();\n //numbering.xml\n this.serializeNumberings();\n //theme.xml\n // if (m_document.DocHasThemes && !isNullOrUndefined(m_document.Themes))\n // SerializeThemes();\n // else\n // this.serializeDefaultThemes();\n //settings.xml\n this.serializeSettings();\n //core.xml\n this.serializeCoreProperties();\n //app.xml\n this.serializeAppProperties();\n //fontTable.xml\n this.serializeFontTable(contenttype);\n //custom.xml\n // if (!isNullOrUndefined(this.wordDocument.CustomDocumentProperties) && m_document.CustomDocumentProperties.length > 0) {\n // SerializeCustomProperties();\n // }\n //Settings Relations\n this.serializeSettingsRelation();\n //Numbering relation if the document has picture bullet\n // if (PictureBullets.length > 0) {\n // SerializeNumberingsRelation();\n // }\n this.serializeHeaderFooters();\n //document relations\n this.serializeDocumentRelations();\n // // Add controls to archieve.\n // if (ControlsPathNames.length > 0) {\n // AddControlsToZip(m_document.DocxPackage);\n // }\n // if (!isNullOrUndefined(m_document.CustomUIPartContainer))\n // AddPartContainerToArchive(m_document.CustomUIPartContainer);\n // if (!isNullOrUndefined(m_document.CustomXMLContainer))\n // AddPartContainerToArchive(m_document.CustomXMLContainer);\n //general relations\n this.serializeGeneralRelations();\n //[ContentTypes].xml\n this.serializeContentTypes(contenttype);\n // Clears the internal fields maintained for serializing.\n this.clearDocument();\n };\n // Sets the document\n WordExport.prototype.setDocument = function (document) {\n this.document = document;\n this.mSections = document.sections;\n this.mLists = document.lists;\n this.mAbstractLists = document.abstractLists;\n this.defCharacterFormat = document.characterFormat;\n this.defParagraphFormat = document.paragraphFormat;\n this.defaultTabWidthValue = document.defaultTabWidth;\n this.mStyles = document.styles;\n };\n // Clears the document\n WordExport.prototype.clearDocument = function () {\n // Owner Nodes\n this.section = undefined;\n this.lastSection = undefined;\n this.blockOwner = undefined;\n this.paragraph = undefined;\n this.table = undefined;\n this.row = undefined;\n this.headerFooter = undefined;\n this.document = undefined;\n this.mSections = undefined;\n this.mLists = undefined;\n this.mAbstractLists = undefined;\n this.defCharacterFormat = undefined;\n this.defParagraphFormat = undefined;\n this.defaultTabWidthValue = undefined;\n this.mRelationShipID = 0;\n this.mDocPrID = 0;\n this.mDifferentFirstPage = false;\n if (this.mHeaderFooterColl) {\n this.mHeaderFooterColl.destroy();\n this.mHeaderFooterColl = undefined;\n }\n if (this.mVerticalMerge) {\n this.mVerticalMerge.destroy();\n this.mVerticalMerge = undefined;\n }\n if (this.mGridSpans) {\n this.mGridSpans.destroy();\n this.mGridSpans = undefined;\n }\n if (this.mDocumentImages) {\n this.mDocumentImages.destroy();\n this.mDocumentImages = undefined;\n }\n if (this.mExternalLinkImages) {\n this.mExternalLinkImages.destroy();\n this.mExternalLinkImages = undefined;\n }\n if (this.mHeaderFooterImages) {\n this.mHeaderFooterImages.destroy();\n this.mHeaderFooterImages = undefined;\n }\n };\n // Serializes the document elements (document.xml)\n WordExport.prototype.serializeDocument = function () {\n var writer = new XmlWriter();\n writer.writeStartElement('w', 'document', this.wNamespace);\n this.writeCommonAttributeStrings(writer);\n this.serializeDocumentBody(writer);\n writer.writeEndElement(); //end of document tag\n var archiveItem = new ZipArchiveItem(writer.buffer, this.documentPath);\n this.mArchive.addItem(archiveItem);\n };\n WordExport.prototype.writeCommonAttributeStrings = function (writer) {\n writer.writeAttributeString('xmlns', 'wpc', undefined, this.wpCanvasNamespace);\n this.writeCustom(writer);\n writer.writeAttributeString('xmlns', 'wp14', undefined, this.wpDrawingNamespace);\n writer.writeAttributeString('xmlns', 'wp', undefined, this.wpNamespace);\n writer.writeAttributeString('xmlns', 'w10', undefined, this.w10Namespace);\n writer.writeAttributeString('xmlns', 'w', undefined, this.wNamespace);\n this.writeDup(writer);\n writer.writeAttributeString('xmlns', 'wne', undefined, this.wneNamespace);\n writer.writeAttributeString('xmlns', 'wps', undefined, this.wpShapeNamespace);\n writer.writeAttributeString('mc', 'Ignorable', undefined, 'w14 w15 wp14');\n };\n WordExport.prototype.writeDup = function (writer) {\n writer.writeAttributeString('xmlns', 'w14', undefined, this.w14Namespace);\n writer.writeAttributeString('xmlns', 'w15', undefined, this.w15Namespace);\n writer.writeAttributeString('xmlns', 'wpg', undefined, this.wpGroupNamespace);\n writer.writeAttributeString('xmlns', 'wpi', undefined, this.wpInkNamespace);\n };\n WordExport.prototype.writeCustom = function (writer) {\n writer.writeAttributeString('xmlns', 'mc', undefined, this.veNamespace);\n writer.writeAttributeString('xmlns', 'o', undefined, this.oNamespace);\n writer.writeAttributeString('xmlns', 'r', undefined, this.rNamespace);\n writer.writeAttributeString('xmlns', 'm', undefined, this.mNamespace);\n writer.writeAttributeString('xmlns', 'v', undefined, this.vNamespace);\n };\n // Serializes the document body\n WordExport.prototype.serializeDocumentBody = function (writer) {\n writer.writeStartElement(undefined, 'body', this.wNamespace);\n var count = this.document.sections.length;\n for (var i = 0; i < count; i++) {\n this.section = this.document.sections[i];\n this.lastSection = i === count - 1;\n this.serializeSection(writer, this.section, i === count - 1);\n this.section = undefined;\n }\n writer.writeEndElement();\n };\n // Serializes the Section.\n WordExport.prototype.serializeSection = function (writer, section, last) {\n this.blockOwner = section;\n this.serializeBodyItems(writer, section.blocks, last);\n if (last) {\n this.serializeSectionProperties(writer, section);\n }\n this.blockOwner = undefined;\n };\n // Serialize the section properties.\n WordExport.prototype.serializeSectionProperties = function (writer, section) {\n writer.writeStartElement('w', 'sectPr', this.wNamespace);\n if (section.headersFooters) {\n this.serializeHFReference(writer, section.headersFooters);\n }\n // if (IsNeedToSerializeSectionFootNoteProperties(section))\n // SerializeFootnoteProperties(section);\n // if (IsNeedToSerializeSectionEndNoteProperties(section))\n // SerializeEndnoteProperties(section);\n this.serializeSectionType(writer, 'nextPage');\n this.serializePageSetup(writer, section.sectionFormat);\n this.serializeColumns(writer, section);\n // this.serializeSectionProtection(section);\n // if (section.PageSetup.VerticalAlignment !== PageAlignment.Top) {\n // writer.writeStartElement('vAlign', this.wNamespace);\n // switch (section.PageSetup.VerticalAlignment) {\n // case PageAlignment.Top:\n // writer.WriteAttributeString('val', this.wNamespace, 'top');\n // break;\n // case PageAlignment.Middle:\n // writer.WriteAttributeString('val', this.wNamespace, 'center');\n // break;\n // case PageAlignment.Justified:\n // writer.WriteAttributeString('val', this.wNamespace, 'both');\n // break;\n // case PageAlignment.Bottom:\n // writer.WriteAttributeString('val', this.wNamespace, 'bottom');\n // break;\n // }\n // writer.WriteEndElement();\n // }\n if (section.sectionFormat !== undefined && section.sectionFormat.differentFirstPage) {\n writer.writeStartElement(undefined, 'titlePg', this.wNamespace);\n writer.writeEndElement();\n }\n // SerializeTextDirection(section);\n // if (section.PageSetup.Bidi) {\n // writer.WriteStartElement('bidi', this.wNamespace);\n // writer.WriteEndElement();\n // }\n //rtlGutter\n // SerializeDocGrid(section);\n //printerSettings\n writer.writeEndElement(); //end of sectPr tag\n };\n // Serialize the column properties of section.\n WordExport.prototype.serializeColumns = function (writer, section) {\n writer.writeStartElement(undefined, 'cols', this.wNamespace);\n writer.writeAttributeString(undefined, 'equalWidth', this.wNamespace, '1');\n writer.writeAttributeString(undefined, 'space', this.wNamespace, '0');\n writer.writeEndElement();\n // ColumnCollection columns = section.Columns;\n // writer.WriteStartElement('cols', this.wNamespace);\n // if (columns.length > 0)\n // {\n // writer.WriteAttributeString('num', this.wNamespace, columns.length.ToString());\n // }\n // if (section.PageSetup.DrawLinesBetweenCols)\n // writer.WriteAttributeString('sep', this.wNamespace, '1');\n // if (columns.OwnerSection.PageSetup.EqualColumnWidth)\n // {\n // writer.WriteAttributeString('equalWidth', this.wNamespace, '1');\n // //When the column count is negative, MS word just reset the column's count to zero\n // //To avoid index out of exception, checked the columns count\n // tslint:disable-next-line:max-line-length\n // writer.WriteAttributeString('space', this.wNamespace, ToString(columns.length > 0 ? columns[0].Space * this.TwentiethOfPoint : 0));\n // }\n // else if (columns.length > 0)\n // {\n // writer.WriteAttributeString('equalWidth', this.wNamespace, '0');\n // foreach (Column column in columns)\n // {\n // writer.WriteStartElement('col', this.wNamespace);\n // writer.WriteAttributeString('w', this.wNamespace, ToString(column.Width * this.TwentiethOfPoint));\n // tslint:disable-next-line:max-line-length\n // writer.WriteAttributeString('space', this.wNamespace, ToString(column.Space * this.TwentiethOfPoint));\n // writer.WriteEndElement();\n // }\n // }\n // writer.WriteEndElement();\n };\n // Serialize the page setup properties.\n WordExport.prototype.serializePageSetup = function (writer, pageSetup) {\n if (pageSetup !== undefined) {\n this.serializePageSize(writer, pageSetup);\n this.serializePageMargins(writer, pageSetup);\n }\n // // StartElement paperSrc (if any)\n // if (pageSetup.FirstPageTray > 0 || pageSetup.OtherPagesTray > 0) {\n // writer.WriteStartElement('paperSrc', this.wNamespace);\n // if (pageSetup.FirstPageTray > 0) {\n // writer.WriteAttributeString('first', this.wNamespace, pageSetup.FirstPageTray.ToString());\n // }\n // if (pageSetup.OtherPagesTray > 0) {\n // writer.WriteAttributeString('other', this.wNamespace, pageSetup.OtherPagesTray.ToString());\n // }\n // writer.WriteEndElement();\n // }\n writer.writeStartElement(undefined, 'pgBorders', this.wNamespace);\n // //zOrder\n // if (pageSetup.PageBordersApplyType === PageBordersApplyType.FirstPage)\n // writer.WriteAttributeString('display', this.wNamespace, 'firstPage');\n // else if (pageSetup.PageBordersApplyType === PageBordersApplyType.AllExceptFirstPage)\n // writer.WriteAttributeString('display', this.wNamespace, 'notFirstPage');\n // if (pageSetup.PageBorderOffsetFrom === PageBorderOffsetFrom.PageEdge) {\n // writer.WriteAttributeString('offsetFrom', this.wNamespace, 'page');\n // }\n // //Serializing zOrder of the front page border\n // if (!pageSetup.IsFrontPageBorder) {\n // writer.WriteAttributeString('zOrder', this.wNamespace, 'back');\n // }\n // SerializePageBorders(pageSetup.Borders);\n writer.writeEndElement();\n // this.serializeLineNumberType(writer, pageSetup);\n //this.serializePageNumberType(writer, pageSetup);\n };\n // serialize the page size\n WordExport.prototype.serializePageSize = function (writer, pageSetup) {\n writer.writeStartElement(undefined, 'pgSz', this.wNamespace);\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'w', this.wNamespace, this.roundToTwoDecimal(pageSetup.pageWidth * this.twentiethOfPoint).toString());\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'h', this.wNamespace, this.roundToTwoDecimal(pageSetup.pageHeight * this.twentiethOfPoint).toString());\n // if (pageSetup.Orientation === PageOrientation.Landscape)\n // {\n // writer.WriteAttributeString('orient', this.wNamespace, 'landscape');\n // }\n writer.writeEndElement();\n };\n // Serialize the border.\n WordExport.prototype.serializePageMargins = function (writer, pageSetup) {\n writer.writeStartElement(undefined, 'pgMar', this.wNamespace);\n var marginValue = Math.round(pageSetup.topMargin * this.twentiethOfPoint);\n writer.writeAttributeString(undefined, 'top', this.wNamespace, marginValue.toString());\n marginValue = Math.round(pageSetup.rightMargin * this.twentiethOfPoint);\n writer.writeAttributeString(undefined, 'right', this.wNamespace, marginValue.toString());\n marginValue = Math.round(pageSetup.bottomMargin * this.twentiethOfPoint);\n writer.writeAttributeString(undefined, 'bottom', this.wNamespace, marginValue.toString());\n marginValue = Math.round(pageSetup.leftMargin * this.twentiethOfPoint);\n writer.writeAttributeString(undefined, 'left', this.wNamespace, marginValue.toString());\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'header', this.wNamespace, this.roundToTwoDecimal(pageSetup.headerDistance * this.twentiethOfPoint).toString());\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'footer', this.wNamespace, this.roundToTwoDecimal(pageSetup.footerDistance * this.twentiethOfPoint).toString());\n writer.writeAttributeString(undefined, 'gutter', this.wNamespace, '0');\n writer.writeEndElement();\n };\n // Serialize the section type.\n WordExport.prototype.serializeSectionType = function (writer, sectionBreakCode) {\n writer.writeStartElement('w', 'type', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, sectionBreakCode); //GetSectionBreakCode(sectionBreakCode));\n writer.writeEndElement();\n };\n // Serialize the heeader/footer reference.\n WordExport.prototype.serializeHFReference = function (writer, headersFooters) {\n var hfId = '';\n if (headersFooters !== undefined) {\n this.mDifferentFirstPage = this.section.sectionFormat.differentOddAndEvenPages;\n var hf = headersFooters.firstPageHeader;\n if (hf && hf.blocks && hf.blocks.length > 0) {\n writer.writeStartElement(undefined, 'headerReference', this.wNamespace);\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'first');\n hfId = this.getNextRelationShipID();\n writer.writeAttributeString(undefined, 'id', this.rNamespace, hfId);\n this.addHeaderFooter(hf, 'FirstPageHeader', hfId);\n writer.writeEndElement();\n }\n hf = headersFooters.firstPageFooter;\n if (hf && hf.blocks && hf.blocks.length > 0) {\n writer.writeStartElement(undefined, 'footerReference', this.wNamespace);\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'first');\n hfId = this.getNextRelationShipID();\n writer.writeAttributeString(undefined, 'id', this.rNamespace, hfId);\n this.addHeaderFooter(hf, 'FirstPageFooter', hfId);\n writer.writeEndElement();\n }\n hf = headersFooters.evenHeader;\n if (hf && hf.blocks && hf.blocks.length > 0) {\n writer.writeStartElement(undefined, 'headerReference', this.wNamespace);\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'even');\n hfId = this.getNextRelationShipID();\n writer.writeAttributeString(undefined, 'id', this.rNamespace, hfId);\n this.addHeaderFooter(hf, 'EvenHeader', hfId);\n writer.writeEndElement();\n }\n hf = headersFooters.evenFooter;\n if (hf && hf.blocks && hf.blocks.length > 0) {\n writer.writeStartElement(undefined, 'footerReference', this.wNamespace);\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'even');\n hfId = this.getNextRelationShipID();\n writer.writeAttributeString(undefined, 'id', this.rNamespace, hfId);\n this.addHeaderFooter(hf, 'EvenFooter', hfId);\n writer.writeEndElement();\n }\n hf = headersFooters.header;\n if (hf && hf.blocks && hf.blocks.length > 0) {\n writer.writeStartElement(undefined, 'headerReference', this.wNamespace);\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'default');\n hfId = this.getNextRelationShipID();\n writer.writeAttributeString(undefined, 'id', this.rNamespace, hfId);\n this.addHeaderFooter(hf, 'OddHeader', hfId);\n writer.writeEndElement();\n }\n hf = headersFooters.footer;\n if (hf && hf.blocks && hf.blocks.length > 0) {\n writer.writeStartElement(undefined, 'footerReference', this.wNamespace);\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'default');\n hfId = this.getNextRelationShipID();\n writer.writeAttributeString(undefined, 'id', this.rNamespace, hfId);\n this.addHeaderFooter(hf, 'OddFooter', hfId);\n writer.writeEndElement();\n }\n }\n };\n // Adds the header footer details to the collection.\n WordExport.prototype.addHeaderFooter = function (hf, hfType, id) {\n var hfColl = new Dictionary();\n this.headersFooters.add(hfType, hfColl);\n this.headersFooters.get(hfType).add(id, hf);\n };\n // Serializes the bodyItems\n WordExport.prototype.serializeBodyItems = function (writer, blockCollection, isLastSection) {\n for (var i = 0; i < blockCollection.length; i++) {\n this.serializeBodyItem(writer, blockCollection[i], isLastSection);\n }\n };\n // Serialize the TextBody item\n WordExport.prototype.serializeBodyItem = function (writer, item, isLastSection) {\n if (isNullOrUndefined(item)) {\n throw new Error('BodyItem should not be undefined');\n }\n if (item.hasOwnProperty('inlines')) {\n this.paragraph = item;\n this.serializeParagraph(writer, item, isLastSection);\n this.paragraph = undefined;\n }\n else {\n var table = item;\n for (var i = 0; i < table.rows.length; i++) {\n if (table.rows[i].cells.length > 0) {\n this.serializeTable(writer, table);\n break;\n }\n }\n }\n };\n // Serialize the paragraph\n WordExport.prototype.serializeParagraph = function (writer, paragraph, isLastSection) {\n if (isNullOrUndefined(paragraph)) {\n throw new Error('Paragraph should not be undefined');\n }\n var sec = this.blockOwner;\n //Need to write the Section Properties if the Paragraph is last item in the section\n if (!isLastSection && sec.hasOwnProperty('sectionFormat')\n && sec.blocks.indexOf(paragraph) === sec.blocks.length - 1) {\n writer.writeStartElement('w', 'p', this.wNamespace);\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n this.serializeSectionProperties(writer, sec);\n writer.writeEndElement();\n writer.writeEndElement();\n }\n // if (paragraph.ParagraphFormat.PageBreakAfter && !IsPageBreakNeedToBeSkipped(paragraph as Entity))\n // paragraph.InsertBreak(BreakType.PageBreak);\n // if (paragraph.ParagraphFormat.ColumnBreakAfter && !IsPageBreakNeedToBeSkipped(paragraph as Entity))\n // paragraph.InsertBreak(BreakType.ColumnBreak);\n //Splits the paragraph based on the newline character\n // paragraph.SplitTextRange();\n writer.writeStartElement('w', 'p', this.wNamespace);\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n this.serializeParagraphFormat(writer, paragraph.paragraphFormat, paragraph);\n writer.writeEndElement(); //end of pPr\n // Serialize watermark if paragraph is the first item of Header document.\n // EnsureWatermark(paragraph);\n this.serializeParagraphItems(writer, paragraph.inlines);\n writer.writeEndElement(); //end of paragraph tag.\n };\n // Serialize the paragraph items\n WordExport.prototype.serializeParagraphItems = function (writer, paraItems) {\n var previousNode = undefined;\n for (var i = 0; i < paraItems.length; i++) {\n var item = paraItems[i];\n if (item.hasOwnProperty('fieldType')) {\n this.serializeFieldCharacter(writer, item);\n }\n else if (item.hasOwnProperty('imageString')) {\n this.serializePicture(writer, item);\n }\n else if (item.hasOwnProperty('bookmarkType')) {\n this.serializeBookMark(writer, item);\n }\n else {\n this.serializeTextRange(writer, item, previousNode);\n }\n previousNode = item;\n }\n };\n // Serialize the book mark\n WordExport.prototype.serializeBookMark = function (writer, bookmark) {\n var bookmarkId = this.getBookmarkId(bookmark.name);\n var bookmarkName = bookmark.name;\n if (bookmark.bookmarkType === 0) {\n writer.writeStartElement('w', 'bookmarkStart', this.wNamespace);\n writer.writeAttributeString('w', 'name', this.wNamespace, bookmarkName);\n }\n else if (bookmark.bookmarkType === 1) {\n writer.writeStartElement('w', 'bookmarkEnd', this.wNamespace);\n }\n writer.writeAttributeString('w', 'id', this.wNamespace, bookmarkId.toString());\n writer.writeEndElement();\n };\n WordExport.prototype.getBookmarkId = function (name) {\n var index = this.bookmarks.indexOf(name);\n if (index < 0) {\n index = this.bookmarks.length;\n this.bookmarks.push(name);\n }\n return index;\n };\n // Serialize the picture.\n WordExport.prototype.serializePicture = function (writer, image) {\n if (image.width >= 0 && image.height >= 0) {\n writer.writeStartElement(undefined, 'r', this.wNamespace);\n this.serializeCharacterFormat(writer, image.characterFormat);\n this.serializeDrawing(writer, image);\n writer.writeEndElement(); //end of run element\n }\n };\n // Serialize the drawing element.\n WordExport.prototype.serializeDrawing = function (writer, image) {\n writer.writeStartElement(undefined, 'drawing', this.wNamespace);\n this.serializeInlinePicture(writer, image);\n writer.writeEndElement();\n };\n // Serialize the inline picture.\n WordExport.prototype.serializeInlinePicture = function (writer, image) {\n writer.writeStartElement(undefined, 'inline', this.wpNamespace);\n writer.writeStartElement(undefined, 'extent', this.wpNamespace);\n var cx = Math.round(image.width * this.emusPerPoint);\n writer.writeAttributeString(undefined, 'cx', undefined, cx.toString());\n var cy = Math.round(image.height * this.emusPerPoint);\n writer.writeAttributeString(undefined, 'cy', undefined, cy.toString());\n writer.writeEndElement();\n // double borderWidth = (double)picture.PictureShape.PictureDescriptor.BorderLeft.LineWidth / DLSConstants.BorderLineFactor;\n // if (borderWidth > 0 && picture.DocxProps.length === 0) {\n // long leftTop = 0, rightBottom = 0;\n // picture.PictureShape.GetEffectExtent(borderWidth, ref leftTop, ref rightBottom);\n // m_writer.WriteStartElement('effectExtent', WP_namespace);\n // m_writer.WriteAttributeString('l', leftTop.ToString(CultureInfo.InvariantCulture));\n // m_writer.WriteAttributeString('t', leftTop.ToString(CultureInfo.InvariantCulture));\n // m_writer.WriteAttributeString('r', rightBottom.ToString(CultureInfo.InvariantCulture));\n // m_writer.WriteAttributeString('b', rightBottom.ToString(CultureInfo.InvariantCulture));\n // m_writer.WriteEndElement();\n // }\n //this.serializePicProperties(writer, image);\n this.serializeDrawingGraphics(writer, image);\n writer.writeEndElement();\n };\n WordExport.prototype.startsWith = function (sourceString, startString) {\n return startString.length > 0 && sourceString.substring(0, startString.length) === startString;\n };\n // Serialize the graphics element for pictures.\n WordExport.prototype.serializeDrawingGraphics = function (writer, picture) {\n var id = '';\n id = this.updateShapeId(picture);\n // picture.ShapeId = this.getNextDocPrID();\n // Processing picture\n writer.writeStartElement('wp', 'docPr', this.wpNamespace);\n writer.writeAttributeString(undefined, 'id', undefined, (this.mDocPrID++).toString());\n // if (!isNullOrUndefined(picture.AlternativeText))\n // m_writer.WriteAttributeString('descr', picture.AlternativeText);\n writer.writeAttributeString(undefined, 'name', undefined, '1'.toString());\n // if (!string.IsNullOrEmpty(picture.Title))\n // m_writer.WriteAttributeString('title', picture.Title);\n // else\n writer.writeAttributeString(undefined, 'title', undefined, '');\n // if (!picture.Visible)\n // m_writer.WriteAttributeString('hidden', '1');\n // SerializePictureHyperlink(picture);\n writer.writeEndElement();\n writer.writeStartElement('a', 'graphic', this.aNamespace);\n writer.writeStartElement('a', 'graphicData', this.aNamespace);\n writer.writeAttributeString(undefined, 'uri', undefined, this.pictureNamespace);\n writer.writeStartElement('pic', 'pic', this.pictureNamespace);\n writer.writeStartElement('pic', 'nvPicPr', this.pictureNamespace);\n writer.writeStartElement('pic', 'cNvPr', this.pictureNamespace);\n writer.writeAttributeString(undefined, 'id', undefined, '0');\n writer.writeAttributeString(undefined, 'name', undefined, '');\n writer.writeAttributeString(undefined, 'descr', undefined, '');\n writer.writeEndElement();\n writer.writeStartElement('pic', 'cNvPicPr', this.pictureNamespace);\n writer.writeStartElement('a', 'picLocks', this.aNamespace);\n writer.writeAttributeString(undefined, 'noChangeAspect', undefined, '1');\n writer.writeAttributeString(undefined, 'noChangeArrowheads', undefined, '1');\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeStartElement('pic', 'blipFill', this.pictureNamespace);\n writer.writeStartElement('a', 'blip', this.aNamespace);\n if (this.startsWith(picture.imageString, 'data:image')) {\n writer.writeAttributeString('r', 'embed', this.rNamespace, id);\n }\n else {\n if (this.documentImages.containsKey(id)) {\n //Remove the image document images collection for this particular key\n //If the picture image data has href means MS Word contains the image in media folder as well as \n //it is having external relationship id\n // if (!this.startsWith(picture.imageString, 'data:image')) {\n this.documentImages.remove(id);\n this.externalImages.add(id, picture.imageString);\n writer.writeAttributeString(undefined, 'link', this.rNamespace, id);\n }\n }\n //End Element Blip\n writer.writeEndElement();\n writer.writeStartElement('a', 'srcRect', this.aNamespace);\n writer.writeEndElement();\n writer.writeStartElement('a', 'stretch', this.aNamespace);\n writer.writeStartElement('a', 'fillRect', this.aNamespace);\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeStartElement('pic', 'spPr', this.pictureNamespace);\n writer.writeAttributeString(undefined, 'bwMode', undefined, 'auto');\n writer.writeStartElement('a', 'xfrm', this.aNamespace);\n // if (picture.Rotation !== 0)\n // m_writer.WriteAttributeString('rot', picture.Rotation.ToString());\n writer.writeStartElement('a', 'off', this.aNamespace);\n writer.writeAttributeString(undefined, 'x', undefined, '0');\n writer.writeAttributeString(undefined, 'y', undefined, '0');\n writer.writeEndElement();\n writer.writeStartElement('a', 'ext', this.aNamespace);\n var cx = Math.round((picture.width * this.emusPerPoint));\n writer.writeAttributeString(undefined, 'cx', undefined, cx.toString());\n var cy = Math.round((picture.height * this.emusPerPoint));\n writer.writeAttributeString(undefined, 'cy', undefined, cy.toString());\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeStartElement('a', 'prstGeom', this.aNamespace);\n writer.writeAttributeString(undefined, 'prst', undefined, 'rect');\n writer.writeStartElement('a', 'avLst', this.aNamespace);\n writer.writeEndElement();\n writer.writeEndElement();\n //When the picture border has been added next to effect list\n //if not, Picture border has not been preserved\n // if (picture.HasBorder)\n // {\n // if (picture.TextWrappingStyle === TextWrappingStyle.Inline && picture.IsShape)\n // SerializeInlineShapeLine(picture.PictureShape);\n // else\n // SerializeShapeLine(picture.PictureShape);\n // }\n // if (picture.DocxProps.length > 0)\n // SerializeDocxProps(picture.DocxProps, 'effectLst');\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n };\n /// Update the shape id.\n WordExport.prototype.updateShapeId = function (picture) {\n var id = '';\n var tOwner = this.paragraph;\n // Adding picture byte data to the corresponding picture collection \n // depending on its owner subdocument\n if (this.headerFooter) {\n id = this.updateHFImageRels(this.headerFooter, picture);\n }\n else {\n if (id === '') {\n if (tOwner.hasOwnProperty('sectionFormat') || tOwner.hasOwnProperty('inlines')) {\n id = this.addImageRelation(this.documentImages, picture);\n // if (owner is WFootnote)\n // {\n // if ((owner as WFootnote).FootnoteType === FootnoteType.Footnote)\n // id = AddImageRelation(FootnoteImages, picture.ImageRecord);\n // else\n // id = AddImageRelation(EndnoteImages, picture.ImageRecord);\n // }\n // if (owner is WComment)\n // id = AddImageRelation(CommentImages, picture.ImageRecord);\n }\n }\n }\n return id;\n };\n // Adds the image relation.\n WordExport.prototype.addImageRelation = function (imageCollection, image) {\n var relationId = '';\n // if (imageCollection.ContainsValue(imageRecord)) {\n // foreach(string key in imageCollection.keys)\n // {\n // if (imageRecord === imageCollection[key]) {\n // relationId = key;\n // break;\n // }\n // }\n // }\n // else {\n relationId = this.getNextRelationShipID();\n imageCollection.add(relationId, image);\n // }\n return relationId;\n };\n // Update the HeaderFooter image relations.\n WordExport.prototype.updateHFImageRels = function (hf, image) {\n var id = '';\n // UpdateImages(image);\n var headerId = '';\n var types = this.headersFooters.keys;\n for (var i = 0; i < types.length; i++) {\n var hfColl = this.headersFooters.get(types[i]);\n var hfKeys = hfColl.keys;\n for (var j = 0; j < hfKeys.length; j++) {\n if (hfColl.get(hfKeys[j]) === hf) {\n headerId = hfKeys[j];\n var headerImages = void 0;\n if (this.headerFooterImages.containsKey(headerId)) {\n headerImages = this.headerFooterImages.get(headerId);\n id = this.addImageRelation(headerImages, image);\n }\n else {\n headerImages = new Dictionary();\n id = this.addImageRelation(headerImages, image);\n this.headerFooterImages.add(headerId, headerImages);\n }\n }\n }\n }\n return id;\n };\n // Serialize the table\n WordExport.prototype.serializeTable = function (writer, table) {\n if (table.rows.length <= 0) {\n return;\n }\n var owner = this.table;\n this.table = table;\n writer.writeStartElement(undefined, 'tbl', this.wNamespace);\n var tableFormat = table.rows[0].rowFormat;\n this.serializeTableFormat(writer, tableFormat, table);\n this.serializeTableGrid(writer, table);\n this.serializeTableRows(writer, table.rows);\n writer.writeEndElement();\n this.table = owner;\n };\n // Serialize the table grid\n WordExport.prototype.serializeTableGrid = function (writer, table) {\n writer.writeStartElement(undefined, 'tblGrid', this.wNamespace);\n if (table.grid.length !== 0) {\n this.serializeGridColumns(writer, table.grid);\n }\n writer.writeEndElement();\n };\n // Serialize the table rows\n WordExport.prototype.serializeTableRows = function (writer, rows) {\n if (rows.length > 0) {\n for (var i = 0; i < rows.length; i++) {\n var row = rows[i];\n if (row.cells.length > 0) {\n this.serializeRow(writer, row);\n }\n }\n }\n };\n // Serialize the table row\n WordExport.prototype.serializeRow = function (writer, row) {\n var owner = this.row;\n this.row = row;\n writer.writeStartElement(undefined, 'tr', this.wNamespace);\n this.serializeRowFormat(writer, row);\n this.serializeCells(writer, row.cells);\n writer.writeEndElement(); //end od table row 'tr'\n this.row = owner;\n };\n // Serialize the row format\n WordExport.prototype.serializeRowFormat = function (writer, row) {\n writer.writeStartElement(undefined, 'trPr', this.wNamespace);\n //Serialize Row Height\n if (row.rowFormat.height > 0) {\n writer.writeStartElement(undefined, 'trHeight', this.wNamespace);\n if (row.rowFormat.heightType === 'Exactly') {\n writer.writeAttributeString('w', 'hRule', this.wNamespace, 'exact');\n }\n else if (row.rowFormat.heightType === 'AtLeast') {\n writer.writeAttributeString('w', 'hRule', this.wNamespace, 'atLeast');\n }\n var height = this.roundToTwoDecimal(row.rowFormat.height * this.twentiethOfPoint).toString();\n writer.writeAttributeString('w', 'val', this.wNamespace, height);\n writer.writeEndElement();\n }\n var rowFormat = row.rowFormat;\n // //Serialize 'gridBefore' element\n var gridBefore = rowFormat.gridBefore;\n if (gridBefore > 0) {\n writer.writeStartElement(undefined, 'gridBefore', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, gridBefore.toString());\n writer.writeEndElement();\n }\n // //Serialize 'gridAfter' element\n var gridAfter = rowFormat.gridAfter;\n if (gridAfter > 0) {\n writer.writeStartElement(undefined, 'gridAfter', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, gridAfter.toString());\n writer.writeEndElement();\n }\n // //Serialize 'wBefore' element \n if (gridBefore > 0) {\n writer.writeStartElement(undefined, 'wBefore', this.wNamespace);\n switch (rowFormat.gridBeforeWidthType) {\n case 'Percent':\n var width = this.roundToTwoDecimal(rowFormat.gridBeforeWidth * this.percentageFactor).toString();\n writer.writeAttributeString('w', 'val', this.wNamespace, width);\n writer.writeAttributeString('w', 'type', this.wNamespace, 'pct');\n break;\n case 'Point':\n var pointWidth = this.roundToTwoDecimal(rowFormat.gridBeforeWidth * this.twipsInOnePoint).toString();\n writer.writeAttributeString('w', 'val', this.wNamespace, pointWidth);\n writer.writeAttributeString('w', 'type', this.wNamespace, 'dxa');\n break;\n }\n writer.writeEndElement();\n }\n //Serialize 'wAfter' element\n if (gridAfter > 0) {\n writer.writeStartElement(undefined, 'wAfter', this.wNamespace);\n switch (rowFormat.gridAfterWidthType) {\n case 'Percent':\n var width = this.roundToTwoDecimal(rowFormat.gridAfterWidth * this.percentageFactor).toString();\n writer.writeAttributeString('w', 'val', this.wNamespace, width);\n writer.writeAttributeString('w', 'type', this.wNamespace, 'pct');\n break;\n case 'Point':\n var pointWidth = this.roundToTwoDecimal(rowFormat.gridAfterWidth * this.twipsInOnePoint).toString();\n writer.writeAttributeString('w', 'val', this.wNamespace, pointWidth);\n writer.writeAttributeString('w', 'type', this.wNamespace, 'dxa');\n break;\n }\n writer.writeEndElement();\n }\n //Serialize 'cantSplit' element \n if (!rowFormat.allowBreakAcrossPages) {\n writer.writeStartElement(undefined, 'cantSplit', this.wNamespace);\n writer.writeEndElement();\n }\n // //Serialize 'tblHeader' element \n if (rowFormat.isHeader) {\n writer.writeStartElement(undefined, 'tblHeader', this.wNamespace);\n writer.writeEndElement();\n }\n writer.writeEndElement();\n };\n // serialize the table cells\n WordExport.prototype.serializeCells = function (writer, cells) {\n for (var i = 0; i < cells.length; i++) {\n this.serializeCell(writer, cells[i]);\n }\n };\n // Serialize the table cell\n WordExport.prototype.serializeCell = function (writer, cell) {\n var owner = this.blockOwner;\n this.blockOwner = cell;\n writer.writeStartElement(undefined, 'tc', this.wNamespace);\n this.serializeCellFormat(writer, cell.cellFormat);\n if (cell.blocks.length > 0) {\n var itemIndex = 0;\n var item = undefined;\n while (itemIndex < cell.blocks.length) {\n item = cell.blocks[itemIndex];\n this.serializeBodyItem(writer, item, false);\n itemIndex += 1;\n }\n }\n else {\n writer.writeStartElement(undefined, 'p', this.wNamespace);\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n writer.writeStartElement(undefined, 'pStyle', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, 'Normal');\n writer.writeEndElement(); //end of pStyle\n writer.writeEndElement(); //end of pPr\n writer.writeEndElement(); //end of P\n }\n writer.writeEndElement(); //end of table cell 'tc' \n this.blockOwner = owner;\n };\n // Serialize the cell formatting\n WordExport.prototype.serializeCellFormat = function (writer, cellFormat) {\n var cell = this.blockOwner;\n //Get the table fomat\n var tf = this.table.tableFormat;\n //Get the row format\n var rf = this.row.rowFormat;\n writer.writeStartElement(undefined, 'tcPr', this.wNamespace);\n //w:cnfStyle - Table Cell Conditional Formatting\n // SerializeCnfStyleElement(cell);\n //w:tcW - Preferred Table Cell Width\n this.serializeCellWidth(writer, cell);\n //w:hMerge - Horizontally Merged Cell and w:vMerge - Vertically Merged Cell\n this.serializeCellMerge(writer, cellFormat);\n //w:gridSpan - Grid Columns Spanned by Current Table Cell\n this.serializeGridSpan(writer, cell);\n //w:tcBorders - Table Cell Borders\n writer.writeStartElement(undefined, 'tcBorders', this.wNamespace);\n this.serializeBorders(writer, cellFormat.borders, 8);\n writer.writeEndElement();\n //w:shd - Table Cell Shading\n this.serializeShading(writer, cell.cellFormat.shading);\n // //w:noWrap - Don't Wrap Cell Content\n // if (cellFormat.HasValue(CellFormat.TextWrapKey)) {\n // m_writer.WriteStartElement('noWrap', W_namespace);\n // if (cellFormat.TextWrap)\n // m_writer.WriteAttributeString('w', 'val', W_namespace, 'false');\n // m_writer.WriteEndElement();\n // }\n // //w:tcMar - Single Table Cell Margins\n // if (!cellFormat.SamePaddingsAsTable) {\n // m_writer.WriteStartElement('tcMar', W_namespace);\n // SerializePaddings(cellFormat.Paddings);\n // m_writer.WriteEndElement();\n // }\n //w:textDirection - Table Cell Text Flow Direction\n this.serializeTableCellDirection(writer, cellFormat);\n // //w:tcFitText - Fit Text Within Cell\n // if (cellFormat.FitText) {\n // m_writer.WriteStartElement('tcFitText', W_namespace);\n // m_writer.WriteEndElement();\n // }\n // //w:hideMark \n // if (cellFormat.HideMark) {\n // m_writer.WriteStartElement('hideMark', W_namespace);\n // m_writer.WriteEndElement();\n // }\n //w:vAlign - Table Cell Vertical Alignment\n // if (cellFormat.HasValue(CellFormat.VrAlignmentKey))\n this.serializeCellVerticalAlign(writer, cellFormat.verticalAlignment);\n // //w:hideMark - Ignore End Of Cell Marker In Row Height Calculation\n // SerializeDocxProps(tempDocxProps, 'hideMark');\n // //w:cellIns - Table Cell Insertion\n // SerializeDocxProps(tempDocxProps, 'cellIns');\n // //w:cellDel - Table Cell Deletion\n // SerializeDocxProps(tempDocxProps, 'cellDel');\n // //w:cellMerge - Vertically Merged/Split Table Cells\n // SerializeDocxProps(tempDocxProps, 'cellMerge');\n // if (cellFormat.OldPropertiesHash.length > 0 && !m_isAlternativeCellFormat) {\n // m_isAlternativeCellFormat = true;\n // SerializeTrackChangeProps('tcPrChange', cellFormat.FormatChangeAuthorName, cellFormat.FormatChangeDateTime);\n // Dictionary < int, object > oldPropertyHash = new Dictionary(cellFormat.OldPropertiesHash);\n // Dictionary < int, object > propertyHash = new Dictionary(cellFormat.PropertiesHash);\n // cellFormat.PropertiesHash.Clear();\n // cellFormat.OldPropertiesHash.Clear();\n // foreach(KeyValuePair < int, object > keyValue in oldPropertyHash)\n // cellFormat.PropertiesHash[keyValue.Key] = keyValue.Value;\n // SerializeCellFormat(cellFormat);\n // cellFormat.PropertiesHash.Clear();\n // foreach(KeyValuePair < int, object > keyValue in propertyHash)\n // cellFormat.PropertiesHash[keyValue.Key] = keyValue.Value;\n // foreach(KeyValuePair < int, object > keyValue in oldPropertyHash)\n // cellFormat.OldPropertiesHash[keyValue.Key] = keyValue.Value;\n // m_writer.WriteEndElement();\n // m_isAlternativeCellFormat = false;\n // }\n writer.writeEndElement();\n };\n // Serialize the cell width\n WordExport.prototype.serializeCellWidth = function (writer, cell) {\n var cf = cell.cellFormat;\n writer.writeStartElement(undefined, 'tcW', this.wNamespace);\n if (cf.preferredWidthType === 'Percent') {\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'pct');\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'w', this.wNamespace, this.roundToTwoDecimal(cf.preferredWidth * this.percentageFactor).toString());\n }\n else if (cf.preferredWidthType === 'Point') {\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'w', this.wNamespace, this.roundToTwoDecimal(cf.preferredWidth * this.twipsInOnePoint).toString());\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'dxa');\n }\n else {\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'auto');\n writer.writeAttributeString(undefined, 'w', this.wNamespace, '0');\n }\n writer.writeEndElement();\n };\n // Serialize cell merge\n WordExport.prototype.serializeCellMerge = function (writer, cellFormat) {\n var cell = this.blockOwner;\n var isserialized = false;\n var collKey;\n var currentIndex = cell.columnIndex;\n var cellIndex = this.row.cells.indexOf(cell);\n var prevIndex = cellIndex > 0 ? this.row.cells[cellIndex - 1].columnIndex : cell.columnIndex;\n if (cell.columnIndex === cellIndex) {\n collKey = cell.columnIndex;\n isserialized = true;\n }\n else {\n isserialized = false;\n }\n if (!isserialized) {\n if (cellIndex === 0) {\n currentIndex = cell.columnIndex;\n prevIndex = -1;\n }\n for (var i = prevIndex; i < currentIndex; i++) {\n collKey = prevIndex + 1;\n prevIndex += 1;\n if (this.mVerticalMerge.containsKey(collKey)) {\n this.createMerge(writer, collKey, cell);\n }\n }\n }\n if (cellFormat.rowSpan > 1) {\n writer.writeStartElement(undefined, 'vMerge', this.wNamespace);\n this.mVerticalMerge.add(collKey, cellFormat.rowSpan - 1);\n if (cellFormat.columnSpan > 1) {\n this.mGridSpans.add(collKey, cellFormat.columnSpan);\n }\n writer.writeAttributeString('w', 'val', this.wNamespace, 'restart');\n writer.writeEndElement();\n }\n else if (this.mVerticalMerge.containsKey(collKey) && isserialized) {\n this.createMerge(writer, collKey, cell);\n }\n else if (this.mVerticalMerge.containsKey(cellIndex + 1) && isserialized && cell.nextNode === undefined) {\n collKey = cell.columnIndex + 1;\n writer.writeEndElement();\n writer.writeStartElement('w', 'p', this.wNamespace);\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeStartElement(undefined, 'tc', this.wNamespace);\n writer.writeStartElement(undefined, 'tcPr', this.wNamespace);\n this.serializeColumnSpan(collKey, writer);\n writer.writeStartElement(undefined, 'vMerge', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, 'continue');\n writer.writeEndElement();\n this.checkMergeCell(collKey);\n }\n };\n WordExport.prototype.createMerge = function (writer, collKey, cell) {\n this.serializeColumnSpan(collKey, writer);\n writer.writeStartElement(undefined, 'vMerge', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, 'continue');\n writer.writeEndElement();\n writer.writeEndElement(); //end tcPr\n writer.writeStartElement('w', 'p', this.wNamespace);\n writer.writeEndElement();\n writer.writeEndElement(); //end tc\n writer.writeStartElement(undefined, 'tc', this.wNamespace);\n writer.writeStartElement(undefined, 'tcPr', this.wNamespace);\n this.serializeCellWidth(writer, cell);\n this.checkMergeCell(collKey);\n };\n WordExport.prototype.serializeColumnSpan = function (collKey, writer) {\n if (this.mGridSpans.keys.length > 0 && this.mGridSpans.containsKey(collKey)) {\n writer.writeStartElement(undefined, 'gridSpan', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.mGridSpans.get(collKey).toString());\n writer.writeEndElement();\n }\n };\n WordExport.prototype.checkMergeCell = function (collKey) {\n if ((this.mVerticalMerge.get(collKey) - 1) === 0) {\n this.mVerticalMerge.remove(collKey);\n if (this.mGridSpans.keys.length > 0 && this.mGridSpans.containsKey(collKey)) {\n this.mGridSpans.remove(collKey);\n }\n }\n else {\n this.mVerticalMerge.set(collKey, this.mVerticalMerge.get(collKey) - 1);\n }\n };\n // Serialize the grid span element of cell.\n WordExport.prototype.serializeGridSpan = function (writer, cell) {\n // int gridSpan = cell.cellFormat.GridSpan;\n if (cell.cellFormat.columnSpan > 1) {\n var num = cell.cellFormat.columnSpan;\n writer.writeStartElement(undefined, 'gridSpan', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, num.toString());\n writer.writeEndElement();\n }\n };\n // Serialize the table cell direction\n WordExport.prototype.serializeTableCellDirection = function (writer, cellFormat) {\n // if (cellFormat..textDirection !== TextDirection.Horizontal)\n // {\n // m_writer.WriteStartElement('textDirection', W_namespace);\n // switch (cellFormat.TextDirection)\n // {\n // case TextDirection.Horizontal:\n // m_writer.WriteAttributeString('w', 'val', W_namespace, 'lrTb');\n // break;\n // case TextDirection.VerticalBottomToTop:\n // m_writer.WriteAttributeString('w', 'val', W_namespace, 'btLr');\n // break;\n // case TextDirection.VerticalTopToBottom:\n // m_writer.WriteAttributeString('w', 'val', W_namespace, 'tbRl');\n // break;\n // case TextDirection.HorizontalFarEast:\n // m_writer.WriteAttributeString('w', 'val', W_namespace, 'lrTbV');\n // break;\n // case TextDirection.Vertical:\n // m_writer.WriteAttributeString('w', 'val', W_namespace, 'tbLrV');\n // break;\n // case TextDirection.VerticalFarEast:\n // m_writer.WriteAttributeString('w', 'val', W_namespace, 'tbRlV');\n // break;\n // }\n // m_writer.WriteEndElement();\n // }\n };\n // Serialize the cell vertical alignment\n WordExport.prototype.serializeCellVerticalAlign = function (writer, alignment) {\n writer.writeStartElement(undefined, 'vAlign', this.wNamespace);\n switch (alignment) {\n case 'Top':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'top');\n break;\n case 'Center':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'center');\n break;\n default:\n writer.writeAttributeString('w', 'val', this.wNamespace, 'bottom');\n break;\n }\n writer.writeEndElement();\n };\n // Serialize the table grid columns.\n WordExport.prototype.serializeGridColumns = function (writer, grid) {\n for (var i = 1, count = grid.length; i < count; i++) {\n var gridValue = Math.round(grid[i] * 20);\n writer.writeStartElement(undefined, 'gridCol', this.wNamespace);\n writer.writeAttributeString(undefined, 'w', this.wNamespace, gridValue.toString());\n writer.writeEndElement();\n }\n };\n // Serialize the row formattings.\n // Table parameter is passed for serializing table format and undefined for serializing row format.\n WordExport.prototype.serializeTableFormat = function (writer, format, table) {\n // if (!isNullOrUndefined(table))\n // {\n // List tempDocxProps = new List();\n // for (int i = 0, cnt = table.DocxTableFormat.NodeArray.length; i < cnt; i++)\n // tempDocxProps.Add(table.DocxTableFormat.NodeArray[i]);\n writer.writeStartElement(undefined, 'tblPr', this.wNamespace);\n // SerializeTableStlye(format);\n // if (format.WrapTextAround &&!((table.OwnerTextBody.Owner is WTextBox) || \n //(table.OwnerTextBody.Owner is WComment) || (table.OwnerTextBody.Owner is WFootnote)))\n // {\n // SerializeTablePositioning(format.Positioning);\n // if (!format.Positioning.AllowOverlap)\n // {\n // m_writer.WriteStartElement('tblOverlap', W_namespace);\n // m_writer.WriteAttributeString('val', W_namespace, 'never');\n // m_writer.WriteEndElement();\n // }\n // }\n // if (format.Bidi)\n // {\n // m_writer.WriteStartElement('bidiVisual', W_namespace);\n // m_writer.WriteEndElement();\n // }\n // SerializeDocxProps(tempDocxProps, 'tblStyleRowBandSize');\n // SerializeDocxProps(tempDocxProps, 'tblStyleColBandSize');\n this.serializeTableWidth(writer, table);\n this.serializeTableAlignment(writer, table.tableFormat);\n this.serializeCellSpacing(writer, table.tableFormat);\n this.serializeTableIndentation(writer, table.tableFormat);\n this.serializeTableBorders(writer, table.tableFormat);\n this.serializeShading(writer, table.tableFormat.shading);\n this.serializeTblLayout(writer, table.tableFormat);\n // this.serializeTableCellMargin(writer, table.tableFormat);\n // SerializeTableLook(table);\n // if (!isNullOrUndefined(table.Title))\n // SerializeTableTitle(table);\n // if (!isNullOrUndefined(table.Description))\n // SerializeTableDescription(table);\n // }\n // else\n // {\n // SerializeCellSpacing(format);\n // SerializeTableIndentation(format);\n // SerializeTableBorders(format);\n // SerializeTableShading(format);\n // SerializeTblLayout(format);\n // SerializeTableCellMargin(format);\n // }\n // if (!isNullOrUndefined(format.OwnerBase) && format.OwnerBase is WTable\n // && format.OldPropertiesHash.length > 0 && !m_isAlternativeTableFormat)\n // {\n // m_isAlternativeTableFormat = true;\n // SerializeTrackChangeProps('tblPrChange', format.FormatChangeAuthorName, format.FormatChangeDateTime);\n // SerializeTableTrackChanges(format, format.OwnerBase as WTable);\n // m_writer.WriteEndElement();\n // m_isAlternativeTableFormat = false;\n // }\n // if (!isNullOrUndefined(format.OwnerRow) && format.OldPropertiesHash.length > 0)\n // {\n // SerializeTrackChangeProps('tblPrExChange', format.FormatChangeAuthorName, format.FormatChangeDateTime);\n // SerializeTableTrackChanges(format, undefined);\n // m_writer.WriteEndElement();\n // }\n // SerializeTblTrackChanges(format);\n if (!isNullOrUndefined(table)) {\n writer.writeEndElement(); //end of tblPr\n }\n };\n // Serialize the table borders\n WordExport.prototype.serializeShading = function (writer, format) {\n // if (format.textureStyle !== 'TextureNone') {\n writer.writeStartElement(undefined, 'shd', this.wNamespace);\n writer.writeAttributeString(undefined, 'fill', this.wNamespace, this.getColor(format.backgroundColor));\n if (format.foregroundColor === 'empty') {\n writer.writeAttributeString(undefined, 'color', this.wNamespace, 'auto');\n }\n else {\n writer.writeAttributeString(undefined, 'color', this.wNamespace, this.getColor(format.foregroundColor));\n }\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getTextureStyle(format.textureStyle));\n writer.writeEndElement();\n // }\n };\n WordExport.prototype.getTextureStyle = function (textureStyle) {\n switch (textureStyle) {\n case 'Texture5Percent':\n case 'Texture2Pt5Percent':\n case 'Texture7Pt5Percent':\n return 'pct5';\n case 'Texture10Percent':\n return 'pct10';\n case 'Texture12Pt5Percent':\n return 'pct12';\n case 'Texture15Percent':\n case 'Texture17Pt5Percent':\n return 'pct15';\n case 'Texture20Percent':\n case 'Texture22Pt5Percent':\n return 'pct20';\n case 'Texture25Percent':\n case 'Texture27Pt5Percent':\n return 'pct25';\n case 'Texture30Percent':\n case 'Texture32Pt5Percent':\n return 'pct30';\n case 'Texture35Percent':\n return 'pct35';\n case 'Texture37Pt5Percent':\n return 'pct37';\n case 'Texture40Percent':\n case 'Texture42Pt5Percent':\n return 'pct40';\n case 'Texture45Percent':\n case 'Texture47Pt5Percent':\n return 'pct45';\n case 'Texture50Percent':\n case 'Texture52Pt5Percent':\n return 'pct50';\n case 'Texture55Percent':\n case 'Texture57Pt5Percent':\n return 'pct55';\n case 'Texture60Percent':\n return 'pct60';\n case 'Texture62Pt5Percent':\n return 'pct62';\n case 'Texture65Percent':\n case 'Texture67Pt5Percent':\n return 'pct65';\n case 'Texture70Percent':\n case 'Texture72Pt5Percent':\n return 'pct70';\n case 'Texture75Percent':\n case 'Texture77Pt5Percent':\n return 'pct75';\n case 'Texture80Percent':\n case 'Texture82Pt5Percent':\n return 'pct80';\n case 'Texture85Percent':\n return 'pct85';\n case 'Texture87Pt5Percent':\n return 'pct87';\n case 'Texture90Percent':\n case 'Texture92Pt5Percent':\n return 'pct90';\n case 'Texture95Percent':\n case 'Texture97Pt5Percent':\n return 'pct95';\n case 'TextureCross':\n return 'thinHorzCross';\n case 'TextureDarkCross':\n return 'horzCross';\n case 'TextureDarkDiagonalCross':\n return 'diagCross';\n case 'TextureDarkDiagonalDown':\n return 'reverseDiagStripe';\n case 'TextureDarkDiagonalUp':\n return 'diagStripe';\n case 'TextureDarkHorizontal':\n return 'horzStripe';\n case 'TextureDarkVertical':\n return 'vertStripe';\n case 'TextureDiagonalCross':\n return 'thinDiagCross';\n case 'TextureDiagonalDown':\n return 'thinReverseDiagStripe';\n case 'TextureDiagonalUp':\n return 'thinDiagStripe';\n case 'TextureHorizontal':\n return 'thinHorzStripe';\n case 'TextureSolid':\n return 'solid';\n case 'TextureVertical':\n return 'thinVertStripe';\n default:\n return 'clear';\n }\n };\n // Serialize the table borders\n WordExport.prototype.serializeTableBorders = function (writer, format) {\n var borders = format.borders;\n // if (IsNoneBorder(borders))\n // return;\n writer.writeStartElement(undefined, 'tblBorders', this.wNamespace);\n this.serializeBorders(writer, format.borders, 8);\n writer.writeEndElement();\n };\n // Serialize the borders.\n WordExport.prototype.serializeBorders = function (writer, borders, multipler) {\n this.serializeBorder(writer, borders.top, 'top', multipler);\n this.serializeBorder(writer, borders.left, 'left', multipler);\n this.serializeBorder(writer, borders.bottom, 'bottom', multipler);\n this.serializeBorder(writer, borders.right, 'right', multipler);\n this.serializeBorder(writer, borders.horizontal, 'insideH', multipler);\n this.serializeBorder(writer, borders.vertical, 'insideV', multipler);\n this.serializeBorder(writer, borders.diagonalDown, 'tl2br', multipler);\n this.serializeBorder(writer, borders.diagonalUp, 'tr2bl', multipler);\n };\n // Serialize the table layout element\n WordExport.prototype.serializeTblLayout = function (writer, format) {\n //TODO: AUTO size property is not mapped yet\n // if (!format.IsAutoResized)\n // {\n // writer.writeStartElement(undefined, 'tblLayout', this.wNamespace);\n // writer.writeAttributeString(undefined, 'type', this.wNamespace, 'fixed');\n // writer.writeEndElement();\n // }\n };\n // Serializes the Border\n WordExport.prototype.serializeBorder = function (writer, border, tagName, multiplier) {\n var borderStyle = border.lineStyle;\n var sz = (border.lineWidth * multiplier);\n var space = border.space;\n if (borderStyle === 'Cleared') {\n writer.writeStartElement(undefined, tagName, this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, 'nil');\n writer.writeEndElement();\n return;\n }\n else if ((borderStyle === 'None' && !border.hasNoneStyle) || sz <= 0) {\n return;\n }\n writer.writeStartElement(undefined, tagName, this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getBorderStyle(borderStyle));\n // if (border.color === '#000000')\n // {\n // writer.writeAttributeString(undefined, 'color', this.wNamespace, 'auto');\n // }\n // else\n // {\n writer.writeAttributeString(undefined, 'color', this.wNamespace, this.getColor(border.color));\n // }\n writer.writeAttributeString(undefined, 'sz', this.wNamespace, this.roundToTwoDecimal(sz).toString());\n writer.writeAttributeString(undefined, 'space', this.wNamespace, space.toString());\n if (border.shadow) {\n writer.writeAttributeString(undefined, 'shadow', this.wNamespace, 'on');\n }\n writer.writeEndElement();\n };\n // Get the border style as string\n WordExport.prototype.getBorderStyle = function (borderStyle) {\n switch (borderStyle) {\n case 'Cleared':\n return 'cleared';\n case 'DashSmallGap':\n return 'dashSmallGap';\n case 'Triple':\n return 'triple';\n case 'Dot':\n return 'dotted';\n case 'DashDot':\n return 'dotDash';\n case 'DashLargeGap':\n return 'dashed';\n case 'DashDotDot':\n return 'dotDotDash';\n case 'Double':\n return 'double';\n case 'ThinThickSmallGap':\n return 'thinThickSmallGap';\n case 'ThickThinSmallGap':\n return 'thickThinSmallGap';\n case 'ThinThickThinSmallGap':\n return 'thinThickThinSmallGap';\n case 'ThickThinMediumGap':\n return 'thickThinMediumGap';\n case 'ThinThickMediumGap':\n return 'thinThickMediumGap';\n case 'ThinThickThinMediumGap':\n return 'thinThickThinMediumGap';\n case 'ThickThinLargeGap':\n return 'thickThinLargeGap';\n case 'ThinThickLargeGap':\n return 'thinThickLargeGap';\n case 'ThinThickThinLargeGap':\n return 'thinThickThinLargeGap';\n case 'Thick':\n return 'thick';\n case 'SingleWavy':\n return 'wave';\n case 'DoubleWavy':\n return 'doubleWave';\n case 'DashDotStroked':\n return 'dashDotStroked';\n case 'Engrave3D':\n return 'threeDEngrave';\n case 'Emboss3D':\n return 'threeDEmboss';\n case 'Outset':\n return 'outset';\n case 'Inset':\n return 'inset';\n // case 'None':\n // return 'none';\n default:\n return 'single';\n }\n };\n // Serialize the table indentation.\n WordExport.prototype.serializeTableIndentation = function (writer, format) {\n writer.writeStartElement(undefined, 'tblInd', this.wNamespace);\n var tableIndent = Math.round(format.leftIndent * this.twipsInOnePoint);\n writer.writeAttributeString(undefined, 'w', this.wNamespace, tableIndent.toString());\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'dxa');\n writer.writeEndElement();\n };\n // Serialize the cell spacing.\n WordExport.prototype.serializeCellSpacing = function (writer, format) {\n if (!isNullOrUndefined(format.cellSpacing) && format.cellSpacing >= 0) {\n writer.writeStartElement(undefined, 'tblCellSpacing', this.wNamespace);\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'w', this.wNamespace, this.roundToTwoDecimal(format.cellSpacing * this.twentiethOfPoint).toString());\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'dxa');\n writer.writeEndElement();\n }\n };\n // Serialize the table width\n WordExport.prototype.serializeTableWidth = function (writer, table) {\n writer.writeStartElement(undefined, 'tblW', this.wNamespace);\n if (table.tableFormat.preferredWidthType === 'Percent') {\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'w', this.wNamespace, (table.tableFormat.preferredWidth * this.percentageFactor).toString());\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'pct');\n }\n else if (table.tableFormat.preferredWidthType === 'Point') {\n var tableWidth = Math.round(table.tableFormat.preferredWidth * this.twipsInOnePoint);\n writer.writeAttributeString(undefined, 'w', this.wNamespace, tableWidth.toString());\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'dxa');\n }\n else {\n writer.writeAttributeString(undefined, 'w', this.wNamespace, '0');\n writer.writeAttributeString(undefined, 'type', this.wNamespace, 'auto');\n }\n writer.writeEndElement();\n };\n // Serialize the table alignment\n WordExport.prototype.serializeTableAlignment = function (writer, format) {\n writer.writeStartElement(undefined, 'jc', this.wNamespace);\n switch (format.tableAlignment) {\n case 'Right':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'right');\n break;\n case 'Center':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'center');\n break;\n default:\n writer.writeAttributeString('w', 'val', this.wNamespace, 'left');\n break;\n }\n writer.writeEndElement();\n };\n // Serialize the field\n WordExport.prototype.serializeFieldCharacter = function (writer, field) {\n writer.writeStartElement(undefined, 'r', this.wNamespace);\n this.serializeCharacterFormat(writer, field.characterFormat);\n writer.writeStartElement(undefined, 'fldChar', this.wNamespace);\n var type = field.fieldType === 0 ? 'begin'\n : field.fieldType === 1 ? 'end' : 'separate';\n writer.writeAttributeString(undefined, 'fldCharType', this.wNamespace, type);\n writer.writeEndElement();\n writer.writeEndElement();\n };\n // Serialize the text range.\n WordExport.prototype.serializeTextRange = function (writer, span, previousNode) {\n writer.writeStartElement('w', 'r', this.wNamespace);\n this.serializeCharacterFormat(writer, span.characterFormat);\n if (span.text === '\\t') {\n writer.writeElementString(undefined, 'tab', this.wNamespace, undefined);\n }\n else if (span.text === '\\v') {\n writer.writeElementString(undefined, 'br', this.wNamespace, undefined);\n }\n else {\n var isField = !isNullOrUndefined(previousNode)\n && previousNode.hasOwnProperty('fieldType') && previousNode.fieldType !== 2;\n writer.writeStartElement(undefined, isField ? 'instrText' : 't', this.wNamespace);\n writer.writeAttributeString('xml', 'space', this.xmlNamespace, 'preserve');\n writer.writeString(span.text);\n writer.writeEndElement();\n }\n writer.writeEndElement();\n };\n // Serializes the paragraph format\n WordExport.prototype.serializeParagraphFormat = function (writer, paragraphFormat, paragraph) {\n if (!isNullOrUndefined(paragraphFormat.styleName)) {\n writer.writeStartElement(undefined, 'pStyle', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, paragraphFormat.styleName);\n writer.writeEndElement(); //end of pStyle\n }\n if (!isNullOrUndefined(paragraph)) {\n this.serializeListFormat(writer, paragraph.paragraphFormat.listFormat);\n }\n else {\n this.serializeListFormat(writer, paragraphFormat.listFormat);\n }\n this.serializeParagraphSpacing(writer, paragraphFormat);\n this.serializeIndentation(writer, paragraphFormat);\n this.serializeParagraphAlignment(writer, paragraphFormat.textAlignment);\n if (!isNullOrUndefined(paragraphFormat.tabs) && paragraphFormat.tabs.length > 0) {\n this.serializeTabs(writer, paragraphFormat.tabs);\n }\n };\n // Serialize Tabs\n WordExport.prototype.serializeTabs = function (writer, tabStops) {\n writer.writeStartElement('w', 'tabs', this.wNamespace);\n for (var i = 0; i < tabStops.length; i++) {\n this.serializeTab(writer, tabStops[i]);\n }\n writer.writeEndElement();\n };\n WordExport.prototype.serializeTab = function (writer, tabStop) {\n var position = 0;\n writer.writeStartElement('w', 'tab', this.wNamespace);\n if (tabStop.position === 0 && tabStop.deletePosition !== 0) {\n position = tabStop.deletePosition * this.twentiethOfPoint;\n writer.writeAttributeString('w', 'val', this.wNamespace, 'clear');\n }\n else {\n position = tabStop.position * this.twentiethOfPoint;\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getTabJustification(tabStop.tabJustification));\n }\n if (!isNullOrUndefined(tabStop.tabLeader) && (tabStop.tabLeader !== 'None')) {\n writer.writeAttributeString('w', 'leader', this.wNamespace, this.getTabLeader(tabStop.tabLeader));\n }\n writer.writeAttributeString('w', 'pos', this.wNamespace, position.toString() + '');\n writer.writeEndElement();\n };\n WordExport.prototype.getTabLeader = function (tabLeader) {\n switch (tabLeader) {\n case 'Dot':\n return 'dot';\n case 'Hyphen':\n return 'hyphen';\n case 'Underscore':\n return 'underscore';\n default:\n return 'none';\n }\n };\n WordExport.prototype.getTabJustification = function (tabJustification) {\n switch (tabJustification) {\n case 'Bar':\n return 'bar';\n case 'Center':\n return 'center';\n case 'Decimal':\n return 'decimal';\n case 'Left':\n return 'left';\n case 'List':\n return 'num';\n case 'Right':\n return 'right';\n default:\n return 'clear';\n }\n };\n // // Seraializes the pargraph list format\n // private serializeListParagraph(writer: XmlWriter, paragraph: any): void {\n // if (!isNullOrUndefined(paragraph.paragraphFormat.listFormat)) {\n // this.serializeListFormat(writer, paragraph.paragraphFormat.listFormat);\n // }\n // }\n // Serialize the list format\n WordExport.prototype.serializeListFormat = function (writer, lf) {\n // let pStyleName = undefined;\n // if (lf.CurrentListStyle.IsBuiltInStyle && !isNullOrUndefined(lf.OwnerParagraph))\n // {\n // pStyleName = lf.OwnerParagraph.StyleName;\n // }\n // int listId = GetListId(lf);\n // if (!isNullOrUndefined(pStyleName) && string.IsNullOrEmpty(lf.LFOStyleName)) \n // {\n // WordDocument doc = lf.OwnerParagraph.Document;\n // WParagraphStyle style = doc.Styles.FindByName(pStyleName, StyleType.ParagraphStyle) as WParagraphStyle;\n // if (style.ListIndex === -1)\n // {\n // ListStyle lstStyle = lf.OwnerParagraph.Document.ListStyles.FindByName(lf.CustomStyleName);\n // style.ListIndex = listId;\n // if (lstStyle.Levels.length > 1)\n // {\n // style.ListLevel = lf.ListLevelNumber;\n // }\n // pStyleName = pStyleName.Replace(' ', '');\n // lstStyle.Levels[lf.ListLevelNumber].ParaStyleName = pStyleName;\n // }\n // }\n // else\n // {\n // if (!isNullOrUndefined(lf.listId) && !isNullOrUndefined(lf.listLevelNumber)) {\n // this.serializeNumPr(writer, lf.listId, lf.listLevelNumber);\n // }\n // }\n if (!isNullOrUndefined(lf.listId) || !isNullOrUndefined(lf.listLevelNumber)) {\n writer.writeStartElement(undefined, 'numPr', this.wNamespace);\n if (!isNullOrUndefined(lf.listLevelNumber) && lf.listLevelNumber !== -1) {\n writer.writeStartElement(undefined, 'ilvl', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, lf.listLevelNumber.toString());\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(lf.listId) && lf.listId !== -1) {\n writer.writeStartElement(undefined, 'numId', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, (lf.listId + 1).toString());\n writer.writeEndElement();\n }\n writer.writeEndElement();\n }\n };\n // // Serializes the numbering properties to the paragraph\n // private serializeNumPr(writer: XmlWriter, listId: number, listLevel: number): void {\n // writer.writeStartElement(undefined, 'numPr', this.wNamespace);\n // if (listLevel !== -1) {\n // writer.writeStartElement(undefined, 'ilvl', this.wNamespace);\n // writer.writeAttributeString('w', 'val', this.wNamespace, listLevel.toString());\n // writer.writeEndElement();\n // }\n // if (listId !== -1) {\n // writer.writeStartElement(undefined, 'numId', this.wNamespace);\n // writer.writeAttributeString('w', 'val', this.wNamespace, listId.toString());\n // writer.writeEndElement();\n // }\n // writer.writeEndElement();\n // }\n WordExport.prototype.serializeParagraphAlignment = function (writer, txtAlignment) {\n if (!isNullOrUndefined(txtAlignment)) {\n writer.writeStartElement(undefined, 'jc', this.wNamespace);\n var alignment = void 0;\n switch (txtAlignment) {\n case 'Center':\n alignment = 'center';\n break;\n case 'Right':\n alignment = 'right';\n break;\n case 'Justify':\n alignment = 'both';\n break;\n default:\n alignment = 'left';\n break;\n }\n writer.writeAttributeString('w', 'val', this.wNamespace, alignment);\n writer.writeEndElement();\n }\n };\n // Serializes the paragraph spacings\n WordExport.prototype.serializeParagraphSpacing = function (writer, paragraphFormat) {\n writer.writeStartElement(undefined, 'spacing', this.wNamespace);\n // if (paragraphFormat.HasValue(WParagraphFormat.BeforeLinesKey))\n // {\n // short beforeLines = (short)Math.Round(paragraphFormat.BeforeLines * DLSConstants.HundredthsUnit);\n // writer.WriteAttributeString('beforeLines', this.wNamespace, ToString((float)beforeLines)); \n // }\n // if (paragraphFormat.HasValue(WParagraphFormat.AfterLinesKey))\n // {\n // short afterLines = (short)Math.Round(paragraphFormat.AfterLines * DLSConstants.HundredthsUnit);\n // writer.WriteAttributeString('afterLines', this.wNamespace, ToString((float)afterLines)); \n // }\n // tslint:disable-next-line:max-line-length\n if (!isNullOrUndefined(paragraphFormat.beforeSpacing)) {\n writer.writeAttributeString(undefined, 'before', this.wNamespace, this.roundToTwoDecimal(paragraphFormat.beforeSpacing * this.twentiethOfPoint).toString());\n }\n //TODO:ISSUEFIX(paragraphFormat.beforeSpacing * this.twentiethOfPoint).toString());\n // if (paragraphFormat.HasValue(WParagraphFormat.SpacingBeforeAutoKey))\n // {\n // if (paragraphFormat.SpaceBeforeAuto)\n // {\n // writer.WriteAttributeString('beforeAutospacing', this.wNamespace, '1');\n // }\n // else\n // {\n // writer.WriteAttributeString('beforeAutospacing', this.wNamespace, '0');\n // }\n // }\n if (!isNullOrUndefined(paragraphFormat.afterSpacing)) {\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'after', this.wNamespace, this.roundToTwoDecimal(paragraphFormat.afterSpacing * this.twentiethOfPoint).toString());\n }\n //TODO:ISSUEFIX(paragraphFormat.afterSpacing * this.twentiethOfPoint).toString());\n // if (paragraphFormat.HasValue(WParagraphFormat.SpacingAfterAutoKey))\n // {\n // if (paragraphFormat.SpaceAfterAuto)\n // {\n // writer.WriteAttributeString('afterAutospacing', this.wNamespace, '1');\n // }\n // else\n // {\n // writer.WriteAttributeString('afterAutospacing', this.wNamespace, '0');\n // }\n // }\n writer.writeAttributeString(undefined, 'line', this.wNamespace, '240');\n //TODO:ISSUEFIX((paragraphFormat.lineSpacing) * this.twentiethOfPoint).toString());\n switch (paragraphFormat.lineSpacingType) {\n case 'AtLeast':\n writer.writeAttributeString(undefined, 'lineRule', this.wNamespace, 'atLeast');\n break;\n case 'Exactly':\n writer.writeAttributeString(undefined, 'lineRule', this.wNamespace, 'exact');\n break;\n default:\n writer.writeAttributeString(undefined, 'lineRule', this.wNamespace, 'auto');\n break;\n }\n writer.writeEndElement();\n };\n // Serializes the paragraph indentation\n WordExport.prototype.serializeIndentation = function (writer, paragraphFormat) {\n writer.writeStartElement(undefined, 'ind', this.wNamespace);\n if (!isNullOrUndefined(paragraphFormat.leftIndent)) {\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'left', this.wNamespace, this.roundToTwoDecimal(paragraphFormat.leftIndent * this.twipsInOnePoint).toString());\n }\n if (!isNullOrUndefined(paragraphFormat.rightIndent)) {\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'right', this.wNamespace, this.roundToTwoDecimal(paragraphFormat.rightIndent * this.twipsInOnePoint).toString());\n }\n if (!isNullOrUndefined(paragraphFormat.firstLineIndent)) {\n if (paragraphFormat.firstLineIndent < 0) {\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'hanging', this.wNamespace, this.roundToTwoDecimal(-1 * paragraphFormat.firstLineIndent * this.twipsInOnePoint).toString());\n }\n else {\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString(undefined, 'firstLine', this.wNamespace, this.roundToTwoDecimal(paragraphFormat.firstLineIndent * this.twipsInOnePoint).toString());\n }\n }\n writer.writeEndElement();\n };\n // Serialize the styles (styles.xml)\n WordExport.prototype.serializeStyles = function () {\n var writer = new XmlWriter();\n writer.writeStartElement('w', 'styles', this.wNamespace);\n writer.writeAttributeString('xmlns', 'mc', undefined, this.veNamespace);\n writer.writeAttributeString('xmlns', 'r', undefined, this.rNamespace);\n writer.writeAttributeString('xmlns', 'w', undefined, this.wNamespace);\n writer.writeAttributeString('xmlns', 'w14', undefined, this.w14Namespace);\n writer.writeAttributeString('xmlns', 'w15', undefined, this.w15Namespace);\n writer.writeAttributeString('mc', 'Ignorable', undefined, 'w14 w15');\n //writes the document defaults, latent styles and default styles.\n this.serializeDefaultStyles(writer);\n //writes the document styles\n this.serializeDocumentStyles(writer);\n writer.writeEndElement(); //end of styles tag\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, this.stylePath);\n this.mArchive.addItem(zipArchiveItem); //this.stylePath, styleStream, false, FileAttributes.Archive);\n };\n // Serializes the default styles (document default paragraph and character format)\n WordExport.prototype.serializeDefaultStyles = function (writer) {\n writer.writeStartElement(undefined, 'docDefaults', this.wNamespace);\n //if (HasDefaultCharFormat())\n //{\n writer.writeStartElement(undefined, 'rPrDefault', this.wNamespace);\n // if (!isNullOrUndefined(this.mDocument.characterFormat)) {\n this.serializeCharacterFormat(writer, this.defCharacterFormat);\n writer.writeEndElement(); // end of rPrDefault\n // }\n // else {\n // writer.writeStartElement(undefined, 'rPr', this.wNamespace);\n // writer.writeStartElement(undefined, 'rFonts', this.wNamespace);\n // if (!string.IsNullOrEmpty(m_document.StandardAsciiFont))\n // writer.WriteAttributeString('ascii', this.wNamespace, m_document.StandardAsciiFont);\n // if (!string.IsNullOrEmpty(m_document.StandardFarEastFont))\n // writer.WriteAttributeString('eastAsia', this.wNamespace, m_document.StandardFarEastFont);\n // if (!string.IsNullOrEmpty(m_document.StandardNonFarEastFont))\n // writer.WriteAttributeString('hAnsi', this.wNamespace, m_document.StandardNonFarEastFont);\n // if (!string.IsNullOrEmpty(m_document.StandardBidiFont))\n // writer.WriteAttributeString('cs', this.wNamespace, m_document.StandardBidiFont);\n // writer.WriteEndElement();\n // float fontSize = GetDefFontSize(m_document, WCharacterFormat.FontSizeKey);\n // if (fontSize !== 0f)\n // {\n // writer.WriteStartElement('sz', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, (fontSize * 2).ToString(CultureInfo.InvariantCulture));\n // writer.WriteEndElement();\n // }\n // fontSize = GetDefFontSize(m_document, WCharacterFormat.FontSizeBidiKey);\n // if (fontSize !== 0f)\n // {\n // writer.WriteStartElement('szCs', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, (fontSize * 2).ToString(CultureInfo.InvariantCulture));\n // writer.WriteEndElement();\n // }\n // writer.WriteEndElement();\n // }\n // writer.WriteEndElement();\n // //}\n writer.writeStartElement(undefined, 'pPrDefault', this.wNamespace);\n if (!isNullOrUndefined(this.defParagraphFormat)) {\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n this.serializeParagraphFormat(writer, this.defParagraphFormat, undefined);\n writer.writeEndElement(); //end of pPr\n }\n writer.writeEndElement(); //end of pPrDefault\n // writer.WriteEndElement();\n // SerializeLatentStyles();\n // //Default styles\n // if (m_document.Styles.length === 0 || isNullOrUndefined(m_document.Styles.FindByName('Normal')))\n // {\n // SerializeDefaultParagraphStyle();\n // }\n // if (!IsDocumentContainsDefaultTableStyle())\n // {\n // SerializeTableNormalStyle();\n // }\n // if (isNullOrUndefined(m_document.Styles.FindByName('No List')) && isNullOrUndefined(m_document.Styles.FindByName('NoList')))\n // SerializeNoListStyle();\n // tslint:disable-next-line:max-line-length\n // if (isNullOrUndefined(m_document.Styles.FindByName('Table Grid')) && isNullOrUndefined(m_document.Styles.FindByName('TableGrid')))\n // {\n // SerializeTableGridStyle();\n // }\n // } \n writer.writeEndElement();\n };\n WordExport.prototype.serializeDocumentStyles = function (writer) {\n for (var i = 0; i < this.mStyles.length; i++) {\n var style = this.mStyles[i];\n writer.writeStartElement(undefined, 'style', this.wNamespace);\n var type = style.type === 'Paragraph' ? 'paragraph' : 'character';\n writer.writeAttributeString('w', 'type', this.wNamespace, type);\n writer.writeAttributeString('w', 'styleId', this.wNamespace, style.name);\n //name\n writer.writeStartElement(undefined, 'name', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, style.name);\n writer.writeEndElement();\n //basedOn\n if (!isNullOrUndefined(style.basedOn)) {\n writer.writeStartElement(undefined, 'basedOn', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, style.basedOn);\n writer.writeEndElement();\n }\n //next\n if (!isNullOrUndefined(style.next)) {\n writer.writeStartElement(undefined, 'next', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, style.next);\n writer.writeEndElement();\n }\n //link\n if (!isNullOrUndefined(style.link)) {\n writer.writeStartElement(undefined, 'link', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, style.link);\n writer.writeEndElement();\n }\n if (style.type === 'Paragraph') {\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n this.serializeParagraphFormat(writer, style.paragraphFormat, undefined);\n writer.writeEndElement();\n }\n // let value = (style.characterFormat as WCharacterFormat).newgetCharacterFormat();\n this.serializeCharacterFormat(writer, style.characterFormat);\n writer.writeEndElement(); //end of Style\n }\n };\n // Serializes the Character format\n WordExport.prototype.serializeCharacterFormat = function (writer, characterFormat) {\n writer.writeStartElement(undefined, 'rPr', this.wNamespace);\n if (!isNullOrUndefined(characterFormat.styleName)) {\n writer.writeStartElement(undefined, 'rStyle', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, characterFormat.styleName);\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.fontFamily)) {\n writer.writeStartElement(undefined, 'rFonts', this.wNamespace);\n writer.writeAttributeString(undefined, 'ascii', this.wNamespace, characterFormat.fontFamily);\n writer.writeAttributeString(undefined, 'hAnsi', this.wNamespace, characterFormat.fontFamily);\n writer.writeAttributeString(undefined, 'eastAsia', this.wNamespace, characterFormat.fontFamily);\n writer.writeAttributeString(undefined, 'cs', this.wNamespace, characterFormat.fontFamily);\n writer.writeEndElement(); //end \n }\n if (!isNullOrUndefined(characterFormat.bold)) {\n this.serializeBoolProperty(writer, 'b', characterFormat.bold);\n }\n if (!isNullOrUndefined(characterFormat.italic)) {\n this.serializeBoolProperty(writer, 'i', characterFormat.italic);\n }\n if (!isNullOrUndefined(characterFormat.strikethrough)) {\n switch (characterFormat.strikethrough) {\n case 'SingleStrike':\n this.serializeBoolProperty(writer, 'strike', true);\n break;\n case 'DoubleStrike':\n this.serializeBoolProperty(writer, 'dstrike', true);\n break;\n default:\n this.serializeBoolProperty(writer, 'strike', false);\n this.serializeBoolProperty(writer, 'dstrike', false);\n break;\n }\n }\n if (!isNullOrUndefined(characterFormat.fontColor)) {\n writer.writeStartElement(undefined, 'color', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getColor(characterFormat.fontColor));\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.fontSize)) {\n writer.writeStartElement(undefined, 'sz', this.wNamespace);\n // tslint:disable-next-line:max-line-length\n writer.writeAttributeString('w', 'val', this.wNamespace, this.roundToTwoDecimal(characterFormat.fontSize * 2).toString());\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.highlightColor) && characterFormat.highlightColor !== 'NoColor') {\n writer.writeStartElement(undefined, 'highlight', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getHighlightColor(characterFormat.highlightColor));\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.underline) && characterFormat.underline !== 'None') {\n writer.writeStartElement(undefined, 'u', this.wNamespace);\n writer.writeAttributeString('w', 'val', this.wNamespace, this.getUnderlineStyle(characterFormat.underline));\n writer.writeEndElement();\n }\n if (!isNullOrUndefined(characterFormat.baselineAlignment)) {\n writer.writeStartElement(undefined, 'vertAlign', this.wNamespace);\n switch (characterFormat.baselineAlignment) {\n case 'Subscript':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'subscript');\n break;\n case 'Superscript':\n writer.writeAttributeString('w', 'val', this.wNamespace, 'superscript');\n break;\n default:\n writer.writeAttributeString('w', 'val', this.wNamespace, 'baseline');\n break;\n }\n writer.writeEndElement();\n }\n writer.writeEndElement(); //end of rPrChange\n };\n WordExport.prototype.getColor = function (color) {\n if (color.length > 0) {\n if (color[0] === '#') {\n color = color.substr(1);\n }\n if (color.length > 6) {\n color = color.substr(0, 6);\n }\n }\n return color;\n };\n // Get the underline style as string\n WordExport.prototype.getUnderlineStyle = function (underlineStyle) {\n switch (underlineStyle) {\n case 'DotDotDashHeavy':\n return 'dashDotDotHeavy';\n case 'DotDashHeavy':\n return 'dashDotHeavy';\n case 'DashHeavy':\n return 'dashedHeavy';\n case 'DashLong':\n return 'dashLong';\n case 'DashLongHeavy':\n return 'dashLongHeavy';\n case 'DotDash':\n return 'dotDash';\n case 'DotDotDash':\n return 'dotDotDash';\n case 'Dotted':\n return 'dotted';\n case 'DottedHeavy':\n return 'dottedHeavy';\n case 'Double':\n return 'double';\n case 'Single':\n return 'single';\n case 'Thick':\n return 'thick';\n case 'Wavy':\n return 'wave';\n case 'WavyDouble':\n return 'wavyDouble';\n case 'WavyHeavy':\n return 'wavyHeavy';\n case 'Words':\n return 'words';\n default:\n return 'dash';\n }\n };\n WordExport.prototype.getHighlightColor = function (highlight) {\n switch (highlight) {\n // Highlights the content with bright green (#ff00ff00) color.\n case 'BrightGreen':\n return 'green';\n // Highlights the content with turquoise (#ff00ffff) color.\n case 'Turquoise':\n return 'cyan';\n // Highlights the content with pink (#ffff00ff) color.\n case 'Pink':\n return 'magenta';\n // Highlights the content with blue (#ff0000ff) color.\n case 'Blue':\n return 'blue';\n // Highlights the content with red (#ffff0000) color.\n case 'Red':\n return 'red';\n // Highlights the content with dark blue (#ff000080) color.\n case 'DarkBlue':\n return 'darkBlue';\n // Highlights the content with teal (#ff008080) color.\n case 'Teal':\n return 'darkCyan';\n // Highlights the content with green (#ff008000) color.\n case 'Green':\n return 'darkGreen';\n // Highlights the content with violet (#ff800080) color.\n case 'Violet':\n return 'darkMagenta';\n // Highlights the content with dark red (#ff800000) color.\n case 'DarkRed':\n return 'darkRed';\n // Highlights the content with dark yellow (#ff808000) color.\n case 'DarkYellow':\n return 'darkYellow';\n // Highlights the content with gray 50 (#ff808080) color.\n case 'Gray50':\n return 'darkGray';\n // Highlights the content with gray 25 (#ffc0c0c0) color.\n case 'Gray25':\n return 'lightGray';\n // Highlights the content with black (#ff000000) color.\n case 'Black':\n return 'black';\n // Highlights the content with yellow (#ffffff00) color.\n default:\n return 'yellow';\n }\n };\n /*private toggleFirstCahar(text: string) {\n return text.charAt(0).toLowerCase() + text.slice(1);\n }*/\n // Serializes the bool character format property\n WordExport.prototype.serializeBoolProperty = function (writer, tag, value) {\n writer.writeStartElement(undefined, tag, this.wNamespace);\n if (!value) {\n writer.writeAttributeString(undefined, 'val', this.wNamespace, '0');\n }\n writer.writeEndElement();\n };\n // Serialize the list styles and numberings (numberings.xml)\n WordExport.prototype.serializeNumberings = function () {\n if (this.document.lists.length === 0) {\n return;\n }\n var writer = new XmlWriter();\n writer.writeStartElement('w', 'numbering', this.wNamespace);\n this.writeCommonAttributeStrings(writer);\n // this.serializePictureBullets(writer, this.mDocument.lists);\n this.serializeAbstractListStyles(writer, this.document.abstractLists);\n this.serializeListInstances(writer, this.document.lists);\n // SerializeListOverrides(writer, this.mDocument.ridesm_document.ListOverrides);\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, this.numberingPath);\n this.mArchive.addItem(zipArchiveItem);\n };\n // Serializes the abstract list styles\n WordExport.prototype.serializeAbstractListStyles = function (writer, listStyles) {\n for (var i = 0; i < listStyles.length; i++) {\n var abstractList = listStyles[i];\n writer.writeStartElement(undefined, 'abstractNum', this.wNamespace);\n writer.writeAttributeString(undefined, 'abstractNumId', this.wNamespace, abstractList.abstractListId.toString());\n writer.writeStartElement(undefined, 'nsid', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, this.generateHex());\n writer.writeEndElement();\n for (var ilvl = 0, cnt = abstractList.levels.length; ilvl < cnt; ilvl++) {\n this.serializeListLevel(writer, abstractList.levels[ilvl], ilvl);\n }\n writer.writeEndElement(); //end of abstractNum\n }\n };\n // Serializes the list styles\n WordExport.prototype.serializeListInstances = function (writer, listStyles) {\n for (var i = 0; i < listStyles.length; i++) {\n var list = listStyles[i];\n writer.writeStartElement(undefined, 'num', this.wNamespace);\n writer.writeAttributeString(undefined, 'numId', this.wNamespace, (list.listId + 1).toString());\n writer.writeStartElement(undefined, 'abstractNumId', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, list.abstractListId.toString());\n writer.writeEndElement();\n writer.writeEndElement();\n }\n };\n WordExport.prototype.generateHex = function () {\n return (Math.floor(Math.random() * (4000000000 - 270000000)) + 270000000).toString(16).toUpperCase();\n };\n WordExport.prototype.roundToTwoDecimal = function (num) {\n return Math.round(num); // * 100) / 100;\n };\n // Serialize the list level\n WordExport.prototype.serializeListLevel = function (writer, listLevel, levelIndex) {\n writer.writeStartElement(undefined, 'lvl', this.wNamespace);\n writer.writeAttributeString(undefined, 'ilvl', this.wNamespace, levelIndex.toString());\n writer.writeStartElement(undefined, 'start', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, listLevel.startAt.toString());\n writer.writeEndElement();\n writer.writeStartElement(undefined, 'numFmt', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, this.getLevelPattern(listLevel.listLevelPattern));\n writer.writeEndElement();\n if (listLevel.restartLevel > 0) {\n writer.writeStartElement(undefined, 'lvlRestart', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, '0');\n writer.writeEndElement();\n }\n // if (!isNullOrUndefined(listLevel.paragraphFormat)) {\n // string name = listLevel.ParaStyleName.Substring(0, 1).ToUpper() + listLevel.ParaStyleName.Remove(0, 1);\n // writer.WriteStartElement('pStyle', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, name);\n // writer.WriteEndElement();\n // }\n // if (listLevel.IsLegalStyleNumbering) {\n // writer.WriteStartElement('isLgl', this.wNamespace);\n // writer.WriteEndElement();\n // }\n this.serializeLevelFollow(writer, listLevel);\n this.serializeLevelText(writer, listLevel, levelIndex + 1);\n // SerializeLegacyProperties(listLevel);\n // if (listLevel.PicBulletId > 0) {\n // writer.WriteStartElement('lvlPicBulletId', this.wNamespace);\n // writer.WriteAttributeString('val', this.wNamespace, listLevel.PicBulletId.ToString());\n // writer.WriteEndElement();\n // }\n // //lvlJc\n // if (listLevel.NumberAlignment !== ListNumberAlignment.Left) {\n // writer.WriteStartElement('lvlJc', this.wNamespace);\n // string alignment = string.Empty;\n // if (listLevel.NumberAlignment === ListNumberAlignment.Right) {\n // alignment = 'right';\n // }\n // else {\n // alignment = 'center';\n // }\n // writer.WriteAttributeString('val', this.wNamespace, alignment);\n // writer.WriteEndElement();\n // }\n writer.writeStartElement(undefined, 'pPr', this.wNamespace);\n this.serializeParagraphFormat(writer, listLevel.paragraphFormat, undefined);\n writer.writeEndElement(); //end of pPr\n this.serializeCharacterFormat(writer, listLevel.characterFormat);\n writer.writeEndElement();\n };\n WordExport.prototype.getLevelPattern = function (levelPattern) {\n var patternType;\n switch (levelPattern) {\n case 'Arabic':\n patternType = 'decimal';\n break;\n case 'UpRoman':\n patternType = 'upperRoman';\n break;\n case 'LowRoman':\n patternType = 'lowerRoman';\n break;\n case 'UpLetter':\n patternType = 'upperLetter';\n break;\n case 'LowLetter':\n patternType = 'lowerLetter';\n break;\n // case 'Ordinal':\n // patternType = 'ordinal';\n // break;\n // case 'Number':\n // patternType = 'cardinalText';\n // break;\n // case 'OrdinalText':\n // patternType = 'ordinalText';\n // break;\n // case 'LeadingZero':\n // patternType = 'decimalZero';\n // break;\n // case 'Bullet':\n default:\n patternType = 'bullet';\n break;\n }\n return patternType;\n };\n // Serializes the level text\n WordExport.prototype.serializeLevelText = function (writer, listLevel, lvlIndex) {\n writer.writeStartElement(undefined, 'lvlText', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, (listLevel.numberFormat));\n writer.writeEndElement();\n };\n // Serialize the level follow character\n WordExport.prototype.serializeLevelFollow = function (writer, listLevel) {\n var fc;\n //TODO:Type issue returns number instead of string\n if (listLevel.followCharacter === 'Tab') {\n fc = 'tab';\n }\n else if (listLevel.followCharacter === 'Space') {\n fc = 'space';\n }\n else {\n fc = 'nothing';\n }\n writer.writeStartElement(undefined, 'suff', this.wNamespace);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, fc);\n writer.writeEndElement();\n };\n WordExport.prototype.serializeSettings = function () {\n var writer = new XmlWriter();\n writer.writeStartElement('w', 'settings', this.wNamespace);\n this.writeCustom(writer);\n // writer.writeAttributeString('xmlns', 'mc', undefined, this.veNamespace);\n // writer.writeAttributeString('xmlns', 'o', undefined, this.oNamespace);\n // writer.writeAttributeString('xmlns', 'r', undefined, this.rNamespace);\n // writer.writeAttributeString('xmlns', 'm', undefined, this.mNamespace);\n // writer.writeAttributeString('xmlns', 'v', undefined, this.vNamespace);\n writer.writeAttributeString('xmlns', 'w10', undefined, this.w10Namespace);\n writer.writeAttributeString('xmlns', 'w14', undefined, this.w14Namespace);\n writer.writeAttributeString('xmlns', 'w15', undefined, this.w15Namespace);\n writer.writeAttributeString('xmlns', 'sl', undefined, this.slNamespace);\n writer.writeAttributeString('mc', 'Ignorable', undefined, 'w14 w15');\n // //w:writeProtection - Write Protection\n // if (m_document.WriteProtected)\n // {\n // writer.writeStartElement('w', 'writeProtection', this.wNamespace);\n // writer.writeAttributeString('recommended', this.wNamespace, '1');\n // writer.writeEndElement();\n // }\n //w:view - Document View Setting\n // if (this.mDocument.ViewSetup.DocumentViewType !== DocumentViewType.PrintLayout &&\n // m_document.ViewSetup.DocumentViewType !== DocumentViewType.NormalLayout)\n // {\n // writer.writeStartElement('view', this.wNamespace);\n // string viewTypeStr = string.Empty;\n // if (m_document.ViewSetup.DocumentViewType === DocumentViewType.OutlineLayout)\n // {\n // viewTypeStr = 'outline';\n // }\n // else if (m_document.ViewSetup.DocumentViewType === DocumentViewType.WebLayout)\n // {\n // viewTypeStr = 'web';\n // }\n // writer.writeAttributeString('val', this.wNamespace, viewTypeStr);\n // writer.writeEndElement();\n // }\n //w:zoom - Magnification Setting\n writer.writeStartElement('w', 'zoom', this.wNamespace);\n // switch (m_document.ViewSetup.ZoomType)\n // {\n // case ZoomType.FullPage:\n // writer.writeAttributeString('w', 'val', this.wNamespace, 'fullPage');\n // break;\n // case ZoomType.PageWidth:\n // writer.writeAttributeString('w', 'val', this.wNamespace, 'bestFit');\n // break;\n // case ZoomType.TextFit:\n // writer.writeAttributeString('w', 'val', this.wNamespace, 'textFit');\n // break;\n // default:\n writer.writeAttributeString('w', 'val', this.wNamespace, 'none');\n // break;\n // }\n writer.writeAttributeString('w', 'percent', this.wNamespace, '100');\n writer.writeEndElement();\n //w:displayBackgroundShape - Display Background Objects When Displaying Document\n // if (m_document.Background.Type !== BackgroundType.NoBackground)\n // {\n writer.writeStartElement(undefined, 'displayBackgroundShape', this.wNamespace);\n writer.writeEndElement();\n // }\n //w:defaultTabStop - Distance Between Automatic Tab Stops\n writer.writeStartElement(undefined, 'defaultTabStop', this.wNamespace);\n var tabWidth = Math.round(this.defaultTabWidthValue * this.twipsInOnePoint);\n writer.writeAttributeString(undefined, 'val', this.wNamespace, tabWidth.toString());\n writer.writeEndElement();\n //w:evenAndOddHeaders - Different Even/Odd Page Headers and Footers \n if (this.mDifferentFirstPage) {\n writer.writeStartElement(undefined, 'evenAndOddHeaders', this.wNamespace);\n writer.writeEndElement();\n }\n //w:footnotePr - Document-Wide Footnote Properties and w:endnotePr - Document-Wide Endnote Properties\n // SerializeFootnoteSettings();\n //w:compat - Compatibility Settings\n writer.writeStartElement(undefined, 'compat', this.wNamespace);\n writer.writeStartElement(undefined, 'compatSetting', this.wNamespace);\n writer.writeAttributeString(undefined, 'name', this.wNamespace, 'compatibilityMode');\n writer.writeAttributeString(undefined, 'uri', this.wNamespace, 'http://schemas.microsoft.com/office/word');\n writer.writeAttributeString(undefined, 'val', this.wNamespace, '15');\n writer.writeEndElement();\n writer.writeEndElement();\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, this.settingsPath);\n this.mArchive.addItem(zipArchiveItem);\n };\n WordExport.prototype.serializeCoreProperties = function () {\n //implementation\n };\n WordExport.prototype.serializeAppProperties = function () {\n //implementation\n };\n WordExport.prototype.serializeFontTable = function (contentType) {\n //implementation\n };\n WordExport.prototype.serializeSettingsRelation = function () {\n //implementation\n };\n WordExport.prototype.serializeHeaderFooters = function () {\n this.serializeHeaderFooter('EvenFooter');\n this.serializeHeaderFooter('EvenHeader');\n this.serializeHeaderFooter('FirstPageFooter');\n this.serializeHeaderFooter('FirstPageHeader');\n this.serializeHeaderFooter('OddFooter');\n this.serializeHeaderFooter('OddHeader');\n };\n // Serializes the Header/Footer\n WordExport.prototype.serializeHeaderFooter = function (hfType) {\n if (this.headersFooters.length === 0) {\n return;\n }\n var headerFooterPath;\n var headerFooterRelsPath;\n if (!this.headersFooters.containsKey(hfType)) {\n return;\n }\n var hfColl = this.headersFooters.get(hfType);\n var hf = undefined;\n for (var i = 0; i < hfColl.keys.length; i++) {\n var id = hfColl.keys[i];\n hf = hfColl.get(id);\n if (hfType === 'EvenHeader' || hfType === 'FirstPageHeader' ||\n hfType === 'OddHeader') {\n headerFooterPath = this.headerPath + id.replace('rId', '') + '.xml';\n headerFooterRelsPath = this.headerRelationPath + id.replace('rId', '') + '.xml.rels';\n this.serializeHeader(hf, id, headerFooterPath, headerFooterRelsPath);\n }\n else {\n headerFooterPath = this.footerPath + id.replace('rId', '') + '.xml';\n headerFooterRelsPath = this.footerRelationPath + id.replace('rId', '') + '.xml.rels';\n this.serializeFooter(hf, id, headerFooterPath, headerFooterRelsPath);\n }\n }\n };\n // Serialize the header part\n WordExport.prototype.serializeHeader = function (header, id, headerFooterPath, headerFooterRelsPath) {\n this.headerFooter = header;\n var writer = new XmlWriter();\n writer.writeStartElement('w', 'hdr', this.wNamespace);\n this.writeHFCommonAttributes(writer);\n var owner = this.blockOwner;\n this.blockOwner = header;\n this.serializeBodyItems(writer, header.blocks, true);\n this.blockOwner = owner;\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, headerFooterPath);\n this.mArchive.addItem(zipArchiveItem);\n this.serializeHFRelations(id, headerFooterRelsPath);\n this.headerFooter = undefined;\n };\n // Serializes the HeaderFooter relations\n WordExport.prototype.serializeHFRelations = function (hfId, headerFooterRelsPath) {\n var hasHFImage = this.headerFooterImages.containsKey(hfId);\n // let hasHFHyperlinks = HeaderFooterHyperlinks.ContainsKey(hfId);\n // let hasHFInclPics = HeaderFooterInclPicUrls.ContainsKey(hfId);\n // let hasHFAlternateChunks = HeaderFooterAlternateChunks.ContainsKey(hfId);\n if (hasHFImage) {\n var writer = new XmlWriter();\n writer.writeStartElement(undefined, 'Relationships', this.rpNamespace);\n this.serializeImagesRelations(this.headerFooterImages.get(hfId), writer);\n // if (hasHFHyperlinks)\n // SerializeHyperlinkRelations(stream, HeaderFooterHyperlinks[hfId]);\n // if (hasHFAlternateChunks)\n // SerializeAltChunkRelations(stream, HeaderFooterAlternateChunks[hfId]);\n // if (hasHFInclPics)\n // SerializeIncludePictureUrlRelations(stream, HeaderFooterInclPicUrls[hfId]);\n // if (HFOleContainers.ContainsKey(hfId))\n // {\n // AddOLEToZip(HFOleContainers[hfId]);\n // }\n // if (HFRelations.ContainsKey(hfId))\n // SerializeHFCommonRelations(stream, HFRelations[hfId]);\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, headerFooterRelsPath);\n this.mArchive.addItem(zipArchiveItem);\n }\n else {\n return;\n }\n };\n WordExport.prototype.writeHFCommonAttributes = function (writer) {\n writer.writeAttributeString('xmlns', 'v', undefined, this.vNamespace);\n writer.writeAttributeString('xmlns', 'w10', undefined, this.w10Namespace);\n writer.writeAttributeString('xmlns', 'o', undefined, this.oNamespace);\n writer.writeAttributeString('xmlns', 've', undefined, this.veNamespace);\n writer.writeAttributeString('xmlns', 'r', undefined, this.rNamespace);\n writer.writeAttributeString('xmlns', 'm', undefined, this.mNamespace);\n writer.writeAttributeString('xmlns', 'wne', undefined, this.wneNamespace);\n writer.writeAttributeString('xmlns', 'a', undefined, this.aNamespace);\n writer.writeAttributeString('xmlns', 'pic', undefined, this.pictureNamespace);\n writer.writeAttributeString('xmlns', 'wp', undefined, this.wpNamespace);\n writer.writeAttributeString('xmlns', 'wpc', undefined, this.wpCanvasNamespace);\n writer.writeAttributeString('xmlns', 'wp14', undefined, this.wpDrawingNamespace);\n this.writeDup(writer);\n writer.writeAttributeString('xmlns', 'wps', undefined, this.wpShapeNamespace);\n writer.writeAttributeString('ve', 'Ignorable', undefined, 'w14 w15 wp14');\n };\n // Serailize the footer and its relations\n WordExport.prototype.serializeFooter = function (footer, id, headerFooterPath, headerFooterRelsPath) {\n this.headerFooter = footer;\n var writer = new XmlWriter();\n writer.writeStartElement('w', 'ftr', this.wNamespace);\n this.writeHFCommonAttributes(writer);\n this.serializeBodyItems(writer, footer.blocks, true);\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, headerFooterPath);\n this.mArchive.addItem(zipArchiveItem);\n this.serializeHFRelations(id, headerFooterRelsPath);\n };\n WordExport.prototype.serializeDocumentRelations = function () {\n var writer = new XmlWriter();\n writer.writeStartElement(undefined, 'Relationships', this.rpNamespace);\n this.serializeRelationShip(writer, this.getNextRelationShipID(), this.stylesRelType, 'styles.xml');\n this.serializeRelationShip(writer, this.getNextRelationShipID(), this.settingsRelType, 'settings.xml');\n // this.serializeRelationShip(writer, this.getNextRelationShipID(), this.ThemeRelType, 'theme/theme1.xml');\n if (this.document.lists.length > 0) {\n this.serializeRelationShip(writer, this.getNextRelationShipID(), this.numberingRelType, 'numbering.xml');\n }\n this.serializeHeaderFooterRelations(writer);\n // if (HasFontTable) {\n // SerializeRelationShip(docRelstream, GetNextRelationShipID(), this.FontTableRelType, 'fontTable.xml');\n // }\n // SerializeIncludePictureUrlRelations(docRelstream, InclPicFieldUrl);\n // //// Creating relationships for every hyperlink and image containing in the document\n this.serializeImagesRelations(this.documentImages, writer);\n // SerializeSvgImageRelation();\n //this.serializeExternalLinkImages(writer);\n // if (HasHyperlink && HyperlinkTargets.length > 0) {\n // SerializeHyperlinkRelations(docRelstream, HyperlinkTargets);\n // }\n // if (m_document.HasMacros\n // && IsMacroEnabled)\n // SerializeRelationShip(docRelstream, GetNextRelationShipID(), this.VbaProjectRelType, this.VbaProject);\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, this.wordRelationPath);\n this.mArchive.addItem(zipArchiveItem);\n this.headerFooter = undefined;\n };\n // Serializes the image relations\n WordExport.prototype.serializeImagesRelations = function (images, writer) {\n if (images.length > 0) {\n var imagePath = '';\n var base64ImageString = void 0;\n var keys = images.keys;\n for (var i = 0; i < keys.length; i++) {\n var mImage = images.get(keys[i]);\n base64ImageString = mImage.imageString;\n if (isNullOrUndefined(base64ImageString)) {\n imagePath = this.imagePath + '/0.jpeg';\n this.serializeRelationShip(writer, keys[i], this.imageRelType, imagePath.replace('word/', ''));\n }\n else {\n var extension = '';\n var formatClippedString = '';\n if (this.startsWith(base64ImageString, 'data:image/bmp;base64,')) {\n extension = '.bmp';\n formatClippedString = base64ImageString.replace('data:image/bmp;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/x-emf;base64,')) {\n extension = '.emf';\n formatClippedString = base64ImageString.replace('data:image/x-emf;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/exif;base64,')) {\n extension = '.exif';\n formatClippedString = base64ImageString.replace('data:image/exif;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/gif;base64,')) {\n extension = '.gif';\n formatClippedString = base64ImageString.replace('data:image/gif;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/icon;base64,')) {\n extension = '.ico';\n formatClippedString = base64ImageString.replace('data:image/icon;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/jpeg;base64,')) {\n extension = '.jpeg';\n formatClippedString = base64ImageString.replace('data:image/jpeg;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/jpg;base64,')) {\n extension = '.jpg';\n formatClippedString = base64ImageString.replace('data:image/jpg;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/png;base64,')) {\n extension = '.png';\n formatClippedString = base64ImageString.replace('data:image/png;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/tiff;base64,')) {\n extension = '.tif';\n formatClippedString = base64ImageString.replace('data:image/tiff;base64,', '');\n }\n else if (this.startsWith(base64ImageString, 'data:image/x-wmf;base64,')) {\n extension = '.wmf';\n formatClippedString = base64ImageString.replace('data:image/x-wmf;base64,', '');\n }\n else {\n extension = '.jpeg';\n }\n imagePath = this.imagePath + keys[i] + extension;\n this.serializeRelationShip(writer, keys[i], this.imageRelType, imagePath.replace('word/', ''));\n //if (m_archive.Find(imagePath.Replace('\\\\', '/')) === -1)\n // {\n var imageBlob = new Blob([this.encodedString(formatClippedString)]);\n var zipArchiveItem = new ZipArchiveItem(imageBlob, imagePath);\n // let TestArchive = new ZipArchive();\n this.mArchive.addItem(zipArchiveItem);\n // TestArchive.save('image.zip').then(function (): void {\n // TestArchive.destroy();\n // });\n // }\n }\n }\n }\n };\n /**\n * @private\n */\n WordExport.prototype.encodedString = function (input) {\n var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n var chr1;\n var chr2;\n var chr3;\n var enc1;\n var enc2;\n var enc3;\n var enc4;\n var i = 0;\n var resultIndex = 0;\n /*let dataUrlPrefix: string = 'data:';*/\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n var totalLength = input.length * 3 / 4;\n if (input.charAt(input.length - 1) === keyStr.charAt(64)) {\n totalLength--;\n }\n if (input.charAt(input.length - 2) === keyStr.charAt(64)) {\n totalLength--;\n }\n if (totalLength % 1 !== 0) {\n // totalLength is not an integer, the length does not match a valid\n // base64 content. That can happen if:\n // - the input is not a base64 content\n // - the input is *almost* a base64 content, with a extra chars at the\n // beginning or at the end\n // - the input uses a base64 variant (base64url for example)\n throw new Error('Invalid base64 input, bad content length.');\n }\n var output = new Uint8Array(totalLength | 0);\n while (i < input.length) {\n enc1 = keyStr.indexOf(input.charAt(i++));\n enc2 = keyStr.indexOf(input.charAt(i++));\n enc3 = keyStr.indexOf(input.charAt(i++));\n enc4 = keyStr.indexOf(input.charAt(i++));\n chr1 = (enc1 << 2) | (enc2 >> 4);\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);\n chr3 = ((enc3 & 3) << 6) | enc4;\n output[resultIndex++] = chr1;\n if (enc3 !== 64) {\n output[resultIndex++] = chr2;\n }\n if (enc4 !== 64) {\n output[resultIndex++] = chr3;\n }\n }\n return output;\n };\n WordExport.prototype.serializeExternalLinkImages = function (writer) {\n var imagePath = '';\n var keys = this.externalImages.keys;\n for (var i = 0; i < this.externalImages.keys.length; i++) {\n this.serializeRelationShip(writer, keys[i], this.imageRelType, this.externalImages.get(keys[i]));\n }\n };\n // Serializes the HeaderFooters relations to the document relations stream\n WordExport.prototype.serializeHeaderFooterRelations = function (writer) {\n this.serializeHFRelation(writer, 'EvenFooter');\n this.serializeHFRelation(writer, 'EvenHeader');\n this.serializeHFRelation(writer, 'FirstPageFooter');\n this.serializeHFRelation(writer, 'FirstPageHeader');\n this.serializeHFRelation(writer, 'OddFooter');\n this.serializeHFRelation(writer, 'OddHeader');\n };\n // Serializes the headers footers relations.\n WordExport.prototype.serializeHFRelation = function (writer, hfType) {\n var headerFooterPath = '';\n var relType;\n if (!this.headersFooters.containsKey(hfType)) {\n return;\n }\n var hfColl = this.headersFooters.get(hfType);\n for (var i = 0; i < hfColl.keys.length; i++) {\n var id = hfColl.keys[i];\n if (hfType === 'EvenHeader' || hfType === 'FirstPageHeader' ||\n hfType === 'OddHeader') {\n headerFooterPath = 'header' + id.replace('rId', '') + '.xml';\n relType = this.headerRelType;\n }\n else {\n headerFooterPath = 'footer' + id.replace('rId', '') + '.xml';\n relType = this.footerRelType;\n }\n this.serializeRelationShip(writer, id, relType, headerFooterPath);\n }\n };\n // Serializes the relationship\n WordExport.prototype.serializeRelationShip = function (writer, relationshipID, relationshipType, targetPath) {\n writer.writeStartElement(undefined, 'Relationship', undefined);\n writer.writeAttributeString(undefined, 'Id', undefined, relationshipID);\n writer.writeAttributeString(undefined, 'Type', undefined, relationshipType);\n writer.writeAttributeString(undefined, 'Target', undefined, targetPath.replace('\\\\', '/').replace('\\v', ''));\n // tslint:disable-next-line:max-line-length\n if (relationshipType === this.hyperlinkRelType || this.startsWith(targetPath, 'http://') || this.startsWith(targetPath, 'https://') || this.startsWith(targetPath, 'file:///')) {\n // Uri targetUri;\n // if ((!targetPath.StartsWith('file:///')) && Uri.TryCreate(targetPath, UriKind.Absolute, out targetUri))\n // {\n // //Handled using Try catch to avoid exception if the Host name type is None because in \n //Silverlight 'HostNameType' property is not available.\n // try\n // {\n // m_writer.WriteAttributeString('Target', targetUri.AbsoluteUri);\n // }\n // catch\n // {\n // m_writer.WriteAttributeString('Target', targetPath.Replace('\\\\', '/').Replace(ControlChar.LineBreak, string.Empty));\n // }\n // }\n // else\n // {\n // m_writer.WriteAttributeString('Target', targetPath.Replace('\\\\', '/').Replace(ControlChar.LineBreak, string.Empty));\n // }\n writer.writeAttributeString(undefined, 'TargetMode', undefined, 'External');\n }\n writer.writeEndElement();\n };\n // Get the next relationship ID\n WordExport.prototype.getNextRelationShipID = function () {\n return 'rId' + (++this.mRelationShipID);\n };\n WordExport.prototype.serializeGeneralRelations = function () {\n var writer = new XmlWriter();\n this.resetRelationShipID();\n writer.writeStartElement(undefined, 'Relationships', this.rpNamespace);\n this.serializeRelationShip(writer, this.getNextRelationShipID(), this.documentRelType, this.documentPath);\n // this.serializeRelationShip(writer, this.getNextRelationShipID(), this.AppRelType, this.appPath);\n // this.serializeRelationShip(writer, this.getNextRelationShipID(), this.CoreRelType, this.corePath);\n //End of Relationships tag\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, this.generalRelationPath);\n this.mArchive.addItem(zipArchiveItem);\n };\n WordExport.prototype.serializeContentTypes = function (contentType) {\n var writer = new XmlWriter();\n writer.writeStartElement(undefined, 'Types', 'http://schemas.openxmlformats.org/package/2006/content-types');\n //if (m_hasOleObject)\n //{\n // // \n // SerializeDefaultContentType(contentStream, 'bin', 'application/vnd.openxmlformats-officedocument.oleObject');\n //}\n this.serializeDefaultContentType(writer, 'rels', this.relationContentType);\n this.serializeDefaultContentType(writer, 'xml', this.xmlContentType);\n // if (m_hasEmbedFonts && !string.IsNullOrEmpty(type))\n // {\n // SerializeDefaultContentType(contentStream,type, this.fontContentType);\n // }\n if (this.documentImages.length > 0 || this.externalImages.length > 0 || this.headerFooterImages.length > 0) {\n this.serializeDefaultContentType(writer, 'png', 'image/png');\n this.serializeDefaultContentType(writer, 'bmp', 'image/bmp');\n this.serializeDefaultContentType(writer, 'emf', 'image/x-emf');\n this.serializeDefaultContentType(writer, 'wmf', 'image/x-wmf');\n this.serializeDefaultContentType(writer, 'gif', 'image/gif');\n this.serializeDefaultContentType(writer, 'ico', 'image/x-icon');\n this.serializeDefaultContentType(writer, 'tif', 'image/tiff');\n this.serializeDefaultContentType(writer, 'tiff', 'image/tiff');\n this.serializeDefaultContentType(writer, 'jpeg', 'image/jpeg');\n this.serializeDefaultContentType(writer, 'jpg', 'image/jpeg');\n this.serializeDefaultContentType(writer, 'svg', 'image/svg+xml');\n }\n // if (m_document.HasMacros\n // && IsMacroEnabled && !m_isSkipBinExtension)\n // {\n // SerializeDefaultContentType(contentStream, 'bin', this.VbaProjectContentType);\n // m_isSkipBinExtension = true;\n // }\n // if (m_hasOleObject)\n // {\n // SerializeOleContentType(contentStream);\n // }\n //document.xml\n this.serializeOverrideContentType(writer, this.documentPath, this.documentContentType);\n // tslint:disable-next-line:max-line-length\n // \n // if (HasNumbering) {\n this.serializeOverrideContentType(writer, this.numberingPath, this.numberingContentType);\n // }\n //Add the header/footer Alternate chunks\n // if (HeaderFooterAlternateChunks.length > 0) {\n // foreach(Dictionary < string, string > item in m_headerFooterAlternateChunks.Values)\n // AddAlternateChunkItem(item);\n // }\n //styles.xml\n this.serializeOverrideContentType(writer, this.stylePath, this.stylesContentType);\n //settings.xml\n this.serializeOverrideContentType(writer, this.settingsPath, this.settingsContentType);\n // //core.xml\n // SerializeOverrideContentType(contentStream, this.corePath, this.CoreContentType);\n // //app.xml\n // SerializeOverrideContentType(contentStream, this.appPath, this.AppContentType);\n // //custom.xml\n // if (!isNullOrUndefined(m_document.CustomDocumentProperties) && m_document.CustomDocumentProperties.length > 0)\n // SerializeOverrideContentType(contentStream, this.CustomPath, this.CustomContentType);\n // #if Chart\n // if (m_hasChart)\n // SerializeChartContentType(contentStream);\n // #endif\n this.serializeHFContentTypes(writer);\n // WriteXmlItemsContentTypes(contentStream);\n //End of Types tag\n writer.writeEndElement();\n var zipArchiveItem = new ZipArchiveItem(writer.buffer, this.contentTypesPath);\n this.mArchive.addItem(zipArchiveItem);\n };\n // Serializes the HeaderFooter content types\n WordExport.prototype.serializeHFContentTypes = function (writer) {\n this.serializeHeaderFootersContentType(writer, 'EvenFooter');\n this.serializeHeaderFootersContentType(writer, 'EvenHeader');\n this.serializeHeaderFootersContentType(writer, 'FirstPageFooter');\n this.serializeHeaderFootersContentType(writer, 'FirstPageHeader');\n this.serializeHeaderFootersContentType(writer, 'OddFooter');\n this.serializeHeaderFootersContentType(writer, 'OddHeader');\n };\n // Serializes the HeaderFooter content types.\n WordExport.prototype.serializeHeaderFootersContentType = function (writer, headerFooterType) {\n var contentType;\n var partName;\n if (!this.headersFooters.containsKey(headerFooterType)) {\n return;\n }\n var hfColl = this.headersFooters.get(headerFooterType);\n for (var i = 0; i < hfColl.keys.length; i++) {\n var id = hfColl.keys[i];\n if (headerFooterType === 'EvenHeader' || headerFooterType === 'FirstPageHeader' ||\n headerFooterType === 'OddHeader') {\n partName = this.headerPath + id.replace('rId', '') + '.xml';\n contentType = this.headerContentType;\n }\n else {\n partName = this.footerPath + id.replace('rId', '') + '.xml';\n contentType = this.footerContentType;\n }\n this.serializeOverrideContentType(writer, partName, contentType);\n }\n };\n // Serializes the Override content type.\n WordExport.prototype.serializeOverrideContentType = function (writer, partName, contentType) {\n writer.writeStartElement(undefined, 'Override', undefined);\n writer.writeAttributeString(undefined, 'PartName', undefined, '/' + partName.replace('\\\\', '/'));\n writer.writeAttributeString(undefined, 'ContentType', undefined, contentType);\n writer.writeEndElement();\n };\n // Serializes the default content type\n WordExport.prototype.serializeDefaultContentType = function (writer, extension, contentType) {\n writer.writeStartElement(undefined, 'Default', undefined);\n writer.writeAttributeString(undefined, 'Extension', undefined, extension);\n writer.writeAttributeString(undefined, 'ContentType', undefined, contentType);\n writer.writeEndElement();\n };\n // Reset the relationship id counter\n WordExport.prototype.resetRelationShipID = function () {\n this.mRelationShipID = 0;\n };\n WordExport.prototype.close = function () {\n //Implement\n };\n return WordExport;\n}());\nexport { WordExport };\n","import { StreamWriter } from '@syncfusion/ej2-file-utils';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * Exports the document to Text format.\n */\nvar TextExport = /** @class */ (function () {\n function TextExport() {\n this.text = '';\n this.curSectionIndex = 0;\n this.inField = false;\n }\n TextExport.prototype.getModuleName = function () {\n return 'TextExport';\n };\n /**\n * @private\n */\n TextExport.prototype.save = function (viewer, fileName) {\n this.serialize(viewer);\n var writer = new StreamWriter();\n this.writeInternal(writer);\n writer.save(fileName + '.txt');\n };\n /**\n * @private\n */\n TextExport.prototype.saveAsBlob = function (viewer) {\n this.serialize(viewer);\n var streamWriter = new StreamWriter();\n this.writeInternal(streamWriter);\n var blob = streamWriter.buffer;\n streamWriter.destroy();\n var promise;\n return new Promise(function (resolve, reject) {\n resolve(blob);\n });\n };\n TextExport.prototype.serialize = function (viewer) {\n var document = viewer.owner.sfdtExportModule.write();\n this.setDocument(document);\n };\n TextExport.prototype.setDocument = function (document) {\n this.document = document;\n this.mSections = document.sections;\n };\n TextExport.prototype.writeInternal = function (streamWriter) {\n var section = undefined;\n var sectionCount = this.document.sections.length - 1;\n var isLastSection = false;\n this.updateLastParagraph();\n for (var i = 0; i <= sectionCount; i++) {\n section = this.document.sections[i];\n isLastSection = (i === sectionCount) ? true : false;\n this.writeBody(streamWriter, section.blocks);\n this.writeNewLine(streamWriter);\n this.writeSectionEnd(section, isLastSection);\n }\n for (var j = 0; j <= sectionCount; j++) {\n section = this.document.sections[j];\n this.writeHeadersFooters(streamWriter, section);\n }\n };\n /// \n /// Writes the specified document content to the text file.\n /// \n TextExport.prototype.writeBody = function (streamWriter, body) {\n var bodyItemsCount = body.length - 1;\n var bodyItem = undefined;\n for (var i = 0; i <= bodyItemsCount; i++) {\n bodyItem = body[i];\n if (bodyItem.hasOwnProperty('inlines')) {\n var isLastPara = (bodyItem === this.lastPara) ? true : false;\n this.writeParagraph(streamWriter, bodyItem, isLastPara);\n }\n else {\n this.writeTable(streamWriter, bodyItem);\n }\n }\n };\n TextExport.prototype.writeParagraph = function (streamWriter, paragraph, isLastPara) {\n for (var i = 0; i < paragraph.inlines.length; i++) {\n var item = paragraph.inlines[i];\n if (item.hasOwnProperty('fieldType')) {\n this.inField = item.fieldType === 0;\n }\n else if (item.hasOwnProperty('text') && !this.inField) {\n this.writeText(streamWriter, item.text);\n }\n }\n if (!isLastPara) {\n this.writeNewLine(streamWriter);\n }\n };\n /// }\n /// \n /// Writes the specified table text content to the text file.\n /// \n TextExport.prototype.writeTable = function (streamWriter, table) {\n for (var i = 0; i < table.rows.length; i++) {\n var row = table.rows[i];\n for (var j = 0; j < row.cells.length; j++) {\n var cell = row.cells[j];\n this.writeBody(streamWriter, cell.blocks);\n }\n }\n };\n /// \n /// Writes the specified Header Footer text content to the text file.\n /// \n TextExport.prototype.writeHeadersFooters = function (streamWriter, section) {\n var headersFooters = section.headersFooters;\n if (isNullOrUndefined(headersFooters)) {\n return;\n }\n this.writeHeaderFooter(streamWriter, section.headersFooters.header);\n this.writeHeaderFooter(streamWriter, section.headersFooters.footer);\n this.writeHeaderFooter(streamWriter, section.headersFooters.evenFooter);\n this.writeHeaderFooter(streamWriter, section.headersFooters.evenHeader);\n this.writeHeaderFooter(streamWriter, section.headersFooters.firstPageHeader);\n this.writeHeaderFooter(streamWriter, section.headersFooters.firstPageFooter);\n };\n TextExport.prototype.writeHeaderFooter = function (streamWriter, headerFooter) {\n if (headerFooter && headerFooter.blocks) {\n this.writeBody(streamWriter, headerFooter.blocks);\n }\n };\n /// \n /// Writes the end of the section.\n /// \n TextExport.prototype.writeSectionEnd = function (section, lastSection) {\n this.curSectionIndex++;\n };\n TextExport.prototype.writeNewLine = function (writer) {\n writer.writeLine('');\n };\n TextExport.prototype.writeText = function (writer, text) {\n writer.write(text);\n };\n TextExport.prototype.updateLastParagraph = function () {\n var cnt = this.document.sections.length;\n var sec;\n if (cnt > 0) {\n sec = this.document.sections[cnt - 1];\n }\n if (!isNullOrUndefined(sec)) {\n var paragraphs = [];\n for (var i = 0; i < sec.blocks.length; i++) {\n if (sec.blocks[i].hasOwnProperty('inlines')) {\n paragraphs.push(sec.blocks[i]);\n }\n }\n var pCount = paragraphs.length;\n if (pCount > 0) {\n this.lastPara = paragraphs[pCount - 1];\n }\n }\n };\n /**\n * @private\n */\n TextExport.prototype.destroy = function () {\n this.document = undefined;\n this.lastPara = undefined;\n this.mSections = undefined;\n this.sections = undefined;\n };\n return TextExport;\n}());\nexport { TextExport };\n","import { LineWidget, ParagraphWidget, BodyWidget, TextElementBox, FieldElementBox, TableRowWidget, TableCellWidget, ImageElementBox, ListTextElementBox, BookmarkElementBox } from '../viewer/page';\nimport { BlockWidget } from '../viewer/page';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { HelperMethods } from '../editor/editor-helper';\nimport { StreamWriter } from '@syncfusion/ej2-file-utils';\n/**\n * Exports the document to Sfdt format.\n */\nvar SfdtExport = /** @class */ (function () {\n /**\n * @private\n */\n function SfdtExport(owner) {\n /* tslint:disable:no-any */\n this.endLine = undefined;\n this.endOffset = undefined;\n this.endCell = undefined;\n this.startColumnIndex = undefined;\n this.endColumnIndex = undefined;\n this.lists = undefined;\n this.viewer = undefined;\n this.document = undefined;\n this.writeInlineStyles = undefined;\n this.viewer = owner;\n }\n SfdtExport.prototype.getModuleName = function () {\n return 'SfdtExport';\n };\n SfdtExport.prototype.clear = function () {\n this.writeInlineStyles = undefined;\n this.endLine = undefined;\n this.lists = undefined;\n this.document = undefined;\n };\n /**\n * Serialize the data as Syncfusion document text.\n * @private\n */\n SfdtExport.prototype.serialize = function () {\n return JSON.stringify(this.write());\n };\n /**\n * @private\n */\n SfdtExport.prototype.saveAsBlob = function (viewer) {\n var streamWriter = new StreamWriter();\n streamWriter.write(this.serialize());\n var blob = streamWriter.buffer;\n streamWriter.destroy();\n var promise;\n return new Promise(function (resolve, reject) {\n resolve(blob);\n });\n };\n // tslint:disable-next-line:max-line-length\n /**\n * @private\n */\n SfdtExport.prototype.write = function (line, startOffset, endLine, endOffset, writeInlineStyles) {\n if (writeInlineStyles) {\n this.writeInlineStyles = true;\n }\n this.lists = [];\n this.document = {};\n this.document.sections = [];\n this.document.characterFormat = this.writeCharacterFormat(this.viewer.characterFormat);\n this.document.paragraphFormat = this.writeParagraphFormat(this.viewer.paragraphFormat);\n if (line instanceof LineWidget && endLine instanceof LineWidget) {\n // For selection\n var startPara = line.paragraph;\n var endPara = endLine.paragraph;\n var startCell = startPara.associatedCell;\n var endCell = endPara.associatedCell;\n // Creates section\n var bodyWidget = startPara.bodyWidget;\n var section = this.createSection(line.paragraph.bodyWidget);\n this.document.sections.push(section);\n if (startCell === endCell || isNullOrUndefined(endCell)) {\n this.endLine = endLine;\n this.endOffset = endOffset;\n }\n else {\n // Todo: Handle nested table cases\n if (startCell instanceof TableCellWidget) {\n var startTable = startCell.getContainerTable();\n var endTable = endCell.getContainerTable();\n if (startTable.tableFormat === endTable.tableFormat) {\n this.endCell = endCell;\n this.endColumnIndex = this.endCell.columnIndex + this.endCell.cellFormat.columnSpan;\n this.startColumnIndex = startCell.columnIndex;\n }\n }\n else {\n this.endCell = endCell;\n }\n }\n if (startCell === endCell || isNullOrUndefined(startCell)) {\n var paragraph = this.createParagraph(line.paragraph);\n section.blocks.push(paragraph);\n if (!this.writeParagraph(line.paragraph, paragraph, section.blocks, line.indexInOwner, startOffset)) {\n // Todo:continue in next section\n }\n }\n else {\n var table = this.createTable(startCell.ownerTable);\n section.blocks.push(table);\n this.writeTable(startCell.ownerTable, table, startCell.ownerRow.indexInOwner, section.blocks);\n }\n }\n else {\n if (this.viewer.pages.length > 0) {\n var page = this.viewer.pages[0];\n if (page.bodyWidgets.length > 0) {\n this.writeBodyWidget(page.bodyWidgets[0], 0);\n }\n }\n }\n this.writeStyles(this.viewer);\n this.writeLists(this.viewer);\n var doc = this.document;\n this.clear();\n return doc;\n };\n SfdtExport.prototype.writeBodyWidget = function (bodyWidget, index) {\n if (!(bodyWidget instanceof BodyWidget)) {\n return true;\n }\n var section = this.createSection(bodyWidget);\n this.document.sections.push(section);\n this.writeHeaderFooters(this.viewer.headersFooters[bodyWidget.index], section);\n if (this.writeBlock(bodyWidget.childWidgets[index], 0, section.blocks)) {\n return true;\n }\n var next = bodyWidget;\n do {\n bodyWidget = next;\n next = next.nextRenderedWidget;\n } while (next instanceof BodyWidget && next.index === bodyWidget.index);\n return this.writeBodyWidget(next, index);\n };\n SfdtExport.prototype.writeHeaderFooters = function (hfs, section) {\n if (isNullOrUndefined(hfs)) {\n return;\n }\n section.headersFooters.header = this.writeHeaderFooter(hfs[0]);\n section.headersFooters.footer = this.writeHeaderFooter(hfs[1]);\n section.headersFooters.evenHeader = this.writeHeaderFooter(hfs[2]);\n section.headersFooters.evenFooter = this.writeHeaderFooter(hfs[3]);\n section.headersFooters.firstPageHeader = this.writeHeaderFooter(hfs[4]);\n section.headersFooters.firstPageFooter = this.writeHeaderFooter(hfs[5]);\n };\n SfdtExport.prototype.writeHeaderFooter = function (widget) {\n if (isNullOrUndefined(widget)) {\n return undefined;\n }\n var headerFooter = {};\n if (widget && widget.childWidgets && widget.childWidgets.length > 0) {\n headerFooter.blocks = [];\n this.writeBlock(widget.firstChild, 0, headerFooter.blocks);\n }\n return headerFooter;\n };\n SfdtExport.prototype.createSection = function (bodyWidget) {\n var section = {};\n section.sectionFormat = {};\n section.sectionFormat.pageWidth = bodyWidget.sectionFormat.pageWidth;\n section.sectionFormat.pageHeight = bodyWidget.sectionFormat.pageHeight;\n section.sectionFormat.leftMargin = bodyWidget.sectionFormat.leftMargin;\n section.sectionFormat.rightMargin = bodyWidget.sectionFormat.rightMargin;\n section.sectionFormat.topMargin = bodyWidget.sectionFormat.topMargin;\n section.sectionFormat.bottomMargin = bodyWidget.sectionFormat.bottomMargin;\n section.sectionFormat.differentFirstPage = bodyWidget.sectionFormat.differentFirstPage;\n section.sectionFormat.differentOddAndEvenPages = bodyWidget.sectionFormat.differentOddAndEvenPages;\n section.sectionFormat.headerDistance = bodyWidget.sectionFormat.headerDistance;\n section.sectionFormat.footerDistance = bodyWidget.sectionFormat.footerDistance;\n section.blocks = [];\n section.headersFooters = {};\n return section;\n };\n SfdtExport.prototype.writeBlock = function (widget, index, blocks) {\n if (!(widget instanceof BlockWidget)) {\n return true;\n }\n if (widget instanceof ParagraphWidget) {\n var paragraph = this.createParagraph(widget);\n blocks.push(paragraph);\n if (this.writeParagraph(widget, paragraph, blocks)) {\n return true;\n }\n }\n else {\n var tableWidget = widget;\n var table = this.createTable(tableWidget);\n blocks.push(table);\n if (this.writeTable(tableWidget, table, 0, blocks)) {\n return true;\n }\n }\n return false;\n };\n SfdtExport.prototype.writeNextBlock = function (widget, blocks) {\n var next = widget.nextRenderedWidget;\n if (next instanceof BlockWidget && next.containerWidget.index === widget.containerWidget.index) {\n return this.writeBlock(widget.nextRenderedWidget, 0, blocks);\n }\n return false;\n };\n SfdtExport.prototype.writeParagraph = function (paragraphWidget, paragraph, blocks, lineIndex, start) {\n if (isNullOrUndefined(lineIndex)) {\n lineIndex = 0;\n }\n if (isNullOrUndefined(start)) {\n start = 0;\n }\n var next = paragraphWidget;\n while (next instanceof ParagraphWidget) {\n if (this.writeLines(next, lineIndex, start, paragraph.inlines)) {\n return true;\n }\n lineIndex = 0;\n start = 0;\n paragraphWidget = next;\n next = paragraphWidget.nextSplitWidget;\n }\n return this.writeNextBlock(paragraphWidget, blocks);\n };\n SfdtExport.prototype.writeInlines = function (line, inlines) {\n for (var i = 0; i < line.children.length; i++) {\n var element = line.children[i];\n if (element instanceof ListTextElementBox) {\n continue;\n }\n var inline = this.writeInline(element);\n if (!isNullOrUndefined(inline)) {\n inlines.push(inline);\n }\n }\n };\n SfdtExport.prototype.writeInline = function (element) {\n var inline = {};\n inline.characterFormat = this.writeCharacterFormat(element.characterFormat);\n if (element instanceof FieldElementBox) {\n inline.fieldType = element.fieldType;\n }\n else if (element instanceof ImageElementBox) {\n inline.imageString = element.imageString;\n inline.width = HelperMethods.convertPixelToPoint(element.width);\n inline.height = HelperMethods.convertPixelToPoint(element.height);\n }\n else if (element instanceof BookmarkElementBox) {\n inline.bookmarkType = element.bookmarkType;\n inline.name = element.name;\n }\n else if (element instanceof TextElementBox) {\n inline.text = element.text;\n }\n else {\n inline = undefined;\n }\n return inline;\n };\n SfdtExport.prototype.writeLines = function (paragraph, lineIndex, offset, inlines) {\n var startIndex = lineIndex;\n var endParagraph = this.endLine instanceof LineWidget && this.endLine.paragraph === paragraph;\n var endIndex = endParagraph ? this.endLine.indexInOwner : paragraph.childWidgets.length - 1;\n for (var i = startIndex; i <= endIndex; i++) {\n var child = paragraph.childWidgets[i];\n if (this.endLine === child || (lineIndex === i && offset !== 0)) {\n this.writeLine(child, offset, inlines);\n }\n else {\n this.writeInlines(child, inlines);\n }\n }\n return endParagraph;\n };\n SfdtExport.prototype.writeLine = function (line, offset, inlines) {\n var isEnd = line === this.endLine;\n var started = false;\n var ended = false;\n var length = 0;\n for (var j = 0; j < line.children.length; j++) {\n var element = line.children[j];\n if (element instanceof ListTextElementBox) {\n continue;\n }\n var inline = undefined;\n length += element.length;\n started = length > offset;\n ended = isEnd && length >= this.endOffset;\n if (!started) {\n continue;\n }\n inline = this.writeInline(element);\n inlines[inlines.length] = inline;\n if (length > offset || ended) {\n if (inline.hasOwnProperty('text')) {\n var startIndex = length - element.length;\n var indexInInline = offset - startIndex;\n var endIndex = ended ? this.endOffset - startIndex : element.length;\n inline.text = inline.text.substring(indexInInline, endIndex);\n }\n offset = -1;\n }\n if (ended) {\n break;\n }\n }\n };\n SfdtExport.prototype.createParagraph = function (paragraphWidget) {\n var paragraph = {};\n paragraph.paragraphFormat = this.writeParagraphFormat(paragraphWidget.paragraphFormat);\n paragraph.characterFormat = this.writeCharacterFormat(paragraphWidget.characterFormat);\n paragraph.inlines = [];\n return paragraph;\n };\n /**\n * @private\n */\n SfdtExport.prototype.writeCharacterFormat = function (format, isInline) {\n var characterFormat = {};\n HelperMethods.writeCharacterFormat(characterFormat, isInline, format);\n if (this.writeInlineStyles && !isInline) {\n characterFormat.inlineFormat = this.writeCharacterFormat(format, true);\n }\n return characterFormat;\n };\n SfdtExport.prototype.writeParagraphFormat = function (format, isInline) {\n var paragraphFormat = {};\n paragraphFormat.leftIndent = isInline ? format.leftIndent : format.getValue('leftIndent');\n paragraphFormat.rightIndent = isInline ? format.rightIndent : format.getValue('rightIndent');\n paragraphFormat.firstLineIndent = isInline ? format.firstLineIndent : format.getValue('firstLineIndent');\n paragraphFormat.textAlignment = isInline ? format.textAlignment : format.getValue('textAlignment');\n paragraphFormat.beforeSpacing = isInline ? format.beforeSpacing : format.getValue('beforeSpacing');\n paragraphFormat.afterSpacing = isInline ? format.afterSpacing : format.getValue('afterSpacing');\n paragraphFormat.lineSpacing = isInline ? format.lineSpacing : format.getValue('lineSpacing');\n paragraphFormat.lineSpacingType = isInline ? format.lineSpacingType : format.getValue('lineSpacingType');\n paragraphFormat.styleName = !isNullOrUndefined(format.baseStyle) ? format.baseStyle.name : undefined;\n paragraphFormat.outlineLevel = isInline ? format.outlineLevel : format.getValue('outlineLevel');\n paragraphFormat.listFormat = this.writeListFormat(format.listFormat, isInline);\n paragraphFormat.tabs = this.writeTabs(format.tabs);\n if (this.writeInlineStyles && !isInline) {\n paragraphFormat.inlineFormat = this.writeParagraphFormat(format, true);\n }\n return paragraphFormat;\n };\n SfdtExport.prototype.writeTabs = function (tabStops) {\n if (isNullOrUndefined(tabStops) || tabStops.length < 1) {\n return undefined;\n }\n var tabs = [];\n for (var i = 0; i < tabStops.length; i++) {\n var tabStop = tabStops[i];\n var tab = {};\n tab.position = tabStop.position;\n tab.deletePosition = tabStop.deletePosition;\n tab.tabJustification = tabStop.tabJustification;\n tab.tabLeader = tabStop.tabLeader;\n tabs.push(tab);\n }\n return tabs;\n };\n /**\n * @private\n */\n SfdtExport.prototype.writeListFormat = function (format, isInline) {\n var listFormat = {};\n var listIdValue = format.getValue('listId');\n if (!isNullOrUndefined(listIdValue) && listIdValue > -1) {\n listFormat.listId = listIdValue;\n listFormat.listLevelNumber = format.getValue('listLevelNumber');\n if (this.lists.indexOf(format.listId) < 0) {\n this.lists.push(format.listId);\n }\n }\n return listFormat;\n };\n SfdtExport.prototype.writeTable = function (tableWidget, table, index, blocks) {\n var widget = tableWidget.childWidgets[index];\n if (widget instanceof TableRowWidget) {\n if (this.writeRow(widget, table.rows)) {\n return true;\n }\n }\n var next = tableWidget;\n do {\n tableWidget = next;\n next = tableWidget.nextSplitWidget;\n } while (next instanceof BlockWidget);\n return this.writeNextBlock(tableWidget, blocks);\n };\n SfdtExport.prototype.writeRow = function (rowWidget, rows) {\n if (!(rowWidget instanceof TableRowWidget)) {\n return false;\n }\n var row = this.createRow(rowWidget);\n rows.push(row);\n for (var i = 0; i < rowWidget.childWidgets.length; i++) {\n var widget = rowWidget.childWidgets[i];\n if (widget instanceof TableCellWidget) {\n if (rowWidget.index === widget.rowIndex\n && (isNullOrUndefined(this.startColumnIndex) || widget.columnIndex >= this.startColumnIndex)\n && (isNullOrUndefined(this.endColumnIndex) || widget.columnIndex < this.endColumnIndex)) {\n if (this.writeCell(widget, row.cells)) {\n return true;\n }\n }\n }\n }\n var next = rowWidget;\n do {\n rowWidget = next;\n next = rowWidget.nextRenderedWidget;\n } while (next instanceof TableRowWidget && next.index === rowWidget.index);\n return this.writeRow(next, rows);\n };\n SfdtExport.prototype.writeCell = function (cellWidget, cells) {\n var cell = this.createCell(cellWidget);\n cells.push(cell);\n if (this.writeBlock(cellWidget.firstChild, 0, cell.blocks)) {\n return true;\n }\n return this.endCell instanceof TableCellWidget ? this.endCell.cellFormat === cellWidget.cellFormat : false;\n };\n SfdtExport.prototype.createTable = function (tableWidget) {\n var table = {};\n table.rows = [];\n table.grid = [];\n for (var i = 0; i < tableWidget.tableHolder.columns.length; i++) {\n table.grid[i] = tableWidget.tableHolder.columns[i].preferredWidth;\n }\n table.tableFormat = this.writeTableFormat(tableWidget.tableFormat);\n table.description = tableWidget.description;\n table.title = tableWidget.title;\n return table;\n };\n SfdtExport.prototype.createRow = function (rowWidget) {\n var row = {};\n row.cells = [];\n row.rowFormat = this.writeRowFormat(rowWidget.rowFormat);\n return row;\n };\n SfdtExport.prototype.createCell = function (cellWidget) {\n var cell = {};\n cell.blocks = [];\n cell.cellFormat = this.writeCellFormat(cellWidget.cellFormat);\n cell.columnIndex = cellWidget.columnIndex;\n return cell;\n };\n SfdtExport.prototype.writeShading = function (wShading) {\n var shading = {};\n shading.backgroundColor = wShading.backgroundColor;\n shading.foregroundColor = wShading.foregroundColor;\n shading.textureStyle = wShading.textureStyle;\n return shading;\n };\n SfdtExport.prototype.writeBorder = function (wBorder) {\n var border = {};\n border.color = wBorder.color;\n border.hasNoneStyle = wBorder.hasNoneStyle;\n border.lineStyle = wBorder.lineStyle;\n border.lineWidth = wBorder.lineWidth;\n border.shadow = wBorder.shadow;\n border.space = wBorder.space;\n return border;\n };\n SfdtExport.prototype.writeBorders = function (wBorders) {\n var borders = {};\n borders.top = this.writeBorder(wBorders.top);\n borders.left = this.writeBorder(wBorders.left);\n borders.right = this.writeBorder(wBorders.right);\n borders.bottom = this.writeBorder(wBorders.bottom);\n borders.diagonalDown = this.writeBorder(wBorders.diagonalDown);\n borders.diagonalUp = this.writeBorder(wBorders.diagonalUp);\n borders.horizontal = this.writeBorder(wBorders.horizontal);\n borders.vertical = this.writeBorder(wBorders.vertical);\n return borders;\n };\n SfdtExport.prototype.writeCellFormat = function (wCellFormat) {\n var cellFormat = {};\n cellFormat.borders = this.writeBorders(wCellFormat.borders);\n cellFormat.shading = this.writeShading(wCellFormat.shading);\n cellFormat.topMargin = wCellFormat.topMargin;\n cellFormat.rightMargin = wCellFormat.rightMargin;\n cellFormat.leftMargin = wCellFormat.leftMargin;\n cellFormat.bottomMargin = wCellFormat.bottomMargin;\n cellFormat.preferredWidth = wCellFormat.preferredWidth;\n cellFormat.preferredWidthType = wCellFormat.preferredWidthType;\n cellFormat.cellWidth = wCellFormat.cellWidth;\n cellFormat.columnSpan = wCellFormat.columnSpan;\n cellFormat.rowSpan = wCellFormat.rowSpan;\n cellFormat.verticalAlignment = wCellFormat.verticalAlignment;\n return cellFormat;\n };\n SfdtExport.prototype.writeRowFormat = function (wRowFormat) {\n var rowFormat = {};\n rowFormat.height = wRowFormat.height;\n rowFormat.allowBreakAcrossPages = wRowFormat.allowBreakAcrossPages;\n rowFormat.heightType = wRowFormat.heightType;\n rowFormat.isHeader = wRowFormat.isHeader;\n rowFormat.borders = this.writeBorders(wRowFormat.borders);\n rowFormat.gridBefore = wRowFormat.gridBefore;\n rowFormat.gridBeforeWidth = wRowFormat.gridBeforeWidth;\n rowFormat.gridBeforeWidthType = wRowFormat.gridBeforeWidthType;\n rowFormat.gridAfter = wRowFormat.gridAfter;\n rowFormat.gridAfterWidth = wRowFormat.gridAfterWidth;\n rowFormat.gridAfterWidthType = wRowFormat.gridAfterWidthType;\n return rowFormat;\n };\n SfdtExport.prototype.writeTableFormat = function (wTableFormat) {\n var tableFormat = {};\n tableFormat.borders = this.writeBorders(wTableFormat.borders);\n tableFormat.shading = this.writeShading(wTableFormat.shading);\n tableFormat.cellSpacing = wTableFormat.cellSpacing;\n tableFormat.leftIndent = wTableFormat.leftIndent;\n tableFormat.tableAlignment = wTableFormat.tableAlignment;\n tableFormat.topMargin = wTableFormat.topMargin;\n tableFormat.rightMargin = wTableFormat.rightMargin;\n tableFormat.leftMargin = wTableFormat.leftMargin;\n tableFormat.bottomMargin = wTableFormat.bottomMargin;\n tableFormat.preferredWidth = wTableFormat.preferredWidth;\n tableFormat.preferredWidthType = wTableFormat.preferredWidthType;\n return tableFormat;\n };\n SfdtExport.prototype.writeStyles = function (viewer) {\n var styles = [];\n this.document.styles = [];\n for (var i = 0; i < viewer.styles.length; i++) {\n this.document.styles.push(this.writeStyle(viewer.styles.getItem(i)));\n }\n };\n SfdtExport.prototype.writeStyle = function (style) {\n var wStyle = {};\n wStyle.name = style.name;\n if (style.type === 'Paragraph') {\n wStyle.type = 'Paragraph';\n wStyle.paragraphFormat = this.writeParagraphFormat(style.paragraphFormat);\n wStyle.characterFormat = this.writeCharacterFormat(style.characterFormat);\n }\n if (style.type === 'Character') {\n wStyle.type = 'Character';\n wStyle.characterFormat = this.writeCharacterFormat(style.characterFormat);\n }\n if (!isNullOrUndefined(style.basedOn)) {\n wStyle.basedOn = style.basedOn.name;\n }\n if (!isNullOrUndefined(style.link)) {\n wStyle.link = style.link.name;\n }\n if (!isNullOrUndefined(style.next)) {\n wStyle.next = style.next.name;\n }\n return wStyle;\n };\n SfdtExport.prototype.writeLists = function (viewer) {\n var abstractLists = [];\n this.document.lists = [];\n for (var i = 0; i < viewer.lists.length; i++) {\n var list = viewer.lists[i];\n if (this.lists.indexOf(list.listId) > -1) {\n this.document.lists.push(this.writeList(list));\n if (abstractLists.indexOf(list.abstractListId) < 0) {\n abstractLists.push(list.abstractListId);\n }\n }\n }\n this.document.abstractLists = [];\n for (var i = 0; i < viewer.abstractLists.length; i++) {\n var abstractList = viewer.abstractLists[i];\n if (this.lists.indexOf(abstractList.abstractListId) > -1) {\n this.document.abstractLists.push(this.writeAbstractList(abstractList));\n }\n }\n };\n SfdtExport.prototype.writeAbstractList = function (wAbstractList) {\n var abstractList = {};\n abstractList.abstractListId = wAbstractList.abstractListId;\n abstractList.levels = [];\n for (var i = 0; i < wAbstractList.levels.length; i++) {\n abstractList.levels[i] = this.writeListLevel(wAbstractList.levels[i]);\n }\n return abstractList;\n };\n SfdtExport.prototype.writeList = function (wList) {\n var list = {};\n list.abstractListId = wList.abstractListId;\n //list.levelOverrides = wList.levelOverrides;\n list.listId = wList.listId;\n return list;\n };\n SfdtExport.prototype.writeListLevel = function (wListLevel) {\n var listLevel = {};\n listLevel.characterFormat = this.writeCharacterFormat(wListLevel.characterFormat);\n listLevel.paragraphFormat = this.writeParagraphFormat(wListLevel.paragraphFormat);\n listLevel.followCharacter = wListLevel.followCharacter;\n listLevel.listLevelPattern = wListLevel.listLevelPattern;\n listLevel.numberFormat = wListLevel.numberFormat;\n listLevel.restartLevel = wListLevel.restartLevel;\n listLevel.startAt = wListLevel.startAt;\n return listLevel;\n };\n /**\n * @private\n */\n SfdtExport.prototype.destroy = function () {\n this.lists = undefined;\n this.endLine = undefined;\n this.endOffset = undefined;\n this.viewer = undefined;\n };\n return SfdtExport;\n}());\nexport { SfdtExport };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, EventHandler, addClass, append, Property, Event, L10n, compile } from '@syncfusion/ej2-base';\nimport { setStyleAttribute, extend, removeClass, prepend, isNullOrUndefined, detach, getValue } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, rippleEffect, ChildProperty, Complex } from '@syncfusion/ej2-base';\nimport { DataManager, Query, DataUtil } from '@syncfusion/ej2-data';\nimport { ListBase, cssClass as ListBaseClasses } from '@syncfusion/ej2-lists';\nvar FieldSettings = /** @class */ (function (_super) {\n __extends(FieldSettings, _super);\n function FieldSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], FieldSettings.prototype, \"text\", void 0);\n __decorate([\n Property()\n ], FieldSettings.prototype, \"value\", void 0);\n __decorate([\n Property()\n ], FieldSettings.prototype, \"iconCss\", void 0);\n __decorate([\n Property()\n ], FieldSettings.prototype, \"groupBy\", void 0);\n __decorate([\n Property()\n ], FieldSettings.prototype, \"htmlAttributes\", void 0);\n return FieldSettings;\n}(ChildProperty));\nexport { FieldSettings };\nexport var dropDownBaseClasses = {\n root: 'e-dropdownbase',\n rtl: 'e-rtl',\n content: 'e-content',\n selected: 'e-active',\n hover: 'e-hover',\n noData: 'e-nodata',\n fixedHead: 'e-fixed-head',\n focus: 'e-item-focus',\n li: ListBaseClasses.li,\n group: ListBaseClasses.group,\n disabled: ListBaseClasses.disabled,\n grouping: 'e-dd-group'\n};\n/**\n * DropDownBase component will generate the list items based on given data and act as base class to drop-down related components\n */\nvar DropDownBase = /** @class */ (function (_super) {\n __extends(DropDownBase, _super);\n /**\n * * Constructor for DropDownBase class\n */\n function DropDownBase(options, element) {\n return _super.call(this, options, element) || this;\n }\n ;\n DropDownBase.prototype.getPropObject = function (prop, newProp, oldProp) {\n var newProperty = new Object();\n var oldProperty = new Object();\n // tslint:disable-next-line:no-function-constructor-with-string-args\n var propName = new Function('prop', 'return prop');\n newProperty[propName(prop)] = newProp[propName(prop)];\n oldProperty[propName(prop)] = oldProp[propName(prop)];\n var data = new Object();\n data.newProperty = newProperty;\n data.oldProperty = oldProperty;\n return data;\n };\n DropDownBase.prototype.getValueByText = function (text, ignoreCase, ignoreAccent) {\n var value = null;\n if (!isNullOrUndefined(this.listData)) {\n if (ignoreCase) {\n value = this.checkValueCase(text, true, ignoreAccent);\n }\n else {\n value = this.checkValueCase(text, false, ignoreAccent);\n }\n }\n return value;\n };\n ;\n DropDownBase.prototype.checkValueCase = function (text, ignoreCase, ignoreAccent, isTextByValue) {\n var _this = this;\n var value = null;\n if (isTextByValue) {\n value = text;\n }\n var dataSource = this.listData;\n var fields = this.fields;\n var type = this.typeOfData(dataSource).typeof;\n if (type === 'string' || type === 'number' || type === 'boolean') {\n for (var _i = 0, dataSource_1 = dataSource; _i < dataSource_1.length; _i++) {\n var item = dataSource_1[_i];\n if (!isNullOrUndefined(item)) {\n if (ignoreAccent) {\n value = this.checkingAccent(String(item), text, ignoreCase);\n }\n else {\n if (ignoreCase) {\n if (this.checkIgnoreCase(String(item), text)) {\n value = this.getItemValue(String(item), text, ignoreCase);\n }\n }\n else {\n if (this.checkNonIgnoreCase(String(item), text)) {\n value = this.getItemValue(String(item), text, ignoreCase, isTextByValue);\n }\n }\n }\n }\n }\n }\n else {\n if (ignoreCase) {\n dataSource.filter(function (item) {\n if (_this.checkIgnoreCase(getValue(fields.text, item).toString(), text)) {\n value = getValue(fields.value, item);\n }\n });\n }\n else {\n if (isTextByValue) {\n dataSource.filter(function (item) {\n var itemValue = getValue(fields.value, item);\n if (!isNullOrUndefined(itemValue) && itemValue.toString() === value.toString()) {\n value = getValue(fields.text, item);\n }\n });\n }\n else {\n dataSource.filter(function (item) {\n if (_this.checkNonIgnoreCase(getValue(fields.text, item), text)) {\n value = getValue(fields.value, item);\n }\n });\n }\n }\n }\n return value;\n };\n DropDownBase.prototype.checkingAccent = function (item, text, ignoreCase) {\n var dataItem = DataUtil.ignoreDiacritics(String(item));\n var textItem = DataUtil.ignoreDiacritics(text.toString());\n var value = null;\n if (ignoreCase) {\n if (this.checkIgnoreCase(dataItem, textItem)) {\n value = this.getItemValue(String(item), text, ignoreCase);\n }\n }\n else {\n if (this.checkNonIgnoreCase(String(item), text)) {\n value = this.getItemValue(String(item), text, ignoreCase);\n }\n }\n return value;\n };\n DropDownBase.prototype.checkIgnoreCase = function (item, text) {\n return String(item).toLowerCase() === text.toString().toLowerCase() ? true : false;\n };\n DropDownBase.prototype.checkNonIgnoreCase = function (item, text) {\n return String(item) === text.toString() ? true : false;\n };\n DropDownBase.prototype.getItemValue = function (dataItem, typedText, ignoreCase, isTextByValue) {\n var value = null;\n var dataSource = this.listData;\n var type = this.typeOfData(dataSource).typeof;\n if (isTextByValue) {\n value = dataItem.toString();\n }\n else {\n if (ignoreCase) {\n value = type === 'string' ? String(dataItem) : this.getFormattedValue(String(dataItem));\n }\n else {\n value = type === 'string' ? typedText : this.getFormattedValue(typedText);\n }\n }\n return value;\n };\n DropDownBase.prototype.l10nUpdate = function (actionFailure) {\n if (this.noRecordsTemplate !== 'No Records Found' || this.actionFailureTemplate !== 'The Request Failed') {\n var template = actionFailure ? this.actionFailureTemplate : this.noRecordsTemplate;\n var compiledString = void 0;\n this.list.innerHTML = '';\n compiledString = compile(template);\n for (var _i = 0, _a = compiledString({}); _i < _a.length; _i++) {\n var item = _a[_i];\n this.list.appendChild(item);\n }\n }\n else {\n var l10nLocale = { noRecordsTemplate: 'No Records Found', actionFailureTemplate: 'The Request Failed' };\n this.l10n = new L10n('dropdowns', l10nLocale, this.locale);\n this.list.innerHTML = actionFailure ?\n this.l10n.getConstant('actionFailureTemplate') : this.l10n.getConstant('noRecordsTemplate');\n }\n };\n DropDownBase.prototype.getTextByValue = function (value) {\n var text;\n text = this.checkValueCase(value, false, false, true);\n return text;\n };\n DropDownBase.prototype.getFormattedValue = function (value) {\n if (this.listData && this.listData.length) {\n var item = this.typeOfData(this.listData);\n if (typeof getValue((this.fields.value ? this.fields.value : 'value'), item.item) === 'number'\n || item.typeof === 'number') {\n return parseInt(value, 10);\n }\n if (typeof getValue((this.fields.value ? this.fields.value : 'value'), item.item) === 'boolean'\n || item.typeof === 'boolean') {\n return (value === 'true');\n }\n }\n return value;\n };\n /**\n * Sets RTL to dropdownbase wrapper\n */\n DropDownBase.prototype.setEnableRtl = function () {\n if (this.list) {\n this.enableRtlElements.push(this.list);\n }\n this.enableRtl ? addClass(this.enableRtlElements, dropDownBaseClasses.rtl) :\n removeClass(this.enableRtlElements, dropDownBaseClasses.rtl);\n };\n ;\n /**\n * Initialize the Component.\n */\n DropDownBase.prototype.initialize = function () {\n this.bindEvent = true;\n if (this.element.tagName === 'UL') {\n var jsonElement = ListBase.createJsonFromElement(this.element);\n this.setProperties({ fields: { text: 'text', value: 'text' } }, true);\n this.resetList(jsonElement, this.fields);\n }\n else if (this.element.tagName === 'SELECT') {\n var dataSource = this.dataSource instanceof Array ? (this.dataSource.length > 0 ? true : false)\n : !isNullOrUndefined(this.dataSource) ? true : false;\n if (!dataSource) {\n this.renderItemsBySelect();\n }\n }\n else {\n this.setListData(this.dataSource, this.fields, this.query);\n }\n };\n ;\n /**\n * Get the properties to be maintained in persisted state.\n */\n DropDownBase.prototype.getPersistData = function () {\n return this.addOnPersist([]);\n };\n ;\n /**\n * Sets the enabled state to DropDownBase.\n */\n DropDownBase.prototype.setEnabled = function () {\n if (this.enabled) {\n this.element.setAttribute('aria-disabled', 'false');\n }\n else {\n this.element.setAttribute('aria-disabled', 'true');\n }\n };\n ;\n DropDownBase.prototype.renderItemsBySelect = function () {\n var element = this.element;\n var fields = { value: 'value', text: 'text' };\n var jsonElement = [];\n var group = element.querySelectorAll('select>optgroup');\n var option = element.querySelectorAll('select>option');\n this.getJSONfromOption(jsonElement, option, fields);\n if (group.length) {\n for (var i = 0; i < group.length; i++) {\n var item = group[i];\n var optionGroup = {};\n optionGroup[fields.text] = item.label;\n optionGroup.isHeader = true;\n var child = item.querySelectorAll('option');\n jsonElement.push(optionGroup);\n this.getJSONfromOption(jsonElement, child, fields);\n }\n var items = element.querySelectorAll('select>option');\n }\n this.fields.text = fields.text;\n this.fields.value = fields.value;\n this.resetList(jsonElement, fields);\n };\n DropDownBase.prototype.getJSONfromOption = function (items, options, fields) {\n for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {\n var option = options_1[_i];\n var json = {};\n json[fields.text] = option.innerText;\n json[fields.value] = option.getAttribute(fields.value) ? option.getAttribute(fields.value) : option.innerText;\n items.push(json);\n }\n };\n /**\n * Execute before render the list items\n * @private\n */\n DropDownBase.prototype.preRender = function () {\n // there is no event handler\n this.scrollTimer = -1;\n this.enableRtlElements = [];\n this.isRequested = false;\n };\n /**\n * Creates the list items of DropDownBase component.\n */\n DropDownBase.prototype.setListData = function (dataSource, fields, query) {\n var _this = this;\n fields = fields ? fields : this.fields;\n var ulElement;\n this.isActive = true;\n var eventArgs = { cancel: false, data: dataSource, query: query };\n this.trigger('actionBegin', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.showSpinner();\n if (dataSource instanceof DataManager) {\n this.isRequested = true;\n eventArgs.data.executeQuery(this.getQuery(eventArgs.query)).then(function (e) {\n _this.trigger('actionComplete', e);\n if (e.cancel) {\n return;\n }\n var listItems = e.result;\n ulElement = _this.renderItems(listItems, fields);\n _this.onActionComplete(ulElement, listItems, e);\n _this.isRequested = false;\n _this.hideSpinner();\n _this.trigger('dataBound', { items: listItems, e: e });\n }).catch(function (e) {\n _this.isRequested = false;\n _this.onActionFailure(e);\n _this.hideSpinner();\n });\n }\n else {\n var dataManager = new DataManager(eventArgs.data);\n var listItems = void 0;\n listItems = (this.getQuery(eventArgs.query)).executeLocal(dataManager);\n var localDataArgs = { cancel: false, result: listItems };\n this.trigger('actionComplete', localDataArgs);\n if (localDataArgs.cancel) {\n return;\n }\n ulElement = this.renderItems(localDataArgs.result, fields);\n this.onActionComplete(ulElement, localDataArgs.result);\n this.hideSpinner();\n this.trigger('dataBound', { items: localDataArgs.result });\n }\n };\n DropDownBase.prototype.showSpinner = function () {\n // Used this method in component side.\n };\n DropDownBase.prototype.hideSpinner = function () {\n // Used this method in component side.\n };\n DropDownBase.prototype.onActionFailure = function (e) {\n this.liCollections = [];\n this.trigger('actionFailure', e);\n this.l10nUpdate(true);\n addClass([this.list], dropDownBaseClasses.noData);\n };\n DropDownBase.prototype.onActionComplete = function (ulElement, list, e) {\n this.listData = list;\n this.list.innerHTML = '';\n this.list.appendChild(ulElement);\n this.liCollections = this.list.querySelectorAll('.' + dropDownBaseClasses.li);\n this.ulElement = this.list.querySelector('ul');\n this.postRender(this.list, list, this.bindEvent);\n };\n DropDownBase.prototype.postRender = function (listElement, list, bindEvent) {\n var focusItem = listElement.querySelector('.' + dropDownBaseClasses.li);\n var selectedItem = listElement.querySelector('.' + dropDownBaseClasses.selected);\n if (focusItem && !selectedItem) {\n addClass([focusItem], dropDownBaseClasses.focus);\n }\n if (list.length <= 0) {\n this.l10nUpdate();\n addClass([listElement], dropDownBaseClasses.noData);\n }\n else {\n listElement.classList.remove(dropDownBaseClasses.noData);\n }\n if (this.groupTemplate) {\n this.renderGroupTemplate(listElement);\n }\n };\n /**\n * Get the query to do the data operation before list item generation.\n */\n DropDownBase.prototype.getQuery = function (query) {\n return query ? query : this.query ? this.query : new Query();\n };\n /**\n * To render the template content for group header element.\n */\n DropDownBase.prototype.renderGroupTemplate = function (listEle) {\n if (this.fields.groupBy !== null && this.dataSource || this.element.querySelector('.' + dropDownBaseClasses.group)) {\n var dataSource = this.dataSource;\n var headerItems = listEle.querySelectorAll('.' + dropDownBaseClasses.group);\n var tempHeaders = ListBase.renderGroupTemplate(this.groupTemplate, dataSource, this.fields.properties, headerItems);\n }\n };\n /**\n * To create the ul li list items\n */\n DropDownBase.prototype.createListItems = function (dataSource, fields) {\n if (dataSource && fields.groupBy || this.element.querySelector('optgroup')) {\n if (fields.groupBy) {\n if (this.sortOrder !== 'None') {\n dataSource = this.getSortedDataSource(dataSource);\n }\n dataSource = ListBase.groupDataSource(dataSource, fields.properties, this.sortOrder);\n }\n addClass([this.list], dropDownBaseClasses.grouping);\n }\n else {\n dataSource = this.getSortedDataSource(dataSource);\n }\n var options = this.listOption(dataSource, fields);\n return ListBase.createList(this.createElement, dataSource, options, true);\n };\n ;\n DropDownBase.prototype.listOption = function (dataSource, fields) {\n var iconCss = isNullOrUndefined(fields.iconCss) ? false : true;\n var fieldValues = !isNullOrUndefined(fields.properties) ?\n fields.properties : fields;\n var options = (fields.text !== null || fields.value !== null) ? {\n fields: fieldValues,\n showIcon: iconCss, ariaAttributes: { groupItemRole: 'presentation' }\n } : { fields: { value: 'text' } };\n return extend({}, options, fields, true);\n };\n ;\n DropDownBase.prototype.setFloatingHeader = function (e) {\n if (isNullOrUndefined(this.fixedHeaderElement)) {\n this.fixedHeaderElement = this.createElement('div', { className: dropDownBaseClasses.fixedHead });\n if (!this.list.querySelector('li').classList.contains(dropDownBaseClasses.group)) {\n this.fixedHeaderElement.style.display = 'none';\n }\n prepend([this.fixedHeaderElement], this.list);\n this.setFixedHeader();\n }\n if (!isNullOrUndefined(this.fixedHeaderElement) && this.fixedHeaderElement.style.zIndex === '0') {\n this.setFixedHeader();\n }\n this.scrollStop(e);\n };\n DropDownBase.prototype.scrollStop = function (e) {\n var target = e.target;\n var liHeight = parseInt(getComputedStyle(this.liCollections[0], null).getPropertyValue('height'), 10);\n var topIndex = Math.round(target.scrollTop / liHeight);\n var liCollections = this.ulElement.querySelectorAll('li');\n for (var i = topIndex; i > -1; i--) {\n if (!isNullOrUndefined(liCollections[i]) && liCollections[i].classList.contains(dropDownBaseClasses.group)) {\n var currentLi = liCollections[i];\n this.fixedHeaderElement.innerHTML = currentLi.innerHTML;\n this.fixedHeaderElement.style.top = e.target.scrollTop + 'px';\n this.fixedHeaderElement.style.display = 'block';\n break;\n }\n else {\n this.fixedHeaderElement.style.display = 'none';\n this.fixedHeaderElement.style.top = 'none';\n }\n }\n };\n /**\n * To render the list items\n */\n DropDownBase.prototype.renderItems = function (listData, fields) {\n var ulElement;\n if (this.itemTemplate && listData) {\n var dataSource = listData;\n if (dataSource && fields.groupBy) {\n if (this.sortOrder !== 'None') {\n dataSource = this.getSortedDataSource(dataSource);\n }\n dataSource = ListBase.groupDataSource(dataSource, fields.properties, this.sortOrder);\n }\n else {\n dataSource = this.getSortedDataSource(dataSource);\n }\n ulElement = this.templateListItem(dataSource, fields);\n }\n else {\n ulElement = this.createListItems(listData, fields);\n }\n return ulElement;\n };\n ;\n DropDownBase.prototype.templateListItem = function (dataSource, fields) {\n var option = this.listOption(dataSource, fields);\n return ListBase.renderContentTemplate(this.createElement, this.itemTemplate, dataSource, fields.properties, option);\n };\n DropDownBase.prototype.typeOfData = function (items) {\n var item = { typeof: null, item: null };\n for (var i = 0; (!isNullOrUndefined(items) && i < items.length); i++) {\n if (!isNullOrUndefined(items[i])) {\n return item = { typeof: typeof items[i], item: items[i] };\n }\n }\n return item;\n };\n DropDownBase.prototype.setFixedHeader = function () {\n this.list.parentElement.style.display = 'block';\n var liWidth = this.liCollections[0].offsetWidth;\n this.fixedHeaderElement.style.width = liWidth.toString() + 'px';\n setStyleAttribute(this.fixedHeaderElement, { zIndex: 10 });\n var firstLi = this.ulElement.querySelector('.' + dropDownBaseClasses.group);\n this.fixedHeaderElement.innerHTML = firstLi.innerHTML;\n };\n DropDownBase.prototype.getSortedDataSource = function (dataSource) {\n if (dataSource && this.sortOrder !== 'None') {\n var textField = this.fields.text ? this.fields.text : 'text';\n dataSource = ListBase.getDataSource(dataSource, ListBase.addSorting(this.sortOrder, textField));\n }\n return dataSource;\n };\n /**\n * Return the index of item which matched with given value in data source\n */\n DropDownBase.prototype.getIndexByValue = function (value) {\n var index;\n var listItems = this.getItems();\n for (var i = 0; i < listItems.length; i++) {\n if (!isNullOrUndefined(value) && listItems[i].getAttribute('data-value') === value.toString()) {\n index = i;\n break;\n }\n }\n return index;\n };\n ;\n /**\n * To dispatch the event manually\n */\n DropDownBase.prototype.dispatchEvent = function (element, type) {\n var evt = document.createEvent('HTMLEvents');\n evt.initEvent(type, false, true);\n element.dispatchEvent(evt);\n };\n /**\n * To set the current fields\n */\n DropDownBase.prototype.setFields = function () {\n var fields = this.fields;\n if (this.fields.value && !this.fields.text) {\n this.fields.text = this.fields.value;\n }\n else if (!fields.value && fields.text) {\n this.fields.value = this.fields.text;\n }\n else if (!this.fields.value && !this.fields.text) {\n this.fields.value = this.fields.text = 'text';\n }\n };\n /**\n * reset the items list.\n */\n DropDownBase.prototype.resetList = function (dataSource, fields, query) {\n if (this.list) {\n this.setListData(dataSource, fields, query);\n }\n };\n DropDownBase.prototype.updateSelection = function () {\n // This is for after added the item, need to update the selected index values.\n };\n DropDownBase.prototype.renderList = function () {\n // This is for render the list items.\n this.render();\n };\n DropDownBase.prototype.updateDataSource = function (prop) {\n this.resetList(this.dataSource);\n };\n DropDownBase.prototype.setUpdateInitial = function (props, newProp) {\n if (!isNullOrUndefined(newProp.fields)) {\n this.setFields();\n }\n for (var j = 0; props.length > j; j++) {\n if (newProp[props[j]]) {\n this.updateDataSource(props[j]);\n }\n }\n };\n /**\n * When property value changes happened, then onPropertyChanged method will execute the respective changes in this component.\n * @private\n */\n DropDownBase.prototype.onPropertyChanged = function (newProp, oldProp) {\n this.setUpdateInitial(['query', 'sortOrder', 'dataSource', 'itemTemplate'], newProp);\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'query':\n case 'sortOrder':\n case 'dataSource':\n case 'itemTemplate':\n break;\n case 'enableRtl':\n this.setEnableRtl();\n break;\n case 'enabled':\n this.setEnabled();\n break;\n case 'groupTemplate':\n this.renderGroupTemplate(this.list);\n if (this.ulElement && this.fixedHeaderElement) {\n var firstLi = this.ulElement.querySelector('.' + dropDownBaseClasses.group);\n this.fixedHeaderElement.innerHTML = firstLi.innerHTML;\n }\n break;\n case 'locale':\n if (this.list && (!isNullOrUndefined(this.liCollections) && this.liCollections.length === 0)) {\n this.l10nUpdate();\n }\n break;\n case 'zIndex':\n this.setProperties({ zIndex: newProp.zIndex }, true);\n this.setZIndex();\n break;\n }\n }\n };\n ;\n /**\n * Build and render the component\n * @private\n */\n DropDownBase.prototype.render = function (isEmptyData) {\n this.list = this.createElement('div', { className: dropDownBaseClasses.content, attrs: { 'tabindex': '0' } });\n this.list.classList.add(dropDownBaseClasses.root);\n this.setFields();\n var rippleModel = { duration: 300, selector: '.' + dropDownBaseClasses.li };\n this.rippleFun = rippleEffect(this.list, rippleModel);\n var group = this.element.querySelector('select>optgroup');\n if (this.fields.groupBy || !isNullOrUndefined(group)) {\n EventHandler.add(this.list, 'scroll', this.setFloatingHeader, this);\n }\n if (this.getModuleName() === 'dropdownbase') {\n if (this.element.getAttribute('tabindex')) {\n this.list.setAttribute('tabindex', this.element.getAttribute('tabindex'));\n }\n removeClass([this.element], dropDownBaseClasses.root);\n this.element.style.display = 'none';\n var wrapperElement = this.createElement('div');\n this.element.parentElement.insertBefore(wrapperElement, this.element);\n wrapperElement.appendChild(this.element);\n wrapperElement.appendChild(this.list);\n }\n this.setEnableRtl();\n this.setEnabled();\n if (!isEmptyData) {\n this.initialize();\n }\n };\n ;\n /**\n * Return the module name of this component.\n * @private\n */\n DropDownBase.prototype.getModuleName = function () {\n return 'dropdownbase';\n };\n ;\n /**\n * Gets all the list items bound on this component.\n * @returns Element[].\n */\n DropDownBase.prototype.getItems = function () {\n return this.ulElement.querySelectorAll('.' + dropDownBaseClasses.li);\n };\n ;\n /**\n * Adds a new item to the popup list. By default, new item appends to the list as the last item,\n * but you can insert based on the index parameter.\n * @param { Object[] } items - Specifies an array of JSON data or a JSON data.\n * @param { number } itemIndex - Specifies the index to place the newly added item in the popup list.\n * @return {void}.\n */\n DropDownBase.prototype.addItem = function (items, itemIndex) {\n if (!this.list || this.list.textContent === this.noRecordsTemplate) {\n this.renderList();\n }\n var itemsCount = this.getItems().length;\n var selectedItemValue = this.list.querySelector('.' + dropDownBaseClasses.selected);\n items = (items instanceof Array ? items : [items]);\n var index;\n index = (isNullOrUndefined(itemIndex) || itemIndex < 0 || itemIndex > itemsCount - 1) ? itemsCount : itemIndex;\n var fields = this.fields;\n var liCollections = [];\n for (var i = 0; i < items.length; i++) {\n var item = items[i];\n var li = this.createElement('li', { className: dropDownBaseClasses.li, id: 'option-add-' + i });\n li.setAttribute('data-value', getValue(fields.value, item));\n li.setAttribute('role', 'option');\n li.appendChild(document.createTextNode(getValue(fields.text, item)));\n liCollections.push(li);\n this.listData.push(item);\n this.updateActionCompleteData(li, item);\n }\n if (itemsCount === 0 && isNullOrUndefined(this.list.querySelector('ul'))) {\n this.list.innerHTML = '';\n this.list.appendChild(this.ulElement);\n append(liCollections, this.ulElement);\n }\n else {\n for (var i = 0; i < items.length; i++) {\n if (this.liCollections[index]) {\n this.liCollections[index].parentNode.insertBefore(liCollections[i], this.liCollections[index]);\n }\n else {\n this.ulElement.appendChild(liCollections[i]);\n }\n var tempLi = [].slice.call(this.liCollections);\n tempLi.splice(index, 0, liCollections[i]);\n this.liCollections = tempLi;\n index += 1;\n }\n }\n if (selectedItemValue || itemIndex === 0) {\n this.updateSelection();\n }\n };\n DropDownBase.prototype.validationAttribute = function (target, hidden) {\n var name = target.getAttribute('name') ? target.getAttribute('name') : target.getAttribute('id');\n hidden.setAttribute('name', name);\n target.removeAttribute('name');\n var attributes = ['required', 'aria-required', 'form'];\n for (var i = 0; i < attributes.length; i++) {\n if (!target.getAttribute(attributes[i])) {\n continue;\n }\n var attr = target.getAttribute(attributes[i]);\n hidden.setAttribute(attributes[i], attr);\n target.removeAttribute(attributes[i]);\n }\n };\n DropDownBase.prototype.setZIndex = function () {\n // this is for component wise\n };\n DropDownBase.prototype.updateActionCompleteData = function (li, item) {\n // this is for ComboBox custom value\n };\n /**\n * Gets the data Object that matches the given value.\n * @param { string | number } value - Specifies the value of the list item.\n * @returns Object.\n */\n DropDownBase.prototype.getDataByValue = function (value) {\n if (!isNullOrUndefined(this.listData)) {\n var type = this.typeOfData(this.listData).typeof;\n if (type === 'string' || type === 'number' || type === 'boolean') {\n for (var _i = 0, _a = this.listData; _i < _a.length; _i++) {\n var item = _a[_i];\n if (!isNullOrUndefined(item) && item === value) {\n return item;\n }\n }\n }\n else {\n for (var _b = 0, _c = this.listData; _b < _c.length; _b++) {\n var item = _c[_b];\n if (!isNullOrUndefined(item) && getValue((this.fields.value ? this.fields.value : 'value'), item) === value) {\n return item;\n }\n }\n }\n }\n return null;\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers. It also removes the attributes and classes.\n * @method destroy\n * @return {void}.\n */\n DropDownBase.prototype.destroy = function () {\n if (document.body.contains(this.list)) {\n EventHandler.remove(this.list, 'scroll', this.setFloatingHeader);\n if (!isNullOrUndefined(this.rippleFun)) {\n this.rippleFun();\n }\n detach(this.list);\n }\n _super.prototype.destroy.call(this);\n };\n ;\n __decorate([\n Complex({ text: null, value: null, iconCss: null, groupBy: null }, FieldSettings)\n ], DropDownBase.prototype, \"fields\", void 0);\n __decorate([\n Property(false)\n ], DropDownBase.prototype, \"enableRtl\", void 0);\n __decorate([\n Property(false)\n ], DropDownBase.prototype, \"enablePersistence\", void 0);\n __decorate([\n Property(null)\n ], DropDownBase.prototype, \"itemTemplate\", void 0);\n __decorate([\n Property(null)\n ], DropDownBase.prototype, \"groupTemplate\", void 0);\n __decorate([\n Property('No Records Found')\n ], DropDownBase.prototype, \"noRecordsTemplate\", void 0);\n __decorate([\n Property('The Request Failed')\n ], DropDownBase.prototype, \"actionFailureTemplate\", void 0);\n __decorate([\n Property('None')\n ], DropDownBase.prototype, \"sortOrder\", void 0);\n __decorate([\n Property(true)\n ], DropDownBase.prototype, \"enabled\", void 0);\n __decorate([\n Property([])\n ], DropDownBase.prototype, \"dataSource\", void 0);\n __decorate([\n Property(null)\n ], DropDownBase.prototype, \"query\", void 0);\n __decorate([\n Property(1000)\n ], DropDownBase.prototype, \"zIndex\", void 0);\n __decorate([\n Property(false)\n ], DropDownBase.prototype, \"ignoreAccent\", void 0);\n __decorate([\n Event()\n ], DropDownBase.prototype, \"actionBegin\", void 0);\n __decorate([\n Event()\n ], DropDownBase.prototype, \"actionComplete\", void 0);\n __decorate([\n Event()\n ], DropDownBase.prototype, \"actionFailure\", void 0);\n __decorate([\n Event()\n ], DropDownBase.prototype, \"select\", void 0);\n __decorate([\n Event()\n ], DropDownBase.prototype, \"dataBound\", void 0);\n __decorate([\n Event()\n ], DropDownBase.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], DropDownBase.prototype, \"destroyed\", void 0);\n DropDownBase = __decorate([\n NotifyPropertyChanges\n ], DropDownBase);\n return DropDownBase;\n}(Component));\nexport { DropDownBase };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n/// \nimport { EventHandler, Property, Event, compile, KeyboardEvents, append } from '@syncfusion/ej2-base';\nimport { attributes, isNullOrUndefined, getUniqueID, formatUnit, isUndefined, getValue } from '@syncfusion/ej2-base';\nimport { Animation, Browser, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { addClass, removeClass, setStyleAttribute, closest, prepend, detach, classList } from '@syncfusion/ej2-base';\nimport { Popup, isCollide, createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { incrementalSearch } from '../common/incremental-search';\nimport { DropDownBase, dropDownBaseClasses } from '../drop-down-base/drop-down-base';\n/* tslint:disable */\nimport { DataManager, Query } from '@syncfusion/ej2-data';\n// don't use space in classnames \nexport var dropDownListClasses = {\n root: 'e-dropdownlist',\n hover: dropDownBaseClasses.hover,\n selected: dropDownBaseClasses.selected,\n rtl: dropDownBaseClasses.rtl,\n li: dropDownBaseClasses.li,\n disable: dropDownBaseClasses.disabled,\n base: dropDownBaseClasses.root,\n focus: dropDownBaseClasses.focus,\n input: 'e-input-group',\n inputFocus: 'e-input-focus',\n icon: 'e-input-group-icon e-ddl-icon',\n iconAnimation: 'e-icon-anim',\n value: 'e-input-value',\n device: 'e-ddl-device',\n backIcon: 'e-input-group-icon e-back-icon e-icons',\n filterBarClearIcon: 'e-input-group-icon e-clear-icon e-icons',\n filterInput: 'e-input-filter',\n filterParent: 'e-filter-parent',\n mobileFilter: 'e-ddl-device-filter',\n footer: 'e-ddl-footer',\n header: 'e-ddl-header',\n clearIcon: 'e-clear-icon',\n clearIconHide: 'e-clear-icon-hide',\n popupFullScreen: 'e-popup-full-page',\n disableIcon: 'e-ddl-disable-icon',\n hiddenElement: 'e-ddl-hidden'\n};\nvar inputObject = {\n container: null,\n buttons: []\n};\n/**\n * The DropDownList component contains a list of predefined values from which you can\n * choose a single value.\n * ```html\n * \n * ```\n * ```typescript\n * let dropDownListObj:DropDownList = new DropDownList();\n * dropDownListObj.appendTo(\"#list\");\n * ```\n */\nvar DropDownList = /** @class */ (function (_super) {\n __extends(DropDownList, _super);\n /**\n * * Constructor for creating the DropDownList component.\n */\n function DropDownList(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.previousValue = null;\n return _this;\n }\n ;\n /**\n * Initialize the event handler.\n * @private\n */\n DropDownList.prototype.preRender = function () {\n this.element.style.opacity = '0';\n this.initializeData();\n _super.prototype.preRender.call(this);\n this.activeIndex = this.index;\n this.queryString = '';\n };\n DropDownList.prototype.initializeData = function () {\n this.isPopupOpen = false;\n this.isDocumentClick = false;\n this.isInteracted = false;\n this.isFilterFocus = false;\n this.beforePopupOpen = false;\n this.initial = true;\n this.initRemoteRender = false;\n this.isNotSearchList = false;\n this.isTyped = false;\n this.isSelected = false;\n this.preventFocus = false;\n this.preventAutoFill = false;\n this.isValidKey = false;\n this.typedString = '';\n this.isEscapeKey = false;\n this.isPreventBlur = false;\n this.isTabKey = false;\n this.actionCompleteData = { isUpdated: false };\n this.prevSelectPoints = {};\n this.isSelectCustom = false;\n this.isDropDownClick = false;\n this.preventAltUp = false;\n this.isCustomFilter = false;\n this.isSecondClick = false;\n this.keyConfigure = {\n tab: 'tab',\n enter: '13',\n escape: '27',\n end: '35',\n home: '36',\n down: '40',\n up: '38',\n pageUp: '33',\n pageDown: '34',\n open: 'alt+40',\n close: 'shift+tab',\n hide: 'alt+38',\n space: '32'\n };\n };\n DropDownList.prototype.setZIndex = function () {\n if (this.popupObj) {\n this.popupObj.setProperties({ 'zIndex': this.zIndex });\n }\n };\n DropDownList.prototype.renderList = function (isEmptyData) {\n _super.prototype.render.call(this, isEmptyData);\n this.wireListEvents();\n };\n DropDownList.prototype.floatLabelChange = function () {\n if (this.getModuleName() === 'dropdownlist' && this.floatLabelType === 'Auto') {\n var floatElement = this.inputWrapper.container.querySelector('.e-float-text');\n if (this.inputElement.value !== '' || this.isInteracted) {\n classList(floatElement, ['e-label-top'], ['e-label-bottom']);\n }\n else {\n classList(floatElement, ['e-label-bottom'], ['e-label-top']);\n }\n }\n };\n DropDownList.prototype.resetHandler = function (e) {\n e.preventDefault();\n this.clear(e);\n this.onChangeEvent(e);\n };\n DropDownList.prototype.resetFocusElement = function () {\n this.removeHover();\n this.removeSelection();\n this.removeFocus();\n this.list.scrollTop = 0;\n if (this.getModuleName() !== 'autocomplete') {\n var li = this.ulElement.querySelector('.' + dropDownListClasses.li);\n if (li) {\n li.classList.add(dropDownListClasses.focus);\n }\n }\n };\n DropDownList.prototype.clear = function (e, property) {\n if (property !== 'dataSource') {\n this.resetSelection();\n }\n var dataItem = this.getItemData();\n if (this.previousValue === dataItem.value) {\n return;\n }\n this.onChangeEvent(e);\n };\n DropDownList.prototype.resetSelection = function () {\n if (this.list) {\n if (this.allowFiltering && this.getModuleName() !== 'autocomplete'\n && !isNullOrUndefined(this.actionCompleteData.ulElement) && !isNullOrUndefined(this.actionCompleteData.list)) {\n this.onActionComplete(this.actionCompleteData.ulElement.cloneNode(true), this.actionCompleteData.list);\n }\n this.resetFocusElement();\n }\n this.hiddenElement.innerHTML = '';\n this.inputElement.value = '';\n this.value = null;\n this.itemData = null;\n this.text = null;\n this.index = null;\n this.activeIndex = null;\n this.item = null;\n this.queryString = '';\n if (this.valueTempElement) {\n detach(this.valueTempElement);\n this.inputElement.style.display = 'block';\n this.valueTempElement = null;\n }\n this.setSelection(null, null);\n this.isSelectCustom = false;\n this.updateIconState();\n };\n DropDownList.prototype.setHTMLAttributes = function () {\n if (Object.keys(this.htmlAttributes).length) {\n for (var _i = 0, _a = Object.keys(this.htmlAttributes); _i < _a.length; _i++) {\n var htmlAttr = _a[_i];\n if (htmlAttr === 'class') {\n this.inputWrapper.container.classList.add(this.htmlAttributes[htmlAttr]);\n }\n else if (htmlAttr === 'disabled' && this.htmlAttributes[htmlAttr] === 'disabled') {\n this.enabled = false;\n this.setEnable();\n }\n else if (htmlAttr === 'readonly' && this.htmlAttributes[htmlAttr] === 'readonly') {\n this.readonly = true;\n this.dataBind();\n }\n else if (htmlAttr === 'style') {\n this.inputWrapper.container.setAttribute('style', this.htmlAttributes[htmlAttr]);\n }\n else {\n var defaultAttr = ['title', 'id', 'placeholder'];\n var validateAttr = ['name', 'required'];\n if (validateAttr.indexOf(htmlAttr) > -1) {\n this.hiddenElement.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n }\n else if (defaultAttr.indexOf(htmlAttr) > -1) {\n htmlAttr === 'placeholder' ? Input.setPlaceholder(this.htmlAttributes[htmlAttr], this.inputElement) :\n this.element.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n }\n else {\n this.inputWrapper.container.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n }\n }\n }\n }\n };\n DropDownList.prototype.getAriaAttributes = function () {\n return {\n 'aria-disabled': 'false',\n 'aria-owns': this.element.id + '_options',\n 'role': 'listbox',\n 'aria-haspopup': 'true',\n 'aria-expanded': 'false',\n 'aria-activedescendant': 'null',\n 'aria-labelledby': this.hiddenElement.id\n };\n };\n DropDownList.prototype.setEnableRtl = function () {\n Input.setEnableRtl(this.enableRtl, [this.inputElement.parentElement]);\n if (this.popupObj) {\n this.popupObj.enableRtl = this.enableRtl;\n this.popupObj.dataBind();\n }\n };\n DropDownList.prototype.setEnable = function () {\n Input.setEnabled(this.enabled, this.inputElement);\n if (this.enabled) {\n removeClass([this.inputWrapper.container], dropDownListClasses.disable);\n this.inputElement.setAttribute('aria-disabled', 'false');\n this.targetElement().setAttribute('tabindex', this.tabIndex);\n }\n else {\n this.hidePopup();\n addClass([this.inputWrapper.container], dropDownListClasses.disable);\n this.inputElement.setAttribute('aria-disabled', 'true');\n this.targetElement().tabIndex = -1;\n }\n };\n /**\n * Get the properties to be maintained in the persisted state.\n */\n DropDownList.prototype.getPersistData = function () {\n return this.addOnPersist(['value']);\n };\n ;\n DropDownList.prototype.preventTabIndex = function (element) {\n if (this.getModuleName() === 'dropdownlist') {\n element.tabIndex = -1;\n }\n };\n DropDownList.prototype.targetElement = function () {\n return this.inputWrapper.container;\n };\n DropDownList.prototype.getNgDirective = function () {\n return 'EJS-DROPDOWNLIST';\n };\n DropDownList.prototype.getElementByText = function (text) {\n return this.getElementByValue(this.getValueByText(text));\n };\n DropDownList.prototype.getElementByValue = function (value) {\n var item;\n var listItems = this.getItems();\n for (var _i = 0, listItems_1 = listItems; _i < listItems_1.length; _i++) {\n var liItem = listItems_1[_i];\n if (this.getFormattedValue(liItem.getAttribute('data-value')) === value) {\n item = liItem;\n break;\n }\n }\n return item;\n };\n ;\n DropDownList.prototype.initValue = function () {\n this.renderList();\n if (this.dataSource instanceof DataManager) {\n this.initRemoteRender = true;\n }\n else {\n this.updateValues();\n }\n };\n DropDownList.prototype.updateValues = function () {\n if (!isNullOrUndefined(this.value)) {\n this.setSelection(this.getElementByValue(this.value), null);\n }\n else if (this.text && isNullOrUndefined(this.value)) {\n var element = this.getElementByText(this.text);\n if (isNullOrUndefined(element)) {\n this.setProperties({ text: null });\n return;\n }\n else {\n this.setSelection(element, null);\n }\n }\n else {\n this.setSelection(this.liCollections[this.activeIndex], null);\n }\n this.setHiddenValue();\n Input.setValue(this.text, this.inputElement, this.floatLabelType, this.showClearButton);\n };\n DropDownList.prototype.onBlur = function (e) {\n if (!this.enabled) {\n return;\n }\n var target = e.relatedTarget;\n var currentTarget = e.target;\n var isPreventBlur = this.isPreventBlur;\n this.isPreventBlur = false;\n //IE 11 - issue\n if (isPreventBlur && !this.isDocumentClick && this.isPopupOpen && (!isNullOrUndefined(currentTarget) ||\n !this.isFilterLayout() && isNullOrUndefined(target))) {\n if (this.getModuleName() === 'dropdownlist' && this.allowFiltering && this.isPopupOpen) {\n this.filterInput.focus();\n }\n else {\n this.targetElement().focus();\n }\n return;\n }\n if (this.isDocumentClick || (!isNullOrUndefined(this.popupObj)\n && document.body.contains(this.popupObj.element) &&\n this.popupObj.element.classList.contains(dropDownListClasses.mobileFilter))) {\n if (!this.beforePopupOpen) {\n this.isDocumentClick = false;\n }\n return;\n }\n if (((this.getModuleName() === 'dropdownlist' && !this.isFilterFocus && target !== this.inputElement)\n && (document.activeElement !== target || (document.activeElement === target &&\n currentTarget.classList.contains(dropDownListClasses.inputFocus)))) ||\n (isNullOrUndefined(target) && this.getModuleName() === 'dropdownlist' && this.allowFiltering &&\n currentTarget !== this.inputWrapper.container) || this.getModuleName() !== 'dropdownlist' &&\n !this.inputWrapper.container.contains(target) || this.isTabKey) {\n this.isDocumentClick = this.isPopupOpen ? true : false;\n this.focusOutAction();\n this.isTabKey = false;\n }\n if (this.isRequested && !this.isPopupOpen && !this.isPreventBlur) {\n this.isActive = false;\n this.beforePopupOpen = false;\n }\n };\n DropDownList.prototype.focusOutAction = function () {\n this.isInteracted = false;\n this.focusOut();\n this.onFocusOut();\n };\n DropDownList.prototype.onFocusOut = function () {\n if (!this.enabled) {\n return;\n }\n if (this.isSelected) {\n this.isSelectCustom = false;\n this.onChangeEvent(null);\n }\n this.floatLabelChange();\n this.dispatchEvent(this.hiddenElement, 'change');\n if (this.getModuleName() === 'dropdownlist' && this.element.tagName !== 'INPUT') {\n this.dispatchEvent(this.inputElement, 'blur');\n }\n if (this.inputWrapper.clearButton) {\n addClass([this.inputWrapper.clearButton], dropDownListClasses.clearIconHide);\n }\n this.trigger('blur');\n };\n DropDownList.prototype.onFocus = function () {\n if (!this.isInteracted) {\n this.isInteracted = true;\n this.trigger('focus');\n }\n this.updateIconState();\n };\n DropDownList.prototype.resetValueHandler = function () {\n this.value = null;\n };\n DropDownList.prototype.wireEvent = function () {\n EventHandler.add(this.inputWrapper.container, 'mousedown', this.dropDownClick, this);\n EventHandler.add(this.inputWrapper.container, 'focus', this.focusIn, this);\n EventHandler.add(this.inputWrapper.container, 'keypress', this.onSearch, this);\n var formElement = closest(this.inputElement, 'form');\n if (formElement) {\n EventHandler.add(formElement, 'reset', this.resetValueHandler, this);\n }\n this.bindCommonEvent();\n };\n DropDownList.prototype.bindCommonEvent = function () {\n EventHandler.add(this.targetElement(), 'blur', this.onBlur, this);\n if (!Browser.isDevice) {\n this.keyboardModule = new KeyboardEvents(this.targetElement(), {\n keyAction: this.keyActionHandler.bind(this), keyConfigs: this.keyConfigure, eventName: 'keydown'\n });\n }\n this.bindClearEvent();\n };\n DropDownList.prototype.bindClearEvent = function () {\n if (this.showClearButton) {\n EventHandler.add(this.inputWrapper.clearButton, 'mousedown', this.resetHandler, this);\n }\n };\n DropDownList.prototype.unBindCommonEvent = function () {\n EventHandler.remove(this.targetElement(), 'blur', this.onBlur);\n if (!Browser.isDevice) {\n this.keyboardModule.destroy();\n }\n if (this.showClearButton) {\n EventHandler.remove(this.inputWrapper.clearButton, 'mousedown', this.resetHandler);\n }\n };\n DropDownList.prototype.updateIconState = function () {\n if (this.showClearButton) {\n if (this.inputElement.value !== '') {\n removeClass([this.inputWrapper.clearButton], dropDownListClasses.clearIconHide);\n }\n else {\n addClass([this.inputWrapper.clearButton], dropDownListClasses.clearIconHide);\n }\n }\n };\n /**\n * Event binding for list\n */\n DropDownList.prototype.wireListEvents = function () {\n EventHandler.add(this.list, 'click', this.onMouseClick, this);\n EventHandler.add(this.list, 'mouseover', this.onMouseOver, this);\n EventHandler.add(this.list, 'mouseout', this.onMouseLeave, this);\n };\n ;\n DropDownList.prototype.onSearch = function (e) {\n if (e.charCode !== 32 && e.charCode !== 13) {\n if (this.list === undefined) {\n this.renderList();\n }\n this.searchKeyEvent = e;\n if (!this.isRequested && !isNullOrUndefined(this.list.querySelector('li'))) {\n this.incrementalSearch(e);\n }\n }\n };\n DropDownList.prototype.onMouseClick = function (e) {\n var target = e.target;\n var classList = target.classList;\n var li = closest(target, '.' + dropDownBaseClasses.li);\n if (!this.isValidLI(li)) {\n return;\n }\n this.setSelection(li, e);\n if (Browser.isDevice && this.isFilterLayout()) {\n history.back();\n }\n else {\n var delay = 100;\n this.closePopup(delay);\n }\n };\n DropDownList.prototype.onMouseOver = function (e) {\n var currentLi = closest(e.target, '.' + dropDownBaseClasses.li);\n this.setHover(currentLi);\n };\n ;\n DropDownList.prototype.setHover = function (li) {\n if (this.enabled && this.isValidLI(li) && !li.classList.contains(dropDownBaseClasses.hover)) {\n this.removeHover();\n addClass([li], dropDownBaseClasses.hover);\n }\n };\n ;\n DropDownList.prototype.onMouseLeave = function (e) {\n this.removeHover();\n };\n ;\n DropDownList.prototype.removeHover = function () {\n var hoveredItem = this.list.querySelectorAll('.' + dropDownBaseClasses.hover);\n if (hoveredItem && hoveredItem.length) {\n removeClass(hoveredItem, dropDownBaseClasses.hover);\n }\n };\n ;\n DropDownList.prototype.isValidLI = function (li) {\n return (li && li.hasAttribute('role') && li.getAttribute('role') === 'option');\n };\n ;\n DropDownList.prototype.incrementalSearch = function (e) {\n if (this.liCollections.length > 0) {\n var li = incrementalSearch(e.charCode, this.liCollections, this.activeIndex, true);\n if (!isNullOrUndefined(li)) {\n this.setSelection(li, e);\n this.setScrollPosition();\n }\n }\n };\n ;\n /**\n * Hides the spinner loader.\n * @returns void.\n */\n DropDownList.prototype.hideSpinner = function () {\n if (!isNullOrUndefined(this.spinnerElement)) {\n hideSpinner(this.spinnerElement);\n removeClass([this.spinnerElement], dropDownListClasses.disableIcon);\n this.spinnerElement.innerHTML = '';\n this.spinnerElement = null;\n }\n };\n /**\n * Shows the spinner loader.\n * @returns void.\n */\n DropDownList.prototype.showSpinner = function () {\n if (isNullOrUndefined(this.spinnerElement)) {\n this.spinnerElement = Browser.isDevice && !isNullOrUndefined(this.filterInputObj) && this.filterInputObj.buttons[1] ||\n !isNullOrUndefined(this.filterInputObj) && this.filterInputObj.buttons[0] || this.inputWrapper.buttons[0];\n addClass([this.spinnerElement], dropDownListClasses.disableIcon);\n createSpinner({\n target: this.spinnerElement,\n width: Browser.isDevice ? '16px' : '14px'\n }, this.createElement);\n showSpinner(this.spinnerElement);\n }\n };\n DropDownList.prototype.keyActionHandler = function (e) {\n var preventAction = e.action === 'pageUp' || e.action === 'pageDown';\n var preventHomeEnd = this.getModuleName() !== 'dropdownlist' && (e.action === 'home' || e.action === 'end');\n this.isEscapeKey = e.action === 'escape';\n this.isTabKey = !this.isPopupOpen && e.action === 'tab';\n var isNavigation = (e.action === 'down' || e.action === 'up' || e.action === 'pageUp' || e.action === 'pageDown'\n || e.action === 'home' || e.action === 'end');\n if ((this.isEditTextBox() || preventAction || preventHomeEnd) && !this.isPopupOpen) {\n return;\n }\n if (!this.readonly) {\n var isTabAction = e.action === 'tab' || e.action === 'close';\n if (this.list === undefined && !this.isRequested && !isTabAction && e.action !== 'escape') {\n this.searchKeyEvent = e;\n this.renderList();\n }\n if (isNullOrUndefined(this.list) || (!isNullOrUndefined(this.liCollections) &&\n isNavigation && this.liCollections.length === 0) || this.isRequested) {\n return;\n }\n if (isTabAction && this.isPopupOpen || e.action === 'escape') {\n e.preventDefault();\n }\n this.isSelected = e.action === 'escape' ? false : this.isSelected;\n this.isTyped = (isNavigation || e.action === 'escape') ? false : this.isTyped;\n switch (e.action) {\n case 'down':\n case 'up':\n var focusEle = this.list.querySelector('.' + dropDownListClasses.focus);\n if (this.isSelectFocusItem(focusEle)) {\n this.setSelection(focusEle, e);\n }\n else {\n var nextItem = void 0;\n var index = e.action === 'down' ? this.activeIndex + 1 : this.activeIndex - 1;\n var startIndex = 0;\n if (this.getModuleName() === 'autocomplete') {\n startIndex = e.action === 'down' && isNullOrUndefined(this.activeIndex) ? 0 : this.liCollections.length - 1;\n index = index < 0 ? this.liCollections.length - 1 : index === this.liCollections.length ? 0 : index;\n }\n nextItem = isNullOrUndefined(this.activeIndex) ? this.liCollections[startIndex] : this.liCollections[index];\n this.setSelection(nextItem, e);\n }\n e.preventDefault();\n break;\n case 'pageUp':\n this.pageUpSelection(this.activeIndex - this.getPageCount(), e);\n e.preventDefault();\n break;\n case 'pageDown':\n this.pageDownSelection(this.activeIndex + this.getPageCount(), e);\n e.preventDefault();\n break;\n case 'home':\n if (this.getModuleName() === 'dropdownlist') {\n e.preventDefault();\n if (this.activeIndex === 0) {\n return;\n }\n this.setSelection(this.liCollections[0], e);\n }\n break;\n case 'end':\n if (this.getModuleName() === 'dropdownlist') {\n e.preventDefault();\n var lastLi = this.getItems().length - 1;\n if (this.activeIndex === lastLi) {\n return;\n }\n this.setSelection(this.liCollections[lastLi], e);\n }\n break;\n case 'space':\n if (this.getModuleName() === 'dropdownlist') {\n if (!this.beforePopupOpen) {\n this.showPopup();\n }\n }\n break;\n case 'open':\n this.showPopup();\n break;\n case 'hide':\n this.preventAltUp = this.isPopupOpen;\n this.hidePopup();\n this.focusDropDown(e);\n break;\n case 'enter':\n this.selectCurrentItem(e);\n break;\n case 'escape':\n case 'tab':\n case 'close':\n if (this.isPopupOpen) {\n this.hidePopup();\n this.focusDropDown(e);\n }\n break;\n }\n }\n };\n DropDownList.prototype.selectCurrentItem = function (e) {\n if (this.isPopupOpen) {\n var li = this.list.querySelector('.' + dropDownListClasses.focus);\n if (li) {\n this.setSelection(li, e);\n this.isTyped = false;\n }\n if (this.isSelected) {\n this.isSelectCustom = false;\n this.onChangeEvent(e);\n }\n this.hidePopup();\n this.focusDropDown(e);\n }\n else {\n this.showPopup();\n }\n };\n DropDownList.prototype.isSelectFocusItem = function (element) {\n return !isNullOrUndefined(element);\n };\n DropDownList.prototype.getPageCount = function () {\n var liHeight = this.list.classList.contains(dropDownBaseClasses.noData) ? null :\n getComputedStyle(this.getItems()[0], null).getPropertyValue('height');\n return Math.round(this.list.getBoundingClientRect().height / parseInt(liHeight, 10));\n };\n DropDownList.prototype.pageUpSelection = function (steps, event) {\n var previousItem = steps >= 0 ? this.liCollections[steps + 1] : this.liCollections[0];\n this.setSelection(previousItem, event);\n };\n ;\n DropDownList.prototype.pageDownSelection = function (steps, event) {\n var list = this.getItems();\n var previousItem = steps <= list.length ? this.liCollections[steps - 1] : this.liCollections[list.length - 1];\n this.setSelection(previousItem, event);\n };\n ;\n DropDownList.prototype.unWireEvent = function () {\n EventHandler.remove(this.inputWrapper.container, 'mousedown', this.dropDownClick);\n EventHandler.remove(this.inputWrapper.container, 'keypress', this.onSearch);\n EventHandler.remove(this.inputWrapper.container, 'focus', this.focusIn);\n var formElement = closest(this.inputElement, 'form');\n if (formElement) {\n EventHandler.remove(formElement, 'reset', this.resetValueHandler);\n }\n this.unBindCommonEvent();\n };\n /**\n * Event un binding for list items.\n */\n DropDownList.prototype.unWireListEvents = function () {\n EventHandler.remove(this.list, 'click', this.onMouseClick);\n EventHandler.remove(this.list, 'mouseover', this.onMouseOver);\n EventHandler.remove(this.list, 'mouseout', this.onMouseLeave);\n };\n ;\n DropDownList.prototype.onDocumentClick = function (e) {\n var target = e.target;\n if (!(!isNullOrUndefined(this.popupObj) && closest(target, '#' + this.popupObj.element.id)) &&\n !this.inputWrapper.container.contains(e.target)) {\n if (this.inputWrapper.container.classList.contains(dropDownListClasses.inputFocus) || this.isPopupOpen) {\n this.isDocumentClick = true;\n var isActive = this.isRequested;\n this.isInteracted = false;\n this.hidePopup();\n if (!isActive) {\n this.onFocusOut();\n this.inputWrapper.container.classList.remove(dropDownListClasses.inputFocus);\n }\n }\n }\n else if (target !== this.inputElement && !(this.allowFiltering && target === this.filterInput)\n && !(this.getModuleName() === 'combobox' &&\n !this.allowFiltering && Browser.isDevice && target === this.inputWrapper.buttons[0])) {\n this.isPreventBlur = (Browser.isIE || Browser.info.name === 'edge') && (document.activeElement === this.targetElement() ||\n document.activeElement === this.filterInput);\n e.preventDefault();\n }\n };\n DropDownList.prototype.activeStateChange = function () {\n if (this.isDocumentClick) {\n this.hidePopup();\n this.onFocusOut();\n this.inputWrapper.container.classList.remove(dropDownListClasses.inputFocus);\n }\n };\n DropDownList.prototype.focusDropDown = function (e) {\n if (!this.initial && this.isFilterLayout()) {\n this.focusIn();\n }\n };\n DropDownList.prototype.dropDownClick = function (e) {\n if (e.which === 3 || e.button === 2) {\n return;\n }\n if (this.targetElement().classList.contains(dropDownListClasses.disable) || this.inputWrapper.clearButton === e.target) {\n return;\n }\n var target = e.target;\n if (target !== this.inputElement && !(this.allowFiltering && target === this.filterInput) && this.getModuleName() !== 'combobox') {\n e.preventDefault();\n }\n if (!this.readonly) {\n if (this.isPopupOpen) {\n this.hidePopup();\n if (this.isFilterLayout()) {\n this.focusDropDown(e);\n }\n }\n else {\n this.focusIn();\n this.floatLabelChange();\n this.queryString = this.inputElement.value.trim() === '' ? null : this.inputElement.value;\n this.isDropDownClick = true;\n this.showPopup();\n }\n var proxy_1 = this;\n if (!this.isSecondClick) {\n setTimeout(function () { proxy_1.cloneElements(); }, 100);\n }\n }\n else {\n this.focusIn();\n }\n };\n DropDownList.prototype.cloneElements = function () {\n if (this.list) {\n var ulElement = this.list.querySelector('ul');\n if (ulElement) {\n ulElement = ulElement.cloneNode ? ulElement.cloneNode(true) : ulElement;\n this.actionCompleteData.ulElement = ulElement;\n this.isSecondClick = true;\n }\n }\n };\n DropDownList.prototype.updateSelectedItem = function (li, e, preventSelect) {\n this.removeSelection();\n li.classList.add(dropDownBaseClasses.selected);\n this.removeHover();\n var value = this.getFormattedValue(li.getAttribute('data-value'));\n this.item = li;\n this.itemData = this.getDataByValue(value);\n if (!this.initial && !preventSelect) {\n var items = this.detachChanges();\n this.isSelected = true;\n var eventArgs = {\n e: e,\n item: this.item,\n itemData: items,\n isInteracted: e ? true : false,\n cancel: false\n };\n this.trigger('select', eventArgs);\n if (eventArgs.cancel) {\n return true;\n }\n }\n var focusedItem = this.list.querySelector('.' + dropDownBaseClasses.focus);\n if (focusedItem) {\n removeClass([focusedItem], dropDownBaseClasses.focus);\n }\n li.setAttribute('aria-selected', 'true');\n this.activeIndex = this.getIndexByValue(value);\n return false;\n };\n DropDownList.prototype.activeItem = function (li) {\n if (this.isValidLI(li) && !li.classList.contains(dropDownBaseClasses.selected)) {\n this.removeSelection();\n li.classList.add(dropDownBaseClasses.selected);\n this.removeHover();\n li.setAttribute('aria-selected', 'true');\n }\n };\n DropDownList.prototype.setValue = function (e) {\n var dataItem = this.getItemData();\n if (dataItem.value === null) {\n Input.setValue(null, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n else {\n Input.setValue(dataItem.text, this.inputElement, this.floatLabelType, this.showClearButton);\n }\n if (this.previousValue === dataItem.value) {\n this.isSelected = false;\n return true;\n }\n else {\n this.isSelected = !this.initial ? true : false;\n this.isSelectCustom = false;\n if (this.getModuleName() === 'dropdownlist') {\n this.updateIconState();\n }\n return false;\n }\n };\n DropDownList.prototype.setSelection = function (li, e) {\n if (this.isValidLI(li) && !li.classList.contains(dropDownBaseClasses.selected)) {\n this.previousItemData = (!isNullOrUndefined(this.itemData)) ? this.itemData : null;\n var argsCancel = this.updateSelectedItem(li, e, false);\n if (argsCancel) {\n return;\n }\n }\n if (this.list) {\n this.removeHover();\n }\n this.previousSelectedLI = (!isNullOrUndefined(this.selectedLI)) ? this.selectedLI : null;\n this.selectedLI = li;\n if (this.setValue(e)) {\n return;\n }\n if (this.valueTemplate && this.itemData !== null) {\n this.setValueTemplate();\n }\n else if (this.inputElement.previousSibling === this.valueTempElement) {\n detach(this.valueTempElement);\n this.inputElement.style.display = 'block';\n }\n if (this.isPopupOpen) {\n attributes(this.targetElement(), { 'aria-activedescendant': this.selectedLI ? this.selectedLI.id : null });\n if (this.isFilterLayout()) {\n attributes(this.filterInput, { 'aria-activedescendant': this.selectedLI ? this.selectedLI.id : null });\n }\n }\n if ((!this.isPopupOpen && !isNullOrUndefined(li)) || (this.isPopupOpen && !isNullOrUndefined(e) &&\n (e.type !== 'keydown' || e.type === 'keydown' && e.action === 'enter'))) {\n this.isSelectCustom = false;\n this.onChangeEvent(e);\n }\n if (this.isPopupOpen && !isNullOrUndefined(this.selectedLI) && this.itemData !== null && (!e || e.type !== 'click')) {\n this.setScrollPosition(e);\n }\n };\n DropDownList.prototype.setValueTemplate = function () {\n var compiledString;\n if (!this.valueTempElement) {\n this.valueTempElement = this.createElement('span', { className: dropDownListClasses.value });\n this.inputElement.parentElement.insertBefore(this.valueTempElement, this.inputElement);\n this.inputElement.style.display = 'none';\n }\n this.valueTempElement.innerHTML = '';\n compiledString = compile(this.valueTemplate);\n for (var _i = 0, _a = compiledString(this.itemData); _i < _a.length; _i++) {\n var item = _a[_i];\n this.valueTempElement.appendChild(item);\n }\n };\n DropDownList.prototype.removeSelection = function () {\n var selectedItems = this.list.querySelectorAll('.' + dropDownBaseClasses.selected);\n if (selectedItems.length) {\n removeClass(selectedItems, dropDownBaseClasses.selected);\n selectedItems[0].removeAttribute('aria-selected');\n }\n };\n ;\n DropDownList.prototype.getItemData = function () {\n var fields = this.fields;\n var dataItem = null;\n dataItem = this.itemData;\n var dataValue;\n var dataText;\n if (!isNullOrUndefined(dataItem)) {\n dataValue = getValue(fields.value, dataItem);\n dataText = getValue(fields.text, dataItem);\n }\n var value = (!isNullOrUndefined(dataItem) &&\n !isUndefined(dataValue) ? dataValue : dataItem);\n var text = (!isNullOrUndefined(dataItem) &&\n !isUndefined(dataValue) ? dataText : dataItem);\n return { value: value, text: text };\n };\n /**\n * To trigger the change event for list.\n */\n DropDownList.prototype.onChangeEvent = function (eve) {\n var dataItem = this.getItemData();\n var index = this.isSelectCustom ? null : this.activeIndex;\n this.setProperties({ 'value': dataItem.value, 'index': index, 'text': dataItem.text }, true);\n this.detachChangeEvent(eve);\n };\n ;\n DropDownList.prototype.detachChanges = function () {\n var items;\n if (typeof this.itemData === 'string' ||\n typeof this.itemData === 'boolean' ||\n typeof this.itemData === 'number') {\n items = Object.defineProperties({}, {\n value: {\n value: this.itemData,\n enumerable: true\n },\n text: {\n value: this.itemData,\n enumerable: true\n }\n });\n }\n else {\n items = this.itemData;\n }\n return items;\n };\n DropDownList.prototype.detachChangeEvent = function (eve) {\n this.isSelected = false;\n this.previousValue = this.value;\n this.activeIndex = this.index;\n this.typedString = !isNullOrUndefined(this.text) ? this.text : '';\n if (!this.initial) {\n var items = this.detachChanges();\n var preItems = void 0;\n if (typeof this.previousItemData === 'string' ||\n typeof this.previousItemData === 'boolean' ||\n typeof this.previousItemData === 'number') {\n preItems = Object.defineProperties({}, {\n value: {\n value: this.previousItemData,\n enumerable: true\n },\n text: {\n value: this.previousItemData,\n enumerable: true\n }\n });\n }\n else {\n preItems = this.previousItemData;\n }\n this.setHiddenValue();\n var eventArgs = {\n e: eve,\n item: this.item,\n itemData: items,\n previousItem: this.previousSelectedLI,\n previousItemData: preItems,\n isInteracted: eve ? true : false,\n value: this.value,\n element: this.element\n };\n this.trigger('change', eventArgs);\n }\n };\n DropDownList.prototype.setHiddenValue = function () {\n if (!isNullOrUndefined(this.value)) {\n this.hiddenElement.innerHTML = '' + this.text + ' ';\n var selectedElement = this.hiddenElement.querySelector('option');\n selectedElement.setAttribute('value', this.value.toString());\n }\n else {\n this.hiddenElement.innerHTML = '';\n }\n };\n /**\n * Filter bar implementation\n */\n DropDownList.prototype.onFilterUp = function (e) {\n this.isValidKey = e.keyCode === 40 || e.keyCode === 38 || this.isValidKey;\n if (this.isValidKey) {\n this.isValidKey = false;\n switch (e.keyCode) {\n case 38: //up arrow \n case 40://down arrow \n if (this.getModuleName() === 'autocomplete' && !this.isPopupOpen && !this.preventAltUp && !this.isRequested) {\n this.preventAutoFill = true;\n this.searchLists(e);\n }\n else {\n this.preventAutoFill = false;\n }\n this.preventAltUp = false;\n e.preventDefault();\n break;\n case 46: //delete\n case 8://backspace\n this.typedString = this.filterInput.value;\n if (!this.isPopupOpen && this.typedString !== '' || this.isPopupOpen && this.queryString.length > 0) {\n this.preventAutoFill = true;\n this.searchLists(e);\n }\n else if (this.typedString === '') {\n this.resetFocusElement();\n this.activeIndex = null;\n if (this.getModuleName() === 'autocomplete') {\n this.hidePopup();\n }\n }\n e.preventDefault();\n break;\n default:\n this.typedString = this.filterInput.value;\n this.preventAutoFill = false;\n this.searchLists(e);\n break;\n }\n }\n };\n DropDownList.prototype.onFilterDown = function (e) {\n switch (e.keyCode) {\n case 13://enter\n break;\n case 40: //down arrow \n case 38://up arrow \n this.queryString = this.filterInput.value;\n e.preventDefault();\n break;\n case 9://tab \n if (this.isPopupOpen) {\n e.preventDefault();\n }\n break;\n default:\n this.prevSelectPoints = this.getSelectionPoints();\n this.queryString = this.filterInput.value;\n break;\n }\n };\n DropDownList.prototype.removeFillSelection = function () {\n if (this.isInteracted) {\n var selection = this.getSelectionPoints();\n this.inputElement.setSelectionRange(selection.end, selection.end);\n }\n };\n DropDownList.prototype.getSelectionPoints = function () {\n var input = this.inputElement;\n return { start: Math.abs(input.selectionStart), end: Math.abs(input.selectionEnd) };\n };\n DropDownList.prototype.searchLists = function (e) {\n var _this = this;\n this.isTyped = true;\n this.activeIndex = null;\n if (this.filterInput.parentElement.querySelector('.' + dropDownListClasses.clearIcon)) {\n var clearElement = this.filterInput.parentElement.querySelector('.' + dropDownListClasses.clearIcon);\n clearElement.style.visibility = this.filterInput.value === '' ? 'hidden' : 'visible';\n }\n if (this.isFiltering()) {\n var eventArgs_1 = {\n preventDefaultAction: false,\n text: this.filterInput.value,\n updateData: function (dataSource, query, fields) {\n if (eventArgs_1.cancel) {\n return;\n }\n _this.isCustomFilter = true;\n _this.filteringAction(dataSource, query, fields);\n },\n baseEventArgs: e,\n cancel: false\n };\n this.trigger('filtering', eventArgs_1);\n if (eventArgs_1.cancel) {\n return;\n }\n if (!this.isCustomFilter && !eventArgs_1.preventDefaultAction) {\n var filterQuery = this.query ? this.query.clone() : new Query();\n var dataType = this.typeOfData(this.dataSource).typeof;\n if (!(this.dataSource instanceof DataManager) && dataType === 'string' || dataType === 'number') {\n filterQuery.where('', 'startswith', this.filterInput.value, true, this.ignoreAccent);\n }\n else {\n var fields = this.fields;\n filterQuery.where(!isNullOrUndefined(fields.text) ? fields.text : '', 'startswith', this.filterInput.value, true, this.ignoreAccent);\n }\n this.filteringAction(this.dataSource, filterQuery, this.fields);\n }\n }\n };\n DropDownList.prototype.filteringAction = function (dataSource, query, fields) {\n if (!isNullOrUndefined(this.filterInput)) {\n this.beforePopupOpen = true;\n if (this.filterInput.value.trim() === '') {\n this.actionCompleteData.isUpdated = false;\n this.isTyped = false;\n if (!isNullOrUndefined(this.actionCompleteData.ulElement) && !isNullOrUndefined(this.actionCompleteData.list)) {\n this.onActionComplete(this.actionCompleteData.ulElement, this.actionCompleteData.list);\n }\n this.isTyped = true;\n if (!isNullOrUndefined(this.itemData) && this.getModuleName() === 'dropdownlist') {\n this.focusIndexItem();\n this.setScrollPosition();\n }\n this.isNotSearchList = true;\n }\n else {\n this.isNotSearchList = false;\n this.resetList(dataSource, fields, query);\n }\n }\n };\n DropDownList.prototype.setSearchBox = function (popupElement) {\n if (this.isFiltering()) {\n var parentElement = this.createElement('span', {\n className: dropDownListClasses.filterParent\n });\n this.filterInput = this.createElement('input', {\n attrs: { type: 'text' },\n className: dropDownListClasses.filterInput\n });\n this.element.parentNode.insertBefore(this.filterInput, this.element);\n var backIcon = false;\n if (Browser.isDevice) {\n backIcon = true;\n }\n this.filterInputObj = Input.createInput({\n element: this.filterInput,\n buttons: backIcon ?\n [dropDownListClasses.backIcon, dropDownListClasses.filterBarClearIcon] : [dropDownListClasses.filterBarClearIcon],\n properties: { placeholder: this.filterBarPlaceholder }\n }, this.createElement);\n append([this.filterInputObj.container], parentElement);\n prepend([parentElement], popupElement);\n attributes(this.filterInput, {\n 'aria-disabled': 'false',\n 'aria-owns': this.element.id + '_options',\n 'role': 'listbox',\n 'aria-activedescendant': this.selectedLI ? this.selectedLI.id : null,\n 'autocomplete': 'off',\n 'autocorrect': 'off',\n 'autocapitalize': 'off',\n 'spellcheck': 'false'\n });\n this.clearIconElement = this.filterInput.parentElement.querySelector('.' + dropDownListClasses.clearIcon);\n if (!Browser.isDevice && this.clearIconElement) {\n EventHandler.add(this.clearIconElement, 'click', this.clearText, this);\n this.clearIconElement.style.visibility = 'hidden';\n }\n if (!Browser.isDevice) {\n this.searchKeyModule = new KeyboardEvents(this.filterInput, {\n keyAction: this.keyActionHandler.bind(this),\n keyConfigs: this.keyConfigure,\n eventName: 'keydown'\n });\n }\n EventHandler.add(this.filterInput, 'input', this.onInput, this);\n EventHandler.add(this.filterInput, 'keyup', this.onFilterUp, this);\n EventHandler.add(this.filterInput, 'keydown', this.onFilterDown, this);\n EventHandler.add(this.filterInput, 'blur', this.onBlur, this);\n return this.filterInputObj;\n }\n else {\n return inputObject;\n }\n };\n ;\n DropDownList.prototype.onInput = function () {\n this.isValidKey = true;\n };\n DropDownList.prototype.onActionFailure = function (e) {\n _super.prototype.onActionFailure.call(this, e);\n if (this.beforePopupOpen) {\n this.renderPopup();\n }\n };\n DropDownList.prototype.onActionComplete = function (ulElement, list, e, isUpdated) {\n if (this.isNotSearchList) {\n this.isNotSearchList = false;\n return;\n }\n if (this.isActive) {\n var selectedItem = this.selectedLI ? this.selectedLI.cloneNode(true) : null;\n _super.prototype.onActionComplete.call(this, ulElement, list, e);\n if (this.isRequested && !isNullOrUndefined(this.searchKeyEvent) && this.searchKeyEvent.type === 'keydown') {\n this.isRequested = false;\n this.keyActionHandler(this.searchKeyEvent);\n this.searchKeyEvent = null;\n }\n if (this.isRequested && !isNullOrUndefined(this.searchKeyEvent)) {\n this.incrementalSearch(this.searchKeyEvent);\n this.searchKeyEvent = null;\n }\n this.list.scrollTop = 0;\n if (!isNullOrUndefined(ulElement)) {\n attributes(ulElement, { 'id': this.element.id + '_options', 'role': 'listbox', 'aria-hidden': 'false' });\n }\n if (this.initRemoteRender) {\n this.initial = true;\n this.activeIndex = this.index;\n this.updateValues();\n this.initRemoteRender = false;\n this.initial = false;\n }\n if (this.getModuleName() !== 'autocomplete' && this.isFiltering() && !this.isTyped) {\n if (!this.actionCompleteData.isUpdated || ((!this.isCustomFilter\n && !this.isFilterFocus)\n && ((this.dataSource instanceof DataManager)\n || (!isNullOrUndefined(this.dataSource.length) && this.dataSource.length !== 0)))) {\n this.actionCompleteData = { ulElement: ulElement.cloneNode(true), list: list, isUpdated: true };\n }\n this.addNewItem(list, selectedItem);\n if (!isNullOrUndefined(this.itemData)) {\n this.focusIndexItem();\n }\n }\n if (this.beforePopupOpen) {\n this.renderPopup();\n }\n }\n };\n DropDownList.prototype.addNewItem = function (listData, newElement) {\n var _this = this;\n if (!isNullOrUndefined(this.itemData) && !isNullOrUndefined(newElement)) {\n var value_1 = this.getItemData().value;\n var isExist = listData.some(function (data) {\n return (((typeof data === 'string' || typeof data === 'number') && data === value_1) ||\n (getValue(_this.fields.value, data) === value_1));\n });\n if (!isExist) {\n this.addItem(this.itemData);\n }\n }\n };\n DropDownList.prototype.updateActionCompleteData = function (li, item) {\n if (this.getModuleName() !== 'autocomplete' && this.actionCompleteData.ulElement) {\n this.actionCompleteData.ulElement.appendChild(li.cloneNode(true));\n if (this.isFiltering()) {\n this.actionCompleteData.list.push(item);\n }\n }\n };\n DropDownList.prototype.focusIndexItem = function () {\n var value = this.getItemData().value;\n this.activeIndex = this.getIndexByValue(value);\n var element = this.list.querySelector('[data-value=\"' + value + '\"]');\n this.selectedLI = element;\n this.activeItem(element);\n this.removeFocus();\n };\n DropDownList.prototype.updateSelection = function () {\n var selectedItem = this.list.querySelector('.' + dropDownBaseClasses.selected);\n if (selectedItem) {\n this.setProperties({ 'index': this.getIndexByValue(selectedItem.getAttribute('data-value')) });\n this.activeIndex = this.index;\n }\n else {\n this.removeFocus();\n this.list.querySelector('.' + dropDownBaseClasses.li).classList.add(dropDownListClasses.focus);\n }\n };\n DropDownList.prototype.removeFocus = function () {\n var highlightedItem = this.list.querySelectorAll('.' + dropDownListClasses.focus);\n if (highlightedItem && highlightedItem.length) {\n removeClass(highlightedItem, dropDownListClasses.focus);\n }\n };\n ;\n DropDownList.prototype.renderPopup = function () {\n if (this.popupObj && document.body.contains(this.popupObj.element)) {\n this.refreshPopup();\n return;\n }\n var args = { cancel: false };\n this.trigger('beforeOpen', args);\n if (args.cancel) {\n return;\n }\n var popupEle = this.createElement('div', {\n id: this.element.id + '_popup', className: 'e-ddl e-popup ' + (this.cssClass != null ? this.cssClass : '')\n });\n var searchBox = this.setSearchBox(popupEle);\n this.listHeight = formatUnit(this.popupHeight);\n if (this.headerTemplate) {\n this.setHeaderTemplate(popupEle);\n }\n append([this.list], popupEle);\n if (this.footerTemplate) {\n this.setFooterTemplate(popupEle);\n }\n document.body.appendChild(popupEle);\n popupEle.style.visibility = 'hidden';\n if (this.popupHeight !== 'auto') {\n this.searchBoxHeight = 0;\n if (!isNullOrUndefined(searchBox.container)) {\n this.searchBoxHeight = (searchBox.container.parentElement).getBoundingClientRect().height;\n this.listHeight = (parseInt(this.listHeight, 10) - (this.searchBoxHeight)).toString() + 'px';\n }\n if (this.headerTemplate) {\n var height = Math.round(this.header.getBoundingClientRect().height);\n this.listHeight = (parseInt(this.listHeight, 10) - (height + this.searchBoxHeight)).toString() + 'px';\n }\n if (this.footerTemplate) {\n var height = Math.round(this.footer.getBoundingClientRect().height);\n this.listHeight = (parseInt(this.listHeight, 10) - (height + this.searchBoxHeight)).toString() + 'px';\n }\n this.list.style.maxHeight = (parseInt(this.listHeight, 10) - 2).toString() + 'px'; // due to box-sizing property\n popupEle.style.maxHeight = formatUnit(this.popupHeight);\n }\n else {\n popupEle.style.height = 'auto';\n }\n var offsetValue = 0;\n var left;\n if (!isNullOrUndefined(this.selectedLI) && (!isNullOrUndefined(this.activeIndex) && this.activeIndex >= 0)) {\n this.setScrollPosition();\n }\n else {\n this.list.scrollTop = 0;\n }\n if (Browser.isDevice && (!this.allowFiltering && (this.getModuleName() === 'dropdownlist' ||\n (this.isDropDownClick && this.getModuleName() === 'combobox')))) {\n offsetValue = this.getOffsetValue(popupEle);\n var firstItem = this.isEmptyList() ? this.list : this.liCollections[0];\n left = -(parseInt(getComputedStyle(firstItem).textIndent, 10) -\n parseInt(getComputedStyle(this.inputElement).paddingLeft, 10) +\n parseInt(getComputedStyle(this.inputElement.parentElement).borderLeftWidth, 10));\n }\n this.getFocusElement();\n this.createPopup(popupEle, offsetValue, left);\n this.checkCollision(popupEle);\n if (Browser.isDevice) {\n this.popupObj.element.classList.add(dropDownListClasses.device);\n if (this.getModuleName() === 'dropdownlist' || (this.getModuleName() === 'combobox'\n && !this.allowFiltering && this.isDropDownClick)) {\n this.popupObj.collision = { X: 'fit', Y: 'fit' };\n }\n if (this.isFilterLayout()) {\n this.popupObj.element.classList.add(dropDownListClasses.mobileFilter);\n this.popupObj.position = { X: 0, Y: 0 };\n this.popupObj.dataBind();\n attributes(this.popupObj.element, { style: 'left:0px;right:0px;top:0px;bottom:0px;' });\n addClass([document.body, this.popupObj.element], dropDownListClasses.popupFullScreen);\n this.setSearchBoxPosition();\n this.backIconElement = searchBox.container.querySelector('.e-back-icon');\n this.clearIconElement = searchBox.container.querySelector('.' + dropDownListClasses.clearIcon);\n EventHandler.add(this.backIconElement, 'click', this.clickOnBackIcon, this);\n EventHandler.add(this.clearIconElement, 'click', this.clearText, this);\n }\n }\n popupEle.style.visibility = 'visible';\n addClass([popupEle], 'e-popup-close');\n var scrollParentElements = this.popupObj.getScrollableParent(this.inputWrapper.container);\n for (var _i = 0, scrollParentElements_1 = scrollParentElements; _i < scrollParentElements_1.length; _i++) {\n var element = scrollParentElements_1[_i];\n EventHandler.add(element, 'scroll', this.scrollHandler, this);\n }\n if (Browser.isDevice && this.isFilterLayout()) {\n EventHandler.add(this.list, 'scroll', this.listScroll, this);\n }\n attributes(this.targetElement(), { 'aria-expanded': 'true' });\n var inputParent = this.isFiltering() ? this.filterInput.parentElement : this.inputWrapper.container;\n addClass([inputParent], [dropDownListClasses.inputFocus]);\n var animModel = { name: 'FadeIn', duration: 100 };\n this.beforePopupOpen = true;\n var eventArgs = { popup: this.popupObj, cancel: false, animation: animModel };\n this.trigger('open', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n addClass([this.inputWrapper.container], [dropDownListClasses.iconAnimation]);\n this.popupObj.show(new Animation(eventArgs.animation), (this.zIndex === 1000) ? this.element : null);\n };\n DropDownList.prototype.checkCollision = function (popupEle) {\n if (!Browser.isDevice || (Browser.isDevice && !(this.getModuleName() === 'dropdownlist' || this.isDropDownClick))) {\n var collision = isCollide(popupEle);\n if (collision.length > 0) {\n popupEle.style.marginTop = -parseInt(getComputedStyle(popupEle).marginTop, 10) + 'px';\n }\n }\n };\n DropDownList.prototype.getOffsetValue = function (popupEle) {\n var popupStyles = getComputedStyle(popupEle);\n var borderTop = parseInt(popupStyles.borderTop, 10);\n var borderBottom = parseInt(popupStyles.borderBottom, 10);\n return this.setPopupPosition(borderTop + borderBottom);\n };\n DropDownList.prototype.createPopup = function (element, offsetValue, left) {\n var _this = this;\n this.popupObj = new Popup(element, {\n width: this.setWidth(), targetType: 'relative',\n relateTo: this.inputWrapper.container, collision: { X: 'flip', Y: 'flip' }, offsetY: offsetValue,\n enableRtl: this.enableRtl, offsetX: left, position: { X: 'left', Y: 'bottom' },\n zIndex: this.zIndex,\n close: function () {\n if (!_this.isDocumentClick) {\n _this.focusDropDown();\n }\n _this.isDocumentClick = false;\n _this.destroyPopup();\n },\n open: function () {\n EventHandler.add(document, 'mousedown', _this.onDocumentClick, _this);\n _this.isPopupOpen = true;\n if (_this.isFilterLayout()) {\n removeClass([_this.inputWrapper.container], [dropDownListClasses.inputFocus]);\n _this.isFilterFocus = true;\n _this.filterInput.focus();\n if (_this.inputWrapper.clearButton) {\n addClass([_this.inputWrapper.clearButton], dropDownListClasses.clearIconHide);\n }\n }\n _this.activeStateChange();\n }\n });\n };\n DropDownList.prototype.isEmptyList = function () {\n return !isNullOrUndefined(this.liCollections) && this.liCollections.length === 0;\n };\n DropDownList.prototype.getFocusElement = function () {\n // combo-box used this method\n };\n DropDownList.prototype.isFilterLayout = function () {\n return this.getModuleName() === 'dropdownlist' && this.allowFiltering;\n };\n DropDownList.prototype.scrollHandler = function () {\n if (Browser.isDevice && ((this.getModuleName() === 'dropdownlist' &&\n !this.isFilterLayout()) || (this.getModuleName() === 'combobox' && !this.allowFiltering && this.isDropDownClick))) {\n this.hidePopup();\n }\n if (this.fields.groupBy && !isNullOrUndefined(this.fixedHeaderElement)) {\n this.fixedHeaderElement.style.zIndex = '0';\n this.fixedHeaderElement.style.display = 'none';\n }\n };\n DropDownList.prototype.setSearchBoxPosition = function () {\n var searchBoxHeight = this.filterInput.parentElement.getBoundingClientRect().height;\n this.popupObj.element.style.maxHeight = '100%';\n this.popupObj.element.style.width = '100%';\n this.list.style.maxHeight = (window.innerHeight - searchBoxHeight) + 'px';\n this.list.style.height = (window.innerHeight - searchBoxHeight) + 'px';\n var clearElement = this.filterInput.parentElement.querySelector('.' + dropDownListClasses.clearIcon);\n detach(this.filterInput);\n clearElement.parentElement.insertBefore(this.filterInput, clearElement);\n };\n DropDownList.prototype.setPopupPosition = function (border) {\n var offsetValue;\n var popupOffset = border;\n var selectedLI = this.list.querySelector('.' + dropDownListClasses.focus) || this.selectedLI;\n var firstItem = this.isEmptyList() ? this.list : this.liCollections[0];\n var lastItem = this.isEmptyList() ? this.list : this.liCollections[this.getItems().length - 1];\n var liHeight = firstItem.getBoundingClientRect().height;\n var listHeight = this.list.offsetHeight / 2;\n var height = isNullOrUndefined(selectedLI) ? firstItem.offsetTop : selectedLI.offsetTop;\n var lastItemOffsetValue = lastItem.offsetTop;\n if (lastItemOffsetValue - listHeight < height && !isNullOrUndefined(this.liCollections) &&\n this.liCollections.length > 0 && !isNullOrUndefined(selectedLI)) {\n var count = this.list.offsetHeight / liHeight;\n var paddingBottom = parseInt(getComputedStyle(this.list).paddingBottom, 10);\n offsetValue = (count - (this.liCollections.length - this.activeIndex)) * liHeight - popupOffset + paddingBottom;\n this.list.scrollTop = selectedLI.offsetTop;\n }\n else if (height > listHeight) {\n offsetValue = listHeight - liHeight / 2;\n this.list.scrollTop = height - listHeight + liHeight / 2;\n }\n else {\n offsetValue = height;\n }\n var inputHeight = this.inputWrapper.container.offsetHeight;\n offsetValue = offsetValue + liHeight + popupOffset - ((liHeight - inputHeight) / 2);\n return -offsetValue;\n };\n DropDownList.prototype.setWidth = function () {\n var width = formatUnit(this.popupWidth);\n if (width.indexOf('%') > -1) {\n var inputWidth = this.inputWrapper.container.offsetWidth * parseFloat(width) / 100;\n width = inputWidth.toString() + 'px';\n }\n if (Browser.isDevice && (!this.allowFiltering && (this.getModuleName() === 'dropdownlist' ||\n (this.isDropDownClick && this.getModuleName() === 'combobox')))) {\n var firstItem = this.isEmptyList() ? this.list : this.liCollections[0];\n width = (parseInt(width, 10) + (parseInt(getComputedStyle(firstItem).textIndent, 10) -\n parseInt(getComputedStyle(this.inputElement).paddingLeft, 10) +\n parseInt(getComputedStyle(this.inputElement.parentElement).borderLeftWidth, 10)) * 2) + 'px';\n }\n return width;\n };\n DropDownList.prototype.scrollBottom = function (isInitial) {\n var currentOffset = this.list.offsetHeight;\n var nextBottom = this.selectedLI.offsetTop + this.selectedLI.offsetHeight - this.list.scrollTop;\n var nextOffset = this.list.scrollTop + nextBottom - currentOffset;\n nextOffset = isInitial ? nextOffset + parseInt(getComputedStyle(this.list).paddingTop, 10) * 2 : nextOffset;\n var boxRange = this.selectedLI.offsetTop + this.selectedLI.offsetHeight - this.list.scrollTop;\n boxRange = this.fields.groupBy && !isNullOrUndefined(this.fixedHeaderElement) ?\n boxRange - this.fixedHeaderElement.offsetHeight : boxRange;\n if (this.activeIndex === 0) {\n this.list.scrollTop = 0;\n }\n else if (nextBottom > currentOffset || !(boxRange > 0 && this.list.offsetHeight > boxRange)) {\n this.list.scrollTop = nextOffset;\n }\n };\n DropDownList.prototype.scrollTop = function () {\n var nextOffset = this.selectedLI.offsetTop - this.list.scrollTop;\n var nextBottom = this.selectedLI.offsetTop + this.selectedLI.offsetHeight - this.list.scrollTop;\n nextOffset = this.fields.groupBy && !isNullOrUndefined(this.fixedHeaderElement) ?\n nextOffset - this.fixedHeaderElement.offsetHeight : nextOffset;\n var boxRange = (this.selectedLI.offsetTop + this.selectedLI.offsetHeight - this.list.scrollTop);\n if (this.activeIndex === 0) {\n this.list.scrollTop = 0;\n }\n else if (nextOffset < 0) {\n this.list.scrollTop = this.list.scrollTop + nextOffset;\n }\n else if (!(boxRange > 0 && this.list.offsetHeight > boxRange)) {\n this.list.scrollTop = this.selectedLI.offsetTop - (this.fields.groupBy && !isNullOrUndefined(this.fixedHeaderElement) ?\n this.fixedHeaderElement.offsetHeight : 0);\n }\n };\n DropDownList.prototype.isEditTextBox = function () {\n return false;\n };\n DropDownList.prototype.isFiltering = function () {\n return this.allowFiltering;\n };\n DropDownList.prototype.isPopupButton = function () {\n return true;\n };\n DropDownList.prototype.setScrollPosition = function (e) {\n if (!isNullOrUndefined(e)) {\n switch (e.action) {\n case 'pageDown':\n case 'down':\n case 'end':\n this.scrollBottom();\n break;\n default:\n this.scrollTop();\n break;\n }\n }\n else {\n this.scrollBottom(true);\n }\n };\n DropDownList.prototype.clearText = function () {\n this.filterInput.value = '';\n this.searchLists(null);\n };\n DropDownList.prototype.listScroll = function () {\n this.filterInput.blur();\n };\n DropDownList.prototype.closePopup = function (delay) {\n this.isTyped = false;\n if (!(this.popupObj && document.body.contains(this.popupObj.element) && this.beforePopupOpen)) {\n return;\n }\n EventHandler.remove(document, 'mousedown', this.onDocumentClick);\n this.isActive = false;\n this.filterInputObj = null;\n this.isDropDownClick = false;\n this.preventAutoFill = false;\n var scrollableParentElements = this.popupObj.getScrollableParent(this.inputWrapper.container);\n for (var _i = 0, scrollableParentElements_1 = scrollableParentElements; _i < scrollableParentElements_1.length; _i++) {\n var element = scrollableParentElements_1[_i];\n EventHandler.remove(element, 'scroll', this.scrollHandler);\n }\n if (Browser.isDevice && this.isFilterLayout()) {\n removeClass([document.body, this.popupObj.element], dropDownListClasses.popupFullScreen);\n EventHandler.remove(this.list, 'scroll', this.listScroll);\n }\n if (this.isFilterLayout()) {\n if (!Browser.isDevice) {\n this.searchKeyModule.destroy();\n if (this.clearIconElement) {\n EventHandler.remove(this.clearIconElement, 'click', this.clearText);\n }\n }\n if (this.backIconElement) {\n EventHandler.remove(this.backIconElement, 'click', this.clickOnBackIcon);\n EventHandler.remove(this.clearIconElement, 'click', this.clearText);\n }\n EventHandler.remove(this.filterInput, 'input', this.onInput);\n EventHandler.remove(this.filterInput, 'keyup', this.onFilterUp);\n EventHandler.remove(this.filterInput, 'keydown', this.onFilterDown);\n EventHandler.remove(this.filterInput, 'blur', this.onBlur);\n this.filterInput = null;\n }\n attributes(this.targetElement(), { 'aria-expanded': 'false', 'aria-activedescendant': null });\n this.inputWrapper.container.classList.remove(dropDownListClasses.iconAnimation);\n if (this.isFiltering()) {\n this.actionCompleteData.isUpdated = false;\n }\n this.beforePopupOpen = false;\n var animModel = {\n name: 'FadeOut',\n duration: 100,\n delay: delay ? delay : 0\n };\n var eventArgs = { popup: this.popupObj, cancel: false, animation: animModel };\n this.trigger('close', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n if (this.getModuleName() === 'autocomplete') {\n this.rippleFun();\n }\n if (this.isPopupOpen) {\n this.popupObj.hide(new Animation(eventArgs.animation));\n }\n else {\n this.destroyPopup();\n }\n };\n DropDownList.prototype.destroyPopup = function () {\n this.isPopupOpen = false;\n this.isFilterFocus = false;\n this.popupObj.destroy();\n detach(this.popupObj.element);\n };\n DropDownList.prototype.clickOnBackIcon = function () {\n this.hidePopup();\n this.focusIn();\n };\n /**\n * To Initialize the control rendering\n * @private\n */\n DropDownList.prototype.render = function () {\n if (this.element.tagName === 'INPUT') {\n this.inputElement = this.element;\n }\n else {\n this.inputElement = this.createElement('input');\n if (this.element.tagName !== this.getNgDirective()) {\n this.element.style.display = 'none';\n }\n this.element.parentElement.insertBefore(this.inputElement, this.element);\n this.preventTabIndex(this.inputElement);\n }\n this.inputWrapper = Input.createInput({\n element: this.inputElement,\n buttons: this.isPopupButton() ? [dropDownListClasses.icon] : null,\n floatLabelType: this.floatLabelType,\n properties: {\n readonly: this.getModuleName() === 'dropdownlist' ? true : this.readonly,\n placeholder: this.placeholder,\n cssClass: this.cssClass,\n enabled: this.enabled,\n enableRtl: this.enableRtl,\n showClearButton: this.showClearButton\n },\n }, this.createElement);\n if (this.element.tagName === this.getNgDirective()) {\n this.element.appendChild(this.inputWrapper.container);\n }\n else {\n this.inputElement.parentElement.insertBefore(this.element, this.inputElement);\n }\n this.hiddenElement = this.createElement('select', {\n attrs: { 'aria-hidden': 'true', 'tabindex': '-1', 'class': dropDownListClasses.hiddenElement }\n });\n prepend([this.hiddenElement], this.inputWrapper.container);\n this.validationAttribute(this.element, this.hiddenElement);\n this.setFields();\n this.inputWrapper.container.style.width = formatUnit(this.width);\n this.inputWrapper.container.classList.add('e-ddl');\n this.wireEvent();\n this.tabIndex = this.element.hasAttribute('tabindex') ? this.element.getAttribute('tabindex') : '0';\n this.element.removeAttribute('tabindex');\n var id = this.element.getAttribute('id') ? this.element.getAttribute('id') : getUniqueID('ej2_dropdownlist');\n this.element.id = id;\n this.hiddenElement.id = id + '_hidden';\n this.targetElement().setAttribute('tabindex', this.tabIndex);\n attributes(this.targetElement(), this.getAriaAttributes());\n this.setHTMLAttributes();\n if (this.value !== null || this.activeIndex !== null || this.text !== null) {\n this.initValue();\n }\n else if (this.element.tagName === 'SELECT' && this.element.options[0]) {\n var selectElement = this.element;\n this.value = selectElement.options[selectElement.selectedIndex].value;\n this.text = isNullOrUndefined(this.value) ? null : selectElement.options[selectElement.selectedIndex].textContent;\n this.initValue();\n }\n this.preventTabIndex(this.element);\n if (!this.enabled) {\n this.targetElement().tabIndex = -1;\n }\n this.initial = false;\n this.element.style.opacity = '';\n this.inputElement.onselect = function (e) { e.stopImmediatePropagation(); };\n this.inputElement.onchange = function (e) { e.stopImmediatePropagation(); };\n if (this.element.hasAttribute('autofocus')) {\n this.focusIn();\n }\n };\n ;\n DropDownList.prototype.setFooterTemplate = function (popupEle) {\n var compiledString;\n if (this.footer) {\n this.footer.innerHTML = '';\n }\n else {\n this.footer = this.createElement('div');\n addClass([this.footer], dropDownListClasses.footer);\n }\n compiledString = compile(this.footerTemplate);\n for (var _i = 0, _a = compiledString({}); _i < _a.length; _i++) {\n var item = _a[_i];\n this.footer.appendChild(item);\n }\n append([this.footer], popupEle);\n };\n DropDownList.prototype.setHeaderTemplate = function (popupEle) {\n var compiledString;\n if (this.header) {\n this.header.innerHTML = '';\n }\n else {\n this.header = this.createElement('div');\n addClass([this.header], dropDownListClasses.header);\n }\n compiledString = compile(this.headerTemplate);\n for (var _i = 0, _a = compiledString({}); _i < _a.length; _i++) {\n var item = _a[_i];\n this.header.appendChild(item);\n }\n var contentEle = popupEle.querySelector('div.e-content');\n popupEle.insertBefore(this.header, contentEle);\n };\n DropDownList.prototype.setOldText = function (text) {\n this.text = text;\n };\n DropDownList.prototype.setOldValue = function (value) {\n this.value = value;\n };\n DropDownList.prototype.refreshPopup = function () {\n if (!isNullOrUndefined(this.popupObj) && document.body.contains(this.popupObj.element) &&\n ((this.allowFiltering && !(Browser.isDevice && this.isFilterLayout())) || this.getModuleName() === 'autocomplete')) {\n this.popupObj.refreshPosition(this.inputWrapper.container);\n }\n };\n DropDownList.prototype.updateDataSource = function (prop) {\n this.clear(null, prop);\n this.resetList(this.dataSource);\n if (!this.isCustomFilter && !this.isFilterFocus && document.activeElement !== this.filterInput) {\n this.itemData = this.getDataByValue(this.value);\n var dataItem = this.getItemData();\n this.setProperties({ 'value': dataItem.value, 'text': dataItem.text });\n }\n };\n /**\n * Dynamically change the value of properties.\n * @private\n */\n DropDownList.prototype.onPropertyChanged = function (newProp, oldProp) {\n this.setUpdateInitial(['query', 'dataSource'], newProp);\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'query':\n case 'dataSource':\n break;\n case 'htmlAttributes':\n this.setHTMLAttributes();\n break;\n case 'width':\n setStyleAttribute(this.inputWrapper.container, { 'width': formatUnit(newProp.width) });\n break;\n case 'placeholder':\n Input.setPlaceholder(newProp.placeholder, this.inputElement);\n break;\n case 'filterBarPlaceholder':\n if (this.filterInput) {\n Input.setPlaceholder(newProp.filterBarPlaceholder, this.filterInput);\n }\n break;\n case 'readonly':\n if (this.getModuleName() !== 'dropdownlist') {\n Input.setReadonly(newProp.readonly, this.inputElement);\n }\n break;\n case 'cssClass':\n this.setCssClass(newProp, oldProp);\n break;\n case 'enableRtl':\n this.setEnableRtl();\n break;\n case 'enabled':\n this.setEnable();\n break;\n case 'text':\n if (newProp.text === null) {\n this.clear();\n break;\n }\n if (!this.list) {\n if (this.dataSource instanceof DataManager) {\n this.initRemoteRender = true;\n }\n this.renderList();\n }\n if (!this.initRemoteRender) {\n var li = this.getElementByText(newProp.text);\n if (this.isValidLI(li)) {\n this.setSelection(li, null);\n }\n else {\n this.setOldText(oldProp.text);\n }\n }\n break;\n case 'value':\n if (newProp.value === null) {\n this.clear();\n break;\n }\n this.notify('beforeValueChange', { newProp: newProp }); // gird component value type change\n if (!this.list) {\n if (this.dataSource instanceof DataManager) {\n this.initRemoteRender = true;\n }\n this.renderList();\n }\n if (!this.initRemoteRender) {\n var item = this.getElementByValue(newProp.value);\n if (this.isValidLI(item)) {\n this.setSelection(item, null);\n }\n else {\n this.setOldValue(oldProp.value);\n }\n }\n break;\n case 'index':\n if (newProp.index === null) {\n this.clear();\n break;\n }\n if (!this.list) {\n if (this.dataSource instanceof DataManager) {\n this.initRemoteRender = true;\n }\n this.renderList();\n }\n if (!this.initRemoteRender) {\n var element = this.liCollections[newProp.index];\n if (this.isValidLI(element)) {\n this.setSelection(element, null);\n }\n else {\n this.index = oldProp.index;\n }\n }\n break;\n case 'footerTemplate':\n if (this.popupObj) {\n this.setFooterTemplate(this.popupObj.element);\n }\n break;\n case 'headerTemplate':\n if (this.popupObj) {\n this.setHeaderTemplate(this.popupObj.element);\n }\n break;\n case 'valueTemplate':\n if (!isNullOrUndefined(this.itemData) && this.valueTemplate != null) {\n this.setValueTemplate();\n }\n break;\n case 'floatLabelType':\n Input.removeFloating(this.inputWrapper);\n Input.addFloating(this.inputElement, newProp.floatLabelType, this.placeholder, this.createElement);\n break;\n case 'showClearButton':\n Input.setClearButton(newProp.showClearButton, this.inputElement, this.inputWrapper, null, this.createElement);\n this.bindClearEvent();\n break;\n default:\n var ddlProps = void 0;\n ddlProps = this.getPropObject(prop, newProp, oldProp);\n _super.prototype.onPropertyChanged.call(this, ddlProps.newProperty, ddlProps.oldProperty);\n break;\n }\n }\n };\n DropDownList.prototype.setCssClass = function (newProp, oldProp) {\n this.inputWrapper.container.classList.remove(oldProp.cssClass);\n Input.setCssClass(newProp.cssClass, [this.inputWrapper.container]);\n if (this.popupObj) {\n this.popupObj.element.classList.remove(oldProp.cssClass);\n this.popupObj.element.classList.add(newProp.cssClass);\n }\n };\n /**\n * Return the module name.\n * @private\n */\n DropDownList.prototype.getModuleName = function () {\n return 'dropdownlist';\n };\n /**\n * Opens the popup that displays the list of items.\n * @returns void.\n */\n DropDownList.prototype.showPopup = function () {\n if (!this.enabled) {\n return;\n }\n if (this.beforePopupOpen) {\n this.refreshPopup();\n return;\n }\n this.beforePopupOpen = true;\n if (this.isFiltering() && !this.isActive && this.actionCompleteData.list && this.actionCompleteData.list[0]) {\n this.isActive = true;\n this.onActionComplete(this.actionCompleteData.ulElement, this.actionCompleteData.list, null, true);\n }\n else if (isNullOrUndefined(this.list) || !isUndefined(this.list) && this.list.classList.contains(dropDownBaseClasses.noData)) {\n this.renderList();\n }\n if (Browser.isDevice && this.isFilterLayout()) {\n var proxy_2 = this;\n window.onpopstate = function () {\n proxy_2.hidePopup();\n };\n history.pushState({}, '');\n }\n if (!isNullOrUndefined(this.list.children[0]) || this.list.classList.contains(dropDownBaseClasses.noData)) {\n this.renderPopup();\n }\n attributes(this.targetElement(), { 'aria-activedescendant': this.selectedLI ? this.selectedLI.id : null });\n };\n /**\n * Hides the popup if it is in an open state.\n * @returns void.\n */\n DropDownList.prototype.hidePopup = function () {\n if (this.isEscapeKey && this.getModuleName() === 'dropdownlist') {\n Input.setValue(this.text, this.inputElement, this.floatLabelType, this.showClearButton);\n this.isEscapeKey = false;\n if (!isNullOrUndefined(this.index)) {\n this.selectedLI = this.liCollections[this.index];\n this.updateSelectedItem(this.selectedLI, null, true);\n if (this.valueTemplate && this.itemData !== null) {\n this.setValueTemplate();\n }\n }\n else {\n this.resetSelection();\n }\n }\n this.closePopup();\n var dataItem = this.getItemData();\n if (this.inputElement.value.trim() === '' && !this.isInteracted && (this.isSelectCustom ||\n !isNullOrUndefined(this.selectedLI) && this.inputElement.value !== dataItem.text)) {\n this.isSelectCustom = false;\n this.clear();\n }\n };\n /**\n * Sets the focus on the component for interaction.\n * @returns void.\n */\n DropDownList.prototype.focusIn = function () {\n if (!this.enabled) {\n return;\n }\n if (this.targetElement().classList.contains(dropDownListClasses.disable)) {\n return;\n }\n var isFocused = false;\n if (this.preventFocus && Browser.isDevice) {\n this.inputWrapper.container.tabIndex = 1;\n this.inputWrapper.container.focus();\n this.preventFocus = false;\n isFocused = true;\n }\n if (!isFocused) {\n this.targetElement().focus();\n }\n addClass([this.inputWrapper.container], [dropDownListClasses.inputFocus]);\n this.onFocus();\n };\n /**\n * Moves the focus from the component if the component is already focused.\n * @returns void.\n */\n DropDownList.prototype.focusOut = function () {\n if (!this.enabled) {\n return;\n }\n this.isTyped = true;\n this.hidePopup();\n this.targetElement().blur();\n removeClass([this.inputWrapper.container], [dropDownListClasses.inputFocus]);\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers. Also it removes the attributes and classes.\n * @method destroy\n * @return {void}.\n */\n DropDownList.prototype.destroy = function () {\n var _this = this;\n this.isActive = false;\n this.hidePopup();\n this.unWireEvent();\n if (this.list) {\n this.unWireListEvents();\n }\n if (this.element && !this.element.classList.contains('e-' + this.getModuleName())) {\n return;\n }\n var attrArray = ['readonly', 'aria-disabled', 'aria-placeholder',\n 'placeholder', 'aria-owns', 'aria-labelledby', 'aria-haspopup', 'aria-expanded',\n 'aria-activedescendant', 'autocomplete', 'aria-readonly', 'autocorrect',\n 'autocapitalize', 'spellcheck', 'aria-autocomplete'];\n attrArray.forEach(function (value) {\n _this.inputElement.removeAttribute(value);\n });\n this.inputElement.setAttribute('tabindex', this.tabIndex);\n this.inputElement.classList.remove('e-input');\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n this.element.style.display = 'block';\n if (this.inputWrapper.container.parentElement.tagName === this.getNgDirective()) {\n detach(this.inputWrapper.container);\n }\n else {\n this.inputWrapper.container.parentElement.insertBefore(this.element, this.inputWrapper.container);\n detach(this.inputWrapper.container);\n }\n _super.prototype.destroy.call(this);\n };\n ;\n /**\n * Gets all the list items bound on this component.\n * @returns Element[].\n */\n DropDownList.prototype.getItems = function () {\n if (!this.list) {\n if (this.dataSource instanceof DataManager) {\n this.initRemoteRender = true;\n }\n this.renderList();\n }\n return this.ulElement ? _super.prototype.getItems.call(this) : null;\n };\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"cssClass\", void 0);\n __decorate([\n Property('100%')\n ], DropDownList.prototype, \"width\", void 0);\n __decorate([\n Property('300px')\n ], DropDownList.prototype, \"popupHeight\", void 0);\n __decorate([\n Property('100%')\n ], DropDownList.prototype, \"popupWidth\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"placeholder\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"filterBarPlaceholder\", void 0);\n __decorate([\n Property({})\n ], DropDownList.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"query\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"valueTemplate\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"headerTemplate\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"footerTemplate\", void 0);\n __decorate([\n Property(false)\n ], DropDownList.prototype, \"allowFiltering\", void 0);\n __decorate([\n Property(false)\n ], DropDownList.prototype, \"readonly\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"text\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"value\", void 0);\n __decorate([\n Property(null)\n ], DropDownList.prototype, \"index\", void 0);\n __decorate([\n Property('Never')\n ], DropDownList.prototype, \"floatLabelType\", void 0);\n __decorate([\n Property(false)\n ], DropDownList.prototype, \"showClearButton\", void 0);\n __decorate([\n Event()\n ], DropDownList.prototype, \"filtering\", void 0);\n __decorate([\n Event()\n ], DropDownList.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], DropDownList.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], DropDownList.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], DropDownList.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], DropDownList.prototype, \"blur\", void 0);\n __decorate([\n Event()\n ], DropDownList.prototype, \"focus\", void 0);\n DropDownList = __decorate([\n NotifyPropertyChanges\n ], DropDownList);\n return DropDownList;\n}(DropDownBase));\nexport { DropDownList };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n/// \nimport { EventHandler, Property, Event, addClass, Browser, removeClass, detach } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, NotifyPropertyChanges, getValue, setValue } from '@syncfusion/ej2-base';\nimport { DropDownList, dropDownListClasses } from '../drop-down-list/drop-down-list';\nimport { Search } from '../common/incremental-search';\nimport { createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';\n/* tslint:disable */\nimport { Input } from '@syncfusion/ej2-inputs';\n/* tslint:enable */\nvar SPINNER_CLASS = 'e-atc-spinner-icon';\ndropDownListClasses.root = 'e-combobox';\nvar inputObject = {\n container: null,\n buttons: []\n};\n/**\n * The ComboBox component allows the user to type a value or choose an option from the list of predefined options.\n * ```html\n * \n * Badminton \n * Basketball \n * Cricket \n * Football \n * Tennis \n * \n * ```\n * ```typescript\n * let games:ComboBox = new ComboBox();\n * games.appendTo(\"#list\");\n * ```\n */\nvar ComboBox = /** @class */ (function (_super) {\n __extends(ComboBox, _super);\n /**\n * *Constructor for creating the component\n */\n function ComboBox(options, element) {\n return _super.call(this, options, element) || this;\n }\n ;\n /**\n * Initialize the event handler\n * @private\n */\n ComboBox.prototype.preRender = function () {\n _super.prototype.preRender.call(this);\n };\n ComboBox.prototype.wireEvent = function () {\n if (this.getModuleName() === 'combobox') {\n EventHandler.add(this.inputWrapper.buttons[0], 'mousedown', this.preventBlur, this);\n EventHandler.add(this.inputWrapper.container, 'blur', this.onBlur, this);\n }\n if (!isNullOrUndefined(this.inputWrapper.buttons[0])) {\n EventHandler.add(this.inputWrapper.buttons[0], 'mousedown', this.dropDownClick, this);\n }\n EventHandler.add(this.inputElement, 'focus', this.targetFocus, this);\n if (!this.readonly) {\n EventHandler.add(this.inputElement, 'input', this.onInput, this);\n EventHandler.add(this.inputElement, 'keyup', this.onFilterUp, this);\n EventHandler.add(this.inputElement, 'keydown', this.onFilterDown, this);\n }\n this.bindCommonEvent();\n };\n ComboBox.prototype.preventBlur = function (e) {\n if ((!this.allowFiltering && document.activeElement !== this.inputElement &&\n !document.activeElement.classList.contains(dropDownListClasses.input) && Browser.isDevice || !Browser.isDevice)) {\n e.preventDefault();\n }\n };\n ComboBox.prototype.targetElement = function () {\n return this.inputElement;\n };\n ComboBox.prototype.setOldText = function (text) {\n Input.setValue(this.text, this.inputElement, this.floatLabelType, this.showClearButton);\n this.customValue();\n this.removeSelection();\n };\n ComboBox.prototype.setOldValue = function (value) {\n if (this.allowCustom) {\n this.valueMuteChange(this.value);\n }\n else {\n this.valueMuteChange(null);\n }\n this.removeSelection();\n this.setHiddenValue();\n };\n ComboBox.prototype.valueMuteChange = function (value) {\n var inputValue = isNullOrUndefined(value) ? null : value.toString();\n Input.setValue(inputValue, this.inputElement, this.floatLabelType, this.showClearButton);\n this.setProperties({ value: value, text: value, index: null }, true);\n this.activeIndex = this.index;\n var fields = this.fields;\n var dataItem = {};\n dataItem[fields.text] = isNullOrUndefined(value) ? null : value.toString();\n dataItem[fields.value] = isNullOrUndefined(value) ? null : value.toString();\n this.itemData = dataItem;\n this.item = null;\n if (this.previousValue !== this.value) {\n this.detachChangeEvent(null);\n }\n };\n ComboBox.prototype.updateValues = function () {\n if (!isNullOrUndefined(this.value)) {\n var li = this.getElementByValue(this.value);\n if (li) {\n this.setSelection(li, null);\n }\n else if (this.allowCustom) {\n this.valueMuteChange(this.value);\n }\n else {\n this.valueMuteChange(null);\n }\n }\n else if (this.text && isNullOrUndefined(this.value)) {\n var li = this.getElementByText(this.text);\n if (li) {\n this.setSelection(li, null);\n }\n else {\n Input.setValue(this.text, this.inputElement, this.floatLabelType, this.showClearButton);\n this.customValue();\n }\n }\n else {\n this.setSelection(this.liCollections[this.activeIndex], null);\n }\n this.setHiddenValue();\n Input.setValue(this.text, this.inputElement, this.floatLabelType, this.showClearButton);\n };\n ComboBox.prototype.getAriaAttributes = function () {\n var ariaAttributes = {\n 'aria-owns': this.element.id + '_options',\n 'role': 'combobox',\n 'aria-autocomplete': 'both',\n 'aria-labelledby': this.hiddenElement.id,\n 'aria-hasPopup': 'true',\n 'aria-expanded': 'false',\n 'aria-readonly': this.readonly.toString(),\n 'autocomplete': 'off',\n 'autocorrect': 'off',\n 'autocapitalize': 'off',\n 'spellcheck': 'false'\n };\n return ariaAttributes;\n };\n ComboBox.prototype.searchLists = function (e) {\n this.isTyped = true;\n if (this.isFiltering()) {\n _super.prototype.searchLists.call(this, e);\n if (this.filterInput.value.trim() === '') {\n this.setHoverList(this.ulElement.querySelector('.' + dropDownListClasses.li));\n }\n }\n else {\n if (this.ulElement && this.inputElement.value === '' && this.preventAutoFill) {\n this.setHoverList(this.ulElement.querySelector('.' + dropDownListClasses.li));\n }\n this.incrementalSearch(e);\n }\n };\n ComboBox.prototype.getNgDirective = function () {\n return 'EJS-COMBOBOX';\n };\n ComboBox.prototype.setSearchBox = function () {\n this.filterInput = this.inputElement;\n return (this.isFiltering() ? this.inputWrapper : inputObject);\n };\n ComboBox.prototype.onActionComplete = function (ulElement, list, e, isUpdated) {\n _super.prototype.onActionComplete.call(this, ulElement, list, e);\n if (this.isSelectCustom) {\n this.removeSelection();\n }\n if (!this.preventAutoFill && this.getModuleName() === 'combobox' && this.isTyped) {\n this.inlineSearch();\n }\n };\n ComboBox.prototype.getFocusElement = function () {\n var dataItem = this.isSelectCustom ? { text: '' } : this.getItemData();\n var selected = this.list.querySelector('.' + dropDownListClasses.selected);\n var isSelected = dataItem.text === this.inputElement.value && !isNullOrUndefined(selected);\n if (isSelected) {\n return selected;\n }\n if ((Browser.isDevice && !this.isDropDownClick || !Browser.isDevice) &&\n !isNullOrUndefined(this.liCollections) && this.liCollections.length > 0) {\n var inputValue = this.inputElement.value;\n var activeItem = Search(inputValue, this.liCollections, 'StartsWith', true);\n var activeElement = activeItem.item;\n if (!isNullOrUndefined(activeElement)) {\n var count = this.getIndexByValue(activeElement.getAttribute('data-value')) - 1;\n var height = parseInt(getComputedStyle(this.liCollections[0], null).getPropertyValue('height'), 10);\n if (!isNaN(height) && this.getModuleName() !== 'autocomplete') {\n this.removeFocus();\n var fixedHead = this.fields.groupBy ? this.liCollections[0].offsetHeight : 0;\n this.list.scrollTop = count * height + fixedHead;\n addClass([activeElement], dropDownListClasses.focus);\n }\n }\n else {\n if (this.isSelectCustom && this.inputElement.value.trim() !== '') {\n this.removeFocus();\n this.list.scrollTop = 0;\n }\n }\n return activeElement;\n }\n else {\n return null;\n }\n };\n ComboBox.prototype.setValue = function (e) {\n if (e && e.type === 'keydown' && e.action === 'enter') {\n this.removeFillSelection();\n }\n if (this.autofill && this.getModuleName() === 'combobox' && e && e.type === 'keydown' && e.action !== 'enter') {\n this.preventAutoFill = false;\n this.inlineSearch(e);\n return false;\n }\n else {\n return _super.prototype.setValue.call(this, e);\n }\n };\n /**\n * Shows the spinner loader.\n * @returns void.\n */\n ComboBox.prototype.showSpinner = function () {\n if (isNullOrUndefined(this.spinnerElement)) {\n this.spinnerElement = (this.getModuleName() === 'autocomplete') ? (this.inputWrapper.buttons[0] ||\n this.inputWrapper.clearButton ||\n Input.appendSpan('e-input-group-icon ' + SPINNER_CLASS, this.inputWrapper.container, this.createElement)) :\n (this.inputWrapper.buttons[0] || this.inputWrapper.clearButton);\n addClass([this.spinnerElement], dropDownListClasses.disableIcon);\n createSpinner({\n target: this.spinnerElement,\n width: Browser.isDevice ? '16px' : '14px'\n }, this.createElement);\n showSpinner(this.spinnerElement);\n }\n };\n /**\n * Hides the spinner loader.\n * @returns void.\n */\n ComboBox.prototype.hideSpinner = function () {\n if (!isNullOrUndefined(this.spinnerElement)) {\n hideSpinner(this.spinnerElement);\n removeClass([this.spinnerElement], dropDownListClasses.disableIcon);\n if (this.spinnerElement.classList.contains(SPINNER_CLASS)) {\n detach(this.spinnerElement);\n }\n else {\n this.spinnerElement.innerHTML = '';\n }\n this.spinnerElement = null;\n }\n };\n ComboBox.prototype.setAutoFill = function (activeElement, isHover) {\n if (!isHover) {\n this.setHoverList(activeElement);\n }\n if (this.autofill && !this.preventAutoFill) {\n var currentValue = this.getTextByValue(activeElement.getAttribute('data-value')).toString();\n var currentFillValue = this.getFormattedValue(activeElement.getAttribute('data-value'));\n if (this.getModuleName() === 'combobox') {\n if (!this.isSelected && this.previousValue !== currentFillValue) {\n this.updateSelectedItem(activeElement, null);\n this.isSelected = true;\n this.previousValue = this.getFormattedValue(activeElement.getAttribute('data-value'));\n }\n else {\n this.updateSelectedItem(activeElement, null, true);\n }\n }\n if (!this.isAndroidAutoFill(currentValue)) {\n this.setAutoFillSelection(currentValue);\n }\n }\n };\n ComboBox.prototype.isAndroidAutoFill = function (value) {\n if (Browser.isAndroid) {\n var currentPoints = this.getSelectionPoints();\n var prevEnd = this.prevSelectPoints.end;\n var curEnd = currentPoints.end;\n var prevStart = this.prevSelectPoints.start;\n var curStart = currentPoints.start;\n if (prevEnd !== 0 && ((prevEnd === value.length && prevStart === value.length) ||\n (prevStart > curStart && prevEnd > curEnd) || (prevEnd === curEnd && prevStart === curStart))) {\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return false;\n }\n };\n ComboBox.prototype.clear = function (e, property) {\n if (isNullOrUndefined(property) || property !== 'dataSource') {\n _super.prototype.clear.call(this, e);\n }\n };\n ComboBox.prototype.isSelectFocusItem = function (element) {\n return !isNullOrUndefined(element);\n };\n ComboBox.prototype.inlineSearch = function (e) {\n var isKeyNavigate = (e && (e.action === 'down' || e.action === 'up' ||\n e.action === 'home' || e.action === 'end' || e.action === 'pageUp' || e.action === 'pageDown'));\n var activeElement = isKeyNavigate ? this.liCollections[this.activeIndex] : this.getFocusElement();\n if (!isNullOrUndefined(activeElement)) {\n if (!isKeyNavigate) {\n var value = this.getFormattedValue(activeElement.getAttribute('data-value'));\n this.activeIndex = this.getIndexByValue(value);\n this.activeIndex = !isNullOrUndefined(this.activeIndex) ? this.activeIndex : null;\n }\n this.preventAutoFill = this.inputElement.value === '' ? false : this.preventAutoFill;\n this.setAutoFill(activeElement, isKeyNavigate);\n }\n else if (this.inputElement.value === '') {\n this.activeIndex = null;\n this.list.scrollTop = 0;\n var focusItem = this.list.querySelector('.' + dropDownListClasses.li);\n this.setHoverList(focusItem);\n }\n else {\n this.activeIndex = null;\n this.removeSelection();\n this.removeFocus();\n }\n };\n ComboBox.prototype.incrementalSearch = function (e) {\n this.showPopup();\n if (!isNullOrUndefined(this.listData)) {\n this.inlineSearch(e);\n e.preventDefault();\n }\n };\n ;\n ComboBox.prototype.setAutoFillSelection = function (currentValue) {\n var selection = this.getSelectionPoints();\n var value = this.inputElement.value.substr(0, selection.start);\n if (value && (value.toLowerCase() === currentValue.substr(0, selection.start).toLowerCase())) {\n var inputValue = value + currentValue.substr(value.length, currentValue.length);\n Input.setValue(inputValue, this.inputElement, this.floatLabelType, this.showClearButton);\n this.inputElement.setSelectionRange(selection.start, this.inputElement.value.length);\n }\n else {\n Input.setValue(currentValue, this.inputElement, this.floatLabelType, this.showClearButton);\n this.inputElement.setSelectionRange(0, this.inputElement.value.length);\n }\n };\n ;\n ComboBox.prototype.getValueByText = function (text) {\n return _super.prototype.getValueByText.call(this, text, true, this.ignoreAccent);\n };\n ComboBox.prototype.unWireEvent = function () {\n if (this.getModuleName() === 'combobox') {\n EventHandler.remove(this.inputWrapper.buttons[0], 'mousedown', this.preventBlur);\n EventHandler.remove(this.inputWrapper.container, 'blur', this.onBlur);\n }\n if (!isNullOrUndefined(this.inputWrapper.buttons[0])) {\n EventHandler.remove(this.inputWrapper.buttons[0], 'mousedown', this.dropDownClick);\n }\n EventHandler.remove(this.inputElement, 'focus', this.targetFocus);\n if (!this.readonly) {\n EventHandler.remove(this.inputElement, 'input', this.onInput);\n EventHandler.remove(this.inputElement, 'keyup', this.onFilterUp);\n EventHandler.remove(this.inputElement, 'keydown', this.onFilterDown);\n }\n this.unBindCommonEvent();\n };\n ComboBox.prototype.setSelection = function (li, e) {\n _super.prototype.setSelection.call(this, li, e);\n if (!isNullOrUndefined(li) && !this.autofill && !this.isDropDownClick) {\n this.removeFocus();\n }\n };\n ComboBox.prototype.selectCurrentItem = function (e) {\n var li;\n if (this.isPopupOpen) {\n li = this.list.querySelector('.' + dropDownListClasses.focus);\n if (li) {\n this.setSelection(li, e);\n this.isTyped = false;\n }\n if (this.isSelected) {\n this.isSelectCustom = false;\n this.onChangeEvent(e);\n }\n }\n if (e.action === 'enter' && this.inputElement.value.trim() === '') {\n this.clear(e);\n }\n else if (this.isTyped && !this.isSelected && isNullOrUndefined(li)) {\n this.customValue();\n }\n this.hidePopup();\n };\n ComboBox.prototype.setHoverList = function (li) {\n this.removeSelection();\n if (this.isValidLI(li) && !li.classList.contains(dropDownListClasses.selected)) {\n this.removeFocus();\n li.classList.add(dropDownListClasses.focus);\n }\n };\n ;\n ComboBox.prototype.targetFocus = function (e) {\n if (Browser.isDevice && !this.allowFiltering) {\n this.preventFocus = false;\n }\n this.onFocus();\n };\n ComboBox.prototype.dropDownClick = function (e) {\n e.preventDefault();\n if (Browser.isDevice && !this.allowFiltering) {\n this.preventFocus = true;\n }\n _super.prototype.dropDownClick.call(this, e);\n };\n ComboBox.prototype.customValue = function () {\n var value = this.getValueByText(this.inputElement.value);\n if (!this.allowCustom && this.inputElement.value !== '') {\n this.setProperties({ value: value });\n if (isNullOrUndefined(this.value)) {\n Input.setValue('', this.inputElement, this.floatLabelType, this.showClearButton);\n }\n }\n else if (this.inputElement.value.trim() !== '') {\n var previousValue = this.value;\n if (isNullOrUndefined(value)) {\n var value_1 = this.inputElement.value === '' ? null : this.inputElement.value;\n var fields = this.fields;\n var eventArgs = void 0;\n eventArgs = { text: value_1, item: {} };\n if (!this.initial) {\n this.trigger('customValueSpecifier', eventArgs);\n }\n var item = eventArgs.item;\n var dataItem = {};\n if (item && getValue(fields.text, item) && getValue(fields.value, item)) {\n dataItem = item;\n }\n else {\n setValue(fields.text, value_1, dataItem);\n setValue(fields.value, value_1, dataItem);\n }\n this.itemData = dataItem;\n var changeData = {\n text: getValue(fields.text, this.itemData),\n value: getValue(fields.value, this.itemData),\n index: null\n };\n this.setProperties(changeData, true);\n this.setSelection(null, null);\n this.isSelectCustom = true;\n }\n else {\n this.isSelectCustom = false;\n this.setProperties({ value: value });\n }\n if (previousValue !== this.value) {\n this.onChangeEvent(null);\n }\n }\n else if (this.allowCustom) {\n this.isSelectCustom = true;\n }\n };\n /**\n * Dynamically change the value of properties.\n * @private\n */\n ComboBox.prototype.onPropertyChanged = function (newProp, oldProp) {\n this.setUpdateInitial(['query', 'dataSource'], newProp);\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'readonly':\n Input.setReadonly(this.readonly, this.inputElement);\n if (this.readonly) {\n EventHandler.remove(this.inputElement, 'keyup', this.onFilterUp);\n EventHandler.remove(this.inputElement, 'keydown', this.onFilterDown);\n }\n else {\n EventHandler.add(this.inputElement, 'keyup', this.onFilterUp, this);\n EventHandler.add(this.inputElement, 'keydown', this.onFilterDown, this);\n }\n break;\n case 'allowFiltering':\n this.setSearchBox();\n if (this.isFiltering() && this.getModuleName() === 'combobox' && isNullOrUndefined(this.list)) {\n _super.prototype.renderList.call(this);\n }\n break;\n case 'allowCustom':\n break;\n default:\n var comboProps = void 0;\n comboProps = this.getPropObject(prop, newProp, oldProp);\n _super.prototype.onPropertyChanged.call(this, comboProps.newProperty, comboProps.oldProperty);\n break;\n }\n }\n };\n /**\n * To initialize the control rendering.\n * @private\n */\n ComboBox.prototype.render = function () {\n _super.prototype.render.call(this);\n this.setSearchBox();\n if (this.isFiltering() && this.getModuleName() === 'combobox' && isNullOrUndefined(this.list)) {\n _super.prototype.renderList.call(this);\n }\n };\n ;\n /**\n * Return the module name of this component.\n * @private\n */\n ComboBox.prototype.getModuleName = function () {\n return 'combobox';\n };\n /**\n * Hides the popup if it is in open state.\n * @returns void.\n */\n ComboBox.prototype.hidePopup = function () {\n var inputValue = this.inputElement.value === '' ? null : this.inputElement.value;\n if (!isNullOrUndefined(this.listData)) {\n var isEscape = this.isEscapeKey;\n if (this.isEscapeKey) {\n Input.setValue(this.typedString, this.inputElement, this.floatLabelType, this.showClearButton);\n this.isEscapeKey = false;\n }\n if (this.autofill) {\n this.removeFillSelection();\n }\n var dataItem = this.isSelectCustom ? { text: '' } : this.getItemData();\n var selected = this.list.querySelector('.' + dropDownListClasses.selected);\n if (dataItem.text === this.inputElement.value && !isNullOrUndefined(selected)) {\n if (this.isSelected) {\n this.onChangeEvent(null);\n this.isSelectCustom = false;\n }\n _super.prototype.hidePopup.call(this);\n return;\n }\n if (this.getModuleName() === 'combobox' && this.inputElement.value.trim() !== '') {\n var searchItem = Search(this.inputElement.value, this.liCollections, 'Equal', true);\n this.selectedLI = searchItem.item;\n if (isNullOrUndefined(searchItem.index)) {\n searchItem.index = Search(this.inputElement.value, this.liCollections, 'StartsWith', true).index;\n }\n this.activeIndex = searchItem.index;\n if (!isNullOrUndefined(this.selectedLI)) {\n this.updateSelectedItem(this.selectedLI, null, true);\n }\n else if (isEscape) {\n this.isSelectCustom = true;\n this.removeSelection();\n }\n }\n if (!this.isEscapeKey && this.isTyped && !this.isInteracted) {\n this.customValue();\n }\n }\n if (isNullOrUndefined(this.listData) && this.allowCustom && !isNullOrUndefined(inputValue) && inputValue !== this.value) {\n this.customValue();\n }\n _super.prototype.hidePopup.call(this);\n };\n /**\n * Sets the focus to the component for interaction.\n * @returns void.\n */\n ComboBox.prototype.focusIn = function () {\n if (!this.enabled) {\n return;\n }\n if (Browser.isDevice && !this.allowFiltering) {\n this.preventFocus = true;\n }\n _super.prototype.focusIn.call(this);\n };\n __decorate([\n Property(false)\n ], ComboBox.prototype, \"autofill\", void 0);\n __decorate([\n Property(true)\n ], ComboBox.prototype, \"allowCustom\", void 0);\n __decorate([\n Property({})\n ], ComboBox.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property(false)\n ], ComboBox.prototype, \"allowFiltering\", void 0);\n __decorate([\n Property(null)\n ], ComboBox.prototype, \"query\", void 0);\n __decorate([\n Property(null)\n ], ComboBox.prototype, \"index\", void 0);\n __decorate([\n Property(true)\n ], ComboBox.prototype, \"showClearButton\", void 0);\n __decorate([\n Event()\n ], ComboBox.prototype, \"customValueSpecifier\", void 0);\n __decorate([\n Event()\n ], ComboBox.prototype, \"filtering\", void 0);\n __decorate([\n Property(null)\n ], ComboBox.prototype, \"valueTemplate\", void 0);\n __decorate([\n Property('Never')\n ], ComboBox.prototype, \"floatLabelType\", void 0);\n __decorate([\n Property(null)\n ], ComboBox.prototype, \"filterBarPlaceholder\", void 0);\n ComboBox = __decorate([\n NotifyPropertyChanges\n ], ComboBox);\n return ComboBox;\n}(DropDownList));\nexport { ComboBox };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n/// \nimport { Property, EventHandler, isNullOrUndefined, detach } from '@syncfusion/ej2-base';\nimport { Event, Complex } from '@syncfusion/ej2-base';\nimport { removeClass, attributes, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { dropDownListClasses } from '../drop-down-list/drop-down-list';\nimport { ComboBox } from '../combo-box/combo-box';\nimport { highlightSearch } from '../common/highlight-search';\nimport { Search } from '../common/incremental-search';\nimport { FieldSettings } from '../drop-down-base/drop-down-base';\n/* tslint:disable */\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { DataManager, Query } from '@syncfusion/ej2-data';\n/* tslint:enable */\ndropDownListClasses.root = 'e-autocomplete';\ndropDownListClasses.icon = 'e-input-group-icon e-ddl-icon e-search-icon';\n/**\n * The AutoComplete component provides the matched suggestion list when type into the input,\n * from which the user can select one.\n * ```html\n * \n * ```\n * ```typescript\n * let atcObj:AutoComplete = new AutoComplete();\n * atcObj.appendTo(\"#list\");\n * ```\n */\nvar AutoComplete = /** @class */ (function (_super) {\n __extends(AutoComplete, _super);\n /**\n * * Constructor for creating the widget\n */\n function AutoComplete(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.isFiltered = false;\n return _this;\n }\n ;\n /**\n * Initialize the event handler\n * @private\n */\n AutoComplete.prototype.preRender = function () {\n _super.prototype.preRender.call(this);\n };\n AutoComplete.prototype.getNgDirective = function () {\n return 'EJS-AUTOCOMPLETE';\n };\n AutoComplete.prototype.getQuery = function (query) {\n var filterQuery = query ? query.clone() : this.query ? this.query.clone() : new Query();\n var filterType = (this.queryString === '' && !isNullOrUndefined(this.value)) ? 'equal' : this.filterType;\n var queryString = (this.queryString === '' && !isNullOrUndefined(this.value)) ? this.value : this.queryString;\n if (this.isFiltered) {\n return filterQuery;\n }\n if (this.queryString !== null) {\n var dataType = this.typeOfData(this.dataSource).typeof;\n if (!(this.dataSource instanceof DataManager) && dataType === 'string' || dataType === 'number') {\n filterQuery.where('', filterType, queryString, this.ignoreCase, this.ignoreAccent);\n }\n else {\n var mapping = !isNullOrUndefined(this.fields.value) ? this.fields.value : '';\n filterQuery.where(mapping, filterType, queryString, this.ignoreCase, this.ignoreAccent);\n }\n }\n if (!isNullOrUndefined(this.suggestionCount)) {\n filterQuery.take(this.suggestionCount);\n }\n return filterQuery;\n };\n AutoComplete.prototype.searchLists = function (e) {\n var _this = this;\n this.isTyped = true;\n this.isSelectCustom = false;\n if (isNullOrUndefined(this.list)) {\n _super.prototype.renderList.call(this, true);\n }\n var isDownUpKey = e.keyCode === 40 || e.keyCode === 38;\n this.queryString = this.filterInput.value;\n if (isDownUpKey) {\n this.queryString = this.queryString === '' ? null : this.queryString;\n this.beforePopupOpen = true;\n this.resetList(this.dataSource, this.fields);\n return;\n }\n this.isSelected = false;\n this.activeIndex = null;\n var eventArgs = {\n preventDefaultAction: false,\n text: this.filterInput.value,\n updateData: function (dataSource, query, fields) {\n if (eventArgs.cancel) {\n return;\n }\n _this.isFiltered = true;\n _this.filterAction(dataSource, query, fields);\n },\n cancel: false\n };\n this.trigger('filtering', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n if (!this.isFiltered && !eventArgs.preventDefaultAction) {\n this.filterAction(this.dataSource, null, this.fields);\n }\n };\n AutoComplete.prototype.filterAction = function (dataSource, query, fields) {\n this.beforePopupOpen = true;\n if (this.queryString !== '' && (this.queryString.length >= this.minLength || this.isFiltered)) {\n this.resetList(dataSource, fields, query);\n }\n else {\n this.hidePopup();\n }\n };\n AutoComplete.prototype.clear = function (e, property) {\n if (isNullOrUndefined(property) || property !== 'dataSource') {\n _super.prototype.clear.call(this, e);\n }\n if (this.beforePopupOpen) {\n this.hidePopup();\n }\n };\n AutoComplete.prototype.onActionComplete = function (ulElement, list, e, isUpdated) {\n this.fixedHeaderElement = null;\n _super.prototype.onActionComplete.call(this, ulElement, list, e);\n var item = this.list.querySelector('.' + dropDownListClasses.li);\n if (!isNullOrUndefined(item)) {\n removeClass([item], dropDownListClasses.focus);\n }\n this.postBackAction();\n };\n AutoComplete.prototype.postBackAction = function () {\n if (this.autofill && !isNullOrUndefined(this.liCollections[0])) {\n var items = [this.liCollections[0]];\n var searchItem = Search(this.inputElement.value, items, 'StartsWith', this.ignoreCase);\n if (!isNullOrUndefined(searchItem.item)) {\n _super.prototype.setAutoFill.call(this, this.liCollections[0], true);\n }\n }\n };\n AutoComplete.prototype.setSelection = function (li, e) {\n if (!this.isValidLI(li)) {\n return;\n }\n if (!isNullOrUndefined(e) && e.type === 'keydown' && e.action !== 'enter' && this.isValidLI(li)) {\n var value = this.getFormattedValue(li.getAttribute('data-value'));\n this.activeIndex = this.getIndexByValue(value);\n this.setHoverList(li);\n this.selectedLI = li;\n this.setScrollPosition(e);\n if (this.autofill) {\n this.preventAutoFill = false;\n _super.prototype.setAutoFill.call(this, li);\n }\n attributes(this.inputElement, { 'aria-activedescendant': this.selectedLI ? this.selectedLI.id : null });\n }\n else {\n _super.prototype.setSelection.call(this, li, e);\n }\n };\n AutoComplete.prototype.listOption = function (dataSource, fieldsSettings) {\n var _this = this;\n var fields = _super.prototype.listOption.call(this, dataSource, fieldsSettings);\n if (isNullOrUndefined(fields.itemCreated)) {\n fields.itemCreated = function (e) {\n if (_this.highlight) {\n highlightSearch(e.item, _this.queryString, _this.ignoreCase, _this.filterType);\n }\n };\n }\n else {\n var itemCreated_1 = fields.itemCreated;\n fields.itemCreated = function (e) {\n if (_this.highlight) {\n highlightSearch(e.item, _this.queryString, _this.ignoreCase, _this.filterType);\n }\n itemCreated_1.apply(_this, [e]);\n };\n }\n return fields;\n };\n ;\n AutoComplete.prototype.isFiltering = function () {\n return true;\n };\n AutoComplete.prototype.renderPopup = function () {\n this.list.scrollTop = 0;\n _super.prototype.renderPopup.call(this);\n };\n AutoComplete.prototype.isEditTextBox = function () {\n return true && this.inputElement.value.trim() !== '';\n };\n AutoComplete.prototype.isPopupButton = function () {\n return this.showPopupButton;\n };\n AutoComplete.prototype.isSelectFocusItem = function (element) {\n return false;\n };\n /**\n * Search the entered text and show it in the suggestion list if available.\n * @returns void.\n */\n AutoComplete.prototype.showPopup = function () {\n if (!this.enabled) {\n return;\n }\n if (this.beforePopupOpen) {\n this.refreshPopup();\n return;\n }\n this.beforePopupOpen = true;\n this.preventAutoFill = true;\n if (isNullOrUndefined(this.list)) {\n this.renderList();\n }\n else {\n this.resetList(this.dataSource, this.fields);\n }\n };\n /**\n * Hides the popup if it is in open state.\n * @returns void.\n */\n AutoComplete.prototype.hidePopup = function () {\n _super.prototype.hidePopup.call(this);\n this.activeIndex = -1;\n };\n /**\n * Dynamically change the value of properties.\n * @private\n */\n AutoComplete.prototype.onPropertyChanged = function (newProp, oldProp) {\n this.setUpdateInitial(['query', 'dataSource'], newProp);\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'showPopupButton':\n if (this.showPopupButton) {\n var button = Input.appendSpan(dropDownListClasses.icon, this.inputWrapper.container, this.createElement);\n this.inputWrapper.buttons[0] = button;\n EventHandler.add(this.inputWrapper.buttons[0], 'click', this.dropDownClick, this);\n }\n else {\n detach(this.inputWrapper.buttons[0]);\n this.inputWrapper.buttons[0] = null;\n }\n break;\n default:\n var atcProps = void 0;\n atcProps = this.getPropObject(prop, newProp, oldProp);\n _super.prototype.onPropertyChanged.call(this, atcProps.newProperty, atcProps.oldProperty);\n break;\n }\n }\n };\n /**\n * Return the module name of this component.\n * @private\n */\n AutoComplete.prototype.getModuleName = function () {\n return 'autocomplete';\n };\n /**\n * To initialize the control rendering\n * @private\n */\n AutoComplete.prototype.render = function () {\n _super.prototype.render.call(this);\n };\n ;\n __decorate([\n Complex({ value: null, iconCss: null, groupBy: null }, FieldSettings)\n ], AutoComplete.prototype, \"fields\", void 0);\n __decorate([\n Property(true)\n ], AutoComplete.prototype, \"ignoreCase\", void 0);\n __decorate([\n Property(false)\n ], AutoComplete.prototype, \"showPopupButton\", void 0);\n __decorate([\n Property(false)\n ], AutoComplete.prototype, \"highlight\", void 0);\n __decorate([\n Property(20)\n ], AutoComplete.prototype, \"suggestionCount\", void 0);\n __decorate([\n Property({})\n ], AutoComplete.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property(null)\n ], AutoComplete.prototype, \"query\", void 0);\n __decorate([\n Property(1)\n ], AutoComplete.prototype, \"minLength\", void 0);\n __decorate([\n Property('Contains')\n ], AutoComplete.prototype, \"filterType\", void 0);\n __decorate([\n Event()\n ], AutoComplete.prototype, \"filtering\", void 0);\n __decorate([\n Property(null)\n ], AutoComplete.prototype, \"index\", void 0);\n __decorate([\n Property('Never')\n ], AutoComplete.prototype, \"floatLabelType\", void 0);\n __decorate([\n Property(null)\n ], AutoComplete.prototype, \"valueTemplate\", void 0);\n __decorate([\n Property(null)\n ], AutoComplete.prototype, \"filterBarPlaceholder\", void 0);\n __decorate([\n Property(false)\n ], AutoComplete.prototype, \"allowFiltering\", void 0);\n __decorate([\n Property(null)\n ], AutoComplete.prototype, \"text\", void 0);\n AutoComplete = __decorate([\n NotifyPropertyChanges\n ], AutoComplete);\n return AutoComplete;\n}(ComboBox));\nexport { AutoComplete };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n/// \nimport { DropDownBase, dropDownBaseClasses } from '../drop-down-base/drop-down-base';\nimport { Popup, createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';\nimport { attributes, setValue } from '@syncfusion/ej2-base';\nimport { NotifyPropertyChanges, extend } from '@syncfusion/ej2-base';\nimport { EventHandler, Property, Event, compile, L10n } from '@syncfusion/ej2-base';\nimport { Animation, Browser, prepend } from '@syncfusion/ej2-base';\nimport { Search } from '../common/incremental-search';\nimport { append, addClass, removeClass, setStyleAttribute, closest, detach, remove } from '@syncfusion/ej2-base';\nimport { getUniqueID, formatUnit, isNullOrUndefined, isUndefined } from '@syncfusion/ej2-base';\n/* tslint:disable */\nimport { DataManager, Query, Predicate } from '@syncfusion/ej2-data';\nimport { createFloatLabel, removeFloating, floatLabelFocus, floatLabelBlur } from './float-label';\n/* tslint:enable */\nvar FOCUS = 'e-input-focus';\nvar DISABLED = 'e-disabled';\nvar OVER_ALL_WRAPPER = 'e-multiselect e-input-group';\nvar ELEMENT_WRAPPER = 'e-multi-select-wrapper';\nvar ELEMENT_MOBILE_WRAPPER = 'e-mob-wrapper';\nvar HIDE_LIST = 'e-hide-listitem';\nvar DELIMITER_VIEW = 'e-delim-view';\nvar CHIP_WRAPPER = 'e-chips-collection';\nvar CHIP = 'e-chips';\nvar CHIP_CONTENT = 'e-chipcontent';\nvar CHIP_CLOSE = 'e-chips-close';\nvar CHIP_SELECTED = 'e-chip-selected';\nvar SEARCHBOX_WRAPPER = 'e-searcher';\nvar DELIMITER_VIEW_WRAPPER = 'e-delimiter';\nvar ZERO_SIZE = 'e-zero-size';\nvar REMAIN_WRAPPER = 'e-remain';\nvar CLOSEICON_CLASS = 'e-chips-close e-close-hooker';\nvar DELIMITER_WRAPPER = 'e-delim-values';\nvar POPUP_WRAPPER = 'e-ddl e-popup e-multi-select-list-wrapper';\nvar INPUT_ELEMENT = 'e-dropdownbase';\nvar RTL_CLASS = 'e-rtl';\nvar CLOSE_ICON_HIDE = 'e-close-icon-hide';\nvar MOBILE_CHIP = 'e-mob-chip';\nvar FOOTER = 'e-ddl-footer';\nvar HEADER = 'e-ddl-header';\nvar DISABLE_ICON = 'e-ddl-disable-icon';\nvar SPINNER_CLASS = 'e-ms-spinner-icon';\nvar HIDDEN_ELEMENT = 'e-multi-hidden';\nvar destroy = 'destroy';\nvar dropdownIcon = 'e-input-group-icon e-ddl-icon';\nvar iconAnimation = 'e-icon-anim';\n/**\n * The Multiselect allows the user to pick a more than one value from list of predefined values.\n * ```html\n * \n * Badminton \n * Basketball \n * Cricket \n * Football \n * Tennis \n * \n * ```\n * ```typescript\n * \n * ```\n */\nvar MultiSelect = /** @class */ (function (_super) {\n __extends(MultiSelect, _super);\n /**\n * Constructor for creating the DropDownList widget.\n */\n function MultiSelect(option, element) {\n var _this = _super.call(this, option, element) || this;\n _this.isValidKey = false;\n _this.selectAllEventData = [];\n _this.selectAllEventEle = [];\n _this.scrollFocusStatus = false;\n _this.keyDownStatus = false;\n return _this;\n }\n ;\n MultiSelect.prototype.enableRTL = function (state) {\n if (state) {\n this.overAllWrapper.classList.add(RTL_CLASS);\n }\n else {\n this.overAllWrapper.classList.remove(RTL_CLASS);\n }\n if (this.popupObj) {\n this.popupObj.enableRtl = state;\n this.popupObj.dataBind();\n }\n };\n MultiSelect.prototype.requiredModules = function () {\n var modules = [];\n if (this.mode === 'CheckBox') {\n this.allowCustomValue = false;\n this.hideSelectedItem = false;\n this.closePopupOnSelect = false;\n this.allowFiltering = true;\n modules.push({\n member: 'CheckBoxSelection',\n args: [this]\n });\n }\n return modules;\n };\n MultiSelect.prototype.updateHTMLAttribute = function () {\n if (Object.keys(this.htmlAttributes).length) {\n for (var _i = 0, _a = Object.keys(this.htmlAttributes); _i < _a.length; _i++) {\n var htmlAttr = _a[_i];\n switch (htmlAttr) {\n case 'class':\n this.overAllWrapper.classList.add(this.htmlAttributes[htmlAttr]);\n this.popupWrapper.classList.add(this.htmlAttributes[htmlAttr]);\n break;\n case 'disabled':\n this.enable(false);\n break;\n case 'placeholder':\n this.inputElement.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n break;\n default:\n var defaultAttr = ['id'];\n var validateAttr = ['name', 'required', 'aria-required', 'form'];\n var containerAttr = ['title', 'role', 'style', 'class'];\n if (defaultAttr.indexOf(htmlAttr) > -1) {\n this.element.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n }\n else if (validateAttr.indexOf(htmlAttr) > -1) {\n this.hiddenElement.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n }\n else if (containerAttr.indexOf(htmlAttr) > -1) {\n this.overAllWrapper.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n }\n else {\n this.inputElement.setAttribute(htmlAttr, this.htmlAttributes[htmlAttr]);\n }\n break;\n }\n }\n }\n };\n MultiSelect.prototype.updateReadonly = function (state) {\n if (state || this.mode === 'CheckBox') {\n this.inputElement.setAttribute('readonly', 'true');\n }\n else {\n this.inputElement.removeAttribute('readonly');\n }\n };\n MultiSelect.prototype.updateClearButton = function (state) {\n if (state) {\n if (this.overAllClear.parentNode) {\n this.overAllClear.style.display = '';\n }\n else {\n this.componentWrapper.appendChild(this.overAllClear);\n }\n this.componentWrapper.classList.remove(CLOSE_ICON_HIDE);\n }\n else {\n this.overAllClear.style.display = 'none';\n this.componentWrapper.classList.add(CLOSE_ICON_HIDE);\n }\n };\n MultiSelect.prototype.updateCssClass = function () {\n if (this.cssClass) {\n this.popupWrapper.classList.add(this.cssClass);\n this.overAllWrapper.classList.add(this.cssClass);\n }\n };\n MultiSelect.prototype.onPopupShown = function () {\n if (Browser.isDevice && (this.mode === 'CheckBox' && this.allowFiltering)) {\n var proxy_1 = this;\n window.onpopstate = function () {\n proxy_1.hidePopup();\n };\n history.pushState({}, '');\n }\n var animModel = { name: 'FadeIn', duration: 100 };\n var eventArgs = { popup: this.popupObj, cancel: false, animation: animModel };\n this.trigger('open', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.focusAtFirstListItem();\n document.body.appendChild(this.popupObj.element);\n if (this.mode === 'CheckBox') {\n addClass([this.overAllWrapper], [iconAnimation]);\n }\n this.popupObj.show(eventArgs.animation, (this.zIndex === 1000) ? this.element : null);\n attributes(this.inputElement, { 'aria-expanded': 'true' });\n if (!this.isFirstClick) {\n var ulElement = this.list.querySelector('ul');\n if (ulElement) {\n this.mainList = ulElement.cloneNode ? ulElement.cloneNode(true) : ulElement;\n }\n this.isFirstClick = true;\n }\n if ((this.allowFiltering || this.allowCustomValue) && this.mainList && this.listData) {\n if (this.value && this.value.length) {\n this.refreshSelection();\n }\n }\n this.notify('reOrder', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', e: this });\n };\n MultiSelect.prototype.focusAtFirstListItem = function () {\n if (this.ulElement && this.ulElement.querySelector('li.'\n + dropDownBaseClasses.li)) {\n var element = void 0;\n if (this.mode === 'CheckBox') {\n element = this.list.querySelector('li.'\n + dropDownBaseClasses.li + ':not(.'\n + HIDE_LIST + ')');\n }\n else {\n element = this.ulElement.querySelector('li.'\n + dropDownBaseClasses.li + ':not(.'\n + HIDE_LIST + ')');\n }\n if (element !== null) {\n this.removeFocus();\n this.addListFocus(element);\n }\n }\n };\n MultiSelect.prototype.focusAtLastListItem = function (data) {\n var activeElement;\n if (data) {\n activeElement = Search(data, this.liCollections, 'StartsWith', this.ignoreCase);\n }\n else {\n if (this.value && this.value.length) {\n Search(this.value[this.value.length - 1], this.liCollections, 'StartsWith', this.ignoreCase);\n }\n else {\n activeElement = null;\n }\n }\n if (activeElement && activeElement.item !== null) {\n this.addListFocus(activeElement.item);\n this.scrollBottom(activeElement.item, activeElement.index);\n }\n };\n MultiSelect.prototype.getAriaAttributes = function () {\n var ariaAttributes = {\n 'aria-disabled': 'false',\n 'aria-owns': this.element.id + '_options',\n 'role': 'listbox',\n 'aria-multiselectable': 'true',\n 'aria-activedescendant': 'null',\n 'aria-haspopup': 'true',\n 'aria-expanded': 'false'\n };\n return ariaAttributes;\n };\n MultiSelect.prototype.updateListARIA = function () {\n attributes(this.ulElement, { 'id': this.element.id + '_options', 'role': 'listbox', 'aria-hidden': 'false' });\n var disableStatus = (this.inputElement.disabled) ? true : false;\n attributes(this.inputElement, this.getAriaAttributes());\n if (disableStatus) {\n attributes(this.inputElement, { 'aria-disabled': 'true' });\n }\n };\n MultiSelect.prototype.removelastSelection = function (e) {\n var elements;\n elements = this.chipCollectionWrapper.querySelectorAll('span.' + CHIP);\n var value = elements[elements.length - 1].getAttribute('data-value');\n if (!isNullOrUndefined(this.value)) {\n this.tempValues = this.value.slice();\n }\n this.removeValue(value, e);\n this.removeChipSelection();\n this.updateDelimeter(this.delimiterChar);\n this.makeTextBoxEmpty();\n if (this.mainList && this.listData) {\n var list = this.mainList.cloneNode ? this.mainList.cloneNode(true) : this.mainList;\n this.onActionComplete(list, this.mainData);\n this.refreshSelection();\n }\n //this.focusAtLastListItem(value);\n };\n MultiSelect.prototype.onActionFailure = function (e) {\n _super.prototype.onActionFailure.call(this, e);\n this.renderPopup();\n this.onPopupShown();\n };\n MultiSelect.prototype.targetElement = function () {\n this.targetInputElement = this.inputElement;\n if (this.mode === 'CheckBox') {\n this.notify('targetElement', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox' });\n }\n return this.targetInputElement.value;\n };\n MultiSelect.prototype.getForQuery = function (valuecheck) {\n var predicate;\n var field = isNullOrUndefined(this.fields.value) ? this.fields.text : this.fields.value;\n for (var i = 0; i < valuecheck.length; i++) {\n if (i === 0) {\n predicate = new Predicate(field, 'equal', valuecheck[i]);\n }\n else {\n predicate = predicate.or(field, 'equal', valuecheck[i]);\n }\n }\n return new Query().where(predicate);\n };\n MultiSelect.prototype.onActionComplete = function (ulElement, list, e, isUpdated) {\n _super.prototype.onActionComplete.call(this, ulElement, list, e);\n var proxy = this;\n var valuecheck = [];\n if (!isNullOrUndefined(this.value)) {\n for (var i = 0; i < this.value.length; i++) {\n var checkEle = ulElement.querySelector('li[data-value=\"' + proxy.value[i] + '\"]');\n if (!checkEle) {\n valuecheck.push(proxy.value[i]);\n }\n }\n }\n if (valuecheck.length > 0 && this.dataSource instanceof DataManager && !isNullOrUndefined(this.value)) {\n this.dataSource.executeQuery(this.getForQuery(valuecheck)).then(function (e) {\n proxy.addItem(e.result, list.length);\n proxy.updateActionList(ulElement, list, e);\n });\n }\n else {\n this.updateActionList(ulElement, list, e);\n }\n };\n MultiSelect.prototype.updateActionList = function (ulElement, list, e, isUpdated) {\n if (this.mode === 'CheckBox' && this.showSelectAll) {\n this.notify('selectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox' });\n }\n if (!this.mainList && !this.mainData) {\n this.mainList = ulElement.cloneNode ? ulElement.cloneNode(true) : ulElement;\n this.mainData = list;\n this.mainListCollection = this.liCollections;\n }\n else if (!isNullOrUndefined(this.mainData) && this.mainData.length === 0) {\n this.mainData = list;\n }\n if ((this.remoteCustomValue || list.length <= 0) && this.allowCustomValue && this.inputFocus && this.allowFiltering) {\n this.checkForCustomValue(this.tempQuery, this.fields);\n return;\n }\n if (this.value && this.value.length && this.inputElement.value !== '') {\n this.refreshSelection();\n }\n this.updateListARIA();\n this.unwireListEvents();\n this.wireListEvents();\n if (!isNullOrUndefined(this.setInitialValue)) {\n this.setInitialValue();\n }\n if (!isNullOrUndefined(this.selectAllAction)) {\n this.selectAllAction();\n }\n if (this.setDynValue) {\n this.initialValueUpdate();\n this.initialUpdate();\n this.refreshPlaceHolder();\n this.updateValueState(null, this.value, null);\n }\n this.renderPopup();\n if (this.beforePopupOpen) {\n this.beforePopupOpen = false;\n this.onPopupShown();\n }\n };\n MultiSelect.prototype.refreshSelection = function () {\n var value;\n var element;\n var className = this.hideSelectedItem ?\n HIDE_LIST :\n dropDownBaseClasses.selected;\n if (!isNullOrUndefined(this.value)) {\n for (var index = 0; !isNullOrUndefined(this.value[index]); index++) {\n value = this.value[index];\n element = this.list.querySelector('li[data-value=\"' + value + '\"]');\n if (element) {\n addClass([element], className);\n if (this.hideSelectedItem && element.previousSibling\n && element.previousElementSibling.classList.contains(dropDownBaseClasses.group)\n && (!element.nextElementSibling ||\n element.nextElementSibling.classList.contains(dropDownBaseClasses.group))) {\n addClass([element.previousElementSibling], className);\n }\n if (this.hideSelectedItem && this.fields.groupBy && !element.previousElementSibling.classList.contains(HIDE_LIST)) {\n this.hideGroupItem(value);\n }\n if (this.hideSelectedItem && element.classList.contains(dropDownBaseClasses.focus)) {\n removeClass([element], dropDownBaseClasses.focus);\n var listEle = element.parentElement.querySelectorAll('.' +\n dropDownBaseClasses.li + ':not(.' + HIDE_LIST + ')');\n if (listEle.length > 0) {\n addClass([listEle[0]], dropDownBaseClasses.focus);\n }\n else {\n this.ulElement = this.ulElement.cloneNode ? this.ulElement.cloneNode(true) : this.ulElement;\n this.l10nUpdate();\n addClass([this.list], dropDownBaseClasses.noData);\n }\n }\n element.setAttribute('aria-selected', 'true');\n if (this.mode === 'CheckBox' && element.classList.contains('e-active')) {\n var ariaValue = element.firstElementChild.getAttribute('aria-checked');\n if (isNullOrUndefined(ariaValue) || ariaValue === 'false') {\n var args = {\n module: 'CheckBoxSelection',\n enable: this.mode === 'CheckBox',\n li: element,\n e: null\n };\n this.notify('updatelist', args);\n }\n }\n }\n }\n }\n this.checkSelectAll();\n this.checkMaxSelection();\n };\n MultiSelect.prototype.hideGroupItem = function (value) {\n var element;\n var element1;\n var className = this.hideSelectedItem ?\n HIDE_LIST :\n dropDownBaseClasses.selected;\n element1 = element = this.ulElement.querySelector('li[data-value=\"' + value + '\"]');\n var i = 0;\n var j = 0;\n var temp = true;\n var temp1 = true;\n do {\n if (element && element.previousElementSibling\n && (!element.previousElementSibling.classList.contains(HIDE_LIST) &&\n element.previousElementSibling.classList.contains(dropDownBaseClasses.li))) {\n temp = false;\n }\n if (!temp || !element || (element.previousElementSibling\n && element.previousElementSibling.classList.contains(dropDownBaseClasses.group))) {\n i = 10;\n }\n else {\n element = element.previousElementSibling;\n }\n if (element1 && element1.nextElementSibling\n && (!element1.nextElementSibling.classList.contains(HIDE_LIST) &&\n element1.nextElementSibling.classList.contains(dropDownBaseClasses.li))) {\n temp1 = false;\n }\n if (!temp1 || !element1 || (element1.nextElementSibling\n && element1.nextElementSibling.classList.contains(dropDownBaseClasses.group))) {\n j = 10;\n }\n else {\n element1 = element1.nextElementSibling;\n }\n } while (i < 10 || j < 10);\n if (temp && temp1 && !element.previousElementSibling.classList.contains(HIDE_LIST)) {\n addClass([element.previousElementSibling], className);\n }\n else if (temp && temp1 && element.previousElementSibling.classList.contains(HIDE_LIST)) {\n removeClass([element.previousElementSibling], className);\n }\n };\n MultiSelect.prototype.checkSelectAll = function () {\n var searchCount = this.list.querySelectorAll('li.' + dropDownBaseClasses.li).length;\n var searchActiveCount = this.list.querySelectorAll('li.' + dropDownBaseClasses.selected).length;\n if ((searchCount === searchActiveCount) && (this.mode === 'CheckBox' && this.showSelectAll)) {\n this.notify('checkSelectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', value: 'check' });\n }\n if ((searchCount !== searchActiveCount) && (this.mode === 'CheckBox' && this.showSelectAll)) {\n this.notify('checkSelectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', value: 'uncheck' });\n }\n };\n MultiSelect.prototype.openClick = function (e) {\n if (!this.openOnClick && this.mode !== 'CheckBox') {\n if (this.targetElement() !== '') {\n this.showPopup();\n }\n else {\n this.hidePopup();\n }\n }\n else if (!this.openOnClick && this.mode === 'CheckBox' && !this.isPopupOpen()) {\n this.showPopup();\n }\n };\n MultiSelect.prototype.KeyUp = function (e) {\n var _this = this;\n if (this.mode === 'CheckBox' && !this.openOnClick) {\n var char = String.fromCharCode(e.keyCode);\n var isWordCharacter = char.match(/\\w/);\n if (!isNullOrUndefined(isWordCharacter)) {\n this.isValidKey = true;\n }\n }\n this.isValidKey = (this.isPopupOpen() && e.keyCode === 8) || this.isValidKey;\n if (this.isValidKey) {\n this.isValidKey = false;\n this.expandTextbox();\n this.showOverAllClear();\n switch (e.keyCode) {\n default:\n if (!this.isPopupOpen() && this.openOnClick) {\n this.showPopup();\n }\n this.openClick(e);\n if (this.checkTextLength() && !this.allowFiltering && (e.keyCode !== 8)) {\n this.focusAtFirstListItem();\n }\n else {\n var text = this.targetElement();\n this.keyCode = e.keyCode;\n if (this.allowFiltering) {\n var eventArgs_1 = {\n preventDefaultAction: false,\n text: this.targetElement(),\n updateData: function (dataSource, query, fields) {\n if (eventArgs_1.cancel) {\n return;\n }\n _this.isFiltered = true;\n _this.remoteFilterAction = true;\n _this.dataUpdater(dataSource, query, fields);\n },\n event: e,\n cancel: false\n };\n this.trigger('filtering', eventArgs_1);\n if (eventArgs_1.cancel) {\n return;\n }\n if (!this.isFiltered && !eventArgs_1.preventDefaultAction) {\n this.filterAction = true;\n this.dataUpdater(this.dataSource, null, this.fields);\n }\n }\n else if (this.allowCustomValue) {\n var query = new Query();\n query = (text !== '') ? query.where(this.fields.text, 'startswith', text, this.ignoreCase, this.ignoreAccent) : query;\n this.dataUpdater(this.mainData, query, this.fields);\n break;\n }\n else {\n var liCollections = void 0;\n liCollections = this.list.querySelectorAll('li.' + dropDownBaseClasses.li + ':not(.e-hide-listitem)');\n var activeElement = Search(this.targetElement(), liCollections, 'StartsWith', this.ignoreCase);\n if (activeElement && activeElement.item !== null) {\n this.addListFocus(activeElement.item);\n this.list.scrollTop =\n activeElement.item.offsetHeight * activeElement.index;\n }\n else if (this.targetElement() !== '') {\n this.removeFocus();\n }\n else {\n this.focusAtFirstListItem();\n }\n }\n }\n }\n }\n };\n MultiSelect.prototype.getQuery = function (query) {\n var filterQuery = query ? query.clone() : this.query ? this.query.clone() : new Query();\n if (this.filterAction) {\n if (this.targetElement() !== null) {\n var dataType = this.typeOfData(this.dataSource).typeof;\n if (!(this.dataSource instanceof DataManager) && dataType === 'string' || dataType === 'number') {\n filterQuery.where('', 'startswith', this.targetElement(), this.ignoreCase, this.ignoreAccent);\n }\n else {\n var fields = this.fields;\n filterQuery.where(!isNullOrUndefined(fields.text) ? fields.text : '', 'startswith', this.targetElement(), this.ignoreCase, this.ignoreAccent);\n }\n }\n return filterQuery;\n }\n else {\n return query ? query : this.query ? this.query : new Query();\n }\n };\n MultiSelect.prototype.dataUpdater = function (dataSource, query, fields) {\n if (this.targetElement().trim() === '') {\n var list = this.mainList.cloneNode ? this.mainList.cloneNode(true) : this.mainList;\n if (this.backCommand) {\n this.remoteCustomValue = false;\n this.onActionComplete(list, this.mainData);\n if (this.value && this.value.length) {\n this.refreshSelection();\n }\n if (this.keyCode !== 8) {\n this.focusAtFirstListItem();\n }\n this.notify('reOrder', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', e: this });\n }\n }\n else {\n this.resetList(dataSource, fields, query);\n if (this.allowCustomValue) {\n if (!(dataSource instanceof DataManager)) {\n this.checkForCustomValue(query, fields);\n }\n else {\n this.remoteCustomValue = true;\n this.tempQuery = query;\n }\n }\n }\n this.refreshPopup();\n };\n MultiSelect.prototype.checkForCustomValue = function (query, fields) {\n var dataChecks = !this.getValueByText(this.inputElement.value, this.ignoreCase);\n if (this.allowCustomValue && dataChecks) {\n var value = this.inputElement.value;\n var customData = (!isNullOrUndefined(this.mainData) && this.mainData.length > 0) ?\n this.mainData[0] : this.mainData;\n if (typeof (customData) !== 'string') {\n var dataItem = {};\n setValue(fields.text, value, dataItem);\n setValue(fields.value, value, dataItem);\n var tempData = JSON.parse(JSON.stringify(this.listData));\n tempData.splice(0, 0, dataItem);\n this.resetList(tempData, fields ? fields : this.fields, query);\n }\n else {\n var tempData = [this.inputElement.value];\n this.resetList(tempData, fields ? fields : this.fields);\n }\n }\n if (this.value && this.value.length) {\n this.refreshSelection();\n }\n };\n MultiSelect.prototype.getNgDirective = function () {\n return 'EJS-MULTISELECT';\n };\n MultiSelect.prototype.wrapperClick = function (e) {\n this.setDynValue = false;\n if (this.readonly || !this.enabled) {\n return;\n }\n if (e.target === this.overAllClear) {\n e.preventDefault();\n return;\n }\n if (!this.inputFocus && this.mode !== 'CheckBox') {\n this.dispatchEvent(this.inputElement, 'focus');\n }\n if (this.mode === 'CheckBox') {\n this.focusIn();\n }\n if (e.target && e.target.classList.toString().indexOf(CHIP_CLOSE) !== -1) {\n if (this.isPopupOpen()) {\n this.refreshPopup();\n }\n return;\n }\n if (!this.isPopupOpen() && this.openOnClick) {\n this.showPopup();\n }\n else {\n this.hidePopup();\n if (this.mode === 'CheckBox') {\n this.focusIn();\n }\n }\n e.preventDefault();\n };\n MultiSelect.prototype.enable = function (state) {\n if (state) {\n this.overAllWrapper.classList.remove(DISABLED);\n this.inputElement.removeAttribute('disabled');\n attributes(this.inputElement, { 'aria-disabled': 'false' });\n }\n else {\n this.overAllWrapper.classList.add(DISABLED);\n this.inputElement.setAttribute('disabled', 'true');\n attributes(this.inputElement, { 'aria-disabled': 'true' });\n }\n if (this.enabled !== state) {\n this.enabled = state;\n }\n this.hidePopup();\n };\n MultiSelect.prototype.onBlur = function (eve) {\n var target;\n if (!isNullOrUndefined(eve)) {\n target = eve.relatedTarget;\n }\n if (this.popupObj && document.body.contains(this.popupObj.element) && this.popupObj.element.contains(target)) {\n if (this.mode !== 'CheckBox') {\n this.inputElement.focus();\n }\n return;\n }\n if (this.mode === 'CheckBox' && Browser.isIE && !isNullOrUndefined(eve)) {\n this.inputFocus = false;\n this.overAllWrapper.classList.remove(FOCUS);\n return;\n }\n if (this.scrollFocusStatus) {\n eve.preventDefault();\n this.inputElement.focus();\n this.scrollFocusStatus = false;\n return;\n }\n this.inputFocus = false;\n this.overAllWrapper.classList.remove(FOCUS);\n if (this.mode !== 'Box' && this.mode !== 'CheckBox') {\n this.refreshListItems(null);\n this.updateDelimView();\n }\n this.updateValueState(eve, this.value, this.tempValues);\n this.dispatchEvent(this.hiddenElement, 'change');\n this.overAllClear.style.display = 'none';\n if (this.isPopupOpen()) {\n this.hidePopup();\n }\n this.makeTextBoxEmpty();\n this.trigger('blur');\n this.focused = true;\n if (Browser.isDevice && this.mode !== 'Delimiter' && this.mode !== 'CheckBox') {\n this.removeChipFocus();\n }\n this.removeChipSelection();\n this.refreshInputHight();\n floatLabelBlur(this.overAllWrapper, this.componentWrapper, this.value, this.floatLabelType, this.placeholder);\n this.refreshPlaceHolder();\n };\n MultiSelect.prototype.refreshInputHight = function () {\n if (!this.value || !this.value.length) {\n this.searchWrapper.classList.remove(ZERO_SIZE);\n }\n else {\n this.searchWrapper.classList.add(ZERO_SIZE);\n }\n };\n MultiSelect.prototype.validateValues = function (newValue, oldValue) {\n return JSON.stringify(newValue.slice().sort()) !== JSON.stringify(oldValue.slice().sort());\n };\n MultiSelect.prototype.updateValueState = function (event, newVal, oldVal) {\n var newValue = newVal ? newVal : [];\n var oldValue = oldVal ? oldVal : [];\n if (this.initStatus && this.validateValues(newValue, oldValue)) {\n var eventArgs = {\n e: event,\n oldValue: oldVal,\n value: newVal,\n isInteracted: event ? true : false,\n element: this.element\n };\n this.trigger('change', eventArgs);\n }\n };\n MultiSelect.prototype.getPagingCount = function () {\n var height = this.list.classList.contains(dropDownBaseClasses.noData) ? null :\n getComputedStyle(this.getItems()[0], null).getPropertyValue('height');\n return Math.round(this.list.offsetHeight / parseInt(height, 10));\n };\n MultiSelect.prototype.pageUpSelection = function (steps) {\n var collection = this.list.querySelectorAll('li.'\n + dropDownBaseClasses.li + ':not(.' + HIDE_LIST + ')' + ':not(.e-reorder-hide)');\n var previousItem;\n previousItem = steps >= 0 ? collection[steps + 1] : collection[0];\n this.addListFocus(previousItem);\n this.scrollBottom(previousItem, this.getIndexByValue(previousItem.getAttribute('data-value')));\n };\n ;\n MultiSelect.prototype.pageDownSelection = function (steps) {\n var list = this.getItems();\n var collection = this.list.querySelectorAll('li.'\n + dropDownBaseClasses.li + ':not(.' + HIDE_LIST + ')' + ':not(.e-reorder-hide)');\n var previousItem;\n previousItem = steps <= collection.length ? collection[steps - 1] : collection[collection.length - 1];\n this.addListFocus(previousItem);\n this.scrollBottom(previousItem, this.getIndexByValue(previousItem.getAttribute('data-value')));\n };\n MultiSelect.prototype.getItems = function () {\n if (!this.list) {\n _super.prototype.render.call(this);\n }\n return this.ulElement ? this.ulElement.querySelectorAll('.' + dropDownBaseClasses.li\n + ':not(.' + HIDE_LIST + ')') : null;\n };\n MultiSelect.prototype.focusIn = function () {\n if (this.enabled && !this.readonly) {\n this.showOverAllClear();\n this.inputFocus = true;\n if (!this.value) {\n this.tempValues = this.value;\n }\n else {\n this.tempValues = this.value.slice();\n }\n if (this.value && this.value.length) {\n if (this.mode !== 'Delimiter' && this.mode !== 'CheckBox') {\n this.chipCollectionWrapper.style.display = '';\n }\n else {\n this.showDelimWrapper();\n }\n if (this.mode !== 'CheckBox') {\n this.viewWrapper.style.display = 'none';\n }\n }\n if (this.mode !== 'CheckBox') {\n this.searchWrapper.classList.remove(ZERO_SIZE);\n }\n if (this.focused) {\n this.inputElement.focus();\n this.trigger('focus');\n this.focused = false;\n }\n if (!this.overAllWrapper.classList.contains(FOCUS)) {\n this.overAllWrapper.classList.add(FOCUS);\n }\n floatLabelFocus(this.overAllWrapper, this.componentWrapper);\n if (this.isPopupOpen()) {\n this.refreshPopup();\n }\n return true;\n }\n else {\n return false;\n }\n };\n MultiSelect.prototype.showDelimWrapper = function () {\n if (this.mode === 'CheckBox') {\n this.viewWrapper.style.display = '';\n }\n else {\n this.delimiterWrapper.style.display = '';\n }\n this.componentWrapper.classList.add(DELIMITER_VIEW_WRAPPER);\n };\n MultiSelect.prototype.hideDelimWrapper = function () {\n this.delimiterWrapper.style.display = 'none';\n this.componentWrapper.classList.remove(DELIMITER_VIEW_WRAPPER);\n };\n MultiSelect.prototype.expandTextbox = function () {\n var size = 5;\n if (this.placeholder) {\n size = size > this.inputElement.placeholder.length ? size : this.inputElement.placeholder.length;\n }\n if (this.inputElement.value.length > size) {\n this.inputElement.size = this.inputElement.value.length;\n }\n else {\n this.inputElement.size = size;\n }\n };\n MultiSelect.prototype.isPopupOpen = function () {\n return ((this.popupWrapper !== null) && (this.popupWrapper.parentElement !== null));\n };\n MultiSelect.prototype.refreshPopup = function () {\n if (this.popupObj && this.mobFilter) {\n this.popupObj.setProperties({ width: this.calcPopupWidth() });\n this.popupObj.refreshPosition(this.overAllWrapper);\n }\n };\n MultiSelect.prototype.checkTextLength = function () {\n return this.targetElement().length < 1;\n };\n MultiSelect.prototype.popupKeyActions = function (keyCode) {\n switch (keyCode) {\n case 38:\n this.hidePopup();\n if (this.mode === 'CheckBox') {\n this.inputElement.focus();\n }\n break;\n case 40:\n if (!this.isPopupOpen()) {\n this.showPopup();\n }\n break;\n }\n };\n MultiSelect.prototype.updateAriaAttribute = function () {\n var focusedItem = this.list.querySelector('.' + dropDownBaseClasses.focus);\n if (!isNullOrUndefined(focusedItem)) {\n this.inputElement.setAttribute('aria-activedescendant', focusedItem.id);\n }\n };\n MultiSelect.prototype.onKeyDown = function (e) {\n if (this.readonly || !this.enabled && this.mode !== 'CheckBox') {\n return;\n }\n this.keyDownStatus = true;\n if (e.keyCode > 111 && e.keyCode < 124) {\n return;\n }\n if (e.altKey) {\n this.popupKeyActions(e.keyCode);\n e.preventDefault();\n return;\n }\n else if (this.isPopupOpen()) {\n var focusedItem = this.list.querySelector('.' + dropDownBaseClasses.focus);\n var activeIndex = void 0;\n switch (e.keyCode) {\n case 36:\n case 35: break;\n case 33:\n e.preventDefault();\n if (focusedItem) {\n this.getIndexByValue(focusedItem.getAttribute('data-value'));\n this.pageUpSelection(activeIndex - this.getPagingCount());\n this.updateAriaAttribute();\n }\n return;\n case 34:\n e.preventDefault();\n if (focusedItem) {\n this.getIndexByValue(focusedItem.getAttribute('data-value'));\n this.pageDownSelection(activeIndex + this.getPagingCount());\n this.updateAriaAttribute();\n }\n return;\n case 38:\n e.preventDefault();\n this.moveByList(-1);\n this.updateAriaAttribute();\n break;\n case 40:\n e.preventDefault();\n this.moveByList(1);\n this.updateAriaAttribute();\n break;\n case 27:\n e.preventDefault();\n this.hidePopup();\n if (this.mode === 'CheckBox') {\n this.inputElement.focus();\n }\n return;\n case 13:\n e.preventDefault();\n if (this.mode !== 'CheckBox') {\n this.selectByKey(e);\n }\n return;\n case 32:\n if (this.mode === 'CheckBox') {\n e.preventDefault();\n this.selectByKey(e);\n }\n return;\n case 9:\n e.preventDefault();\n this.hidePopup();\n this.inputElement.focus();\n this.overAllWrapper.classList.add(FOCUS);\n }\n }\n else {\n switch (e.keyCode) {\n case 13:\n case 9:\n case 16:\n case 17:\n case 20:\n return;\n case 40:\n if (this.openOnClick) {\n this.showPopup();\n }\n break;\n case 27:\n e.preventDefault();\n this.escapeAction();\n return;\n }\n }\n if (this.checkTextLength()) {\n this.keyNavigation(e);\n }\n if (this.mode === 'CheckBox' && this.enableSelectionOrder) {\n this.checkBackCommand(e);\n }\n this.expandTextbox();\n this.refreshPopup();\n };\n MultiSelect.prototype.checkBackCommand = function (e) {\n if (e.keyCode === 8 && this.targetElement() === '') {\n this.backCommand = false;\n }\n else {\n this.backCommand = true;\n }\n };\n MultiSelect.prototype.keyNavigation = function (e) {\n if ((this.mode !== 'Delimiter' && this.mode !== 'CheckBox') && this.value && this.value.length) {\n switch (e.keyCode) {\n case 37://left arrow \n e.preventDefault();\n this.moveBy(-1, e);\n break;\n case 39://right arrow \n e.preventDefault();\n this.moveBy(1, e);\n break;\n case 8:\n this.removelastSelection(e);\n break;\n case 46://del\n this.removeSelectedChip(e);\n break;\n }\n }\n else if (e.keyCode === 8 && this.mode === 'Delimiter') {\n if (this.value && this.value.length) {\n e.preventDefault();\n var temp = this.value[this.value.length - 1];\n this.removeValue(temp, e);\n this.updateDelimeter(this.delimiterChar);\n this.focusAtLastListItem(temp);\n }\n }\n };\n MultiSelect.prototype.selectByKey = function (e) {\n this.removeChipSelection();\n this.selectListByKey(e);\n if (this.hideSelectedItem) {\n this.focusAtFirstListItem();\n }\n };\n MultiSelect.prototype.escapeAction = function () {\n var temp = this.tempValues ? this.tempValues.slice() : [];\n if (this.value && this.validateValues(this.value, temp)) {\n this.value = temp;\n this.initialValueUpdate();\n if (this.mode !== 'Delimiter' && this.mode !== 'CheckBox') {\n this.chipCollectionWrapper.style.display = '';\n }\n else {\n this.showDelimWrapper();\n }\n this.refreshPlaceHolder();\n if (this.value.length) {\n this.showOverAllClear();\n }\n else {\n this.hideOverAllClear();\n }\n }\n this.makeTextBoxEmpty();\n };\n MultiSelect.prototype.scrollBottom = function (selectedLI, activeIndex) {\n var currentOffset = this.list.offsetHeight;\n var nextBottom = selectedLI.offsetTop + selectedLI.offsetHeight - this.list.scrollTop;\n var nextOffset = this.list.scrollTop + nextBottom - currentOffset;\n var boxRange = (selectedLI.offsetTop + selectedLI.offsetHeight - this.list.scrollTop);\n boxRange = this.fields.groupBy && !isUndefined(this.fixedHeaderElement) ?\n boxRange - this.fixedHeaderElement.offsetHeight : boxRange;\n if (activeIndex === 0) {\n this.list.scrollTop = 0;\n }\n else if (nextBottom > currentOffset) {\n this.list.scrollTop = nextOffset;\n }\n else if (!(boxRange > 0 && this.list.offsetHeight > boxRange)) {\n this.list.scrollTop = nextOffset;\n }\n };\n MultiSelect.prototype.scrollTop = function (selectedLI, activeIndex) {\n var nextOffset = selectedLI.offsetTop - this.list.scrollTop;\n var nextBottom = selectedLI.offsetTop + selectedLI.offsetHeight - this.list.scrollTop;\n nextOffset = this.fields.groupBy && !isUndefined(this.fixedHeaderElement) ?\n nextOffset - this.fixedHeaderElement.offsetHeight : nextOffset;\n var boxRange = (selectedLI.offsetTop + selectedLI.offsetHeight - this.list.scrollTop);\n if (activeIndex === 0) {\n this.list.scrollTop = 0;\n }\n else if (nextOffset < 0) {\n this.list.scrollTop = this.list.scrollTop + nextOffset;\n }\n else if (!(boxRange > 0 && this.list.offsetHeight > boxRange)) {\n this.list.scrollTop = selectedLI.offsetTop - (this.fields.groupBy && !isUndefined(this.fixedHeaderElement) ?\n this.fixedHeaderElement.offsetHeight : 0);\n }\n };\n MultiSelect.prototype.selectListByKey = function (e) {\n var li = this.list.querySelector('li.' + dropDownBaseClasses.focus);\n var limit = this.value && this.value.length ? this.value.length : 0;\n if (li !== null) {\n if (li.classList.contains('e-active')) {\n limit = limit - 1;\n }\n if (this.isValidLI(li) && limit < this.maximumSelectionLength) {\n this.updateListSelection(li, e);\n this.addListFocus(li);\n if (this.mode === 'CheckBox') {\n this.updateDelimView();\n this.refreshInputHight();\n this.updateDelimeter(this.delimiterChar);\n }\n else {\n this.updateDelimeter(this.delimiterChar);\n }\n this.makeTextBoxEmpty();\n if (this.mode !== 'CheckBox') {\n this.refreshListItems(li.textContent);\n }\n this.refreshPopup();\n }\n if (this.closePopupOnSelect) {\n this.hidePopup();\n }\n }\n this.refreshPlaceHolder();\n };\n MultiSelect.prototype.refreshListItems = function (data) {\n if ((this.allowFiltering || this.allowCustomValue) && this.mainList && this.listData) {\n var list = void 0;\n if (this.sortOrder === 'Descending' || this.sortOrder === 'Ascending') {\n list = this.ulElement.cloneNode ? this.ulElement.cloneNode(true) : this.ulElement;\n }\n else {\n list = this.mainList.cloneNode ? this.mainList.cloneNode(true) : this.mainList;\n }\n this.onActionComplete(list, this.mainData);\n this.focusAtLastListItem(data);\n if (this.value && this.value.length) {\n this.refreshSelection();\n }\n }\n };\n MultiSelect.prototype.removeSelectedChip = function (e) {\n var selectedElem = this.chipCollectionWrapper.querySelector('span.' + CHIP_SELECTED);\n var temp;\n if (selectedElem !== null) {\n if (!isNullOrUndefined(this.value)) {\n this.tempValues = this.value.slice();\n }\n temp = selectedElem.nextElementSibling;\n if (temp !== null) {\n this.removeChipSelection();\n this.addChipSelection(temp, e);\n }\n this.removeValue(selectedElem.getAttribute('data-value'), e);\n this.makeTextBoxEmpty();\n }\n if (this.closePopupOnSelect) {\n this.hidePopup();\n }\n };\n MultiSelect.prototype.moveByTop = function (state) {\n var elements = this.list.querySelectorAll('li.' + dropDownBaseClasses.li);\n var index;\n if (elements.length > 1) {\n this.removeFocus();\n index = state ? 0 : (elements.length - 1);\n this.addListFocus(elements[index]);\n this.scrollBottom(elements[index], index);\n }\n this.updateAriaAttribute();\n };\n MultiSelect.prototype.moveByList = function (position) {\n if (this.list) {\n var elements = this.list.querySelectorAll('li.'\n + dropDownBaseClasses.li\n + ':not(.' + HIDE_LIST + ')' + ':not(.e-reorder-hide)');\n var selectedElem = this.list.querySelector('li.' + dropDownBaseClasses.focus);\n var temp = -1;\n if (elements.length) {\n for (var index = 0; index < elements.length; index++) {\n if (elements[index] === selectedElem) {\n temp = index;\n break;\n }\n }\n if (position > 0) {\n if (temp < (elements.length - 1)) {\n this.removeFocus();\n this.addListFocus(elements[++temp]);\n this.scrollBottom(elements[temp], temp);\n }\n }\n else {\n if (temp > 0) {\n this.removeFocus();\n this.addListFocus(elements[--temp]);\n this.scrollTop(elements[temp], temp);\n }\n }\n }\n }\n };\n MultiSelect.prototype.moveBy = function (position, e) {\n var elements;\n var selectedElem;\n var temp;\n elements = this.chipCollectionWrapper.querySelectorAll('span.' + CHIP);\n selectedElem = this.chipCollectionWrapper.querySelector('span.' + CHIP_SELECTED);\n if (selectedElem === null) {\n if (position < 0) {\n this.addChipSelection(elements[elements.length - 1], e);\n }\n }\n else {\n if (position < 0) {\n temp = selectedElem.previousElementSibling;\n if (temp !== null) {\n this.removeChipSelection();\n this.addChipSelection(temp, e);\n }\n }\n else {\n temp = selectedElem.nextElementSibling;\n this.removeChipSelection();\n if (temp !== null) {\n this.addChipSelection(temp, e);\n }\n }\n }\n };\n MultiSelect.prototype.chipClick = function (e) {\n if (this.enabled) {\n var elem = closest(e.target, '.' + CHIP);\n this.removeChipSelection();\n this.addChipSelection(elem, e);\n }\n };\n MultiSelect.prototype.removeChipSelection = function () {\n if (this.chipCollectionWrapper) {\n this.removeChipFocus();\n }\n };\n MultiSelect.prototype.addChipSelection = function (element, e) {\n addClass([element], CHIP_SELECTED);\n this.trigger('chipSelection', e);\n };\n MultiSelect.prototype.onChipRemove = function (e) {\n if (e.which === 3 || e.button === 2) {\n return;\n }\n if (this.enabled && !this.readonly) {\n var element = e.target.parentElement;\n var value = this.getFormattedValue(element.getAttribute('data-value'));\n if (this.isPopupOpen() && this.mode !== 'CheckBox') {\n this.hidePopup();\n }\n if (!this.inputFocus) {\n this.inputElement.focus();\n }\n this.removeValue(value, e);\n if (isNullOrUndefined(this.list.querySelector('li[data-value=\"' + value + '\"]')) && this.mainList && this.listData) {\n var list = this.mainList.cloneNode ? this.mainList.cloneNode(true) : this.mainList;\n this.onActionComplete(list, this.mainData);\n }\n this.updateDelimeter(this.delimiterChar);\n this.makeTextBoxEmpty();\n e.preventDefault();\n }\n };\n MultiSelect.prototype.makeTextBoxEmpty = function () {\n this.inputElement.value = '';\n this.refreshPlaceHolder();\n };\n MultiSelect.prototype.refreshPlaceHolder = function () {\n if (this.placeholder && this.floatLabelType === 'Never') {\n if (this.value && this.value.length) {\n this.inputElement.placeholder = '';\n }\n else {\n this.inputElement.placeholder = this.placeholder;\n }\n }\n else {\n this.setFloatLabelType();\n }\n this.expandTextbox();\n };\n MultiSelect.prototype.removeValue = function (value, eve, length) {\n var index = this.value.indexOf(this.getFormattedValue(value));\n var className = this.hideSelectedItem ?\n HIDE_LIST :\n dropDownBaseClasses.selected;\n if (index !== -1) {\n var element = this.list.querySelector('li[data-value=\"' + value + '\"]');\n var val = this.getDataByValue(value);\n var eventArgs = {\n e: eve,\n item: element,\n itemData: val,\n isInteracted: eve ? true : false,\n cancel: false\n };\n this.trigger('removing', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.value.splice(index, 1);\n this.setProperties({ value: [].concat([], this.value) }, true);\n if (element !== null) {\n element.setAttribute('aria-selected', 'false');\n removeClass([element], className);\n this.notify('activeList', {\n module: 'CheckBoxSelection',\n enable: this.mode === 'CheckBox', li: element,\n e: this, index: index\n });\n this.notify('updatelist', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', li: element, e: eve });\n attributes(this.inputElement, { 'aria-activedescendant': element.id });\n if ((this.value.length !== this.mainData.length) && (this.mode === 'CheckBox' && this.showSelectAll)) {\n this.notify('checkSelectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', value: 'uncheck' });\n }\n }\n if (this.hideSelectedItem && this.fields.groupBy) {\n this.hideGroupItem(value);\n }\n this.updateMainList(true, value);\n this.removeChip(value);\n this.updateChipStatus();\n var limit = this.value && this.value.length ? this.value.length : 0;\n if (limit < this.maximumSelectionLength) {\n var collection = this.list.querySelectorAll('li.'\n + dropDownBaseClasses.li + ':not(.e-active)');\n removeClass(collection, 'e-disable');\n }\n this.trigger('removed', eventArgs);\n if (length) {\n this.selectAllEventData.push(val);\n this.selectAllEventEle.push(element);\n }\n if (length === 1) {\n var args = {\n e: eve,\n items: this.selectAllEventEle,\n itemData: this.selectAllEventData,\n isInteracted: eve ? true : false,\n IsChecked: false\n };\n this.trigger('selectedAll', args);\n this.selectAllEventData = [];\n this.selectAllEventEle = [];\n }\n }\n };\n MultiSelect.prototype.updateMainList = function (state, value) {\n if (this.allowFiltering) {\n var element2 = this.mainList.querySelector('li[data-value=\"' + value + '\"]');\n if (element2) {\n if (state) {\n element2.setAttribute('aria-selected', 'false');\n removeClass([element2], this.hideSelectedItem ?\n HIDE_LIST :\n dropDownBaseClasses.selected);\n if (this.mode === 'CheckBox') {\n element2.firstElementChild.setAttribute('aria-checked', 'false');\n removeClass([element2.firstElementChild.lastElementChild], 'e-check');\n }\n }\n else {\n element2.setAttribute('aria-selected', 'true');\n addClass([element2], this.hideSelectedItem ?\n HIDE_LIST :\n dropDownBaseClasses.selected);\n if (this.mode === 'CheckBox') {\n element2.firstElementChild.setAttribute('aria-checked', 'true');\n addClass([element2.firstElementChild.lastElementChild], 'e-check');\n }\n }\n }\n }\n };\n MultiSelect.prototype.removeChip = function (value) {\n if (this.chipCollectionWrapper) {\n var element = this.chipCollectionWrapper.querySelector('span[data-value=\"' + value + '\"]');\n if (element) {\n remove(element);\n }\n }\n };\n MultiSelect.prototype.updateChipStatus = function () {\n if (this.value.length) {\n if (!isNullOrUndefined(this.chipCollectionWrapper)) {\n (this.chipCollectionWrapper.style.display = '');\n }\n if (this.mode === 'Delimiter' || this.mode === 'CheckBox') {\n this.showDelimWrapper();\n }\n this.showOverAllClear();\n }\n else {\n if (!isNullOrUndefined(this.chipCollectionWrapper)) {\n this.chipCollectionWrapper.style.display = 'none';\n }\n if (!isNullOrUndefined(this.delimiterWrapper)) {\n (this.delimiterWrapper.style.display = 'none');\n }\n this.hideOverAllClear();\n }\n };\n MultiSelect.prototype.addValue = function (value, text, eve) {\n if (!this.value) {\n this.value = [];\n }\n this.setProperties({ value: [].concat([], this.value, [value]) }, true);\n var element = this.list.querySelector('li[data-value=\"' + value + '\"]');\n this.removeFocus();\n if (element) {\n this.addListFocus(element);\n this.addListSelection(element);\n }\n if (this.mode !== 'Delimiter' && this.mode !== 'CheckBox') {\n this.addChip(text, value, eve);\n }\n if (this.hideSelectedItem && this.fields.groupBy) {\n this.hideGroupItem(value);\n }\n this.updateChipStatus();\n this.checkMaxSelection();\n };\n MultiSelect.prototype.checkMaxSelection = function () {\n var limit = this.value && this.value.length ? this.value.length : 0;\n if (limit === this.maximumSelectionLength) {\n var collection = this.list.querySelectorAll('li.'\n + dropDownBaseClasses.li + ':not(.e-active)');\n addClass(collection, 'e-disable');\n }\n };\n MultiSelect.prototype.dispatchSelect = function (value, eve, element, isNotTrigger, length) {\n if (this.initStatus && !isNotTrigger) {\n var val = this.getDataByValue(value);\n var eventArgs = {\n e: eve,\n item: element,\n itemData: val,\n isInteracted: eve ? true : false,\n cancel: false\n };\n this.trigger('select', eventArgs);\n if (eventArgs.cancel) {\n return true;\n }\n if (length) {\n this.selectAllEventData.push(val);\n this.selectAllEventEle.push(element);\n }\n if (length === 1) {\n var args = {\n e: eve,\n items: this.selectAllEventEle,\n itemData: this.selectAllEventData,\n isInteracted: eve ? true : false,\n IsChecked: true\n };\n this.trigger('selectedAll', args);\n this.selectAllEventData = [];\n }\n }\n return false;\n };\n MultiSelect.prototype.addChip = function (text, value, e) {\n if (this.chipCollectionWrapper) {\n var item = this.getChip(text, value, e);\n if (item.cancel) {\n return;\n }\n this.chipCollectionWrapper.appendChild(item.element);\n }\n };\n MultiSelect.prototype.removeChipFocus = function () {\n var elements;\n var closeElements;\n elements = this.chipCollectionWrapper.querySelectorAll('span.' + CHIP);\n closeElements = this.chipCollectionWrapper.querySelectorAll('span.' + CHIP_CLOSE.split(' ')[0]);\n removeClass(elements, CHIP_SELECTED);\n if (Browser.isDevice) {\n for (var index = 0; index < closeElements.length; index++) {\n closeElements[index].style.display = 'none';\n }\n }\n };\n MultiSelect.prototype.onMobileChipInteraction = function (e) {\n var chipElem = closest(e.target, '.' + CHIP);\n var chipClose = chipElem.querySelector('span.' + CHIP_CLOSE.split(' ')[0]);\n if (this.enabled && !this.readonly) {\n if (!chipElem.classList.contains(CHIP_SELECTED)) {\n this.removeChipFocus();\n chipClose.style.display = '';\n chipElem.classList.add(CHIP_SELECTED);\n }\n this.refreshPopup();\n e.preventDefault();\n }\n };\n MultiSelect.prototype.getChip = function (data, value, e) {\n var itemData = { text: value, value: value };\n var chip = this.createElement('span', {\n className: CHIP,\n attrs: { 'data-value': value, 'title': data }\n });\n var chipContent = this.createElement('span', { className: CHIP_CONTENT });\n var chipClose = this.createElement('span', { className: CHIP_CLOSE });\n if (this.mainData) {\n itemData = this.getDataByValue(value);\n }\n if (this.valueTemplate && !isNullOrUndefined(itemData)) {\n var compiledString = compile(this.valueTemplate);\n for (var _i = 0, _a = compiledString(itemData); _i < _a.length; _i++) {\n var item = _a[_i];\n chipContent.appendChild(item);\n }\n }\n else {\n chipContent.innerHTML = data;\n }\n chip.appendChild(chipContent);\n var eventArgs = {\n isInteracted: e ? true : false,\n itemData: itemData,\n e: e,\n setClass: function (classes) {\n addClass([chip], classes);\n },\n cancel: false\n };\n this.trigger('tagging', eventArgs);\n if (eventArgs.cancel) {\n return { cancel: true, element: chip };\n }\n if (Browser.isDevice) {\n chip.classList.add(MOBILE_CHIP);\n append([chipClose], chip);\n chipClose.style.display = 'none';\n EventHandler.add(chip, 'click', this.onMobileChipInteraction, this);\n }\n else {\n EventHandler.add(chip, 'mousedown', this.chipClick, this);\n if (this.showClearButton) {\n chip.appendChild(chipClose);\n }\n }\n EventHandler.add(chipClose, 'mousedown', this.onChipRemove, this);\n return { cancel: false, element: chip };\n };\n MultiSelect.prototype.calcPopupWidth = function () {\n var width = formatUnit(this.popupWidth);\n if (width.indexOf('%') > -1) {\n var inputWidth = (this.componentWrapper.offsetWidth) * parseFloat(width) / 100;\n width = inputWidth.toString() + 'px';\n }\n return width;\n };\n MultiSelect.prototype.mouseIn = function () {\n if (this.enabled && !this.readonly) {\n this.showOverAllClear();\n }\n };\n MultiSelect.prototype.mouseOut = function () {\n if (!this.inputFocus) {\n this.overAllClear.style.display = 'none';\n }\n };\n MultiSelect.prototype.listOption = function (dataSource, fields) {\n var iconCss = isNullOrUndefined(fields.iconCss) ? false : true;\n var fieldProperty = fields.properties;\n this.listCurrentOptions = (fields.text !== null || fields.value !== null) ? {\n fields: fieldProperty, showIcon: iconCss, ariaAttributes: { groupItemRole: 'presentation' }\n } : { fields: { value: 'text' } };\n extend(this.listCurrentOptions, this.listCurrentOptions, fields, true);\n if (this.mode === 'CheckBox') {\n this.notify('listoption', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', dataSource: dataSource, fieldProperty: fieldProperty });\n }\n return this.listCurrentOptions;\n };\n MultiSelect.prototype.renderPopup = function () {\n var _this = this;\n if (!this.list) {\n _super.prototype.render.call(this);\n }\n if (!this.popupObj) {\n var args = { cancel: false };\n this.trigger('beforeOpen', args);\n if (args.cancel) {\n return;\n }\n document.body.appendChild(this.popupWrapper);\n var overAllHeight = parseInt(this.popupHeight, 10);\n this.popupWrapper.style.visibility = 'hidden';\n if (this.headerTemplate) {\n this.setHeaderTemplate();\n overAllHeight -= this.header.offsetHeight;\n }\n append([this.list], this.popupWrapper);\n if (this.footerTemplate) {\n this.setFooterTemplate();\n overAllHeight -= this.footer.offsetHeight;\n }\n if (this.mode === 'CheckBox' && this.showSelectAll) {\n this.notify('selectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox' });\n overAllHeight -= this.selectAllHeight;\n }\n else if (this.mode === 'CheckBox' && !this.showSelectAll && (!this.headerTemplate || !this.footerTemplate)) {\n this.notify('selectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox' });\n overAllHeight = parseInt(this.popupHeight, 10);\n }\n else if (this.mode === 'CheckBox' && !this.showSelectAll) {\n this.notify('selectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox' });\n overAllHeight = parseInt(this.popupHeight, 10);\n if (this.headerTemplate && this.header) {\n overAllHeight -= this.header.offsetHeight;\n }\n if (this.footerTemplate && this.footer) {\n overAllHeight -= this.footer.offsetHeight;\n }\n }\n if (this.mode === 'CheckBox') {\n var args_1 = {\n module: 'CheckBoxSelection',\n enable: this.mode === 'CheckBox',\n popupElement: this.popupWrapper\n };\n this.notify('searchBox', args_1);\n overAllHeight -= this.searchBoxHeight;\n addClass([this.popupWrapper], 'e-checkbox');\n }\n if (this.popupHeight !== 'auto') {\n this.list.style.maxHeight = formatUnit(overAllHeight);\n this.popupWrapper.style.maxHeight = formatUnit(this.popupHeight);\n }\n else {\n this.list.style.maxHeight = formatUnit(this.popupHeight);\n }\n this.popupObj = new Popup(this.popupWrapper, {\n width: this.calcPopupWidth(), targetType: 'relative', position: { X: 'left', Y: 'bottom' },\n relateTo: this.overAllWrapper, collision: { X: 'flip', Y: 'flip' }, offsetY: 1,\n enableRtl: this.enableRtl,\n zIndex: this.zIndex,\n close: function () {\n if (_this.popupObj.element.parentElement) {\n detach(_this.popupObj.element);\n }\n },\n open: function () {\n _this.notify('inputFocus', { module: 'CheckBoxSelection', enable: _this.mode === 'CheckBox', value: 'focus' });\n }\n });\n this.popupObj.close();\n this.popupWrapper.style.visibility = '';\n if (this.mode === 'CheckBox' && Browser.isDevice) {\n this.notify('deviceSearchBox', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox' });\n }\n }\n };\n MultiSelect.prototype.setHeaderTemplate = function () {\n var compiledString;\n if (this.header) {\n this.header.remove();\n }\n this.header = this.createElement('div');\n addClass([this.header], HEADER);\n compiledString = compile(this.headerTemplate);\n var elements = compiledString({});\n for (var temp = 0; temp < elements.length; temp++) {\n this.header.appendChild(elements[temp]);\n }\n if (this.mode === 'CheckBox' && this.showSelectAll) {\n prepend([this.header], this.popupWrapper);\n }\n else {\n append([this.header], this.popupWrapper);\n }\n EventHandler.add(this.header, 'mousedown', this.onListMouseDown, this);\n };\n MultiSelect.prototype.setFooterTemplate = function () {\n var compiledString;\n if (this.footer) {\n this.footer.remove();\n }\n this.footer = this.createElement('div');\n addClass([this.footer], FOOTER);\n compiledString = compile(this.footerTemplate);\n var elements = compiledString({});\n for (var temp = 0; temp < elements.length; temp++) {\n this.footer.appendChild(elements[temp]);\n }\n append([this.footer], this.popupWrapper);\n EventHandler.add(this.footer, 'mousedown', this.onListMouseDown, this);\n };\n MultiSelect.prototype.ClearAll = function (e) {\n if (this.enabled && !this.readonly) {\n var temp = void 0;\n var tempValues = this.value ? this.value.slice() : [];\n if (this.value) {\n for (temp = this.value[0]; this.value.length !== 0; temp = this.value[0]) {\n this.removeValue(temp, e);\n }\n }\n if (this.mainList && this.listData && this.allowFiltering) {\n var list = this.mainList.cloneNode ? this.mainList.cloneNode(true) : this.mainList;\n this.onActionComplete(list, this.mainData);\n }\n this.focusAtFirstListItem();\n this.updateDelimeter(this.delimiterChar);\n if (this.mode !== 'Box') {\n this.updateDelimView();\n }\n this.makeTextBoxEmpty();\n if (this.isPopupOpen()) {\n this.refreshPopup();\n }\n if (!this.inputFocus) {\n this.updateValueState(e, this.value, tempValues);\n if (this.mode !== 'CheckBox') {\n this.inputElement.focus();\n }\n }\n if (this.mode === 'CheckBox') {\n this.refreshPlaceHolder();\n this.refreshInputHight();\n }\n e.preventDefault();\n }\n };\n MultiSelect.prototype.windowResize = function () {\n this.refreshPopup();\n if (!this.inputFocus && this.viewWrapper && this.viewWrapper.parentElement) {\n this.updateDelimView();\n }\n };\n MultiSelect.prototype.resetValueHandler = function () {\n this.value = null;\n };\n MultiSelect.prototype.wireEvent = function () {\n EventHandler.add(this.componentWrapper, 'mousedown', this.wrapperClick, this);\n EventHandler.add(window, 'resize', this.windowResize, this);\n EventHandler.add(this.inputElement, 'focus', this.focusIn, this);\n EventHandler.add(this.inputElement, 'keydown', this.onKeyDown, this);\n EventHandler.add(this.inputElement, 'keyup', this.KeyUp, this);\n if (this.mode !== 'CheckBox') {\n EventHandler.add(this.inputElement, 'input', this.onInput, this);\n }\n EventHandler.add(this.inputElement, 'blur', this.onBlur, this);\n EventHandler.add(this.componentWrapper, 'mousemove', this.mouseIn, this);\n var formElement = closest(this.inputElement, 'form');\n if (formElement) {\n EventHandler.add(formElement, 'reset', this.resetValueHandler, this);\n }\n EventHandler.add(this.componentWrapper, 'mouseout', this.mouseOut, this);\n EventHandler.add(this.overAllClear, 'mouseup', this.ClearAll, this);\n };\n MultiSelect.prototype.onInput = function () {\n if (this.keyDownStatus) {\n this.isValidKey = true;\n }\n else {\n this.isValidKey = false;\n }\n this.keyDownStatus = false;\n };\n MultiSelect.prototype.preRender = function () {\n this.initializeData();\n _super.prototype.preRender.call(this);\n };\n MultiSelect.prototype.initializeData = function () {\n this.mainListCollection = [];\n this.beforePopupOpen = false;\n this.filterAction = false;\n this.remoteFilterAction = false;\n this.isFirstClick = false;\n this.mobFilter = true;\n this.isFiltered = false;\n this.focused = true;\n this.initial = true;\n this.backCommand = true;\n };\n MultiSelect.prototype.updateData = function (delimiterChar) {\n var data = '';\n var delim = this.mode === 'Delimiter' || this.mode === 'CheckBox';\n var text = [];\n var temp;\n var tempData = this.listData;\n this.listData = this.mainData;\n this.hiddenElement.innerHTML = '';\n if (!isNullOrUndefined(this.value)) {\n for (var index = 0; !isNullOrUndefined(this.value[index]); index++) {\n if (this.listData) {\n temp = this.getTextByValue(this.value[index]);\n }\n else {\n temp = this.value[index];\n }\n data += temp + delimiterChar + ' ';\n text.push(temp);\n this.hiddenElement.innerHTML += '' + index + ' ';\n }\n }\n this.text = text.toString();\n if (delim) {\n this.delimiterWrapper.innerHTML = data;\n }\n this.listData = tempData;\n };\n MultiSelect.prototype.initialValueUpdate = function () {\n if (this.list) {\n var text = void 0;\n var textField = void 0;\n var valueField = void 0;\n var element = void 0;\n var value = void 0;\n if (this.chipCollectionWrapper) {\n this.chipCollectionWrapper.innerHTML = '';\n }\n this.removeListSelection();\n if (!isNullOrUndefined(this.value)) {\n for (var index = 0; !isNullOrUndefined(this.value[index]); index++) {\n value = this.value[index];\n element = this.hideSelectedItem ? this.ulElement.querySelector('li[data-value=\"' + value + '\"]')\n : this.list.querySelector('li[data-value=\"' + value + '\"]');\n text = this.getTextByValue(value);\n if ((element && (element.getAttribute('aria-selected') !== 'true')) ||\n (element && (element.getAttribute('aria-selected') === 'true' && this.hideSelectedItem) &&\n (this.mode === 'Box' || this.mode === 'Default'))) {\n this.addChip(text, value);\n this.addListSelection(element);\n }\n else if (value && this.allowCustomValue) {\n var indexItem = this.listData.length;\n var newValue = {};\n setValue(this.fields.text, value, newValue);\n setValue(this.fields.value, value, newValue);\n this.addItem(newValue, indexItem);\n this.addChip(text, value);\n this.addListSelection(element);\n }\n }\n }\n if (this.mode === 'CheckBox') {\n this.updateDelimView();\n this.updateValueState(null, this.value, this.tempValues);\n this.refreshInputHight();\n this.updateDelimeter(this.delimiterChar);\n }\n else {\n this.updateDelimeter(this.delimiterChar);\n }\n if (this.mode === 'CheckBox' && this.showSelectAll && isNullOrUndefined(this.value)) {\n this.notify('checkSelectAll', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', value: 'uncheck' });\n }\n if (!this.inputFocus) {\n if (this.mode === 'Box') {\n this.chipCollectionWrapper.style.display = '';\n }\n else if (this.mode === 'Delimiter' || this.mode === 'CheckBox') {\n this.showDelimWrapper();\n }\n }\n }\n };\n MultiSelect.prototype.isValidLI = function (li) {\n return (li && !li.classList.contains(dropDownBaseClasses.disabled) && !li.classList.contains(dropDownBaseClasses.group) &&\n li.classList.contains(dropDownBaseClasses.li));\n };\n ;\n MultiSelect.prototype.updateListSelection = function (li, e, length) {\n var value = this.getFormattedValue(li.getAttribute('data-value'));\n var text = this.getTextByValue(value);\n this.removeHover();\n if (!this.value || this.value.indexOf(value) === -1) {\n var argsCancel = this.dispatchSelect(value, e, li, (li.getAttribute('aria-selected') === 'true'), length);\n if (argsCancel) {\n return;\n }\n if ((this.allowCustomValue || this.allowFiltering) && !this.mainList.querySelector('li[data-value=\"' + value + '\"]')) {\n var temp = li.cloneNode(true);\n var data = this.getDataByValue(value);\n append([temp], this.mainList);\n this.mainData.push(data);\n var eventArgs = {\n newData: data,\n cancel: false\n };\n this.trigger('customValueSelection', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n }\n this.remoteCustomValue = false;\n this.addValue(value, text, e);\n }\n else {\n this.removeValue(value, e, length);\n }\n };\n MultiSelect.prototype.removeListSelection = function () {\n var className = this.hideSelectedItem ?\n HIDE_LIST :\n dropDownBaseClasses.selected;\n var selectedItems = this.list.querySelectorAll('.' + className);\n var temp = selectedItems.length;\n if (selectedItems && selectedItems.length) {\n removeClass(selectedItems, className);\n while (temp > 0) {\n selectedItems[temp - 1].setAttribute('aria-selected', 'false');\n temp--;\n }\n }\n if (!isNullOrUndefined(this.mainList)) {\n var selectItems = this.mainList.querySelectorAll('.' + className);\n var temp1 = selectItems.length;\n if (selectItems && selectItems.length) {\n removeClass(selectItems, className);\n while (temp1 > 0) {\n selectItems[temp1 - 1].setAttribute('aria-selected', 'false');\n if (this.mode === 'CheckBox') {\n selectItems[temp1 - 1].firstElementChild.setAttribute('aria-checked', 'false');\n removeClass([selectItems[temp1 - 1].firstElementChild.lastElementChild], 'e-check');\n }\n temp1--;\n }\n }\n }\n };\n ;\n MultiSelect.prototype.removeHover = function () {\n var hoveredItem = this.list.querySelectorAll('.' + dropDownBaseClasses.hover);\n if (hoveredItem && hoveredItem.length) {\n removeClass(hoveredItem, dropDownBaseClasses.hover);\n }\n };\n ;\n MultiSelect.prototype.removeFocus = function () {\n if (this.list) {\n var hoveredItem = this.list.querySelectorAll('.' + dropDownBaseClasses.focus);\n var mainlist = this.mainList.querySelectorAll('.' + dropDownBaseClasses.focus);\n if (hoveredItem && hoveredItem.length) {\n removeClass(hoveredItem, dropDownBaseClasses.focus);\n removeClass(mainlist, dropDownBaseClasses.focus);\n }\n }\n };\n ;\n MultiSelect.prototype.addListHover = function (li) {\n if (this.enabled && this.isValidLI(li)) {\n this.removeHover();\n addClass([li], dropDownBaseClasses.hover);\n }\n };\n ;\n MultiSelect.prototype.addListFocus = function (element) {\n if (this.enabled && this.isValidLI(element)) {\n this.removeFocus();\n addClass([element], dropDownBaseClasses.focus);\n }\n };\n MultiSelect.prototype.addListSelection = function (element) {\n var className = this.hideSelectedItem ?\n HIDE_LIST :\n dropDownBaseClasses.selected;\n if (this.isValidLI(element) && !element.classList.contains(dropDownBaseClasses.hover)) {\n addClass([element], className);\n this.updateMainList(false, element.getAttribute('data-value'));\n element.setAttribute('aria-selected', 'true');\n if (this.mode === 'CheckBox') {\n var ariaCheck = element.firstElementChild.getAttribute('aria-checked');\n if (ariaCheck === 'false' || isNullOrUndefined(ariaCheck)) {\n this.notify('updatelist', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', li: element, e: this });\n }\n }\n this.notify('activeList', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', li: element, e: this });\n if (this.chipCollectionWrapper !== null) {\n this.removeChipSelection();\n }\n attributes(this.inputElement, { 'aria-activedescendant': element.id });\n }\n };\n MultiSelect.prototype.updateDelimeter = function (delimChar) {\n this.updateData(delimChar);\n };\n MultiSelect.prototype.onMouseClick = function (e) {\n this.scrollFocusStatus = false;\n var target = e.target;\n var li = closest(target, '.' + dropDownBaseClasses.li);\n if (this.isValidLI(li)) {\n var limit = this.value && this.value.length ? this.value.length : 0;\n if (li.classList.contains('e-active')) {\n limit = limit - 1;\n }\n if (limit < this.maximumSelectionLength) {\n this.updateListSelection(li, e);\n this.addListFocus(li);\n if ((this.allowCustomValue || this.allowFiltering) && this.mainList && this.listData) {\n if (this.mode !== 'CheckBox') {\n this.focusAtLastListItem(li.getAttribute('data-value'));\n }\n this.refreshSelection();\n }\n else {\n this.makeTextBoxEmpty();\n }\n }\n if (this.mode === 'CheckBox') {\n this.updateDelimView();\n this.refreshInputHight();\n this.updateDelimeter(this.delimiterChar);\n }\n else {\n this.updateDelimeter(this.delimiterChar);\n }\n this.checkSelectAll();\n this.refreshPopup();\n if (this.hideSelectedItem) {\n this.focusAtFirstListItem();\n }\n if (this.closePopupOnSelect) {\n this.hidePopup();\n }\n else {\n e.preventDefault();\n }\n this.makeTextBoxEmpty();\n }\n else {\n e.preventDefault();\n }\n if (this.mode !== 'CheckBox') {\n this.refreshListItems(isNullOrUndefined(li) ? null : li.textContent);\n }\n this.refreshPlaceHolder();\n };\n MultiSelect.prototype.onMouseOver = function (e) {\n var currentLi = closest(e.target, '.' + dropDownBaseClasses.li);\n this.addListHover(currentLi);\n };\n MultiSelect.prototype.onMouseLeave = function (e) {\n this.removeHover();\n };\n MultiSelect.prototype.onListMouseDown = function (e) {\n e.preventDefault();\n this.scrollFocusStatus = true;\n };\n MultiSelect.prototype.onDocumentClick = function (e) {\n if (this.mode !== 'CheckBox') {\n var target = e.target;\n if (!(!isNullOrUndefined(this.popupObj) && closest(target, '#' + this.popupObj.element.id)) &&\n !this.overAllWrapper.contains(e.target)) {\n this.scrollFocusStatus = false;\n }\n else {\n this.scrollFocusStatus = (Browser.isIE || Browser.info.name === 'edge') && (document.activeElement === this.inputElement);\n }\n }\n };\n MultiSelect.prototype.wireListEvents = function () {\n EventHandler.add(document, 'mousedown', this.onDocumentClick, this);\n EventHandler.add(this.list, 'mousedown', this.onListMouseDown, this);\n EventHandler.add(this.list, 'mouseup', this.onMouseClick, this);\n EventHandler.add(this.list, 'mouseover', this.onMouseOver, this);\n EventHandler.add(this.list, 'mouseout', this.onMouseLeave, this);\n };\n ;\n MultiSelect.prototype.unwireListEvents = function () {\n EventHandler.remove(document, 'mousedown', this.onDocumentClick);\n if (this.list) {\n EventHandler.remove(this.list, 'mousedown', this.onListMouseDown);\n EventHandler.remove(this.list, 'mouseup', this.onMouseClick);\n EventHandler.remove(this.list, 'mouseover', this.onMouseOver);\n EventHandler.remove(this.list, 'mouseout', this.onMouseLeave);\n }\n };\n ;\n MultiSelect.prototype.hideOverAllClear = function () {\n if (!this.value || !this.value.length || this.inputElement.value === '') {\n this.overAllClear.style.display = 'none';\n }\n };\n MultiSelect.prototype.showOverAllClear = function () {\n if ((this.value && this.value.length) || this.inputElement.value !== '') {\n this.overAllClear.style.display = '';\n }\n else {\n this.overAllClear.style.display = 'none';\n }\n };\n /**\n * Shows the spinner loader.\n * @returns void.\n */\n MultiSelect.prototype.showSpinner = function () {\n if (isNullOrUndefined(this.spinnerElement)) {\n if (this.overAllClear.style.display !== 'none') {\n this.spinnerElement = this.overAllClear;\n }\n else {\n this.spinnerElement = this.createElement('span', { className: CLOSEICON_CLASS + ' ' + SPINNER_CLASS });\n this.componentWrapper.appendChild(this.spinnerElement);\n }\n createSpinner({ target: this.spinnerElement, width: Browser.isDevice ? '16px' : '14px' }, this.createElement);\n addClass([this.spinnerElement], DISABLE_ICON);\n showSpinner(this.spinnerElement);\n }\n };\n /**\n * Hides the spinner loader.\n * @returns void.\n */\n MultiSelect.prototype.hideSpinner = function () {\n if (!isNullOrUndefined(this.spinnerElement)) {\n hideSpinner(this.spinnerElement);\n removeClass([this.spinnerElement], DISABLE_ICON);\n if (this.spinnerElement.classList.contains(SPINNER_CLASS)) {\n detach(this.spinnerElement);\n }\n else {\n this.spinnerElement.innerHTML = '';\n }\n this.spinnerElement = null;\n }\n };\n MultiSelect.prototype.updateDelimView = function () {\n if (this.delimiterWrapper) {\n this.hideDelimWrapper();\n }\n if (this.chipCollectionWrapper) {\n this.chipCollectionWrapper.style.display = 'none';\n }\n this.viewWrapper.style.display = '';\n if (this.value && this.value.length) {\n var data = '';\n var temp = void 0;\n var tempData = void 0;\n var tempIndex = 1;\n var wrapperleng = void 0;\n var remaining = void 0;\n this.viewWrapper.innerHTML = '';\n var l10nLocale = {\n noRecordsTemplate: 'No Records Found',\n actionFailureTemplate: 'The Request Failed',\n overflowCountTemplate: '+${count} more..'\n };\n var l10n = new L10n('dropdowns', l10nLocale, this.locale);\n var remainContent = l10n.getConstant('overflowCountTemplate');\n var raminElement = this.createElement('span', {\n className: REMAIN_WRAPPER\n });\n var compiledString = compile(remainContent);\n raminElement.appendChild(compiledString({ 'count': this.value.length })[0]);\n this.viewWrapper.appendChild(raminElement);\n var remainSize = raminElement.offsetWidth;\n remove(raminElement);\n this.viewWrapper.innerHTML = '';\n var inputleng = this.searchWrapper.offsetWidth;\n var overAllContainer = parseInt(window.getComputedStyle(this.componentWrapper).width, 10) -\n parseInt(window.getComputedStyle(this.componentWrapper).paddingLeft, 10) -\n parseInt(window.getComputedStyle(this.componentWrapper).paddingRight, 10);\n var remainValue = void 0;\n if (!isNullOrUndefined(this.value)) {\n for (var index = 0; !isNullOrUndefined(this.value[index]); index++) {\n data += (index === 0) ? '' : this.delimiterChar + ' ';\n if (this.mainData && this.mainData.length) {\n if (this.mode === 'CheckBox') {\n remainValue = 110;\n var newTemp = this.listData;\n this.listData = this.mainData;\n temp = this.getTextByValue(this.value[index]);\n this.listData = newTemp;\n }\n else {\n remainValue = 0;\n temp = this.getTextByValue(this.value[index]);\n }\n }\n else {\n temp = this.value[index];\n }\n data += temp;\n temp = this.viewWrapper.innerHTML;\n this.viewWrapper.innerHTML = data;\n wrapperleng = this.viewWrapper.offsetWidth;\n if ((wrapperleng) > overAllContainer - remainValue) {\n if (tempData !== undefined) {\n temp = tempData;\n index = tempIndex + 1;\n }\n this.viewWrapper.innerHTML = temp;\n remaining = this.value.length - index;\n break;\n }\n else if ((wrapperleng + remainSize) <= overAllContainer) {\n tempData = data;\n tempIndex = index;\n }\n else if (index === 0) {\n tempData = '';\n tempIndex = -1;\n }\n }\n }\n if (remaining > 0) {\n raminElement.innerHTML = '';\n raminElement.appendChild(compiledString({ 'count': remaining })[0]);\n this.viewWrapper.appendChild(raminElement);\n }\n }\n else {\n this.viewWrapper.innerHTML = '';\n this.viewWrapper.style.display = 'none';\n }\n };\n MultiSelect.prototype.unWireEvent = function () {\n EventHandler.remove(this.componentWrapper, 'mousedown', this.wrapperClick);\n EventHandler.remove(window, 'resize', this.windowResize);\n EventHandler.remove(this.inputElement, 'focus', this.focusIn);\n EventHandler.remove(this.inputElement, 'keydown', this.onKeyDown);\n if (this.mode !== 'CheckBox') {\n EventHandler.remove(this.inputElement, 'input', this.onInput);\n }\n EventHandler.remove(this.inputElement, 'keyup', this.KeyUp);\n var formElement = closest(this.inputElement, 'form');\n if (formElement) {\n EventHandler.remove(formElement, 'reset', this.resetValueHandler);\n }\n EventHandler.remove(this.inputElement, 'blur', this.onBlur);\n EventHandler.remove(this.componentWrapper, 'mousemove', this.mouseIn);\n EventHandler.remove(this.componentWrapper, 'mouseout', this.mouseOut);\n EventHandler.remove(this.overAllClear, 'mousedown', this.ClearAll);\n };\n MultiSelect.prototype.selectAllItem = function (state) {\n var li;\n li = this.list.querySelectorAll(state ?\n 'li.e-list-item:not([aria-selected=\"true\"]):not(.e-reorder-hide)' :\n 'li[aria-selected=\"true\"]:not(.e-reorder-hide)');\n var length = li.length;\n if (li && li.length) {\n while (length > 0) {\n this.updateListSelection(li[length - 1], null, length);\n length--;\n }\n }\n if (this.mode !== 'Box' && !this.isPopupOpen()) {\n this.updateDelimView();\n }\n else {\n this.searchWrapper.classList.remove(ZERO_SIZE);\n }\n if (this.mode === 'CheckBox') {\n this.updateDelimView();\n this.refreshInputHight();\n this.updateDelimeter(this.delimiterChar);\n }\n else {\n this.updateDelimeter(this.delimiterChar);\n }\n this.refreshPlaceHolder();\n };\n MultiSelect.prototype.setZIndex = function () {\n if (this.popupObj) {\n this.popupObj.setProperties({ 'zIndex': this.zIndex });\n }\n };\n MultiSelect.prototype.updateDataSource = function (prop) {\n if (isNullOrUndefined(this.list)) {\n this.renderPopup();\n }\n else {\n this.resetList(this.dataSource);\n }\n if (this.value && this.value.length) {\n this.refreshSelection();\n }\n };\n MultiSelect.prototype.onLoadSelect = function () {\n this.setDynValue = true;\n this.renderPopup();\n };\n /**\n * Get the properties to be maintained in the persisted state.\n */\n MultiSelect.prototype.getPersistData = function () {\n return this.addOnPersist(['value']);\n };\n ;\n /**\n * Dynamically change the value of properties.\n * @private\n */\n MultiSelect.prototype.onPropertyChanged = function (newProp, oldProp) {\n if (newProp.dataSource && !isNullOrUndefined(Object.keys(newProp.dataSource))) {\n this.mainList = null;\n this.mainData = null;\n }\n this.setUpdateInitial(['query', 'dataSource'], newProp);\n for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {\n var prop = _a[_i];\n switch (prop) {\n case 'query':\n case 'dataSource':\n if (this.mode === 'CheckBox' && this.showSelectAll) {\n if (!isNullOrUndefined(this.popupObj)) {\n this.popupObj.destroy();\n this.popupObj = null;\n }\n this.renderPopup();\n }\n break;\n case 'htmlAttributes':\n this.updateHTMLAttribute();\n break;\n case 'showClearButton':\n this.updateClearButton(newProp.showClearButton);\n break;\n case 'value':\n if (!this.list) {\n this.onLoadSelect();\n }\n else if (!this.inputFocus) {\n this.initialValueUpdate();\n if (this.mode !== 'Box') {\n this.updateDelimView();\n }\n this.refreshInputHight();\n this.refreshPlaceHolder();\n this.updateValueState(null, this.value, oldProp.value);\n }\n break;\n case 'width':\n setStyleAttribute(this.overAllWrapper, { 'width': formatUnit(newProp.width) });\n this.popupObj.setProperties({ width: this.calcPopupWidth() });\n break;\n case 'placeholder':\n this.refreshPlaceHolder();\n break;\n case 'filterBarPlaceholder':\n this.notify('filterBarPlaceholder', { filterBarPlaceholder: newProp.filterBarPlaceholder });\n break;\n case 'delimiterChar':\n if (this.mode !== 'Box') {\n this.updateDelimView();\n }\n this.updateData(newProp.delimiterChar);\n break;\n case 'cssClass':\n this.popupWrapper.classList.remove(oldProp.cssClass);\n this.overAllWrapper.classList.remove(oldProp.cssClass);\n this.updateCssClass();\n break;\n case 'enableRtl':\n this.enableRTL(newProp.enableRtl);\n _super.prototype.onPropertyChanged.call(this, newProp, oldProp);\n break;\n case 'readonly':\n this.updateReadonly(newProp.readonly);\n this.hidePopup();\n break;\n case 'enabled':\n this.hidePopup();\n this.enable(newProp.enabled);\n break;\n case 'showSelectAll':\n if (this.popupObj) {\n this.popupObj.destroy();\n this.popupObj = null;\n }\n this.renderPopup();\n break;\n case 'showDropDownIcon':\n this.dropDownIcon();\n break;\n case 'floatLabelType':\n this.setFloatLabelType();\n break;\n case 'enableSelectionOrder':\n break;\n case 'selectAllText':\n this.notify('selectAllText', false);\n break;\n case 'popupHeight':\n case 'headerTemplate':\n case 'footerTemplate':\n if (this.popupObj) {\n this.popupObj.destroy();\n this.popupObj = null;\n }\n this.renderPopup();\n break;\n default:\n var msProps = void 0;\n msProps = this.getPropObject(prop, newProp, oldProp);\n _super.prototype.onPropertyChanged.call(this, msProps.newProperty, msProps.oldProperty);\n break;\n }\n }\n };\n /**\n * Hides the popup, if the popup in a open state.\n * @returns void\n */\n MultiSelect.prototype.hidePopup = function () {\n var delay = 100;\n if (this.isPopupOpen()) {\n var animModel = {\n name: 'FadeOut',\n duration: 100,\n delay: delay ? delay : 0\n };\n var eventArgs = { popup: this.popupObj, cancel: false, animation: animModel };\n this.trigger('close', eventArgs);\n if (eventArgs.cancel) {\n return;\n }\n this.beforePopupOpen = false;\n this.overAllWrapper.classList.remove(iconAnimation);\n this.popupObj.hide(new Animation(eventArgs.animation));\n attributes(this.inputElement, { 'aria-expanded': 'false' });\n this.notify('inputFocus', { module: 'CheckBoxSelection', enable: this.mode === 'CheckBox', value: 'clear' });\n this.popupObj.hide();\n removeClass([document.body, this.popupObj.element], 'e-popup-full-page');\n }\n };\n /**\n * Shows the popup, if the popup in a closed state.\n * @returns void\n */\n MultiSelect.prototype.showPopup = function () {\n if (!this.enabled) {\n return;\n }\n if (!this.ulElement) {\n this.beforePopupOpen = true;\n _super.prototype.render.call(this);\n return;\n }\n var mainLiLength = this.ulElement.querySelectorAll('li.' + 'e-list-item').length;\n var liLength = this.ulElement.querySelectorAll('li.'\n + dropDownBaseClasses.li + '.' + HIDE_LIST).length;\n if (mainLiLength > 0 && (mainLiLength === liLength) && (liLength === this.mainData.length)) {\n this.beforePopupOpen = false;\n return;\n }\n this.onPopupShown();\n };\n /**\n * Based on the state parameter, entire list item will be selected/deselected.\n * parameter\n * `true` - Selects entire list items.\n * `false` - Un Selects entire list items.\n * @returns void\n */\n MultiSelect.prototype.selectAll = function (state) {\n var _this = this;\n if (isNullOrUndefined(this.list)) {\n this.selectAllAction = function () {\n if (_this.mode === 'CheckBox' && _this.showSelectAll) {\n var args = {\n module: 'CheckBoxSelection',\n enable: _this.mode === 'CheckBox',\n value: state ? 'check' : 'uncheck'\n };\n _this.notify('checkSelectAll', args);\n }\n _this.selectAllItem(state);\n _this.selectAllAction = null;\n };\n _super.prototype.render.call(this);\n }\n else {\n this.selectAllAction = null;\n if (this.mode === 'CheckBox' && this.showSelectAll) {\n var args = {\n module: 'CheckBoxSelection',\n enable: this.mode === 'CheckBox',\n value: state ? 'check' : 'uncheck'\n };\n this.notify('checkSelectAll', args);\n }\n this.selectAllItem(state);\n }\n };\n MultiSelect.prototype.getModuleName = function () {\n return 'multiselect';\n };\n ;\n /**\n * To Initialize the control rendering\n * @private\n */\n MultiSelect.prototype.render = function () {\n var _this = this;\n this.initStatus = false;\n this.setDynValue = false;\n this.searchWrapper = this.createElement('span', { className: SEARCHBOX_WRAPPER });\n this.viewWrapper = this.createElement('span', { className: DELIMITER_VIEW + ' ' + DELIMITER_WRAPPER, styles: 'display:none;' });\n var iconClass;\n this.overAllClear = this.createElement('span', {\n className: CLOSEICON_CLASS, styles: 'display:none;'\n });\n this.componentWrapper = this.createElement('div', { className: ELEMENT_WRAPPER });\n this.overAllWrapper = this.createElement('div', { className: OVER_ALL_WRAPPER });\n if (this.mode === 'CheckBox') {\n addClass([this.overAllWrapper], 'e-checkbox');\n }\n if (Browser.isDevice) {\n this.componentWrapper.classList.add(ELEMENT_MOBILE_WRAPPER);\n }\n this.overAllWrapper.style.width = formatUnit(this.width);\n this.overAllWrapper.appendChild(this.componentWrapper);\n this.popupWrapper = this.createElement('div', { id: this.element.id + '_popup', className: POPUP_WRAPPER });\n if (this.mode === 'Delimiter' || this.mode === 'CheckBox') {\n this.delimiterWrapper = this.createElement('span', { className: DELIMITER_WRAPPER, styles: 'display:none' });\n this.componentWrapper.appendChild(this.delimiterWrapper);\n }\n else {\n this.chipCollectionWrapper = this.createElement('span', {\n className: CHIP_WRAPPER,\n styles: 'display:none'\n });\n this.componentWrapper.appendChild(this.chipCollectionWrapper);\n }\n if (this.mode !== 'Box') {\n this.componentWrapper.appendChild(this.viewWrapper);\n }\n this.componentWrapper.appendChild(this.searchWrapper);\n if (this.showClearButton && !Browser.isDevice) {\n this.componentWrapper.appendChild(this.overAllClear);\n }\n else {\n this.componentWrapper.classList.add(CLOSE_ICON_HIDE);\n }\n this.dropDownIcon();\n this.inputElement = this.createElement('input', {\n className: INPUT_ELEMENT,\n attrs: {\n spellcheck: 'false',\n type: 'text',\n autocomplete: 'off',\n tabindex: '0'\n }\n });\n if (this.element.tagName !== this.getNgDirective()) {\n this.element.style.display = 'none';\n }\n if (this.element.tagName === this.getNgDirective()) {\n this.element.appendChild(this.overAllWrapper);\n this.searchWrapper.appendChild(this.inputElement);\n }\n else {\n this.element.parentElement.insertBefore(this.overAllWrapper, this.element);\n this.searchWrapper.appendChild(this.inputElement);\n this.searchWrapper.appendChild(this.element);\n this.element.removeAttribute('tabindex');\n }\n if (this.floatLabelType !== 'Never') {\n createFloatLabel(this.overAllWrapper, this.searchWrapper, this.element, this.inputElement, this.value, this.floatLabelType, this.placeholder);\n }\n else if (this.floatLabelType === 'Never') {\n this.refreshPlaceHolder();\n }\n this.element.style.opacity = '';\n var id = this.element.getAttribute('id') ? this.element.getAttribute('id') : getUniqueID('ej2_dropdownlist');\n this.element.id = id;\n this.hiddenElement = this.createElement('select', {\n attrs: { 'aria-hidden': 'true', 'class': HIDDEN_ELEMENT, 'tabindex': '-1', 'multiple': 'true' }\n });\n this.componentWrapper.appendChild(this.hiddenElement);\n this.validationAttribute(this.element, this.hiddenElement);\n if (this.mode !== 'CheckBox') {\n this.hideOverAllClear();\n }\n this.wireEvent();\n this.enable(this.enabled);\n this.enableRTL(this.enableRtl);\n if (this.value && this.value.length) {\n this.renderPopup();\n if (!(this.dataSource instanceof DataManager)) {\n this.initialValueUpdate();\n this.initialUpdate();\n }\n else {\n this.setInitialValue = function () {\n _this.initStatus = false;\n _this.initialValueUpdate();\n _this.initialUpdate();\n _this.setInitialValue = null;\n _this.initStatus = true;\n };\n }\n }\n else {\n this.initialUpdate();\n }\n this.initStatus = true;\n this.checkAutoFocus();\n };\n MultiSelect.prototype.checkAutoFocus = function () {\n if (this.element.hasAttribute('autofocus')) {\n this.focusIn();\n }\n };\n MultiSelect.prototype.setFloatLabelType = function () {\n removeFloating(this.overAllWrapper, this.componentWrapper, this.searchWrapper, this.inputElement, this.value, this.floatLabelType, this.placeholder);\n if (this.floatLabelType !== 'Never') {\n createFloatLabel(this.overAllWrapper, this.searchWrapper, this.element, this.inputElement, this.value, this.floatLabelType, this.placeholder);\n }\n };\n MultiSelect.prototype.dropDownIcon = function () {\n if (this.mode === 'CheckBox' && this.showDropDownIcon) {\n this.dropIcon = this.createElement('span', { className: dropdownIcon });\n this.componentWrapper.appendChild(this.dropIcon);\n addClass([this.componentWrapper], ['e-down-icon']);\n }\n else {\n if (!isNullOrUndefined(this.dropIcon)) {\n this.dropIcon.parentElement.removeChild(this.dropIcon);\n removeClass([this.componentWrapper], ['e-down-icon']);\n }\n }\n };\n MultiSelect.prototype.initialUpdate = function () {\n if (this.mode !== 'Box') {\n this.updateDelimView();\n }\n this.updateCssClass();\n this.updateHTMLAttribute();\n this.updateReadonly(this.readonly);\n this.refreshInputHight();\n };\n /**\n * Removes the component from the DOM and detaches all its related event handlers. Also it removes the attributes and classes.\n * @method destroy\n * @return {void}\n */\n MultiSelect.prototype.destroy = function () {\n if (this.popupObj) {\n this.popupObj.hide();\n }\n this.notify(destroy, {});\n this.unwireListEvents();\n this.unWireEvent();\n this.list = null;\n this.popupObj = null;\n this.mainList = null;\n this.mainData = null;\n _super.prototype.destroy.call(this);\n var temp = ['readonly', 'aria-disabled', 'aria-placeholder', 'placeholder'];\n var length = temp.length;\n while (length > 0) {\n this.inputElement.removeAttribute(temp[length - 1]);\n length--;\n }\n this.element.style.display = 'block';\n if (this.overAllWrapper.parentElement) {\n if (this.overAllWrapper.parentElement.tagName === this.getNgDirective()) {\n remove(this.overAllWrapper);\n }\n else {\n this.overAllWrapper.parentElement.insertBefore(this.element, this.overAllWrapper);\n remove(this.overAllWrapper);\n }\n }\n };\n ;\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"cssClass\", void 0);\n __decorate([\n Property('100%')\n ], MultiSelect.prototype, \"width\", void 0);\n __decorate([\n Property('300px')\n ], MultiSelect.prototype, \"popupHeight\", void 0);\n __decorate([\n Property('100%')\n ], MultiSelect.prototype, \"popupWidth\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"placeholder\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"filterBarPlaceholder\", void 0);\n __decorate([\n Property({})\n ], MultiSelect.prototype, \"htmlAttributes\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"valueTemplate\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"headerTemplate\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"footerTemplate\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"itemTemplate\", void 0);\n __decorate([\n Property(false)\n ], MultiSelect.prototype, \"allowFiltering\", void 0);\n __decorate([\n Property(false)\n ], MultiSelect.prototype, \"allowCustomValue\", void 0);\n __decorate([\n Property(true)\n ], MultiSelect.prototype, \"showClearButton\", void 0);\n __decorate([\n Property(1000)\n ], MultiSelect.prototype, \"maximumSelectionLength\", void 0);\n __decorate([\n Property(false)\n ], MultiSelect.prototype, \"readonly\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"text\", void 0);\n __decorate([\n Property(null)\n ], MultiSelect.prototype, \"value\", void 0);\n __decorate([\n Property(true)\n ], MultiSelect.prototype, \"hideSelectedItem\", void 0);\n __decorate([\n Property(true)\n ], MultiSelect.prototype, \"closePopupOnSelect\", void 0);\n __decorate([\n Property('Default')\n ], MultiSelect.prototype, \"mode\", void 0);\n __decorate([\n Property(',')\n ], MultiSelect.prototype, \"delimiterChar\", void 0);\n __decorate([\n Property(true)\n ], MultiSelect.prototype, \"ignoreCase\", void 0);\n __decorate([\n Property(false)\n ], MultiSelect.prototype, \"showDropDownIcon\", void 0);\n __decorate([\n Property('Never')\n ], MultiSelect.prototype, \"floatLabelType\", void 0);\n __decorate([\n Property(false)\n ], MultiSelect.prototype, \"showSelectAll\", void 0);\n __decorate([\n Property('Select All')\n ], MultiSelect.prototype, \"selectAllText\", void 0);\n __decorate([\n Property('Unselect All')\n ], MultiSelect.prototype, \"unSelectAllText\", void 0);\n __decorate([\n Property(true)\n ], MultiSelect.prototype, \"enableSelectionOrder\", void 0);\n __decorate([\n Property(true)\n ], MultiSelect.prototype, \"openOnClick\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"change\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"removing\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"removed\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"selectedAll\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"beforeOpen\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"open\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"close\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"blur\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"focus\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"chipSelection\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"filtering\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"tagging\", void 0);\n __decorate([\n Event()\n ], MultiSelect.prototype, \"customValueSelection\", void 0);\n MultiSelect = __decorate([\n NotifyPropertyChanges\n ], MultiSelect);\n return MultiSelect;\n}(DropDownBase));\nexport { MultiSelect };\n","import { createCheckBox } from '@syncfusion/ej2-buttons';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { EventHandler, select, removeClass, addClass, detach, compile, L10n } from '@syncfusion/ej2-base';\nimport { Browser, attributes, isNullOrUndefined, append, closest, prepend } from '@syncfusion/ej2-base';\nimport { dropDownBaseClasses } from '../drop-down-base/drop-down-base';\nvar ICON = 'e-icons';\nvar CHECKBOXFRAME = 'e-frame';\nvar CHECK = 'e-check';\nvar CHECKBOXWRAP = 'e-checkbox-wrapper';\nvar CHECKBOXRIPPLE = 'e-ripple-container';\nvar INDETERMINATE = 'e-stop';\nvar checkAllParent = 'e-selectall-parent';\nvar searchBackIcon = 'e-input-group-icon e-back-icon e-icons';\nvar filterBarClearIcon = 'e-input-group-icon e-clear-icon e-icons';\nvar filterInput = 'e-input-filter';\nvar filterParent = 'e-filter-parent';\nvar mobileFilter = 'e-ddl-device-filter';\nvar clearIcon = 'e-clear-icon';\nvar popupFullScreen = 'e-popup-full-page';\nvar device = 'e-ddl-device';\nvar FOCUS = 'e-input-focus';\n/**\n * The Multiselect enable CheckBoxSelection call this inject module.\n */\nvar CheckBoxSelection = /** @class */ (function () {\n function CheckBoxSelection(parent) {\n this.activeLi = [];\n this.activeEle = [];\n this.parent = parent;\n this.addEventListener();\n }\n CheckBoxSelection.prototype.getModuleName = function () {\n return 'CheckBoxSelection';\n };\n CheckBoxSelection.prototype.addEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on('updatelist', this.listSelection, this);\n this.parent.on('listoption', this.listOption, this);\n this.parent.on('selectAll', this.setSelectAll, this);\n this.parent.on('checkSelectAll', this.checkSelectAll, this);\n this.parent.on('searchBox', this.setSearchBox, this);\n this.parent.on('blur', this.onBlur, this);\n this.parent.on('targetElement', this.targetElement, this);\n this.parent.on('deviceSearchBox', this.setDeviceSearchBox, this);\n this.parent.on('inputFocus', this.getFocus, this);\n this.parent.on('reOrder', this.setReorder, this);\n this.parent.on('activeList', this.getActiveList, this);\n this.parent.on('selectAllText', this.setLocale, this);\n this.parent.on('filterBarPlaceholder', this.setPlaceholder, this);\n EventHandler.add(document, 'mousedown', this.onDocumentClick, this);\n };\n CheckBoxSelection.prototype.removeEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off('updatelist', this.listSelection);\n this.parent.off('listoption', this.listOption);\n this.parent.off('selectAll', this.setSelectAll);\n this.parent.off('checkSelectAll', this.checkSelectAll);\n this.parent.off('searchBox', this.setSearchBox);\n this.parent.off('blur', this.onBlur);\n this.parent.off('targetElement', this.targetElement);\n this.parent.off('deviceSearchBox', this.setDeviceSearchBox);\n this.parent.off('inputFocus', this.getFocus);\n this.parent.off('reOrder', this.setReorder);\n this.parent.off('activeList', this.getActiveList);\n this.parent.off('selectAllText', this.setLocale);\n this.parent.off('filterBarPlaceholder', this.setPlaceholder);\n EventHandler.remove(document, 'mousedown', this.onDocumentClick);\n };\n CheckBoxSelection.prototype.listOption = function (args) {\n var _this = this;\n if (isNullOrUndefined(this.parent.listCurrentOptions.itemCreated)) {\n this.parent.listCurrentOptions.itemCreated = function (e) {\n _this.checboxCreate(e);\n };\n }\n else {\n var itemCreated_1 = this.parent.listCurrentOptions.itemCreated;\n this.parent.listCurrentOptions.itemCreated = function (e) {\n _this.checboxCreate(e);\n itemCreated_1.apply(_this, [e]);\n };\n }\n };\n ;\n CheckBoxSelection.prototype.setPlaceholder = function (props) {\n Input.setPlaceholder(props.filterBarPlaceholder, this.filterInput);\n };\n CheckBoxSelection.prototype.checboxCreate = function (e) {\n var item;\n if (!isNullOrUndefined(e.item)) {\n item = e.item;\n }\n else {\n item = e;\n }\n if (item.className !== 'e-list-group-item ' && item.className !== 'e-list-group-item') {\n var checkboxEle = createCheckBox(this.parent.createElement, true);\n var icon = select('div.' + ICON, item);\n var id = item.getAttribute('data-uid');\n item.insertBefore(checkboxEle, item.childNodes[isNullOrUndefined(icon) ? 0 : 1]);\n select('.' + CHECKBOXFRAME, checkboxEle);\n var frame = select('.' + CHECKBOXFRAME, checkboxEle);\n return item;\n }\n else {\n return item;\n }\n };\n CheckBoxSelection.prototype.setSelectAll = function () {\n if (this.parent.showSelectAll) {\n if (isNullOrUndefined(this.checkAllParent)) {\n this.checkAllParent = this.parent.createElement('div', {\n className: checkAllParent\n });\n this.selectAllSpan = this.parent.createElement('span', {\n className: 'e-all-text'\n });\n this.selectAllSpan.textContent = '';\n this.checkAllParent.appendChild(this.selectAllSpan);\n this.setLocale();\n this.checboxCreate(this.checkAllParent);\n if (this.parent.headerTemplate) {\n if (!isNullOrUndefined(this.filterParent)) {\n append([this.checkAllParent], this.filterParent);\n }\n else {\n append([this.checkAllParent], this.parent.popupWrapper);\n }\n }\n if (!this.parent.headerTemplate) {\n if (!isNullOrUndefined(this.filterParent)) {\n append([this.checkAllParent], this.filterParent);\n }\n else {\n prepend([this.checkAllParent], this.parent.popupWrapper);\n }\n }\n EventHandler.add(this.checkAllParent, 'mousedown', this.clickHandler, this);\n }\n if (this.parent.list.classList.contains('e-nodata')) {\n this.checkAllParent.style.display = 'none';\n }\n else {\n this.checkAllParent.style.display = 'block';\n }\n this.parent.selectAllHeight = this.checkAllParent.getBoundingClientRect().height;\n }\n else if (!isNullOrUndefined(this.checkAllParent)) {\n this.checkAllParent.parentElement.removeChild(this.checkAllParent);\n this.checkAllParent = null;\n }\n };\n CheckBoxSelection.prototype.destroy = function () {\n this.removeEventListener();\n };\n CheckBoxSelection.prototype.listSelection = function (args) {\n var target;\n if (!isNullOrUndefined(args.e)) {\n target = !isNullOrUndefined(args.e.target) ?\n args.e.target.classList.contains('e-frame') ?\n args.e.target : args.li.querySelector('.e-checkbox-wrapper').childNodes[1]\n : args.li.querySelector('.e-checkbox-wrapper').childNodes[1];\n }\n else {\n target = args.li.lastElementChild.childNodes[1];\n }\n if (this.parent.itemTemplate) {\n target = args.li.firstElementChild.childNodes[1];\n }\n this.checkWrapper = closest(target, '.' + CHECKBOXWRAP);\n if (!isNullOrUndefined(this.checkWrapper)) {\n var checkElement = select('.' + CHECKBOXFRAME, this.checkWrapper);\n var selectAll = false;\n this.validateCheckNode(this.checkWrapper, checkElement.classList.contains(CHECK), args.li, args.e, selectAll);\n }\n };\n CheckBoxSelection.prototype.validateCheckNode = function (checkWrap, isCheck, li, e, selectAll) {\n this.changeState(checkWrap, isCheck ? 'uncheck' : 'check', e, true, selectAll);\n };\n CheckBoxSelection.prototype.clickHandler = function (e) {\n var target;\n if (e.currentTarget.classList.contains(this.checkAllParent.className)) {\n target = e.currentTarget.firstElementChild.lastElementChild;\n }\n else {\n target = e.currentTarget;\n }\n this.checkWrapper = closest(target, '.' + CHECKBOXWRAP);\n var selectAll = true;\n if (!isNullOrUndefined(this.checkWrapper)) {\n var checkElement = select('.' + CHECKBOXFRAME, this.checkWrapper);\n this.validateCheckNode(this.checkWrapper, checkElement.classList.contains(CHECK), null, e, selectAll);\n }\n e.preventDefault();\n };\n CheckBoxSelection.prototype.changeState = function (wrapper, state, e, isPrevent, selectAll) {\n var ariaState;\n var frameSpan = wrapper.getElementsByClassName(CHECKBOXFRAME)[0];\n if (state === 'check' && !frameSpan.classList.contains(CHECK)) {\n frameSpan.classList.remove(INDETERMINATE);\n frameSpan.classList.add(CHECK);\n ariaState = 'true';\n if (selectAll) {\n this.parent.selectAll(true);\n this.setLocale(true);\n }\n }\n else if (state === 'uncheck' && (frameSpan.classList.contains(CHECK) || frameSpan.classList.contains(INDETERMINATE))) {\n removeClass([frameSpan], [CHECK, INDETERMINATE]);\n ariaState = 'false';\n if (selectAll) {\n this.parent.selectAll(false);\n this.setLocale();\n }\n }\n ariaState = state === 'check' ? 'true' : state === 'uncheck' ? 'false' : ariaState;\n if (!isNullOrUndefined(ariaState)) {\n wrapper.setAttribute('aria-checked', ariaState);\n }\n };\n CheckBoxSelection.prototype.setSearchBox = function (args) {\n if (isNullOrUndefined(this.filterParent)) {\n this.filterParent = this.parent.createElement('span', {\n className: filterParent\n });\n this.filterInput = this.parent.createElement('input', {\n attrs: { type: 'text' },\n className: filterInput\n });\n this.parent.element.parentNode.insertBefore(this.filterInput, this.parent.element);\n var backIcon = false;\n if (Browser.isDevice) {\n backIcon = true;\n this.parent.mobFilter = false;\n }\n this.filterInputObj = Input.createInput({\n element: this.filterInput,\n buttons: backIcon ? [searchBackIcon, filterBarClearIcon] : [filterBarClearIcon],\n properties: { placeholder: this.parent.filterBarPlaceholder }\n }, this.parent.createElement);\n append([this.filterInputObj.container], this.filterParent);\n prepend([this.filterParent], args.popupElement);\n attributes(this.filterInput, {\n 'aria-disabled': 'false',\n 'aria-owns': this.parent.element.id + '_options',\n 'role': 'listbox',\n 'aria-activedescendant': null,\n 'autocomplete': 'off',\n 'autocorrect': 'off',\n 'autocapitalize': 'off',\n 'spellcheck': 'false'\n });\n this.clearIconElement = this.filterInput.parentElement.querySelector('.' + clearIcon);\n if (!Browser.isDevice && this.clearIconElement) {\n EventHandler.add(this.clearIconElement, 'mousedown', this.clearText, this);\n this.clearIconElement.style.visibility = 'hidden';\n }\n EventHandler.add(this.filterInput, 'input', this.parent.onInput, this.parent);\n EventHandler.add(this.filterInput, 'keyup', this.parent.KeyUp, this.parent);\n EventHandler.add(this.filterInput, 'keydown', this.parent.onKeyDown, this.parent);\n EventHandler.add(this.filterInput, 'blur', this.onBlur, this);\n this.parent.searchBoxHeight = (this.filterInputObj.container.parentElement).getBoundingClientRect().height;\n return this.filterInputObj;\n }\n };\n ;\n CheckBoxSelection.prototype.clickOnBackIcon = function (e) {\n this.parent.hidePopup();\n removeClass([document.body, this.parent.popupObj.element], popupFullScreen);\n };\n CheckBoxSelection.prototype.clearText = function (e) {\n this.parent.targetInputElement.value = '';\n this.parent.refreshPopup();\n this.parent.refreshListItems(null);\n this.clearIconElement.style.visibility = 'hidden';\n this.filterInput.focus();\n this.setReorder(e);\n e.preventDefault();\n };\n CheckBoxSelection.prototype.setDeviceSearchBox = function () {\n this.parent.popupObj.element.classList.add(device);\n this.parent.popupObj.element.classList.add(mobileFilter);\n this.parent.popupObj.position = { X: 0, Y: 0 };\n this.parent.popupObj.dataBind();\n attributes(this.parent.popupObj.element, { style: 'left:0px;right:0px;top:0px;bottom:0px;' });\n addClass([document.body, this.parent.popupObj.element], popupFullScreen);\n this.setSearchBoxPosition();\n this.backIconElement = this.filterInputObj.container.querySelector('.e-back-icon');\n this.clearIconElement = this.filterInputObj.container.querySelector('.' + clearIcon);\n this.clearIconElement.style.visibility = 'hidden';\n EventHandler.add(this.backIconElement, 'click', this.clickOnBackIcon, this);\n EventHandler.add(this.clearIconElement, 'click', this.clearText, this);\n };\n CheckBoxSelection.prototype.setSearchBoxPosition = function () {\n var searchBoxHeight = this.filterInput.parentElement.getBoundingClientRect().height;\n this.parent.popupObj.element.style.maxHeight = '100%';\n this.parent.popupObj.element.style.width = '100%';\n this.parent.list.style.maxHeight = (window.innerHeight - searchBoxHeight) + 'px';\n this.parent.list.style.height = (window.innerHeight - searchBoxHeight) + 'px';\n var clearElement = this.filterInput.parentElement.querySelector('.' + clearIcon);\n detach(this.filterInput);\n clearElement.parentElement.insertBefore(this.filterInput, clearElement);\n };\n CheckBoxSelection.prototype.targetElement = function () {\n this.parent.targetInputElement = this.filterInput;\n this.clearIconElement.style.visibility = this.parent.targetInputElement.value === '' ? 'hidden' : 'visible';\n return this.parent.targetInputElement.value;\n };\n CheckBoxSelection.prototype.onBlur = function (e) {\n var target;\n if (Browser.isIE) {\n target = !isNullOrUndefined(e) && e.target;\n }\n if (!Browser.isIE) {\n target = !isNullOrUndefined(e) && e.relatedTarget;\n }\n if (document.body.contains(this.parent.popupObj.element) && this.parent.popupObj.element.contains(target) && !Browser.isIE) {\n this.filterInput.focus();\n return;\n }\n if (this.parent.scrollFocusStatus) {\n e.preventDefault();\n this.filterInput.focus();\n this.parent.scrollFocusStatus = false;\n return;\n }\n if (document.body.contains(this.parent.popupObj.element) && !this.parent.popupObj.element.classList.contains('e-popup-close')) {\n this.parent.inputFocus = false;\n this.parent.updateValueState(e, this.parent.value, this.parent.tempValues);\n this.parent.dispatchEvent(this.parent.hiddenElement, 'change');\n }\n if (document.body.contains(this.parent.popupObj.element) &&\n !this.parent.popupObj.element.classList.contains('e-popup-close')) {\n this.parent.inputFocus = false;\n this.parent.overAllWrapper.classList.remove(FOCUS);\n this.parent.trigger('blur');\n this.parent.focused = true;\n }\n if (document.body.contains(this.parent.popupObj.element) &&\n !this.parent.popupObj.element.classList.contains('e-popup-close') && !Browser.isDevice) {\n this.parent.hidePopup();\n }\n };\n CheckBoxSelection.prototype.onDocumentClick = function (e) {\n var target = e.target;\n if (!isNullOrUndefined(this.parent.popupObj) && closest(target, '#' + this.parent.popupObj.element.id)) {\n e.preventDefault();\n }\n if (!(!isNullOrUndefined(this.parent.popupObj) && closest(target, '#' + this.parent.popupObj.element.id)) &&\n !this.parent.overAllWrapper.contains(e.target)) {\n if (this.parent.overAllWrapper.classList.contains(dropDownBaseClasses.focus) || this.parent.isPopupOpen()) {\n this.parent.inputFocus = false;\n this.parent.hidePopup();\n this.parent.onBlur();\n this.parent.focused = true;\n }\n }\n else {\n this.parent.scrollFocusStatus = (Browser.isIE || Browser.info.name === 'edge') && (document.activeElement === this.filterInput);\n }\n if (!this.parent.overAllWrapper.contains(e.target) && this.parent.overAllWrapper.classList.contains('e-input-focus') &&\n !this.parent.isPopupOpen()) {\n this.parent.onBlur(e);\n }\n };\n CheckBoxSelection.prototype.getFocus = function (e) {\n this.parent.overAllWrapper.classList.remove(FOCUS);\n if (e.value === 'focus') {\n this.filterInput.focus();\n }\n if (e.value === 'clear') {\n this.filterInput.value = '';\n this.clearIconElement.style.visibility = 'hidden';\n }\n };\n CheckBoxSelection.prototype.checkSelectAll = function (e) {\n if (e.value === 'check' && this.checkAllParent.getAttribute('aria-checked') !== 'true') {\n this.changeState(this.checkAllParent, e.value, null, null, false);\n this.setLocale(true);\n }\n if (e.value === 'uncheck') {\n this.changeState(this.checkAllParent, e.value, null, null, false);\n this.setLocale();\n }\n };\n CheckBoxSelection.prototype.setLocale = function (unSelect) {\n if (this.parent.selectAllText !== 'Select All' || this.parent.unSelectAllText !== 'Unselect All') {\n var template = unSelect ? this.parent.unSelectAllText : this.parent.selectAllText;\n var compiledString = void 0;\n this.selectAllSpan.textContent = '';\n compiledString = compile(template);\n for (var _i = 0, _a = compiledString({}); _i < _a.length; _i++) {\n var item = _a[_i];\n this.selectAllSpan.textContent = item.textContent;\n }\n }\n else {\n var l10nLocale = { selectAllText: 'Select All', unSelectAllText: 'Unselect All' };\n var l10n = new L10n('dropdowns', l10nLocale, this.parent.locale);\n this.selectAllSpan.textContent = unSelect ? l10n.getConstant('unSelectAllText') : l10n.getConstant('selectAllText');\n }\n };\n CheckBoxSelection.prototype.getActiveList = function (args) {\n if (args.li.classList.contains('e-active')) {\n this.activeLi.push(args.li.cloneNode(true));\n }\n else {\n this.activeLi.splice(args.index, 1);\n }\n };\n CheckBoxSelection.prototype.setReorder = function (args) {\n if (this.parent.enableSelectionOrder && !isNullOrUndefined(this.parent.value)) {\n var activeLiCount = this.parent.ulElement.querySelectorAll('li.e-active').length;\n var remLi = void 0;\n var ulEle = this.parent.createElement('ul', {\n className: 'e-list-parent e-ul e-reorder'\n });\n var removeEle = this.parent.createElement('div');\n if (activeLiCount > 0) {\n append(this.parent.ulElement.querySelectorAll('li.e-active'), ulEle);\n remLi = this.parent.ulElement.querySelectorAll('li.e-active');\n addClass(remLi, 'e-reorder-hide');\n prepend([ulEle], this.parent.list);\n }\n this.parent.focusAtFirstListItem();\n }\n };\n return CheckBoxSelection;\n}());\nexport { CheckBoxSelection };\n","import { createElement, isNullOrUndefined, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { DropDownList } from '@syncfusion/ej2-dropdowns';\nimport { CheckBox } from '@syncfusion/ej2-buttons';\n/**\n * The Hyperlink dialog is used to insert or edit hyperlink at selection.\n */\n/* tslint:disable:max-line-length */\nvar HyperlinkDialog = /** @class */ (function () {\n /**\n * @private\n */\n function HyperlinkDialog(viewer) {\n var _this = this;\n this.displayText = '';\n this.navigationUrl = undefined;\n this.bookmarkDropdown = undefined;\n this.bookmarkCheckbox = undefined;\n this.bookmarks = [];\n /**\n * @private\n */\n this.onKeyUpOnUrlBox = function (event) {\n if (event.keyCode === 13) {\n if (_this.displayTextBox.value !== '' && _this.urlTextBox.value !== '') {\n _this.onInsertHyperlink();\n }\n return;\n }\n var selectedText = _this.owner.selection.text;\n var urlValue = _this.urlTextBox.value;\n if (urlValue.substring(0, 4).toLowerCase() === 'www.') {\n _this.urlTextBox.value = 'http://' + urlValue;\n }\n if (_this.displayText === '') {\n _this.displayTextBox.value = urlValue;\n }\n _this.enableOrDisableInsertButton();\n };\n /**\n * @private\n */\n this.onKeyUpOnDisplayBox = function () {\n _this.displayText = _this.displayTextBox.value;\n _this.enableOrDisableInsertButton();\n };\n /**\n * @private\n */\n this.onInsertButtonClick = function () {\n _this.onInsertHyperlink();\n };\n /**\n * @private\n */\n this.onCancelButtonClick = function () {\n _this.owner.dialog.hide();\n _this.clearValue();\n };\n /**\n * @private\n */\n this.loadHyperlinkDialog = function () {\n _this.owner.updateFocus();\n _this.bookmarks = [];\n for (var i = 0; i < _this.owner.bookmarks.keys.length; i++) {\n var bookmark = _this.owner.bookmarks.keys[i];\n if (bookmark.indexOf('_') !== 0) {\n _this.bookmarks.push(bookmark);\n }\n }\n var fieldBegin = _this.owner.selection.getHyperlinkField();\n if (!isNullOrUndefined(fieldBegin)) {\n if (!isNullOrUndefined(fieldBegin.fieldSeparator)) {\n var format = undefined;\n // tslint:disable-next-line:max-line-length\n var fieldObj = _this.owner.selection.getHyperlinkDisplayText(fieldBegin.fieldSeparator.line.paragraph, fieldBegin.fieldSeparator, fieldBegin.fieldEnd, false, format);\n _this.displayText = fieldObj.displayText;\n _this.displayTextBox.disabled = fieldObj.isNestedField;\n }\n _this.displayTextBox.value = _this.displayText;\n var link = _this.owner.selection.getLinkText(fieldBegin);\n _this.urlTextBox.value = _this.navigationUrl = link;\n _this.owner.dialog.header = _this.localObj.getConstant('Edit Hyperlink');\n }\n else {\n _this.displayText = _this.owner.selection.getText(true);\n if (_this.displayText !== '') {\n if (_this.displayText.indexOf(String.fromCharCode(65532)) !== -1 ||\n _this.displayText.indexOf('\\r') !== -1 && (_this.displayText.lastIndexOf('\\r') !== -1 &&\n _this.displayText.slice(0, -1).indexOf('\\r') !== -1)) {\n _this.displayTextBox.value = '<>';\n _this.displayTextBox.disabled = true;\n }\n else {\n _this.displayTextBox.value = _this.displayText;\n }\n }\n }\n _this.bookmarkDiv.style.display = 'none';\n _this.addressText.style.display = 'block';\n _this.urlTextBox.style.display = 'block';\n _this.bookmarkCheckbox.checked = false;\n _this.bookmarkDropdown.dataSource = _this.owner.bookmarks.keys;\n _this.insertButton = document.getElementsByClassName('e-hyper-insert')[0];\n _this.enableOrDisableInsertButton();\n _this.urlTextBox.focus();\n if (_this.owner.selection.caret.style.display !== 'none') {\n _this.owner.selection.caret.style.display = 'none';\n }\n };\n /**\n * @private\n */\n this.closeHyperlinkDialog = function () {\n _this.clearValue();\n _this.owner.updateFocus();\n };\n /* tslint:disable:no-any */\n this.onUseBookmarkChange = function (args) {\n if (args.checked) {\n _this.bookmarkDiv.style.display = 'block';\n _this.bookmarkDropdown.dataSource = _this.bookmarks;\n _this.addressText.style.display = 'none';\n _this.urlTextBox.style.display = 'none';\n }\n else {\n _this.bookmarkDiv.style.display = 'none';\n _this.addressText.style.display = 'block';\n _this.urlTextBox.style.display = 'block';\n }\n };\n this.onBookmarkchange = function (args) {\n if (_this.bookmarkDropdown.value !== '') {\n _this.insertButton.disabled = false;\n }\n };\n this.owner = viewer;\n }\n /**\n * @private\n */\n HyperlinkDialog.prototype.getModuleName = function () {\n return 'HyperlinkDialog';\n };\n /**\n * @private\n */\n HyperlinkDialog.prototype.initHyperlinkDialog = function (localValue) {\n var instance = this;\n var id = this.owner.owner.containerId + '_insert_hyperlink';\n this.target = createElement('div', { id: id, className: 'e-de-hyperlink' });\n var container = createElement('div');\n var displayText = createElement('div', { className: 'e-de-hyperlink-dlg-title', innerHTML: localValue.getConstant('Text to display') });\n this.displayTextBox = createElement('input', { id: this.owner.owner.containerId + '_display_text', className: 'e-input e-de-hyperlink-dlg-input' });\n this.displayTextBox.addEventListener('keyup', instance.onKeyUpOnDisplayBox);\n container.appendChild(displayText);\n container.appendChild(this.displayTextBox);\n this.addressText = createElement('div', { className: 'e-de-hyperlink-dlg-title', innerHTML: localValue.getConstant('Address') });\n this.urlTextBox = createElement('input', { id: this.owner.owner.containerId + '_url_text', className: 'e-input e-de-hyperlink-dlg-input', attrs: { autofocus: 'true' } });\n this.urlTextBox.addEventListener('input', instance.onKeyUpOnUrlBox);\n this.urlTextBox.addEventListener('keyup', instance.onKeyUpOnUrlBox);\n container.appendChild(this.addressText);\n container.appendChild(this.urlTextBox);\n this.bookmarkDiv = createElement('div', { styles: 'display:none;' });\n var bookmarkText = createElement('div', { className: 'e-de-hyperlink-dlg-title', innerHTML: localValue.getConstant('Bookmark') });\n var bookmarkTextElement = createElement('div', { className: 'e-de-hyperlink-dlg-bookmark' });\n // tslint:disable-next-line:max-line-length\n var bookmarkValue = createElement('input', { id: 'e-de-hyperlink-dlg-bookmark-value' });\n bookmarkTextElement.appendChild(bookmarkValue);\n // tslint:disable-next-line:max-line-length\n this.bookmarkDropdown = new DropDownList({ dataSource: [], change: this.onBookmarkchange, popupHeight: '230px', width: '230px', noRecordsTemplate: localValue.getConstant('No bookmarks found') });\n this.bookmarkDropdown.appendTo(bookmarkValue);\n this.bookmarkDiv.appendChild(bookmarkText);\n this.bookmarkDiv.appendChild(bookmarkTextElement);\n container.appendChild(this.bookmarkDiv);\n // tslint:disable-next-line:max-line-length\n var bookmarkCheckDiv = createElement('div', { className: 'e-de-hyperlink-bookmark-check e-de-hyperlink-dlg-title' });\n var bookmarkCheck = createElement('input', { attrs: { type: 'checkbox' }, id: this.target.id + '_bookmark', className: this.target.id + '_bookmarkcheck' });\n bookmarkCheckDiv.appendChild(bookmarkCheck);\n this.bookmarkCheckbox = new CheckBox({ label: localValue.getConstant('Use bookmarks'), change: this.onUseBookmarkChange });\n this.bookmarkCheckbox.appendTo(bookmarkCheck);\n container.appendChild(bookmarkCheckDiv);\n this.target.appendChild(container);\n };\n /**\n * @private\n */\n HyperlinkDialog.prototype.show = function () {\n this.localObj = new L10n('documenteditor', this.owner.owner.defaultLocale);\n this.localObj.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initHyperlinkDialog(this.localObj);\n }\n this.owner.dialog.header = this.localObj.getConstant('Insert Hyperlink');\n this.owner.dialog.height = 'auto';\n this.owner.dialog.width = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.buttons = [{\n click: this.onInsertButtonClick,\n buttonModel: { content: this.localObj.getConstant('Ok'), cssClass: 'e-flat e-hyper-insert', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: this.localObj.getConstant('Cancel'), cssClass: 'e-flat e-hyper-cancel' }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.beforeOpen = this.loadHyperlinkDialog;\n this.owner.dialog.close = this.closeHyperlinkDialog;\n this.owner.dialog.show();\n };\n /**\n * @private\n */\n HyperlinkDialog.prototype.hide = function () {\n this.closeHyperlinkDialog();\n };\n HyperlinkDialog.prototype.enableOrDisableInsertButton = function () {\n if (!isNullOrUndefined(this.insertButton)) {\n // tslint:disable-next-line:max-line-length\n this.insertButton.disabled = (this.urlTextBox.value === '' || this.displayTextBox.value === '');\n }\n };\n /**\n * @private\n */\n HyperlinkDialog.prototype.onInsertHyperlink = function () {\n var displayText = this.displayTextBox.value.trim();\n var address = this.urlTextBox.value.trim();\n var isBookmark = false;\n if (!isNullOrUndefined(this.bookmarkDropdown.value) && this.bookmarkDropdown.value !== '') {\n address = this.bookmarkDropdown.value;\n isBookmark = true;\n }\n if (address === '') {\n this.owner.dialog.hide();\n return;\n }\n if (displayText === '' && address !== '') {\n displayText = address;\n }\n else {\n displayText = this.displayTextBox.value;\n }\n if (!isNullOrUndefined(this.navigationUrl)) {\n this.owner.owner.editorModule.editHyperlink(this.owner.selection, address, displayText, isBookmark);\n }\n else {\n var remove = this.owner.selection.text !== displayText && !this.displayTextBox.disabled;\n this.owner.owner.editorModule.insertHyperlink(address, displayText, remove, isBookmark);\n }\n this.owner.dialog.hide();\n this.navigationUrl = undefined;\n };\n /* tslint:enable:no-any */\n /**\n * @private\n */\n HyperlinkDialog.prototype.clearValue = function () {\n this.displayTextBox.value = '';\n this.urlTextBox.value = '';\n this.displayText = '';\n this.displayTextBox.disabled = false;\n this.bookmarks = [];\n };\n /**\n * @private\n */\n HyperlinkDialog.prototype.destroy = function () {\n if (this.displayTextBox) {\n this.displayTextBox.innerHTML = '';\n this.displayTextBox = undefined;\n }\n if (this.urlTextBox) {\n this.urlTextBox.parentElement.removeChild(this.urlTextBox);\n this.urlTextBox = undefined;\n }\n this.owner = undefined;\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n this.target.innerHTML = '';\n this.target = undefined;\n }\n };\n return HyperlinkDialog;\n}());\nexport { HyperlinkDialog };\n","import { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { L10n, createElement, setCulture, isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * The Table dialog is used to insert table at selection.\n */\nvar TableDialog = /** @class */ (function () {\n /**\n * @private\n */\n function TableDialog(viewer) {\n var _this = this;\n /**\n * @private\n */\n this.keyUpInsertTable = function (event) {\n if (event.keyCode === 13) {\n if (_this.rowsCountBox.value !== '' && _this.columnsCountBox.value !== '') {\n _this.onInsertTableClick();\n }\n }\n };\n /**\n * @private\n */\n this.onCancelButtonClick = function () {\n _this.owner.dialog.hide();\n };\n /**\n * @private\n */\n this.onInsertTableClick = function () {\n var rowCount = _this.rowValueTextBox.value;\n var columnCount = _this.columnValueTexBox.value;\n if (!(isNullOrUndefined(rowCount) && isNullOrUndefined(columnCount))) {\n _this.owner.owner.editor.insertTable(rowCount, columnCount);\n }\n _this.owner.dialog.hide();\n };\n this.owner = viewer;\n }\n TableDialog.prototype.getModuleName = function () {\n return 'TableDialog';\n };\n /**\n * @private\n */\n TableDialog.prototype.initTableDialog = function (localValue) {\n var instance = this;\n var id = this.owner.owner.containerId + '_insert_Table';\n this.target = createElement('div', { id: id, className: 'e-de-insert-table' });\n var parentDiv = createElement('div');\n var columnContainer = createElement('div', {\n className: 'e-de-insert-table-dlg-sub-header', innerHTML: localValue.getConstant('Number of columns')\n });\n var columnValue = createElement('div', { className: 'e-de-insert-table-dlg-input' });\n this.columnsCountBox = createElement('input', {\n attrs: { type: 'text' }, id: this.owner.owner.containerId + '_column'\n });\n columnValue.appendChild(this.columnsCountBox);\n var rowContainer = createElement('div', {\n className: 'e-de-insert-table-dlg-sub-header', innerHTML: localValue.getConstant('Number of rows')\n });\n var rowValue = createElement('div', { className: 'e-de-insert-table-dlg-input' });\n this.rowsCountBox = createElement('input', {\n attrs: { type: 'text' }, id: this.owner.owner.containerId + 'row'\n });\n rowValue.appendChild(this.rowsCountBox);\n parentDiv.appendChild(columnContainer);\n parentDiv.appendChild(columnValue);\n parentDiv.appendChild(rowContainer);\n parentDiv.appendChild(rowValue);\n this.target.appendChild(parentDiv);\n this.columnsCountBox.addEventListener('keyup', instance.keyUpInsertTable);\n this.rowsCountBox.addEventListener('keyup', instance.keyUpInsertTable);\n this.rowValueTextBox = new NumericTextBox({\n format: '#',\n value: 2,\n min: 1,\n max: 32767,\n enablePersistence: false\n });\n this.rowValueTextBox.appendTo(this.rowsCountBox);\n this.columnValueTexBox = new NumericTextBox({\n format: '#',\n value: 2,\n min: 1,\n max: 63,\n enablePersistence: false\n });\n this.columnValueTexBox.appendTo(this.columnsCountBox);\n };\n /**\n * @private\n */\n TableDialog.prototype.show = function () {\n var localValue = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localValue.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initTableDialog(localValue);\n }\n if (this.owner.selection.caret.style.display !== 'none') {\n this.owner.selection.caret.style.display = 'none';\n }\n this.owner.dialog.header = localValue.getConstant('Insert Table');\n this.owner.dialog.height = 'auto';\n this.owner.dialog.width = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = this.owner.updateFocus;\n this.owner.dialog.buttons = [{\n click: this.onInsertTableClick,\n buttonModel: { content: localValue.getConstant('Ok'), cssClass: 'e-flat e-table-ok', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: localValue.getConstant('Cancel'), cssClass: 'e-flat e-table-cancel' }\n }];\n this.rowValueTextBox.value = 2;\n this.columnValueTexBox.value = 2;\n this.owner.dialog.close = this.owner.updateFocus;\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n /**\n * @private\n */\n TableDialog.prototype.destroy = function () {\n if (this.columnsCountBox) {\n if (this.columnsCountBox.parentElement) {\n this.columnsCountBox.parentElement.removeChild(this.columnsCountBox);\n }\n this.columnsCountBox = undefined;\n }\n if (this.rowsCountBox) {\n if (this.rowsCountBox.parentElement) {\n this.rowsCountBox.parentElement.removeChild(this.rowsCountBox);\n }\n this.rowsCountBox = undefined;\n }\n if (this.columnValueTexBox) {\n this.columnValueTexBox.destroy();\n this.columnValueTexBox = undefined;\n }\n if (this.rowValueTextBox) {\n this.rowValueTextBox.destroy();\n this.rowValueTextBox = undefined;\n }\n this.columnsCountBox = undefined;\n this.rowsCountBox = undefined;\n this.owner = undefined;\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var i = 0; i < this.target.childNodes.length; i++) {\n this.target.removeChild(this.target.childNodes[i]);\n i--;\n }\n this.target = undefined;\n }\n };\n return TableDialog;\n}());\nexport { TableDialog };\n","import { ListView } from '@syncfusion/ej2-lists';\nimport { Button } from '@syncfusion/ej2-buttons';\nimport { createElement, L10n, setCulture } from '@syncfusion/ej2-base';\n/**\n * The Bookmark dialog is used to add, navigate or delete bookmarks.\n */\nvar BookmarkDialog = /** @class */ (function () {\n /**\n * @private\n */\n function BookmarkDialog(viewer) {\n var _this = this;\n this.addBookmark = function () {\n _this.owner.owner.editorModule.insertBookmark(_this.textBoxInput.value);\n _this.owner.dialog.hide();\n };\n /* tslint:disable:no-any */\n this.selectHandler = function (args) {\n _this.textBoxInput.value = args.text;\n /* tslint:disable:no-any */\n var value = document.getElementById('bookmark_text_box');\n value.setSelectionRange(0, args.text.length);\n value.focus();\n };\n this.gotoBookmark = function () {\n _this.owner.selection.selectBookmark(_this.textBoxInput.value);\n };\n this.deleteBookmark = function () {\n _this.owner.owner.editorModule.deleteBookmark(_this.textBoxInput.value);\n _this.show();\n };\n this.owner = viewer;\n }\n /**\n * @private\n */\n BookmarkDialog.prototype.getModuleName = function () {\n return 'BookmarkDialog';\n };\n /**\n * @private\n */\n BookmarkDialog.prototype.initBookmarkDialog = function (localValue, bookmarks) {\n var instance = this;\n var id = this.owner.owner.containerId + '_insert_bookmark';\n this.target = createElement('div', { id: id, className: 'e-de-bookmark' });\n var headerValue = localValue.getConstant('Bookmark name') + ':';\n var dlgFields = createElement('div', { innerHTML: headerValue, className: 'e-bookmark-dlgfields' });\n this.target.appendChild(dlgFields);\n var commonDiv = createElement('div', { className: 'e-bookmark-common' });\n this.target.appendChild(commonDiv);\n var searchDiv = createElement('div', { className: 'e-bookmark-list' });\n commonDiv.appendChild(searchDiv);\n var textBoxDiv = createElement('div', { className: 'e-bookmark-textboxdiv' });\n searchDiv.appendChild(textBoxDiv);\n // tslint:disable-next-line:max-line-length\n this.textBoxInput = createElement('input', { className: 'e-input e-bookmark-textbox-input', id: 'bookmark_text_box' });\n this.textBoxInput.setAttribute('type', 'text');\n textBoxDiv.appendChild(this.textBoxInput);\n var listviewDiv = createElement('div', { className: 'e-bookmark-listViewDiv', id: 'bookmark_listview' });\n searchDiv.appendChild(listviewDiv);\n var arts = this.owner.bookmarks.keys;\n this.listviewInstance = new ListView({\n dataSource: bookmarks,\n cssClass: 'e-bookmark-listview',\n });\n this.listviewInstance.appendTo(listviewDiv);\n this.listviewInstance.addEventListener('select', this.selectHandler);\n var buttonDiv = createElement('div', { className: 'e-bookmark-button' });\n commonDiv.appendChild(buttonDiv);\n var addbuttonDiv = createElement('div', { className: 'e-bookmark-addbutton' });\n buttonDiv.appendChild(addbuttonDiv);\n var addButtonElement = createElement('button', { innerHTML: 'Add', id: 'add' });\n addbuttonDiv.appendChild(addButtonElement);\n var addbutton = new Button({ cssClass: 'e-button-custom' });\n addbutton.appendTo(addButtonElement);\n addButtonElement.addEventListener('click', this.addBookmark);\n var deleteButtonDiv = createElement('div', { className: 'e-bookmark-deletebutton' });\n buttonDiv.appendChild(deleteButtonDiv);\n var deleteButtonElement = createElement('button', { innerHTML: 'Delete', id: 'delete' });\n deleteButtonDiv.appendChild(deleteButtonElement);\n var deletebutton = new Button({ cssClass: 'e-button-custom' });\n deletebutton.appendTo(deleteButtonElement);\n deleteButtonElement.addEventListener('click', this.deleteBookmark);\n var gotoButtonDiv = createElement('div', { className: 'e-bookmark-gotobutton' });\n buttonDiv.appendChild(gotoButtonDiv);\n var gotoButtonElement = createElement('button', { innerHTML: 'Go To', id: 'goto' });\n gotoButtonDiv.appendChild(gotoButtonElement);\n var gotobutton = new Button({ cssClass: 'e-button-custom' });\n gotobutton.appendTo(gotoButtonElement);\n gotoButtonElement.addEventListener('click', this.gotoBookmark);\n };\n /**\n * @private\n */\n BookmarkDialog.prototype.show = function () {\n var bookmarks = this.owner.getBookmarks();\n var localObj = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localObj.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n // if (!this.target) {\n this.initBookmarkDialog(localObj, bookmarks);\n //}\n this.owner.dialog.header = 'Bookmark';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.width = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = this.owner.updateFocus;\n this.owner.dialog.close = this.owner.updateFocus;\n this.owner.dialog.buttons = [{\n click: this.removeObjects.bind(this),\n buttonModel: { content: localObj.getConstant('Cancel'), cssClass: 'e-flat e-hyper-insert', isPrimary: true }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n BookmarkDialog.prototype.removeObjects = function () {\n this.owner.dialog.hide();\n };\n /**\n * @private\n */\n BookmarkDialog.prototype.destroy = function () {\n if (this.textBoxInput) {\n this.textBoxInput.remove();\n this.textBoxInput = undefined;\n }\n if (this.listviewInstance) {\n this.listviewInstance.destroy();\n this.listviewInstance = undefined;\n }\n };\n return BookmarkDialog;\n}());\nexport { BookmarkDialog };\n","import { L10n, setCulture, createElement, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { CheckBox, Button } from '@syncfusion/ej2-buttons';\nimport { DropDownList } from '@syncfusion/ej2-dropdowns';\nimport { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { ListView } from '@syncfusion/ej2-lists';\n/**\n * The Table of contents dialog is used to insert or edit table of contents at selection.\n */\nvar TableOfContentsDialog = /** @class */ (function () {\n /**\n * @private\n */\n function TableOfContentsDialog(viewer) {\n var _this = this;\n /**\n * @private\n */\n this.loadTableofContentDialog = function () {\n _this.owner.updateFocus();\n _this.pageNumber.checked = true;\n _this.rightAlign.disabled = false;\n _this.rightAlign.checked = true;\n _this.tabLeader.enabled = true;\n _this.hyperlink.checked = true;\n _this.style.checked = true;\n _this.outline.checked = true;\n _this.outline.disabled = false;\n _this.showLevel.enabled = true;\n };\n /**\n * @private\n */\n this.closeTableOfContentDialog = function () {\n _this.unWireEventsAndBindings();\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.onCancelButtonClick = function () {\n _this.owner.dialog.hide();\n _this.unWireEventsAndBindings();\n };\n /* tslint:disable:no-any */\n this.selectHandler = function (args) {\n _this.textBoxInput.value = args.text;\n /* tslint:disable:no-any */\n var value = document.getElementById('toclist');\n value.setSelectionRange(0, args.text.length);\n value.focus();\n };\n this.showStyleDialog = function () {\n if (!isNullOrUndefined(_this.owner.owner.styleDialogModule)) {\n _this.owner.owner.styleDialogModule.show(_this.textBoxInput.value);\n }\n };\n this.changeShowLevelValue = function (event) {\n var levels = event.value;\n var values = [];\n switch (levels) {\n case 1:\n values = ['1', null, null, null, null, null, null, null, null];\n _this.changeByValue(values);\n break;\n case 2:\n values = ['1', '2', null, null, null, null, null, null, null];\n _this.changeByValue(values);\n break;\n case 3:\n values = ['1', '2', '3', null, null, null, null, null, null];\n _this.changeByValue(values);\n break;\n case 4:\n values = ['1', '2', '3', '4', null, null, null, null, null];\n _this.changeByValue(values);\n break;\n case 5:\n values = ['1', '2', '3', '4', '5', null, null, null, null];\n _this.changeByValue(values);\n break;\n case 6:\n values = ['1', '2', '3', '4', '5', '6', null, null, null];\n _this.changeByValue(values);\n break;\n case 7:\n values = ['1', '2', '3', '4', '5', '6', '7', null, null];\n _this.changeByValue(values);\n break;\n case 8:\n values = ['1', '2', '3', '4', '5', '6', '7', '8', null];\n _this.changeByValue(values);\n break;\n case 9:\n values = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];\n _this.changeByValue(values);\n break;\n }\n };\n this.changeByValue = function (headings) {\n _this.heading1.value = headings[0];\n _this.heading2.value = headings[1];\n _this.heading3.value = headings[2];\n _this.heading4.value = headings[3];\n _this.heading5.value = headings[4];\n _this.heading6.value = headings[5];\n _this.heading7.value = headings[6];\n _this.heading8.value = headings[7];\n _this.heading9.value = headings[8];\n };\n this.reset = function () {\n _this.showLevel.enabled = true;\n _this.showLevel.value = 3;\n _this.outline.disabled = false;\n _this.outline.checked = true;\n var values = ['1', '2', '3', null, null, null, null, null, null];\n _this.changeByValue(values);\n _this.normal.value = null;\n };\n this.changeStyle = function (args) {\n var headingValue = args.srcElement.value;\n var value = _this.getElementValue(args.srcElement);\n if (headingValue !== value && headingValue !== '') {\n _this.showLevel.enabled = false;\n }\n else {\n _this.showLevel.enabled = true;\n _this.checkLevel();\n }\n };\n this.changeHeadingStyle = function (args) {\n var headingValue = args.srcElement.value;\n if (headingValue === '') {\n _this.showLevel.enabled = true;\n }\n else {\n _this.showLevel.enabled = false;\n }\n if (_this.normal === args.srcElement) {\n _this.outline.checked = false;\n _this.outline.disabled = true;\n }\n };\n /**\n * @private\n */\n this.changePageNumberValue = function (args) {\n if (args.checked) {\n _this.rightAlign.checked = true;\n _this.rightAlign.disabled = false;\n _this.tabLeader.enabled = true;\n }\n else {\n _this.rightAlign.disabled = true;\n _this.tabLeader.enabled = false;\n }\n };\n /**\n * @private\n */\n this.changeRightAlignValue = function (args) {\n if (args.checked) {\n _this.tabLeader.enabled = true;\n }\n else {\n _this.tabLeader.enabled = false;\n }\n };\n /**\n * @private\n */\n this.changeStyleValue = function (args) {\n if (args.checked) {\n _this.heading1.disabled = false;\n _this.heading2.disabled = false;\n _this.heading3.disabled = false;\n _this.heading4.disabled = false;\n _this.heading5.disabled = false;\n _this.heading6.disabled = false;\n _this.heading7.disabled = false;\n _this.heading8.disabled = false;\n _this.heading9.disabled = false;\n _this.normal.disabled = false;\n }\n else {\n _this.heading1.disabled = true;\n _this.heading2.disabled = true;\n _this.heading3.disabled = true;\n _this.heading4.disabled = true;\n _this.heading5.disabled = true;\n _this.heading6.disabled = true;\n _this.heading7.disabled = true;\n _this.heading8.disabled = true;\n _this.heading9.disabled = true;\n _this.normal.disabled = true;\n }\n };\n /**\n * @private\n */\n this.applyTableOfContentProperties = function () {\n var tocSettings = {\n startLevel: 1,\n endLevel: _this.showLevel.value,\n includeHyperlink: _this.hyperlink.checked,\n includePageNumber: _this.pageNumber.checked,\n rightAlign: _this.rightAlign.checked,\n tabLeader: _this.tabLeader.value,\n includeOutlineLevels: _this.outline.checked\n };\n _this.applyLevelSetting(tocSettings);\n _this.owner.owner.editorModule.insertTableOfContents(tocSettings);\n _this.owner.dialog.hide();\n };\n /**\n * @private\n */\n this.unWireEventsAndBindings = function () {\n _this.pageNumber.checked = false;\n _this.rightAlign.checked = false;\n _this.tabLeader.value = '';\n _this.hyperlink.checked = false;\n _this.style.checked = false;\n _this.outline.checked = false;\n _this.normal.value = '';\n };\n this.owner = viewer;\n }\n TableOfContentsDialog.prototype.getModuleName = function () {\n return 'TableOfContentsDialog';\n };\n /*tslint:disable max-func-body-length*/\n /**\n * @private\n */\n TableOfContentsDialog.prototype.initTableOfContentDialog = function (locale) {\n var instance = this;\n var ownerId = this.owner.owner.containerId;\n var id = ownerId + '_toc_dialog';\n this.target = createElement('div', { id: id, className: 'e-de-toc-dlg-container' });\n this.owner.owner.element.appendChild(this.target);\n // tslint:disable-next-line:max-line-length\n var generalDiv = createElement('div', { id: 'general_div', className: 'e-de-toc-dlg-sub-container' });\n this.target.appendChild(generalDiv);\n // tslint:disable-next-line:max-line-length\n var genLabel = createElement('div', { id: ownerId + '_genLabel', className: 'e-de-toc-dlg-main-heading', styles: 'margin-bottom: 13px;', innerHTML: locale.getConstant('General') });\n generalDiv.appendChild(genLabel);\n // tslint:disable-next-line:max-line-length\n var leftGeneralDiv = createElement('div', { id: 'left_general', styles: 'float:left;position:relative;' });\n generalDiv.appendChild(leftGeneralDiv);\n // tslint:disable-next-line:max-line-length\n var rightGeneralDiv = createElement('div', { styles: 'position:relative;', className: 'e-de-toc-dlg-right-general-div' });\n generalDiv.appendChild(rightGeneralDiv);\n // tslint:disable-next-line:max-line-length\n var leftBottomGeneralDiv = createElement('div', { id: 'leftBottom_general', styles: 'float:left;position:absolute;top:210px;' });\n generalDiv.appendChild(leftBottomGeneralDiv);\n // tslint:disable-next-line:max-line-length\n var rightBottomGeneralDiv = createElement('div', { className: 'e-de-toc-dlg-right-sub-container', styles: 'float:right;' });\n generalDiv.appendChild(rightBottomGeneralDiv);\n // tslint:disable-next-line:max-line-length\n var pageNumberDiv = createElement('div', { id: 'pageNumber_div', className: 'e-de-toc-dlg-sub-container' });\n var pageNumber = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_pageNumber'\n });\n pageNumberDiv.appendChild(pageNumber);\n // tslint:disable-next-line:max-line-length\n var rightAlignDiv = createElement('div', { id: 'rightAlign_div', className: 'e-de-toc-dlg-sub-container' });\n var rightAlign = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_rightAlign'\n });\n rightAlignDiv.appendChild(rightAlign);\n // tslint:disable-next-line:max-line-length\n this.pageNumber = new CheckBox({ label: locale.getConstant('Show page numbers'), checked: true, change: this.changePageNumberValue });\n // tslint:disable-next-line:max-line-length\n this.rightAlign = new CheckBox({ label: locale.getConstant('Right align page numbers'), checked: true, change: this.changeRightAlignValue });\n this.pageNumber.appendTo(pageNumber);\n this.rightAlign.appendTo(rightAlign);\n var tabDiv = createElement('div', { id: 'tab_div', className: 'e-de-toc-dlg-tab-div' });\n // tslint:disable-next-line:max-line-length\n var tabLeaderLabelDiv = createElement('div', { id: 'tabLeaderLabel_div' });\n // tslint:disable-next-line:max-line-length\n var tabLeaderLabel = createElement('label', { id: ownerId + '_tabLeaderLabel', className: 'e-de-toc-dlg-heading', innerHTML: locale.getConstant('Tab leader') + ':' });\n tabLeaderLabelDiv.appendChild(tabLeaderLabel);\n var tabLeaderDiv = createElement('div', { id: 'tabLeader_div' });\n var tabLeader = createElement('select', {\n id: ownerId + '_tabLeader',\n innerHTML: '' + '(' + locale.getConstant('None').toLocaleLowerCase() + ')' +\n ' ' + '....................' +\n ' ' + '-------------------' +\n ' ' + '____________' + ' '\n });\n tabLeaderDiv.appendChild(tabLeader);\n tabDiv.appendChild(tabLeaderLabelDiv);\n tabDiv.appendChild(tabLeaderDiv);\n leftGeneralDiv.appendChild(pageNumberDiv);\n leftGeneralDiv.appendChild(rightAlignDiv);\n leftGeneralDiv.appendChild(tabDiv);\n this.tabLeader = new DropDownList({ width: 210 });\n this.tabLeader.appendTo(tabLeader);\n var hyperlink = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_hyperlink'\n });\n rightGeneralDiv.appendChild(hyperlink);\n this.hyperlink = new CheckBox({ label: locale.getConstant('Use hyperlinks instead of page numbers'), checked: true });\n this.hyperlink.appendTo(hyperlink);\n // tslint:disable-next-line:max-line-length\n var showDiv = createElement('div', { id: 'show_div', className: 'e-de-toc-dlg-style-label' });\n // tslint:disable-next-line:max-line-length\n var showLevelLabelDiv = createElement('div', { id: 'showLevelLabel_div', className: 'e-de-toc-dlg-show-level-div' });\n // tslint:disable-next-line:max-line-length\n var showLevelLabel = createElement('label', { id: ownerId + '_showLevelLabel', className: 'e-de-toc-dlg-heading', innerHTML: locale.getConstant('Show levels') + ':' });\n showLevelLabelDiv.appendChild(showLevelLabel);\n // tslint:disable-next-line:max-line-length\n var showLevelDiv = createElement('div', { id: 'showLevel_div', className: 'e-de-toc-dlg-showlevel-div' });\n // tslint:disable-next-line:max-line-length\n var showLevel = createElement('input', { id: ownerId + '_showLevel', attrs: { 'type': 'text' } });\n showLevelDiv.appendChild(showLevel);\n showDiv.appendChild(showLevelLabelDiv);\n showDiv.appendChild(showLevelDiv);\n rightGeneralDiv.appendChild(showDiv);\n this.showLevel = new NumericTextBox({ format: '#', value: 3, min: 1, max: 9, width: 210, change: this.changeShowLevelValue });\n this.showLevel.appendTo(showLevel);\n // tslint:disable-next-line:max-line-length\n var buildTableDiv = createElement('div', { id: 'buildTable_div', className: 'e-de-toc-dlg-sub-container' });\n // tslint:disable-next-line:max-line-length\n var buildTableLabel = createElement('div', { id: ownerId + '_buildTableLabel', className: 'e-de-toc-dlg-main-heading e-de-toc-dlg-build-table', styles: 'margin-bottom: 13px;', innerHTML: locale.getConstant('Build table of contents from') + ':' });\n leftBottomGeneralDiv.appendChild(buildTableDiv);\n leftBottomGeneralDiv.appendChild(buildTableLabel);\n var style = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_style',\n });\n leftBottomGeneralDiv.appendChild(style);\n this.style = new CheckBox({ label: locale.getConstant('Styles'), checked: true, change: this.changeStyleValue });\n this.style.appendTo(style);\n var table = createElement('TABLE', { styles: 'margin-top:3px;' });\n var tr1 = createElement('tr');\n var td1 = createElement('td', { styles: 'width:120px;padding-left:10px;' });\n var availableLabel = createElement('label', {\n // tslint:disable-next-line:max-line-length\n innerHTML: locale.getConstant('Available styles'), className: 'e-de-toc-dlg-main-heading e-de-toc-dlg-sub-level-heading', id: this.target.id + '_availableLabel'\n });\n td1.appendChild(availableLabel);\n var td2 = createElement('td');\n var tocLabel = createElement('label', {\n innerHTML: locale.getConstant('TOC level') + ':', className: 'e-de-toc-dlg-main-heading e-de-toc-dlg-sub-level-heading',\n id: this.target.id + '_tocLabel'\n });\n td2.appendChild(tocLabel);\n tr1.appendChild(td1);\n tr1.appendChild(td2);\n table.appendChild(tr1);\n // tslint:disable-next-line:max-line-length\n var tableDiv = createElement('div', { id: 'table_div', className: 'e-de-toc-table-div' });\n var table1 = createElement('TABLE');\n var tr2 = createElement('tr');\n var td3 = createElement('td');\n var heading1Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 1',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading1Label'\n });\n td3.appendChild(heading1Label);\n var td4 = createElement('td');\n this.heading1 = createElement('input', { id: '_heading1', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading1.value = '1';\n this.heading1.addEventListener('keyup', this.changeStyle);\n td4.appendChild(this.heading1);\n tr2.appendChild(td3);\n tr2.appendChild(td4);\n var tr3 = createElement('tr');\n var td5 = createElement('td');\n var heading2Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 2',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading2Label'\n });\n td5.appendChild(heading2Label);\n var td6 = createElement('td');\n this.heading2 = createElement('input', { id: '_heading2', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading2.value = '2';\n this.heading2.addEventListener('keyup', this.changeStyle);\n td6.appendChild(this.heading2);\n tr3.appendChild(td5);\n tr3.appendChild(td6);\n var tr4 = createElement('tr');\n var td7 = createElement('td');\n var heading3Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 3',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading3Label'\n });\n td7.appendChild(heading3Label);\n var td8 = createElement('td');\n this.heading3 = createElement('input', { id: '_heading3', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading3.value = '3';\n this.heading3.addEventListener('keyup', this.changeStyle);\n td8.appendChild(this.heading3);\n tr4.appendChild(td7);\n tr4.appendChild(td8);\n var tr5 = createElement('tr');\n var td9 = createElement('td');\n var heading4Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 4',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading4Label'\n });\n td9.appendChild(heading4Label);\n var td10 = createElement('td');\n this.heading4 = createElement('input', { id: '_heading4', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading4.addEventListener('keyup', this.changeStyle);\n td10.appendChild(this.heading4);\n tr5.appendChild(td9);\n tr5.appendChild(td10);\n var tr6 = createElement('tr');\n var td11 = createElement('td');\n var heading5Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 5',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading5Label'\n });\n td11.appendChild(heading5Label);\n var td12 = createElement('td');\n this.heading5 = createElement('input', { id: '_heading5', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading5.addEventListener('keyup', this.changeStyle);\n td12.appendChild(this.heading5);\n tr6.appendChild(td11);\n tr6.appendChild(td12);\n var tr7 = createElement('tr');\n var td13 = createElement('td');\n var heading6Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 6',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading6Label'\n });\n td13.appendChild(heading6Label);\n var td14 = createElement('td');\n this.heading6 = createElement('input', { id: '_heading6', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading6.addEventListener('keyup', this.changeStyle);\n td14.appendChild(this.heading6);\n tr7.appendChild(td13);\n tr7.appendChild(td14);\n var tr8 = createElement('tr');\n var td15 = createElement('td');\n var heading7Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 7',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading7Label'\n });\n td15.appendChild(heading7Label);\n var td16 = createElement('td');\n this.heading7 = createElement('input', { id: '_heading7', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading7.addEventListener('keyup', this.changeStyle);\n td16.appendChild(this.heading7);\n tr8.appendChild(td15);\n tr8.appendChild(td16);\n var tr9 = createElement('tr');\n var td17 = createElement('td');\n var heading8Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 8',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading8Label'\n });\n td17.appendChild(heading8Label);\n var td18 = createElement('td');\n this.heading8 = createElement('input', { id: '_heading8', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading8.addEventListener('keyup', this.changeStyle);\n td18.appendChild(this.heading8);\n tr9.appendChild(td17);\n tr9.appendChild(td18);\n var tr10 = createElement('tr');\n var td19 = createElement('td');\n var heading9Label = createElement('label', {\n innerHTML: locale.getConstant('Heading') + ' 9',\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_heading9Label'\n });\n td19.appendChild(heading9Label);\n var td20 = createElement('td');\n this.heading9 = createElement('input', { id: '_heading9', className: 'e-input e-de-toc-dlg-toc-level' });\n this.heading9.addEventListener('keyup', this.changeStyle);\n td20.appendChild(this.heading9);\n tr10.appendChild(td19);\n tr10.appendChild(td20);\n var tr12 = createElement('tr');\n var td23 = createElement('td');\n var normalLabel = createElement('label', {\n innerHTML: locale.getConstant('Normal'),\n className: 'e-de-toc-dlg-sub-heading', id: this.target.id + '_normalLabel'\n });\n td23.appendChild(normalLabel);\n var td24 = createElement('td');\n this.normal = createElement('input', { id: '_normal', className: 'e-input e-de-toc-dlg-toc-level' });\n this.normal.addEventListener('keyup', this.changeHeadingStyle);\n td24.appendChild(this.normal);\n tr12.appendChild(td23);\n tr12.appendChild(td24);\n table1.appendChild(tr2);\n table1.appendChild(tr3);\n table1.appendChild(tr4);\n table1.appendChild(tr5);\n table1.appendChild(tr6);\n table1.appendChild(tr7);\n table1.appendChild(tr8);\n table1.appendChild(tr9);\n table1.appendChild(tr10);\n table1.appendChild(tr12);\n tableDiv.appendChild(table1);\n var stylesLevelDiv = createElement('div', { className: 'e-de-toc-styles-table-div' });\n stylesLevelDiv.appendChild(table);\n stylesLevelDiv.appendChild(tableDiv);\n leftBottomGeneralDiv.appendChild(stylesLevelDiv);\n //leftBottomGeneralDiv.appendChild(table); leftBottomGeneralDiv.appendChild(tableDiv);\n var fieldsDiv = createElement('div', { id: 'fields_div', styles: 'display: flex;' });\n leftBottomGeneralDiv.appendChild(fieldsDiv);\n var outDiv = createElement('div', { id: 'out_div' });\n // tslint:disable-next-line:max-line-length\n var outlineDiv = createElement('div', { id: 'outline_div', className: 'e-de-toc-dlg-sub-container e-de-toc-dlg-outline-levels' });\n var outline = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: '_outline'\n });\n outlineDiv.appendChild(outline);\n outDiv.appendChild(outlineDiv);\n fieldsDiv.appendChild(outDiv);\n this.outline = new CheckBox({ label: locale.getConstant('Outline levels'), checked: true });\n this.outline.appendTo(outline);\n var resetButtonDiv = createElement('div', { className: 'e-de-toc-reset-button' });\n fieldsDiv.appendChild(resetButtonDiv);\n var resetElement = createElement('button', { innerHTML: 'Reset', id: 'reset' });\n resetButtonDiv.appendChild(resetElement);\n var resetButton = new Button({ cssClass: 'e-btn e-flat' });\n resetButton.appendTo(resetElement);\n resetElement.addEventListener('click', this.reset);\n // tslint:disable-next-line:max-line-length\n var tocStylesDiv = createElement('div', { id: 'tocStyles_div', className: 'e-de-toc-dlg-sub-container' });\n // tslint:disable-next-line:max-line-length\n var tocStylesLabel = createElement('div', {\n id: ownerId + '_tocStylesLabel', className: 'e-de-toc-dlg-main-heading e-de-toc-dlg-styles',\n innerHTML: locale.getConstant('Styles') + ':'\n });\n rightBottomGeneralDiv.appendChild(tocStylesDiv);\n rightBottomGeneralDiv.appendChild(tocStylesLabel);\n var textBoxDiv = createElement('div', { className: 'e-de-toc-dlg-style-input' });\n rightBottomGeneralDiv.appendChild(textBoxDiv);\n this.textBoxInput = createElement('input', { className: 'e-input', id: 'toclist' });\n this.textBoxInput.setAttribute('type', 'text');\n textBoxDiv.appendChild(this.textBoxInput);\n var listViewDiv = createElement('div', { className: 'e-de-toc-list-view' });\n var styleValues = ['TOC 1', 'TOC 2', 'TOC 3', 'TOC 4', 'TOC 5', 'TOC 6', 'TOC 7', 'TOC 8', 'TOC 9'];\n this.listViewInstance = new ListView({ dataSource: styleValues, cssClass: 'e-toc-list-view' });\n this.listViewInstance.appendTo(listViewDiv);\n this.listViewInstance.addEventListener('select', this.selectHandler);\n rightBottomGeneralDiv.appendChild(listViewDiv);\n var modifyButtonDiv = createElement('div', { className: 'e-de-toc-modify-button' });\n rightBottomGeneralDiv.appendChild(modifyButtonDiv);\n var modifyElement = createElement('button', { innerHTML: 'Modify', id: 'modify' });\n modifyButtonDiv.appendChild(modifyElement);\n var modifyButton = new Button({ cssClass: 'e-btn e-flat' });\n modifyButton.appendTo(modifyElement);\n modifyElement.addEventListener('click', this.showStyleDialog);\n };\n /**\n * @private\n */\n TableOfContentsDialog.prototype.show = function () {\n var localValue = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localValue.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initTableOfContentDialog(localValue);\n }\n this.owner.dialog.header = localValue.getConstant('Table of Contents');\n this.owner.dialog.width = 'auto';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = this.loadTableofContentDialog;\n this.owner.dialog.close = this.closeTableOfContentDialog;\n this.owner.dialog.buttons = [{\n click: this.applyTableOfContentProperties,\n buttonModel: { content: localValue.getConstant('Ok'), cssClass: 'e-flat e-toc-okay', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: localValue.getConstant('Cancel'), cssClass: 'e-flat e-toc-cancel' }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n TableOfContentsDialog.prototype.checkLevel = function () {\n if (this.heading1.value !== '') {\n this.showLevel.value = 1;\n }\n if (this.heading2.value !== '') {\n this.showLevel.value = 2;\n }\n if (this.heading3.value !== '') {\n this.showLevel.value = 3;\n }\n if (this.heading4.value !== '') {\n this.showLevel.value = 4;\n }\n if (this.heading5.value !== '') {\n this.showLevel.value = 5;\n }\n if (this.heading6.value !== '') {\n this.showLevel.value = 6;\n }\n if (this.heading7.value !== '') {\n this.showLevel.value = 7;\n }\n if (this.heading8.value !== '') {\n this.showLevel.value = 8;\n }\n if (this.heading9.value !== '') {\n this.showLevel.value = 9;\n }\n };\n TableOfContentsDialog.prototype.getElementValue = function (element) {\n switch (element) {\n case this.heading1:\n return '1';\n case this.heading2:\n return '2';\n case this.heading3:\n return '3';\n case this.heading4:\n return '4';\n case this.heading5:\n return '5';\n case this.heading6:\n return '6';\n case this.heading7:\n return '7';\n case this.heading8:\n return '8';\n case this.heading9:\n return '9';\n default:\n return '1';\n }\n };\n TableOfContentsDialog.prototype.getHeadingLevel = function (index) {\n switch (index) {\n case 1:\n return parseInt(this.heading1.value);\n case 2:\n return parseInt(this.heading2.value);\n case 3:\n return parseInt(this.heading3.value);\n case 4:\n return parseInt(this.heading4.value);\n case 5:\n return parseInt(this.heading5.value);\n case 6:\n return parseInt(this.heading6.value);\n case 7:\n return parseInt(this.heading7.value);\n case 8:\n return parseInt(this.heading8.value);\n case 9:\n return parseInt(this.heading9.value);\n default:\n return 0;\n }\n };\n TableOfContentsDialog.prototype.applyLevelSetting = function (tocSettings) {\n tocSettings.levelSettings = {};\n var headingPrefix = 'Heading ';\n var newStartLevel = 0;\n var newEndLevel = 0;\n var isEndLevel = false;\n for (var i = 1; i <= tocSettings.endLevel; i++) {\n var outlineLevel = this.getHeadingLevel(i);\n if (i === outlineLevel) {\n if (newStartLevel === 0) {\n newStartLevel = i;\n isEndLevel = false;\n }\n if (!isEndLevel) {\n newEndLevel = i;\n }\n }\n else {\n isEndLevel = true;\n if (outlineLevel !== 0) {\n var headingStyle = headingPrefix + i.toString();\n tocSettings.levelSettings[headingStyle] = outlineLevel;\n }\n }\n }\n tocSettings.startLevel = newStartLevel;\n tocSettings.endLevel = newEndLevel;\n if (this.normal.value !== '') {\n tocSettings.levelSettings['Normal'] = +this.normal.value;\n }\n };\n /**\n * @private\n */\n TableOfContentsDialog.prototype.destroy = function () {\n if (this.pageNumber) {\n this.pageNumber.destroy();\n this.pageNumber = undefined;\n }\n if (this.rightAlign) {\n this.rightAlign.destroy();\n this.rightAlign = undefined;\n }\n if (this.tabLeader) {\n this.tabLeader.destroy();\n this.tabLeader = undefined;\n }\n if (this.showLevel) {\n this.showLevel.destroy();\n this.showLevel = undefined;\n }\n if (this.hyperlink) {\n this.hyperlink.destroy();\n this.hyperlink = undefined;\n }\n if (this.style) {\n this.style.destroy();\n this.style = undefined;\n }\n if (this.outline) {\n this.outline.destroy();\n this.outline = undefined;\n }\n if (this.listViewInstance) {\n this.listViewInstance.destroy();\n this.listViewInstance = undefined;\n }\n this.heading1 = undefined;\n this.heading2 = undefined;\n this.heading3 = undefined;\n this.heading4 = undefined;\n this.heading5 = undefined;\n this.heading6 = undefined;\n this.heading7 = undefined;\n this.heading8 = undefined;\n this.heading9 = undefined;\n this.normal = undefined;\n this.textBoxInput = undefined;\n this.owner = undefined;\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var count = 0; count < this.target.childNodes.length; count++) {\n this.target.removeChild(this.target.childNodes[count]);\n count--;\n }\n this.target = undefined;\n }\n };\n return TableOfContentsDialog;\n}());\nexport { TableOfContentsDialog };\n","import { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { createElement, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { DropDownList } from '@syncfusion/ej2-dropdowns';\nimport { CheckBox, RadioButton } from '@syncfusion/ej2-buttons';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { WSectionFormat } from './../../implementation/format/index';\nimport { Tab } from '@syncfusion/ej2-navigations';\n/**\n * The Page setup dialog is used to modify formatting of selected sections.\n */\nvar PageSetupDialog = /** @class */ (function () {\n /**\n * @private\n */\n function PageSetupDialog(viewer) {\n var _this = this;\n this.isPortrait = true;\n /**\n * @private\n */\n this.loadPageSetupDialog = function () {\n _this.owner.updateFocus();\n var sectionFormat = _this.owner.selection.sectionFormat;\n _this.topMarginBox.value = sectionFormat.topMargin;\n _this.leftMarginBox.value = sectionFormat.leftMargin;\n _this.bottomMarginBox.value = sectionFormat.bottomMargin;\n _this.rightMarginBox.value = sectionFormat.rightMargin;\n _this.widthBox.value = sectionFormat.pageWidth;\n _this.heightBox.value = sectionFormat.pageHeight;\n _this.checkBox1.checked = sectionFormat.differentOddAndEvenPages;\n _this.checkBox2.checked = sectionFormat.differentFirstPage;\n _this.headerBox.value = sectionFormat.headerDistance;\n _this.footerBox.value = sectionFormat.footerDistance;\n if (_this.widthBox.value > _this.heightBox.value) {\n _this.landscape.checked = true;\n }\n else {\n _this.portrait.checked = true;\n }\n };\n /**\n * @private\n */\n this.closePageSetupDialog = function () {\n _this.unWireEventsAndBindings();\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.onCancelButtonClick = function () {\n _this.owner.dialog.hide();\n _this.unWireEventsAndBindings();\n };\n /**\n * @private\n */\n this.keyUpInsertPageSettings = function (event) {\n if (event.keyCode === 13) {\n _this.applyPageSetupProperties();\n }\n };\n /**\n * @private\n */\n this.applyPageSetupProperties = function () {\n var sectionFormat = new WSectionFormat();\n sectionFormat.bottomMargin = _this.bottomMarginBox.value;\n sectionFormat.topMargin = _this.topMarginBox.value;\n sectionFormat.leftMargin = _this.leftMarginBox.value;\n sectionFormat.rightMargin = _this.rightMarginBox.value;\n sectionFormat.pageWidth = _this.widthBox.value;\n sectionFormat.pageHeight = _this.heightBox.value;\n sectionFormat.differentOddAndEvenPages = _this.checkBox1.checked;\n sectionFormat.differentFirstPage = _this.checkBox2.checked;\n sectionFormat.headerDistance = _this.headerBox.value;\n sectionFormat.footerDistance = _this.footerBox.value;\n _this.owner.owner.editorModule.onApplySectionFormat(undefined, sectionFormat);\n _this.owner.dialog.hide();\n };\n /**\n * @private\n */\n this.changeByPaperSize = function (event) {\n var value = event.value;\n var sectionFormat = _this.owner.selection.sectionFormat;\n var width = sectionFormat.pageWidth;\n var height = sectionFormat.pageHeight;\n if (_this.owner.selection.sectionFormat.pageWidth > _this.owner.selection.sectionFormat.pageHeight || _this.landscape.checked) {\n _this.isPortrait = false;\n }\n else {\n _this.isPortrait = true;\n }\n if (value === 'letter') {\n if (_this.isPortrait) {\n _this.widthBox.value = 612;\n _this.heightBox.value = 792;\n }\n else {\n _this.widthBox.value = 792;\n _this.heightBox.value = 612;\n }\n }\n else if (value === 'tabloid') {\n if (_this.isPortrait) {\n _this.widthBox.value = 792;\n _this.heightBox.value = 1224;\n }\n else {\n _this.widthBox.value = 1224;\n _this.heightBox.value = 792;\n }\n }\n else if (value === 'legal') {\n if (_this.isPortrait) {\n _this.widthBox.value = 612;\n _this.heightBox.value = 1008;\n }\n else {\n _this.widthBox.value = 1008;\n _this.heightBox.value = 612;\n }\n }\n else if (value === 'statement') {\n if (_this.isPortrait) {\n _this.widthBox.value = 392;\n _this.heightBox.value = 612;\n }\n else {\n _this.widthBox.value = 612;\n _this.heightBox.value = 392;\n }\n }\n else if (value === 'executive') {\n if (_this.isPortrait) {\n _this.widthBox.value = 522;\n _this.heightBox.value = 756;\n }\n else {\n _this.widthBox.value = 756;\n _this.heightBox.value = 522;\n }\n }\n else if (value === 'a3') {\n if (_this.isPortrait) {\n _this.widthBox.value = 841.9;\n _this.heightBox.value = 1190.55;\n }\n else {\n _this.widthBox.value = 1190.55;\n _this.heightBox.value = 841.9;\n }\n }\n else if (value === 'a4') {\n if (_this.isPortrait) {\n _this.widthBox.value = 595.3;\n _this.heightBox.value = 841.9;\n }\n else {\n _this.widthBox.value = 841.9;\n _this.heightBox.value = 595.3;\n }\n }\n else if (value === 'a5') {\n if (_this.isPortrait) {\n _this.widthBox.value = 419.55;\n _this.heightBox.value = 595.3;\n }\n else {\n _this.widthBox.value = 595.3;\n _this.heightBox.value = 419.55;\n }\n }\n else if (value === 'b4') {\n if (_this.isPortrait) {\n _this.widthBox.value = 728.5;\n _this.heightBox.value = 1031.8;\n }\n else {\n _this.widthBox.value = 1031.8;\n _this.heightBox.value = 728.5;\n }\n }\n else if (value === 'b5') {\n if (_this.isPortrait) {\n _this.widthBox.value = 515.9;\n _this.heightBox.value = 728.5;\n }\n else {\n _this.widthBox.value = 728.5;\n _this.heightBox.value = 515.9;\n }\n }\n else if (value === 'customsize') {\n if (_this.isPortrait) {\n _this.widthBox.value = 515.9;\n _this.heightBox.value = 728.5;\n }\n else {\n _this.widthBox.value = 728.5;\n _this.heightBox.value = 515.9;\n }\n }\n };\n /**\n * @private\n */\n this.onPortrait = function (event) {\n _this.landscape.checked = false;\n var width = _this.widthBox.value;\n var height = _this.heightBox.value;\n if (width > height) {\n _this.widthBox.value = height;\n _this.heightBox.value = width;\n }\n };\n /**\n * @private\n */\n this.onLandscape = function (event) {\n _this.portrait.checked = false;\n var width = _this.widthBox.value;\n var height = _this.heightBox.value;\n if (width < height) {\n _this.widthBox.value = height;\n _this.heightBox.value = width;\n }\n };\n /**\n * @private\n */\n this.unWireEventsAndBindings = function () {\n _this.paperSize.value = undefined;\n _this.topMarginBox.value = undefined;\n _this.bottomMarginBox.value = undefined;\n _this.leftMarginBox.value = undefined;\n _this.rightMarginBox.value = undefined;\n _this.headerBox.value = undefined;\n _this.footerBox.value = undefined;\n _this.widthBox.value = undefined;\n _this.heightBox.value = undefined;\n _this.checkBox1.checked = false;\n _this.checkBox2.checked = false;\n _this.portrait.checked = false;\n _this.landscape.checked = false;\n };\n this.owner = viewer;\n }\n PageSetupDialog.prototype.getModuleName = function () {\n return 'PageSetupDialog';\n };\n /**\n * @private\n */\n PageSetupDialog.prototype.initPageSetupDialog = function (locale) {\n var id = this.owner.owner.containerId + '_pagesetup_dialog';\n this.target = createElement('div', { id: id, className: 'e-de-pagesetup-dlg-container' });\n this.owner.owner.element.appendChild(this.target);\n var ejtabContainer = createElement('div', { id: this.target.id + '_MarginTabContainer' });\n this.target.appendChild(ejtabContainer);\n this.marginTab = createElement('div', {\n id: this.target.id + '_marginPropertyTab', styles: 'position: relative;width:400px;'\n });\n this.paperTab = createElement('div', {\n id: this.target.id + '_paperSizePropertyTab', styles: 'position: relative;width:400px;'\n });\n this.layoutTab = createElement('div', {\n id: this.target.id + '_CellPropertiesDialogTab', styles: 'position: relative;width:400px;'\n });\n // tslint:disable-next-line:max-line-length\n var ejtab = createElement('div', { id: this.target.id + '_PageSetupDialogTab', className: 'e-de-page-setup-ppty-tab' });\n var headerContainer = createElement('div', { className: 'e-tab-header' });\n var marginHeader = createElement('div', {\n id: this.target.id + '_marginHeader', innerHTML: locale.getConstant('Margin')\n });\n var paperHeader = createElement('div', {\n id: this.target.id + '_paperHeader', innerHTML: locale.getConstant('Paper')\n });\n var layoutHeader = createElement('div', {\n id: this.target.id + '_layoutHeader', innerHTML: locale.getConstant('Layout')\n });\n headerContainer.appendChild(marginHeader);\n headerContainer.appendChild(paperHeader);\n headerContainer.appendChild(layoutHeader);\n var contentContainer = createElement('div', { className: 'e-content' });\n var marginContent = createElement('div', { id: this.target.id + '_marginContent' });\n var paperContent = createElement('div', { id: this.target.id + '_paperContent' });\n var layoutContent = createElement('div', { id: this.target.id + '_layoutContent' });\n marginContent.appendChild(this.marginTab);\n paperContent.appendChild(this.paperTab);\n layoutContent.appendChild(this.layoutTab);\n contentContainer.appendChild(marginContent);\n contentContainer.appendChild(paperContent);\n contentContainer.appendChild(layoutContent);\n ejtab.appendChild(headerContainer);\n ejtab.appendChild(contentContainer);\n ejtabContainer.appendChild(ejtab);\n this.initMarginProperties(this.marginTab, locale);\n this.initPaperSizeProperties(this.paperTab, locale);\n this.initLayoutProperties(this.layoutTab, locale);\n var tabObj = new Tab({}, ejtab);\n this.target.addEventListener('keyup', this.keyUpInsertPageSettings);\n var marginTabHeader = tabObj.element.getElementsByClassName('e-item e-toolbar-item')[0];\n var marginTabHeaderItem = marginTabHeader.getElementsByClassName('e-tab-wrap')[0];\n marginTabHeaderItem.classList.add('e-de-page-setup-dlg-margin-tab-header');\n };\n /**\n * @private\n */\n PageSetupDialog.prototype.initMarginProperties = function (element, locale) {\n var marginDiv = createElement('div', {\n id: 'margin_div',\n className: 'e-de-page-setup-dlg-sub-container', styles: 'height:135px;'\n });\n // tslint:disable-next-line:max-line-length\n var leftMarginDiv = createElement('div', { id: 'left_margin', className: 'e-de-page-setup-dlg-left-sub-container' });\n marginDiv.appendChild(leftMarginDiv);\n // tslint:disable-next-line:max-line-length\n var rightMarginDiv = createElement('div', { className: 'e-de-page-setup-dlg-right-sub-container' });\n marginDiv.appendChild(rightMarginDiv);\n var topLabel = createElement('label', {\n innerHTML: locale.getConstant('Top'), className: 'e-de-page-setup-dlg-sub-header',\n id: this.target.id + '_TopLabel', styles: 'padding-top:0px;width:190px;'\n });\n var topTextBox = createElement('input', {\n attrs: { 'type': 'text' }, id: this.target.id + '_Top'\n });\n var bottomBoxLabel = createElement('label', {\n innerHTML: locale.getConstant('Bottom'),\n className: 'e-de-page-setup-dlg-sub-title-header', id: this.target.id + '_bottomLabel'\n });\n var bottomTextBox = createElement('input', {\n attrs: { 'type': 'text' },\n id: this.target.id + '_bottom'\n });\n leftMarginDiv.appendChild(topLabel);\n leftMarginDiv.appendChild(topTextBox);\n leftMarginDiv.appendChild(bottomBoxLabel);\n leftMarginDiv.appendChild(bottomTextBox);\n var leftBoxLabel = createElement('label', {\n innerHTML: locale.getConstant('Left'), className: 'e-de-page-setup-dlg-sub-header', styles: 'padding-top:0px;width:190px;',\n id: this.target.id + '_leftLabel'\n });\n var leftTextBox = createElement('input', {\n attrs: { 'type': 'text' }, id: this.target.id + '_left'\n });\n var rightLabel = createElement('label', {\n innerHTML: locale.getConstant('Right'),\n id: this.target.id + '_rightLabel', className: 'e-de-page-setup-dlg-sub-title-header'\n });\n var rightTextBox = createElement('input', {\n attrs: { 'type': 'text' },\n id: this.target.id + '_right'\n });\n rightMarginDiv.appendChild(leftBoxLabel);\n rightMarginDiv.appendChild(leftTextBox);\n rightMarginDiv.appendChild(rightLabel);\n rightMarginDiv.appendChild(rightTextBox);\n element.appendChild(marginDiv);\n this.topMarginBox = new NumericTextBox({ value: 71, width: 170, decimals: 2 });\n this.topMarginBox.appendTo(topTextBox);\n this.leftMarginBox = new NumericTextBox({ value: 73, width: 170, decimals: 2 });\n this.leftMarginBox.appendTo(leftTextBox);\n this.bottomMarginBox = new NumericTextBox({ value: 72, width: 170, decimals: 2 });\n this.bottomMarginBox.appendTo(bottomTextBox);\n this.rightMarginBox = new NumericTextBox({ value: 74, width: 170, decimals: 2 });\n this.rightMarginBox.appendTo(rightTextBox);\n // tslint:disable-next-line:max-line-length\n var orientationDiv = createElement('div', { id: 'orientation_div', className: 'e-de-page-setup-dlg-sub-container-port' });\n // tslint:disable-next-line:max-line-length\n var orientationLabeldiv = createElement('div', { id: '_orientationLabelDiv', className: 'e-de-page-setup-dlg-sub-label', innerHTML: locale.getConstant('Orientation') });\n var orientationPropDiv = createElement('div', { id: '_orientationPropDiv', styles: 'display: flex;', className: 'e-de-page-setup-dlg-orientation-prop' });\n var portraitDiv = createElement('div', { id: '_portraitDiv', styles: 'padding-right: 30px;' });\n var portrait = createElement('input', {\n attrs: { 'type': 'radiobutton' }, id: this.target.id + '_portrait'\n });\n var landscapeDiv = createElement('div', { id: '_landscapeDiv' });\n var landscape = createElement('input', {\n attrs: { 'type': 'radiobutton' }, id: this.target.id + '_landscape'\n });\n portraitDiv.appendChild(portrait);\n landscapeDiv.appendChild(landscape);\n orientationPropDiv.appendChild(portraitDiv);\n orientationPropDiv.appendChild(landscapeDiv);\n orientationDiv.appendChild(orientationLabeldiv);\n orientationDiv.appendChild(orientationPropDiv);\n this.portrait = new RadioButton({ label: locale.getConstant('Portrait'), checked: true, change: this.onPortrait });\n this.landscape = new RadioButton({ label: locale.getConstant('Landscape'), change: this.onLandscape });\n this.portrait.appendTo(portrait);\n this.landscape.appendTo(landscape);\n element.appendChild(orientationDiv);\n };\n /**\n * @private\n */\n PageSetupDialog.prototype.initPaperSizeProperties = function (element, locale) {\n var sizeDiv = createElement('div', {\n id: 'size_div',\n className: 'e-de-page-setup-dlg-sub-size-container'\n });\n // tslint:disable-next-line:max-line-length\n var leftSizeDiv = createElement('div', { id: 'left_size', className: 'e-de-page-setup-dlg-left-sub-container' });\n sizeDiv.appendChild(leftSizeDiv);\n // tslint:disable-next-line:max-line-length\n var rightSizeDiv = createElement('div', { className: 'e-de-page-setup-dlg-right-sub-container' });\n sizeDiv.appendChild(rightSizeDiv);\n var widthLabel = createElement('label', {\n innerHTML: locale.getConstant('Width'), className: 'e-de-page-setup-dlg-sub-header',\n id: this.target.id + '_widthLabel', styles: 'padding-top:0px;width:190px;'\n });\n var widthTextBox = createElement('input', {\n attrs: { 'type': 'text' }, id: this.target.id + '_Width'\n });\n leftSizeDiv.appendChild(widthLabel);\n leftSizeDiv.appendChild(widthTextBox);\n var heightLabel = createElement('label', {\n innerHTML: locale.getConstant('Height'), className: 'e-de-page-setup-dlg-sub-header', styles: 'padding-top:0px;width:190px;',\n id: this.target.id + '_heightLabel'\n });\n var heightTextBox = createElement('input', {\n attrs: { 'type': 'text' }, id: this.target.id + '_height'\n });\n rightSizeDiv.appendChild(heightLabel);\n rightSizeDiv.appendChild(heightTextBox);\n element.appendChild(sizeDiv);\n this.widthBox = new NumericTextBox({ value: 612, width: 170, decimals: 2 });\n this.widthBox.appendTo(widthTextBox);\n this.heightBox = new NumericTextBox({ value: 792, width: 170, decimals: 2 });\n this.heightBox.appendTo(heightTextBox);\n // tslint:disable-next-line:max-line-length\n var paperSizeDiv = createElement('div', { id: '_paperSizeDiv', styles: 'height:37px;', className: 'e-de-page-setup-dlg-sub-container' });\n var paperSize = createElement('select', {\n id: this.target.id + '_papersize', styles: 'width:170px;padding-bottom: 20px;',\n innerHTML: '' + locale.getConstant('Letter') +\n ' ' + locale.getConstant('Tabloid') +\n ' ' + locale.getConstant('Legal') +\n ' ' + locale.getConstant('Statement') +\n ' ' + locale.getConstant('Executive') +\n ' ' + locale.getConstant('A3') +\n ' ' + locale.getConstant('A4') +\n ' ' + locale.getConstant('A5') +\n ' ' + locale.getConstant('B4') +\n ' ' + locale.getConstant('B5') +\n ' ' + locale.getConstant('Custom Size') + ' '\n });\n paperSizeDiv.appendChild(paperSize);\n this.paperSize = new DropDownList({ change: this.changeByPaperSize, width: '170px' });\n this.paperSize.appendTo(paperSize);\n element.appendChild(paperSizeDiv);\n };\n /**\n * @private\n */\n PageSetupDialog.prototype.initLayoutProperties = function (element, locale) {\n // tslint:disable-next-line:max-line-length\n var layoutDiv = createElement('div', { id: '_layoutDiv', className: 'e-de-page-setup-dlg-layout-sub-container', });\n // tslint:disable-next-line:max-line-length\n var firstPageDiv = createElement('div', { id: '_firstPageDiv', styles: 'height: 27px;', className: 'e-de-page-setup-dlg-first-page-prop' });\n var checkBox1 = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_oddoreven'\n });\n firstPageDiv.appendChild(checkBox1);\n // tslint:disable-next-line:max-line-length\n var oddOrEvenDiv = createElement('div', { id: '_oddOrEvenDiv', styles: 'height: 27px;', className: 'e-de-page-setup-dlg-odd-or-even-prop' });\n var checkBox2 = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_even'\n });\n oddOrEvenDiv.appendChild(checkBox2);\n layoutDiv.appendChild(firstPageDiv);\n layoutDiv.appendChild(oddOrEvenDiv);\n this.checkBox1 = new CheckBox({ label: locale.getConstant('Different odd and even') });\n this.checkBox2 = new CheckBox({ label: locale.getConstant('Different first page') });\n this.checkBox1.appendTo(checkBox1);\n this.checkBox2.appendTo(checkBox2);\n element.appendChild(layoutDiv);\n // tslint:disable-next-line:max-line-length\n var textLabelDiv = createElement('div', { id: '_textLabelDiv', className: 'e-de-page-setup-dlg-sub-label' });\n var textLabel = createElement('label', {\n innerHTML: locale.getConstant('From edge'), id: this.target.id + '_textLabel'\n });\n textLabelDiv.appendChild(textLabel);\n element.appendChild(textLabelDiv);\n // tslint:disable-next-line:max-line-length\n var propertyDiv = createElement('div', { id: '_headerFooeterPropDiv', className: 'e-de-page-setup-dlg-sub-container', styles: 'height: 65px;' });\n // tslint:disable-next-line:max-line-length\n var leftLayoutDiv = createElement('div', { id: '_leftLayoutDiv', className: 'e-de-page-setup-dlg-left-layout-container' });\n propertyDiv.appendChild(leftLayoutDiv);\n // tslint:disable-next-line:max-line-length\n var rightLayoutDiv = createElement('div', { className: 'e-de-page-setup-dlg-right-layout-container' });\n propertyDiv.appendChild(rightLayoutDiv);\n var headerLabel = createElement('label', {\n innerHTML: locale.getConstant('Header'), className: 'e-de-page-setup-dlg-sub-header',\n id: this.target.id + '_headerLabel', styles: 'padding-top:0px;width:190px;'\n });\n var headerBox = createElement('input', {\n attrs: { 'type': 'text' }, id: this.target.id + '_header'\n });\n leftLayoutDiv.appendChild(headerLabel);\n leftLayoutDiv.appendChild(headerBox);\n var footerLabel = createElement('label', {\n innerHTML: locale.getConstant('Footer'), className: 'e-de-page-setup-dlg-sub-header', styles: 'padding-top:0px;width:190px;',\n id: this.target.id + '_footerLabel'\n });\n var footerBox = createElement('input', {\n attrs: { 'type': 'text' }, id: this.target.id + '_footer'\n });\n rightLayoutDiv.appendChild(footerLabel);\n rightLayoutDiv.appendChild(footerBox);\n element.appendChild(propertyDiv);\n this.headerBox = new NumericTextBox({ value: 612, width: 170, decimals: 2 });\n this.headerBox.appendTo(headerBox);\n this.footerBox = new NumericTextBox({ value: 792, width: 170, decimals: 2 });\n this.footerBox.appendTo(footerBox);\n };\n /**\n * @private\n */\n PageSetupDialog.prototype.show = function () {\n var localValue = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localValue.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initPageSetupDialog(localValue);\n }\n this.owner.dialog.header = localValue.getConstant('Page Setup');\n this.owner.dialog.width = 'auto';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = this.loadPageSetupDialog;\n this.owner.dialog.close = this.closePageSetupDialog;\n this.owner.dialog.buttons = [{\n click: this.applyPageSetupProperties,\n buttonModel: { content: localValue.getConstant('Ok'), cssClass: 'e-flat e-layout-ppty-okay', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: localValue.getConstant('Cancel'), cssClass: 'e-flat e-layout-ppty-cancel' }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n /**\n * @private\n */\n PageSetupDialog.prototype.destroy = function () {\n if (this.topMarginBox) {\n this.topMarginBox.destroy();\n this.topMarginBox = undefined;\n }\n if (this.leftMarginBox) {\n this.leftMarginBox.destroy();\n this.leftMarginBox = undefined;\n }\n if (this.bottomMarginBox) {\n this.bottomMarginBox.destroy();\n this.bottomMarginBox = undefined;\n }\n if (this.rightMarginBox) {\n this.rightMarginBox.destroy();\n this.rightMarginBox = undefined;\n }\n if (this.headerBox) {\n this.headerBox.destroy();\n this.headerBox = undefined;\n }\n if (this.footerBox) {\n this.footerBox.destroy();\n this.footerBox = undefined;\n }\n if (this.widthBox) {\n this.widthBox.destroy();\n this.widthBox = undefined;\n }\n if (this.heightBox) {\n this.heightBox.destroy();\n this.heightBox = undefined;\n }\n if (this.paperSize) {\n this.paperSize.destroy();\n this.paperSize = undefined;\n }\n if (this.checkBox1) {\n this.checkBox1.destroy();\n this.checkBox1 = undefined;\n }\n if (this.checkBox2) {\n this.checkBox2.destroy();\n this.checkBox2 = undefined;\n }\n if (this.portrait) {\n this.portrait.destroy();\n this.portrait = undefined;\n }\n if (this.landscape) {\n this.landscape.destroy();\n this.landscape = undefined;\n }\n this.owner = undefined;\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var s = 0; s < this.target.childNodes.length; s++) {\n this.target.removeChild(this.target.childNodes[s]);\n s--;\n }\n this.target = undefined;\n }\n };\n return PageSetupDialog;\n}());\nexport { PageSetupDialog };\n","import { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { createElement, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { DropDownList } from '@syncfusion/ej2-dropdowns';\nimport { WParagraphFormat } from '../index';\n/**\n * The Paragraph dialog is used to modify formatting of selected paragraphs.\n */\nvar ParagraphDialog = /** @class */ (function () {\n /**\n * @private\n */\n function ParagraphDialog(viewer) {\n var _this = this;\n //paragraph Format properties\n this.leftIndent = undefined;\n this.rightIndent = undefined;\n this.beforeSpacing = undefined;\n this.afterSpacing = undefined;\n this.textAlignment = undefined;\n this.firstLineIndent = undefined;\n this.lineSpacingIn = undefined;\n this.lineSpacingType = undefined;\n this.paragraphFormat = undefined;\n /**\n * @private\n */\n this.keyUpParagraphSettings = function (event) {\n if (event.keyCode === 13) {\n _this.applyParagraphFormat();\n }\n };\n this.changeBeforeSpacing = function (event) {\n _this.beforeSpacing = event.value;\n };\n this.changeAfterSpacing = function (event) {\n _this.afterSpacing = event.value;\n };\n this.changeLeftIndent = function (event) {\n _this.leftIndent = event.value;\n };\n this.changeRightIndent = function (event) {\n _this.rightIndent = event.value;\n };\n this.changeLineSpacingValue = function (event) {\n _this.lineSpacingIn = event.value;\n };\n this.changeFirstLineIndent = function (event) {\n _this.firstLineIndent = event.value;\n };\n this.changeByTextAlignment = function (args) {\n _this.textAlignment = args.value;\n };\n /**\n * @private\n */\n this.changeByValue = function (event) {\n var paragraphFormat = _this.owner.selection.paragraphFormat;\n switch (_this.special.index) {\n case 0:\n if (paragraphFormat.firstLineIndent !== 0) {\n _this.byIn.value = 0;\n }\n break;\n case 1:\n if (paragraphFormat.firstLineIndent === 0 || isNullOrUndefined(paragraphFormat.firstLineIndent)) {\n _this.byIn.value = 0.1;\n }\n else if (paragraphFormat.firstLineIndent < 0) {\n _this.byIn.value = -(paragraphFormat.firstLineIndent);\n }\n break;\n case 2:\n if (paragraphFormat.firstLineIndent === 0 || isNullOrUndefined(paragraphFormat.firstLineIndent)) {\n paragraphFormat.firstLineIndent = -0.1;\n }\n else if (paragraphFormat.firstLineIndent > 0) {\n _this.byIn.value = -(paragraphFormat.firstLineIndent);\n }\n break;\n }\n };\n /**\n * @private\n */\n this.changeBySpacing = function (event) {\n if (isNullOrUndefined(_this.lineSpacing)) {\n return;\n }\n switch (_this.lineSpacing.index) {\n case 0:\n _this.lineSpacingType = 'AtLeast';\n _this.atIn.value = 12;\n break;\n case 1:\n _this.lineSpacingType = 'Exactly';\n _this.atIn.value = 12;\n break;\n case 2:\n _this.lineSpacingType = 'Multiple';\n _this.atIn.value = 1;\n break;\n }\n };\n /* tslint:enable */\n /**\n * @private\n */\n this.loadParagraphDialog = function () {\n var selectionFormat;\n if (_this.paragraphFormat) {\n selectionFormat = _this.paragraphFormat;\n }\n else {\n selectionFormat = _this.owner.selection.paragraphFormat;\n }\n var alignValue = _this.alignment.index;\n if (selectionFormat.textAlignment === 'Center') {\n alignValue = 0;\n }\n else if (selectionFormat.textAlignment === 'Left') {\n alignValue = 1;\n }\n else if (selectionFormat.textAlignment === 'Right') {\n alignValue = 2;\n }\n else {\n alignValue = 3;\n }\n _this.alignment.index = alignValue;\n _this.beforeSpacingIn.value = selectionFormat.beforeSpacing;\n _this.afterSpacingIn.value = selectionFormat.afterSpacing;\n _this.leftIndentIn.value = selectionFormat.leftIndent;\n _this.rightIndentIn.value = selectionFormat.rightIndent;\n _this.byIn.value = selectionFormat.firstLineIndent;\n var lineSpaceValue = _this.lineSpacing.index;\n if (selectionFormat.lineSpacingType === 'AtLeast') {\n lineSpaceValue = 0;\n }\n else if (selectionFormat.lineSpacingType === 'Exactly') {\n lineSpaceValue = 1;\n }\n else {\n lineSpaceValue = 2;\n }\n _this.lineSpacing.index = lineSpaceValue;\n _this.atIn.value = selectionFormat.lineSpacing;\n if (_this.owner.selection.caret.style.display !== 'none') {\n _this.owner.selection.caret.style.display = 'none';\n }\n };\n /**\n * @private\n */\n this.applyParagraphFormat = function () {\n var paraFormat;\n var isApply;\n if (_this.paragraphFormat) {\n paraFormat = _this.paragraphFormat;\n isApply = false;\n }\n else {\n paraFormat = new WParagraphFormat();\n isApply = true;\n }\n if (!isNullOrUndefined(_this.beforeSpacing)) {\n paraFormat.beforeSpacing = _this.beforeSpacing;\n }\n if (!isNullOrUndefined(_this.afterSpacing)) {\n paraFormat.afterSpacing = _this.afterSpacing;\n }\n if (!isNullOrUndefined(_this.lineSpacingType)) {\n paraFormat.lineSpacingType = _this.lineSpacingType;\n }\n if (!isNullOrUndefined(_this.leftIndent)) {\n paraFormat.leftIndent = _this.leftIndent;\n }\n if (!isNullOrUndefined(_this.rightIndent)) {\n paraFormat.rightIndent = _this.rightIndent;\n }\n if (!isNullOrUndefined(_this.lineSpacingIn)) {\n paraFormat.lineSpacing = _this.lineSpacingIn;\n }\n if (!isNullOrUndefined(_this.firstLineIndent)) {\n paraFormat.firstLineIndent = _this.firstLineIndent;\n }\n if (!isNullOrUndefined(_this.textAlignment)) {\n paraFormat.textAlignment = _this.textAlignment;\n }\n if (isApply) {\n _this.onParagraphFormat(paraFormat);\n }\n else {\n _this.owner.owner.styleDialogModule.updateParagraphFormat();\n }\n _this.owner.dialog.hide();\n };\n /**\n * @private\n */\n this.closeParagraphDialog = function () {\n _this.leftIndent = undefined;\n _this.afterSpacing = undefined;\n _this.beforeSpacing = undefined;\n _this.firstLineIndent = undefined;\n _this.textAlignment = undefined;\n _this.rightIndent = undefined;\n _this.lineSpacingIn = undefined;\n _this.lineSpacingType = undefined;\n _this.paragraphFormat = undefined;\n _this.owner.dialog.hide();\n _this.owner.updateFocus();\n };\n this.owner = viewer;\n }\n /**\n * @private\n */\n ParagraphDialog.prototype.getModuleName = function () {\n return 'ParagraphDialog';\n };\n /*tslint:disable max-func-body-length*/\n /**\n * @private\n */\n ParagraphDialog.prototype.initParagraphDialog = function (locale) {\n var instance = this;\n var ownerId = this.owner.owner.containerId;\n var id = ownerId + '_paragraph_dialog';\n this.target = createElement('div', { id: id, className: 'e-de-para-dlg-container' });\n // tslint:disable-next-line:max-line-length\n var div = createElement('div', { id: 'property_div', styles: 'width:400px;' });\n var generalDiv = createElement('div', { id: 'genral_div', styles: 'width:200px;height:85px;', className: 'e-de-para-dlg-sub-container' });\n // tslint:disable-next-line:max-line-length\n var genLabel = createElement('div', { id: ownerId + '_genLabel', className: 'e-de-para-dlg-heading', innerHTML: locale.getConstant('General') });\n var alignLabel = createElement('div', { id: ownerId + '_AlignLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Alignment') });\n var alignment = createElement('select', {\n id: ownerId + '_Alignment',\n innerHTML: '' + locale.getConstant('Center') +\n ' ' + locale.getConstant('Left') +\n ' ' + locale.getConstant('Right') +\n ' ' + locale.getConstant('Justify') + ' '\n });\n generalDiv.appendChild(genLabel);\n generalDiv.appendChild(alignLabel);\n generalDiv.appendChild(alignment);\n // tslint:disable-next-line:max-line-length\n var indentionDiv = createElement('div', { id: 'indention_div', styles: 'width: 400px;height: 150px;', className: 'e-de-para-dlg-sub-container' });\n var leftIndentionDiv = createElement('div', { id: 'left_indention', styles: 'float:left;position:relative;' });\n indentionDiv.appendChild(leftIndentionDiv);\n // tslint:disable-next-line:max-line-length\n var rightIndentionDiv = createElement('div', { className: 'e-de-para-dlg-right-sub-container', styles: 'float:right;position:relative;' });\n indentionDiv.appendChild(rightIndentionDiv);\n // tslint:disable-next-line:max-line-length\n var spacingDiv = createElement('div', { id: 'spacing_div', styles: 'width: 400px;height: 150px;', className: 'e-de-para-dlg-sub-container' });\n var leftSpacingDiv = createElement('div', { id: 'left_spacing', styles: 'float:left;position:relative;' });\n spacingDiv.appendChild(leftSpacingDiv);\n // tslint:disable-next-line:max-line-length\n var rightSpacingDiv = createElement('div', { className: 'e-de-para-dlg-right-sub-container', styles: 'float:right;position:relative;' });\n spacingDiv.appendChild(rightSpacingDiv);\n // tslint:disable-next-line:max-line-length\n var indentLabel = createElement('div', {\n id: ownerId + '_indentLabel', className: 'e-de-para-dlg-heading', innerHTML: locale.getConstant('Indentation')\n });\n var beforeTextLabel = createElement('div', {\n id: ownerId + '_bfTextLabel',\n className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Before text')\n });\n // tslint:disable-next-line:max-line-length\n var leftIndent = createElement('input', { id: ownerId + '_leftIndent', attrs: { 'type': 'text' } });\n var specialLabel = createElement('div', { id: ownerId + '_specialLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Special') });\n var special = createElement('select', {\n id: ownerId + '_special',\n innerHTML: '' + locale.getConstant('None') +\n ' ' + locale.getConstant('First line') +\n ' ' + locale.getConstant('Hanging') + ' '\n });\n leftIndentionDiv.appendChild(indentLabel);\n leftIndentionDiv.appendChild(beforeTextLabel);\n leftIndentionDiv.appendChild(leftIndent);\n leftIndentionDiv.appendChild(specialLabel);\n leftIndentionDiv.appendChild(special);\n // tslint:disable-next-line:max-line-length\n var afterTextLabel = createElement('div', { id: ownerId + '_afTextLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('After text') });\n var rightIndent = createElement('input', { id: ownerId + '_rightIndent', attrs: { 'type': 'text' } });\n // tslint:disable-next-line:max-line-length\n var byLabel = createElement('label', { id: ownerId + '_byLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('By') });\n var by = createElement('input', { id: ownerId + '_By', attrs: { 'type': 'text' } });\n rightIndentionDiv.appendChild(afterTextLabel);\n rightIndentionDiv.appendChild(rightIndent);\n rightIndentionDiv.appendChild(byLabel);\n rightIndentionDiv.appendChild(by);\n // tslint:disable-next-line:max-line-length\n var spaceLabel = createElement('div', { innerHTML: locale.getConstant('Spacing'), className: 'e-de-para-dlg-heading', id: ownerId + '_spaceLabel' });\n var beforeLabel = createElement('div', { className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Before'), id: ownerId + '_beforeLabel' });\n // tslint:disable-next-line:max-line-length\n var beforeSpacing = createElement('input', { id: ownerId + '_beforeSpacing', attrs: { 'type': 'text' } });\n var lineSpaceLabel = createElement('div', { id: ownerId + '_lineSpaceLabel', className: 'e-de-dlg-sub-header', innerHTML: locale.getConstant('Line Spacing') });\n // tslint:disable-next-line:max-line-length\n var lineSpacing = createElement('select', {\n id: ownerId + '_lineSpacing', styles: 'width:180px;',\n innerHTML: '' + locale.getConstant('At least') +\n ' ' + locale.getConstant('Exactly') +\n ' ' + locale.getConstant('Multiple') + ' '\n });\n leftSpacingDiv.appendChild(spaceLabel);\n leftSpacingDiv.appendChild(beforeLabel);\n leftSpacingDiv.appendChild(beforeSpacing);\n leftSpacingDiv.appendChild(lineSpaceLabel);\n leftSpacingDiv.appendChild(lineSpacing);\n // tslint:disable-next-line:max-line-length\n var afterLabel = createElement('div', { innerHTML: locale.getConstant('After'), className: 'e-de-dlg-sub-header', id: ownerId + '_afterLabel' });\n var afterSpacing = createElement('input', { id: ownerId + '_afterSpacing', attrs: { 'type': 'text' } });\n // tslint:disable-next-line:max-line-length\n var atLabel = createElement('div', { innerHTML: locale.getConstant('At'), id: ownerId + '_atLabel', className: 'e-de-dlg-sub-header' });\n var lineSpacingAt = createElement('input', { id: ownerId + '_lineSpacingAt', attrs: { 'type': 'text' } });\n rightSpacingDiv.appendChild(afterLabel);\n rightSpacingDiv.appendChild(afterSpacing);\n rightSpacingDiv.appendChild(atLabel);\n rightSpacingDiv.appendChild(lineSpacingAt);\n div.appendChild(generalDiv);\n div.appendChild(indentionDiv);\n div.appendChild(spacingDiv);\n this.target.appendChild(div);\n this.leftIndentIn = new NumericTextBox({\n format: 'n1', value: 0, min: -1584, max: 1584, width: 180, enablePersistence: false, change: this.changeLeftIndent\n });\n this.leftIndentIn.appendTo(leftIndent);\n this.rightIndentIn = new NumericTextBox({\n format: 'n1', value: 0, min: -1584, max: 1584, width: 180, enablePersistence: false, change: this.changeRightIndent\n });\n this.rightIndentIn.appendTo(rightIndent);\n this.byIn = new NumericTextBox({\n format: 'n1', value: 0, min: 0, max: 1584, width: 180, enablePersistence: false, change: this.changeFirstLineIndent\n });\n this.byIn.appendTo(by);\n this.beforeSpacingIn = new NumericTextBox({\n format: 'n1', value: 0, min: 0, max: 1584, width: 180, step: 6, enablePersistence: false,\n change: this.changeBeforeSpacing\n });\n this.beforeSpacingIn.appendTo(beforeSpacing);\n this.afterSpacingIn = new NumericTextBox({\n format: 'n1', value: 0, min: 0, max: 1584, width: 180, step: 6, enablePersistence: false,\n change: this.changeAfterSpacing\n });\n this.afterSpacingIn.appendTo(afterSpacing);\n this.atIn = new NumericTextBox({\n format: 'n1', value: 0, min: 1, max: 1584, width: 180, step: 0.5, enablePersistence: false, change: this.changeLineSpacingValue\n });\n this.special = new DropDownList({ change: this.changeByValue, width: 180 });\n this.special.appendTo(special);\n this.lineSpacing = new DropDownList({ change: this.changeBySpacing, width: '180px' });\n this.lineSpacing.appendTo(lineSpacing);\n this.alignment = new DropDownList({ width: 180, change: this.changeByTextAlignment });\n this.alignment.appendTo(alignment);\n this.atIn.appendTo(lineSpacingAt);\n this.target.addEventListener('keyup', instance.keyUpParagraphSettings);\n };\n /**\n * Applies Paragraph Format\n * @param {WParagraphFormat} paragraphFormat\n * @private\n */\n ParagraphDialog.prototype.onParagraphFormat = function (paragraphFormat) {\n this.owner.owner.editorModule.initHistory('ParagraphFormat');\n var selection = this.owner.selection;\n this.owner.owner.isShiftingEnabled = true;\n if (this.owner.selection.isEmpty) {\n this.owner.owner.editorModule.applyParaFormatProperty(selection.start.paragraph, undefined, paragraphFormat, false);\n this.owner.owner.editor.layoutItemBlock(selection.start.paragraph, false);\n }\n else {\n this.owner.owner.editorModule.updateSelectionParagraphFormatting('ParagraphFormat', paragraphFormat, false);\n }\n this.owner.owner.editorModule.reLayout(selection);\n };\n /**\n * @private\n */\n ParagraphDialog.prototype.show = function (paragraphFormat) {\n if (paragraphFormat) {\n this.paragraphFormat = paragraphFormat;\n }\n var local = new L10n('documenteditor', this.owner.owner.defaultLocale);\n local.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initParagraphDialog(local);\n }\n this.loadParagraphDialog();\n this.owner.dialog.header = 'Paragraph';\n this.owner.dialog.content = this.target;\n this.owner.dialog.height = 'auto';\n this.owner.dialog.width = 'auto';\n this.owner.dialog.buttons = [{\n click: this.applyParagraphFormat,\n buttonModel: { content: local.getConstant('Ok'), cssClass: 'e-flat e-para-okay', isPrimary: true }\n },\n {\n click: this.closeParagraphDialog,\n buttonModel: { content: local.getConstant('Cancel'), cssClass: 'e-flat e-para-cancel' }\n }];\n this.owner.dialog.beforeOpen = this.owner.updateFocus;\n this.owner.dialog.close = this.owner.updateFocus;\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n /**\n * @private\n */\n ParagraphDialog.prototype.destroy = function () {\n if (this.afterSpacingIn) {\n this.afterSpacingIn.destroy();\n this.afterSpacingIn = undefined;\n }\n if (this.beforeSpacingIn) {\n this.beforeSpacingIn.destroy();\n this.beforeSpacingIn = undefined;\n }\n if (this.leftIndentIn) {\n this.leftIndentIn.destroy();\n this.leftIndentIn = undefined;\n }\n if (this.rightIndentIn) {\n this.rightIndentIn.destroy();\n this.rightIndentIn = undefined;\n }\n if (this.byIn) {\n this.byIn.destroy();\n this.byIn = undefined;\n }\n if (this.atIn) {\n this.atIn.destroy();\n this.atIn = undefined;\n }\n if (this.alignment) {\n this.alignment.change = undefined;\n this.alignment.destroy();\n }\n this.alignment = undefined;\n if (this.lineSpacing) {\n this.lineSpacing.change = undefined;\n this.lineSpacing.destroy();\n }\n this.lineSpacing = undefined;\n if (this.special) {\n this.special.change = undefined;\n this.special.destroy();\n }\n this.special = undefined;\n this.owner = undefined;\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var q = 0; q < this.target.childNodes.length; q++) {\n this.target.removeChild(this.target.childNodes[q]);\n q--;\n }\n this.target = undefined;\n }\n };\n return ParagraphDialog;\n}());\nexport { ParagraphDialog };\n","import { WCharacterFormat, WParagraphFormat } from '../format/index';\nimport { WList } from '../list/list';\nimport { WAbstractList } from '../list/abstract-list';\nimport { WListLevel } from '../list/list-level';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * List view model implementation\n * @private\n */\nvar ListViewModel = /** @class */ (function () {\n /**\n * @private\n */\n function ListViewModel() {\n this.listIn = undefined;\n this.levelNumberIn = undefined;\n /**\n * @private\n */\n this.dialog = undefined;\n this.levelNumber = 0;\n }\n Object.defineProperty(ListViewModel.prototype, \"levelNumber\", {\n /**\n * @private\n */\n get: function () {\n return this.levelNumberIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.levelNumberIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ListViewModel.prototype, \"list\", {\n /**\n * @private\n */\n get: function () {\n return this.listIn;\n },\n /**\n * @private\n */\n set: function (value) {\n if (isNullOrUndefined(value)) {\n this.createList();\n }\n else {\n this.listIn = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ListViewModel.prototype, \"listLevel\", {\n /**\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.list) && this.levelNumber >= 0 && this.levelNumber < 9) {\n if (!isNullOrUndefined(this.dialog.owner.getAbstractListById(this.list.abstractListId))) {\n if (this.dialog.owner.getAbstractListById(this.list.abstractListId).levels.length <= this.levelNumber) {\n this.addListLevels();\n }\n return this.dialog.owner.getAbstractListById(this.list.abstractListId).levels[this.levelNumber];\n }\n else {\n this.dialog.owner.lists.push(this.list);\n var abstractList = this.list.abstractList;\n if (!this.list.abstractList) {\n abstractList = new WAbstractList();\n abstractList.abstractListId = this.list.abstractListId;\n }\n var listLevelAdv = new WListLevel(abstractList);\n listLevelAdv.characterFormat = new WCharacterFormat(listLevelAdv);\n listLevelAdv.paragraphFormat = new WParagraphFormat(listLevelAdv);\n listLevelAdv.paragraphFormat.leftIndent = (1) * 48;\n listLevelAdv.paragraphFormat.firstLineIndent = -24;\n listLevelAdv.numberFormat = '%' + (1).toString() + '.';\n listLevelAdv.listLevelPattern = 'UpRoman';\n listLevelAdv.followCharacter = 'Tab';\n listLevelAdv.startAt = 1;\n listLevelAdv.restartLevel = 1;\n this.dialog.owner.abstractLists.push(abstractList);\n return this.dialog.owner.getAbstractListById(this.list.abstractListId).levels[0];\n // return this.dialog.owner.getAbstractListById(this.list.abstractListId).levels.getItem(0);\n }\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ListViewModel.prototype, \"listLevelPattern\", {\n /**\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.listLevel)) {\n return this.listLevel.listLevelPattern;\n }\n return 'Arabic';\n },\n /**\n * @private\n */\n set: function (value) {\n if (!isNullOrUndefined(this.listLevel)) {\n this.listLevel.listLevelPattern = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ListViewModel.prototype, \"followCharacter\", {\n /**\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.listLevel)) {\n return this.listLevel.followCharacter;\n }\n return 'None';\n },\n /**\n * @private\n */\n set: function (value) {\n if (!isNullOrUndefined(this.listLevel)) {\n this.listLevel.followCharacter = value;\n }\n },\n enumerable: true,\n configurable: true\n });\n ListViewModel.prototype.createList = function () {\n this.list = new WList();\n this.list.listId = this.dialog.owner.lists.length + 1;\n var abstractList = new WAbstractList();\n abstractList.abstractListId = this.dialog.owner.abstractLists.length + 1;\n this.list.abstractListId = abstractList.abstractListId;\n this.dialog.owner.lists.push(this.list);\n var listLevel = new WListLevel(abstractList);\n listLevel.paragraphFormat = new WParagraphFormat(listLevel);\n listLevel.paragraphFormat.leftIndent = 48;\n listLevel.paragraphFormat.firstLineIndent = -24;\n listLevel.characterFormat = new WCharacterFormat(listLevel);\n listLevel.numberFormat = '%1.';\n listLevel.startAt = 1;\n abstractList.levels.push(listLevel);\n this.dialog.owner.abstractLists.push(abstractList);\n };\n ListViewModel.prototype.addListLevels = function () {\n if (!isNullOrUndefined(this.list) && !isNullOrUndefined(this.list.abstractListId)) {\n for (var i = this.dialog.owner.getAbstractListById(this.list.abstractListId).levels.length; i < 9; i++) {\n var listLevelAdv = new WListLevel(this.dialog.owner.getAbstractListById(this.list.abstractListId));\n listLevelAdv.characterFormat = new WCharacterFormat(listLevelAdv);\n listLevelAdv.paragraphFormat = new WParagraphFormat(listLevelAdv);\n listLevelAdv.paragraphFormat.leftIndent = (i + 1) * 48;\n listLevelAdv.paragraphFormat.firstLineIndent = -24;\n listLevelAdv.numberFormat = '%' + (i + 1).toString() + '.';\n listLevelAdv.listLevelPattern = 'Arabic';\n listLevelAdv.followCharacter = 'Tab';\n listLevelAdv.startAt = 1;\n listLevelAdv.restartLevel = i;\n (this.dialog.owner).getAbstractListById(this.list.abstractListId).levels.push(listLevelAdv);\n }\n }\n };\n /**\n * @private\n */\n ListViewModel.prototype.destroy = function () {\n this.list = undefined;\n this.followCharacter = undefined;\n this.levelNumber = undefined;\n this.listLevelPattern = undefined;\n };\n return ListViewModel;\n}());\nexport { ListViewModel };\n","import { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { createElement, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\n// tslint:disable-next-line:max-line-length\nimport { WCharacterFormat, WParagraphFormat } from '../format/index';\nimport { WAbstractList } from '../list/abstract-list';\nimport { WLevelOverride } from '../list/level-override';\nimport { DropDownList } from '@syncfusion/ej2-dropdowns';\nimport { Tooltip } from '@syncfusion/ej2-popups';\nimport { ListViewModel } from './list-view-model';\n/**\n * The List dialog is used to create or modify lists.\n */\n/* tslint:disable:no-any */\nvar ListDialog = /** @class */ (function () {\n /**\n * @private\n */\n function ListDialog(viewer) {\n var _this = this;\n /**\n * @private\n */\n this.dialog = undefined;\n this.target = undefined;\n /**\n * @private\n */\n this.owner = undefined;\n this.viewModel = undefined;\n this.startAt = undefined;\n this.textIndent = undefined;\n this.alignedAt = undefined;\n this.listLevelElement = undefined;\n this.followNumberWith = undefined;\n this.numberStyle = undefined;\n this.numberFormat = undefined;\n this.restartBy = undefined;\n /**\n * @private\n */\n this.isListCharacterFormat = false;\n this.onTextIndentChanged = function (args) {\n _this.viewModel.listLevel.paragraphFormat.leftIndent = args.value;\n };\n this.onStartValueChanged = function (args) {\n _this.viewModel.listLevel.startAt = args.value;\n };\n this.onListLevelValueChanged = function (args) {\n _this.viewModel.levelNumber = parseInt(args.value.slice(args.value.length - 1), 10) - 1;\n if (isNullOrUndefined(_this.listLevel)) {\n return;\n }\n if (isNullOrUndefined(_this.listLevel.characterFormat)) {\n _this.listLevel.characterFormat = new WCharacterFormat(_this.viewModel.listLevel);\n }\n if (!isNullOrUndefined(_this.listLevel.paragraphFormat)) {\n _this.listLevel.paragraphFormat = new WParagraphFormat(_this.viewModel.listLevel);\n }\n _this.updateDialogValues();\n _this.updateRestartLevelBox();\n };\n this.onNumberFormatChanged = function (args) {\n _this.viewModel.listLevel.numberFormat = args.target.value;\n };\n this.onAlignedAtValueChanged = function (args) {\n _this.viewModel.listLevel.paragraphFormat.firstLineIndent = args.value;\n };\n this.onFollowCharacterValueChanged = function (args) {\n if (args.value) {\n _this.viewModel.followCharacter = args.value;\n }\n };\n this.onLevelPatternValueChanged = function (args) {\n _this.viewModel.listLevelPattern = args.value;\n var numberFormat = '%' + (_this.levelNumber + 1).toString();\n // tslint:disable-next-line:max-line-length\n var numberFormatTextBox = document.getElementById(_this.owner.owner.containerId + '_numberFormat');\n if (_this.listLevel.listLevelPattern === 'Bullet') {\n _this.listLevel.numberFormat = '\\uf0b7';\n numberFormatTextBox.value = _this.listLevel.numberFormat;\n _this.listLevel.characterFormat.fontFamily = 'Wingdings';\n }\n else {\n if (_this.listLevel.listLevelPattern === 'None') {\n _this.listLevel.numberFormat = '';\n }\n if (!_this.listLevel.numberFormat.match(numberFormat) && _this.listLevel.listLevelPattern !== 'None') {\n _this.listLevel.numberFormat = numberFormat + '.';\n }\n numberFormatTextBox.value = _this.listLevel.numberFormat;\n }\n };\n this.loadListDialog = function () {\n _this.owner.updateFocus();\n if (isNullOrUndefined(_this.owner.owner)) {\n return;\n }\n _this.viewModel = new ListViewModel();\n _this.viewModel.dialog = _this;\n if (_this.owner.selection.paragraphFormat.listLevelNumber > 0) {\n _this.viewModel.levelNumber = _this.owner.selection.paragraphFormat.listLevelNumber;\n }\n _this.viewModel.list = _this.owner.selection.paragraphFormat.getList();\n if (isNullOrUndefined(_this.listLevel)) {\n return;\n }\n if (isNullOrUndefined(_this.listLevel.characterFormat)) {\n _this.listLevel.characterFormat = new WCharacterFormat(_this.viewModel.listLevel);\n }\n if (isNullOrUndefined(_this.listLevel.paragraphFormat)) {\n _this.listLevel.paragraphFormat = new WParagraphFormat(_this.viewModel.listLevel);\n }\n _this.updateDialogValues();\n if (_this.owner.selection.caret.style.display !== 'none') {\n _this.owner.selection.caret.style.display = 'none';\n }\n };\n this.showFontDialog = function () {\n _this.owner.owner.fontDialogModule.showFontDialog(_this.listLevel.characterFormat);\n };\n this.onApplyList = function () {\n if (!isNullOrUndefined(_this.owner)) {\n _this.owner.selection.paragraphFormat.setList(_this.list);\n }\n _this.owner.dialog2.hide();\n _this.owner.updateFocus();\n };\n this.onCancelButtonClick = function () {\n _this.disposeBindingForListUI();\n _this.owner.dialog2.hide();\n _this.owner.updateFocus();\n _this.isListCharacterFormat = false;\n };\n this.closeListDialog = function () {\n _this.disposeBindingForListUI();\n _this.owner.updateFocus();\n _this.isListCharacterFormat = false;\n };\n this.owner = viewer;\n this.viewModel = new ListViewModel();\n }\n Object.defineProperty(ListDialog.prototype, \"listLevel\", {\n /**\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.viewModel)) {\n return this.viewModel.listLevel;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ListDialog.prototype, \"list\", {\n /**\n * @private\n */\n get: function () {\n if (!isNullOrUndefined(this.viewModel)) {\n return this.viewModel.list;\n }\n return undefined;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ListDialog.prototype, \"levelNumber\", {\n /**\n * @private\n */\n get: function () {\n if (this.listLevel.ownerBase instanceof WLevelOverride) {\n return this.listLevel.ownerBase.levelNumber;\n // tslint:disable-next-line:max-line-length\n }\n else if (this.listLevel.ownerBase instanceof WAbstractList && !isNullOrUndefined(this.listLevel.ownerBase.levels)) {\n return this.listLevel.ownerBase.levels.indexOf(this.listLevel);\n }\n else {\n return -1;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n ListDialog.prototype.getModuleName = function () {\n return 'ListDialog';\n };\n /**\n * @private\n */\n ListDialog.prototype.showListDialog = function () {\n var locale = new L10n('documenteditor', this.owner.owner.defaultLocale);\n locale.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initListDialog(locale);\n }\n this.isListCharacterFormat = true;\n this.owner.dialog2.header = locale.getConstant('Define new Multilevel list');\n this.owner.dialog2.height = 'auto';\n this.owner.dialog2.width = 'auto';\n this.owner.dialog2.content = this.target;\n this.owner.dialog2.buttons = [{\n click: this.showFontDialog,\n buttonModel: { content: locale.getConstant('Font'), cssClass: 'e-flat e-list-dlg-font e-font' }\n }, {\n click: this.onApplyList,\n buttonModel: { content: locale.getConstant('Ok'), cssClass: 'e-flat e-list-dlg', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: locale.getConstant('Cancel'), cssClass: 'e-flat e-list-dlg' }\n }];\n this.owner.dialog2.dataBind();\n this.owner.dialog2.beforeOpen = this.loadListDialog;\n this.owner.dialog2.close = this.closeListDialog;\n this.owner.dialog2.position = { X: 'center', Y: 'top' };\n this.owner.dialog2.show();\n };\n /**\n * Shows the table properties dialog\n * @private\n */\n ListDialog.prototype.initListDialog = function (locale) {\n var instance = this;\n var containerId = this.owner.owner.containerId;\n var id = containerId + '_insert_list';\n this.target = createElement('div', { id: id, className: 'e-de-list-dlg' });\n this.owner.owner.element.appendChild(this.target);\n // tslint:disable-next-line:max-line-length\n var listLevelDiv = createElement('div', { innerHTML: '' + locale.getConstant('Level') + ' 1' + ' ' + locale.getConstant('Level') + ' 2' + ' ' + locale.getConstant('Level') + ' 3' + ' ' + locale.getConstant('Level') + ' 4' + ' ' + locale.getConstant('Level') + ' 5' + ' ' + locale.getConstant('Level') + ' 6' + ' ' + locale.getConstant('Level') + ' 7' + ' ' + locale.getConstant('Level') + ' 8' + ' ' + locale.getConstant('Level') + ' 9' + ' ' });\n this.target.appendChild(listLevelDiv);\n var div = createElement('div');\n // tslint:disable-next-line:max-line-length\n var numberStyleDiv = createElement('div', { innerHTML: '' });\n div.appendChild(numberFormatDiv);\n this.target.appendChild(div);\n // tslint:disable-next-line:max-line-length\n var indentsDiv = createElement('div', { innerHTML: '' + locale.getConstant('Tab character') + ' ' + locale.getConstant('Space') + ' ' + locale.getConstant('Nothing') + '
', });\n this.target.appendChild(indentsDiv);\n var startAtTextBox = document.getElementById(containerId + '_startAt');\n var textIndentAtTextBox = document.getElementById(containerId + '_textIndent');\n var alignedAtTextBox = document.getElementById(containerId + '_alignedAt');\n this.startAt = new NumericTextBox({\n format: '#',\n decimals: 0,\n min: 0,\n max: 50,\n width: '180px',\n enablePersistence: false,\n });\n this.startAt.addEventListener('change', instance.onStartValueChanged);\n this.startAt.appendTo(startAtTextBox);\n this.textIndent = new NumericTextBox({\n format: '#',\n decimals: 0,\n min: 0,\n max: 1584,\n width: '180px',\n step: 4,\n enablePersistence: false\n });\n this.textIndent.addEventListener('change', instance.onTextIndentChanged);\n this.textIndent.appendTo(textIndentAtTextBox);\n this.alignedAt = new NumericTextBox({\n format: '#',\n max: 1584,\n step: 6,\n width: '180px',\n enablePersistence: false\n });\n this.alignedAt.addEventListener('change', instance.onAlignedAtValueChanged);\n this.alignedAt.appendTo(alignedAtTextBox);\n var listLevel = document.getElementById(containerId + '_listLevel');\n this.listLevelElement = new DropDownList({ popupHeight: '150px', width: '180px', change: instance.onListLevelValueChanged });\n this.listLevelElement.appendTo(listLevel);\n var followCharacterElement = document.getElementById(containerId + '_followCharacter');\n this.followNumberWith = new DropDownList({ popupHeight: '150px', width: '180px', change: instance.onFollowCharacterValueChanged });\n this.followNumberWith.appendTo(followCharacterElement);\n var numberStyleEle = document.getElementById(containerId + '_numberStyle');\n this.numberStyle = new DropDownList({ popupHeight: '150px', width: '180px', change: instance.onLevelPatternValueChanged });\n this.numberStyle.appendTo(numberStyleEle);\n this.numberFormat = document.getElementById(containerId + '_numberFormat');\n this.numberFormat.addEventListener('change', instance.onNumberFormatChanged);\n var restartElement = document.getElementById(containerId + '_restartBy');\n this.restartBy = new DropDownList({ popupHeight: '150px', width: '180px' });\n this.restartBy.appendTo(restartElement);\n var button = document.getElementById(containerId + '_list_info');\n this.formatInfoToolTip = new Tooltip({ width: 200 });\n // tslint:disable-next-line:max-line-length\n this.formatInfoToolTip.content = locale.getConstant('Number format tooltip information');\n this.formatInfoToolTip.position = 'RightTop';\n this.formatInfoToolTip.appendTo(button);\n };\n ListDialog.prototype.updateRestartLevelBox = function () {\n var containerId = this.owner.owner.containerId;\n var listLevel = document.getElementById(containerId + '_listLevel');\n var restartBy = document.getElementById(containerId + '_restartBy');\n for (var i = 0; i < restartBy.options.length; i) {\n restartBy.options.remove(i);\n }\n if (listLevel.selectedIndex === 0) {\n var option = document.createElement('option');\n option.value = 'No Restart';\n option.innerHTML = 'No Restart';\n restartBy.appendChild(option);\n }\n else {\n for (var i = listLevel.selectedIndex; i > 0; i--) {\n var option_1 = document.createElement('option');\n option_1.value = 'Level ' + i;\n option_1.innerHTML = 'Level ' + i;\n restartBy.appendChild(option_1);\n }\n var option = document.createElement('option');\n option.value = 'No Restart';\n option.innerHTML = 'No Restart';\n restartBy.appendChild(option);\n }\n restartBy.selectedIndex = 0;\n };\n ListDialog.prototype.listPatternConverter = function (listLevelPattern) {\n switch (listLevelPattern) {\n case 'Arabic': return 0;\n case 'UpRoman': return 1;\n case 'LowRoman': return 2;\n case 'UpLetter': return 3;\n case 'LowLetter': return 4;\n case 'Number': return 5;\n case 'LeadingZero': return 6;\n case 'Bullet': return 7;\n case 'Ordinal': return 8;\n case 'OrdinalText': return 9;\n case 'Special': return 10;\n case 'FarEast': return 11;\n default: return 12;\n }\n };\n ListDialog.prototype.followCharacterConverter = function (followCharacter) {\n switch (followCharacter) {\n case 'Tab':\n return 0;\n case 'Space':\n return 1;\n default:\n return 2;\n }\n };\n ListDialog.prototype.updateDialogValues = function () {\n // tslint:disable-next-line:max-line-length\n var restartByTextBox = document.getElementById(this.owner.owner.containerId + '_restartBy');\n this.startAt.value = this.viewModel.listLevel.startAt;\n this.textIndent.value = this.viewModel.listLevel.paragraphFormat.leftIndent;\n this.alignedAt.value = this.viewModel.listLevel.paragraphFormat.firstLineIndent;\n this.followNumberWith.index = this.followCharacterConverter(this.viewModel.followCharacter);\n this.numberFormat.value = this.viewModel.listLevel.numberFormat;\n this.numberStyle.index = this.listPatternConverter(this.viewModel.listLevelPattern);\n this.listLevelElement.index = this.viewModel.levelNumber;\n this.viewModel.levelNumber = this.viewModel.levelNumber;\n };\n ListDialog.prototype.disposeBindingForListUI = function () {\n this.followNumberWith.index = -1;\n this.numberFormat.value = ' ';\n this.numberStyle.index = -1;\n this.listLevelElement.index = -1;\n this.restartBy.index = -1;\n this.viewModel.destroy();\n };\n /**\n * @private\n */\n ListDialog.prototype.destroy = function () {\n if (this.alignedAt) {\n this.alignedAt.destroy();\n }\n this.alignedAt = undefined;\n this.dialog = undefined;\n if (this.followNumberWith) {\n this.followNumberWith.destroy();\n }\n this.followNumberWith = undefined;\n if (this.listLevelElement) {\n this.listLevelElement.destroy();\n }\n this.listLevelElement = undefined;\n if (this.textIndent) {\n this.textIndent.destroy();\n }\n this.textIndent = undefined;\n if (this.startAt) {\n this.startAt.destroy();\n }\n this.startAt = undefined;\n if (this.numberStyle) {\n this.numberStyle.destroy();\n }\n this.numberStyle = undefined;\n this.numberFormat = undefined;\n if (this.restartBy) {\n this.restartBy.destroy();\n }\n this.restartBy = undefined;\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var l = 0; l < this.target.childNodes.length; l++) {\n this.target.removeChild(this.target.childNodes[l]);\n l--;\n }\n this.target = undefined;\n }\n this.owner = undefined;\n this.viewModel = undefined;\n };\n return ListDialog;\n}());\nexport { ListDialog };\n/* tslint:enable:no-any */ \n","import { createElement, isNullOrUndefined, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { DropDownList, ComboBox } from '@syncfusion/ej2-dropdowns';\nimport { Button } from '@syncfusion/ej2-buttons';\nimport { WCharacterStyle, WParagraphStyle } from '../../implementation/format/style';\nimport { BulletsAndNumberingDialog } from './index';\nimport { WAbstractList } from '../list/abstract-list';\nimport { ColorPicker } from '@syncfusion/ej2-inputs';\nimport { DropDownButton } from '@syncfusion/ej2-splitbuttons';\n/**\n * The Style dialog is used to create or modify styles.\n */\nvar StyleDialog = /** @class */ (function () {\n /**\n * @private\n */\n function StyleDialog(viewer) {\n var _this = this;\n this.target = undefined;\n this.styleType = undefined;\n this.styleBasedOn = undefined;\n this.styleParagraph = undefined;\n this.onlyThisDocument = undefined;\n this.template = undefined;\n this.fontFamily = undefined;\n this.fontSize = undefined;\n this.characterFormat = undefined;\n this.paragraphFormat = undefined;\n /* tslint:disable-next-line:no-any */\n this.openDialog = function (args) {\n switch (args.item.id) {\n case 'style_font':\n _this.showFontDialog();\n break;\n case 'style_paragraph':\n _this.showParagraphDialog();\n break;\n case 'style_numbering':\n _this.showNumberingBulletDialog();\n break;\n }\n };\n this.setBoldProperty = function () {\n _this.characterFormat.bold = !_this.characterFormat.bold;\n _this.fontButtonClicked(undefined);\n };\n this.setItalicProperty = function () {\n _this.characterFormat.italic = !_this.characterFormat.italic;\n _this.fontButtonClicked(undefined);\n };\n this.setUnderlineProperty = function () {\n _this.characterFormat.underline = _this.characterFormat.underline === 'None' ? 'Single' : 'None';\n _this.fontButtonClicked(undefined);\n };\n /* tslint:disable-next-line:no-any */\n this.fontButtonClicked = function (args) {\n if (_this.characterFormat.bold) {\n if (!_this.bold.classList.contains('e-active')) {\n _this.bold.classList.add('e-active');\n }\n }\n else {\n if (_this.bold.classList.contains('e-active')) {\n _this.bold.classList.remove('e-active');\n }\n }\n if (_this.characterFormat.italic) {\n if (!_this.italic.classList.contains('e-active')) {\n _this.italic.classList.add('e-active');\n }\n }\n else {\n if (_this.italic.classList.contains('e-active')) {\n _this.italic.classList.remove('e-active');\n }\n }\n if (_this.characterFormat.underline !== undefined && _this.characterFormat.underline !== 'None') {\n if (!_this.underline.classList.contains('e-active')) {\n _this.underline.classList.add('e-active');\n _this.characterFormat.underline = 'Single';\n }\n }\n else {\n if (_this.underline.classList.contains('e-active')) {\n _this.underline.classList.remove('e-active');\n _this.characterFormat.underline = 'None';\n }\n }\n };\n /* tslint:disable-next-line:no-any */\n this.fontSizeUpdate = function (args) {\n _this.characterFormat.fontSize = args.value;\n };\n /* tslint:disable-next-line:no-any */\n this.fontFamilyChanged = function (args) {\n _this.characterFormat.fontFamily = args.value;\n };\n /* tslint:disable-next-line:no-any */\n this.fontColorUpdate = function (args) {\n _this.characterFormat.fontColor = args.currentValue.rgba;\n };\n this.setLeftAlignment = function () {\n if (_this.paragraphFormat.textAlignment === 'Left') {\n _this.paragraphFormat.textAlignment = 'Justify';\n }\n else {\n _this.paragraphFormat.textAlignment = 'Left';\n }\n _this.updateParagraphFormat();\n };\n this.setRightAlignment = function () {\n if (_this.paragraphFormat.textAlignment === 'Right') {\n _this.paragraphFormat.textAlignment = 'Left';\n }\n else {\n _this.paragraphFormat.textAlignment = 'Right';\n }\n _this.updateParagraphFormat();\n };\n this.setCenterAlignment = function () {\n if (_this.paragraphFormat.textAlignment === 'Center') {\n _this.paragraphFormat.textAlignment = 'Left';\n }\n else {\n _this.paragraphFormat.textAlignment = 'Center';\n }\n _this.updateParagraphFormat();\n };\n this.setJustifyAlignment = function () {\n if (_this.paragraphFormat.textAlignment === 'Justify') {\n _this.paragraphFormat.textAlignment = 'Left';\n }\n else {\n _this.paragraphFormat.textAlignment = 'Justify';\n }\n _this.updateParagraphFormat();\n };\n this.increaseBeforeAfterSpacing = function () {\n _this.paragraphFormat.beforeSpacing += 6;\n _this.paragraphFormat.afterSpacing += 6;\n };\n this.decreaseBeforeAfterSpacing = function () {\n if (_this.paragraphFormat.beforeSpacing >= 6) {\n _this.paragraphFormat.beforeSpacing -= 6;\n }\n else {\n _this.paragraphFormat.beforeSpacing = 0;\n }\n if (_this.paragraphFormat.afterSpacing >= 6) {\n _this.paragraphFormat.afterSpacing -= 6;\n }\n else {\n _this.paragraphFormat.afterSpacing = 0;\n }\n };\n /**\n * @private\n */\n this.updateNextStyle = function (args) {\n var typedName = args.srcElement.value;\n if (_this.getTypeValue() === 'Paragraph' && !isNullOrUndefined(typedName) && typedName !== '' && !_this.isUserNextParaUpdated) {\n var styles = _this.owner.owner.viewer.styles.getStyleNames(_this.getTypeValue());\n if (_this.isEdit) {\n styles = styles.filter(function (e) { return e !== _this.editStyleName; });\n }\n styles.push(typedName);\n _this.styleParagraph.dataSource = styles;\n _this.styleParagraph.index = null;\n _this.styleParagraph.index = styles.indexOf(typedName);\n _this.styleParagraph.dataBind();\n }\n };\n /**\n * @private\n */\n this.updateOkButton = function () {\n var styleName = _this.target.getElementsByClassName('e-input e-de-style-dlg-name-input').item(0).value;\n _this.enableOrDisableOkButton();\n };\n /**\n * @private\n */\n /* tslint:disable-next-line:no-any */\n this.styleTypeChange = function (args) {\n if (args.isInteracted) {\n var type = void 0;\n if (args.value === 'Character') {\n _this.style = new WCharacterStyle();\n type = 'Character';\n }\n if (args.value === 'Paragraph' || args.value === 'Linked(Paragraph and Character)') {\n _this.style = new WParagraphStyle();\n type = 'Paragraph';\n }\n _this.toggleDisable();\n _this.updateStyleNames(type);\n }\n };\n /* tslint:disable-next-line:no-any */\n this.styleBasedOnChange = function (args) {\n //Based on change\n };\n /**\n * @private\n */\n /* tslint:disable-next-line:no-any */\n this.styleParagraphChange = function (args) {\n if (args.isInteracted) {\n _this.isUserNextParaUpdated = true;\n }\n //Next change\n };\n /**\n * @private\n */\n this.showFontDialog = function () {\n if (!isNullOrUndefined(_this.owner.owner.fontDialogModule)) {\n _this.owner.owner.showFontDialog(_this.characterFormat);\n }\n _this.updateCharacterFormat();\n };\n /**\n * @private\n */\n this.showParagraphDialog = function () {\n if (!isNullOrUndefined(_this.owner.owner.paragraphDialogModule)) {\n _this.owner.owner.showParagraphDialog(_this.paragraphFormat);\n }\n };\n /**\n * @private\n */\n this.showNumberingBulletDialog = function () {\n _this.numberingBulletDialog = new BulletsAndNumberingDialog(_this.owner.owner.viewer);\n if (_this.style instanceof WParagraphStyle && (!isNullOrUndefined(_this.style.paragraphFormat))) {\n // tslint:disable-next-line:max-line-length\n _this.numberingBulletDialog.showNumberBulletDialog(_this.style.paragraphFormat.listFormat, _this.abstractList);\n }\n };\n /**\n * @private\n */\n this.onOkButtonClick = function () {\n var styleName = _this.styleNameElement.value;\n if (styleName.length > 0) {\n var style = _this.owner.owner.viewer.styles.findByName(styleName);\n var name_1;\n if (!isNullOrUndefined(style)) {\n _this.style.type = _this.getTypeValue();\n _this.style.basedOn = _this.owner.owner.viewer.styles.findByName(_this.styleBasedOn.value);\n if (_this.styleType.value === 'Paragraph' || _this.styleType.value === 'Linked(Paragraph and Character)') {\n _this.style.next = _this.owner.owner.viewer.styles.findByName(_this.styleParagraph.value);\n _this.style.characterFormat.mergeFormat(style.characterFormat);\n _this.style.paragraphFormat.mergeFormat(style.paragraphFormat);\n _this.updateList();\n // tslint:disable-next-line:max-line-length\n _this.style.link = (_this.styleType.value === 'Linked(Paragraph and Character)') ? _this.createLinkStyle(styleName, _this.isEdit) : undefined;\n }\n //Updating existing style implementation\n _this.style.name = style.name;\n name_1 = style.name;\n style = _this.style;\n _this.owner.owner.isShiftingEnabled = true;\n _this.owner.owner.editorModule.layoutWholeDocument();\n _this.owner.owner.isShiftingEnabled = false;\n }\n else {\n /* tslint:disable-next-line:no-any */\n var basedOn = _this.owner.owner.viewer.styles.findByName(_this.styleBasedOn.value);\n if (_this.styleType.value === 'Paragraph' || _this.styleType.value === 'Linked(Paragraph and Character)') {\n if (styleName === _this.styleParagraph.value) {\n _this.style.next = _this.style;\n }\n else {\n _this.style.next = _this.owner.owner.viewer.styles.findByName(_this.styleParagraph.value);\n }\n _this.updateList();\n }\n // tslint:disable-next-line:max-line-length\n _this.style.link = (_this.styleType.value === 'Linked(Paragraph and Character)') ? _this.createLinkStyle(styleName) : undefined;\n _this.style.type = _this.getTypeValue();\n _this.style.name = styleName;\n _this.style.basedOn = basedOn;\n /* tslint:disable-next-line:no-any */\n _this.owner.owner.viewer.styles.push(_this.style);\n name_1 = styleName;\n _this.owner.owner.editorModule.applyStyle(name_1);\n }\n _this.owner.owner.viewer.dialog2.hide();\n }\n else {\n throw new Error('Enter valid Style name');\n }\n if (_this.style) {\n //this.style.destroy();\n }\n };\n /* tslint:disable-next-line:no-any */\n this.loadStyleDialog = function (args) {\n _this.owner.owner.viewer.updateFocus();\n _this.isUserNextParaUpdated = false;\n /* tslint:disable-next-line:max-line-length */\n _this.styleNameElement = _this.target.getElementsByClassName('e-input e-de-style-dlg-name-input').item(0);\n _this.styleNameElement.value = null;\n if (!_this.isEdit) {\n _this.styleType.index = 0; //Set to paragraph \n }\n var name;\n if (_this.isEdit) {\n _this.styleNameElement.value = _this.editStyleName;\n name = _this.editStyleName;\n }\n /* tslint:disable-next-line:max-line-length */\n _this.okButton = _this.owner.dialog2.element.getElementsByClassName('e-flat e-style-okay').item(0);\n _this.enableOrDisableOkButton();\n _this.updateStyleNames(_this.getTypeValue(), name);\n _this.updateCharacterFormat(_this.style.characterFormat);\n _this.updateParagraphFormat(_this.style.paragraphFormat);\n };\n /**\n * @private\n */\n this.onCancelButtonClick = function () {\n if (!_this.isEdit && _this.style) {\n _this.style.destroy();\n }\n _this.owner.owner.viewer.dialog2.hide();\n };\n /**\n * @private\n */\n this.closeStyleDialog = function () {\n _this.owner.owner.viewer.updateFocus();\n };\n this.owner = viewer;\n }\n /**\n * @private\n */\n StyleDialog.prototype.getModuleName = function () {\n return 'StyleDialog';\n };\n /**\n * @private\n */\n //tslint:disable: max-func-body-length\n StyleDialog.prototype.initStyleDialog = function (localValue) {\n var instance = this;\n var id = this.owner.owner.containerId + '_style';\n this.target = createElement('div', { id: id, className: 'e-de-style-dialog' });\n var container = createElement('div');\n // tslint:disable-next-line:max-line-length\n var properties = createElement('div', { className: 'e-de-style-properties', innerHTML: localValue.getConstant('Properties') });\n container.appendChild(properties);\n var styleNameTypeDiv = createElement('div', { styles: 'display:flex', className: 'e-de-style-nametype-div' });\n container.appendChild(styleNameTypeDiv);\n var nameWholeDiv = createElement('div', { className: 'e-de-style-left-div' });\n styleNameTypeDiv.appendChild(nameWholeDiv);\n var name = createElement('div', { className: 'e-de-style-name', innerHTML: localValue.getConstant('Name') + ':' });\n nameWholeDiv.appendChild(name);\n // tslint:disable-next-line:max-line-length\n var nameValue = createElement('input', { id: this.owner.owner.containerId + '_style_name', styles: 'width:210px;', className: 'e-input e-de-style-dlg-name-input' });\n nameValue.addEventListener('keyup', this.updateOkButton);\n nameValue.addEventListener('input', this.updateOkButton);\n nameValue.addEventListener('blur', this.updateNextStyle);\n nameWholeDiv.appendChild(nameValue);\n var styleTypeWholeDiv = createElement('div');\n styleNameTypeDiv.appendChild(styleTypeWholeDiv);\n // tslint:disable-next-line:max-line-length\n var styleType = createElement('div', { className: 'e-de-style-styletype', innerHTML: localValue.getConstant('Style type') + ':' });\n styleTypeWholeDiv.appendChild(styleType);\n var styleTypeDivElement = createElement('div', { className: 'e-de-style-style-type-div' });\n var styleTypeValue = createElement('select', { id: 'e-de-style-style-type' });\n // tslint:disable-next-line:max-line-length\n styleTypeValue.innerHTML = 'Paragraph Character Linked(Paragraph and Character) '; //Linked(Paragraph and Character) Table List ';\n styleTypeDivElement.appendChild(styleTypeValue);\n this.styleType = new DropDownList({ change: this.styleTypeChange, popupHeight: '253px', width: '210px' });\n this.styleType.appendTo(styleTypeValue);\n styleTypeWholeDiv.appendChild(styleTypeDivElement);\n // tslint:disable-next-line:max-line-length\n var styleBasedParaDiv = createElement('div', { styles: 'display:flex', className: 'e-de-style-based-para-div' });\n container.appendChild(styleBasedParaDiv);\n var styleBasedOnWholeDiv = createElement('div', { className: 'e-de-style-left-div' });\n styleBasedParaDiv.appendChild(styleBasedOnWholeDiv);\n // tslint:disable-next-line:max-line-length\n var styleBasedOn = createElement('div', { className: 'e-de-style-style-based-on', innerHTML: localValue.getConstant('Style based on') + ':' });\n styleBasedOnWholeDiv.appendChild(styleBasedOn);\n var styleBasedOnDivElement = createElement('div', { className: 'e-de-style-style-based-on-div' });\n // tslint:disable-next-line:max-line-length\n var styleBasedOnValue = createElement('input', { id: 'e-de-style-style-based-on-value' });\n //styleBasedOnValue.innerHTML = 'Normal Heading 1 Heading 2 Heading 3 Heading 4 Heading 5 Heading 6 ';\n styleBasedOnDivElement.appendChild(styleBasedOnValue);\n this.styleBasedOn = new DropDownList({ dataSource: [], select: this.styleBasedOnChange, popupHeight: '253px', width: '210px' });\n this.styleBasedOn.appendTo(styleBasedOnValue);\n styleBasedOnWholeDiv.appendChild(styleBasedOnDivElement);\n var styleParagraphWholeDiv = createElement('div', { className: 'e-de-style-left-div' });\n styleBasedParaDiv.appendChild(styleParagraphWholeDiv);\n // tslint:disable-next-line:max-line-length\n var styleParagraph = createElement('div', { className: 'e-de-style-style-paragraph', innerHTML: localValue.getConstant('Style for following paragraph') + ':' });\n styleParagraphWholeDiv.appendChild(styleParagraph);\n var styleParagraphDivElement = createElement('div', { className: 'e-de-style-style-paragraph-div' });\n // tslint:disable-next-line:max-line-length\n var styleParagraphValue = createElement('input', { id: 'e-de-style-style-paragraph-value' });\n // tslint:disable-next-line:max-line-length\n //styleParagraphValue.innerHTML = 'Normal Heading 1 Heading 2 Heading 3 Heading 4 Heading 5 Heading 6 ';\n styleParagraphDivElement.appendChild(styleParagraphValue);\n this.styleParagraph = new DropDownList({ dataSource: [], select: this.styleParagraphChange, popupHeight: '253px', width: '210px' });\n this.styleParagraph.appendTo(styleParagraphValue);\n styleParagraphWholeDiv.appendChild(styleParagraphDivElement);\n // tslint:disable-next-line:max-line-length\n var formatting = createElement('div', { className: 'e-de-style-formatting', innerHTML: localValue.getConstant('Formatting') });\n container.appendChild(formatting);\n var optionsDiv = createElement('div', { className: 'e-de-style-options-div' });\n container.appendChild(optionsDiv);\n var fontOptionsDiv = createElement('div', { styles: 'display:flex;margin-bottom: 15px;' });\n optionsDiv.appendChild(fontOptionsDiv);\n this.createFontOptions(fontOptionsDiv);\n var paragraphOptionsDiv = createElement('div', { styles: 'display:flex', className: 'e-style-paragraph' });\n optionsDiv.appendChild(paragraphOptionsDiv);\n this.createParagraphOptions(paragraphOptionsDiv);\n // let radioOptionsDiv: HTMLElement = createElement('div', { styles: 'display:flex' });\n // container.appendChild(radioOptionsDiv);\n // let onlyThisDocumentDiv: HTMLElement = createElement('div', { className: 'e-de-style-radio-button' });\n // tslint:disable-next-line:max-line-length\n // let onlyThisDocument: HTMLInputElement = createElement('input', { className: 'e-de-style-only-this-doc', attrs: { type: 'radio' } }) as HTMLInputElement;\n // onlyThisDocumentDiv.appendChild(onlyThisDocument);\n // tslint:disable-next-line:max-line-length\n // this.onlyThisDocument = new RadioButton({ label: 'Only in this document', value: 'only in this document', checked: true, name: 'styles' });\n // this.onlyThisDocument.appendTo(onlyThisDocument);\n // radioOptionsDiv.appendChild(onlyThisDocumentDiv);\n // let templateDiv: HTMLElement = createElement('div', { className: 'e-de-style-radio-button' });\n // tslint:disable-next-line:max-line-length\n // let template: HTMLInputElement = createElement('input', { className: 'e-de-style-temp', attrs: { type: 'radio' } }) as HTMLInputElement;\n // templateDiv.appendChild(template);\n // this.template = new RadioButton({ label: 'Template', value: 'template', name: 'styles' });\n // this.template.appendTo(template);\n // radioOptionsDiv.appendChild(templateDiv);\n this.createFormatDropdown(container, localValue);\n this.target.appendChild(container);\n };\n StyleDialog.prototype.createFormatDropdown = function (parentDiv, localValue) {\n var _this = this;\n var formatBtn = createElement('button', { id: 'style_format_dropdown', innerHTML: localValue.getConstant('Format') });\n formatBtn.style.height = '35px';\n parentDiv.appendChild(formatBtn);\n var items = [{ text: localValue.getConstant('Font') + '..', id: 'style_font' },\n { text: localValue.getConstant('Paragraph') + '..', id: 'style_paragraph' },\n { text: localValue.getConstant('Numbering') + '..', id: 'style_numbering' }];\n var dropDownbtn = new DropDownButton({\n items: items, cssClass: 'e-de-style-format-dropdwn',\n beforeItemRender: function (args) {\n if (_this.styleType.value === 'Character') {\n if (args.item.text === 'Paragraph') {\n args.element.classList.add('e-disabled');\n }\n if (args.item.text === 'Numbering') {\n args.element.classList.add('e-disabled');\n }\n }\n else {\n if (args.item.text === 'Paragraph') {\n args.element.classList.remove('e-disabled');\n }\n if (args.item.text === 'Numbering') {\n args.element.classList.remove('e-disabled');\n }\n }\n }\n });\n dropDownbtn.appendTo(formatBtn);\n dropDownbtn.addEventListener('select', this.openDialog);\n };\n StyleDialog.prototype.createFontOptions = function (parentDiv) {\n var fontFamilyElement = createElement('select', { id: this.target.id + '_fontName' });\n fontFamilyElement.innerHTML = 'Arial Calibri Candara ' +\n 'Comic Sans MS Consolas Constantia Corbel ' +\n 'Courier New Ebrima Franklin Gothic ' +\n 'Gabriola Gadugi Georgia Impact ' +\n 'Javanese Text Microsoft Sans Serif MS Gothic MS UI Gothic ' +\n 'Segoe Print Times New Roman Verdana Segoe UI ' +\n 'Algerian Cambria Georgia Consolas ';\n parentDiv.appendChild(fontFamilyElement);\n this.fontFamily = new ComboBox({\n width: '123px', popupWidth: '123px',\n cssClass: 'e-style-font-fmaily-right', change: this.fontFamilyChanged\n });\n this.fontFamily.showClearButton = false;\n this.fontFamily.appendTo(fontFamilyElement);\n var fontSizeElement = createElement('input');\n parentDiv.appendChild(fontSizeElement);\n var sizeDataSource = [8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72];\n this.fontSize = new ComboBox({\n dataSource: sizeDataSource, width: '73px', cssClass: 'e-style-font-fmaily-right',\n change: this.fontSizeUpdate\n });\n this.fontSize.showClearButton = false;\n this.fontSize.appendTo(fontSizeElement);\n var fontGroupButton = createElement('div', { className: 'e-de-style-font-group-button' });\n parentDiv.appendChild(fontGroupButton);\n // tslint:disable-next-line:max-line-length\n this.bold = this.createButtonElement(fontGroupButton, 'e-de-bold', 'e-de-style-bold-button-size', this.owner.owner.containerId + '_style_bold');\n this.bold.addEventListener('click', this.setBoldProperty);\n // tslint:disable-next-line:max-line-length\n this.italic = this.createButtonElement(fontGroupButton, 'e-de-italic', 'e-de-style-icon-button-size', this.owner.owner.containerId + '_style_italic');\n this.italic.addEventListener('click', this.setItalicProperty);\n // tslint:disable-next-line:max-line-length\n this.underline = this.createButtonElement(fontGroupButton, 'e-de-underline', 'e-de-style-icon-button-size', this.owner.owner.containerId + '_style_underline');\n this.underline.addEventListener('click', this.setUnderlineProperty);\n var fontColorElement = createElement('input', { attrs: { type: 'color' }, className: 'e-de-style-icon-button-size' });\n parentDiv.appendChild(fontColorElement);\n this.fontColor = new ColorPicker({ cssClass: 'e-de-style-font-color-picker', change: this.fontColorUpdate });\n this.fontColor.appendTo(fontColorElement);\n };\n StyleDialog.prototype.createParagraphOptions = function (parentDiv) {\n var _this = this;\n var alignmentDiv = createElement('div', { className: 'e-de-style-paragraph-group-button' });\n parentDiv.appendChild(alignmentDiv);\n this.leftAlign = this.createButtonElement(alignmentDiv, 'e-de-align-left', 'e-de-style-icon-button-size');\n this.leftAlign.addEventListener('click', this.setLeftAlignment);\n this.centerAlign = this.createButtonElement(alignmentDiv, 'e-de-align-center', 'e-de-style-icon-button-size');\n this.centerAlign.addEventListener('click', this.setCenterAlignment);\n this.rightAlign = this.createButtonElement(alignmentDiv, 'e-de-align-right', 'e-de-style-icon-button-size');\n this.rightAlign.addEventListener('click', this.setRightAlignment);\n this.justify = this.createButtonElement(alignmentDiv, 'e-de-justify', 'e-de-style-icon-button-last-size');\n this.justify.addEventListener('click', this.setJustifyAlignment);\n var lineSpacingDiv = createElement('div', { className: 'e-de-style-paragraph-group-button' });\n parentDiv.appendChild(lineSpacingDiv);\n this.singleLineSpacing = this.createButtonElement(lineSpacingDiv, 'e-de-single-spacing', 'e-de-style-icon-button-first-size');\n this.singleLineSpacing.addEventListener('click', function () {\n _this.paragraphFormat.lineSpacing = 1;\n _this.updateParagraphFormat();\n });\n // tslint:disable-next-line:max-line-length\n this.onePointFiveLineSpacing = this.createButtonElement(lineSpacingDiv, 'e-de-one-point-five-spacing', 'e-de-style-icon-button-size');\n this.onePointFiveLineSpacing.addEventListener('click', function () {\n _this.paragraphFormat.lineSpacing = 1.5;\n _this.updateParagraphFormat();\n });\n this.doubleLineSpacing = this.createButtonElement(lineSpacingDiv, 'e-de-double-spacing', 'e-de-style-icon-button-last-size');\n this.doubleLineSpacing.addEventListener('click', function () {\n _this.paragraphFormat.lineSpacing = 2;\n _this.updateParagraphFormat();\n });\n var spacingDiv = createElement('div', { className: 'e-de-style-paragraph-group-button' });\n parentDiv.appendChild(spacingDiv);\n var beforeSpacing = this.createButtonElement(spacingDiv, 'e-de-before-spacing', 'e-de-style-icon-button-first-size');\n var afterSpacing = this.createButtonElement(spacingDiv, 'e-de-after-spacing', 'e-de-style-icon-button-last-size');\n beforeSpacing.addEventListener('click', this.increaseBeforeAfterSpacing);\n afterSpacing.addEventListener('click', this.decreaseBeforeAfterSpacing);\n var indentingDiv = createElement('div', { className: 'e-de-style-paragraph-indent-group-button' });\n parentDiv.appendChild(indentingDiv);\n var decreaseIndent = this.createButtonElement(indentingDiv, 'e-de-indent', 'e-de-style-icon-button-first-size');\n decreaseIndent.addEventListener('click', function () {\n if (_this.paragraphFormat.leftIndent >= 36) {\n _this.paragraphFormat.leftIndent -= 36;\n }\n else {\n _this.paragraphFormat.leftIndent = 0;\n }\n });\n var increaseindent = this.createButtonElement(indentingDiv, 'e-de-outdent', 'e-de-style-icon-button-size');\n increaseindent.addEventListener('click', function () {\n _this.paragraphFormat.leftIndent += 36;\n });\n };\n StyleDialog.prototype.createButtonElement = function (parentDiv, iconCss, className, id) {\n var buttonElement = createElement('button');\n if (!isNullOrUndefined(id)) {\n buttonElement.id = id;\n }\n parentDiv.appendChild(buttonElement);\n var button = new Button({ iconCss: iconCss, cssClass: className });\n button.appendTo(buttonElement);\n return buttonElement;\n };\n StyleDialog.prototype.toggleDisable = function () {\n if (this.styleType.value === 'Character') {\n this.styleParagraph.enabled = false;\n // tslint:disable-next-line:max-line-length\n this.target.getElementsByClassName('e-style-paragraph').item(0).setAttribute('style', 'display:flex;pointer-events:none;opacity:0.5');\n }\n else {\n this.styleParagraph.enabled = true;\n this.target.getElementsByClassName('e-style-paragraph').item(0).removeAttribute('style');\n this.target.getElementsByClassName('e-style-paragraph').item(0).setAttribute('style', 'display:flex');\n }\n this.styleBasedOn.enabled = true;\n };\n /**\n * @private\n */\n StyleDialog.prototype.show = function (styleName, header) {\n var localObj = new L10n('documenteditor', this.owner.owner.defaultLocale);\n this.isEdit = (!isNullOrUndefined(styleName) && styleName.length > 0) ? true : false;\n this.editStyleName = styleName;\n this.abstractList = new WAbstractList();\n // tslint:disable-next-line:max-line-length\n var style = this.owner.owner.viewer.styles.findByName(styleName);\n this.style = !this.isEdit ? new WParagraphStyle() : style ? style : this.getStyle(styleName);\n localObj.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initStyleDialog(localObj);\n }\n if (isNullOrUndefined(header)) {\n header = localObj.getConstant('Create New Style');\n }\n this.owner.owner.viewer.dialog2.header = header;\n this.owner.owner.viewer.dialog2.height = 'auto';\n this.owner.owner.viewer.dialog2.width = 'auto';\n this.owner.owner.viewer.dialog2.content = this.target;\n this.owner.owner.viewer.dialog2.buttons = [{\n click: this.onOkButtonClick,\n buttonModel: { content: localObj.getConstant('Ok'), cssClass: 'e-flat e-style-okay', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: localObj.getConstant('Cancel'), cssClass: 'e-flat e-style-cancel' }\n }];\n this.toggleDisable();\n this.owner.owner.viewer.dialog2.dataBind();\n this.owner.owner.viewer.dialog2.beforeOpen = this.loadStyleDialog;\n this.owner.owner.viewer.dialog2.close = this.closeStyleDialog;\n this.owner.owner.viewer.dialog2.position = { X: 'center', Y: 'center' };\n this.owner.owner.viewer.dialog2.show();\n };\n StyleDialog.prototype.updateList = function () {\n var listId = this.style.paragraphFormat.listFormat.listId;\n if (listId > -1) {\n if (this.owner.owner.viewer.lists.filter(function (a) { return (a.listId === listId); }).length === 0) {\n this.owner.owner.viewer.lists.push(this.style.paragraphFormat.listFormat.list);\n }\n else {\n this.owner.owner.viewer.lists = this.owner.owner.viewer.lists.filter(function (a) { return (a.listId !== listId); });\n this.owner.owner.viewer.lists.push(this.style.paragraphFormat.listFormat.list);\n }\n }\n if (this.abstractList.abstractListId !== -1) {\n this.owner.owner.viewer.abstractLists.push(this.abstractList);\n }\n };\n StyleDialog.prototype.createLinkStyle = function (name, isEdit) {\n var charStyle;\n if (isEdit) {\n charStyle = this.owner.owner.viewer.styles.findByName((name + ' Char'), 'Character');\n }\n else {\n charStyle = new WCharacterStyle();\n }\n charStyle.type = 'Character';\n charStyle.name = name + ' Char';\n charStyle.characterFormat = this.style.characterFormat.cloneFormat();\n charStyle.basedOn = this.style.basedOn;\n if (!isEdit) {\n this.owner.owner.viewer.styles.push(charStyle);\n }\n return this.owner.owner.viewer.styles.findByName(charStyle.name, 'Character');\n };\n /**\n * @private\n */\n StyleDialog.prototype.updateCharacterFormat = function (characterFormat) {\n if (!isNullOrUndefined(characterFormat)) {\n this.characterFormat = characterFormat;\n }\n this.fontFamily.value = this.characterFormat.fontFamily;\n this.fontSize.value = this.characterFormat.fontSize;\n this.fontColor.value = this.characterFormat.fontColor;\n this.fontButtonClicked(undefined);\n };\n /**\n * @private\n */\n StyleDialog.prototype.updateParagraphFormat = function (paragraphFOrmat) {\n if (!isNullOrUndefined(paragraphFOrmat)) {\n this.paragraphFormat = paragraphFOrmat;\n }\n if (this.paragraphFormat.textAlignment === 'Left') {\n if (!this.leftAlign.classList.contains('e-active')) {\n this.leftAlign.classList.add('e-active');\n }\n if (this.rightAlign.classList.contains('e-active')) {\n this.rightAlign.classList.remove('e-active');\n }\n if (this.centerAlign.classList.contains('e-active')) {\n this.centerAlign.classList.remove('e-active');\n }\n if (this.justify.classList.contains('e-active')) {\n this.justify.classList.remove('e-active');\n }\n }\n else if (this.paragraphFormat.textAlignment === 'Right') {\n if (this.leftAlign.classList.contains('e-active')) {\n this.leftAlign.classList.remove('e-active');\n }\n if (!this.rightAlign.classList.contains('e-active')) {\n this.rightAlign.classList.add('e-active');\n }\n if (this.centerAlign.classList.contains('e-active')) {\n this.centerAlign.classList.remove('e-active');\n }\n if (this.justify.classList.contains('e-active')) {\n this.justify.classList.remove('e-active');\n }\n }\n else if (this.paragraphFormat.textAlignment === 'Center') {\n if (this.leftAlign.classList.contains('e-active')) {\n this.leftAlign.classList.remove('e-active');\n }\n if (this.rightAlign.classList.contains('e-active')) {\n this.rightAlign.classList.remove('e-active');\n }\n if (!this.centerAlign.classList.contains('e-active')) {\n this.centerAlign.classList.add('e-active');\n }\n if (this.justify.classList.contains('e-active')) {\n this.justify.classList.remove('e-active');\n }\n }\n else if (this.paragraphFormat.textAlignment === 'Justify') {\n if (this.leftAlign.classList.contains('e-active')) {\n this.leftAlign.classList.remove('e-active');\n }\n if (this.rightAlign.classList.contains('e-active')) {\n this.rightAlign.classList.remove('e-active');\n }\n if (this.centerAlign.classList.contains('e-active')) {\n this.centerAlign.classList.remove('e-active');\n }\n if (!this.justify.classList.contains('e-active')) {\n this.justify.classList.add('e-active');\n }\n }\n if (this.paragraphFormat.lineSpacing === 1) {\n this.singleLineSpacing.classList.add('e-active');\n this.onePointFiveLineSpacing.classList.remove('e-active');\n this.doubleLineSpacing.classList.remove('e-active');\n }\n else if (this.paragraphFormat.lineSpacing === 1.5) {\n this.singleLineSpacing.classList.remove('e-active');\n this.onePointFiveLineSpacing.classList.add('e-active');\n this.doubleLineSpacing.classList.remove('e-active');\n }\n else if (this.paragraphFormat.lineSpacing === 2) {\n this.singleLineSpacing.classList.remove('e-active');\n this.onePointFiveLineSpacing.classList.remove('e-active');\n this.doubleLineSpacing.classList.add('e-active');\n }\n else {\n this.singleLineSpacing.classList.remove('e-active');\n this.onePointFiveLineSpacing.classList.remove('e-active');\n this.doubleLineSpacing.classList.remove('e-active');\n }\n };\n StyleDialog.prototype.enableOrDisableOkButton = function () {\n if (!isNullOrUndefined(this.okButton)) {\n this.okButton.disabled = (this.styleNameElement.value === '');\n }\n };\n StyleDialog.prototype.getTypeValue = function () {\n var type;\n if (this.styleType.value === 'Linked(Paragraph and Character)' || this.styleType.value === 'Paragraph') {\n return 'Paragraph';\n }\n else {\n return 'Character';\n }\n };\n StyleDialog.prototype.updateStyleNames = function (type, name) {\n var styles = this.owner.owner.viewer.styles.getStyleNames(type);\n this.styleParagraph.dataSource = styles;\n this.styleParagraph.index = null;\n if (name) {\n this.styleBasedOn.dataSource = styles.filter(function (e) { return e !== name; });\n this.styleBasedOn.index = null;\n var style = this.getStyle(name);\n if (style.basedOn instanceof String || isNullOrUndefined(style.basedOn)) {\n this.styleBasedOn.enabled = false;\n }\n else {\n /* tslint:disable-next-line:max-line-length */\n this.styleBasedOn.index = styles.indexOf(style.basedOn.name) > -1 ? styles.indexOf(style.basedOn.name) : 0;\n }\n if (style.type === 'Paragraph') {\n if (!isNullOrUndefined(style.link)) {\n this.styleType.index = 2;\n }\n else {\n this.styleType.index = 0;\n }\n }\n else {\n this.styleType.index = 1;\n }\n if (!isNullOrUndefined(style.next)) {\n var nxtName = style.next.name;\n var index = 0;\n if (styles.indexOf(nxtName) > -1) {\n index = styles.indexOf(nxtName);\n }\n this.styleParagraph.index = index;\n this.isUserNextParaUpdated = (nxtName === name) ? false : true;\n }\n }\n else {\n this.styleBasedOn.dataSource = styles;\n this.styleBasedOn.index = null;\n var basedOnIndex = 0;\n if (this.owner.owner.selectionModule) {\n var styleName = void 0;\n if (type === 'Character') {\n styleName = this.owner.owner.selection.characterFormat.styleName;\n }\n else {\n styleName = this.owner.owner.selection.paragraphFormat.styleName;\n }\n basedOnIndex = styles.indexOf(styleName);\n }\n this.styleBasedOn.index = basedOnIndex;\n this.styleParagraph.index = 0;\n }\n if (this.isEdit) {\n this.styleType.enabled = false;\n }\n else {\n this.styleType.enabled = true;\n }\n this.styleBasedOn.dataBind();\n this.styleParagraph.dataBind();\n };\n StyleDialog.prototype.getStyle = function (styleName) {\n /* tslint:disable-next-line:max-line-length */\n if (isNullOrUndefined(this.owner.owner.viewer.styles.findByName(styleName))) {\n /* tslint:disable-next-line:max-line-length */\n this.owner.owner.editor.createStyle(this.owner.owner.viewer.preDefinedStyles.get(styleName));\n }\n return this.owner.owner.viewer.styles.findByName(styleName);\n };\n /**\n * @private\n */\n StyleDialog.prototype.destroy = function () {\n this.owner = undefined;\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var n = 0; n < this.target.childNodes.length; n++) {\n this.target.removeChild(this.target.childNodes[n]);\n n--;\n }\n this.target = undefined;\n }\n if (this.styleType) {\n this.styleType.destroy();\n }\n this.styleType = undefined;\n if (this.styleBasedOn) {\n this.styleBasedOn.destroy();\n }\n this.styleBasedOn = undefined;\n if (this.styleParagraph) {\n this.styleParagraph.destroy();\n }\n this.styleParagraph = undefined;\n if (this.onlyThisDocument) {\n this.onlyThisDocument.destroy();\n }\n this.onlyThisDocument = undefined;\n if (this.template) {\n this.template.destroy();\n }\n this.template = undefined;\n if (this.style) {\n this.style = undefined;\n }\n if (this.abstractList) {\n this.abstractList = undefined;\n }\n if (this.numberingBulletDialog) {\n this.numberingBulletDialog.destroy();\n }\n this.numberingBulletDialog = undefined;\n };\n return StyleDialog;\n}());\nexport { StyleDialog };\n","import { createElement, isNullOrUndefined, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { Tab } from '@syncfusion/ej2-navigations';\nimport { WList } from '../list/list';\nimport { WAbstractList } from '../list/abstract-list';\nimport { WListLevel } from '../list/list-level';\nimport { WListFormat } from '../../implementation/format/list-format';\n/**\n * The Bullets and Numbering dialog is used to apply list format for a paragraph style.\n */\n/* tslint:disable:no-any */\nvar BulletsAndNumberingDialog = /** @class */ (function () {\n /**\n * @private\n */\n function BulletsAndNumberingDialog(layoutViewer) {\n var _this = this;\n this.isBullet = false;\n /**\n * @private\n */\n this.numberListClick = function (args) {\n _this.isBullet = false;\n _this.setActiveElement(args);\n if (args.currentTarget.classList.contains('e-de-list-numbered-none')) {\n _this.numberFormat = undefined;\n _this.listLevelPattern = undefined;\n }\n else if (args.currentTarget.classList.contains('e-de-list-numbered-number-dot')) {\n _this.numberFormat = '%1.';\n _this.listLevelPattern = 'Arabic';\n }\n else if (args.currentTarget.classList.contains('e-de-list-numbered-number-brace')) {\n _this.numberFormat = '%1)';\n _this.listLevelPattern = 'Arabic';\n }\n else if (args.currentTarget.classList.contains('e-de-list-numbered-up-roman')) {\n _this.numberFormat = '%1.';\n _this.listLevelPattern = 'UpRoman';\n }\n else if (args.currentTarget.classList.contains('e-de-list-numbered-up-letter')) {\n _this.numberFormat = '%1.';\n _this.listLevelPattern = 'UpLetter';\n }\n else if (args.currentTarget.classList.contains('e-de-list-numbered-low-letter-brace')) {\n _this.numberFormat = '%1)';\n _this.listLevelPattern = 'LowLetter';\n }\n else if (args.currentTarget.classList.contains('e-de-numbered-low-letter-dot')) {\n _this.numberFormat = '%1.';\n _this.listLevelPattern = 'LowLetter';\n }\n else if (args.currentTarget.classList.contains('e-de-list-numbered-low-roman')) {\n _this.numberFormat = '%1.';\n _this.listLevelPattern = 'LowRoman';\n }\n };\n /**\n * @private\n */\n this.bulletListClick = function (args) {\n _this.isBullet = true;\n _this.setActiveElement(args);\n if (args.currentTarget.classList.contains('e-bullet-none')) {\n _this.symbol = undefined;\n _this.fontFamily = undefined;\n }\n else if (args.currentTarget.classList.contains('e-bullet-dot')) {\n _this.symbol = '\\uf0b7';\n _this.fontFamily = 'Symbol';\n }\n else if (args.currentTarget.classList.contains('e-bullet-circle')) {\n _this.symbol = '\\uf06f' + '\\u0020';\n _this.fontFamily = 'Symbol';\n }\n else if (args.currentTarget.classList.contains('e-bullet-square')) {\n _this.symbol = '\\uf0a7';\n _this.fontFamily = 'Wingdings';\n }\n else if (args.currentTarget.classList.contains('e-bullet-flower')) {\n _this.symbol = '\\uf076';\n _this.fontFamily = 'Wingdings';\n }\n else if (args.currentTarget.classList.contains('e-bullet-arrow')) {\n _this.symbol = '\\uf0d8';\n _this.fontFamily = 'Wingdings';\n }\n else if (args.currentTarget.classList.contains('e-bullet-tick')) {\n _this.symbol = '\\uf0fc';\n _this.fontFamily = 'Wingdings';\n }\n };\n /**\n * @private\n */\n this.loadNumberingBulletDialog = function () {\n //Load \n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.closeNumberingBulletDialog = function () {\n _this.unWireEventsAndBindings();\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.onCancelButtonClick = function () {\n _this.isBullet = false;\n _this.listLevelPattern = undefined;\n _this.numberFormat = undefined;\n _this.symbol = undefined;\n _this.fontFamily = undefined;\n _this.owner.dialog.hide();\n _this.unWireEventsAndBindings();\n };\n /**\n * @private\n */\n this.onOkButtonClick = function () {\n if (_this.owner.owner.viewer.lists.length > 0) {\n _this.listFormat.list.listId = _this.owner.owner.viewer.lists[_this.owner.owner.viewer.lists.length - 1].listId + 1;\n _this.listFormat.listId = _this.listFormat.list.listId;\n }\n else {\n _this.listFormat.list.listId = 0;\n _this.listFormat.listId = 0;\n }\n if (_this.owner.owner.viewer.abstractLists.length > 0) {\n /* tslint:disable-next-line:max-line-length */\n _this.abstractList.abstractListId = _this.owner.owner.viewer.abstractLists[_this.owner.owner.viewer.abstractLists.length - 1].abstractListId + 1;\n }\n else {\n _this.abstractList.abstractListId = 0;\n }\n _this.listFormat.list.abstractListId = _this.abstractList.abstractListId;\n var listLevel = new WListLevel(_this.abstractList);\n listLevel.listLevelPattern = !isNullOrUndefined(_this.listLevelPattern) ? _this.listLevelPattern : 'Bullet';\n listLevel.numberFormat = _this.isBullet ? _this.symbol : _this.numberFormat;\n if (listLevel.listLevelPattern !== 'Bullet') {\n listLevel.startAt = 1;\n }\n listLevel.characterFormat.fontFamily = !isNullOrUndefined(_this.fontFamily) ? _this.fontFamily : 'Verdana';\n listLevel.paragraphFormat.leftIndent = 36;\n listLevel.paragraphFormat.firstLineIndent = -18;\n _this.abstractList.levels.push(listLevel);\n _this.listFormat.listLevelNumber = 0;\n _this.listFormat.list.abstractList = _this.abstractList;\n _this.owner.dialog.hide();\n };\n this.owner = layoutViewer;\n }\n /**\n * @private\n */\n BulletsAndNumberingDialog.prototype.getModuleName = function () {\n return 'BulletsAndNumberingDialog';\n };\n /**\n * @private\n */\n BulletsAndNumberingDialog.prototype.initNumberingBulletDialog = function (locale) {\n var instance = this;\n var id = this.owner.owner.containerId;\n this.target = createElement('div', { id: id + '_insertNumberBulletDialog', className: 'e-de-number-bullet-dlg' });\n var tabTarget = createElement('div', { id: id + '_tabNumberBulletDialog', className: 'e-de-tab-number-bullet-dlg' });\n this.target.appendChild(tabTarget);\n this.createNumberList(id);\n this.createBulletList(id);\n //Initialize Tab component\n var tabObj = new Tab({\n items: [\n {\n header: { 'text': locale.getConstant('Numbering') },\n /* tslint:disable-next-line:max-line-length */\n content: ('#' + id + '_Number'),\n },\n {\n header: { 'text': locale.getConstant('Bullets') },\n /* tslint:disable-next-line:max-line-length */\n content: ('#' + id + '_Bullet'),\n },\n ],\n heightAdjustMode: 'None',\n width: 272,\n });\n //Render initialized Tab component\n tabObj.appendTo(tabTarget);\n this.owner.owner.element.appendChild(this.target);\n tabObj.refresh();\n };\n BulletsAndNumberingDialog.prototype.createNumberList = function (id) {\n var numberListDiv = createElement('div', { className: 'e-de-style-numbered-list', id: id + '_Number' });\n numberListDiv.style.display = 'none';\n numberListDiv.style.height = '270px';\n var ulTag = createElement('ul', {\n styles: 'display: block; outline: 0px;',\n id: 'listMenu',\n className: 'e-de-ui-wfloating-menu e-de-ui-bullets-menu e-de-list-container e-de-list-thumbnail'\n });\n numberListDiv.appendChild(ulTag);\n var numberedNone = this.createNumberNoneListTag(ulTag);\n var numberedNumberDot = this.createNumberListTag(ulTag, '1.', '2.', '3.', 'e-de-list-numbered-number-dot');\n var numberedNumberBrace = this.createNumberListTag(ulTag, '1)', '2)', '3)', 'e-de-list-numbered-number-brace');\n var numberedUpRoman = this.createNumberListTag(ulTag, 'I.', 'II.', 'III.', 'e-de-list-numbered-up-roman');\n var numberedUpLettter = this.createNumberListTag(ulTag, 'A.', 'B.', 'C.', 'e-de-list-numbered-up-letter');\n var numberedLowLetterDot = this.createNumberListTag(ulTag, 'a.', 'b.', 'c.', 'e-de-numbered-low-letter-dot');\n var numberedLowLetterBrace = this.createNumberListTag(ulTag, 'a)', 'b)', 'c)', 'e-de-list-numbered-low-letter-brace');\n var numberedLowRoman = this.createNumberListTag(ulTag, 'i.', 'ii.', 'iii.', 'e-de-list-numbered-low-roman');\n numberedNone.addEventListener('click', this.numberListClick);\n numberedNumberDot.addEventListener('click', this.numberListClick);\n numberedNumberBrace.addEventListener('click', this.numberListClick);\n numberedUpRoman.addEventListener('click', this.numberListClick);\n numberedUpLettter.addEventListener('click', this.numberListClick);\n numberedLowLetterBrace.addEventListener('click', this.numberListClick);\n numberedLowLetterDot.addEventListener('click', this.numberListClick);\n numberedLowRoman.addEventListener('click', this.numberListClick);\n this.target.appendChild(numberListDiv);\n };\n BulletsAndNumberingDialog.prototype.createNumberListTag = function (ulTag, text1, text2, text3, className) {\n var liTag = createElement('li', {\n styles: 'display:block',\n className: 'e-de-ui-wfloating-menuitem e-de-ui-wfloating-menuitem-md e-de-list-items e-de-list-item-size ' + className\n });\n ulTag.appendChild(liTag);\n /* tslint:disable-next-line:max-line-length */\n var innerHTML = '' + text1 + '
' + text2 + '';\n innerHTML += '
' + text3 + '
';\n var liInnerDiv = createElement('div', {\n className: 'e-de-ui-list-header-presetmenu',\n id: 'e-de-ui-zlist0', innerHTML: innerHTML\n });\n liTag.style.cssFloat = 'left';\n liTag.appendChild(liInnerDiv);\n return liTag;\n };\n BulletsAndNumberingDialog.prototype.createNumberNoneListTag = function (ulTag) {\n var liTag = createElement('li', {\n styles: 'display:block',\n /* tslint:disable-next-line:max-line-length */\n className: 'e-de-ui-wfloating-menuitem e-de-ui-wfloating-menuitem-md e-de-list-items e-de-list-item-size e-de-list-numbered-none'\n });\n ulTag.appendChild(liTag);\n var innerHTML = 'None
';\n var liInnerDiv = createElement('div', {\n className: 'e-de-ui-list-header-presetmenu',\n id: 'e-de-ui-zlist0', innerHTML: innerHTML\n });\n liTag.style.cssFloat = 'left';\n liTag.appendChild(liInnerDiv);\n return liTag;\n };\n BulletsAndNumberingDialog.prototype.createBulletListTag = function (ulTag, iconCss, className) {\n var liTag = createElement('li', {\n styles: 'display:block;',\n className: 'e-de-ui-wfloating-menuitem e-de-ui-wfloating-bullet-menuitem-md e-de-list-items e-de-list-item-size ' + className\n });\n ulTag.appendChild(liTag);\n /* tslint:disable-next-line:max-line-length */\n var liInnerDiv = createElement('div', { className: 'e-de-ui-bullet-list-header-presetmenu e-de-bullet-icon-size', id: 'e-de-ui-zlist0' });\n var liNextDiv = createElement('div', { className: iconCss });\n liInnerDiv.appendChild(liNextDiv);\n liTag.appendChild(liInnerDiv);\n return liTag;\n };\n BulletsAndNumberingDialog.prototype.createBulletList = function (id) {\n var bulletListDiv = createElement('div', { className: 'e-de-ui-bullet-list-header-presetmenu', id: id + '_Bullet' });\n bulletListDiv.style.display = 'none';\n bulletListDiv.style.height = '270px';\n var ulTag = createElement('ul', {\n styles: 'display: block; outline: 0px;', id: 'listMenu',\n className: 'e-de-ui-wfloating-menu e-de-ui-bullets-menu e-de-list-container e-de-list-thumbnail'\n });\n bulletListDiv.appendChild(ulTag);\n var bulletNone = this.createBulletListTag(ulTag, 'e-de-icon-bullet-list-none e-de-bullet-icons', 'e-bullet-none');\n var bulletDot = this.createBulletListTag(ulTag, 'e-de-icon-bullet-list-dot e-de-bullet-icons', 'e-bullet-dot');\n /* tslint:disable-next-line:max-line-length */\n var bulletCircle = this.createBulletListTag(ulTag, 'e-de-icon-bullet-list-circle e-de-bullet-icons', 'e-bullet-circle');\n var bulletSquare = this.createBulletListTag(ulTag, 'e-de-icon-bullet-list-square e-de-bullet-icons', 'e-bullet-square');\n /* tslint:disable-next-line:max-line-length */\n var bulletFlower = this.createBulletListTag(ulTag, 'e-de-icon-bullet-list-flower e-de-bullet-icons', 'e-bullet-flower');\n var bulletArrow = this.createBulletListTag(ulTag, 'e-de-icon-bullet-list-arrow e-de-bullet-icons', 'e-bullet-arrow');\n var bulletTick = this.createBulletListTag(ulTag, 'e-de-icon-bullet-list-tick e-de-bullet-icons', 'e-bullet-tick');\n bulletNone.addEventListener('click', this.bulletListClick);\n bulletDot.addEventListener('click', this.bulletListClick);\n bulletCircle.addEventListener('click', this.bulletListClick);\n bulletSquare.addEventListener('click', this.bulletListClick);\n bulletFlower.addEventListener('click', this.bulletListClick);\n bulletArrow.addEventListener('click', this.bulletListClick);\n bulletTick.addEventListener('click', this.bulletListClick);\n // bulletListDiv.appendChild(table1); \n this.target.appendChild(bulletListDiv);\n };\n /**\n * @private\n */\n BulletsAndNumberingDialog.prototype.showNumberBulletDialog = function (listFormat, abstractList) {\n if (!isNullOrUndefined(listFormat)) {\n this.listFormat = listFormat;\n }\n else {\n this.listFormat = new WListFormat();\n }\n if (isNullOrUndefined(this.listFormat.list)) {\n this.listFormat.list = new WList();\n }\n if (!isNullOrUndefined(abstractList)) {\n this.abstractList = abstractList;\n }\n else {\n this.abstractList = new WAbstractList();\n }\n var locale = new L10n('documenteditor', this.owner.owner.defaultLocale);\n locale.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initNumberingBulletDialog(locale);\n }\n this.owner.dialog.header = locale.getConstant('Numbering and Bullets');\n this.owner.dialog.width = 'auto';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = this.loadNumberingBulletDialog;\n this.owner.dialog.close = this.closeNumberingBulletDialog;\n this.owner.dialog.position = { X: 'center', Y: 'center' };\n this.owner.dialog.buttons = [{\n click: this.onOkButtonClick,\n buttonModel: { content: locale.getConstant('Ok'), cssClass: 'e-flat e-numbering-bullet-okay', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: locale.getConstant('Cancel'), cssClass: 'e-flat e-numbering-bullet-cancel' }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n BulletsAndNumberingDialog.prototype.setActiveElement = function (args) {\n var html = args.currentTarget.parentElement;\n for (var i = 0; i < html.childElementCount; i++) {\n if (html.childNodes[i].classList.contains('e-de-list-active')) {\n html.childNodes[i].classList.remove('e-de-list-active');\n }\n }\n args.currentTarget.classList.add('e-de-list-active');\n };\n /**\n * @private\n */\n BulletsAndNumberingDialog.prototype.unWireEventsAndBindings = function () {\n //Unwire events\n };\n /**\n * @private\n */\n BulletsAndNumberingDialog.prototype.destroy = function () {\n this.owner = undefined;\n if (this.listFormat) {\n this.listFormat.destroy();\n this.listFormat = undefined;\n }\n if (this.abstractList) {\n this.abstractList.destroy();\n this.abstractList = undefined;\n }\n if (this.target && this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n for (var m = 0; m < this.target.childNodes.length; m++) {\n this.target.removeChild(this.target.childNodes[m]);\n m--;\n }\n this.target = undefined;\n }\n };\n return BulletsAndNumberingDialog;\n}());\nexport { BulletsAndNumberingDialog };\n/* tslint:enable:no-any */ \n","import { createElement, isNullOrUndefined, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { DropDownList, ComboBox } from '@syncfusion/ej2-dropdowns';\nimport { CheckBox } from '@syncfusion/ej2-buttons';\nimport { WCharacterFormat } from '../format/character-format';\nimport { ColorPicker } from '@syncfusion/ej2-inputs';\n/**\n * The Font dialog is used to modify formatting of selected text.\n */\n/* tslint:disable:no-any */\nvar FontDialog = /** @class */ (function () {\n /**\n * @private\n */\n function FontDialog(layoutViewer) {\n var _this = this;\n this.fontStyleInternal = undefined;\n this.fontNameList = undefined;\n this.fontStyleText = undefined;\n this.fontSizeText = undefined;\n this.colorPicker = undefined;\n this.underlineDrop = undefined;\n this.strikethroughBox = undefined;\n this.doublestrikethrough = undefined;\n this.superscript = undefined;\n this.subscript = undefined;\n //Character Format Property\n this.bold = undefined;\n this.italic = undefined;\n this.underline = undefined;\n this.strikethrough = undefined;\n this.baselineAlignment = undefined;\n this.fontSize = undefined;\n this.fontFamily = undefined;\n this.fontColor = undefined;\n /**\n * @private\n */\n this.characterFormat = undefined;\n /**\n * @private\n */\n this.loadFontDialog = function () {\n _this.owner.updateFocus();\n var characterFormat;\n if (_this.characterFormat) {\n characterFormat = _this.characterFormat;\n }\n else {\n characterFormat = _this.owner.owner.selection.characterFormat;\n }\n _this.fontNameList.value = characterFormat.fontFamily;\n if (!characterFormat.bold && !characterFormat.italic) {\n _this.fontStyleText.value = _this.fontSizeText.value;\n _this.fontStyleText.index = 0;\n }\n else if (characterFormat.bold && !characterFormat.italic) {\n _this.fontStyleText.value = _this.fontSizeText.value;\n _this.fontStyleText.index = 1;\n }\n else if (!characterFormat.bold && characterFormat.italic) {\n _this.fontStyleText.value = _this.fontSizeText.value;\n _this.fontStyleText.index = 2;\n }\n else if (characterFormat.bold && characterFormat.italic) {\n _this.fontStyleText.value = _this.fontSizeText.value;\n _this.fontStyleText.index = 3;\n }\n if (!isNullOrUndefined(characterFormat.fontSize)) {\n for (var i = 0; i <= 15; i++) {\n var items = _this.fontSizeText.getItems();\n if (characterFormat.fontSize.toString() === items[i].innerHTML) {\n _this.fontSizeText.value = characterFormat.fontSize;\n _this.fontSizeText.index = i;\n break;\n }\n }\n }\n if (!isNullOrUndefined(characterFormat.fontColor)) {\n _this.colorPicker.value = characterFormat.fontColor;\n }\n else {\n _this.colorPicker.value = '#000000';\n }\n if (characterFormat.underline === 'None') {\n _this.underlineDrop.index = 0;\n }\n else if (characterFormat.underline === 'Single') {\n _this.underlineDrop.index = 1;\n }\n if (characterFormat.strikethrough === 'SingleStrike') {\n _this.strikethroughBox.checked = true;\n }\n else if (characterFormat.strikethrough === 'DoubleStrike') {\n _this.doublestrikethrough.checked = true;\n }\n else {\n _this.strikethroughBox.checked = false;\n _this.doublestrikethrough.checked = false;\n }\n if (characterFormat.baselineAlignment === 'Superscript') {\n _this.superscript.checked = true;\n }\n else if (characterFormat.baselineAlignment === 'Subscript') {\n _this.subscript.checked = true;\n }\n else {\n _this.superscript.checked = false;\n _this.subscript.checked = false;\n }\n if (_this.owner.selection.caret.style.display !== 'none') {\n _this.owner.selection.caret.style.display = 'none';\n }\n };\n /**\n * @private\n */\n this.closeFontDialog = function () {\n _this.unWireEventsAndBindings();\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.onCancelButtonClick = function () {\n _this.owner.dialog.hide();\n _this.unWireEventsAndBindings();\n };\n /**\n * @private\n */\n this.onInsertFontFormat = function () {\n var format;\n if (_this.characterFormat) {\n format = _this.characterFormat;\n }\n else {\n format = new WCharacterFormat(undefined);\n }\n if (!isNullOrUndefined(_this.bold)) {\n format.bold = _this.bold;\n }\n if (!isNullOrUndefined(_this.italic)) {\n format.italic = _this.italic;\n }\n if (!isNullOrUndefined(_this.fontSize) && _this.fontSize > 0) {\n format.fontSize = _this.fontSize;\n }\n if (!isNullOrUndefined(_this.fontColor)) {\n format.fontColor = _this.fontColor;\n }\n if (!isNullOrUndefined(_this.baselineAlignment)) {\n format.baselineAlignment = _this.baselineAlignment;\n }\n if (!isNullOrUndefined(_this.strikethrough)) {\n format.strikethrough = _this.strikethrough;\n }\n if (!isNullOrUndefined(_this.underline)) {\n format.underline = _this.underline;\n }\n if (!isNullOrUndefined(_this.fontFamily)) {\n format.fontFamily = _this.fontFamily;\n }\n if (!_this.characterFormat) {\n _this.onCharacterFormat(_this.owner.selection, format);\n }\n else {\n _this.owner.owner.styleDialogModule.updateCharacterFormat();\n }\n _this.owner.dialog.hide();\n };\n this.fontSizeUpdate = function (args) {\n _this.fontSize = args.value;\n };\n this.fontStyleUpdate = function (args) {\n _this.fontStyle = args.value;\n };\n this.fontFamilyUpdate = function (args) {\n _this.fontFamily = args.value;\n };\n this.underlineUpdate = function (args) {\n _this.underline = args.value;\n };\n this.fontColorUpdate = function (args) {\n if (!isNullOrUndefined(args.currentValue)) {\n _this.fontColor = args.currentValue.hex;\n }\n };\n this.singleStrikeUpdate = function (args) {\n _this.enableCheckBoxProperty(args);\n if (args.checked) {\n _this.strikethrough = 'SingleStrike';\n }\n else {\n _this.strikethrough = 'None';\n }\n };\n this.doubleStrikeUpdate = function (args) {\n _this.enableCheckBoxProperty(args);\n if (args.checked) {\n _this.strikethrough = 'DoubleStrike';\n }\n else {\n _this.strikethrough = 'None';\n }\n };\n this.superscriptUpdate = function (args) {\n _this.enableCheckBoxProperty(args);\n if (args.checked) {\n _this.baselineAlignment = 'Superscript';\n }\n else {\n _this.baselineAlignment = 'Normal';\n }\n };\n this.subscriptUpdate = function (args) {\n _this.enableCheckBoxProperty(args);\n if (args.checked) {\n _this.baselineAlignment = 'Subscript';\n }\n else {\n _this.baselineAlignment = 'Normal';\n }\n };\n this.owner = layoutViewer;\n }\n Object.defineProperty(FontDialog.prototype, \"fontStyle\", {\n /**\n * @private\n */\n get: function () {\n return this.fontStyleInternal;\n },\n /**\n * @private\n */\n set: function (value) {\n this.fontStyleInternal = value;\n switch (this.fontStyle) {\n case 'Bold':\n this.bold = true;\n this.italic = false;\n break;\n case 'Italic':\n this.bold = false;\n this.italic = true;\n break;\n case 'BoldItalic':\n this.bold = true;\n this.italic = true;\n break;\n case 'Regular':\n this.bold = false;\n this.italic = false;\n break;\n }\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n FontDialog.prototype.getModuleName = function () {\n return 'FontDialog';\n };\n FontDialog.prototype.createInputElement = function (type, id, className) {\n var element = createElement('input', {\n attrs: { type: type },\n id: id,\n className: className\n });\n return element;\n };\n /**\n * @private\n */\n FontDialog.prototype.initFontDialog = function (locale) {\n var instance = this;\n var effectLabel;\n var strikeThroughElement;\n var superScriptElement;\n var subScriptElement;\n var doubleStrikeThroughElement;\n var id = this.owner.owner.containerId;\n this.target = createElement('div', { id: id + '_insertFontDialog', className: 'e-de-font-dlg' });\n var fontDiv = this.getFontDiv(locale);\n this.target.appendChild(fontDiv);\n var sizeDiv = this.getFontSizeDiv(locale);\n this.target.appendChild(sizeDiv);\n var colorDiv = createElement('div', { id: id + '_fontColor', styles: 'margin-top:15px;' });\n this.fontColorDiv = createElement('div', { id: id + '_fontColorDiv', className: 'e-de-font-dlg-display' });\n var fontColorLabel = createElement('label', {\n className: 'e-de-font-dlg-header-font-color e-de-font-color-margin', innerHTML: locale.getConstant('Font color')\n });\n this.fontColorDiv.appendChild(fontColorLabel);\n var fontColorElement = this.createInputElement('color', this.target.id + '_ColorDiv', 'e-de-font-dlg-color');\n this.fontColorDiv.appendChild(fontColorElement);\n colorDiv.appendChild(this.fontColorDiv);\n this.target.appendChild(colorDiv);\n var fontEffectsDiv = createElement('div', { id: id + '_fontEffectsDiv' });\n var fontEffectSubDiv1 = createElement('div', {\n className: 'e-de-font-color-label e-de-font-dlg-display',\n id: this.target.id + '_fontEffectsSubDiv1'\n });\n effectLabel = createElement('label', { className: 'e-de-font-dlg-header-effects', innerHTML: locale.getConstant('Effects') });\n fontEffectSubDiv1.appendChild(effectLabel);\n strikeThroughElement = this.createInputElement('checkbox', this.target.id + '_strikeThrough', '');\n fontEffectSubDiv1.appendChild(strikeThroughElement);\n superScriptElement = this.createInputElement('checkbox', this.target.id + '_superScript', '');\n fontEffectSubDiv1.appendChild(superScriptElement);\n fontEffectsDiv.appendChild(fontEffectSubDiv1);\n var fontEffectSubDiv2 = createElement('div', { className: 'e-de-font-checkbox', id: id + '_fontEffectsSubDiv2' });\n subScriptElement = this.createInputElement('checkbox', this.target.id + '_subScript', '');\n fontEffectSubDiv2.appendChild(subScriptElement);\n doubleStrikeThroughElement = this.createInputElement('checkbox', this.target.id + '_doubleStrikeThrough', '');\n fontEffectSubDiv2.appendChild(doubleStrikeThroughElement);\n fontEffectsDiv.appendChild(fontEffectSubDiv2);\n this.target.appendChild(fontEffectsDiv);\n this.owner.owner.element.appendChild(this.target);\n this.colorPicker = new ColorPicker({\n change: this.fontColorUpdate, value: '#000000',\n });\n this.colorPicker.appendTo(fontColorElement);\n this.strikethroughBox = new CheckBox({\n change: this.singleStrikeUpdate,\n cssClass: 'e-de-font-content-label',\n label: locale.getConstant('Strikethrough')\n });\n this.strikethroughBox.appendTo(strikeThroughElement);\n this.doublestrikethrough = new CheckBox({\n change: this.doubleStrikeUpdate,\n cssClass: 'e-de-font-content-checkbox-label',\n label: locale.getConstant('Double strikethrough')\n });\n this.doublestrikethrough.appendTo(doubleStrikeThroughElement);\n this.subscript = new CheckBox({\n label: locale.getConstant('Subscript'),\n change: this.subscriptUpdate\n });\n this.subscript.appendTo(subScriptElement);\n this.superscript = new CheckBox({\n label: locale.getConstant('Superscript'),\n cssClass: 'e-de-font-content-label', change: this.superscriptUpdate\n });\n this.superscript.appendTo(superScriptElement);\n };\n FontDialog.prototype.getFontSizeDiv = function (locale) {\n var fontSize;\n var sizeDiv;\n var id = this.owner.owner.containerId;\n sizeDiv = createElement('div', { id: id + '_fontSizeAndUnderlineDiv', className: 'e-de-font-dlg-padding e-de-font-dlg-display' });\n var sizeSubDiv1 = createElement('div', { id: id + '_fontSizeAndUnderlineSubDiv1' });\n var sizeLabel = createElement('label', { className: 'e-de-font-dlg-header', innerHTML: locale.getConstant('Size') });\n var styles = 'font-family:Roboto;font-size:14px;opacity:0.8;';\n fontSize = createElement('select', { id: this.target.id + '_fontSize', styles: styles });\n fontSize.innerHTML = '8 9 10 11 12 ' +\n '14 16 18 20 24 26 ' +\n '28 36 48 72 96 ';\n sizeSubDiv1.appendChild(sizeLabel);\n sizeSubDiv1.appendChild(fontSize);\n sizeDiv.appendChild(sizeSubDiv1);\n var sizeSubDiv2 = createElement('div', {\n className: 'e-de-font-dlg-cb-right',\n id: id + '_fontSizeAndUnderlineSubDiv2'\n });\n var html = locale.getConstant('Underline style');\n var underlineLabel = createElement('label', { className: 'e-de-font-dlg-header', innerHTML: html });\n var underlineElement;\n underlineElement = createElement('select', { id: this.target.id + '_underLine', styles: styles });\n underlineElement.innerHTML = '' + locale.getConstant('None') + ' ________ ';\n sizeSubDiv2.appendChild(underlineLabel);\n sizeSubDiv2.appendChild(underlineElement);\n sizeDiv.appendChild(sizeSubDiv2);\n this.fontSizeText = new ComboBox({ change: this.fontSizeUpdate, popupHeight: '170px', width: '170px' });\n this.fontSizeText.showClearButton = false;\n this.fontSizeText.appendTo(fontSize);\n this.underlineDrop = new DropDownList({ change: this.underlineUpdate, popupHeight: '100px', width: '170px' });\n this.underlineDrop.appendTo(underlineElement);\n return sizeDiv;\n };\n FontDialog.prototype.getFontDiv = function (locale) {\n var id = this.owner.owner.containerId;\n var fontDiv = createElement('div', { id: id + '_fontDiv', className: 'e-de-font-dlg-display' });\n var fontSubDiv1 = createElement('div', { id: id + '_fontSubDiv1' });\n var fontNameLabel = createElement('label', {\n className: 'e-de-font-dlg-header',\n innerHTML: locale.getConstant('Font')\n });\n var fontNameValues = createElement('select', { id: this.target.id + '_fontName' });\n fontNameValues.innerHTML = 'Arial Calibri Candara Comic Sans MS ' +\n 'Consolas Constantia Corbel ' +\n 'Courier New Ebrima Franklin Gothic ' +\n 'Gabriola Gadugi Georgia Impact ' +\n 'Javanese Text Microsoft Sans Serif MS Gothic MS UI Gothic ' +\n 'Segoe Print Times New Roman Verdana Segoe UI ' +\n 'Algerian Cambria Georgia Consolas ';\n fontSubDiv1.appendChild(fontNameLabel);\n fontSubDiv1.appendChild(fontNameValues);\n fontDiv.appendChild(fontSubDiv1);\n var fontSubDiv2;\n var fontStyleLabel;\n var fontStyleValues;\n fontSubDiv2 = createElement('div', { className: 'e-de-font-dlg-cb-right', id: id + '_fontSubDiv2', styles: 'float:right;' });\n fontStyleLabel = createElement('label', { className: 'e-de-font-dlg-header', innerHTML: locale.getConstant('Font style') });\n var fontStyle = 'font-family:Roboto;font-size:14px;opacity:0.8;';\n fontStyleValues = createElement('select', { id: this.target.id + '_fontStyle', styles: fontStyle });\n fontStyleValues.innerHTML = '' +\n locale.getConstant('Regular') + ' ' + locale.getConstant('Bold') + ' ' +\n locale.getConstant('Italic') + ' ' + locale.getConstant('Bold') + locale.getConstant('Italic') + ' ';\n fontSubDiv2.appendChild(fontStyleLabel);\n fontSubDiv2.appendChild(fontStyleValues);\n fontDiv.appendChild(fontSubDiv2);\n this.fontNameList = new ComboBox({ change: this.fontFamilyUpdate, popupHeight: '200px', width: '170px' });\n this.fontNameList.showClearButton = false;\n this.fontNameList.appendTo(fontNameValues);\n this.fontStyleText = new DropDownList({ change: this.fontStyleUpdate, popupHeight: '170px', width: '170px' });\n this.fontStyleText.appendTo(fontStyleValues);\n return fontDiv;\n };\n /**\n * @private\n */\n FontDialog.prototype.showFontDialog = function (characterFormat) {\n if (characterFormat) {\n this.characterFormat = characterFormat;\n }\n var locale = new L10n('documenteditor', this.owner.owner.defaultLocale);\n locale.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initFontDialog(locale);\n }\n this.owner.dialog.header = locale.getConstant('Font');\n this.owner.dialog.width = 'auto';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = this.loadFontDialog;\n this.owner.dialog.close = this.closeFontDialog;\n this.owner.dialog.buttons = [{\n click: this.onInsertFontFormat,\n buttonModel: { content: locale.getConstant('Ok'), cssClass: 'e-flat e-font-okay', isPrimary: true }\n },\n {\n click: this.onCancelButtonClick,\n buttonModel: { content: locale.getConstant('Cancel'), cssClass: 'e-flat e-font-cancel' }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n /**\n * Applies character format\n * @param {Selection} selection\n * @param {WCharacterFormat} format\n * @private\n */\n FontDialog.prototype.onCharacterFormat = function (selection, format) {\n this.owner.owner.editorModule.initHistory('CharacterFormat');\n if (selection.isEmpty) {\n if (selection.start.offset === selection.getParagraphLength(selection.start.paragraph)) {\n // tslint:disable-next-line:max-line-length\n this.owner.owner.editorModule.applyCharFormatValueInternal(selection, selection.start.paragraph.characterFormat, undefined, format);\n this.owner.owner.editorModule.reLayout(selection);\n }\n this.owner.updateFocus();\n return;\n }\n else {\n //Iterate and update formating.\n this.owner.owner.editorModule.setOffsetValue(this.owner.selection);\n this.owner.owner.editorModule.updateSelectionCharacterFormatting('CharacterFormat', format, false);\n }\n };\n /**\n * @private\n */\n FontDialog.prototype.enableCheckBoxProperty = function (args) {\n if (this.strikethroughBox.checked && this.doublestrikethrough.checked) {\n this.strikethroughBox.checked = false;\n this.doublestrikethrough.checked = false;\n if (args.event.currentTarget.id === this.target.id + '_doubleStrikeThrough') {\n this.doublestrikethrough.checked = true;\n }\n else {\n this.strikethroughBox.checked = true;\n }\n }\n if (this.superscript.checked && this.subscript.checked) {\n this.subscript.checked = false;\n this.superscript.checked = false;\n if (args.event.currentTarget.id === this.target.id + '_subScript') {\n this.subscript.checked = true;\n }\n else {\n this.superscript.checked = true;\n }\n }\n };\n /**\n * @private\n */\n FontDialog.prototype.unWireEventsAndBindings = function () {\n this.fontNameList.value = '';\n this.fontSizeText.value = '';\n this.fontStyleText.value = '';\n this.strikethroughBox.checked = false;\n this.doublestrikethrough.checked = false;\n this.superscript.checked = false;\n this.subscript.checked = false;\n this.bold = undefined;\n this.italic = undefined;\n this.underline = undefined;\n this.strikethrough = undefined;\n this.baselineAlignment = undefined;\n this.fontColor = undefined;\n this.fontSize = undefined;\n this.fontFamily = undefined;\n };\n /**\n * @private\n */\n FontDialog.prototype.destroy = function () {\n this.owner = undefined;\n if (this.characterFormat) {\n this.characterFormat.destroy();\n this.characterFormat = undefined;\n }\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var m = 0; m < this.target.childNodes.length; m++) {\n this.target.removeChild(this.target.childNodes[m]);\n m--;\n }\n this.target = undefined;\n }\n if (this.fontNameList) {\n this.fontNameList.destroy();\n }\n this.fontNameList = undefined;\n if (this.fontStyleText) {\n this.fontStyleText.destroy();\n }\n this.fontStyleText = undefined;\n if (this.fontSizeText) {\n this.fontSizeText.destroy();\n }\n this.fontSizeText = undefined;\n if (this.colorPicker) {\n this.colorPicker.destroy();\n }\n this.colorPicker = undefined;\n if (this.underlineDrop) {\n this.underlineDrop.destroy();\n }\n this.underlineDrop = undefined;\n if (this.strikethroughBox) {\n this.strikethroughBox.destroy();\n }\n this.strikethroughBox = undefined;\n if (this.doublestrikethrough) {\n this.doublestrikethrough.destroy();\n }\n this.doublestrikethrough = undefined;\n if (this.superscript) {\n this.superscript.destroy();\n }\n this.superscript = undefined;\n if (this.subscript) {\n this.subscript.destroy();\n }\n this.subscript = undefined;\n };\n return FontDialog;\n}());\nexport { FontDialog };\n/* tslint:enable:no-any */ \n","import { createElement, isNullOrUndefined, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { WTableFormat, WRowFormat, WCellFormat } from '../format/index';\nimport { CheckBox } from '@syncfusion/ej2-buttons';\nimport { DropDownList } from '@syncfusion/ej2-dropdowns';\nimport { Tab } from '@syncfusion/ej2-navigations';\nimport { classList } from '@syncfusion/ej2-base';\nimport { HelperMethods } from '../editor/editor-helper';\n/**\n * The Table properties dialog is used to modify properties of selected table.\n */\nvar TablePropertiesDialog = /** @class */ (function () {\n /**\n * @private\n */\n function TablePropertiesDialog(viewer) {\n var _this = this;\n this.hasTableWidth = false;\n this.hasCellWidth = false;\n /**\n * @private\n */\n this.isTableBordersAndShadingUpdated = false;\n /**\n * @private\n */\n this.isCellBordersAndShadingUpdated = false;\n this.tabObj = undefined;\n /**\n * @private\n */\n this.isCellOptionsUpdated = false;\n /**\n * @private\n */\n this.isTableOptionsUpdated = false;\n this.onBeforeOpen = function () {\n _this.owner.updateFocus();\n _this.loadTableProperties();\n };\n /**\n * @private\n */\n this.onCloseTablePropertyDialog = function () {\n _this.unWireEvent.bind(_this);\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.applyTableProperties = function () {\n var selection = _this.owner.selection;\n if (!_this.preferCheckBox.checked && !_this.preferCheckBox.indeterminate) {\n if (isNullOrUndefined(selection.tableFormat.preferredWidth) || selection.tableFormat.preferredWidth !== 0) {\n _this.tableFormat.preferredWidth = 0;\n _this.tableFormat.preferredWidthType = 'Point';\n }\n }\n if (_this.tableFormat.hasValue('tableAlignment') && _this.tableFormat.tableAlignment !== 'Left') {\n if (isNullOrUndefined(selection.tableFormat.leftIndent) || selection.tableFormat.leftIndent !== 0) {\n _this.tableFormat.leftIndent = 0;\n }\n }\n if (!_this.rowHeightCheckBox.checked && !_this.rowHeightCheckBox.indeterminate) {\n if (isNullOrUndefined(selection.rowFormat.height) || selection.rowFormat.height !== 0) {\n _this.rowFormat.heightType = 'AtLeast';\n _this.rowFormat.height = 0;\n }\n }\n if (!_this.preferredCellWidthCheckBox.checked && !_this.preferredCellWidthCheckBox.indeterminate) {\n if (isNullOrUndefined(selection.cellFormat.preferredWidth) || selection.cellFormat.preferredWidth === 0) {\n _this.cellFormat.preferredWidthType = 'Point';\n _this.cellFormat.preferredWidth = 0;\n }\n }\n else {\n if (_this.cellFormat.preferredWidthType === 'Percent') {\n if (!_this.tableFormat.hasValue('preferredWidth') && !_this.tableFormat.hasValue('preferredWidthType')\n && _this.owner.selection.start.paragraph.associatedCell.ownerTable.tableFormat.preferredWidth === 0) {\n // tslint:disable-next-line:max-line-length\n var containerWidth = _this.owner.selection.start.paragraph.associatedCell.ownerTable.getOwnerWidth(true);\n var tableWidth = _this.owner.selection.start.paragraph.associatedCell.ownerTable.getTableClientWidth(containerWidth);\n _this.tableFormat.preferredWidthType = 'Percent';\n _this.tableFormat.preferredWidth = tableWidth / HelperMethods.convertPixelToPoint(_this.owner.clientArea.width) * 100;\n }\n }\n }\n if (_this.rowHeightValue) {\n _this.rowFormat.height = _this.rowHeightValue;\n }\n _this.owner.owner.editorModule.initComplexHistory('TableProperties');\n _this.owner.owner.editorModule.onTableFormat(_this.tableFormat);\n _this.owner.owner.editorModule.onRowFormat(_this.rowFormat);\n _this.owner.owner.editorModule.onCellFormat(_this.cellFormat);\n _this.owner.owner.editorHistory.updateComplexHistory();\n _this.closeTablePropertiesDialog();\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.applyTableSubProperties = function () {\n if (_this.isCellOptionsUpdated) {\n var cellFormat = _this.owner.owner.cellOptionsDialogModule.cellFormat;\n _this.owner.owner.cellOptionsDialogModule.applySubCellOptions(cellFormat);\n }\n if (_this.isTableOptionsUpdated) {\n var tableFormat = _this.owner.owner.tableOptionsDialogModule.tableFormat;\n _this.owner.owner.tableOptionsDialogModule.applySubTableOptions(tableFormat);\n }\n _this.isCellOptionsUpdated = false;\n _this.isTableOptionsUpdated = false;\n };\n /**\n * @private\n */\n this.unWireEvent = function () {\n //Table Format\n _this.preferCheckBox.change = undefined;\n _this.tableWidthBox.change = undefined;\n _this.tableWidthType.change = undefined;\n _this.leftIndentBox.change = undefined;\n //Row Format\n _this.rowHeightCheckBox.change = undefined;\n _this.rowHeightBox.change = undefined;\n _this.rowHeightType.change = undefined;\n _this.repeatHeader.change = undefined;\n _this.allowRowBreak.change = undefined;\n //Cell Format\n _this.preferredCellWidthCheckBox.change = undefined;\n _this.cellWidthBox.change = undefined;\n _this.cellWidthType.change = undefined;\n _this.cellFormat.destroy();\n _this.rowFormat.destroy();\n _this.tableFormat.destroy();\n _this.rowHeightValue = undefined;\n _this.owner.dialog2.open = _this.owner.selection.hideCaret.bind(_this.owner);\n };\n /**\n * @private\n */\n this.closeTablePropertiesDialog = function () {\n _this.owner.dialog2.hide();\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.changeTableCheckBox = function () {\n var enable = (_this.preferCheckBox.checked || _this.preferCheckBox.indeterminate);\n _this.tableWidthBox.enabled = enable;\n _this.tableWidthType.enabled = enable;\n if (enable) {\n _this.tableFormat.preferredWidthType = (_this.tableWidthType.value === 'Points') ?\n 'Point' : _this.tableWidthType.value;\n }\n else {\n _this.tableFormat.preferredWidthType = _this.owner.selection.tableFormat.preferredWidthType;\n }\n };\n /**\n * @private\n */\n this.changeTableAlignment = function (event) {\n _this.updateClassForAlignmentProperties(_this.tableTab);\n var element = event.target;\n classList(element, ['e-de-table-alignment-active'], ['e-de-table-properties-alignment']);\n if (element.classList.contains('e-de-table-left-alignment')) {\n _this.leftIndentBox.enabled = true;\n }\n else {\n _this.leftIndentBox.enabled = false;\n }\n _this.tableFormat.tableAlignment = _this.getTableAlignment();\n };\n /**\n * @private\n */\n this.changeTableRowCheckBox = function () {\n _this.rowHeightType.enabled = _this.rowHeightCheckBox.checked;\n _this.rowHeightBox.enabled = _this.rowHeightCheckBox.checked;\n if (_this.rowHeightType.enabled) {\n _this.rowFormat.heightType = _this.rowHeightType.value;\n }\n else {\n _this.rowFormat.heightType = _this.owner.selection.rowFormat.heightType;\n }\n };\n /**\n * @private\n */\n this.changeTableCellCheckBox = function () {\n _this.cellWidthType.enabled = _this.preferredCellWidthCheckBox.checked;\n _this.cellWidthBox.enabled = _this.preferredCellWidthCheckBox.checked;\n };\n /**\n * @private\n */\n this.changeCellAlignment = function (event) {\n _this.updateClassForCellAlignment(_this.cellTab);\n var element = event.target;\n classList(element, ['e-de-table-alignment-active'], ['e-de-tablecell-alignment']);\n _this.cellFormat.verticalAlignment = _this.getCellAlignment();\n };\n //#endregion\n /**\n * @private\n */\n this.showTableOptionsDialog = function () {\n _this.owner.owner.tableOptionsDialogModule.show();\n _this.owner.dialog2.element.style.pointerEvents = 'none';\n };\n /**\n * @private\n */\n this.showBordersShadingsPropertiesDialog = function () {\n _this.owner.owner.bordersAndShadingDialogModule.show();\n _this.owner.dialog2.element.style.pointerEvents = 'none';\n };\n /**\n * @private\n */\n this.showCellOptionsDialog = function () {\n _this.owner.owner.cellOptionsDialogModule.show();\n _this.owner.dialog2.element.style.pointerEvents = 'none';\n };\n this.owner = viewer;\n }\n Object.defineProperty(TablePropertiesDialog.prototype, \"cellFormat\", {\n /**\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.cellFormatIn)) {\n return this.cellFormatIn = new WCellFormat();\n }\n return this.cellFormatIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.cellFormatIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TablePropertiesDialog.prototype, \"tableFormat\", {\n /**\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.tableFormatIn)) {\n this.tableFormatIn = new WTableFormat();\n return this.tableFormatIn;\n }\n return this.tableFormatIn;\n },\n /**\n * @private\n */\n set: function (value) {\n this.tableFormatIn = value;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TablePropertiesDialog.prototype, \"rowFormat\", {\n /**\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.rowFormatInternal)) {\n this.rowFormatInternal = new WRowFormat();\n return this.rowFormatInternal;\n }\n return this.rowFormatInternal;\n },\n enumerable: true,\n configurable: true\n });\n TablePropertiesDialog.prototype.getModuleName = function () {\n return 'TablePropertiesDialog';\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.initTablePropertyDialog = function (localValue) {\n var id = this.owner.owner.containerId + '_TablePropertiesDialog';\n this.target = createElement('div', { id: id, className: 'e-de-table-properties-dlg' });\n this.owner.owner.element.appendChild(this.target);\n var ejtabContainer = createElement('div', { id: this.target.id + '_TabContainer' });\n this.target.appendChild(ejtabContainer);\n this.tableTab = createElement('div', {\n id: this.target.id + '_TablePropertiesContentDialogTab', className: 'e-de-table-ppty-dlg-tabs'\n });\n this.rowTab = createElement('div', {\n id: this.target.id + '_RowPropertiesDialogTab', className: 'e-de-table-ppty-dlg-tabs'\n });\n this.cellTab = createElement('div', {\n id: this.target.id + '_CellPropertiesDialogTab', className: 'e-de-table-ppty-dlg-tabs'\n });\n var separatorLine = createElement('div', { className: 'e-de-table-dialog-separator-line' });\n // tslint:disable-next-line:max-line-length\n var ejtab = createElement('div', { id: this.target.id + '_TablePropertiesDialogTab', className: 'e-de-table-ppty-tab' });\n var headerContainer = createElement('div', { className: 'e-tab-header' });\n var tableHeader = createElement('div', {\n id: this.target.id + '_tableHeader', innerHTML: localValue.getConstant('Table')\n });\n var rowHeader = createElement('div', {\n id: this.target.id + '_rowHeader', innerHTML: localValue.getConstant('Row')\n });\n var cellHeader = createElement('div', {\n id: this.target.id + '_cellHeader', innerHTML: localValue.getConstant('Cell')\n });\n headerContainer.appendChild(tableHeader);\n headerContainer.appendChild(rowHeader);\n headerContainer.appendChild(cellHeader);\n var contentContainer = createElement('div', { className: 'e-content' });\n var tableContent = createElement('div', { id: this.target.id + '_tableContent' });\n var rowContent = createElement('div', { id: this.target.id + '_rowContent' });\n var cellContent = createElement('div', { id: this.target.id + '_cellContent' });\n tableContent.appendChild(this.tableTab);\n rowContent.appendChild(this.rowTab);\n cellContent.appendChild(this.cellTab);\n contentContainer.appendChild(tableContent);\n contentContainer.appendChild(rowContent);\n contentContainer.appendChild(cellContent);\n ejtab.appendChild(headerContainer);\n ejtab.appendChild(contentContainer);\n ejtabContainer.appendChild(ejtab);\n this.initTableProperties(this.tableTab, localValue);\n this.initTableRowProperties(this.rowTab, localValue);\n this.initTableCellProperties(this.cellTab, localValue);\n this.tabObj = new Tab({}, ejtab);\n this.target.appendChild(separatorLine);\n var alignMentButtons = this.tableTab.getElementsByClassName(this.tableTab.id + 'e-de-table-alignment');\n for (var i = 0; i < alignMentButtons.length; i++) {\n alignMentButtons[i].addEventListener('click', this.changeTableAlignment);\n }\n var cellAlignment = this.cellTab.getElementsByClassName(this.cellTab.id + 'e-de-table-cell-alignment');\n for (var i = 0; i < cellAlignment.length; i++) {\n cellAlignment[i].addEventListener('click', this.changeCellAlignment);\n }\n var tableTabHeader = this.tabObj.element.getElementsByClassName('e-item e-toolbar-item')[0];\n var tableTabHeaderItem = tableTabHeader.getElementsByClassName('e-tab-wrap')[0];\n tableTabHeaderItem.classList.add('e-de-table-ppty-dlg-table-header');\n var rowTabHeader = this.tabObj.element.getElementsByClassName('e-item e-toolbar-item')[1];\n var rowTabHeaderItem = rowTabHeader.getElementsByClassName('e-tab-wrap')[0];\n rowTabHeaderItem.classList.add('e-de-table-ppty-dlg-row-header');\n var cellTabHeader = this.tabObj.element.getElementsByClassName('e-item e-toolbar-item')[2];\n var cellTabHeaderItem = cellTabHeader.getElementsByClassName('e-tab-wrap')[0];\n cellTabHeaderItem.classList.add('e-de-table-ppty-dlg-cell-header');\n this.tabObj.element.getElementsByClassName('e-indicator')[0].style.right = '155px';\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.show = function () {\n var localValue = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localValue.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initTablePropertyDialog(localValue);\n }\n if (this.owner.selection.caret.style.display !== 'none') {\n this.owner.selection.caret.style.display = 'none';\n }\n this.owner.dialog2.header = localValue.getConstant('Table Properties');\n this.owner.dialog2.position = { X: 'center', Y: 'center' };\n this.owner.dialog2.width = 'auto';\n this.owner.dialog2.height = 'auto';\n this.owner.dialog2.content = this.target;\n this.owner.dialog2.beforeOpen = this.onBeforeOpen;\n this.owner.dialog2.close = this.onCloseTablePropertyDialog;\n this.owner.dialog2.open = this.wireEvent.bind(this);\n this.owner.dialog2.buttons = [{\n click: this.applyTableProperties,\n buttonModel: { content: localValue.getConstant('Ok'), cssClass: 'e-flat e-table-ppty-okay', isPrimary: true }\n },\n {\n click: this.closeTablePropertiesDialog,\n buttonModel: { content: localValue.getConstant('Cancel'), cssClass: 'e-flat e-table-ppty-cancel' }\n }];\n //this.tabObj.select(0);\n this.owner.dialog2.dataBind();\n this.owner.dialog2.show();\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.calculateGridValue = function (table) {\n table.calculateGrid();\n table.isGridUpdated = false;\n table.buildTableColumns();\n table.isGridUpdated = true;\n this.owner.selection.owner.isLayoutEnabled = true;\n this.owner.layout.reLayoutTable(table);\n this.owner.owner.editorModule.reLayout(this.owner.selection);\n this.owner.owner.editorModule.updateSelectionTextPosition(true);\n var history = this.owner.owner.editorHistory;\n if (history && history.currentBaseHistoryInfo) {\n if (history.currentBaseHistoryInfo.modifiedProperties.length > 0) {\n history.currentBaseHistoryInfo.updateSelection();\n }\n history.updateHistory();\n }\n this.owner.owner.editorModule.fireContentChange();\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.loadTableProperties = function () {\n this.setTableProperties();\n this.setTableRowProperties();\n this.setTableCellProperties();\n if (!this.owner.owner.bordersAndShadingDialogModule) {\n this.bordersAndShadingButton.disabled = true;\n }\n else {\n this.bordersAndShadingButton.disabled = false;\n }\n // if (!this.owner.owner.tableOptionsDialogModule) {\n // this.tableOptionButton.disabled = true;\n // } else {\n this.tableOptionButton.disabled = false;\n // }\n // if (!this.owner.owner.cellOptionsDialogModule) {\n // this.cellOptionButton.disabled = true;\n // } else {\n this.cellOptionButton.disabled = false;\n // }\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.wireEvent = function () {\n this.owner.selection.hideCaret();\n //Table Format\n this.preferCheckBox.change = this.changeTableCheckBox.bind(this);\n this.tableWidthBox.change = this.onTableWidthChange.bind(this);\n this.tableWidthType.change = this.onTableWidthTypeChange.bind(this);\n this.leftIndentBox.change = this.onLeftIndentChange.bind(this);\n //Row Format\n this.rowHeightCheckBox.change = this.changeTableRowCheckBox.bind(this);\n this.rowHeightBox.change = this.onRowHeightChange.bind(this);\n this.rowHeightType.change = this.onRowHeightTypeChange.bind(this);\n this.allowRowBreak.change = this.onAllowBreakAcrossPage.bind(this);\n this.repeatHeader.change = this.onRepeatHeader.bind(this);\n //Cell Format\n this.preferredCellWidthCheckBox.change = this.changeTableCellCheckBox.bind(this);\n this.cellWidthBox.change = this.onCellWidthChange.bind(this);\n this.cellWidthType.change = this.onCellWidthTypeChange.bind(this);\n };\n //#region Table Format\n /**\n * @private\n */\n // tslint:disable-next-line:max-func-body-length\n TablePropertiesDialog.prototype.initTableProperties = function (element, localValue) {\n var container = createElement('div', { id: element.id + '_table_TabContainer' });\n var sizeHeader = createElement('div', {\n id: container.id + '_sizeLabel', innerHTML: localValue.getConstant('Size'),\n styles: 'width:100%;margin:0px;padding-top: 20px;padding-bottom: 0px;', className: 'e-de-table-dialog-options-label'\n });\n var parentContainer = createElement('div', { styles: 'display: inline-flex;' });\n var childContainer1 = createElement('div', {\n styles: 'float: left;',\n className: 'e-de-table-container-div'\n });\n var childContainer2 = createElement('div', {\n className: 'e-de-table-ppty-dlg-preferred-width-div'\n });\n var child1 = createElement('div', {\n styles: 'display: inline;',\n className: 'e-de-table-ppty-dlg-measure-div'\n });\n var child2 = createElement('div', {\n styles: 'display: inline;position: absolute;',\n className: 'e-de-table-ppty-dlg-measure-drop-down-div'\n });\n var childContainer3 = createElement('div');\n var preferCheckBox = createElement('input', {\n id: element.id + '_Prefer_Width_CheckBox', attrs: { 'type': 'checkbox' }\n });\n this.preferredWidth = createElement('input', { id: element.id + 'preferred_Width' });\n var controlDiv = createElement('div');\n var tableWidthType = createElement('select', {\n innerHTML: '' + localValue.getConstant('Points') +\n ' ' + localValue.getConstant('Percent') + ' ', id: element.id + '_width_dropdown'\n });\n var labeltext = createElement('label', {\n innerHTML: localValue.getConstant('Measure in'), styles: 'width: 60px;font-size: 11px; font-weight: normal;'\n });\n var alignmentHeader = createElement('div', {\n innerHTML: localValue.getConstant('Alignment'), className: 'e-de-table-dialog-options-label',\n styles: 'width: 100%;margin: 0px;padding-bottom: 15px'\n });\n var alignmentContainer = createElement('div', { styles: 'height:70px;' });\n var classDivName = element.id + 'e-de-table-alignment';\n var leftAlignDiv = createElement('div', { className: 'e-de-table-dia-align-div' });\n this.left = createElement('div', {\n className: 'e-icons e-de-table-properties-alignment e-de-table-left-alignment ' + classDivName,\n id: element.id + '_left_alignment', styles: 'width:54px;height:54px;margin:2px'\n });\n leftAlignDiv.appendChild(this.left);\n var centerAlignDiv = createElement('div', { className: 'e-de-table-dia-align-div' });\n this.center = createElement('div', {\n className: 'e-icons e-de-table-properties-alignment e-de-table-center-alignment ' + classDivName,\n id: element.id + '_center_alignment', styles: 'width:54px;height:54px;margin:2px'\n });\n centerAlignDiv.appendChild(this.center);\n this.right = createElement('div', {\n styles: 'width:54px;height:54px;margin:2px', id: element.id + '_right_alignment',\n className: 'e-icons e-de-table-properties-alignment e-de-table-right-alignment ' + classDivName\n });\n var rightAlignDiv = createElement('div', { className: 'e-de-table-dia-align-div' });\n rightAlignDiv.appendChild(this.right);\n var leftlabel = createElement('label', {\n innerHTML: localValue.getConstant('Left'), className: 'e-de-table-dia-align-label'\n });\n var centerlabel = createElement('label', {\n innerHTML: localValue.getConstant('Center'), className: 'e-de-table-dia-align-label'\n });\n var rightlabel = createElement('label', {\n innerHTML: localValue.getConstant('Right'), className: 'e-de-table-dia-align-label'\n });\n var leftIndenetContainer = createElement('div', {\n className: 'e-de-table-ppty-dlg-left-indent-container'\n });\n var leftIndentLabel = createElement('label', {\n innerHTML: localValue.getConstant('Indent from left'),\n styles: 'font-weight: normal;font-size: 11px;float:right;margin-right:121px;'\n });\n var leftIndentBox = createElement('div', {\n styles: 'margin-top: 27px;'\n });\n this.leftIndent = createElement('input', { id: element.id + '_left_indent' });\n var tableOptionContiner = createElement('div', {\n className: 'e-de-tbl-dlg-border-btn'\n });\n this.bordersAndShadingButton = createElement('button', {\n innerHTML: localValue.getConstant('Borders and Shading'),\n id: element.id + '_borders_and_shadings', className: 'e-control e-btn e-flat e-de-ok-button'\n });\n this.tableOptionButton = createElement('button', {\n className: 'e-control e-btn e-flat', innerHTML: localValue.getConstant('Options'),\n id: element.id + '_table_cellmargin'\n });\n this.tableOptionButton.addEventListener('click', this.showTableOptionsDialog);\n this.bordersAndShadingButton.addEventListener('click', this.showBordersShadingsPropertiesDialog);\n tableOptionContiner.appendChild(this.bordersAndShadingButton);\n tableOptionContiner.appendChild(this.tableOptionButton);\n leftIndenetContainer.appendChild(leftIndentLabel);\n leftIndentBox.appendChild(this.leftIndent);\n leftIndenetContainer.appendChild(leftIndentBox);\n alignmentContainer.appendChild(leftAlignDiv);\n alignmentContainer.appendChild(centerAlignDiv);\n alignmentContainer.appendChild(rightAlignDiv);\n leftAlignDiv.appendChild(leftlabel);\n centerAlignDiv.appendChild(centerlabel);\n rightAlignDiv.appendChild(rightlabel);\n alignmentContainer.appendChild(leftIndenetContainer);\n container.appendChild(sizeHeader);\n element.appendChild(container);\n childContainer1.appendChild(preferCheckBox);\n parentContainer.appendChild(childContainer1);\n childContainer2.appendChild(this.preferredWidth);\n parentContainer.appendChild(childContainer2);\n controlDiv.appendChild(tableWidthType);\n child1.appendChild(labeltext);\n child2.appendChild(controlDiv);\n childContainer3.appendChild(child1);\n childContainer3.appendChild(child2);\n parentContainer.appendChild(childContainer3);\n element.appendChild(parentContainer);\n element.appendChild(alignmentHeader);\n element.appendChild(alignmentContainer);\n element.appendChild(tableOptionContiner);\n this.tableWidthBox = new NumericTextBox({\n value: 0, decimals: 2, min: 0, max: 1584, width: 120, enablePersistence: false\n });\n this.tableWidthBox.appendTo(this.preferredWidth);\n this.leftIndentBox = new NumericTextBox({\n value: 0, decimals: 2, min: -1584, max: 1584, width: 140, enablePersistence: false\n });\n this.leftIndentBox.appendTo(this.leftIndent);\n this.preferCheckBox = new CheckBox({\n label: localValue.getConstant('Preferred Width')\n });\n this.preferCheckBox.appendTo(preferCheckBox);\n this.tableWidthType = new DropDownList({ width: '120px' });\n this.tableWidthType.appendTo(tableWidthType);\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onTableWidthChange = function () {\n this.tableFormat.preferredWidth = this.tableWidthBox.value;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onTableWidthTypeChange = function () {\n var value;\n var table = this.owner.selection.start.paragraph.associatedCell.ownerTable;\n var width = HelperMethods.convertPixelToPoint(this.owner.clientArea.width);\n if (this.tableWidthType.text === 'Percent' && this.owner.selection.tableFormat.preferredWidthType !== 'Percent') {\n value = this.tableWidthBox.value / width * 100;\n this.formatNumericTextBox(this.tableWidthBox, 'Percent', value);\n }\n else if (this.tableWidthType.text === 'Points' && this.owner.selection.tableFormat.preferredWidthType !== 'Point') {\n value = width / 100 * this.tableWidthBox.value;\n this.formatNumericTextBox(this.tableWidthBox, 'Point', value);\n }\n else {\n if (this.tableWidthBox.format === '#\\'\\%\\'') {\n if (this.tableWidthType.text === 'Points') {\n value = width / 100 * this.tableWidthBox.value;\n }\n else {\n value = this.tableWidthBox.value;\n }\n }\n else {\n if (this.tableWidthType.text === 'Percent') {\n value = this.tableWidthBox.value / width * 100;\n }\n else {\n value = this.tableWidthBox.value;\n }\n }\n // tslint:disable-next-line:max-line-length\n this.formatNumericTextBox(this.tableWidthBox, (this.tableWidthType.text === 'Points') ? 'Point' : this.tableWidthType.text, value);\n }\n this.tableFormat.preferredWidthType = (this.tableWidthType.text === 'Points') ? 'Point' : this.tableWidthType.text;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onLeftIndentChange = function () {\n this.tableFormat.leftIndent = this.leftIndentBox.value;\n };\n TablePropertiesDialog.prototype.setTableProperties = function () {\n //instance of Table Property values\n var tableFormat = this.owner.selection.tableFormat;\n var tableHasWidth = tableFormat.preferredWidth > 0;\n var preferredWidth = tableFormat.preferredWidth;\n if (isNullOrUndefined(tableFormat.preferredWidth)) {\n this.preferCheckBox.indeterminate = true;\n var startTable = this.owner.selection.start.paragraph.associatedCell.ownerTable;\n var table = startTable.combineWidget(this.owner);\n preferredWidth = table.tableFormat.preferredWidth;\n }\n else {\n this.preferCheckBox.checked = tableHasWidth;\n }\n this.tableWidthBox.enabled = tableHasWidth;\n this.tableWidthType.enabled = tableHasWidth;\n this.formatNumericTextBox(this.tableWidthBox, tableFormat.preferredWidthType, preferredWidth);\n if (tableFormat.preferredWidthType === 'Auto' || tableFormat.preferredWidthType === 'Point') {\n this.tableWidthType.index = 0;\n }\n else {\n this.tableWidthType.index = 1;\n }\n this.leftIndentBox.value = tableFormat.leftIndent;\n this.leftIndentBox.enabled = tableFormat.tableAlignment === 'Left';\n classList(this.left, [], ['e-de-table-alignment-active']);\n classList(this.right, [], ['e-de-table-alignment-active']);\n classList(this.center, [], ['e-de-table-alignment-active']);\n if (tableFormat.tableAlignment === 'Left') {\n this.left.classList.add('e-de-table-alignment-active');\n }\n else if (tableFormat.tableAlignment === 'Center') {\n this.center.classList.add('e-de-table-alignment-active');\n }\n else if (tableFormat.tableAlignment === 'Right') {\n this.right.classList.add('e-de-table-alignment-active');\n }\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.getTableAlignment = function () {\n var id = this.tableTab.id;\n var groupButtons = this.tableTab.getElementsByClassName(id + 'e-de-table-alignment');\n for (var j = 0; j < groupButtons.length; j++) {\n var groupButton = groupButtons[j];\n if (groupButton.classList.contains('e-de-table-alignment-active')) {\n if (j === 0) {\n return 'Left';\n }\n else if (j === 1) {\n return 'Center';\n }\n else {\n return 'Right';\n }\n }\n }\n return undefined;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.updateClassForAlignmentProperties = function (element) {\n var id = element.id;\n var groupButtons = element.getElementsByClassName(id + 'e-de-table-alignment');\n for (var j = 0; j < groupButtons.length; j++) {\n var groupButton = groupButtons[j];\n if (groupButton.classList.contains('e-de-table-alignment-active')) {\n classList(groupButton, ['e-de-table-properties-alignment'], ['e-de-table-alignment-active']);\n }\n }\n };\n //#endregion\n //#region Row Format\n /**\n * @private\n */\n TablePropertiesDialog.prototype.initTableRowProperties = function (element, localValue) {\n var rowDiv = createElement('div', { styles: 'width: 100%;' });\n var sizeLabeldiv = createElement('div', {\n innerHTML: localValue.getConstant('Size'),\n styles: 'width: 100%;padding-top: 20px;padding-bottom: 10px;',\n className: 'e-de-table-dialog-options-label'\n });\n var parentDiv = createElement('div', { styles: 'display: inline;width: 100%;' });\n var childDiv1 = createElement('div', {\n styles: 'display: inline;float: left;',\n className: 'e-de-table-header-div'\n });\n var rowHeightCheckBox = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: element.id + '_height_CheckBox'\n });\n var childdiv2 = createElement('div', {\n styles: 'display: inline-block;',\n className: 'e-de-row-ht-top'\n });\n this.rowHeight = createElement('input', {\n attrs: { 'type': 'text' }, 'id': element.id + '_table_row_height'\n });\n var child2 = createElement('div', {\n styles: 'float: right;display: inline;width: auto;margin-top: 5px;'\n });\n var child3 = createElement('div', {\n styles: 'display: inline;',\n className: 'e-de-table-ppty-dlg-row-height-label'\n });\n var child4 = createElement('div', {\n styles: 'display: inline;',\n className: 'e-de-table-subheader-div'\n });\n var controlDiv = createElement('div');\n var rowHeightType = createElement('select', {\n innerHTML: '' + localValue.getConstant('At least')\n + ' ' + localValue.getConstant('Exactly') + ' ',\n id: element.id + '_height_type'\n });\n var labeltext = createElement('label', {\n innerHTML: localValue.getConstant('Row height is'), styles: 'font-size: 11px;font-weight: normal;width: 75px;'\n });\n rowDiv.appendChild(sizeLabeldiv);\n element.appendChild(rowDiv);\n childDiv1.appendChild(rowHeightCheckBox);\n parentDiv.appendChild(childDiv1);\n childdiv2.appendChild(this.rowHeight);\n parentDiv.appendChild(childdiv2);\n controlDiv.appendChild(rowHeightType);\n child3.appendChild(labeltext);\n child4.appendChild(controlDiv);\n child2.appendChild(child3);\n child2.appendChild(child4);\n parentDiv.appendChild(child2);\n element.appendChild(parentDiv);\n var alignmentDiv = createElement('div', {\n innerHTML: localValue.getConstant('Options'), styles: 'width: 100%;',\n className: 'e-de-table-dialog-options-label'\n });\n // tslint:disable-next-line:max-line-length\n var allowRowContainer = createElement('div', { className: 'e-de-table-ppty-options-break' });\n var repeatHeaderContaniner = createElement('div', { className: 'e-de-table-ppty-options-header-row' });\n var allowRowBreak = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: element.id + '_allow_row_break'\n });\n var repeatHeader = createElement('input', {\n attrs: { 'type': 'checkbox' }, 'id': element.id + '_repeat_header'\n });\n allowRowContainer.appendChild(allowRowBreak);\n repeatHeaderContaniner.appendChild(repeatHeader);\n element.appendChild(alignmentDiv);\n element.appendChild(allowRowContainer);\n element.appendChild(repeatHeaderContaniner);\n this.rowHeightBox = new NumericTextBox({\n value: 0, decimals: 2, min: 0, max: 1584, width: 120, enablePersistence: false\n });\n this.rowHeightBox.appendTo(this.rowHeight);\n this.rowHeightCheckBox = new CheckBox({\n label: localValue.getConstant('Specify height')\n });\n this.rowHeightCheckBox.appendTo(rowHeightCheckBox);\n this.rowHeightType = new DropDownList({ width: '120px' });\n this.rowHeightType.appendTo(rowHeightType);\n this.allowRowBreak = new CheckBox({\n label: localValue.getConstant('Allow row to break across pages')\n });\n this.allowRowBreak.appendTo(allowRowBreak);\n this.repeatHeader = new CheckBox({\n label: localValue.getConstant('Repeat as header row at the top of each page')\n });\n this.repeatHeader.appendTo(repeatHeader);\n };\n TablePropertiesDialog.prototype.setTableRowProperties = function () {\n var rowFormat = this.owner.selection.rowFormat;\n var enableRowHeight = (rowFormat.height > 0 || rowFormat.heightType === 'Exactly');\n //instance of table row values\n if (enableRowHeight) {\n this.rowHeightCheckBox.checked = true;\n }\n else {\n if (rowFormat.heightType === undefined) {\n this.rowHeightCheckBox.indeterminate = true;\n enableRowHeight = true;\n }\n else {\n this.rowHeightCheckBox.checked = false;\n }\n }\n this.rowHeightBox.enabled = enableRowHeight;\n this.rowHeightType.enabled = enableRowHeight;\n // let enabledHeader: boolean = this.enableRepeatHeader() ? false : true;\n var enabledHeader = true;\n if (isNullOrUndefined(this.owner.selection.rowFormat.isHeader)) {\n this.repeatHeader.indeterminate = true;\n this.repeatHeader.disabled = true;\n }\n else if (this.owner.selection.rowFormat.isHeader) {\n this.repeatHeader.checked = !enabledHeader;\n this.repeatHeader.indeterminate = enabledHeader;\n this.repeatHeader.disabled = enabledHeader;\n }\n else {\n this.repeatHeader.checked = false;\n this.repeatHeader.indeterminate = false;\n this.repeatHeader.disabled = enabledHeader;\n }\n if (isNullOrUndefined(rowFormat.allowBreakAcrossPages)) {\n this.allowRowBreak.indeterminate = true;\n }\n else {\n this.allowRowBreak.checked = rowFormat.allowBreakAcrossPages;\n }\n this.rowHeightBox.value = rowFormat.height;\n if (rowFormat.heightType === 'Auto' || rowFormat.heightType === 'AtLeast') {\n this.rowHeightType.index = 0;\n }\n else {\n this.rowHeightType.index = 1;\n }\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onRowHeightChange = function () {\n this.rowHeightValue = this.rowHeightBox.value;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onRowHeightTypeChange = function () {\n this.rowFormat.heightType = this.rowHeightType.text;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onAllowBreakAcrossPage = function () {\n this.rowFormat.allowBreakAcrossPages = this.allowRowBreak.checked;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onRepeatHeader = function () {\n this.rowFormat.isHeader = this.repeatHeader.checked;\n };\n /**\n * @private\n */\n // public enableRepeatHeader(): boolean {\n // let isFirstRow: number = 0;\n // for (let i: number = 0; i < this.owner.selection.selectionRanges.length; i++) {\n // let range: SelectionRange = this.owner.selection.selectionRanges.getRange(i);\n // let table: WTable = range.start.paragraph.associatedCell.ownerTable;\n // if (table.childNodes.indexOf(range.start.paragraph.associatedCell.ownerRow) === 0 ||\n // table.childNodes.indexOf(range.start.paragraph.associatedCell.ownerRow) === 0) {\n // isFirstRow++;\n // }\n // }\n // return isFirstRow === this.owner.selection.selectionRanges.length;\n // }\n //#endregion\n //#region Cell Format\n /**\n * @private\n */\n TablePropertiesDialog.prototype.initTableCellProperties = function (element, localValue) {\n var sizeDiv = createElement('div', { styles: 'width: 100%;' });\n var div = createElement('div', {\n innerHTML: localValue.getConstant('Size'), className: 'e-de-table-dialog-options-label',\n styles: 'width: 100%;padding-top: 20px;padding-bottom: 10px;',\n });\n var parentdiv = createElement('div', { styles: 'display: inline;width: 100%;' });\n var childdiv1 = createElement('div', {\n styles: 'display: inline;float: left;',\n className: 'e-de-table-cell-header-div'\n });\n var preferredCellWidthCheckBox = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: element.id + '_Prefer_Width_CheckBox_cell'\n });\n var childdiv2 = createElement('div', {\n styles: 'display: inline-block;',\n className: 'e-de-cell-width-top'\n });\n this.preferredCellWidth = createElement('input', {\n id: element.id + 'tablecell_Width_textBox', attrs: { 'type': 'text' }\n });\n var child2 = createElement('div', {\n styles: 'float: right;display: inline;width: auto;margin-top: 5px;'\n });\n var child3 = createElement('div', {\n styles: 'display: inline;',\n className: 'e-de-table-ppty-dlg-cell-tab-measure-label'\n });\n var child4 = createElement('div', {\n styles: 'display: inline;float: right;', className: 'e-de-table-cell-subheader-div'\n });\n var controlDiv = createElement('div');\n var cellWidthType = createElement('select', {\n innerHTML: '' + localValue.getConstant('Points') + ' ' +\n localValue.getConstant('Percent') + ' ', 'id': element.id + '_measure_type_cell'\n });\n var labeltext = createElement('label', {\n innerHTML: localValue.getConstant('Measure in'),\n styles: 'font-size: 11px;font-weight: normal;'\n });\n sizeDiv.appendChild(div);\n element.appendChild(sizeDiv);\n childdiv1.appendChild(preferredCellWidthCheckBox);\n parentdiv.appendChild(childdiv1);\n childdiv2.appendChild(this.preferredCellWidth);\n parentdiv.appendChild(childdiv2);\n controlDiv.appendChild(cellWidthType);\n child3.appendChild(labeltext);\n child4.appendChild(controlDiv);\n child2.appendChild(child3);\n child2.appendChild(child4);\n parentdiv.appendChild(child2);\n element.appendChild(parentdiv);\n var alignmentDiv = createElement('div', {\n innerHTML: localValue.getConstant('Vertical alignment'),\n styles: 'width: 100%;margin: 0px;',\n className: 'e-de-table-dialog-options-label'\n });\n var classDivName = element.id + 'e-de-table-cell-alignment';\n var divAlignment = createElement('div', {\n styles: 'width: 100%;height: 100px;'\n });\n var divStyle = 'width:54px;height:54px;margin:2px;border-style:solid;border-width:1px';\n var topAlignDiv = createElement('div', { className: 'e-de-table-dia-align-div' });\n this.cellTopAlign = createElement('div', {\n styles: divStyle, id: element.id + '_cell_top-alignment',\n className: 'e-icons e-de-tablecell-alignment e-de-tablecell-top-alignment ' + classDivName\n });\n topAlignDiv.appendChild(this.cellTopAlign);\n var centerAlignDiv = createElement('div', { className: 'e-de-table-dia-align-div' });\n this.cellCenterAlign = createElement('div', {\n styles: divStyle, id: element.id + '_cell_center-alignment',\n className: 'e-icons e-de-tablecell-alignment e-de-tablecell-center-alignment ' + classDivName\n });\n centerAlignDiv.appendChild(this.cellCenterAlign);\n var bottomAlignDiv = createElement('div', { className: 'e-de-table-dia-align-div' });\n this.cellBottomAlign = createElement('div', {\n styles: divStyle, id: element.id + '_cell_bottom-alignment',\n className: 'e-icons e-de-tablecell-alignment e-de-tablecell-bottom-alignment ' + classDivName\n });\n bottomAlignDiv.appendChild(this.cellBottomAlign);\n var topLabel = createElement('label', {\n innerHTML: localValue.getConstant('Top'), className: 'e-de-table-dia-align-label'\n });\n var centerLabel = createElement('label', {\n innerHTML: localValue.getConstant('Center'), className: 'e-de-table-dia-align-label'\n });\n var bottomLabel = createElement('label', {\n innerHTML: localValue.getConstant('Bottom'), className: 'e-de-table-dia-align-label'\n });\n this.cellOptionButton = createElement('button', {\n innerHTML: localValue.getConstant('Options'), id: element.id + '_table_cellmargin',\n className: 'e-de-tbl-dlg-op-btn e-control e-btn e-flat e-de-cell-options',\n });\n divAlignment.appendChild(topAlignDiv);\n divAlignment.appendChild(centerAlignDiv);\n divAlignment.appendChild(bottomAlignDiv);\n topAlignDiv.appendChild(topLabel);\n centerAlignDiv.appendChild(centerLabel);\n bottomAlignDiv.appendChild(bottomLabel);\n element.appendChild(alignmentDiv);\n element.appendChild(divAlignment);\n element.appendChild(this.cellOptionButton);\n this.cellOptionButton.addEventListener('click', this.showCellOptionsDialog);\n this.cellWidthBox = new NumericTextBox({\n value: 0, decimals: 2, min: 0, max: 1584, width: 120, enablePersistence: false\n });\n this.cellWidthBox.appendTo(this.preferredCellWidth);\n this.preferredCellWidthCheckBox = new CheckBox({ label: localValue.getConstant('Preferred Width') });\n this.preferredCellWidthCheckBox.appendTo(preferredCellWidthCheckBox);\n this.cellWidthType = new DropDownList({ width: '120px' });\n this.cellWidthType.appendTo(cellWidthType);\n };\n TablePropertiesDialog.prototype.setTableCellProperties = function () {\n var cellFormat = this.owner.selection.cellFormat;\n //instance of table cell Values\n this.hasCellWidth = cellFormat.preferredWidth > 0;\n var preferredWidth = cellFormat.preferredWidth;\n if (isNullOrUndefined(cellFormat.preferredWidth)) {\n this.preferredCellWidthCheckBox.indeterminate = true;\n preferredWidth = this.owner.selection.start.paragraph.associatedCell.cellFormat.preferredWidth;\n }\n else {\n this.preferredCellWidthCheckBox.checked = this.hasCellWidth;\n }\n this.cellWidthBox.enabled = this.hasCellWidth;\n this.cellWidthType.enabled = this.hasCellWidth;\n if (cellFormat.preferredWidthType === 'Auto' || cellFormat.preferredWidthType === 'Point') {\n this.cellWidthType.index = 0;\n }\n else {\n this.cellWidthType.index = 1;\n }\n this.formatNumericTextBox(this.cellWidthBox, cellFormat.preferredWidthType, preferredWidth);\n classList(this.cellTopAlign, ['e-de-tablecell-alignment'], ['e-de-table-alignment-active']);\n classList(this.cellCenterAlign, ['e-de-tablecell-alignment'], ['e-de-table-alignment-active']);\n classList(this.cellBottomAlign, ['e-de-tablecell-alignment'], ['e-de-table-alignment-active']);\n if (cellFormat.verticalAlignment === 'Top') {\n this.cellTopAlign.classList.add('e-de-table-alignment-active');\n }\n else if (cellFormat.verticalAlignment === 'Center') {\n this.cellCenterAlign.classList.add('e-de-table-alignment-active');\n }\n else if (cellFormat.verticalAlignment === 'Bottom') {\n this.cellBottomAlign.classList.add('e-de-table-alignment-active');\n }\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.updateClassForCellAlignment = function (element) {\n var cellAlignments = element.getElementsByClassName(element.id + 'e-de-table-cell-alignment');\n for (var j = 0; j < cellAlignments.length; j++) {\n var cellAlignment = cellAlignments[j];\n if (cellAlignment.classList.contains('e-de-table-alignment-active')) {\n classList(cellAlignment, ['e-de-tablecell-alignment'], ['e-de-table-alignment-active']);\n }\n }\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.formatNumericTextBox = function (textBox, format, value) {\n if (format === 'Auto' || format === 'Point') {\n textBox.format = 'n2';\n }\n else {\n textBox.format = '#\\'\\%\\'';\n }\n textBox.step = 1;\n textBox.decimals = 2;\n textBox.value = value;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.getCellAlignment = function () {\n var id = this.cellTab.id;\n var groupButtons = this.cellTab.getElementsByClassName(id + 'e-de-table-cell-alignment');\n for (var j = 0; j < groupButtons.length; j++) {\n var groupButton = groupButtons[j];\n if (groupButton.classList.contains('e-de-table-alignment-active')) {\n if (j === 0) {\n return 'Top';\n }\n else if (j === 1) {\n return 'Center';\n }\n else {\n return 'Bottom';\n }\n }\n }\n return this.owner.selection.cellFormat.verticalAlignment;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onCellWidthChange = function () {\n this.cellFormat.preferredWidth = this.cellWidthBox.value;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.onCellWidthTypeChange = function () {\n var value;\n var table = this.owner.selection.start.paragraph.associatedCell.ownerTable;\n var containerWidth = table.getOwnerWidth(true);\n var tableWidth = table.getTableClientWidth(containerWidth);\n if (this.cellWidthType.text === 'Percent' && this.owner.selection.cellFormat.preferredWidthType !== 'Percent') {\n value = this.cellWidthBox.value / tableWidth * 100;\n this.formatNumericTextBox(this.cellWidthBox, 'Percent', value);\n }\n else if (this.cellWidthType.text === 'Points' && this.owner.selection.cellFormat.preferredWidthType !== 'Point') {\n value = tableWidth / 100 * this.cellWidthBox.value;\n this.formatNumericTextBox(this.cellWidthBox, 'Point', value);\n }\n else {\n if (this.cellWidthBox.format === '#\\'\\%\\'') {\n if (this.cellWidthType.text === 'Points') {\n value = tableWidth / 100 * this.cellWidthBox.value;\n }\n else {\n value = this.cellWidthBox.value;\n }\n }\n else {\n if (this.cellWidthType.text === 'Percent') {\n value = this.cellWidthBox.value / tableWidth * 100;\n }\n else {\n value = this.cellWidthBox.value;\n }\n }\n // tslint:disable-next-line:max-line-length\n this.formatNumericTextBox(this.cellWidthBox, (this.cellWidthType.text === 'Points') ? 'Point' : this.cellWidthType.text, value);\n }\n this.cellFormat.preferredWidthType = (this.cellWidthType.text === 'Points') ? 'Point' : this.cellWidthType.text;\n };\n /**\n * @private\n */\n TablePropertiesDialog.prototype.destroy = function () {\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var s = 0; s < this.target.childNodes.length; s++) {\n this.target.removeChild(this.target.childNodes[s]);\n s--;\n }\n this.target = undefined;\n }\n this.dialog = undefined;\n this.target = undefined;\n this.cellAlignment = undefined;\n this.tableAlignment = undefined;\n this.owner = undefined;\n this.preferCheckBox = undefined;\n this.tableWidthType = undefined;\n this.preferredWidth = undefined;\n this.rowHeightType = undefined;\n this.rowHeightCheckBox = undefined;\n this.rowHeight = undefined;\n this.cellWidthType = undefined;\n this.preferredCellWidthCheckBox = undefined;\n this.preferredCellWidth = undefined;\n this.tableTab = undefined;\n this.rowTab = undefined;\n this.cellTab = undefined;\n this.left = undefined;\n this.center = undefined;\n this.right = undefined;\n this.leftIndent = undefined;\n this.allowRowBreak = undefined;\n this.repeatHeader = undefined;\n this.cellTopAlign = undefined;\n this.cellCenterAlign = undefined;\n this.cellBottomAlign = undefined;\n this.tableFormat.destroy();\n this.cellFormat.destroy();\n this.tableFormat = undefined;\n this.cellFormat = undefined;\n };\n return TablePropertiesDialog;\n}());\nexport { TablePropertiesDialog };\n","import { createElement, isNullOrUndefined, L10n, setCulture } from '@syncfusion/ej2-base';\nimport { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { WTableFormat, WBorder, WBorders, WShading, WCellFormat } from '../format/index';\nimport { DropDownList } from '@syncfusion/ej2-dropdowns';\nimport { ColorPicker } from '@syncfusion/ej2-inputs';\n/**\n * The Borders and Shading dialog is used to modify borders and shading options for selected table or cells.\n */\nvar BordersAndShadingDialog = /** @class */ (function () {\n /**\n * @private\n */\n function BordersAndShadingDialog(viewer) {\n var _this = this;\n this.cellFormat = new WCellFormat();\n this.tableFormat = new WTableFormat();\n this.applyBordersShadingsProperties = function () {\n var tablePropertiesDialog = _this.owner.owner.tablePropertiesDialogModule;\n var selectedCell = _this.owner.selection.start.paragraph.associatedCell;\n //Need to bind the properties with current cell and current table formats.\n var borders = undefined;\n if (_this.checkClassName(_this.previewDivTopTop) || _this.checkClassName(_this.previewDivTopBottom)\n || _this.checkClassName(_this.previewDivTopCenter) || _this.checkClassName(_this.previewDivBottomcenter)\n || _this.checkClassName(_this.previewDivBottomLeft) || _this.checkClassName(_this.previewDivBottomRight)\n || _this.checkClassName(_this.previewDivDiagonalRight) || _this.checkClassName(_this.previewDivLeftDiagonal)) {\n borders = new WBorders();\n if (_this.checkClassName(_this.previewDivTopTop)) {\n borders.top = _this.getBorder();\n }\n if (_this.checkClassName(_this.previewDivTopBottom)) {\n borders.bottom = _this.getBorder();\n }\n if (_this.checkClassName(_this.previewDivBottomLeft)) {\n borders.left = _this.getBorder();\n }\n if (_this.checkClassName(_this.previewDivBottomRight)) {\n borders.right = _this.getBorder();\n }\n if (_this.checkClassName(_this.previewDivTopCenter)) {\n borders.horizontal = _this.getBorder();\n }\n if (_this.checkClassName(_this.previewDivBottomcenter)) {\n borders.vertical = _this.getBorder();\n }\n if (_this.checkClassName(_this.previewDivLeftDiagonal)) {\n borders.diagonalDown = _this.getBorder();\n }\n if (_this.checkClassName(_this.previewDivDiagonalRight)) {\n borders.diagonalUp = _this.getBorder();\n }\n }\n var shading = new WShading();\n var editorModule = _this.owner.owner.editorModule;\n shading.backgroundColor = _this.shadingColorPicker.value;\n if (_this.ulelementShading.index === 0) {\n _this.applyTo = 0;\n if (tablePropertiesDialog) {\n tablePropertiesDialog.isCellBordersAndShadingUpdated = true;\n }\n _this.cellFormat.borders = new WBorders();\n if (!isNullOrUndefined(borders)) {\n editorModule.applyBordersInternal(_this.cellFormat.borders, borders);\n }\n else if (_this.noneDiv.classList.contains('e-de-table-border-inside-setting-click')) {\n editorModule.applyBordersInternal(_this.cellFormat.borders, new WBorders());\n }\n // Once option has been added for texture and foreground, need to handle this similar to Shading Fill.\n if (!isNullOrUndefined(selectedCell.cellFormat.shading)) {\n shading.foregroundColor = selectedCell.cellFormat.shading.foregroundColor;\n shading.textureStyle = selectedCell.cellFormat.shading.textureStyle;\n }\n _this.cellFormat.shading = new WShading();\n editorModule.applyShading(_this.cellFormat.shading, shading);\n }\n else {\n if (tablePropertiesDialog) {\n tablePropertiesDialog.isTableBordersAndShadingUpdated = true;\n }\n _this.applyTo = 1;\n var currentTableFormat = _this.owner.owner.selection.tableFormat.table.tableFormat;\n _this.tableFormat.copyFormat(currentTableFormat);\n _this.tableFormat.borders = new WBorders();\n if (!isNullOrUndefined(borders)) {\n editorModule.applyBordersInternal(_this.tableFormat.borders, borders);\n }\n else if (_this.noneDiv.classList.contains('e-de-table-border-inside-setting-click')) {\n editorModule.applyBordersInternal(_this.tableFormat.borders, new WBorders());\n }\n // Once option has been added for texture and foreground, need to handle this similar to Shading Fill.\n if (!isNullOrUndefined(currentTableFormat.shading)) {\n shading.foregroundColor = currentTableFormat.shading.foregroundColor;\n shading.textureStyle = currentTableFormat.shading.textureStyle;\n }\n _this.tableFormat.shading = new WShading();\n editorModule.applyShading(_this.tableFormat.shading, shading);\n }\n _this.applyFormat();\n _this.closeDialog();\n };\n /**\n * @private\n */\n this.closeDialog = function () {\n _this.owner.dialog.hide();\n _this.closeBordersShadingsDialog();\n };\n this.closeBordersShadingsDialog = function () {\n _this.owner.dialog2.element.style.pointerEvents = '';\n _this.owner.updateFocus();\n };\n this.handleSettingCheckBoxAction = function (event) {\n var targetId = event.target.id;\n var tableBorderDialogId = _this.target.id;\n var targetDiv;\n if (targetId === tableBorderDialogId + '_None_Div' || targetId === tableBorderDialogId + '_None_Div_Container'\n || targetId === tableBorderDialogId + '_None_Div_Transparent') {\n _this.updateClassForSettingDivElements();\n _this.noneDiv.classList.add('e-de-table-border-inside-setting-click');\n _this.setSettingPreviewDivElement('none');\n }\n else if (targetId === tableBorderDialogId + '_Box_Div' || targetId === tableBorderDialogId + '_Box_Div_Container'\n || targetId === tableBorderDialogId + '_Box_Div_Transparent') {\n _this.updateClassForSettingDivElements();\n _this.boxDiv.classList.add('e-de-table-border-inside-setting-click');\n _this.setSettingPreviewDivElement('box');\n }\n else if (targetId === tableBorderDialogId + '_All_Div' || targetId === tableBorderDialogId + '_All_Div_Container'\n || targetId === tableBorderDialogId + '_All_Div_Transparent') {\n _this.updateClassForSettingDivElements();\n _this.allDiv.classList.add('e-de-table-border-inside-setting-click');\n _this.setSettingPreviewDivElement('all');\n }\n else {\n _this.updateClassForSettingDivElements();\n _this.customDiv.classList.add('e-de-table-border-inside-setting-click');\n _this.setSettingPreviewDivElement('customDiv');\n }\n };\n this.handlePreviewCheckBoxAction = function (event) {\n var target = event.target;\n var targetId = target.id;\n var tableBorderDialog = _this.target;\n var tableBorderDialogId = _this.target.id;\n var checkBox;\n var compareClass = 'e-de-table-border-inside-preview-click';\n _this.customDiv.click();\n if (targetId === tableBorderDialogId + '_Preview_Div_TopTop_Container' || targetId === tableBorderDialogId + '_Preview_Div_TopTop'\n || targetId === tableBorderDialogId + '_previewDivTopTopTransParent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivTopTop);\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div', '_Preview_Div_TopTop', 'TopTop');\n }\n else if (targetId === tableBorderDialogId + '_Preview_Div_TopCenter_Container'\n || targetId === tableBorderDialogId + '_Preview_Div_TopCenter'\n || targetId === tableBorderDialogId + '_previewDivTopCenterTransParent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivTopCenter);\n // tslint:disable-next-line:max-line-length\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div_Horizontal', '_Preview_Div_TopCenter', 'TopCenter');\n }\n else if (targetId === tableBorderDialogId + '_Preview_Div_TopBottom_Container' || targetId === tableBorderDialogId + '_Preview_Div_TopBottom'\n || targetId === tableBorderDialogId + '_previewDivTopBottomTransParent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivTopBottom);\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div', '_Preview_Div_TopBottom', 'TopBottom');\n }\n else if (targetId === tableBorderDialogId + '_Preview_Div_LeftDiagonal_Container'\n || targetId === tableBorderDialogId + '_Preview_Div_LeftDiagonal'\n || targetId === tableBorderDialogId + '_previewDivLeftDiagonalTransParent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivLeftDiagonal);\n // tslint:disable-next-line:max-line-length\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div_Left_Diagonal', '_Preview_Div_LeftDiagonal', 'LeftDiagonal');\n }\n else if (targetId === tableBorderDialogId + '_Preview_Div_BottomLeft_Container' || targetId === tableBorderDialogId + '_Preview_Div_BottomLeft'\n || targetId === tableBorderDialogId + '_previewDivBottomLeftTransparent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivBottomLeft);\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div', '_Preview_Div_BottomLeft', 'BottomLeft');\n }\n else if (targetId === tableBorderDialogId + '_Preview_Div_BottomCenter_Container'\n || targetId === tableBorderDialogId + '_Preview_Div_BottomCenter'\n || targetId === tableBorderDialogId + '_previewDivBottomcenterTransparent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivBottomcenter);\n // tslint:disable-next-line:max-line-length\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div_Vertical', '_Preview_Div_BottomCenter', 'BottomCenter');\n }\n else if (targetId === tableBorderDialogId + '_Preview_Div_BottomRight_Container' || targetId === tableBorderDialogId + '_Preview_Div_BottomRight'\n || targetId === tableBorderDialogId + '_previewDivBottomRightTransparent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivBottomRight);\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div', '_Preview_Div_BottomRight', 'BottomRight');\n }\n else if (targetId === tableBorderDialogId + '_Preview_Div_RightDiagonal_Container'\n || targetId === tableBorderDialogId + '_Preview_Div_RightDiagonal'\n || targetId === tableBorderDialogId + '_previewDivDiagonalRightTransparent') {\n _this.handlePreviewCheckBoxShowHide(tableBorderDialogId, compareClass, _this.previewDivDiagonalRight);\n // tslint:disable-next-line:max-line-length\n _this.showHidePreviewDivElements(tableBorderDialogId, compareClass, '_Preview_Div_Right_Diagonal', '_Preview_Div_RightDiagonal', 'RightDiagonal');\n }\n };\n this.applyTableCellPreviewBoxes = function () {\n _this.customDiv.click();\n if (!isNullOrUndefined(_this.ulelementShading)) {\n if (_this.ulelementShading.index === 0) {\n _this.previewDivBottomcenterContainer.style.display = 'none';\n _this.previewDivTopCenterContainer.style.display = 'none';\n _this.previewVerticalDiv.style.display = 'none';\n _this.previewHorizontalDiv.style.display = 'none';\n _this.previewDivLeftDiagonal.style.display = '';\n _this.previewDivDiagonalRight.style.display = '';\n _this.previewDivBottomRightContainer.style.left = '80px';\n }\n else {\n _this.previewDivLeftDiagonal.style.display = 'none';\n _this.previewDivDiagonalRight.style.display = 'none';\n _this.previewDivBottomcenterContainer.style.display = '';\n _this.previewDivTopCenterContainer.style.display = '';\n _this.previewVerticalDiv.style.display = '';\n _this.previewHorizontalDiv.style.display = '';\n _this.previewDivBottomRightContainer.style.left = '110px';\n }\n }\n };\n this.applyPreviewTableBackgroundColor = function (args) {\n if (!isNullOrUndefined(args.currentValue)) {\n var color = args.currentValue.hex;\n _this.previewDiv.style.backgroundColor = color;\n }\n };\n this.applyPreviewTableBorderColor = function (args) {\n if (!isNullOrUndefined(args.currentValue)) {\n var color = args.currentValue.hex;\n _this.previewDiv.style.borderColor = color;\n _this.previewRightDiagonalDiv.style.backgroundColor = color;\n _this.previewLeftDiagonalDiv.style.backgroundColor = color;\n _this.previewVerticalDiv.style.backgroundColor = color;\n _this.previewHorizontalDiv.style.backgroundColor = color;\n }\n };\n this.owner = viewer;\n }\n BordersAndShadingDialog.prototype.getModuleName = function () {\n return 'BordersAndShadingDialog';\n };\n /**\n * @private\n */\n // tslint:disable-next-line:max-func-body-length\n BordersAndShadingDialog.prototype.initBordersAndShadingsDialog = function (localeValue) {\n var instance = this;\n this.target = createElement('div', {\n id: instance.owner.owner.containerId + '_table_border_shadings',\n className: 'e-de-table-border-shading-dlg'\n });\n this.owner.owner.element.appendChild(this.target);\n var displayText = createElement('div', {\n innerHTML: localeValue.getConstant('Borders'), styles: 'position: absolute;top: 65px;',\n id: this.target.id + '_border_label', className: 'e-de-table-border-heading'\n });\n var settingsContiner = createElement('div', {\n styles: 'display: inline-block;position: absolute;top: 105px;width: 100px;height: 235px;border-style: none;',\n id: this.target.id + '_border_settings'\n });\n var styleContainer = createElement('div', {\n // tslint:disable-next-line:max-line-length\n styles: 'display: inline-block;position: absolute;left: 125px;top: 125px;width: 150px;height: 235px;padding-left: 40px;border-style: none;padding-right: 40px;',\n id: this.target.id + '_border_style'\n });\n var previewContiner = createElement('div', {\n // tslint:disable-next-line:max-line-length\n styles: 'display: inline-block;position: absolute;left: 345px;top: 87px;width: 180px;height: 235px;padding: 0px;border-style: none;',\n id: this.target.id + '_border_preview'\n });\n var styleText = createElement('div', {\n innerHTML: localeValue.getConstant('Style'), styles: 'width: 100%;padding-bottom: 10px;',\n className: 'e-de-table-element-subheading'\n });\n var dropDownList = createElement('select', {\n id: this.target.id + '_border_style_dropDown'\n });\n dropDownList.innerHTML = '' + localeValue.getConstant('None') + ' '\n + localeValue.getConstant('Single') + ' ' + localeValue.getConstant('Dot') + ' '\n + localeValue.getConstant('DashSmallGap') + ' ' + localeValue.getConstant('DashLargeGap') + ' '\n + localeValue.getConstant('DashDot') + ' ' + localeValue.getConstant('DashDotDot') + ' '\n + localeValue.getConstant('Double') + ' ' + localeValue.getConstant('Triple') + ' '\n + localeValue.getConstant('ThinThickSmallGap') + ' '\n + localeValue.getConstant('ThickThinSmallGap') + ' ' + localeValue.getConstant('ThinThickThinSmallGap')\n + ' ' + localeValue.getConstant('ThinThickMediumGap') + ' '\n + localeValue.getConstant('ThickThinMediumGap') + ' ' + localeValue.getConstant('ThinThickThinMediumGap')\n + ' ' + localeValue.getConstant('ThinThickLargeGap') + ' '\n + localeValue.getConstant('ThickThinLargeGap') + ' ' + localeValue.getConstant('ThinThickThinLargeGap')\n + ' ' + localeValue.getConstant('SingleWavy') + ' '\n + localeValue.getConstant('DoubleWavy') + ' ' + localeValue.getConstant('DashDotStroked')\n + ' ' + localeValue.getConstant('Emboss3D') + ' ' + localeValue.getConstant('Engrave3D')\n + ' ' + localeValue.getConstant('Outset') + ' '\n + localeValue.getConstant('Inset') + ' ' + localeValue.getConstant('Thick') + ' ';\n var widthText = createElement('div', {\n innerHTML: localeValue.getConstant('Width'), styles: 'width:100%;padding-top: 20px;padding-bottom: 10px;',\n className: 'e-de-table-element-subheading'\n });\n var widthNumeric = createElement('input', {\n id: this.target.id + '_width'\n });\n var colorText = createElement('div', {\n innerHTML: localeValue.getConstant('Color'), styles: 'padding-top: 25px;',\n className: 'e-de-table-setting-heading'\n });\n var borderColorPickerElement = createElement('input', {\n attrs: { 'type': 'color' },\n id: this.target.id + '_border_color',\n styles: 'width: 30px;position: absolute;left: 90px;',\n className: 'e-dlg-clr-pkr-top'\n });\n var settingText = createElement('div', {\n innerHTML: localeValue.getConstant('Setting'), styles: 'width: 100%;position: absolute;',\n className: 'e-de-table-setting-heading'\n });\n var noneDivContainer = createElement('div', {\n id: this.target.id + '_None_Div_Container', className: 'e-de-table-border-none'\n });\n this.noneDiv = createElement('div', {\n id: this.target.id + '_None_Div',\n className: 'e-de-table-border-inside-setting e-de-table-border-setting-genral'\n });\n var noneDivLabel = createElement('label', {\n innerHTML: localeValue.getConstant('None'), className: 'e-de-table-setting-labels-heading',\n styles: 'padding-left: 10px;top: 20px;position: absolute;',\n id: this.target.id + '_None_Div_Label'\n });\n var boxDivContainer = createElement('div', {\n id: this.target.id + '_Box_Div_Container', className: 'e-de-table-border-box'\n });\n this.boxDiv = createElement('div', {\n id: this.target.id + '_Box_Div',\n className: 'e-de-table-border-inside-setting e-de-table-border-setting-genral'\n });\n var boxDivLabel = createElement('label', {\n innerHTML: localeValue.getConstant('Box'), className: 'e-de-table-setting-labels-heading',\n styles: 'padding-left: 10px;top: 20px;position: absolute;',\n id: this.target.id + '_Box_Div_Label'\n });\n var allDivContainer = createElement('div', {\n id: this.target.id + '_All_Div_Container', className: 'e-de-table-border-all'\n });\n this.allDiv = createElement('div', {\n id: this.target.id + '_All_Div',\n className: 'e-de-table-border-inside-setting e-de-table-border-setting-genral'\n });\n var allDivLabel = createElement('label', {\n innerHTML: localeValue.getConstant('All'), className: 'e-de-table-setting-labels-heading',\n styles: 'padding-left: 10px;top: 25px;position: absolute;',\n id: this.target.id + '_All_Div_Label'\n });\n var customDivContainer = createElement('div', {\n id: this.target.id + '_Custom_Div_Container', className: 'e-de-table-border-custom'\n });\n this.customDiv = createElement('div', {\n id: this.target.id + '_Custom_Div',\n className: 'e-de-table-border-inside-setting e-de-table-border-setting-genral'\n });\n var customDivLabel = createElement('label', {\n innerHTML: localeValue.getConstant('Custom'), className: 'e-de-table-setting-labels-heading',\n styles: 'padding-left: 10px;top: 25px;position: absolute;',\n id: this.target.id + '_Custom_Div_Label'\n });\n this.noneDivTransparent = createElement('div', {\n id: this.target.id + '_None_Div_Transparent', className: 'e-icons e-de-table-border-setting e-de-table-border-none-setting'\n });\n this.boxDivTransparent = createElement('div', {\n id: this.target.id + '_Box_Div_Transparent', className: 'e-icons e-de-table-border-setting e-de-table-border-box-setting'\n });\n this.allDivTransparent = createElement('div', {\n id: this.target.id + '_All_Div_Transparent', className: 'e-icons e-de-table-border-setting e-de-table-border-all-setting'\n });\n this.customDivTransparent = createElement('div', {\n id: this.target.id + '_Custom_Div_Transparent', className: 'e-icons e-de-table-border-setting e-de-table-border-custom-setting'\n });\n var previewText = createElement('div', {\n innerHTML: localeValue.getConstant('Preview'), className: 'e-de-table-setting-heading',\n styles: 'position: absolute;top: 20px;left: 10px;'\n });\n this.previewDiv = createElement('div', {\n styles: 'width: 80px;height: 80px;position: absolute; left: 50px;top: 50px;',\n id: this.target.id + '_Preview_Div', className: 'e-de-border-dlg-preview-div'\n });\n this.previewRightDiagonalDiv = createElement('div', {\n styles: 'position: absolute;width:1px;height:113px;left: 90px;top: 34px;transform: rotate(135deg);',\n id: this.target.id + '_Preview_Div_Right_Diagonal',\n className: 'e-de-border-dlg-preview-inside-divs'\n });\n this.previewLeftDiagonalDiv = createElement('div', {\n styles: 'position: absolute;width: 1px;height: 113px;left: 90px;top: 34px;transform:rotate(45deg);',\n id: this.target.id + '_Preview_Div_Left_Diagonal',\n className: 'e-de-border-dlg-preview-inside-divs'\n });\n this.previewVerticalDiv = createElement('div', {\n styles: 'width: 1px;height: 81px;position: absolute;left: 90px;top: 50px;',\n id: this.target.id + '_Preview_Div_Vertical',\n className: 'e-de-border-dlg-preview-inside-divs'\n });\n this.previewHorizontalDiv = createElement('div', {\n styles: 'width: 81px;height: 1px;position: absolute;left: 50px;top: 90px;',\n id: this.target.id + '_Preview_Div_Horizontal',\n className: 'e-de-border-dlg-preview-inside-divs'\n });\n this.previewDivTopTopContainer = createElement('div', {\n styles: 'top: 50px;position: absolute;left: 10px;', id: this.target.id + '_Preview_Div_TopTop_Container'\n });\n this.previewDivTopTop = createElement('div', {\n id: this.target.id + '_Preview_Div_TopTop',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivTopCenterContainer = createElement('div', {\n styles: 'top: 80px;position: absolute;left: 10px;', id: this.target.id + '_Preview_Div_TopCenter_Container'\n });\n this.previewDivTopCenter = createElement('div', {\n id: this.target.id + '_Preview_Div_TopCenter',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivTopBottomContainer = createElement('div', {\n styles: 'top: 110px;position: absolute;left: 10px;', id: this.target.id + '_Preview_Div_TopBottom_Container'\n });\n this.previewDivTopBottom = createElement('div', {\n id: this.target.id + '_Preview_Div_TopBottom',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivLeftDiagonalContainer = createElement('div', {\n styles: 'top: 145px;position: absolute;left: 10px;', id: this.target.id + '_Preview_Div_LeftDiagonal_Container'\n });\n this.previewDivLeftDiagonal = createElement('div', {\n id: this.target.id + '_Preview_Div_LeftDiagonal',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivBottomLeftContainer = createElement('div', {\n styles: 'top: 145px;position: absolute;left: 50px', id: this.target.id + '_Preview_Div_BottomLeft_Container'\n });\n this.previewDivBottomLeft = createElement('div', {\n id: this.target.id + '_Preview_Div_BottomLeft',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivBottomcenterContainer = createElement('div', {\n styles: 'top: 145px;position: absolute;left: 80px;', id: this.target.id + '_Preview_Div_BottomCenter_Container'\n });\n this.previewDivBottomcenter = createElement('div', {\n id: this.target.id + '_Preview_Div_BottomCenter',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivBottomRightContainer = createElement('div', {\n styles: 'top: 145px;position: absolute;left: 110px;', id: this.target.id + '_Preview_Div_BottomRight_Container'\n });\n this.previewDivBottomRight = createElement('div', {\n id: this.target.id + '_Preview_Div_BottomRight',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivDiagonalRightContainer = createElement('div', {\n styles: 'top: 145px; position: absolute; left: 110px;', id: this.target.id + '_Preview_Div_RightDiagonal_Container'\n });\n this.previewDivDiagonalRight = createElement('div', {\n id: this.target.id + '_Preview_Div_RightDiagonal',\n className: 'e-de-table-border-inside-preview e-de-table-border-preview-genral'\n });\n this.previewDivTopTopTransParent = createElement('div', {\n id: this.target.id + '_previewDivTopTopTransParent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-toptop-alignment'\n });\n this.previewDivTopCenterTransParent = createElement('div', {\n id: this.target.id + '_previewDivTopCenterTransParent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-topcenter-alignment'\n });\n this.previewDivTopBottomTransParent = createElement('div', {\n id: this.target.id + '_previewDivTopBottomTransParent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-topbottom-alignment'\n });\n this.previewDivLeftDiagonalTransParent = createElement('div', {\n id: this.target.id + '_previewDivLeftDiagonalTransParent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-diagionalup-alignment'\n });\n this.previewDivBottomLeftTransparent = createElement('div', {\n id: this.target.id + '_previewDivBottomLeftTransparent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-bottomleft-alignment'\n });\n this.previewDivBottomcenterTransparent = createElement('div', {\n id: this.target.id + '_previewDivBottomcenterTransparent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-bottomcenter-alignment'\n });\n this.previewDivBottomRightTransparent = createElement('div', {\n id: this.target.id + '_previewDivBottomRightTransparent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-bottomright-alignment'\n });\n this.previewDivDiagonalRightTransparent = createElement('div', {\n id: this.target.id + '_previewDivDiagonalRightTransparent',\n className: 'e-icons e-de-table-border-preview e-de-table-border-diagionaldown-alignment'\n });\n this.shadingContiner = createElement('div', {\n /* tslint:disable:max-line-length */\n styles: 'display:inline-block;position:absolute;left:17px;width:400px;height:100px;padding:0px;border-style: none;margin-left:10px;',\n id: this.target.id + '_shading_preview', className: 'e-de-table-shading-preview'\n });\n var shadingText = createElement('div', {\n innerHTML: localeValue.getConstant('Shading'), className: 'e-de-table-border-heading',\n styles: 'padding-top: 30px;left: 5px;'\n });\n var shadings = createElement('div', { styles: 'display:flex;' });\n var label = createElement('div', {\n innerHTML: localeValue.getConstant('Fill'), className: 'e-de-table-setting-heading e-de-table-border-fill',\n styles: 'top: 50px;left: 10px;'\n });\n var shadingColorPickerElement = createElement('input', {\n attrs: { 'type': 'color' },\n id: this.target.id + '_shading_color', styles: 'position: absolute;top: 75px;left: 40px;width: 30px;'\n });\n var shdApply = createElement('div', {\n styles: 'position:absolute;top:41px;left:150px;width:180px;'\n });\n var div = createElement('div', {\n styles: 'width:100px;padding-bottom: 10px;', innerHTML: localeValue.getConstant('Apply To'),\n className: 'e-de-table-element-subheading'\n });\n var divsion = createElement('div', { styles: 'width:100px;position:absolute;' });\n var ulelementShading = createElement('select', {\n innerHTML: '' + localeValue.getConstant('Cell') + ' '\n + '' + localeValue.getConstant('Table') + ' ',\n id: this.target.id + '_shading'\n });\n divsion.appendChild(ulelementShading);\n this.noneDiv.appendChild(this.noneDivTransparent);\n this.boxDiv.appendChild(this.boxDivTransparent);\n this.allDiv.appendChild(this.allDivTransparent);\n this.customDiv.appendChild(this.customDivTransparent);\n noneDivContainer.appendChild(this.noneDiv);\n noneDivContainer.appendChild(noneDivLabel);\n boxDivContainer.appendChild(this.boxDiv);\n boxDivContainer.appendChild(boxDivLabel);\n allDivContainer.appendChild(this.allDiv);\n allDivContainer.appendChild(allDivLabel);\n customDivContainer.appendChild(this.customDiv);\n customDivContainer.appendChild(customDivLabel);\n settingsContiner.appendChild(settingText);\n settingsContiner.appendChild(noneDivContainer);\n settingsContiner.appendChild(boxDivContainer);\n settingsContiner.appendChild(allDivContainer);\n settingsContiner.appendChild(customDivContainer);\n this.previewDivBottomcenter.appendChild(this.previewDivBottomcenterTransparent);\n this.previewDivBottomRight.appendChild(this.previewDivBottomRightTransparent);\n this.previewDivBottomLeft.appendChild(this.previewDivBottomLeftTransparent);\n this.previewDivTopTop.appendChild(this.previewDivTopTopTransParent);\n this.previewDivTopCenter.appendChild(this.previewDivTopCenterTransParent);\n this.previewDivTopBottom.appendChild(this.previewDivTopBottomTransParent);\n this.previewDivDiagonalRight.appendChild(this.previewDivDiagonalRightTransparent);\n this.previewDivLeftDiagonal.appendChild(this.previewDivLeftDiagonalTransParent);\n this.previewDivBottomcenterContainer.appendChild(this.previewDivBottomcenter);\n this.previewDivBottomLeftContainer.appendChild(this.previewDivBottomLeft);\n this.previewDivBottomRightContainer.appendChild(this.previewDivBottomRight);\n this.previewDivDiagonalRightContainer.appendChild(this.previewDivDiagonalRight);\n this.previewDivLeftDiagonalContainer.appendChild(this.previewDivLeftDiagonal);\n this.previewDivTopBottomContainer.appendChild(this.previewDivTopBottom);\n this.previewDivTopCenterContainer.appendChild(this.previewDivTopCenter);\n this.previewDivTopTopContainer.appendChild(this.previewDivTopTop);\n previewContiner.appendChild(previewText);\n previewContiner.appendChild(this.previewDiv);\n previewContiner.appendChild(this.previewRightDiagonalDiv);\n previewContiner.appendChild(this.previewHorizontalDiv);\n previewContiner.appendChild(this.previewLeftDiagonalDiv);\n previewContiner.appendChild(this.previewVerticalDiv);\n previewContiner.appendChild(this.previewDivBottomcenterContainer);\n previewContiner.appendChild(this.previewDivBottomLeftContainer);\n previewContiner.appendChild(this.previewDivBottomRightContainer);\n previewContiner.appendChild(this.previewDivDiagonalRightContainer);\n previewContiner.appendChild(this.previewDivLeftDiagonalContainer);\n previewContiner.appendChild(this.previewDivTopBottomContainer);\n previewContiner.appendChild(this.previewDivTopCenterContainer);\n previewContiner.appendChild(this.previewDivTopTopContainer);\n shdApply.appendChild(div);\n shdApply.appendChild(divsion);\n shadings.appendChild(label);\n shadings.appendChild(shadingColorPickerElement);\n shadings.appendChild(shdApply);\n this.shadingContiner.appendChild(shadingText);\n this.shadingContiner.appendChild(shadings);\n styleContainer.appendChild(styleText);\n styleContainer.appendChild(dropDownList);\n styleContainer.appendChild(widthText);\n styleContainer.appendChild(widthNumeric);\n styleContainer.appendChild(colorText);\n styleContainer.appendChild(borderColorPickerElement);\n this.target.appendChild(displayText);\n this.target.appendChild(settingsContiner);\n this.target.appendChild(styleContainer);\n this.target.appendChild(previewContiner);\n this.target.appendChild(this.shadingContiner);\n // Handling Setting Container\n noneDivContainer.addEventListener('click', this.handleSettingCheckBoxAction);\n boxDivContainer.addEventListener('click', this.handleSettingCheckBoxAction);\n allDivContainer.addEventListener('click', this.handleSettingCheckBoxAction);\n customDivContainer.addEventListener('click', this.handleSettingCheckBoxAction);\n // Handling Preview Div Container\n this.previewDivBottomcenterContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n this.previewDivBottomLeftContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n this.previewDivBottomRightContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n this.previewDivTopTopContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n this.previewDivTopBottomContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n this.previewDivTopCenterContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n this.previewDivDiagonalRightContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n this.previewDivLeftDiagonalContainer.addEventListener('click', this.handlePreviewCheckBoxAction);\n // handling dropdown change\n this.borderWidth = new NumericTextBox({\n value: 0, min: 0, max: 6, decimals: 2,\n width: 150, enablePersistence: false\n });\n this.borderWidth.appendTo(widthNumeric);\n this.borderStyle = new DropDownList({\n width: '150px', popupHeight: '150px', index: 1\n });\n this.borderStyle.appendTo(dropDownList);\n this.ulelementShading = new DropDownList({\n width: '150px', change: this.applyTableCellPreviewBoxes, index: 1\n });\n this.ulelementShading.appendTo(ulelementShading);\n this.borderColorPicker = new ColorPicker({\n value: '#000000', change: this.applyPreviewTableBorderColor\n });\n this.borderColorPicker.appendTo(borderColorPickerElement);\n this.shadingColorPicker = new ColorPicker({\n value: '#000000', change: this.applyPreviewTableBackgroundColor\n });\n this.shadingColorPicker.appendTo(shadingColorPickerElement);\n };\n BordersAndShadingDialog.prototype.applyFormat = function () {\n var selection = this.owner.selection;\n var editorModule = this.owner.owner.editorModule;\n editorModule.initComplexHistory('BordersAndShading');\n editorModule.isBordersAndShadingDialog = true;\n if (this.applyTo === 0) {\n editorModule.onCellFormat(this.cellFormat);\n }\n else {\n editorModule.onTableFormat(this.tableFormat);\n }\n if (!isNullOrUndefined(this.owner.owner.editorHistory.currentHistoryInfo)) {\n this.owner.owner.editorHistory.updateComplexHistory();\n }\n editorModule.isBordersAndShadingDialog = false;\n };\n BordersAndShadingDialog.prototype.getBorder = function () {\n var border = new WBorder();\n border.color = this.borderColorPicker.value;\n border.lineStyle = this.borderStyle.text;\n border.lineWidth = this.borderWidth.value;\n return border;\n };\n BordersAndShadingDialog.prototype.checkClassName = function (element) {\n return element.classList.contains('e-de-table-border-inside-preview-click');\n };\n /**\n * @private\n */\n BordersAndShadingDialog.prototype.show = function () {\n var localeValue = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localeValue.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initBordersAndShadingsDialog(localeValue);\n }\n this.loadBordersShadingsPropertiesDialog();\n this.owner.dialog.content = this.target;\n this.owner.dialog.header = localeValue.getConstant('Borders and Shading');\n this.owner.dialog.beforeOpen = this.owner.updateFocus;\n this.owner.dialog.close = this.closeBordersShadingsDialog;\n this.owner.dialog.position = { X: 'center', Y: 'top' };\n this.owner.dialog.width = 'auto';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.buttons = [{\n click: this.applyBordersShadingsProperties,\n buttonModel: { content: localeValue.getConstant('Ok'), cssClass: 'e-flat e-table-border-shading-okay', isPrimary: true }\n },\n {\n click: this.closeDialog,\n buttonModel: { content: localeValue.getConstant('Cancel'), cssClass: 'e-flat e-table-border-shading-cancel' }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n BordersAndShadingDialog.prototype.updateClassForSettingDivElements = function () {\n var settingDivs = this.target.getElementsByClassName('e-de-table-border-inside-setting');\n for (var j = 0; j < settingDivs.length; j++) {\n if (settingDivs[j].className.indexOf('e-de-table-border-inside-setting-click') !== -1) {\n var tempClassName = settingDivs[j].className;\n tempClassName = tempClassName.replace('e-de-table-border-inside-setting-click', '');\n settingDivs[j].className = tempClassName;\n }\n }\n };\n BordersAndShadingDialog.prototype.setSettingPreviewDivElement = function (position) {\n switch (position) {\n case 'none':\n this.previewDivTopTop.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivTopCenter.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivTopBottom.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivLeftDiagonal.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivDiagonalRight.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivBottomRight.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivBottomLeft.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivBottomcenter.classList.remove('e-de-table-border-inside-preview-click');\n this.isShowHidePreviewTableElements('none');\n break;\n case 'box':\n this.previewDivTopCenter.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivLeftDiagonal.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivDiagonalRight.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivBottomcenter.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivTopTop.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivTopBottom.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivBottomRight.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivBottomLeft.classList.add('e-de-table-border-inside-preview-click');\n this.isShowHidePreviewTableElements('box');\n break;\n case 'all':\n this.previewDivLeftDiagonal.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivDiagonalRight.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivBottomcenter.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivTopTop.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivTopBottom.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivBottomRight.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivBottomLeft.classList.add('e-de-table-border-inside-preview-click');\n this.previewDivTopCenter.classList.add('e-de-table-border-inside-preview-click');\n this.isShowHidePreviewTableElements('all');\n break;\n }\n };\n BordersAndShadingDialog.prototype.isShowHidePreviewTableElements = function (settingDiv) {\n switch (settingDiv) {\n case 'none':\n this.previewDiv.style.border = 'none';\n this.previewRightDiagonalDiv.style.display = 'none';\n this.previewLeftDiagonalDiv.style.display = 'none';\n this.previewHorizontalDiv.style.display = 'none';\n this.previewVerticalDiv.style.display = 'none';\n break;\n case 'box':\n this.previewDiv.style.border = '1px solid rgba(0, 0, 0, .54)';\n this.previewRightDiagonalDiv.style.display = 'none';\n this.previewLeftDiagonalDiv.style.display = 'none';\n this.previewHorizontalDiv.style.display = 'none';\n this.previewVerticalDiv.style.display = 'none';\n break;\n case 'all':\n this.previewDiv.style.border = '1px solid rgba(0, 0, 0, .54)';\n this.previewRightDiagonalDiv.style.display = 'none';\n this.previewLeftDiagonalDiv.style.display = 'none';\n this.previewHorizontalDiv.style.display = 'block';\n this.previewVerticalDiv.style.display = 'block';\n break;\n }\n };\n BordersAndShadingDialog.prototype.handlePreviewCheckBoxShowHide = function (tableBorderDialogId, compareClass, element) {\n if (element.classList.contains(compareClass)) {\n element.classList.remove(compareClass);\n }\n else {\n element.classList.add(compareClass);\n }\n };\n // tslint:disable-next-line:max-line-length\n BordersAndShadingDialog.prototype.showHidePreviewDivElements = function (tableBorderDialogId, compareClass, elementClass, compareElementClass, position) {\n var setElement = document.getElementById(tableBorderDialogId + elementClass);\n var compareElement = document.getElementById(tableBorderDialogId + compareElementClass);\n if (position === 'TopTop') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'border-top');\n }\n else if (position === 'TopCenter') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'display');\n }\n else if (position === 'TopBottom') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'border-bottom');\n }\n else if (position === 'LeftDiagonal') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'display');\n }\n else if (position === 'BottomLeft') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'border-left');\n }\n else if (position === 'BottomCenter') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'display');\n }\n else if (position === 'BottomRight') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'border-right');\n }\n else if (position === 'RightDiagonal') {\n this.setPropertyPreviewDivElement(setElement, compareElement, compareClass, 'display');\n }\n };\n BordersAndShadingDialog.prototype.setPropertyPreviewDivElement = function (ele, compareElement, compareClass, property) {\n if (compareElement.classList.contains(compareClass) && property.split('-')[0] === 'border') {\n /* tslint:disable:no-any */\n ele.style[property] = '1px solid rgba(0, 0, 0, .54)';\n }\n else if (compareElement.classList.contains(compareClass) && property === 'display') {\n ele.style[property] = 'block';\n }\n else {\n ele.style[property] = 'none';\n /* tslint:enable:no-any */\n }\n };\n BordersAndShadingDialog.prototype.loadBordersShadingsPropertiesDialog = function () {\n var tableFormat = this.owner.selection.tableFormat.table.tableFormat;\n var lineStyle;\n var borderColor;\n var fillColor;\n var borderWidth;\n if (!isNullOrUndefined(tableFormat) && !isNullOrUndefined(tableFormat.borders)) {\n this.cloneBorders(tableFormat.borders);\n if (isNullOrUndefined(tableFormat.borders) || isNullOrUndefined(tableFormat.borders.top)) {\n lineStyle = 1;\n borderColor = '#000000';\n borderWidth = 0;\n fillColor = '#000000';\n }\n else {\n lineStyle = this.getLineStyle(tableFormat.borders.top.lineStyle);\n borderColor = tableFormat.borders.top.color;\n borderWidth = tableFormat.borders.top.getLineWidth();\n fillColor = tableFormat.shading.backgroundColor;\n }\n }\n this.borderColorPicker.value = borderColor;\n this.shadingColorPicker.value = fillColor;\n /* tslint:disable:no-any */\n var colorPickerEvent = {\n target: this.borderColorPicker, ctrlKey: false,\n shiftKey: false, which: 0\n };\n var fillColorEvent = {\n target: this.shadingColorPicker, ctrlKey: false,\n shiftKey: false, which: 0\n };\n /* tslint:enable:no-any */\n this.applyPreviewTableBackgroundColor(fillColorEvent);\n this.applyPreviewTableBorderColor(colorPickerEvent);\n this.ulelementShading.index = 1;\n this.previewDivLeftDiagonal.style.display = 'none';\n this.previewDivDiagonalRight.style.display = 'none';\n this.borderWidth.value = borderWidth;\n this.borderStyle.index = lineStyle;\n };\n // tslint:disable:max-func-body-length\n BordersAndShadingDialog.prototype.cloneBorders = function (borders) {\n var topBorder = false;\n var bottomBorder = false;\n var leftBorder = false;\n var rightBorder = false;\n var horizontalBorder = false;\n var verticalBorder = false;\n var diagonalDownBorder = false;\n var customBorder = false;\n var diagonalUpBorder = false;\n if (borders !== null) {\n if (borders.top && (borders.top.hasNoneStyle || borders.top.lineStyle !== 'None')) {\n topBorder = true;\n }\n if (borders.bottom && (borders.bottom.hasNoneStyle || borders.bottom.lineStyle !== 'None')) {\n bottomBorder = true;\n }\n if (borders.left && (borders.left.hasNoneStyle || borders.left.lineStyle !== 'None')) {\n leftBorder = true;\n }\n if (borders.right && (borders.right.hasNoneStyle || borders.right.lineStyle !== 'None')) {\n rightBorder = true;\n }\n if (borders.horizontal && (borders.horizontal.hasNoneStyle || borders.horizontal.lineStyle !== 'None')) {\n horizontalBorder = true;\n }\n if (borders.vertical && (borders.vertical.hasNoneStyle || borders.vertical.lineStyle !== 'None')) {\n verticalBorder = true;\n }\n if (borders.diagonalDown && (borders.diagonalDown.hasNoneStyle || borders.diagonalDown.lineStyle !== 'None')) {\n diagonalDownBorder = true;\n }\n if (borders.diagonalUp && (borders.diagonalUp.hasNoneStyle || borders.diagonalUp.lineStyle !== 'None')) {\n diagonalUpBorder = true;\n }\n if (!(!topBorder || !bottomBorder || !leftBorder || !rightBorder)) {\n if (!(!topBorder || !bottomBorder || !leftBorder || !rightBorder || !horizontalBorder\n || !verticalBorder || diagonalUpBorder || diagonalDownBorder)) {\n if ((topBorder && bottomBorder && leftBorder && rightBorder && horizontalBorder && verticalBorder\n && !diagonalUpBorder && !diagonalDownBorder)) {\n if (borders.top.hasNoneStyle && borders.bottom.hasNoneStyle && borders.left.hasNoneStyle\n && borders.right.hasNoneStyle && borders.horizontal.hasNoneStyle && borders.vertical.hasNoneStyle) {\n this.setSettingPreviewDivElement('none');\n this.customDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.noneDiv.classList.add('e-de-table-border-inside-setting-click');\n this.boxDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.allDiv.classList.remove('e-de-table-border-inside-setting-click');\n }\n else {\n this.setSettingPreviewDivElement('all');\n this.allDiv.classList.add('e-de-table-border-inside-setting-click');\n this.customDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.noneDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.boxDiv.classList.remove('e-de-table-border-inside-setting-click');\n }\n }\n }\n else if ((leftBorder && bottomBorder && topBorder && rightBorder && !horizontalBorder && !verticalBorder)) {\n if (borders.top.hasNoneStyle && borders.bottom.hasNoneStyle && borders.left.hasNoneStyle\n && borders.right.hasNoneStyle && borders.horizontal.hasNoneStyle && borders.vertical.hasNoneStyle) {\n this.setSettingPreviewDivElement('none');\n this.boxDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.allDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.customDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.noneDiv.classList.add('e-de-table-border-inside-setting-click');\n }\n else {\n this.setSettingPreviewDivElement('box');\n this.customDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.noneDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.boxDiv.classList.add('e-de-table-border-inside-setting-click');\n this.allDiv.classList.remove('e-de-table-border-inside-setting-click');\n }\n }\n else {\n customBorder = true;\n }\n }\n else {\n customBorder = true;\n }\n this.previewDivLeftDiagonal.classList.remove('e-de-table-border-inside-preview-click');\n this.previewDivDiagonalRight.classList.remove('e-de-table-border-inside-preview-click');\n if (customBorder) {\n this.customDiv.classList.add('e-de-table-border-inside-setting-click');\n this.noneDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.boxDiv.classList.remove('e-de-table-border-inside-setting-click');\n this.allDiv.classList.remove('e-de-table-border-inside-setting-click');\n if (topBorder) {\n this.previewDivTopTop.classList.add('e-de-table-border-inside-preview-click');\n }\n else {\n this.previewDivTopTop.classList.remove('e-de-table-border-inside-preview-click');\n }\n if (bottomBorder) {\n this.previewDivTopBottom.classList.add('e-de-table-border-inside-preview-click');\n }\n else {\n this.previewDivTopBottom.classList.remove('e-de-table-border-inside-preview-click');\n }\n if (leftBorder) {\n this.previewDivBottomLeft.classList.add('e-de-table-border-inside-preview-click');\n }\n else {\n this.previewDivBottomLeft.classList.remove('e-de-table-border-inside-preview-click');\n }\n if (rightBorder) {\n this.previewDivBottomRight.classList.add('e-de-table-border-inside-preview-click');\n }\n else {\n this.previewDivBottomRight.classList.remove('e-de-table-border-inside-preview-click');\n }\n if (verticalBorder) {\n this.previewDivBottomcenter.classList.add('e-de-table-border-inside-preview-click');\n }\n else {\n this.previewDivBottomcenter.classList.remove('e-de-table-border-inside-preview-click');\n }\n if (horizontalBorder) {\n this.previewDivTopCenter.classList.add('e-de-table-border-inside-preview-click');\n }\n else {\n this.previewDivTopCenter.classList.remove('e-de-table-border-inside-preview-click');\n }\n }\n }\n };\n BordersAndShadingDialog.prototype.getLineStyle = function (lineStyle) {\n switch (lineStyle) {\n case 'Single': return 1;\n case 'Dot': return 2;\n case 'DashSmallGap': return 3;\n case 'DashLargeGap': return 4;\n case 'DashDot': return 5;\n case 'DashDotDot': return 6;\n case 'Double': return 7;\n case 'Triple': return 8;\n case 'ThinThickSmallGap': return 9;\n case 'ThickThinSmallGap': return 10;\n case 'ThinThickThinSmallGap': return 11;\n case 'ThinThickMediumGap': return 12;\n case 'ThickThinMediumGap': return 13;\n case 'ThinThickThinMediumGap': return 14;\n case 'ThinThickLargeGap': return 15;\n case 'ThickThinLargeGap': return 16;\n case 'ThinThickThinLargeGap': return 17;\n case 'SingleWavy': return 18;\n case 'DoubleWavy': return 19;\n case 'DashDotStroked': return 20;\n case 'Emboss3D': return 21;\n case 'Engrave3D': return 22;\n case 'Outset': return 23;\n case 'Inset': return 24;\n case 'Thick': return 25;\n }\n return 0;\n };\n /**\n * @private\n */\n BordersAndShadingDialog.prototype.destroy = function () {\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var k = 0; k < this.target.childNodes.length; k++) {\n this.target.removeChild(this.target.childNodes[k]);\n k--;\n }\n this.target = undefined;\n }\n if (this.cellFormat) {\n this.cellFormat.destroy();\n this.cellFormat = undefined;\n }\n if (this.tableFormat) {\n this.tableFormat.destroy();\n this.tableFormat = undefined;\n }\n this.dialog = undefined;\n this.target = undefined;\n if (!isNullOrUndefined(this.borderStyle)) {\n this.borderStyle.destroy();\n }\n this.borderStyle = undefined;\n if (!isNullOrUndefined(this.borderColorPicker)) {\n this.borderColorPicker.destroy();\n }\n this.borderColorPicker = undefined;\n if (!isNullOrUndefined(this.shadingColorPicker)) {\n this.shadingColorPicker.destroy();\n }\n this.shadingColorPicker = undefined;\n if (!isNullOrUndefined(this.ulelementShading)) {\n this.ulelementShading.destroy();\n }\n this.ulelementShading = undefined;\n this.noneDivTransparent = undefined;\n this.boxDivTransparent = undefined;\n this.allDivTransparent = undefined;\n this.customDivTransparent = undefined;\n this.previewDiv = undefined;\n this.previewRightDiagonalDiv = undefined;\n this.previewLeftDiagonalDiv = undefined;\n this.previewVerticalDiv = undefined;\n this.previewHorizontalDiv = undefined;\n this.previewDivTopTopContainer = undefined;\n this.previewDivTopTop = undefined;\n this.previewDivTopCenterContainer = undefined;\n this.previewDivTopCenter = undefined;\n this.previewDivTopBottomContainer = undefined;\n this.previewDivTopBottom = undefined;\n this.previewDivLeftDiagonalContainer = undefined;\n this.previewDivLeftDiagonal = undefined;\n this.previewDivBottomLeftContainer = undefined;\n this.previewDivBottomLeft = undefined;\n this.previewDivBottomcenterContainer = undefined;\n this.previewDivBottomcenter = undefined;\n this.previewDivBottomRightContainer = undefined;\n this.previewDivBottomRight = undefined;\n this.previewDivDiagonalRightContainer = undefined;\n this.previewDivDiagonalRight = undefined;\n this.previewDivTopTopTransParent = undefined;\n this.previewDivTopCenterTransParent = undefined;\n this.previewDivTopBottomTransParent = undefined;\n this.previewDivLeftDiagonalTransParent = undefined;\n this.previewDivBottomLeftTransparent = undefined;\n this.previewDivBottomcenterTransparent = undefined;\n this.previewDivBottomRightTransparent = undefined;\n this.previewDivDiagonalRightTransparent = undefined;\n this.shadingContiner = undefined;\n this.noneDiv = undefined;\n this.customDiv = undefined;\n this.allDiv = undefined;\n this.boxDiv = undefined;\n };\n return BordersAndShadingDialog;\n}());\nexport { BordersAndShadingDialog };\n","import { CheckBox } from '@syncfusion/ej2-buttons';\nimport { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { WTableFormat } from '../index';\nimport { isNullOrUndefined, L10n, createElement, setCulture } from '@syncfusion/ej2-base';\nimport { CellOptionsDialog } from './index';\n/**\n * The Table options dialog is used to modify default cell margins and cell spacing of selected table.\n */\nvar TableOptionsDialog = /** @class */ (function () {\n /**\n * @private\n */\n function TableOptionsDialog(viewer) {\n var _this = this;\n /**\n * @private\n */\n this.applyTableCellProperties = function () {\n var tableFormat = _this.owner.selection.tableFormat;\n if (!isNullOrUndefined(_this.bottomMarginBox.value || _this.leftMarginBox.value\n || _this.rightMarginBox.value || _this.topMarginBox.value || _this.cellSpaceTextBox.value)\n && (tableFormat.bottomMargin !== _this.bottomMarginBox.value\n || tableFormat.leftMargin !== _this.leftMarginBox.value\n || tableFormat.rightMargin !== _this.rightMarginBox.value\n || tableFormat.topMargin !== _this.topMarginBox.value\n || tableFormat.cellSpacing !== _this.cellSpaceTextBox.value)) {\n _this.owner.owner.tablePropertiesDialogModule.isTableOptionsUpdated = true;\n _this.applyTableOptions(_this.tableFormat);\n _this.owner.owner.tablePropertiesDialogModule.applyTableSubProperties();\n }\n _this.closeCellMarginsDialog();\n };\n /**\n * @private\n */\n this.closeCellMarginsDialog = function () {\n _this.owner.dialog.hide();\n _this.owner.dialog.element.style.pointerEvents = '';\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.changeAllowSpaceCheckBox = function () {\n if (_this.allowSpaceCheckBox.checked) {\n _this.cellSpaceTextBox.enabled = true;\n }\n else {\n _this.cellSpaceTextBox.enabled = false;\n }\n };\n /**\n * @private\n */\n this.removeEvents = function () {\n _this.owner.dialog2.element.style.pointerEvents = '';\n _this.owner.updateFocus();\n };\n this.owner = viewer;\n }\n Object.defineProperty(TableOptionsDialog.prototype, \"tableFormat\", {\n /**\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.tableFormatIn)) {\n return this.tableFormatIn = new WTableFormat();\n }\n return this.tableFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n TableOptionsDialog.prototype.getModuleName = function () {\n return 'TableOptionsDialog';\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.initTableOptionsDialog = function (localValue) {\n var instance = this.owner;\n this.target = createElement('div', {\n id: this.owner.owner.containerId + '_insertCellMarginsDialog', className: 'e-de-table-options-dlg'\n });\n this.owner.owner.element.appendChild(this.target);\n var innerDiv = createElement('div', { styles: 'width: 475px;position: relative;height: 180px;' });\n var innerDivLabel = createElement('Label', {\n id: this.target.id + '_innerDivLabel', className: 'e-de-cell-dia-options-label',\n innerHTML: localValue.getConstant('Default cell margins')\n });\n innerDiv.appendChild(innerDivLabel);\n CellOptionsDialog.getCellMarginDialogElements(this, innerDiv, localValue);\n var div = createElement('div', { styles: 'width: 475px; position: relative;' });\n var cellSpaceLabel = createElement('Label', {\n className: 'e-de-cell-dia-options-label',\n id: this.target.id + '_cellSpaceLabel'\n });\n cellSpaceLabel.innerHTML = localValue.getConstant('Default cell spacing');\n div.appendChild(cellSpaceLabel);\n var table2 = createElement('TABLE', {\n styles: 'height: 30px;padding-bottom: 15px;'\n });\n var tr3 = createElement('tr');\n var td5 = createElement('td');\n var allowSpaceCheckBox = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_cellcheck'\n });\n var td6 = createElement('td', { styles: 'padding-left: 15px;', });\n this.cellspacingTextBox = createElement('input', {\n attrs: { 'type': 'text' }, id: this.target.id + '_cellspacing'\n });\n td5.appendChild(allowSpaceCheckBox);\n td6.appendChild(this.cellspacingTextBox);\n tr3.appendChild(td5);\n tr3.appendChild(td6);\n table2.appendChild(tr3);\n div.appendChild(table2);\n var divBtn = document.createElement('div');\n this.target.appendChild(div);\n this.target.appendChild(divBtn);\n this.cellSpaceTextBox = new NumericTextBox({\n value: 0, min: 0, max: 264.5, width: 150,\n decimals: 2, enablePersistence: false\n });\n this.cellSpaceTextBox.appendTo(this.cellspacingTextBox);\n this.allowSpaceCheckBox = new CheckBox({\n label: localValue.getConstant('Allow spacing between cells'),\n change: this.changeAllowSpaceCheckBox,\n cssClass: 'e-de-tbl-margin-sub-header',\n });\n this.allowSpaceCheckBox.appendTo(allowSpaceCheckBox);\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.loadCellMarginsDialog = function () {\n var tableFormat = this.owner.selection.tableFormat;\n this.cellSpaceTextBox.value = tableFormat.cellSpacing;\n this.bottomMarginBox.value = tableFormat.bottomMargin;\n this.topMarginBox.value = tableFormat.topMargin;\n this.rightMarginBox.value = tableFormat.rightMargin;\n this.leftMarginBox.value = tableFormat.leftMargin;\n if (tableFormat.cellSpacing > 0) {\n this.allowSpaceCheckBox.checked = true;\n this.cellSpaceTextBox.enabled = true;\n }\n else {\n this.allowSpaceCheckBox.checked = false;\n this.cellSpaceTextBox.enabled = false;\n }\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.applySubTableOptions = function (tableFormat) {\n this.owner.owner.editorHistory.initComplexHistory(this.owner.selection, 'TableMarginsSelection');\n this.applyTableOptionsHistory(tableFormat);\n if (!isNullOrUndefined(this.owner.owner.editorHistory.currentHistoryInfo)) {\n this.owner.owner.editorHistory.updateComplexHistory();\n }\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.applyTableOptionsHelper = function (tableFormat) {\n this.applySubTableOptionsHelper(tableFormat);\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.applyTableOptionsHistory = function (tableFormat) {\n this.owner.owner.editorModule.initHistory('TableOptions');\n this.applySubTableOptionsHelper(tableFormat);\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.applySubTableOptionsHelper = function (tableFormat) {\n var ownerTable = this.owner.selection.start.currentWidget.paragraph.associatedCell.ownerTable;\n ownerTable = ownerTable.combineWidget(this.owner);\n var currentTableFormat = ownerTable.tableFormat;\n if (!isNullOrUndefined(this.owner.owner.editorHistory.currentBaseHistoryInfo)) {\n this.owner.owner.editorHistory.currentBaseHistoryInfo.addModifiedTableOptions(currentTableFormat);\n }\n currentTableFormat.cellSpacing = tableFormat.cellSpacing;\n currentTableFormat.leftMargin = tableFormat.leftMargin;\n currentTableFormat.topMargin = tableFormat.topMargin;\n currentTableFormat.rightMargin = tableFormat.rightMargin;\n currentTableFormat.bottomMargin = tableFormat.bottomMargin;\n this.owner.owner.tablePropertiesDialogModule.calculateGridValue(ownerTable);\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.applyTableOptions = function (tableFormat) {\n tableFormat.leftMargin = this.leftMarginBox.value;\n tableFormat.topMargin = this.topMarginBox.value;\n tableFormat.bottomMargin = this.bottomMarginBox.value;\n tableFormat.rightMargin = this.rightMarginBox.value;\n if (this.allowSpaceCheckBox.checked) {\n tableFormat.cellSpacing = this.cellSpaceTextBox.value;\n }\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.show = function () {\n var documentLocale = new L10n('documenteditor', this.owner.owner.defaultLocale);\n documentLocale.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initTableOptionsDialog(documentLocale);\n }\n this.loadCellMarginsDialog();\n this.owner.dialog.header = documentLocale.getConstant('Table Options');\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = undefined;\n this.owner.dialog.position = { X: 'center', Y: 'top' };\n // this.owner.dialog.cssClass = 'e-de-table-margin-size';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.width = 'auto';\n this.owner.dialog.open = undefined;\n this.owner.dialog.beforeOpen = this.owner.updateFocus;\n this.owner.dialog.close = this.removeEvents;\n this.owner.dialog.buttons = [{\n click: this.applyTableCellProperties,\n buttonModel: { content: documentLocale.getConstant('Ok'), cssClass: 'e-flat e-table-cell-okay', isPrimary: true }\n },\n {\n click: this.closeCellMarginsDialog,\n buttonModel: { content: documentLocale.getConstant('Cancel'), cssClass: 'e-flat e-table-cell-cancel' }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n /**\n * @private\n */\n TableOptionsDialog.prototype.destroy = function () {\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var p = 0; p < this.target.childNodes.length; p++) {\n this.target.removeChild(this.target.childNodes[p]);\n p--;\n }\n this.target = undefined;\n }\n this.dialog = undefined;\n this.target = undefined;\n this.owner = undefined;\n this.cellspacingTextBox = undefined;\n this.allowSpaceCheckBox = undefined;\n };\n return TableOptionsDialog;\n}());\nexport { TableOptionsDialog };\n","import { CheckBox } from '@syncfusion/ej2-buttons';\nimport { NumericTextBox } from '@syncfusion/ej2-inputs';\nimport { WCellFormat } from '../index';\nimport { isNullOrUndefined, L10n, createElement, setCulture } from '@syncfusion/ej2-base';\n/**\n * The Cell options dialog is used to modify margins of selected cells.\n */\nvar CellOptionsDialog = /** @class */ (function () {\n /**\n * @private\n */\n function CellOptionsDialog(viewer) {\n var _this = this;\n /**\n * @private\n */\n this.removeEvents = function () {\n _this.owner.dialog2.element.style.pointerEvents = '';\n _this.owner.updateFocus();\n };\n /**\n * @private\n */\n this.changeSameAsTable = function () {\n if (_this.sameAsTableCheckBox.checked) {\n _this.leftMarginBox.enabled = false;\n _this.rightMarginBox.enabled = false;\n _this.bottomMarginBox.enabled = false;\n _this.topMarginBox.enabled = false;\n }\n else {\n _this.leftMarginBox.enabled = true;\n _this.rightMarginBox.enabled = true;\n _this.bottomMarginBox.enabled = true;\n _this.topMarginBox.enabled = true;\n }\n };\n /**\n * @private\n */\n this.applyTableCellProperties = function () {\n var cellFormat = _this.owner.selection.cellFormat;\n if (!isNullOrUndefined(_this.bottomMarginBox.value || _this.leftMarginBox.value\n || _this.rightMarginBox.value || _this.topMarginBox.value) &&\n (cellFormat.bottomMargin !== _this.bottomMarginBox.value || cellFormat.leftMargin !== _this.leftMarginBox.value\n || cellFormat.rightMargin !== _this.rightMarginBox.value || cellFormat.topMargin !== _this.topMarginBox.value)) {\n _this.owner.owner.tablePropertiesDialogModule.isCellOptionsUpdated = true;\n _this.applyTableOptions(_this.cellFormat);\n _this.owner.owner.tablePropertiesDialogModule.applyTableSubProperties();\n }\n _this.closeCellMarginsDialog();\n };\n /**\n * @private\n */\n this.closeCellMarginsDialog = function () {\n _this.owner.dialog.hide();\n _this.owner.dialog.element.style.pointerEvents = '';\n };\n this.owner = viewer;\n }\n Object.defineProperty(CellOptionsDialog.prototype, \"cellFormat\", {\n /**\n * @private\n */\n get: function () {\n if (isNullOrUndefined(this.cellFormatIn)) {\n return this.cellFormatIn = new WCellFormat();\n }\n return this.cellFormatIn;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @private\n */\n CellOptionsDialog.prototype.getModuleName = function () {\n return 'CellOptionsDialog';\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.initCellMarginsDialog = function (localValue) {\n var instance = this.owner;\n this.target = createElement('div', {\n id: this.owner.owner.containerId + '_tableCellMarginsDialog', className: 'e-de-table-cell-margin-dlg'\n });\n this.owner.owner.element.appendChild(this.target);\n var innerDiv = createElement('div', { styles: 'width: 475px;position: relative;height: 165px;' });\n var innerDivLabel = createElement('Label', {\n className: 'e-de-cell-dia-options-label', id: this.target.id + '_innerDivLabel'\n });\n innerDivLabel.innerHTML = localValue.getConstant('Cell margins');\n innerDiv.appendChild(innerDivLabel);\n var table = createElement('TABLE', {\n styles: 'height: 40px;padding-bottom: 0px;', className: 'e-de-cell-margin-top'\n });\n var tr = createElement('tr');\n var td = createElement('td', { className: 'e-de-tbl-btn-seperator' });\n var sameAsTableCheckBox = createElement('input', {\n attrs: { 'type': 'checkbox' }, id: this.target.id + '_sameAsCheckBox'\n });\n td.appendChild(sameAsTableCheckBox);\n tr.appendChild(td);\n table.appendChild(tr);\n innerDiv.appendChild(table);\n CellOptionsDialog.getCellMarginDialogElements(this, innerDiv, localValue);\n var divBtn = document.createElement('div');\n this.target.appendChild(divBtn);\n this.sameAsTableCheckBox = new CheckBox({\n label: localValue.getConstant('Same as the whole table'),\n change: this.changeSameAsTable\n });\n this.sameAsTableCheckBox.appendTo(sameAsTableCheckBox);\n this.sameAsTableCheckBox.addEventListener('change', this.changeSameAsTable);\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.show = function () {\n var localizeValue = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localizeValue.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n if (!this.target) {\n this.initCellMarginsDialog(localizeValue);\n }\n this.loadCellMarginsDialog();\n this.owner.dialog.header = localizeValue.getConstant('Cell Options');\n this.owner.dialog.position = { X: 'center', Y: 'top' };\n this.owner.dialog.height = 'auto';\n this.owner.dialog.width = 'auto';\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = undefined;\n this.owner.dialog.open = undefined;\n this.owner.dialog.close = this.removeEvents;\n this.owner.dialog.buttons = [{\n click: this.applyTableCellProperties,\n buttonModel: { content: localizeValue.getConstant('Ok'), cssClass: 'e-flat e-table-cell-margin-okay', isPrimary: true }\n },\n {\n click: this.closeCellMarginsDialog,\n buttonModel: { content: localizeValue.getConstant('Cancel'), cssClass: 'e-flat e-table-cell-margin-cancel' }\n }];\n this.owner.dialog.show();\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.loadCellMarginsDialog = function () {\n var cellFormat = this.owner.selection.cellFormat;\n this.sameAsTable = isNullOrUndefined(cellFormat.leftMargin || cellFormat.topMargin\n || cellFormat.rightMargin || cellFormat.bottomMargin);\n if (this.sameAsTable) {\n var tableFormat = this.owner.selection.tableFormat;\n this.loadCellProperties(tableFormat, false, true);\n }\n else {\n this.loadCellProperties(cellFormat, true, false);\n }\n };\n CellOptionsDialog.prototype.loadCellProperties = function (format, enableTextBox, enableCheckBox) {\n this.leftMarginBox.value = format.leftMargin;\n this.rightMarginBox.value = format.rightMargin;\n this.topMarginBox.value = format.topMargin;\n this.bottomMarginBox.value = format.bottomMargin;\n this.leftMarginBox.enabled = enableTextBox;\n this.rightMarginBox.enabled = enableTextBox;\n this.topMarginBox.enabled = enableTextBox;\n this.bottomMarginBox.enabled = enableTextBox;\n this.sameAsTableCheckBox.checked = enableCheckBox;\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.applySubCellOptions = function (cellFormat) {\n this.owner.owner.editorHistory.initComplexHistory(this.owner.selection, 'CellMarginsSelection');\n this.owner.owner.editorModule.initHistory('CellOptions');\n /* tslint:disable:max-line-length */\n var startTable = this.owner.selection.start.paragraph.associatedCell.ownerTable;\n startTable = startTable.combineWidget(this.owner);\n this.applyCellmarginsValue(this.owner.selection.start.paragraph.associatedCell.ownerRow.combineWidget(this.owner), this.owner.selection.start, this.owner.selection.end, cellFormat);\n this.owner.owner.editorModule.reLayout(this.owner.selection, false);\n if (!isNullOrUndefined(this.owner.owner.editorHistory.currentHistoryInfo)) {\n this.owner.owner.editorHistory.updateComplexHistory();\n }\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.applyCellmarginsValue = function (row, start, end, cellFormat) {\n this.applyCellMarginsInternal(row, cellFormat);\n if (end.paragraph.associatedCell.ownerRow === row) {\n return;\n }\n var newRow = row.nextWidget;\n if (!isNullOrUndefined(newRow)) {\n this.applyCellmarginsValue(newRow, start, end, cellFormat);\n }\n };\n CellOptionsDialog.prototype.applyCellMarginsInternal = function (row, cellFormat) {\n if (!isNullOrUndefined(this.owner.owner.editorHistory.currentBaseHistoryInfo)) {\n var currentFormat = row.childWidgets[0].cellFormat;\n /* tslint:disable:max-line-length */\n cellFormat = this.owner.owner.editorHistory.currentBaseHistoryInfo.addModifiedCellOptions(currentFormat, cellFormat, row.ownerTable);\n }\n if (!isNullOrUndefined(cellFormat)) {\n this.applyCellMarginsForCells(row, cellFormat);\n }\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.applyCellMarginsForCells = function (row, cellFormat) {\n var rowCells = row.childWidgets;\n this.iterateCells(rowCells, cellFormat);\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.iterateCells = function (cells, cellFormat) {\n for (var i = 0; i < cells.length; i++) {\n this.applySubCellMargins(cells[i].cellFormat, cellFormat);\n }\n this.owner.owner.tablePropertiesDialogModule.calculateGridValue(cells[0].ownerTable);\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.applySubCellMargins = function (sourceFormat, cellFormat) {\n sourceFormat.leftMargin = cellFormat.leftMargin;\n sourceFormat.topMargin = cellFormat.topMargin;\n sourceFormat.rightMargin = cellFormat.rightMargin;\n sourceFormat.bottomMargin = cellFormat.bottomMargin;\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.applyTableOptions = function (cellFormat) {\n if (!this.sameAsTableCheckBox.checked) {\n cellFormat.leftMargin = this.leftMarginBox.value;\n cellFormat.topMargin = this.topMarginBox.value;\n cellFormat.bottomMargin = this.bottomMarginBox.value;\n cellFormat.rightMargin = this.rightMarginBox.value;\n }\n };\n /**\n * @private\n */\n CellOptionsDialog.prototype.destroy = function () {\n if (!isNullOrUndefined(this.target)) {\n if (this.target.parentElement) {\n this.target.parentElement.removeChild(this.target);\n }\n for (var y = 0; y < this.target.childNodes.length; y++) {\n this.target.removeChild(this.target.childNodes[y]);\n y--;\n }\n this.target = undefined;\n }\n this.dialog = undefined;\n this.target = undefined;\n this.owner = undefined;\n this.sameAsTableCheckBox = undefined;\n };\n /**\n * @private\n */\n CellOptionsDialog.getCellMarginDialogElements = function (dialog, div, locale) {\n if (!isNullOrUndefined(dialog)) {\n var table = createElement('TABLE', { className: 'e-de-cell-margin-top' });\n var tr1 = createElement('tr', { styles: 'height: 50px;color:black;' });\n var td1 = createElement('td');\n var topLabel = createElement('label', {\n innerHTML: locale.getConstant('Top'), className: 'e-de-cell-dia-label-common',\n id: dialog.target.id + '_TopLabel'\n });\n var topTextBox = createElement('input', {\n attrs: { 'type': 'text' }, styles: 'width:100%', id: dialog.target.id + '_Top'\n });\n td1.appendChild(topLabel);\n td1.appendChild(topTextBox);\n var td2 = createElement('td', { className: 'e-de-tbl-btn-seperator' });\n var leftLabel = createElement('label', {\n innerHTML: locale.getConstant('Left'), className: 'e-de-cell-dia-label-common',\n id: dialog.target.id + '_leftLabel'\n });\n var leftTextBox = createElement('input', {\n attrs: { 'type': 'text' },\n styles: 'width:100%', id: dialog.target.id + '_left'\n });\n td2.appendChild(leftLabel);\n td2.appendChild(leftTextBox);\n tr1.appendChild(td1);\n tr1.appendChild(td2);\n var tr2 = createElement('tr', { styles: 'height: 50px;color:black;' });\n var td3 = createElement('td', { styles: 'width:40%;' });\n var bottomLabel = createElement('label', {\n innerHTML: locale.getConstant('Bottom'),\n className: 'e-de-cell-dia-label-common', id: dialog.target.id + '_bottomLabel'\n });\n var bottomTextBox = createElement('input', {\n attrs: { 'type': 'text' },\n styles: 'width:100%', id: dialog.target.id + '_bottom'\n });\n td3.appendChild(bottomLabel);\n td3.appendChild(bottomTextBox);\n var td4 = createElement('td', { styles: 'width:40%;' });\n var rightLabel = createElement('label', {\n innerHTML: locale.getConstant('Right'), id: dialog.target.id + '_rightLabel',\n className: 'e-de-cell-dia-label-common'\n });\n var rightTextBox = createElement('input', {\n attrs: { 'type': 'text' },\n styles: 'width:100%', id: dialog.target.id + '_right'\n });\n td4.appendChild(rightLabel);\n td4.appendChild(rightTextBox);\n tr2.appendChild(td3);\n tr2.appendChild(td4);\n table.appendChild(tr1);\n table.appendChild(tr2);\n div.appendChild(table);\n dialog.target.appendChild(div);\n dialog.topMarginBox = new NumericTextBox({\n value: 0, min: 0, max: 1584, width: 150, decimals: 2,\n enablePersistence: false\n });\n dialog.topMarginBox.appendTo(topTextBox);\n dialog.leftMarginBox = new NumericTextBox({\n value: 0, min: 0, max: 1584, width: 150,\n decimals: 2, enablePersistence: false\n });\n dialog.leftMarginBox.appendTo(leftTextBox);\n dialog.bottomMarginBox = new NumericTextBox({\n value: 0, min: 0, max: 1584, width: 150, decimals: 2,\n enablePersistence: false\n });\n dialog.bottomMarginBox.appendTo(bottomTextBox);\n dialog.rightMarginBox = new NumericTextBox({\n value: 0, min: 0, max: 1584, width: 150,\n decimals: 2, enablePersistence: false\n });\n dialog.rightMarginBox.appendTo(rightTextBox);\n }\n };\n return CellOptionsDialog;\n}());\nexport { CellOptionsDialog };\n","import { ListView } from '@syncfusion/ej2-lists';\nimport { Button } from '@syncfusion/ej2-buttons';\nimport { createElement, L10n, setCulture } from '@syncfusion/ej2-base';\n/**\n * The Styles dialog is used to create or modify styles.\n */\nvar StylesDialog = /** @class */ (function () {\n /**\n * @private\n */\n function StylesDialog(viewer) {\n var _this = this;\n this.updateStyleNames = function () {\n var collection = _this.owner.owner.viewer.styles.getStyleNames('Paragraph');\n var defaultStyleNames = ['Normal', 'Heading 1', 'Heading 2', 'Heading 3', 'Heading 4', 'Heading 5', 'Heading 6'];\n var finalList = collection.concat(defaultStyleNames).filter(function (v, i, a) { return a.indexOf(v) === i; });\n return finalList;\n };\n this.modifyStyles = function () {\n _this.owner.dialog.hide();\n _this.owner.owner.styleDialogModule.show(_this.styleName, _this.localValue.getConstant('Modify Style'));\n };\n /* tslint:disable:no-any */\n this.selectHandler = function (args) {\n _this.styleName = args.text;\n };\n this.addNewStyles = function () {\n _this.owner.dialog.hide();\n _this.owner.owner.styleDialogModule.show();\n };\n this.owner = viewer;\n }\n /**\n * @private\n */\n StylesDialog.prototype.getModuleName = function () {\n return 'StylesDialog';\n };\n /**\n * @private\n */\n StylesDialog.prototype.initStylesDialog = function (localValue, styles) {\n var instance = this;\n var id = this.owner.owner.containerId + '_insert_styles';\n this.target = createElement('div', { id: id, className: 'e-de-styles' });\n var headerValue = localValue.getConstant('Styles');\n var dlgFields = createElement('div', { innerHTML: headerValue, className: 'e-styles-dlgfields' });\n this.target.appendChild(dlgFields);\n var commonDiv = createElement('div', { className: 'e-styles-common' });\n this.target.appendChild(commonDiv);\n var searchDiv = createElement('div', { className: 'e-styles-list' });\n commonDiv.appendChild(searchDiv);\n var listviewDiv = createElement('div', { className: 'e-styles-listViewDiv', id: 'styles_listview' });\n searchDiv.appendChild(listviewDiv);\n this.listviewInstance = new ListView({\n dataSource: styles,\n cssClass: 'e-styles-listview',\n });\n this.listviewInstance.appendTo(listviewDiv);\n this.listviewInstance.addEventListener('select', this.selectHandler);\n var buttonDiv = createElement('div', { className: 'e-styles-button' });\n commonDiv.appendChild(buttonDiv);\n var newButtonDiv = createElement('div', { className: 'e-styles-addbutton' });\n buttonDiv.appendChild(newButtonDiv);\n var newButtonElement = createElement('button', { innerHTML: localValue.getConstant('New'), id: 'new' });\n newButtonDiv.appendChild(newButtonElement);\n var newbutton = new Button({ cssClass: 'e-button-custom' });\n newbutton.appendTo(newButtonElement);\n newButtonElement.addEventListener('click', this.addNewStyles);\n var modifybuttonDiv = createElement('div', { className: 'e-styles-addbutton' });\n buttonDiv.appendChild(modifybuttonDiv);\n var modifyButtonElement = createElement('button', { innerHTML: localValue.getConstant('Modify'), id: 'modify' });\n modifybuttonDiv.appendChild(modifyButtonElement);\n var addbutton = new Button({ cssClass: 'e-button-custom' });\n addbutton.appendTo(modifyButtonElement);\n modifyButtonElement.addEventListener('click', this.modifyStyles);\n };\n /**\n * @private\n */\n StylesDialog.prototype.show = function () {\n var styles = this.updateStyleNames();\n var localValue = new L10n('documenteditor', this.owner.owner.defaultLocale);\n localValue.setLocale(this.owner.owner.locale);\n setCulture(this.owner.owner.locale);\n this.localValue = localValue;\n this.initStylesDialog(localValue, styles);\n this.owner.dialog.content = this.target;\n this.owner.dialog.beforeOpen = this.owner.updateFocus;\n this.owner.dialog.close = this.owner.updateFocus;\n this.owner.dialog.header = 'Styles';\n this.owner.dialog.height = 'auto';\n this.owner.dialog.width = 'auto';\n this.owner.dialog.buttons = [{\n click: this.hideObjects.bind(this),\n buttonModel: { content: localValue.getConstant('Cancel'), cssClass: 'e-flat e-hyper-insert', isPrimary: true }\n }];\n this.owner.dialog.dataBind();\n this.owner.dialog.show();\n };\n StylesDialog.prototype.hideObjects = function () {\n this.owner.dialog.hide();\n };\n /**\n * @private\n */\n StylesDialog.prototype.destroy = function () {\n if (this.listviewInstance) {\n this.listviewInstance.destroy();\n this.listviewInstance = undefined;\n }\n };\n return StylesDialog;\n}());\nexport { StylesDialog };\n","import * as index from '@syncfusion/ej2-documenteditor';\nindex.DocumentEditor.Inject( index.Print,index.SfdtExport,index.WordExport,index.TextExport,index.Selection,index.Search,index.Editor,index.EditorHistory,index.OptionsPane,index.ContextMenu,index.ImageResizer,index.HyperlinkDialog,index.TableDialog,index.BookmarkDialog,index.TableOfContentsDialog,index.PageSetupDialog,index.ParagraphDialog,index.ListDialog,index.StyleDialog,index.StylesDialog,index.BulletsAndNumberingDialog,index.FontDialog,index.TablePropertiesDialog,index.BordersAndShadingDialog,index.TableOptionsDialog,index.CellOptionsDialog);\nexport * from '@syncfusion/ej2-documenteditor';\n","import * as index from '@syncfusion/ej2-dropdowns';\nindex.MultiSelect.Inject( index.CheckBoxSelection);\nexport * from '@syncfusion/ej2-dropdowns';\n","/**\n * Defines types of Cell\n * @hidden\n */\nexport var CellType;\n(function (CellType) {\n /** Defines CellType as Data */\n CellType[CellType[\"Data\"] = 0] = \"Data\";\n /** Defines CellType as Header */\n CellType[CellType[\"Header\"] = 1] = \"Header\";\n /** Defines CellType as Summary */\n CellType[CellType[\"Summary\"] = 2] = \"Summary\";\n /** Defines CellType as GroupSummary */\n CellType[CellType[\"GroupSummary\"] = 3] = \"GroupSummary\";\n /** Defines CellType as CaptionSummary */\n CellType[CellType[\"CaptionSummary\"] = 4] = \"CaptionSummary\";\n /** Defines CellType as Filter */\n CellType[CellType[\"Filter\"] = 5] = \"Filter\";\n /** Defines CellType as Indent */\n CellType[CellType[\"Indent\"] = 6] = \"Indent\";\n /** Defines CellType as GroupCaption */\n CellType[CellType[\"GroupCaption\"] = 7] = \"GroupCaption\";\n /** Defines CellType as GroupCaptionEmpty */\n CellType[CellType[\"GroupCaptionEmpty\"] = 8] = \"GroupCaptionEmpty\";\n /** Defines CellType as Expand */\n CellType[CellType[\"Expand\"] = 9] = \"Expand\";\n /** Defines CellType as HeaderIndent */\n CellType[CellType[\"HeaderIndent\"] = 10] = \"HeaderIndent\";\n /** Defines CellType as StackedHeader */\n CellType[CellType[\"StackedHeader\"] = 11] = \"StackedHeader\";\n /** Defines CellType as DetailHeader */\n CellType[CellType[\"DetailHeader\"] = 12] = \"DetailHeader\";\n /** Defines CellType as DetailExpand */\n CellType[CellType[\"DetailExpand\"] = 13] = \"DetailExpand\";\n /** Defines CellType as CommandColumn */\n CellType[CellType[\"CommandColumn\"] = 14] = \"CommandColumn\";\n})(CellType || (CellType = {}));\n/**\n * Defines types of Render\n * @hidden\n */\nexport var RenderType;\n(function (RenderType) {\n /** Defines RenderType as Header */\n RenderType[RenderType[\"Header\"] = 0] = \"Header\";\n /** Defines RenderType as Content */\n RenderType[RenderType[\"Content\"] = 1] = \"Content\";\n /** Defines RenderType as Summary */\n RenderType[RenderType[\"Summary\"] = 2] = \"Summary\";\n})(RenderType || (RenderType = {}));\n/**\n * Defines Predefined toolbar items.\n * @hidden\n */\nexport var ToolbarItem;\n(function (ToolbarItem) {\n ToolbarItem[ToolbarItem[\"Add\"] = 0] = \"Add\";\n ToolbarItem[ToolbarItem[\"Edit\"] = 1] = \"Edit\";\n ToolbarItem[ToolbarItem[\"Update\"] = 2] = \"Update\";\n ToolbarItem[ToolbarItem[\"Delete\"] = 3] = \"Delete\";\n ToolbarItem[ToolbarItem[\"Cancel\"] = 4] = \"Cancel\";\n ToolbarItem[ToolbarItem[\"Print\"] = 5] = \"Print\";\n ToolbarItem[ToolbarItem[\"Search\"] = 6] = \"Search\";\n ToolbarItem[ToolbarItem[\"ColumnChooser\"] = 7] = \"ColumnChooser\";\n ToolbarItem[ToolbarItem[\"PdfExport\"] = 8] = \"PdfExport\";\n ToolbarItem[ToolbarItem[\"ExcelExport\"] = 9] = \"ExcelExport\";\n ToolbarItem[ToolbarItem[\"CsvExport\"] = 10] = \"CsvExport\";\n ToolbarItem[ToolbarItem[\"WordExport\"] = 11] = \"WordExport\";\n})(ToolbarItem || (ToolbarItem = {}));\n","/**\n * CellStyle class\n */\nvar CellStyle = /** @class */ (function () {\n function CellStyle() {\n this.numFmtId = 0;\n this.backColor = 'none';\n this.fontName = 'Calibri';\n this.fontSize = 14;\n this.fontColor = '#000000';\n this.italic = false;\n this.bold = false;\n this.underline = false;\n this.wrapText = false;\n this.hAlign = 'general';\n this.vAlign = 'bottom';\n this.indent = 0;\n this.numberFormat = 'GENERAL';\n this.type = 'datetime';\n this.borders = new Borders();\n this.isGlobalStyle = false;\n }\n return CellStyle;\n}());\nexport { CellStyle };\nvar Font = /** @class */ (function () {\n function Font() {\n this.sz = 14;\n this.name = 'Calibri';\n this.u = false;\n this.b = false;\n this.i = false;\n this.color = 'FF000000';\n }\n return Font;\n}());\nexport { Font };\nvar CellXfs = /** @class */ (function () {\n function CellXfs() {\n }\n return CellXfs;\n}());\nexport { CellXfs };\nvar Alignment = /** @class */ (function () {\n function Alignment() {\n }\n return Alignment;\n}());\nexport { Alignment };\nvar CellStyleXfs = /** @class */ (function () {\n function CellStyleXfs() {\n }\n return CellStyleXfs;\n}());\nexport { CellStyleXfs };\nvar CellStyles = /** @class */ (function () {\n function CellStyles() {\n this.name = 'Normal';\n this.xfId = 0;\n }\n return CellStyles;\n}());\nexport { CellStyles };\nvar NumFmt = /** @class */ (function () {\n function NumFmt(id, code) {\n this.numFmtId = id;\n this.formatCode = code;\n }\n return NumFmt;\n}());\nexport { NumFmt };\n/**\n * Border class\n */\nvar Border = /** @class */ (function () {\n function Border(mLine, mColor) {\n this.lineStyle = mLine;\n this.color = mColor;\n }\n return Border;\n}());\nexport { Border };\n/**\n * Border class\n */\nvar Borders = /** @class */ (function () {\n function Borders() {\n this.left = new Border('none', '#FFFFFF');\n this.right = new Border('none', '#FFFFFF');\n this.top = new Border('none', '#FFFFFF');\n this.bottom = new Border('none', '#FFFFFF');\n this.all = new Border('none', '#FFFFFF');\n }\n return Borders;\n}());\nexport { Borders };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * Worksheet class\n */\nvar Cell = /** @class */ (function () {\n function Cell() {\n }\n return Cell;\n}());\nexport { Cell };\n/**\n * Rows class\n */\nvar Cells = /** @class */ (function (_super) {\n __extends(Cells, _super);\n function Cells() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.add = function (cell) {\n var inserted = false;\n var count = 0;\n for (var _i = 0, _a = _this; _i < _a.length; _i++) {\n var c = _a[_i];\n if (c.index === cell.index) {\n _this[count] = cell;\n inserted = true;\n }\n count++;\n }\n if (!inserted) {\n _this.push(cell);\n }\n };\n return _this;\n }\n return Cells;\n}(Array));\nexport { Cells };\n","/**\n * Column class\n */\nvar Column = /** @class */ (function () {\n function Column() {\n }\n return Column;\n}());\nexport { Column };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * Worksheet class\n */\nvar Row = /** @class */ (function () {\n function Row() {\n }\n return Row;\n}());\nexport { Row };\n/**\n * Rows class\n */\nvar Rows = /** @class */ (function (_super) {\n __extends(Rows, _super);\n function Rows() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.add = function (row) {\n var inserted = false;\n var count = 0;\n for (var _i = 0, _a = _this; _i < _a.length; _i++) {\n var r = _a[_i];\n if (r.index === row.index) {\n _this[count] = row;\n inserted = true;\n }\n count++;\n }\n if (!inserted) {\n _this.push(row);\n }\n };\n return _this;\n }\n return Rows;\n}(Array));\nexport { Rows };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * Worksheets class\n */\nvar Worksheets = /** @class */ (function (_super) {\n __extends(Worksheets, _super);\n function Worksheets() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return Worksheets;\n}(Array));\nexport { Worksheets };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * Worksheet class\n */\nvar Worksheet = /** @class */ (function () {\n function Worksheet() {\n this.isSummaryRowBelow = true;\n }\n return Worksheet;\n}());\nexport { Worksheet };\nvar HyperLink = /** @class */ (function () {\n function HyperLink() {\n }\n return HyperLink;\n}());\nexport { HyperLink };\nvar Grouping = /** @class */ (function () {\n function Grouping() {\n }\n return Grouping;\n}());\nexport { Grouping };\nvar FreezePane = /** @class */ (function () {\n function FreezePane() {\n }\n return FreezePane;\n}());\nexport { FreezePane };\nvar MergeCell = /** @class */ (function () {\n function MergeCell() {\n }\n return MergeCell;\n}());\nexport { MergeCell };\n/**\n * MergeCells class\n */\nvar MergeCells = /** @class */ (function (_super) {\n __extends(MergeCells, _super);\n function MergeCells() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.add = function (mergeCell) {\n var inserted = false;\n var count = 0;\n for (var _i = 0, _a = _this; _i < _a.length; _i++) {\n var mCell = _a[_i];\n if (MergeCells.isIntersecting(mCell, mergeCell)) {\n var intersectingCell = new MergeCell();\n intersectingCell.x = Math.min(mCell.x, mergeCell.x);\n intersectingCell.y = Math.min(mCell.Y, mergeCell.y);\n intersectingCell.width = Math.max(mCell.Width + mCell.X, mergeCell.width + mergeCell.x);\n intersectingCell.height = Math.max(mCell.Height + mCell.Y, mergeCell.height + mergeCell.y);\n intersectingCell.ref = (_this[count].ref.split(':')[0]) + ':' + (mergeCell.ref.split(':')[1]);\n _this[count] = intersectingCell;\n mergeCell = intersectingCell;\n inserted = true;\n }\n count++;\n }\n if (!inserted) {\n _this.push(mergeCell);\n }\n return mergeCell;\n };\n return _this;\n }\n MergeCells.isIntersecting = function (base, compare) {\n return (base.x <= compare.x + compare.width)\n && (compare.x <= base.x + base.width)\n && (base.y <= compare.y + compare.height)\n && (compare.y <= base.y + base.height);\n };\n return MergeCells;\n}(Array));\nexport { MergeCells };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Internationalization } from '@syncfusion/ej2-base';\n// import { IValueFormatter } from '../base/interface';\n/**\n * ValueFormatter class to globalize the value.\n * @hidden\n */\nvar ValueFormatter = /** @class */ (function () {\n function ValueFormatter(cultureName) {\n this.intl = new Internationalization();\n // if (!isNullOrUndefined(cultureName)) {\n // this.intl.culture = cultureName;\n // }\n }\n ValueFormatter.prototype.getFormatFunction = function (format) {\n if (format.type) {\n return this.intl.getDateFormat(format);\n }\n else {\n return this.intl.getNumberFormat(format);\n }\n };\n // public getParserFunction(format: NumberFormatOptions | DateFormatOptions): Function {\n // if ((format).type) {\n // return this.intl.getDateParser(format);\n // } else {\n // return this.intl.getNumberParser(format);\n // }\n // }\n // public fromView(value: string, format: Function, type?: string): string | number | Date {\n // if (type === 'date' || type === 'datetime' || type === 'number') {\n // return format(value);\n // } else {\n // return value;\n // }\n // }\n ValueFormatter.prototype.toView = function (value, format) {\n var result = value;\n if (!isNullOrUndefined(format) && !isNullOrUndefined(value)) {\n result = format(value);\n }\n return result;\n };\n // public setCulture(cultureName: string): void {\n // if (!isNullOrUndefined(cultureName)) {\n // setCulture(cultureName);\n // }\n // }\n /* tslint:disable:no-any */\n ValueFormatter.prototype.displayText = function (value, format) {\n return this.toView(value, this.getFormatFunction(format));\n };\n return ValueFormatter;\n}());\nexport { ValueFormatter };\n","import { ValueFormatter } from './value-formatter';\n/**\n * CsvHelper class\n */\nvar CsvHelper = /** @class */ (function () {\n /* tslint:disable:no-any */\n function CsvHelper(json) {\n this.csvStr = '';\n this.formatter = new ValueFormatter();\n this.isMicrosoftBrowser = !(!navigator.msSaveBlob);\n if (json.styles !== null && json.styles !== undefined) {\n this.globalStyles = new Map();\n for (var i = 0; i < json.styles.length; i++) {\n if (json.styles[i].name !== undefined && json.styles[i].numberFormat !== undefined) {\n this.globalStyles.set(json.styles[i].name, json.styles[i].numberFormat);\n }\n }\n }\n // Parses Worksheets data to DOM. \n if (json.worksheets !== null && json.worksheets !== undefined) {\n this.parseWorksheet(json.worksheets[0]);\n }\n //this.csvStr = 'a1,a2,a3\\nb1,b2,b3';\n }\n CsvHelper.prototype.parseWorksheet = function (json) {\n //Rows\n if (json.rows !== null && json.rows !== undefined) {\n this.parseRows(json.rows);\n }\n };\n /* tslint:disable:no-any */\n CsvHelper.prototype.parseRows = function (rows) {\n var count = 1;\n for (var _i = 0, rows_1 = rows; _i < rows_1.length; _i++) {\n var row = rows_1[_i];\n //Row index\n if (row.index !== null && row.index !== undefined) {\n while (count < row.index) {\n this.csvStr += '\\n';\n count++;\n }\n this.parseRow(row);\n }\n else {\n throw Error('Row index is missing.');\n }\n }\n };\n /* tslint:disable:no-any */\n CsvHelper.prototype.parseRow = function (row) {\n if (row.cells !== null && row.cells !== undefined) {\n var count = 1;\n for (var _i = 0, _a = row.cells; _i < _a.length; _i++) {\n var cell = _a[_i];\n //cell index\n if (cell.index !== null && cell.index !== undefined) {\n while (count < cell.index) {\n this.csvStr += ',';\n count++;\n }\n this.parseCell(cell);\n }\n else {\n throw Error('Cell index is missing.');\n }\n }\n }\n };\n /* tslint:disable:no-any */\n CsvHelper.prototype.parseCell = function (cell) {\n var csv = this.csvStr;\n if (cell.value !== undefined) {\n if (cell.value instanceof Date) {\n if (cell.style !== undefined && cell.style.numberFormat !== undefined) {\n /* tslint:disable-next-line:max-line-length */\n csv += this.parseCellValue(this.formatter.displayText(cell.value, { type: 'dateTime', skeleton: cell.style.numberFormat }));\n }\n else if (cell.style !== undefined && cell.style.name !== undefined && this.globalStyles.has(cell.style.name)) {\n /* tslint:disable-next-line:max-line-length */\n csv += this.parseCellValue(this.formatter.displayText(cell.value, { type: 'dateTime', skeleton: this.globalStyles.get(cell.style.name) }));\n }\n else {\n csv += cell.value;\n }\n }\n else if (typeof (cell.value) === 'boolean') {\n csv += cell.value ? 'TRUE' : 'FALSE';\n }\n else if (typeof (cell.value) === 'number') {\n if (cell.style !== undefined && cell.style.numberFormat !== undefined) {\n /* tslint:disable-next-line:max-line-length */\n csv += this.parseCellValue(this.formatter.displayText(cell.value, { format: cell.style.numberFormat }));\n }\n else if (cell.style !== undefined && cell.style.name !== undefined && this.globalStyles.has(cell.style.name)) {\n /* tslint:disable-next-line:max-line-length */\n csv += this.parseCellValue(this.formatter.displayText(cell.value, { format: this.globalStyles.get(cell.style.name) }));\n }\n else {\n csv += cell.value;\n }\n }\n else {\n csv += this.parseCellValue(cell.value);\n }\n }\n this.csvStr = csv;\n };\n CsvHelper.prototype.parseCellValue = function (value) {\n if (value.indexOf(',') !== -1) {\n return value = '\\\"' + value + '\\\"';\n }\n else {\n return value;\n }\n };\n /**\n * Saves the file with specified name and sends the file to client browser\n * @param {string} fileName- file name to save.\n * @param {Blob} buffer- the content to write in file\n */\n CsvHelper.prototype.save = function (fileName) {\n this.buffer = new Blob(['\\ufeff' + this.csvStr], { type: 'text/csv;charset=UTF-8' });\n if (this.isMicrosoftBrowser) {\n navigator.msSaveBlob(this.buffer, fileName);\n }\n else {\n var dataUrl_1 = window.URL.createObjectURL(this.buffer);\n var dwlLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');\n dwlLink.download = fileName;\n dwlLink.href = dataUrl_1;\n var event_1 = document.createEvent('MouseEvent');\n event_1.initEvent('click', true, true);\n dwlLink.dispatchEvent(event_1);\n setTimeout(function () {\n window.URL.revokeObjectURL(dataUrl_1);\n });\n }\n };\n CsvHelper.prototype.saveAsBlob = function () {\n return new Blob(['\\ufeff' + this.csvStr], { type: 'text/csv;charset=UTF-8' });\n };\n return CsvHelper;\n}());\nexport { CsvHelper };\n","/**\n * BlobHelper class\n */\nvar BlobHelper = /** @class */ (function () {\n function BlobHelper() {\n /* tslint:disable:no-any */\n this.parts = [];\n }\n /* tslint:disable:no-any */\n BlobHelper.prototype.append = function (part) {\n this.parts.push(part);\n this.blob = undefined; // Invalidate the blob\n };\n BlobHelper.prototype.getBlob = function () {\n return new Blob(this.parts, { type: 'text/plain' });\n };\n return BlobHelper;\n}());\nexport { BlobHelper };\n","import { Worksheets } from './worksheets';\nimport { Worksheet, FreezePane, MergeCell, MergeCells, HyperLink, Grouping } from './worksheet';\nimport { CellStyle, Font, Borders, CellXfs, Alignment, NumFmt, CellStyleXfs, CellStyles } from './cell-style';\nimport { Column } from './column';\nimport { Row, Rows } from './row';\nimport { Cell, Cells } from './cell';\nimport { ZipArchive, ZipArchiveItem } from '@syncfusion/ej2-compression';\nimport { CsvHelper } from './csv-helper';\nimport { Internationalization, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { BlobHelper } from './blob-helper';\n/**\n * Workbook class\n */\nvar Workbook = /** @class */ (function () {\n /* tslint:disable:no-any */\n function Workbook(json, saveType, culture, currencyString) {\n this.sharedStringCount = 0;\n this.unitsProportions = [\n 96 / 75.0,\n 96 / 300.0,\n 96,\n 96 / 25.4,\n 96 / 2.54,\n 1,\n 96 / 72.0,\n 96 / 72.0 / 12700,\n ];\n /* tslint:disable:no-any */\n this.hyperlinkStyle = { fontColor: '#0000FF', underline: true };\n if (culture !== undefined) {\n this.culture = culture;\n }\n else {\n this.culture = 'en-US';\n }\n if (currencyString !== undefined) {\n this.currency = currencyString;\n }\n else {\n this.currency = 'USD';\n }\n this.intl = new Internationalization(this.culture);\n this.mSaveType = saveType;\n if (saveType === 'xlsx') {\n this.mArchive = new ZipArchive();\n this.sharedString = [];\n this.mFonts = [];\n this.mBorders = [];\n this.mStyles = [];\n this.printTitles = new Map();\n this.cellStyles = new Map();\n this.mNumFmt = new Map();\n this.mFills = new Map();\n this.mStyles.push(new CellStyle());\n this.mFonts.push(new Font());\n /* tslint:disable */\n this.cellStyles.set('Normal', new CellStyles());\n /* tslint:enable */\n this.mCellXfs = [];\n this.mCellStyleXfs = [];\n if (json.styles !== null && json.styles !== undefined) {\n /* tslint:disable-next-line:no-any */\n this.globalStyles = new Map();\n for (var i = 0; i < json.styles.length; i++) {\n if (json.styles[i].name !== undefined) {\n if (!this.cellStyles.has(json.styles[i].name)) {\n var cellStyle = new CellStyle();\n cellStyle.isGlobalStyle = true;\n this.parserCellStyle(json.styles[i], cellStyle, 'none');\n var cellStylesIn = new CellStyles();\n cellStylesIn.name = cellStyle.name;\n cellStylesIn.xfId = (cellStyle.index - 1);\n this.cellStyles.set(cellStylesIn.name, cellStylesIn);\n /* tslint:disable-next-line:no-any */\n var tFormat = {};\n if (json.styles[i].numberFormat !== undefined) {\n tFormat.format = json.styles[i].numberFormat;\n }\n if (json.styles[i].type !== undefined) {\n tFormat.type = json.styles[i].type;\n }\n else {\n tFormat.type = 'datetime';\n }\n if (tFormat.format !== undefined) {\n this.globalStyles.set(json.styles[i].name, tFormat);\n }\n }\n else {\n throw Error('Style name ' + json.styles[i].name + ' is already existed');\n }\n }\n }\n }\n // Parses Worksheets data to DOM. \n if (json.worksheets !== null && json.worksheets !== undefined) {\n this.parserWorksheets(json.worksheets);\n }\n else {\n throw Error('Worksheet is expected.');\n }\n // Parses the BuiltInProperties data to DOM. \n if (json.builtInProperties !== null && json.builtInProperties !== undefined) {\n this.builtInProperties = new BuiltInProperties();\n this.parserBuiltInProperties(json.builtInProperties, this.builtInProperties);\n }\n }\n else {\n this.csvHelper = new CsvHelper(json);\n }\n }\n /* tslint:disable:no-any */\n Workbook.prototype.parserBuiltInProperties = function (jsonBuiltInProperties, builtInProperties) {\n //Author\n if (jsonBuiltInProperties.author !== null && jsonBuiltInProperties.author !== undefined) {\n builtInProperties.author = jsonBuiltInProperties.author;\n }\n //Comments\n if (jsonBuiltInProperties.comments !== null && jsonBuiltInProperties.comments !== undefined) {\n builtInProperties.comments = jsonBuiltInProperties.comments;\n }\n //Category\n if (jsonBuiltInProperties.category !== null && jsonBuiltInProperties.category !== undefined) {\n builtInProperties.category = jsonBuiltInProperties.category;\n }\n //Company\n if (jsonBuiltInProperties.company !== null && jsonBuiltInProperties.company !== undefined) {\n builtInProperties.company = jsonBuiltInProperties.company;\n }\n //Manager\n if (jsonBuiltInProperties.manager !== null && jsonBuiltInProperties.manager !== undefined) {\n builtInProperties.manager = jsonBuiltInProperties.manager;\n }\n //Subject\n if (jsonBuiltInProperties.subject !== null && jsonBuiltInProperties.subject !== undefined) {\n builtInProperties.subject = jsonBuiltInProperties.subject;\n }\n //Title\n if (jsonBuiltInProperties.title !== null && jsonBuiltInProperties.title !== undefined) {\n builtInProperties.title = jsonBuiltInProperties.title;\n }\n //Creation date\n if (jsonBuiltInProperties.createdDate !== null && jsonBuiltInProperties.createdDate !== undefined) {\n builtInProperties.createdDate = jsonBuiltInProperties.createdDate;\n }\n //Modified date\n if (jsonBuiltInProperties.modifiedDate !== null && jsonBuiltInProperties.modifiedDate !== undefined) {\n builtInProperties.modifiedDate = jsonBuiltInProperties.modifiedDate;\n }\n //Tags\n if (jsonBuiltInProperties.tags !== null && jsonBuiltInProperties.tags !== undefined) {\n builtInProperties.tags = jsonBuiltInProperties.tags;\n }\n //Status\n if (jsonBuiltInProperties.status !== null && jsonBuiltInProperties.status !== undefined) {\n builtInProperties.status = jsonBuiltInProperties.status;\n }\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserWorksheets = function (json) {\n this.worksheets = new Worksheets();\n var length = json.length;\n for (var i = 0; i < length; i++) {\n var jsonSheet = json[i];\n var sheet = new Worksheet();\n this.mergeCells = new MergeCells();\n this.mergedCellsStyle = new Map();\n this.mHyperLinks = [];\n //Name\n if (jsonSheet.name !== null && jsonSheet.name !== undefined) {\n sheet.name = jsonSheet.name;\n }\n else {\n sheet.name = 'Sheet' + (i + 1).toString();\n }\n sheet.index = (i + 1);\n //Columns\n if (jsonSheet.columns !== null && jsonSheet.columns !== undefined) {\n this.parserColumns(jsonSheet.columns, sheet);\n }\n //Rows\n if (jsonSheet.rows !== null && jsonSheet.rows !== undefined) {\n this.parserRows(jsonSheet.rows, sheet);\n }\n //FreezePanes\n if (jsonSheet.freeze !== null && jsonSheet.freeze !== undefined) {\n this.parserFreezePanes(jsonSheet.freeze, sheet);\n }\n //Print Title\n if (jsonSheet.printTitle !== null && jsonSheet.printTitle !== undefined) {\n this.parserPrintTitle(jsonSheet.printTitle, sheet);\n }\n if (jsonSheet.pageSetup !== undefined) {\n if (jsonSheet.pageSetup.isSummaryRowBelow !== undefined) {\n sheet.isSummaryRowBelow = jsonSheet.pageSetup.isSummaryRowBelow;\n }\n }\n sheet.index = (i + 1);\n sheet.mergeCells = this.mergeCells;\n sheet.hyperLinks = this.mHyperLinks;\n this.worksheets.push(sheet);\n }\n };\n /* tslint:disable:no-any */\n Workbook.prototype.mergeOptions = function (fromJson, toJson) {\n /* tslint:disable:no-any */\n var result = {};\n this.applyProperties(fromJson, result);\n this.applyProperties(toJson, result);\n return result;\n };\n /* tslint:disable:no-any */\n Workbook.prototype.applyProperties = function (sourceJson, destJson) {\n var keys = Object.keys(sourceJson);\n for (var index = 0; index < keys.length; index++) {\n if (keys[index] !== 'name') {\n destJson[keys[index]] = sourceJson[keys[index]];\n }\n }\n };\n Workbook.prototype.getCellName = function (row, column) {\n return this.getColumnName(column) + row.toString();\n };\n Workbook.prototype.getColumnName = function (col) {\n col--;\n var strColumnName = '';\n do {\n var iCurrentDigit = col % 26;\n col = col / 26 - 1;\n strColumnName = String.fromCharCode(65 + iCurrentDigit) + strColumnName;\n } while (col >= 0);\n return strColumnName;\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserPrintTitle = function (json, sheet) {\n var printTitleName = '';\n var titleRowName;\n if (json.fromRow !== null && json.fromRow !== undefined) {\n var fromRow = json.fromRow;\n var toRow = void 0;\n if (json.toRow !== null && json.toRow !== undefined) {\n toRow = json.toRow;\n }\n else {\n toRow = json.fromRow;\n }\n titleRowName = '$' + fromRow + ':$' + toRow;\n }\n var titleColName;\n if (json.fromColumn !== null && json.fromColumn !== undefined) {\n var fromColumn = json.fromColumn;\n var toColumn = void 0;\n if (json.toColumn !== null && json.toColumn !== undefined) {\n toColumn = json.toColumn;\n }\n else {\n toColumn = json.fromColumn;\n }\n titleColName = '$' + this.getColumnName(fromColumn) + ':$' + this.getColumnName(toColumn);\n }\n if (titleRowName !== undefined) {\n printTitleName += (sheet.name + '!' + titleRowName);\n }\n if (titleColName !== undefined && titleRowName !== undefined) {\n printTitleName += ',' + (sheet.name + '!' + titleColName);\n }\n else if (titleColName !== undefined) {\n printTitleName += (sheet.name + '!' + titleColName);\n }\n if (printTitleName !== '') {\n this.printTitles.set(sheet.index - 1, printTitleName);\n }\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserFreezePanes = function (json, sheet) {\n sheet.freezePanes = new FreezePane();\n if (json.row !== null && json.row !== undefined) {\n sheet.freezePanes.row = json.row;\n }\n else {\n sheet.freezePanes.row = 0;\n }\n if (json.column !== null && json.column !== undefined) {\n sheet.freezePanes.column = json.column;\n }\n else {\n sheet.freezePanes.column = 0;\n }\n sheet.freezePanes.leftCell = this.getCellName(sheet.freezePanes.row + 1, sheet.freezePanes.column + 1);\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserColumns = function (json, sheet) {\n var columnsLength = json.length;\n sheet.columns = [];\n for (var column = 0; column < columnsLength; column++) {\n var col = new Column();\n if (json[column].index !== null && json[column].index !== undefined) {\n col.index = json[column].index;\n }\n else {\n throw Error('Column index is missing.');\n }\n if (json[column].width !== null && json[column].width !== undefined) {\n col.width = json[column].width;\n }\n sheet.columns.push(col);\n }\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserRows = function (json, sheet) {\n var rowsLength = json.length;\n sheet.rows = new Rows();\n var rowId = 0;\n for (var r = 0; r < rowsLength; r++) {\n var row = this.parserRow(json[r], rowId);\n rowId = row.index;\n sheet.rows.add(row);\n }\n this.insertMergedCellsStyle(sheet);\n };\n Workbook.prototype.insertMergedCellsStyle = function (sheet) {\n var _this = this;\n if (this.mergeCells.length > 0) {\n this.mergedCellsStyle.forEach(function (value, key) {\n var row = sheet.rows.filter(function (item) {\n return item.index === value.y;\n })[0];\n if (!isNullOrUndefined(row)) {\n var cell = row.cells.filter(function (item) {\n return item.index === value.x;\n })[0];\n if (!isNullOrUndefined(cell)) {\n cell.styleIndex = value.styleIndex;\n }\n else {\n var cells = row.cells.filter(function (item) {\n return item.index <= value.x;\n });\n var insertIndex = 0;\n if (cells.length > 0) {\n insertIndex = row.cells.indexOf(cells[cells.length - 1]) + 1;\n }\n row.cells.splice(insertIndex, 0, _this.createCell(value, key));\n }\n }\n else {\n var rows = sheet.rows.filter(function (item) {\n return item.index <= value.y;\n });\n var rowToInsert = new Row();\n rowToInsert.index = value.y;\n rowToInsert.cells = new Cells();\n rowToInsert.cells.add(_this.createCell(value, key));\n var insertIndex = 0;\n if (rows.length > 0) {\n insertIndex = sheet.rows.indexOf(rows[rows.length - 1]) + 1;\n }\n sheet.rows.splice(insertIndex, 0, rowToInsert);\n }\n });\n }\n };\n Workbook.prototype.createCell = function (value, key) {\n var cellToInsert = new Cell();\n cellToInsert.refName = key;\n cellToInsert.index = value.x;\n cellToInsert.cellStyle = new CellStyle();\n cellToInsert.styleIndex = value.styleIndex;\n return cellToInsert;\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserRow = function (json, rowIndex) {\n var row = new Row();\n //Row Height\n if (json.height !== null && json.height !== undefined) {\n row.height = json.height;\n }\n //Row index\n if (json.index !== null && json.index !== undefined) {\n row.index = json.index;\n }\n else {\n throw Error('Row index is missing.');\n }\n if (json.grouping !== null && json.grouping !== undefined) {\n this.parseGrouping(json.grouping, row);\n }\n this.parseCells(json.cells, row);\n return row;\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parseGrouping = function (json, row) {\n row.grouping = new Grouping();\n if (json.outlineLevel !== undefined) {\n row.grouping.outlineLevel = json.outlineLevel;\n }\n if (json.isCollapsed !== undefined) {\n row.grouping.isCollapsed = json.isCollapsed;\n }\n if (json.isHidden !== undefined) {\n row.grouping.isHidden = json.isHidden;\n }\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parseCells = function (json, row) {\n row.cells = new Cells();\n var cellsLength = json !== undefined ? json.length : 0;\n var spanMin = 1;\n var spanMax = 1;\n var curCellIndex = 0;\n for (var cellId = 0; cellId < cellsLength; cellId++) {\n /* tslint:disable:no-any */\n var jsonCell = json[cellId];\n var cell = new Cell();\n //cell index\n if (jsonCell.index !== null && jsonCell.index !== undefined) {\n cell.index = jsonCell.index;\n }\n else {\n throw Error('Cell index is missing.');\n }\n if (cell.index < spanMin) {\n spanMin = cell.index;\n }\n else if (cell.index > spanMax) {\n spanMax = cell.index;\n }\n //Update the Cell name\n cell.refName = this.getCellName(row.index, cell.index);\n //Row span\n if (jsonCell.rowSpan !== null && jsonCell.rowSpan !== undefined) {\n cell.rowSpan = jsonCell.rowSpan - 1;\n }\n else {\n cell.rowSpan = 0;\n }\n //Column span\n if (jsonCell.colSpan !== null && jsonCell.colSpan !== undefined) {\n cell.colSpan = jsonCell.colSpan - 1;\n }\n else {\n cell.colSpan = 0;\n }\n //Hyperlink\n if (jsonCell.hyperlink !== null && jsonCell.hyperlink !== undefined) {\n var hyperLink = new HyperLink();\n if (jsonCell.hyperlink.target !== undefined) {\n hyperLink.target = jsonCell.hyperlink.target;\n if (jsonCell.hyperlink.displayText !== undefined) {\n cell.value = jsonCell.hyperlink.displayText;\n }\n else {\n cell.value = jsonCell.hyperlink.target;\n }\n cell.type = this.getCellValueType(cell.value);\n hyperLink.ref = cell.refName;\n hyperLink.rId = (this.mHyperLinks.length + 1);\n this.mHyperLinks.push(hyperLink);\n cell.cellStyle = new CellStyle();\n /* tslint:disable-next-line:max-line-length */\n this.parserCellStyle((jsonCell.style !== undefined ? this.mergeOptions(jsonCell.style, this.hyperlinkStyle) : this.hyperlinkStyle), cell.cellStyle, 'string');\n cell.styleIndex = cell.cellStyle.index;\n }\n }\n //Cell value\n if (jsonCell.value !== null && jsonCell.value !== undefined) {\n cell.value = jsonCell.value;\n cell.type = this.getCellValueType(cell.value);\n }\n if (jsonCell.style !== null && jsonCell.style !== undefined && cell.styleIndex === undefined) {\n cell.cellStyle = new CellStyle();\n if (cell.value instanceof Date) {\n this.parserCellStyle(jsonCell.style, cell.cellStyle, cell.type, 14);\n }\n else {\n this.parserCellStyle(jsonCell.style, cell.cellStyle, cell.type);\n }\n cell.styleIndex = cell.cellStyle.index;\n }\n else if (cell.value instanceof Date) {\n cell.cellStyle = new CellStyle();\n this.parserCellStyle({}, cell.cellStyle, cell.type, 14);\n cell.styleIndex = cell.cellStyle.index;\n }\n this.parseCellType(cell);\n this.mergeCells = this.processMergeCells(cell, row.index, this.mergeCells);\n row.cells.add(cell);\n curCellIndex = (cell.index + 1);\n }\n row.spans = (spanMin) + ':' + (spanMax);\n };\n Workbook.prototype.applyGlobalStyle = function (json, cellStyle) {\n var index = 0;\n if (this.cellStyles.has(json.name)) {\n cellStyle.index = this.mStyles.filter(function (a) { return (a.name === json.name); })[0].index;\n cellStyle.name = json.name;\n }\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserCellStyle = function (json, cellStyle, cellType, defStyleIndex) {\n //name\n if (json.name !== null && json.name !== undefined) {\n if (cellStyle.isGlobalStyle) {\n cellStyle.name = json.name;\n }\n else {\n this.applyGlobalStyle(json, cellStyle);\n return;\n }\n }\n //background color\n if (json.backColor !== null && json.backColor !== undefined) {\n cellStyle.backColor = json.backColor;\n }\n //borders\n //leftBorder\n cellStyle.borders = new Borders();\n //AllBorder\n if (json.borders !== null && json.borders !== undefined) {\n this.parserBorder(json.borders, cellStyle.borders.all);\n }\n //leftborder\n if (json.leftBorder !== null && json.leftBorder !== undefined) {\n this.parserBorder(json.leftBorder, cellStyle.borders.left);\n }\n //rightBorder\n if (json.rightBorder !== null && json.rightBorder !== undefined) {\n this.parserBorder(json.rightBorder, cellStyle.borders.right);\n }\n //topBorder\n if (json.topBorder !== null && json.topBorder !== undefined) {\n this.parserBorder(json.topBorder, cellStyle.borders.top);\n }\n //bottomBorder\n if (json.bottomBorder !== null && json.bottomBorder !== undefined) {\n this.parserBorder(json.bottomBorder, cellStyle.borders.bottom);\n }\n //fontName\n if (json.fontName !== null && json.fontName !== undefined) {\n cellStyle.fontName = json.fontName;\n }\n //fontSize\n if (json.fontSize !== null && json.fontSize !== undefined) {\n cellStyle.fontSize = json.fontSize;\n }\n //fontColor\n if (json.fontColor !== null && json.fontColor !== undefined) {\n cellStyle.fontColor = json.fontColor;\n }\n //italic\n if (json.italic !== null && json.italic !== undefined) {\n cellStyle.italic = json.italic;\n }\n //bold\n if (json.bold !== null && json.bold !== undefined) {\n cellStyle.bold = json.bold;\n }\n //hAlign\n if (json.hAlign !== null && json.hAlign !== undefined) {\n cellStyle.hAlign = json.hAlign;\n }\n //indent\n if (json.indent !== null && json.indent !== undefined) {\n cellStyle.indent = json.indent;\n if (!(cellStyle.hAlign === 'left' || cellStyle.hAlign === 'right')) {\n cellStyle.hAlign = 'left';\n }\n }\n //vAlign\n if (json.vAlign !== null && json.vAlign !== undefined) {\n cellStyle.vAlign = json.vAlign;\n }\n //underline\n if (json.underline !== null && json.underline !== undefined) {\n cellStyle.underline = json.underline;\n }\n //wrapText\n if (json.wrapText !== null && json.wrapText !== undefined) {\n cellStyle.wrapText = json.wrapText;\n }\n //numberFormat\n if (json.numberFormat !== null && json.numberFormat !== undefined) {\n if (json.type !== null && json.type !== undefined) {\n cellStyle.numberFormat = this.getNumberFormat(json.numberFormat, json.type);\n }\n else {\n cellStyle.numberFormat = this.getNumberFormat(json.numberFormat, cellType);\n }\n }\n else if (defStyleIndex !== undefined) {\n cellStyle.numFmtId = 14;\n cellStyle.numberFormat = 'GENERAL';\n }\n else {\n cellStyle.numberFormat = 'GENERAL';\n }\n cellStyle.index = this.processCellStyle(cellStyle);\n };\n Workbook.prototype.switchNumberFormat = function (numberFormat, type) {\n var format = this.getNumberFormat(numberFormat, type);\n if (format !== numberFormat) {\n var numFmt = this.mNumFmt.get(numberFormat);\n if (numFmt !== undefined) {\n numFmt.formatCode = format;\n if (this.mNumFmt.has(format)) {\n for (var _i = 0, _a = this.mCellStyleXfs; _i < _a.length; _i++) {\n var cellStyleXfs = _a[_i];\n if (cellStyleXfs.numFmtId === numFmt.numFmtId) {\n cellStyleXfs.numFmtId = this.mNumFmt.get(format).numFmtId;\n }\n }\n for (var _b = 0, _c = this.mCellXfs; _b < _c.length; _b++) {\n var cellXfs = _c[_b];\n if (cellXfs.numFmtId === numFmt.numFmtId) {\n cellXfs.numFmtId = this.mNumFmt.get(format).numFmtId;\n }\n }\n }\n }\n }\n };\n Workbook.prototype.getNumberFormat = function (numberFormat, type) {\n var returnFormat;\n switch (type) {\n case 'number':\n try {\n returnFormat = this.intl.getNumberPattern({ format: numberFormat, currency: this.currency });\n }\n catch (error) {\n returnFormat = numberFormat;\n }\n break;\n case 'datetime':\n try {\n returnFormat = this.intl.getDatePattern({ skeleton: numberFormat, type: 'dateTime' }, true);\n }\n catch (error) {\n returnFormat = numberFormat;\n }\n break;\n case 'date':\n try {\n returnFormat = this.intl.getDatePattern({ skeleton: numberFormat, type: 'date' }, true);\n }\n catch (error) {\n returnFormat = numberFormat;\n }\n break;\n case 'time':\n try {\n returnFormat = this.intl.getDatePattern({ skeleton: numberFormat, type: 'time' }, true);\n }\n catch (error) {\n returnFormat = numberFormat;\n }\n break;\n default:\n returnFormat = numberFormat;\n break;\n }\n return returnFormat;\n };\n /* tslint:disable:no-any */\n Workbook.prototype.parserBorder = function (json, border) {\n if (json.color !== null && json.color !== undefined) {\n border.color = json.color;\n }\n else {\n border.color = '#000000';\n }\n if (json.lineStyle !== null && json.lineStyle !== undefined) {\n border.lineStyle = json.lineStyle;\n }\n else {\n border.lineStyle = 'thin';\n }\n };\n Workbook.prototype.processCellStyle = function (style) {\n if (style.isGlobalStyle) {\n this.processNumFormatId(style);\n this.mStyles.push(style);\n return this.mStyles.length;\n }\n else {\n var compareResult = this.compareStyle(style);\n if (!compareResult.result) {\n this.processNumFormatId(style);\n this.mStyles.push(style);\n return this.mStyles.length;\n }\n else {\n //Return the index of the already existing style.\n return compareResult.index;\n }\n }\n };\n Workbook.prototype.processNumFormatId = function (style) {\n if (style.numberFormat !== 'GENERAL' && !this.mNumFmt.has(style.numberFormat)) {\n var id = this.mNumFmt.size + 164;\n this.mNumFmt.set(style.numberFormat, new NumFmt(id, style.numberFormat));\n }\n };\n Workbook.prototype.isNewFont = function (toCompareStyle) {\n var result = false;\n var index = 0;\n for (var _i = 0, _a = this.mFonts; _i < _a.length; _i++) {\n var font = _a[_i];\n index++;\n var fontColor = undefined;\n if (toCompareStyle.fontColor !== undefined) {\n fontColor = ('FF' + toCompareStyle.fontColor.replace('#', ''));\n }\n result = font.color === fontColor &&\n font.b === toCompareStyle.bold &&\n font.i === toCompareStyle.italic &&\n font.u === toCompareStyle.underline &&\n font.name === toCompareStyle.fontName &&\n font.sz === toCompareStyle.fontSize;\n if (result) {\n break;\n }\n }\n index = index - 1;\n return { index: index, result: result };\n };\n Workbook.prototype.isNewBorder = function (toCompareStyle) {\n var bStyle = new CellStyle();\n if (this.isAllBorder(toCompareStyle.borders)) {\n return (bStyle.borders.all.color === toCompareStyle.borders.all.color &&\n bStyle.borders.all.lineStyle === toCompareStyle.borders.all.lineStyle);\n }\n else {\n return (bStyle.borders.left.color === toCompareStyle.borders.left.color &&\n bStyle.borders.left.lineStyle === toCompareStyle.borders.left.lineStyle &&\n bStyle.borders.right.color === toCompareStyle.borders.right.color &&\n bStyle.borders.right.lineStyle === toCompareStyle.borders.right.lineStyle &&\n bStyle.borders.top.color === toCompareStyle.borders.top.color &&\n bStyle.borders.top.lineStyle === toCompareStyle.borders.top.lineStyle &&\n bStyle.borders.bottom.color === toCompareStyle.borders.bottom.color &&\n bStyle.borders.bottom.lineStyle === toCompareStyle.borders.bottom.lineStyle);\n }\n };\n Workbook.prototype.isAllBorder = function (toCompareBorder) {\n var allBorderStyle = new CellStyle();\n return allBorderStyle.borders.all.color !== toCompareBorder.all.color &&\n allBorderStyle.borders.all.lineStyle !== toCompareBorder.all.lineStyle;\n };\n Workbook.prototype.compareStyle = function (toCompareStyle) {\n var result = true;\n var index = 0;\n var globalStyleIndex = 0;\n for (var _i = 0, _a = this.mStyles; _i < _a.length; _i++) {\n var baseStyle = _a[_i];\n result = baseStyle.isGlobalStyle ? false : (baseStyle.backColor === toCompareStyle.backColor &&\n baseStyle.bold === toCompareStyle.bold &&\n baseStyle.numFmtId === toCompareStyle.numFmtId &&\n baseStyle.numberFormat === toCompareStyle.numberFormat &&\n baseStyle.type === toCompareStyle.type &&\n baseStyle.fontColor === toCompareStyle.fontColor &&\n baseStyle.fontName === toCompareStyle.fontName &&\n baseStyle.fontSize === toCompareStyle.fontSize &&\n baseStyle.hAlign === toCompareStyle.hAlign &&\n baseStyle.italic === toCompareStyle.italic &&\n baseStyle.underline === toCompareStyle.underline &&\n baseStyle.vAlign === toCompareStyle.vAlign &&\n baseStyle.indent === toCompareStyle.indent &&\n baseStyle.wrapText === toCompareStyle.wrapText &&\n (baseStyle.borders.all.color === toCompareStyle.borders.all.color &&\n baseStyle.borders.all.lineStyle === toCompareStyle.borders.all.lineStyle) &&\n (baseStyle.borders.left.color === toCompareStyle.borders.left.color &&\n baseStyle.borders.left.lineStyle === toCompareStyle.borders.left.lineStyle &&\n baseStyle.borders.right.color === toCompareStyle.borders.right.color &&\n baseStyle.borders.right.lineStyle === toCompareStyle.borders.right.lineStyle &&\n baseStyle.borders.top.color === toCompareStyle.borders.top.color &&\n baseStyle.borders.top.lineStyle === toCompareStyle.borders.top.lineStyle &&\n baseStyle.borders.bottom.color === toCompareStyle.borders.bottom.color &&\n baseStyle.borders.bottom.lineStyle === toCompareStyle.borders.bottom.lineStyle));\n if (result) {\n index = baseStyle.index;\n break;\n }\n }\n return { index: index, result: result };\n };\n Workbook.prototype.contains = function (array, item) {\n var index = array.indexOf(item);\n return index > -1 && index < array.length;\n };\n Workbook.prototype.getCellValueType = function (value) {\n if (value instanceof Date) {\n return 'datetime';\n }\n else if (typeof (value) === 'boolean') {\n return 'boolean';\n }\n else if (typeof (value) === 'number') {\n return 'number';\n }\n else {\n return 'string';\n }\n };\n Workbook.prototype.parseCellType = function (cell) {\n var type = cell.type;\n var saveType;\n var value = cell.value;\n switch (type) {\n case 'datetime':\n value = this.toOADate(value);\n if (cell.cellStyle !== undefined && cell.cellStyle.name !== undefined) {\n if (this.globalStyles.has(cell.cellStyle.name)) {\n var value_1 = this.globalStyles.get(cell.cellStyle.name);\n this.switchNumberFormat(value_1.format, value_1.type);\n }\n }\n saveType = 'n';\n break;\n //TODO: Update the number format index and style\n case 'boolean':\n value = value ? 1 : 0;\n saveType = 'b';\n break;\n case 'number':\n saveType = 'n';\n if (cell.cellStyle !== undefined && cell.cellStyle.name !== undefined) {\n if (this.globalStyles.has(cell.cellStyle.name)) {\n this.switchNumberFormat(this.globalStyles.get(cell.cellStyle.name).format, 'number');\n }\n }\n break;\n case 'string':\n this.sharedStringCount++;\n saveType = 's';\n if (!this.contains(this.sharedString, value)) {\n this.sharedString.push(value);\n }\n value = this.sharedString.indexOf(value);\n break;\n default:\n break;\n }\n cell.saveType = saveType;\n cell.value = value;\n };\n Workbook.prototype.saveAsBlob = function (blobSaveType) {\n var _this = this;\n switch (blobSaveType) {\n case 'text/csv':\n return new Promise(function (resolve, reject) {\n var obj = {};\n obj.blobData = _this.csvHelper.saveAsBlob();\n resolve(obj);\n });\n default:\n return new Promise(function (resolve, reject) {\n _this.saveInternal();\n _this.mArchive.saveAsBlob().then(function (blob) {\n var obj = {};\n obj.blobData = new Blob([blob], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });\n resolve(obj);\n });\n });\n }\n };\n Workbook.prototype.save = function (fileName, proxyUrl) {\n var _this = this;\n if (fileName === null || fileName === undefined || fileName === '') {\n throw new Error('Argument Null Exception: fileName cannot be null or empty');\n }\n var xlsxMatch = fileName.match('.xlsx$');\n var csvMatch = fileName.match('.csv$');\n if (xlsxMatch !== null && xlsxMatch[0] === ('.' + this.mSaveType)) {\n this.saveInternal();\n this.mArchive.save(fileName).then(function () {\n _this.mArchive.destroy();\n });\n }\n else if (csvMatch !== null && csvMatch[0] === ('.' + this.mSaveType)) {\n this.csvHelper.save(fileName);\n }\n else {\n throw Error('Save type and file extension is different.');\n }\n };\n Workbook.prototype.saveInternal = function () {\n this.saveWorkbook();\n this.saveWorksheets();\n this.saveSharedString();\n this.saveStyles();\n this.saveApp(this.builtInProperties);\n this.saveCore(this.builtInProperties);\n this.saveContentType();\n this.saveTopLevelRelation();\n this.saveWorkbookRelation();\n };\n Workbook.prototype.saveWorkbook = function () {\n /* tslint:disable-next-line:max-line-length */\n var workbookTemp = ' ';\n var sheets = '';\n var length = this.worksheets.length;\n for (var i = 0; i < length; i++) {\n /* tslint:disable-next-line:max-line-length */\n sheets += ' ';\n }\n sheets += ' ';\n workbookTemp += sheets;\n if (this.printTitles.size > 0) {\n var printTitle_1 = '';\n this.printTitles.forEach(function (value, key) {\n printTitle_1 += '' + value + ' ';\n });\n printTitle_1 += ' ';\n workbookTemp += printTitle_1;\n }\n this.addToArchive(workbookTemp + ' ', 'xl/workbook.xml');\n };\n Workbook.prototype.saveWorksheets = function () {\n var length = this.worksheets.length;\n for (var i = 0; i < length; i++) {\n this.saveWorksheet(this.worksheets[i], i);\n }\n };\n Workbook.prototype.saveWorksheet = function (sheet, index) {\n var sheetBlob = new BlobHelper();\n /* tslint:disable-next-line:max-line-length */\n var sheetString = '';\n if (!sheet.isSummaryRowBelow) {\n sheetString += ('' + '' + ' ' + ' ');\n }\n else {\n sheetString += (' ');\n }\n if (sheet.freezePanes !== undefined) {\n sheetString += (this.saveFreezePanes(sheet));\n }\n if (sheet.columns !== undefined) {\n var colString = '';\n for (var _i = 0, _a = sheet.columns; _i < _a.length; _i++) {\n var column = _a[_i];\n /* tslint:disable-next-line:max-line-length */\n if (column.width !== undefined) {\n colString += ' ';\n }\n else {\n colString += ' ';\n }\n }\n sheetString += (colString + ' ');\n }\n sheetString += ('');\n sheetBlob.append(sheetString);\n sheetString = '';\n if (sheet.rows !== undefined) {\n for (var _b = 0, _c = sheet.rows; _b < _c.length; _b++) {\n var row = _c[_b];\n var rowString = '');\n for (var _d = 0, _e = row.cells; _d < _e.length; _d++) {\n var cell = _e[_d];\n if (cell !== undefined && (cell.value !== undefined || cell.cellStyle !== undefined)) {\n rowString += ('');\n if (cell.value !== undefined) {\n rowString += ('' + cell.value + ' ');\n }\n else {\n rowString += ('');\n }\n }\n }\n rowString += ('
');\n sheetBlob.append(rowString);\n }\n }\n sheetString += (' ');\n if (sheet.mergeCells.length > 0) {\n sheetString += ('');\n for (var _f = 0, _g = sheet.mergeCells; _f < _g.length; _f++) {\n var mCell = _g[_f];\n sheetString += (' ');\n }\n sheetString += (' ');\n }\n if (sheet.hyperLinks.length > 0) {\n sheetString += ('');\n for (var _h = 0, _j = sheet.hyperLinks; _h < _j.length; _h++) {\n var hLink = _j[_h];\n sheetString += (' ');\n }\n sheetString += (' ');\n this.addToArchive(this.saveSheetRelations(sheet), ('xl/worksheets/_rels/sheet' + sheet.index + '.xml.rels'));\n }\n /* tslint:disable-next-line:max-line-length */\n sheetString += (' ');\n sheetBlob.append(sheetString);\n this.addToArchive(sheetBlob.getBlob(), 'xl/worksheets' + '/sheet' + (index + 1) + '.xml');\n };\n Workbook.prototype.pixelsToColumnWidth = function (pixels) {\n var dDigitWidth = 7;\n var val = (pixels > dDigitWidth + 5) ?\n this.trunc((pixels - 5) / dDigitWidth * 100 + 0.5) / 100 :\n pixels / (dDigitWidth + 5);\n return (val > 1) ?\n ((val * dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0 :\n (val * (dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0;\n };\n Workbook.prototype.trunc = function (x) {\n var n = x - x % 1;\n return n === 0 && (x < 0 || (x === 0 && (1 / x !== 1 / 0))) ? -0 : n;\n };\n Workbook.prototype.pixelsToRowHeight = function (pixels) {\n return (pixels * this.unitsProportions[5] / this.unitsProportions[6]);\n };\n Workbook.prototype.saveSheetRelations = function (sheet) {\n /* tslint:disable-next-line:max-line-length */\n var relStr = '';\n for (var _i = 0, _a = sheet.hyperLinks; _i < _a.length; _i++) {\n var hLink = _a[_i];\n /* tslint:disable-next-line:max-line-length */\n relStr += ' ';\n }\n relStr += ' ';\n return relStr;\n };\n Workbook.prototype.saveFreezePanes = function (sheet) {\n var paneString = ' ';\n return paneString;\n };\n Workbook.prototype.saveSharedString = function () {\n var length = this.sharedString.length;\n if (length > 0) {\n /* tslint:disable-next-line:max-line-length */\n var sstStart = '';\n var si = '';\n for (var i = 0; i < length; i++) {\n si += '';\n si += this.processString(this.sharedString[i]);\n si += ' ';\n }\n si += ' ';\n this.addToArchive(sstStart + si, 'xl/sharedStrings.xml');\n }\n };\n Workbook.prototype.processString = function (value) {\n if (value.indexOf('&') !== -1) {\n value = value.replace(/&/g, '&');\n }\n if (value.indexOf('<') !== -1) {\n value = value.replace(/') !== -1) {\n value = value.replace(/>/g, '>');\n }\n return value;\n };\n Workbook.prototype.saveStyles = function () {\n this.updateCellXfsStyleXfs();\n /* tslint:disable-next-line:max-line-length */\n var styleTemp = '';\n styleTemp += this.saveNumberFormats();\n styleTemp += this.saveFonts();\n styleTemp += this.saveFills();\n styleTemp += this.saveBorders();\n styleTemp += this.saveCellStyleXfs();\n styleTemp += this.saveCellXfs();\n styleTemp += this.saveCellStyles();\n this.addToArchive(styleTemp + ' ', 'xl/styles.xml');\n };\n Workbook.prototype.updateCellXfsStyleXfs = function () {\n for (var _i = 0, _a = this.mStyles; _i < _a.length; _i++) {\n var style = _a[_i];\n var cellXfs = undefined;\n if (style.isGlobalStyle) {\n cellXfs = new CellStyleXfs();\n cellXfs.xfId = (style.index - 1);\n }\n else {\n cellXfs = new CellXfs();\n cellXfs.xfId = 0;\n }\n //Add font\n var compareFontResult = this.isNewFont(style);\n if (!compareFontResult.result) {\n var font = new Font();\n font.b = style.bold;\n font.i = style.italic;\n font.name = style.fontName;\n font.sz = style.fontSize;\n font.u = style.underline;\n font.color = ('FF' + style.fontColor.replace('#', ''));\n this.mFonts.push(font);\n cellXfs.fontId = this.mFonts.length - 1;\n }\n else {\n cellXfs.fontId = compareFontResult.index;\n }\n //Add fill\n if (style.backColor !== 'none') {\n var backColor = 'FF' + style.backColor.replace('#', '');\n if (this.mFills.has(backColor)) {\n var fillId = this.mFills.get(backColor);\n cellXfs.fillId = fillId;\n }\n else {\n var fillId = this.mFills.size + 2;\n this.mFills.set(backColor, fillId);\n cellXfs.fillId = (fillId);\n }\n }\n else {\n cellXfs.fillId = 0;\n }\n //Add border \n if (!this.isNewBorder(style)) {\n this.mBorders.push(style.borders);\n cellXfs.borderId = this.mBorders.length;\n }\n else {\n cellXfs.borderId = 0;\n }\n //Add Number Format \n if (style.numberFormat !== 'GENERAL') {\n if (this.mNumFmt.has(style.numberFormat)) {\n var numFmt = this.mNumFmt.get(style.numberFormat);\n cellXfs.numFmtId = numFmt.numFmtId;\n }\n else {\n var id = this.mNumFmt.size + 164;\n this.mNumFmt.set(style.numberFormat, new NumFmt(id, style.numberFormat));\n cellXfs.numFmtId = id;\n }\n }\n else {\n if (style.numberFormat === 'GENERAL' && style.numFmtId === 14) {\n cellXfs.numFmtId = 14;\n }\n else {\n cellXfs.numFmtId = 0;\n }\n }\n //Add alignment \n if (!style.isGlobalStyle) {\n cellXfs.applyAlignment = 1;\n }\n cellXfs.alignment = new Alignment();\n cellXfs.alignment.indent = style.indent;\n cellXfs.alignment.horizontal = style.hAlign;\n cellXfs.alignment.vertical = style.vAlign;\n cellXfs.alignment.wrapText = style.wrapText ? 1 : 0;\n if (style.isGlobalStyle) {\n this.mCellStyleXfs.push(cellXfs);\n this.mCellXfs.push(cellXfs);\n }\n else {\n //Add cellxfs\n this.mCellXfs.push(cellXfs);\n }\n }\n };\n Workbook.prototype.saveNumberFormats = function () {\n if (this.mNumFmt.size >= 1) {\n var numFmtStyle_1 = '';\n this.mNumFmt.forEach(function (value, key) {\n numFmtStyle_1 += ' ';\n });\n return (numFmtStyle_1 += ' ');\n }\n else {\n return '';\n }\n };\n Workbook.prototype.saveFonts = function () {\n /* tslint:disable-next-line:max-line-length */\n var fontStyle = '';\n if (this.mFonts.length >= 1) {\n for (var _i = 0, _a = this.mFonts; _i < _a.length; _i++) {\n var font = _a[_i];\n fontStyle += '';\n if (font.b) {\n fontStyle += ' ';\n }\n if (font.i) {\n fontStyle += ' ';\n }\n if (font.u) {\n fontStyle += ' ';\n }\n fontStyle += ' ';\n fontStyle += ' ';\n fontStyle += ' ';\n }\n }\n return fontStyle + ' ';\n };\n Workbook.prototype.saveFills = function () {\n /* tslint:disable-next-line:max-line-length */\n var fillsStyle = ' ';\n if (this.mFills.size >= 1) {\n this.mFills.forEach(function (value, key) {\n /* tslint:disable-next-line:max-line-length */\n fillsStyle += ' ';\n });\n }\n return fillsStyle + ' ';\n };\n Workbook.prototype.saveBorders = function () {\n /* tslint:disable-next-line:max-line-length */\n var bordersStyle = ' ';\n if (this.mBorders.length >= 1) {\n for (var _i = 0, _a = this.mBorders; _i < _a.length; _i++) {\n var borders = _a[_i];\n if (this.isAllBorder(borders)) {\n var color = borders.all.color.replace('#', '');\n var lineStyle = borders.all.lineStyle;\n /* tslint:disable-next-line:max-line-length */\n bordersStyle += ' ';\n }\n else {\n /* tslint:disable-next-line:max-line-length */\n bordersStyle += ' ';\n }\n }\n }\n return bordersStyle + ' ';\n };\n Workbook.prototype.saveCellStyles = function () {\n var _this = this;\n var cellStyleString = '';\n this.cellStyles.forEach(function (value, key) {\n cellStyleString += ' ';\n });\n return cellStyleString += ' ';\n };\n Workbook.prototype.saveCellStyleXfs = function () {\n /* tslint:disable-next-line:max-line-length */\n var cellXfsStyle = ' ';\n if (this.mCellStyleXfs.length >= 1) {\n for (var _i = 0, _a = this.mCellStyleXfs; _i < _a.length; _i++) {\n var cellStyleXf = _a[_i];\n /* tslint:disable-next-line:max-line-length */\n cellXfsStyle += '' + this.saveAlignment(cellStyleXf) + ' ';\n }\n else {\n cellXfsStyle += ' />';\n }\n }\n }\n return cellXfsStyle + ' ';\n };\n Workbook.prototype.saveCellXfs = function () {\n /* tslint:disable-next-line:max-line-length */\n var cellXfsStyle = ' ';\n if (this.mCellXfs.length >= 1) {\n for (var _i = 0, _a = this.mCellXfs; _i < _a.length; _i++) {\n var cellXf = _a[_i];\n /* tslint:disable-next-line:max-line-length */\n cellXfsStyle += '' + this.saveAlignment(cellXf) + ' ';\n }\n }\n return cellXfsStyle + ' ';\n };\n Workbook.prototype.saveAlignment = function (cellXf) {\n var alignString = ' ';\n return alignString;\n };\n Workbook.prototype.saveApp = function (builtInProperties) {\n /* tslint:disable-next-line:max-line-length */\n var appString = 'Essential XlsIO ';\n if (builtInProperties !== undefined) {\n if (builtInProperties.manager !== undefined) {\n appString += '' + builtInProperties.manager + ' ';\n }\n if (builtInProperties.company !== undefined) {\n appString += '' + builtInProperties.company + ' ';\n }\n }\n this.addToArchive((appString + ' '), 'docProps/app.xml');\n };\n Workbook.prototype.saveCore = function (builtInProperties) {\n var createdDate = new Date();\n /* tslint:disable-next-line:max-line-length */\n var coreString = '';\n if (this.builtInProperties !== undefined) {\n if (builtInProperties.author !== undefined) {\n coreString += '' + builtInProperties.author + ' ';\n }\n if (builtInProperties.subject !== undefined) {\n coreString += '' + builtInProperties.subject + ' ';\n }\n if (builtInProperties.category !== undefined) {\n coreString += '' + builtInProperties.category + ' ';\n }\n if (builtInProperties.comments !== undefined) {\n coreString += '' + builtInProperties.comments + ' ';\n }\n if (builtInProperties.title !== undefined) {\n coreString += '' + builtInProperties.title + ' ';\n }\n if (builtInProperties.tags !== undefined) {\n coreString += '' + builtInProperties.tags + ' ';\n }\n if (builtInProperties.status !== undefined) {\n coreString += '' + builtInProperties.status + ' ';\n }\n if (builtInProperties.createdDate !== undefined) {\n /* tslint:disable-next-line:max-line-length */\n coreString += '' + builtInProperties.createdDate.toISOString() + ' ';\n }\n else {\n coreString += '' + createdDate.toISOString() + ' ';\n }\n if (builtInProperties.modifiedDate !== undefined) {\n /* tslint:disable-next-line:max-line-length */\n coreString += '' + builtInProperties.modifiedDate.toISOString() + ' ';\n }\n else {\n coreString += '' + createdDate.toISOString() + ' ';\n }\n }\n else {\n coreString += '' + createdDate.toISOString() + ' ';\n coreString += '' + createdDate.toISOString() + ' ';\n }\n /* tslint:disable-next-line:max-line-length */\n coreString += ' ';\n this.addToArchive(coreString, 'docProps/core.xml');\n };\n Workbook.prototype.saveTopLevelRelation = function () {\n /* tslint:disable-next-line:max-line-length */\n var topRelation = ' ';\n this.addToArchive(topRelation, '_rels/.rels');\n };\n Workbook.prototype.saveWorkbookRelation = function () {\n /* tslint:disable-next-line:max-line-length */\n var wbRelation = '';\n var length = this.worksheets.length;\n var count = 0;\n for (var i = 0; i < length; i++, count++) {\n /* tslint:disable-next-line:max-line-length */\n wbRelation += ' ';\n }\n /* tslint:disable-next-line:max-line-length */\n wbRelation += ' ';\n if (this.sharedStringCount > 0) {\n /* tslint:disable-next-line:max-line-length */\n wbRelation += ' ';\n }\n this.addToArchive((wbRelation + ' '), 'xl/_rels/workbook.xml.rels');\n };\n Workbook.prototype.saveContentType = function () {\n /* tslint:disable-next-line:max-line-length */\n var contentTypeString = ' ';\n var sheetsOverride = '';\n var length = this.worksheets.length;\n for (var i = 0; i < length; i++) {\n /* tslint:disable-next-line:max-line-length */\n sheetsOverride += ' ';\n }\n if (this.sharedStringCount > 0) {\n /* tslint:disable-next-line:max-line-length */\n contentTypeString += ' ';\n }\n this.addToArchive((contentTypeString + sheetsOverride + ' '), '[Content_Types].xml');\n };\n Workbook.prototype.addToArchive = function (xmlString, itemName) {\n if (typeof (xmlString) === 'string') {\n var blob = new Blob([xmlString], { type: 'text/plain' });\n var archiveItem = new ZipArchiveItem(blob, itemName);\n this.mArchive.addItem(archiveItem);\n }\n else {\n var archiveItem = new ZipArchiveItem(xmlString, itemName);\n this.mArchive.addItem(archiveItem);\n }\n };\n Workbook.prototype.processMergeCells = function (cell, rowIndex, mergeCells) {\n if (cell.rowSpan !== 0 || cell.colSpan !== 0) {\n var mCell = new MergeCell();\n mCell.x = cell.index;\n mCell.width = cell.colSpan;\n mCell.y = rowIndex;\n mCell.height = cell.rowSpan;\n var startCell = this.getCellName(mCell.y, mCell.x);\n var endCell = this.getCellName(rowIndex + mCell.height, cell.index + mCell.width);\n mCell.ref = startCell + ':' + endCell;\n var mergedCell = mergeCells.add(mCell);\n var start = { x: mCell.x, y: mCell.y };\n var end = {\n x: (cell.index + mCell.width), y: (rowIndex + mCell.height)\n };\n this.updatedMergedCellStyles(start, end, cell);\n }\n return mergeCells;\n };\n Workbook.prototype.updatedMergedCellStyles = function (sCell, eCell, cell) {\n for (var x = sCell.x; x <= eCell.x; x++) {\n for (var y = sCell.y; y <= eCell.y; y++) {\n this.mergedCellsStyle.set(this.getCellName(y, x), { x: x, y: y, styleIndex: cell.styleIndex });\n }\n }\n };\n /**\n * Returns the tick count corresponding to the given year, month, and day.\n * @param year number value of year\n * @param month number value of month\n * @param day number value of day\n */\n Workbook.prototype.dateToTicks = function (year, month, day) {\n var ticksPerDay = 10000 * 1000 * 60 * 60 * 24;\n var daysToMonth365 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];\n var daysToMonth366 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366];\n if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) {\n var days = this.isLeapYear(year) ? daysToMonth366 : daysToMonth365;\n var y = year - 1;\n var n = y * 365 + ((y / 4) | 0) - ((y / 100) | 0) + ((y / 400) | 0) + days[month - 1] + day - 1;\n return n * ticksPerDay;\n }\n throw new Error('Not a valid date');\n };\n /**\n * Return the tick count corresponding to the given hour, minute, second.\n * @param hour number value of hour\n * @param minute number value if minute\n * @param second number value of second\n */\n Workbook.prototype.timeToTicks = function (hour, minute, second) {\n if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) {\n var totalSeconds = hour * 3600 + minute * 60 + second;\n return totalSeconds * 10000 * 1000;\n }\n throw new Error('Not valid time');\n };\n /**\n * Checks if given year is a leap year.\n * @param year Year value.\n */\n Workbook.prototype.isLeapYear = function (year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n };\n /**\n * Converts `DateTime` to the equivalent OLE Automation date.\n */\n Workbook.prototype.toOADate = function (date) {\n var ticks = 0;\n /* tslint:disable-next-line:max-line-length */\n ticks = this.dateToTicks(date.getFullYear(), (date.getMonth() + 1), date.getDate()) + this.timeToTicks(date.getHours(), date.getMinutes(), date.getSeconds());\n if (ticks === 0) {\n return 0.0;\n }\n var ticksPerDay = 10000 * 1000 * 60 * 60 * 24;\n var daysTo1899 = (((365 * 4 + 1) * 25 - 1) * 4 + 1) * 4 + ((365 * 4 + 1) * 25 - 1) * 3 - 367;\n var doubleDateOffset = daysTo1899 * ticksPerDay;\n var oaDateMinAsTicks = (((365 * 4 + 1) * 25 - 1) - 365) * ticksPerDay;\n if (ticks < oaDateMinAsTicks) {\n throw new Error('Arg_OleAutDateInvalid');\n }\n var millisPerDay = 1000 * 60 * 60 * 24;\n return ((ticks - doubleDateOffset) / 10000) / millisPerDay;\n };\n return Workbook;\n}());\nexport { Workbook };\nvar BuiltInProperties = /** @class */ (function () {\n function BuiltInProperties() {\n }\n return BuiltInProperties;\n}());\nexport { BuiltInProperties };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Internationalization, setCulture } from '@syncfusion/ej2-base';\n/**\n * ValueFormatter class to globalize the value.\n * @hidden\n */\nvar ValueFormatter = /** @class */ (function () {\n function ValueFormatter(cultureName) {\n this.intl = new Internationalization();\n if (!isNullOrUndefined(cultureName)) {\n this.intl.culture = cultureName;\n }\n }\n ValueFormatter.prototype.getFormatFunction = function (format) {\n if (format.type) {\n return this.intl.getDateFormat(format);\n }\n else {\n return this.intl.getNumberFormat(format);\n }\n };\n ValueFormatter.prototype.getParserFunction = function (format) {\n if (format.type) {\n return this.intl.getDateParser(format);\n }\n else {\n return this.intl.getNumberParser(format);\n }\n };\n ValueFormatter.prototype.fromView = function (value, format, type) {\n if (type === 'date' || type === 'datetime' || type === 'number') {\n return format(value);\n }\n else {\n return value;\n }\n };\n ValueFormatter.prototype.toView = function (value, format) {\n var result = value;\n if (!isNullOrUndefined(format) && !isNullOrUndefined(value)) {\n result = format(value);\n }\n return result;\n };\n ValueFormatter.prototype.setCulture = function (cultureName) {\n if (!isNullOrUndefined(cultureName)) {\n setCulture(cultureName);\n }\n };\n return ValueFormatter;\n}());\nexport { ValueFormatter };\n","import { merge, isNullOrUndefined, getValue, extend } from '@syncfusion/ej2-base';\nimport { Query, DataUtil } from '@syncfusion/ej2-data';\nimport { ValueFormatter } from '../services/value-formatter';\nimport { getUid, templateCompiler, getForeignData } from '../base/util';\n/**\n * Represents Grid `Column` model class.\n */\nvar Column = /** @class */ (function () {\n function Column(options) {\n var _this = this;\n /**\n * If `allowSorting` set to false, then it disables sorting option of a particular column.\n * By default all columns are sortable.\n * @default true\n */\n this.allowSorting = true;\n /**\n * If `allowResizing` is set to false, it disables resize option of a particular column.\n * By default all the columns can be resized.\n * @default true\n */\n this.allowResizing = true;\n /**\n * If `allowFiltering` set to false, then it disables filtering option and filter bar element of a particular column.\n * By default all columns are filterable.\n * @default true\n */\n this.allowFiltering = true;\n /**\n * If `allowGrouping` set to false, then it disables grouping of a particular column.\n * By default all columns are groupable.\n * @default true\n */\n this.allowGrouping = true;\n /**\n * If `allowReordering` set to false, then it disables reorder of a particular column.\n * By default all columns can be reorder.\n * @default true\n */\n this.allowReordering = true;\n /**\n * If `showColumnMenu` set to false, then it disable the column menu of a particular column.\n * By default column menu will show for all columns\n * @default true\n */\n this.showColumnMenu = true;\n /**\n * If `enableGroupByFormat` set to true, then it groups the particular column by formatted values.\n * @default true\n */\n this.enableGroupByFormat = false;\n /**\n * If `allowEditing` set to false, then it disables editing of a particular column.\n * By default all columns are editable.\n * @default true\n */\n this.allowEditing = true;\n /**\n * It is used to customize the default filter options for a specific columns.\n * * type - Specifies the filter type as menu or checkbox.\n * * ui - to render custom component for specific column it has following functions.\n * * ui.create – It is used for creating custom components.\n * * ui.read - It is used for read the value from the component.\n * * ui.write - It is used to apply component model as dynamically.\n * {% codeBlock src=\"grid/filter-menu-api/index.ts\" %}{% endcodeBlock %}\n *\n * > Check the [`Filter UI`](./filtering.html#custom-component-in-filter-menu) for its customization.\n * @default null\n */\n this.filter = {};\n /**\n * If `showInColumnChooser` set to false, then hide the particular column in column chooser.\n * By default all columns are displayed in column Chooser.\n * @default true\n */\n this.showInColumnChooser = true;\n /**\n * Defines the `IEditCell` object to customize default edit cell.\n * @default {}\n */\n this.edit = {};\n this.sortDirection = 'Descending';\n merge(this, options);\n this.uid = getUid('grid-column');\n var valueFormatter = new ValueFormatter();\n if (options.format && (options.format.skeleton || options.format.format)) {\n this.setFormatter(valueFormatter.getFormatFunction(options.format));\n this.setParser(valueFormatter.getParserFunction(options.format));\n }\n if (!this.field) {\n this.allowFiltering = false;\n this.allowGrouping = false;\n this.allowSorting = false;\n }\n if (this.commands && !this.textAlign) {\n this.textAlign = 'Right';\n }\n if (this.template || this.commandsTemplate) {\n this.templateFn = templateCompiler(this.template || this.commandsTemplate);\n }\n if (this.headerTemplate) {\n this.headerTemplateFn = templateCompiler(this.headerTemplate);\n }\n if (this.filter.itemTemplate) {\n this.fltrTemplateFn = templateCompiler(this.filter.itemTemplate);\n }\n if (this.isForeignColumn() && (isNullOrUndefined(this.editType) || this.editType === 'dropdownedit')) {\n this.editType = 'dropdownedit';\n this.edit.params = extend({\n dataSource: this.dataSource,\n query: new Query(), fields: { value: this.foreignKeyField || this.field, text: this.foreignKeyValue }\n }, this.edit.params);\n }\n if (this.sortComparer) {\n var a_1 = this.sortComparer;\n this.sortComparer = function comparer(x, y) {\n if (typeof a_1 === 'string') {\n a_1 = getValue(a_1, window);\n }\n if (this.sortDirection === 'Descending') {\n var z = x;\n x = y;\n y = z;\n }\n return a_1(x, y);\n };\n }\n if (!this.sortComparer && this.isForeignColumn()) {\n this.sortComparer = function (x, y) {\n x = getValue(_this.foreignKeyValue, getForeignData(_this, {}, x)[0]);\n y = getValue(_this.foreignKeyValue, getForeignData(_this, {}, y)[0]);\n return _this.sortDirection === 'Descending' ? DataUtil.fnDescending(x, y) : DataUtil.fnAscending(x, y);\n };\n }\n }\n /** @hidden */\n Column.prototype.getSortDirection = function () {\n return this.sortDirection;\n };\n /** @hidden */\n Column.prototype.setSortDirection = function (direction) {\n this.sortDirection = direction;\n };\n /** @hidden */\n Column.prototype.setProperties = function (column) {\n //Angular two way binding\n var keys = Object.keys(column);\n for (var i = 0; i < keys.length; i++) {\n this[keys[i]] = column[keys[i]];\n }\n };\n /**\n * @hidden\n * It defines the column is foreign key column or not.\n */\n Column.prototype.isForeignColumn = function () {\n return !!(this.dataSource && this.foreignKeyValue);\n };\n /** @hidden */\n Column.prototype.getFormatter = function () {\n return this.formatFn;\n };\n /** @hidden */\n Column.prototype.setFormatter = function (value) {\n this.formatFn = value;\n };\n /** @hidden */\n Column.prototype.getParser = function () {\n return this.parserFn;\n };\n /** @hidden */\n Column.prototype.setParser = function (value) {\n this.parserFn = value;\n };\n /** @hidden */\n Column.prototype.getColumnTemplate = function () {\n return this.templateFn;\n };\n /** @hidden */\n Column.prototype.getHeaderTemplate = function () {\n return this.headerTemplateFn;\n };\n /** @hidden */\n Column.prototype.getFilterItemTemplate = function () {\n return this.fltrTemplateFn;\n };\n /** @hidden */\n Column.prototype.getDomSetter = function () {\n return this.disableHtmlEncode ? 'textContent' : 'innerHTML';\n };\n return Column;\n}());\nexport { Column };\n","/** @hidden */\nexport var created = 'create';\n/** @hidden */\nexport var destroyed = 'destroy';\n/** @hidden */\nexport var load = 'load';\n/** @hidden */\nexport var rowDataBound = 'rowDataBound';\n/** @hidden */\nexport var queryCellInfo = 'queryCellInfo';\n/** @hidden */\nexport var headerCellInfo = 'headerCellInfo';\n/** @hidden */\nexport var actionBegin = 'actionBegin';\n/** @hidden */\nexport var actionComplete = 'actionComplete';\n/** @hidden */\nexport var actionFailure = 'actionFailure';\n/** @hidden */\nexport var dataBound = 'dataBound';\n/** @hidden */\nexport var rowSelecting = 'rowSelecting';\n/** @hidden */\nexport var rowSelected = 'rowSelected';\n/** @hidden */\nexport var rowDeselecting = 'rowDeselecting';\n/** @hidden */\nexport var rowDeselected = 'rowDeselected';\n/** @hidden */\nexport var cellSelecting = 'cellSelecting';\n/** @hidden */\nexport var cellSelected = 'cellSelected';\n/** @hidden */\nexport var cellDeselecting = 'cellDeselecting';\n/** @hidden */\nexport var cellDeselected = 'cellDeselected';\n/** @hidden */\nexport var columnDragStart = 'columnDragStart';\n/** @hidden */\nexport var columnDrag = 'columnDrag';\n/** @hidden */\nexport var columnDrop = 'columnDrop';\n/** @hidden */\nexport var rowDragStart = 'rowDragStart';\n/** @hidden */\nexport var rowDrag = 'rowDrag';\n/** @hidden */\nexport var rowDrop = 'rowDrop';\n/** @hidden */\nexport var beforePrint = 'beforePrint';\n/** @hidden */\nexport var printComplete = 'printComplete';\n/** @hidden */\nexport var detailDataBound = 'detailDataBound';\n/** @hidden */\nexport var toolbarClick = 'toolbarClick';\n/** @hidden */\nexport var batchAdd = 'batchAdd';\n/** @hidden */\nexport var batchCancel = 'batchCancel';\n/** @hidden */\nexport var batchDelete = 'batchDelete';\n/** @hidden */\nexport var beforeBatchAdd = 'beforeBatchAdd';\n/** @hidden */\nexport var beforeBatchDelete = 'beforeBatchDelete';\n/** @hidden */\nexport var beforeBatchSave = 'beforeBatchSave';\n/** @hidden */\nexport var beginEdit = 'beginEdit';\n/** @hidden */\nexport var cellEdit = 'cellEdit';\n/** @hidden */\nexport var cellSave = 'cellSave';\n/** @hidden */\nexport var cellSaved = 'cellSaved';\n/** @hidden */\nexport var endAdd = 'endAdd';\n/** @hidden */\nexport var endDelete = 'endDelete';\n/** @hidden */\nexport var endEdit = 'endEdit';\n/** @hidden */\nexport var recordDoubleClick = 'recordDoubleClick';\n/** @hidden */\nexport var recordClick = 'recordClick';\n/** @hidden */\nexport var beforeDataBound = 'beforeDataBound';\n/** @hidden */\nexport var beforeOpenColumnChooser = 'beforeOpenColumnChooser';\n/** @hidden */\nexport var resizeStart = 'resizeStart';\n/** @hidden */\nexport var onResize = 'resizing';\n/** @hidden */\nexport var resizeStop = 'resizeStop';\n/** @hidden */\nexport var checkBoxChange = 'checkBoxChange';\n/** @hidden */\nexport var beforeCopy = 'beforeCopy';\n/** @hidden */\nexport var filterChoiceRequest = 'filterchoicerequest';\n/** @hidden */\nexport var filterAfterOpen = 'filterafteropen';\n/** @hidden */\nexport var filterBeforeOpen = 'filterbeforeopen';\n/** @hidden */\nexport var filterSearchBegin = 'filtersearchbegin';\n/**\n * Specifies grid internal events\n */\n/** @hidden */\nexport var initialLoad = 'initial-load';\n/** @hidden */\nexport var initialEnd = 'initial-end';\n/** @hidden */\nexport var dataReady = 'data-ready';\n/** @hidden */\nexport var contentReady = 'content-ready';\n/** @hidden */\nexport var uiUpdate = 'ui-update';\n/** @hidden */\nexport var onEmpty = 'on-empty';\n/** @hidden */\nexport var inBoundModelChanged = 'inbound-model-changed';\n/** @hidden */\nexport var modelChanged = 'model-changed';\n/** @hidden */\nexport var colGroupRefresh = 'colgroup-refresh';\n/** @hidden */\nexport var headerRefreshed = 'header-refreshed';\n/** @hidden */\nexport var pageBegin = 'paging-begin';\n/** @hidden */\nexport var pageComplete = 'paging-complete';\n/** @hidden */\nexport var sortBegin = 'sorting-begin';\n/** @hidden */\nexport var sortComplete = 'sorting-complete';\n/** @hidden */\nexport var filterBegin = 'filtering-begin';\n/** @hidden */\nexport var filterComplete = 'filtering-complete';\n/** @hidden */\nexport var searchBegin = 'searching-begin';\n/** @hidden */\nexport var searchComplete = 'searching-complete';\n/** @hidden */\nexport var reorderBegin = 'reorder-begin';\n/** @hidden */\nexport var reorderComplete = 'reorder-complete';\n/** @hidden */\nexport var rowDragAndDropBegin = 'rowdraganddrop-begin';\n/** @hidden */\nexport var rowDragAndDropComplete = 'rowdraganddrop-complete';\n/** @hidden */\nexport var groupBegin = 'grouping-begin';\n/** @hidden */\nexport var groupComplete = 'grouping-complete';\n/** @hidden */\nexport var ungroupBegin = 'ungrouping-begin';\n/** @hidden */\nexport var ungroupComplete = 'ungrouping-complete';\n/** @hidden */\nexport var rowSelectionBegin = 'rowselecting';\n/** @hidden */\nexport var rowSelectionComplete = 'rowselected';\n/** @hidden */\nexport var columnSelectionBegin = 'columnselecting';\n/** @hidden */\nexport var columnSelectionComplete = 'columnselected';\n/** @hidden */\nexport var cellSelectionBegin = 'cellselecting';\n/** @hidden */\nexport var cellSelectionComplete = 'cellselected';\n/** @hidden */\nexport var beforeCellFocused = 'beforecellfocused';\n/** @hidden */\nexport var cellFocused = 'cellfocused';\n/** @hidden */\nexport var keyPressed = 'key-pressed';\n/** @hidden */\nexport var click = 'click';\n/** @hidden */\nexport var destroy = 'destroy';\n/** @hidden */\nexport var columnVisibilityChanged = 'column-visible-changed';\n/** @hidden */\nexport var scroll = 'scroll';\n/** @hidden */\nexport var columnWidthChanged = 'column-width-changed';\n/** @hidden */\nexport var columnPositionChanged = 'column-position-changed';\n/** @hidden */\nexport var rowDragAndDrop = 'row-drag-and-drop';\n/** @hidden */\nexport var rowsAdded = 'rows-added';\n/** @hidden */\nexport var rowsRemoved = 'rows-removed';\n/** @hidden */\nexport var columnDragStop = 'column-drag-stop';\n/** @hidden */\nexport var headerDrop = 'header-drop';\n/** @hidden */\nexport var dataSourceModified = 'datasource-modified';\n/** @hidden */\nexport var refreshComplete = 'refresh-complete';\n/** @hidden */\nexport var refreshVirtualBlock = 'refresh-virtual-block';\n/** @hidden */\nexport var dblclick = 'dblclick';\n/** @hidden */\nexport var toolbarRefresh = 'toolbar-refresh';\n/** @hidden */\nexport var bulkSave = 'bulk-save';\n/** @hidden */\nexport var autoCol = 'auto-col';\n/** @hidden */\nexport var tooltipDestroy = 'tooltip-destroy';\n/** @hidden */\nexport var updateData = 'update-data';\n/** @hidden */\nexport var editBegin = 'edit-begin';\n/** @hidden */\nexport var editComplete = 'edit-complete';\n/** @hidden */\nexport var addBegin = 'add-begin';\n/** @hidden */\nexport var addComplete = 'add-complete';\n/** @hidden */\nexport var saveComplete = 'save-complete';\n/** @hidden */\nexport var deleteBegin = 'delete-begin';\n/** @hidden */\nexport var deleteComplete = 'delete-complete';\n/** @hidden */\nexport var preventBatch = 'prevent-batch';\n/** @hidden */\nexport var dialogDestroy = 'dialog-destroy';\n/** @hidden */\nexport var crudAction = 'crud-Action';\n/** @hidden */\nexport var addDeleteAction = 'add-delete-Action';\n/** @hidden */\nexport var destroyForm = 'destroy-form';\n/** @hidden */\nexport var doubleTap = 'double-tap';\n/** @hidden */\nexport var beforeExcelExport = 'beforeExcelExport';\n/** @hidden */\nexport var excelExportComplete = 'excelExportComplete';\n/** @hidden */\nexport var excelQueryCellInfo = 'excelQueryCellInfo';\n/** @hidden */\nexport var excelHeaderQueryCellInfo = 'excelHeaderQueryCellInfo';\n/** @hidden */\nexport var beforePdfExport = 'beforePdfExport';\n/** @hidden */\nexport var pdfExportComplete = 'pdfExportComplete';\n/** @hidden */\nexport var pdfQueryCellInfo = 'pdfQueryCellInfo';\n/** @hidden */\nexport var pdfHeaderQueryCellInfo = 'pdfHeaderQueryCellInfo';\n/** @hidden */\nexport var accessPredicate = 'access-predicate';\n/** @hidden */\nexport var contextMenuClick = 'contextMenuClick';\n/** @hidden */\nexport var freezeRender = 'freezerender';\n/** @hidden */\nexport var freezeRefresh = 'freezerefresh';\n/** @hidden */\nexport var contextMenuOpen = 'contextMenuOpen';\n/** @hidden */\nexport var columnMenuClick = 'columnMenuClick';\n/** @hidden */\nexport var columnMenuOpen = 'columnMenuOpen';\n/** @hidden */\nexport var filterOpen = 'filterOpen';\n/** @hidden */\nexport var filterDialogCreated = 'filterDialogCreated';\n/** @hidden */\nexport var filterMenuClose = 'filter-menu-close';\n/** @hidden */\nexport var initForeignKeyColumn = 'initForeignKeyColumn';\n/** @hidden */\nexport var getForeignKeyData = 'getForeignKeyData';\n/** @hidden */\nexport var generateQuery = 'generateQuery';\n/** @hidden */\nexport var showEmptyGrid = 'showEmptyGrid';\n/** @hidden */\nexport var foreignKeyData = 'foreignKeyData';\n/** @hidden */\nexport var dataStateChange = 'dataStateChange';\n/** @hidden */\nexport var dataSourceChanged = 'dataSourceChanged';\n/** @hidden */\nexport var rtlUpdated = 'rtl-updated';\n/** @hidden */\nexport var beforeFragAppend = 'beforeFragAppend';\n/** @hidden */\nexport var frozenHeight = 'frozenHeight';\n/** @hidden */\nexport var recordAdded = 'recordAdded';\n/** @hidden */\nexport var cancelBegin = 'cancel-Begin';\n/** @hidden */\nexport var editNextValCell = 'editNextValCell';\n","/* tslint:disable-next-line:max-line-length */\nimport { EventHandler, isNullOrUndefined, extend, classList, addClass, removeClass, Browser, getValue, setValue } from '@syncfusion/ej2-base';\nimport { parentsUntil, getUid, isActionPrevent, appendChildren, getDatePredicate } from '../base/util';\nimport { remove, debounce } from '@syncfusion/ej2-base';\nimport { DataUtil, Query, DataManager, Predicate, UrlAdaptor, Deferred } from '@syncfusion/ej2-data';\nimport { createCheckBox } from '@syncfusion/ej2-buttons';\nimport * as events from '../base/constant';\nimport { ValueFormatter } from '../services/value-formatter';\nimport { getForeignData } from '../base/util';\nimport { Dialog } from '@syncfusion/ej2-popups';\nimport { Input } from '@syncfusion/ej2-inputs';\nimport { createSpinner, hideSpinner, showSpinner } from '@syncfusion/ej2-popups';\nimport { getFilterMenuPostion, toogleCheckbox, createCboxWithWrap, removeAddCboxClasses, getColumnByForeignKeyValue } from '../base/util';\n/**\n * @hidden\n * `CheckBoxFilter` module is used to handle filtering action.\n */\nvar CheckBoxFilter = /** @class */ (function () {\n /**\n * Constructor for checkbox filtering module\n * @hidden\n */\n function CheckBoxFilter(parent, filterSettings, serviceLocator) {\n this.existingPredicate = {};\n this.filterState = true;\n this.values = {};\n this.parent = parent;\n this.id = this.parent.element.id;\n this.serviceLocator = serviceLocator;\n this.filterSettings = filterSettings;\n this.valueFormatter = new ValueFormatter(this.parent.locale);\n this.cBoxTrue = createCheckBox(this.parent.createElement, false, { checked: true, label: ' ' });\n this.cBoxFalse = createCheckBox(this.parent.createElement, false, { checked: false, label: ' ' });\n this.cBoxTrue.insertBefore(this.parent.createElement('input', {\n className: 'e-chk-hidden', attrs: { type: 'checkbox' }\n }), this.cBoxTrue.firstChild);\n this.cBoxFalse.insertBefore(this.parent.createElement('input', {\n className: 'e-chk-hidden', attrs: { 'type': 'checkbox' }\n }), this.cBoxFalse.firstChild);\n this.cBoxFalse.querySelector('.e-frame').classList.add('e-uncheck');\n if (this.parent.enableRtl) {\n addClass([this.cBoxTrue, this.cBoxFalse], ['e-rtl']);\n }\n }\n /**\n * To destroy the filter bar.\n * @return {void}\n * @hidden\n */\n CheckBoxFilter.prototype.destroy = function () {\n this.closeDialog();\n };\n CheckBoxFilter.prototype.wireEvents = function () {\n EventHandler.add(this.dlg, 'click', this.clickHandler, this);\n this.searchHandler = debounce(this.searchBoxKeyUp, 200);\n EventHandler.add(this.dlg.querySelector('.e-searchinput'), 'keyup', this.searchHandler, this);\n };\n CheckBoxFilter.prototype.unWireEvents = function () {\n EventHandler.remove(this.dlg, 'click', this.clickHandler);\n var elem = this.dlg.querySelector('.e-searchinput');\n if (elem) {\n EventHandler.remove(elem, 'keyup', this.searchHandler);\n }\n };\n CheckBoxFilter.prototype.searchBoxClick = function (e) {\n var target = e.target;\n if (target.classList.contains('e-searchclear')) {\n this.sInput.value = '';\n this.refreshCheckboxes();\n this.updateSearchIcon();\n this.sInput.focus();\n }\n };\n CheckBoxFilter.prototype.searchBoxKeyUp = function (e) {\n this.refreshCheckboxes();\n this.updateSearchIcon();\n };\n CheckBoxFilter.prototype.updateSearchIcon = function () {\n if (this.sInput.value.length) {\n classList(this.sIcon, ['e-chkcancel-icon'], ['e-search-icon']);\n }\n else {\n classList(this.sIcon, ['e-search-icon'], ['e-chkcancel-icon']);\n }\n };\n /**\n * Gets the localized label by locale keyword.\n * @param {string} key\n * @return {string}\n */\n CheckBoxFilter.prototype.getLocalizedLabel = function (key) {\n return this.localeObj.getConstant(key);\n };\n CheckBoxFilter.prototype.updateDataSource = function () {\n var dataSource = this.options.dataSource;\n if (!(dataSource instanceof DataManager)) {\n for (var i = 0; i < dataSource.length; i++) {\n if (typeof dataSource !== 'object') {\n var obj = {};\n obj[this.options.field] = dataSource[i];\n dataSource[i] = obj;\n }\n }\n }\n };\n CheckBoxFilter.prototype.updateModel = function (options) {\n this.options = options;\n this.existingPredicate = options.actualPredicate || {};\n this.options.dataSource = options.dataSource;\n this.updateDataSource();\n this.options.type = options.type || 'string';\n this.options.format = options.format || '';\n this.options.filteredColumns = options.filteredColumns || this.parent.filterSettings.columns;\n this.options.sortedColumns = options.sortedColumns || this.parent.sortSettings.columns;\n this.options.query = options.query || new Query();\n this.options.allowCaseSensitive = options.allowCaseSensitive || false;\n this.values = {};\n this.localeObj = options.localeObj;\n this.isFiltered = options.filteredColumns.length;\n };\n CheckBoxFilter.prototype.getAndSetChkElem = function (options) {\n this.dlg = this.parent.createElement('div', {\n id: this.id + this.options.type + '_excelDlg',\n className: 'e-checkboxfilter e-filter-popup'\n });\n this.sBox = this.parent.createElement('div', { className: 'e-searchcontainer' });\n if (!options.hideSearchbox) {\n this.sInput = this.parent.createElement('input', {\n id: this.id + '_SearchBox',\n className: 'e-searchinput'\n });\n this.sIcon = this.parent.createElement('span', {\n className: 'e-searchclear e-search-icon e-icons e-input-group-icon', attrs: {\n type: 'text', title: this.getLocalizedLabel('Search')\n }\n });\n this.searchBox = this.parent.createElement('span', { className: 'e-searchbox e-fields' });\n this.searchBox.appendChild(this.sInput);\n this.sBox.appendChild(this.searchBox);\n var inputargs = {\n element: this.sInput, floatLabelType: 'Never', properties: {\n placeholder: this.getLocalizedLabel('Search')\n }\n };\n Input.createInput(inputargs, this.parent.createElement);\n this.searchBox.querySelector('.e-input-group').appendChild(this.sIcon);\n }\n this.spinner = this.parent.createElement('div', { className: 'e-spinner' }); //for spinner\n this.cBox = this.parent.createElement('div', {\n id: this.id + this.options.type + '_CheckBoxList',\n className: 'e-checkboxlist e-fields'\n });\n this.spinner.appendChild(this.cBox);\n this.sBox.appendChild(this.spinner);\n return this.sBox;\n };\n CheckBoxFilter.prototype.showDialog = function (options) {\n var args = {\n requestType: events.filterBeforeOpen, filterModel: this,\n columnName: this.options.field, columnType: this.options.type, cancel: false\n };\n this.parent.trigger(events.actionBegin, args);\n if (args.cancel) {\n return;\n }\n this.dialogObj = new Dialog({\n visible: false, content: this.sBox,\n close: this.closeDialog.bind(this),\n width: (!isNullOrUndefined(parentsUntil(options.target, 'e-bigger')))\n || this.parent.element.classList.contains('e-device') ? 260 : 255,\n target: this.parent.element, animationSettings: { effect: 'None' },\n buttons: [{\n click: this.btnClick.bind(this),\n buttonModel: {\n content: this.getLocalizedLabel(this.isExcel ? 'OKButton' : 'FilterButton'),\n cssClass: 'e-primary', isPrimary: true\n }\n },\n {\n click: this.btnClick.bind(this),\n buttonModel: { cssClass: 'e-flat', content: this.getLocalizedLabel(this.isExcel ? 'CancelButton' : 'ClearButton') }\n }],\n created: this.dialogCreated.bind(this),\n open: this.dialogOpen.bind(this)\n });\n this.dialogObj.appendTo(this.dlg);\n this.dialogObj.element.style.maxHeight = '800px';\n this.dialogObj.show();\n this.wireEvents();\n createSpinner({ target: this.spinner }, this.parent.createElement);\n showSpinner(this.spinner);\n this.getAllData();\n };\n CheckBoxFilter.prototype.dialogCreated = function (e) {\n if (!Browser.isDevice) {\n getFilterMenuPostion(this.options.target, this.dialogObj, this.parent);\n }\n else {\n this.dialogObj.position = { X: 'center', Y: 'center' };\n }\n this.parent.notify(events.filterDialogCreated, e);\n };\n CheckBoxFilter.prototype.openDialog = function (options) {\n this.updateModel(options);\n this.getAndSetChkElem(options);\n this.showDialog(options);\n };\n CheckBoxFilter.prototype.closeDialog = function () {\n if (this.dialogObj && !this.dialogObj.isDestroyed) {\n this.parent.notify(events.filterMenuClose, { field: this.options.field });\n this.dialogObj.destroy();\n this.unWireEvents();\n remove(this.dlg);\n this.dlg = null;\n }\n };\n CheckBoxFilter.prototype.clearFilter = function () {\n if (isActionPrevent(this.parent)) {\n this.parent.notify(events.preventBatch, { instance: this, handler: this.clearFilter });\n return;\n }\n this.options.handler({ action: 'clear-filter', field: this.options.field });\n };\n CheckBoxFilter.prototype.btnClick = function (e) {\n if (this.filterState) {\n if (e.target.tagName.toLowerCase() === 'input') {\n var args = {\n action: 'filtering', filterCollection: {\n field: this.options.field,\n operator: this.options.column.type === 'date' || this.options.column.type === 'datetime' ? 'equal' : 'contains',\n value: e.target.value, matchCase: false, type: this.options.column.type\n },\n field: this.options.field\n };\n e.target.value ? this.options.handler(args) : this.closeDialog();\n }\n else {\n var text = e.target.firstChild.textContent.toLowerCase();\n if (this.getLocalizedLabel(this.isExcel ? 'OKButton' : 'FilterButton').toLowerCase() === text) {\n this.fltrBtnHandler();\n }\n else if (this.getLocalizedLabel('ClearButton').toLowerCase() === text) {\n this.clearFilter();\n }\n }\n this.closeDialog();\n }\n else if (!(e.target.tagName.toLowerCase() === 'input')) {\n this.clearFilter();\n this.closeDialog();\n }\n };\n CheckBoxFilter.prototype.fltrBtnHandler = function () {\n var checked = [].slice.call(this.cBox.querySelectorAll('.e-check:not(.e-selectall)'));\n var optr = 'equal';\n var caseSen = this.options.type === 'string' ?\n this.options.allowCaseSensitive : true;\n var defaults = {\n field: this.options.field, predicate: 'or',\n operator: optr, matchCase: caseSen, ignoreAccent: this.parent.filterSettings.ignoreAccent\n };\n var isNotEqual = this.itemsCnt !== checked.length && this.itemsCnt - checked.length < checked.length;\n if (isNotEqual) {\n optr = 'notequal';\n checked = [].slice.call(this.cBox.querySelectorAll('.e-uncheck:not(.e-selectall)'));\n defaults.predicate = 'and';\n defaults.operator = 'notequal';\n }\n var value;\n var fObj;\n var coll = [];\n var searchInput = this.searchBox.querySelector('.e-searchinput');\n if (checked.length !== this.itemsCnt || (searchInput.value && searchInput.value !== '')) {\n for (var i = 0; i < checked.length; i++) {\n value = this.values[parentsUntil(checked[i], 'e-ftrchk').getAttribute('uid')];\n fObj = extend({}, { value: value }, defaults);\n if (value && !value.toString().length) {\n fObj.operator = isNotEqual ? 'notequal' : 'equal';\n }\n coll.push(fObj);\n if (isActionPrevent(this.parent)) {\n this.parent.notify(events.preventBatch, {\n instance: this, handler: this.fltrBtnHandler, arg1: fObj.field, arg2: fObj.predicate, arg3: fObj.operator,\n arg4: fObj.matchCase, arg5: fObj.ignoreAccent, arg6: fObj.value\n });\n return;\n }\n }\n this.initiateFilter(coll);\n }\n else {\n this.clearFilter();\n }\n };\n CheckBoxFilter.prototype.initiateFilter = function (fColl) {\n var firstVal = fColl[0];\n var predicate;\n if (!isNullOrUndefined(firstVal)) {\n predicate = firstVal.ejpredicate ? firstVal.ejpredicate :\n new Predicate(firstVal.field, firstVal.operator, firstVal.value, !firstVal.matchCase, firstVal.ignoreAccent);\n for (var j = 1; j < fColl.length; j++) {\n predicate = fColl[j].ejpredicate !== undefined ?\n predicate[fColl[j].predicate](fColl[j].ejpredicate) :\n predicate[fColl[j].predicate](fColl[j].field, fColl[j].operator, fColl[j].value, !fColl[j].matchCase, fColl[j].ignoreAccent);\n }\n var args = {\n action: 'filtering', filterCollection: fColl, field: this.options.field,\n ejpredicate: Predicate.or(predicate)\n };\n this.options.handler(args);\n }\n };\n CheckBoxFilter.prototype.refreshCheckboxes = function () {\n var val = this.sInput.value;\n var query = this.options.query.clone();\n var parsed = (this.options.type !== 'string' && parseFloat(val)) ? parseFloat(val) : val;\n var operator = this.options.type ? 'startswith' : 'contains';\n var matchCase = true;\n var ignoreAccent = this.parent.filterSettings.ignoreAccent;\n parsed = (parsed === '' || parsed === undefined) ? undefined : parsed;\n var predicte;\n if (this.options.type === 'boolean') {\n if (parsed !== undefined &&\n this.getLocalizedLabel('FilterTrue').toLowerCase().indexOf(parsed.toLowerCase()) !== -1) {\n parsed = 'true';\n }\n else if (parsed !== undefined &&\n this.getLocalizedLabel('FilterFalse').toLowerCase().indexOf(parsed.toLowerCase()) !== -1) {\n parsed = 'false';\n }\n parsed = parsed === 'true';\n operator = 'equal';\n }\n var args = {\n requestType: events.filterSearchBegin,\n filterModel: this, columnName: this.options.field, column: this.options.column,\n operator: operator, matchCase: matchCase, ignoreAccent: ignoreAccent, filterChoiceCount: null,\n query: query\n };\n this.parent.trigger(events.actionBegin, args);\n predicte = new Predicate(this.options.field, args.operator, parsed, args.matchCase, args.ignoreAccent);\n if (this.options.type === 'date' || this.options.type === 'datetime') {\n parsed = this.valueFormatter.fromView(val, this.options.parserFn, this.options.type);\n operator = 'equal';\n if (isNullOrUndefined(parsed) && val.length) {\n return;\n }\n var filterObj = {\n field: this.options.field, operator: operator, value: parsed, matchCase: matchCase,\n ignoreAccent: ignoreAccent\n };\n predicte = getDatePredicate(filterObj, this.options.type);\n }\n if (val.length) {\n query.where(predicte);\n }\n args.filterChoiceCount = !isNullOrUndefined(args.filterChoiceCount) ? args.filterChoiceCount : 1000;\n query.take(args.filterChoiceCount);\n if (this.parent.dataSource && 'result' in this.parent.dataSource) {\n this.filterEvent(args, query);\n }\n else {\n this.processSearch(query);\n }\n };\n CheckBoxFilter.prototype.getPredicateFromCols = function (columns) {\n var predicate;\n var predicates = CheckBoxFilter.getPredicate(columns);\n var predicateList = [];\n var fPredicate = {};\n var foreignColumn = this.parent.getForeignKeyColumns();\n for (var _i = 0, _a = Object.keys(predicates); _i < _a.length; _i++) {\n var prop = _a[_i];\n var col = getColumnByForeignKeyValue(prop, foreignColumn);\n if (col) {\n this.parent.notify(events.generateQuery, { predicate: fPredicate, column: col });\n if (fPredicate.predicate.predicates.length) {\n predicateList.push(Predicate.or(fPredicate.predicate.predicates));\n }\n }\n else {\n predicateList.push(predicates[prop]);\n }\n }\n return predicateList.length && Predicate.and(predicateList);\n };\n CheckBoxFilter.prototype.getAllData = function () {\n var query = new Query();\n query = this.parent.query.clone();\n query.requiresCount(); //consider take query\n var args = {\n requestType: events.filterChoiceRequest, filterModel: this, query: query, filterChoiceCount: null\n };\n this.parent.trigger(events.actionBegin, args);\n args.filterChoiceCount = !isNullOrUndefined(args.filterChoiceCount) ? args.filterChoiceCount : 1000;\n query.take(args.filterChoiceCount);\n if (this.parent.dataSource && 'result' in this.parent.dataSource) {\n this.filterEvent(args, query);\n }\n else {\n this.processDataOperation(query);\n }\n };\n CheckBoxFilter.prototype.filterEvent = function (args, query) {\n var _this = this;\n var def = this.eventPromise(args, query);\n def.promise.then(function (e) {\n _this.dataSuccess(e);\n });\n };\n CheckBoxFilter.prototype.eventPromise = function (args, query) {\n var state;\n state = this.getStateEventArgument(query);\n var def = new Deferred();\n state.dataSource = def.resolve;\n state.action = args;\n this.parent.trigger(events.dataStateChange, state);\n return def;\n };\n ;\n CheckBoxFilter.prototype.getStateEventArgument = function (query) {\n var adaptr = new UrlAdaptor();\n var dm = new DataManager({ url: '', adaptor: new UrlAdaptor });\n var state = adaptr.processQuery(dm, query);\n var data = JSON.parse(state.data);\n return data;\n };\n ;\n CheckBoxFilter.prototype.processDataOperation = function (query) {\n var _this = this;\n this.options.dataSource = this.options.dataSource instanceof DataManager ?\n this.options.dataSource : new DataManager(this.options.dataSource);\n var allPromise = [];\n var runArray = [];\n if (this.options.column.isForeignColumn()) {\n allPromise.push(this.options.column.dataSource.executeQuery(new Query()));\n runArray.push(function (data) { return _this.foreignKeyData = data; });\n }\n allPromise.push(this.options.dataSource.executeQuery(query));\n runArray.push(this.dataSuccess.bind(this));\n var i = 0;\n Promise.all(allPromise).then(function (e) {\n e.forEach(function (data) {\n runArray[i++](data.result);\n });\n });\n };\n CheckBoxFilter.prototype.dataSuccess = function (e) {\n this.fullData = e;\n var query = new Query();\n if ((this.options.filteredColumns.length)) {\n var cols = [];\n for (var i = 0; i < this.options.filteredColumns.length; i++) {\n if (!(this.options.filteredColumns[i].field === this.options.field ||\n this.options.filteredColumns[i].field === this.options.foreignKeyValue)) {\n cols.push(this.options.filteredColumns[i]);\n }\n }\n var predicate = this.getPredicateFromCols(cols);\n if (predicate) {\n query.where(predicate);\n }\n }\n // query.select(this.options.field);\n var result = new DataManager(this.fullData).executeLocal(query);\n var col = this.options.column;\n var res = CheckBoxFilter.getDistinct(result, this.options.field, col, this.foreignKeyData);\n this.filteredData = res.records || [];\n this.processDataSource(null, true, this.filteredData);\n this.sInput.focus();\n var args = {\n requestType: events.filterAfterOpen,\n filterModel: this, columnName: this.options.field, columnType: this.options.type\n };\n this.parent.trigger(events.actionComplete, args);\n };\n CheckBoxFilter.prototype.processDataSource = function (query, isInitial, dataSource) {\n showSpinner(this.spinner);\n // query = query ? query : this.options.query.clone();\n // query.requiresCount();\n // let result: Object = new DataManager(dataSource as JSON[]).executeLocal(query);\n // let res: { result: Object[] } = result as { result: Object[] };\n this.updateResult();\n this.createFilterItems(dataSource, isInitial);\n };\n CheckBoxFilter.prototype.processSearch = function (query) {\n this.processDataOperation(query);\n };\n CheckBoxFilter.prototype.updateResult = function () {\n this.result = {};\n var predicate = this.getPredicateFromCols(this.options.filteredColumns);\n var query = new Query();\n if (predicate) {\n query.where(predicate);\n }\n var result = new DataManager(this.fullData).executeLocal(query);\n for (var _i = 0, result_1 = result; _i < result_1.length; _i++) {\n var res = result_1[_i];\n this.result[getValue(this.options.field, res)] = true;\n }\n };\n CheckBoxFilter.prototype.clickHandler = function (e) {\n var target = e.target;\n var elem = parentsUntil(target, 'e-checkbox-wrapper');\n if (parentsUntil(target, 'e-searchbox')) {\n this.searchBoxClick(e);\n }\n if (elem) {\n var selectAll = elem.querySelector('.e-selectall');\n if (selectAll) {\n this.updateAllCBoxes(!selectAll.classList.contains('e-check'));\n }\n else {\n toogleCheckbox(elem.parentElement);\n }\n this.updateIndeterminatenBtn();\n elem.querySelector('.e-chk-hidden').focus();\n }\n };\n CheckBoxFilter.prototype.updateAllCBoxes = function (checked) {\n var cBoxes = [].slice.call(this.cBox.querySelectorAll('.e-frame'));\n for (var _i = 0, cBoxes_1 = cBoxes; _i < cBoxes_1.length; _i++) {\n var cBox = cBoxes_1[_i];\n removeAddCboxClasses(cBox, checked);\n }\n };\n CheckBoxFilter.prototype.dialogOpen = function () {\n if (this.parent.element.classList.contains('e-device')) {\n this.dialogObj.element.querySelector('.e-input-group').classList.remove('e-input-focus');\n this.dialogObj.element.querySelector('.e-btn').focus();\n }\n };\n CheckBoxFilter.prototype.createCheckbox = function (value, checked, data) {\n var elem = checked ? this.cBoxTrue.cloneNode(true) :\n this.cBoxFalse.cloneNode(true);\n var label = elem.querySelector('.e-label');\n label.innerHTML = !isNullOrUndefined(value) && value.toString().length ? value :\n this.getLocalizedLabel('Blanks');\n if (this.options.template) {\n label.innerHTML = '';\n appendChildren(label, this.options.template(data));\n }\n return elem;\n };\n CheckBoxFilter.prototype.updateIndeterminatenBtn = function () {\n var cnt = this.cBox.children.length - 1;\n var className = [];\n var elem = this.cBox.querySelector('.e-selectall');\n var selected = this.cBox.querySelectorAll('.e-check:not(.e-selectall)').length;\n var btn = this.dialogObj.btnObj[0];\n btn.disabled = false;\n if (cnt === selected) {\n className = ['e-check'];\n }\n else if (selected) {\n className = ['e-stop'];\n }\n else {\n className = ['e-uncheck'];\n btn.disabled = true;\n }\n this.filterState = !btn.disabled;\n btn.dataBind();\n removeClass([elem], ['e-check', 'e-stop', 'e-uncheck']);\n addClass([elem], className);\n };\n CheckBoxFilter.prototype.createFilterItems = function (data, isInitial) {\n var cBoxes = this.parent.createElement('div');\n var btn = this.dialogObj.btnObj[0];\n this.itemsCnt = data.length;\n if (data.length) {\n var selectAllValue = this.getLocalizedLabel('SelectAll');\n var checkBox = this.createCheckbox(selectAllValue, false, (_a = {}, _a[this.options.field] = selectAllValue, _a));\n var selectAll = createCboxWithWrap(getUid('cbox'), checkBox, 'e-ftrchk');\n selectAll.querySelector('.e-frame').classList.add('e-selectall');\n cBoxes.appendChild(selectAll);\n var predicate = new Predicate('field', 'equal', this.options.field);\n if (this.options.foreignKeyValue) {\n predicate = predicate.or('field', 'equal', this.options.foreignKeyValue);\n }\n var isColFiltered = new DataManager(this.options.filteredColumns).executeLocal(new Query().where(predicate)).length;\n for (var i = 0; i < data.length; i++) {\n var uid = getUid('cbox');\n this.values[uid] = getValue('ejValue', data[i]);\n var value = this.valueFormatter.toView(getValue(this.options.field, data[i]), this.options.formatFn);\n var checkbox = this.createCheckbox(value, this.getCheckedState(isColFiltered, this.values[uid]), getValue('dataObj', data[i]));\n cBoxes.appendChild(createCboxWithWrap(uid, checkbox, 'e-ftrchk'));\n }\n this.cBox.innerHTML = cBoxes.innerHTML;\n this.updateIndeterminatenBtn();\n btn.disabled = false;\n }\n else {\n cBoxes.appendChild(this.parent.createElement('span', { innerHTML: this.getLocalizedLabel('NoResult') }));\n this.cBox.innerHTML = cBoxes.innerHTML;\n btn.disabled = true;\n }\n this.filterState = !btn.disabled;\n btn.dataBind();\n var args = { requestType: events.filterChoiceRequest, filterModel: this, dataSource: data };\n this.parent.trigger(events.actionComplete, args);\n hideSpinner(this.spinner);\n var _a;\n };\n CheckBoxFilter.prototype.getCheckedState = function (isColFiltered, value) {\n if (!this.isFiltered || !isColFiltered) {\n return true;\n }\n else {\n return this.result[value];\n }\n };\n CheckBoxFilter.getDistinct = function (json, field, column, foreignKeyData) {\n var len = json.length;\n var result = [];\n var value;\n var ejValue = 'ejValue';\n var lookup = {};\n var isForeignKey = column && column.isForeignColumn();\n while (len--) {\n value = json[len];\n value = getValue(field, value); //local remote diff, check with mdu \n if (!isNullOrUndefined(value)) {\n if (!(value in lookup)) {\n var obj = {};\n obj[ejValue] = value;\n lookup[value] = true;\n if (isForeignKey) {\n var foreignDataObj = getForeignData(column, {}, value, foreignKeyData)[0];\n setValue(events.foreignKeyData, foreignDataObj, json[len]);\n value = getValue(column.foreignKeyValue, foreignDataObj);\n }\n setValue(field, isNullOrUndefined(value) ? null : value, obj);\n setValue('dataObj', json[len], obj);\n result.push(obj);\n }\n }\n }\n return DataUtil.group(DataUtil.sort(result, field, DataUtil.fnAscending), 'ejValue');\n };\n CheckBoxFilter.getPredicate = function (columns) {\n var cols = DataUtil.distinct(columns, 'field', true) || [];\n var collection = [];\n var pred = {};\n for (var i = 0; i < cols.length; i++) {\n collection = new DataManager(columns).executeLocal(new Query().where('field', 'equal', cols[i].field));\n if (collection.length !== 0) {\n pred[cols[i].field] = CheckBoxFilter.generatePredicate(collection);\n }\n }\n return pred;\n };\n CheckBoxFilter.generatePredicate = function (cols) {\n var len = cols ? cols.length : 0;\n var predicate;\n var first;\n first = CheckBoxFilter.updateDateFilter(cols[0]);\n first.ignoreAccent = !isNullOrUndefined(first.ignoreAccent) ? first.ignoreAccent : false;\n if (first.type === 'date' || first.type === 'datetime') {\n predicate = getDatePredicate(first, first.type);\n }\n else {\n predicate = first.ejpredicate ? first.ejpredicate :\n new Predicate(first.field, first.operator, first.value, !CheckBoxFilter.getCaseValue(first), first.ignoreAccent);\n }\n for (var p = 1; p < len; p++) {\n cols[p] = CheckBoxFilter.updateDateFilter(cols[p]);\n if (len > 2 && p > 1 && cols[p].predicate === 'or') {\n if (cols[p].type === 'date' || cols[p].type === 'datetime') {\n predicate.predicates.push(getDatePredicate(cols[p], cols[p].type));\n }\n else {\n predicate.predicates.push(new Predicate(cols[p].field, cols[p].operator, cols[p].value, !CheckBoxFilter.getCaseValue(cols[p]), cols[p].ignoreAccent));\n }\n }\n else {\n if (cols[p].type === 'date' || cols[p].type === 'datetime') {\n predicate = predicate[(cols[p].predicate)](getDatePredicate(cols[p], cols[p].type), cols[p].ignoreAccent);\n }\n else {\n predicate = cols[p].ejpredicate ?\n predicate[cols[p].predicate](cols[p].ejpredicate) :\n predicate[(cols[p].predicate)](cols[p].field, cols[p].operator, cols[p].value, !CheckBoxFilter.getCaseValue(cols[p]), cols[p].ignoreAccent);\n }\n }\n }\n return predicate || null;\n };\n CheckBoxFilter.getCaseValue = function (filter) {\n if (isNullOrUndefined(filter.matchCase)) {\n return true;\n }\n else {\n return filter.matchCase;\n }\n };\n CheckBoxFilter.updateDateFilter = function (filter) {\n if ((filter.type === 'date' || filter.type === 'datetime' || filter.value instanceof Date)) {\n filter.type = filter.type || 'date';\n }\n return filter;\n };\n /**\n * For internal use only - Get the module name.\n * @private\n */\n CheckBoxFilter.prototype.getModuleName = function () {\n return 'checkboxFilter';\n };\n return CheckBoxFilter;\n}());\nexport { CheckBoxFilter };\n","import { isNullOrUndefined, extend } from '@syncfusion/ej2-base';\nimport { Query, DataManager, Predicate, Deferred, UrlAdaptor } from '@syncfusion/ej2-data';\nimport { setFormatter, getDatePredicate, getColumnByForeignKeyValue } from '../base/util';\nimport * as events from '../base/constant';\nimport { ValueFormatter } from '../services/value-formatter';\nimport { CheckBoxFilter } from '../actions/checkbox-filter';\n/**\n * Grid data module is used to generate query and data source.\n * @hidden\n */\nvar Data = /** @class */ (function () {\n /**\n * Constructor for data module.\n * @hidden\n */\n function Data(parent, serviceLocator) {\n this.dataState = { isPending: false, resolver: null, group: [] };\n this.parent = parent;\n this.serviceLocator = serviceLocator;\n this.initDataManager();\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.rowsAdded, this.addRows, this);\n this.parent.on(events.rowsRemoved, this.removeRows, this);\n this.parent.on(events.dataSourceModified, this.initDataManager, this);\n this.parent.on(events.destroy, this.destroy, this);\n this.parent.on(events.updateData, this.crudActions, this);\n this.parent.on(events.addDeleteAction, this.getData, this);\n }\n /**\n * The function used to initialize dataManager and external query\n * @return {void}\n */\n Data.prototype.initDataManager = function () {\n var gObj = this.parent;\n this.dataManager = gObj.dataSource instanceof DataManager ? gObj.dataSource :\n (isNullOrUndefined(gObj.dataSource) ? new DataManager() : new DataManager(gObj.dataSource));\n gObj.query = gObj.query instanceof Query ? gObj.query : new Query();\n };\n /**\n * The function is used to generate updated Query from Grid model.\n * @return {Query}\n * @hidden\n */\n Data.prototype.generateQuery = function (skipPage) {\n var gObj = this.parent;\n var query = gObj.query.clone();\n if (this.parent.columnQueryMode === 'ExcludeHidden') {\n query.select(this.parent.getColumns().filter(function (column) { return !(column.isPrimaryKey !== true && column.visible === false || column.field === undefined); }).map(function (column) { return column.field; }));\n }\n else if (this.parent.columnQueryMode === 'Schema') {\n var selectQueryFields = [];\n var columns = this.parent.columns;\n for (var i = 0; i < columns.length; i++) {\n selectQueryFields.push(columns[i].field);\n }\n query.select(selectQueryFields);\n }\n this.filterQuery(query);\n this.searchQuery(query);\n this.aggregateQuery(query);\n this.sortQuery(query);\n this.pageQuery(query, skipPage);\n this.groupQuery(query);\n return query;\n };\n Data.prototype.aggregateQuery = function (query, isForeign) {\n this.parent.aggregates.forEach(function (row) {\n row.columns.forEach(function (column) {\n var types = column.type instanceof Array ? column.type : [column.type];\n types.forEach(function (type) { return query.aggregate(type.toLowerCase(), column.field); });\n });\n });\n return query;\n };\n Data.prototype.pageQuery = function (query, skipPage) {\n var gObj = this.parent;\n if ((gObj.allowPaging || gObj.enableVirtualization) && skipPage !== true) {\n gObj.pageSettings.currentPage = Math.max(1, gObj.pageSettings.currentPage);\n if (gObj.pageSettings.pageCount <= 0) {\n gObj.pageSettings.pageCount = 8;\n }\n if (gObj.pageSettings.pageSize <= 0) {\n gObj.pageSettings.pageSize = 12;\n }\n query.page(gObj.pageSettings.currentPage, gObj.pageSettings.pageSize);\n }\n return query;\n };\n Data.prototype.groupQuery = function (query) {\n var gObj = this.parent;\n if (gObj.allowGrouping && gObj.groupSettings.columns.length) {\n var columns = gObj.groupSettings.columns;\n for (var i = 0, len = columns.length; i < len; i++) {\n var column = this.getColumnByField(columns[i]);\n var isGrpFmt = column.enableGroupByFormat;\n var format = column.format;\n if (isGrpFmt) {\n query.group(columns[i], this.formatGroupColumn.bind(this), format);\n }\n else {\n query.group(columns[i], null);\n }\n }\n }\n return query;\n };\n Data.prototype.sortQuery = function (query) {\n var gObj = this.parent;\n if ((gObj.allowSorting || gObj.allowGrouping) && gObj.sortSettings.columns.length) {\n var columns = gObj.sortSettings.columns;\n var sortGrp = [];\n for (var i = columns.length - 1; i > -1; i--) {\n var col = this.getColumnByField(columns[i].field);\n if (col) {\n col.setSortDirection(columns[i].direction);\n }\n var fn = col.sortComparer && !this.isRemote() ? col.sortComparer.bind(col) :\n columns[i].direction;\n if (gObj.groupSettings.columns.indexOf(columns[i].field) === -1) {\n query.sortBy(col.field, fn);\n }\n else {\n sortGrp.push({ direction: fn, field: col.field });\n }\n }\n for (var i = 0, len = sortGrp.length; i < len; i++) {\n query.sortBy(sortGrp[i].field, sortGrp[i].direction);\n }\n }\n return query;\n };\n Data.prototype.searchQuery = function (query) {\n var _this = this;\n var sSettings = this.parent.searchSettings;\n var fields = sSettings.fields.length ? sSettings.fields : this.parent.getColumns().map(function (f) { return f.field; });\n var predicateList = [];\n var needForeignKeySearch = false;\n if (this.parent.searchSettings.key.length) {\n needForeignKeySearch = this.parent.getForeignKeyColumns().some(function (col) { return fields.indexOf(col.field) > -1; });\n if (needForeignKeySearch && !(this.dataManager.adaptor.getModulename &&\n this.dataManager.adaptor.getModulename() === 'ODataV4Adaptor')) {\n fields.forEach(function (columnName) {\n var column = _this.getColumnByField(columnName);\n if (column.isForeignColumn()) {\n predicateList = _this.fGeneratePredicate(column, predicateList);\n }\n else {\n predicateList.push(new Predicate(column.field, sSettings.operator, sSettings.key, sSettings.ignoreCase, sSettings.ignoreAccent));\n }\n });\n query.where(Predicate.or(predicateList));\n }\n else {\n query.search(sSettings.key, fields, sSettings.operator, sSettings.ignoreCase, sSettings.ignoreAccent);\n }\n }\n return query;\n };\n Data.prototype.filterQuery = function (query, column, skipFoerign) {\n var gObj = this.parent;\n var predicateList = [];\n var fPredicate = {};\n var actualFilter = [];\n var foreignColumn = this.parent.getForeignKeyColumns();\n if (gObj.allowFiltering && gObj.filterSettings.columns.length) {\n var columns = column ? column : gObj.filterSettings.columns;\n var colType = {};\n for (var _i = 0, _a = gObj.columns; _i < _a.length; _i++) {\n var col = _a[_i];\n colType[col.field] = col.filter.type ? col.filter.type : gObj.filterSettings.type;\n }\n var checkBoxCols = [];\n var defaultFltrCols = [];\n for (var _b = 0, columns_1 = columns; _b < columns_1.length; _b++) {\n var col = columns_1[_b];\n if (colType[col.field] === 'CheckBox' || colType[col.field] === 'Excel') {\n checkBoxCols.push(col);\n }\n else {\n defaultFltrCols.push(col);\n }\n }\n if (checkBoxCols.length) {\n var excelPredicate = CheckBoxFilter.getPredicate(checkBoxCols);\n for (var _c = 0, _d = Object.keys(excelPredicate); _c < _d.length; _c++) {\n var prop = _d[_c];\n var col = getColumnByForeignKeyValue(prop, foreignColumn);\n if (col && !skipFoerign) {\n predicateList = this.fGeneratePredicate(col, predicateList);\n actualFilter.push(col);\n }\n else {\n predicateList.push(excelPredicate[prop]);\n }\n }\n }\n if (defaultFltrCols.length) {\n for (var _e = 0, defaultFltrCols_1 = defaultFltrCols; _e < defaultFltrCols_1.length; _e++) {\n var col = defaultFltrCols_1[_e];\n var column_1 = this.getColumnByField(col.field) ||\n getColumnByForeignKeyValue(col.field, this.parent.getForeignKeyColumns());\n var sType = column_1.type;\n if (getColumnByForeignKeyValue(col.field, foreignColumn) && !skipFoerign) {\n actualFilter.push(col);\n predicateList = this.fGeneratePredicate(column_1, predicateList);\n }\n else {\n if (sType !== 'date' && sType !== 'datetime') {\n predicateList.push(new Predicate(col.field, col.operator, col.value, !col.matchCase, this.parent.filterSettings.ignoreAccent));\n }\n else {\n predicateList.push(getDatePredicate(col, sType));\n }\n }\n }\n }\n if (predicateList.length) {\n query.where(Predicate.and(predicateList));\n }\n else {\n this.parent.notify(events.showEmptyGrid, {});\n }\n }\n return query;\n };\n Data.prototype.fGeneratePredicate = function (col, predicateList) {\n var fPredicate = {};\n if (col) {\n this.parent.notify(events.generateQuery, { predicate: fPredicate, column: col });\n if (fPredicate.predicate.predicates.length) {\n predicateList.push(fPredicate.predicate);\n }\n }\n return predicateList;\n };\n /**\n * The function is used to get dataManager promise by executing given Query.\n * @param {Query} query - Defines the query which will execute along with data processing.\n * @return {Promise}\n * @hidden\n */\n Data.prototype.getData = function (args, query) {\n var _this = this;\n if (args === void 0) { args = { requestType: '' }; }\n var key = this.getKey(args.foreignKeyData &&\n Object.keys(args.foreignKeyData).length ?\n args.foreignKeyData : this.parent.getPrimaryKeyFieldNames());\n if (this.parent.dataSource && 'result' in this.parent.dataSource) {\n var def = this.eventPromise(args, query, key);\n return def.promise;\n }\n else {\n var crud = void 0;\n switch (args.requestType) {\n case 'delete':\n query = query ? query : this.generateQuery();\n var len = Object.keys(args.data).length;\n if (len === 1) {\n crud = this.dataManager.remove(key, args.data[0], query.fromTable, query);\n }\n else {\n var changes = {\n addedRecords: [],\n deletedRecords: [],\n changedRecords: []\n };\n changes.deletedRecords = args.data;\n crud = this.dataManager.saveChanges(changes, key, query.fromTable, query.requiresCount());\n }\n break;\n case 'save':\n query = query ? query : this.generateQuery();\n args.index = isNullOrUndefined(args.index) ? 0 : args.index;\n crud = this.dataManager.insert(args.data, query.fromTable, query, args.index);\n break;\n }\n if (crud && !Array.isArray(crud) && !crud.hasOwnProperty('deletedRecords')) {\n return crud.then(function (result) {\n return _this.insert(query, args);\n });\n }\n else {\n return this.insert(query, args);\n }\n }\n };\n Data.prototype.insert = function (query, args) {\n if (args.requestType === 'save') {\n this.parent.notify(events.recordAdded, args);\n }\n return this.executeQuery(query);\n };\n Data.prototype.executeQuery = function (query) {\n var _this = this;\n if (this.dataManager.ready) {\n var deferred_1 = new Deferred();\n var ready = this.dataManager.ready;\n ready.then(function (e) {\n _this.dataManager.executeQuery(query).then(function (result) {\n deferred_1.resolve(result);\n });\n }).catch(function (e) {\n deferred_1.reject(e);\n });\n return deferred_1.promise;\n }\n else {\n return this.dataManager.executeQuery(query);\n }\n };\n Data.prototype.formatGroupColumn = function (value, field) {\n var gObj = this.parent;\n var serviceLocator = this.serviceLocator;\n var column = this.getColumnByField(field);\n var date = value;\n if (!column.type) {\n column.type = date.getDay ? (date.getHours() > 0 || date.getMinutes() > 0 ||\n date.getSeconds() > 0 || date.getMilliseconds() > 0 ? 'datetime' : 'date') : typeof (value);\n }\n if (isNullOrUndefined(column.getFormatter())) {\n setFormatter(serviceLocator, column);\n }\n var formatVal = ValueFormatter.prototype.toView(value, column.getFormatter());\n return formatVal;\n };\n Data.prototype.crudActions = function (args) {\n var query = this.generateQuery();\n var promise = null;\n var pr = 'promise';\n var key = this.getKey(args.foreignKeyData &&\n Object.keys(args.foreignKeyData).length ? args.foreignKeyData :\n this.parent.getPrimaryKeyFieldNames());\n if (this.parent.dataSource && 'result' in this.parent.dataSource) {\n this.eventPromise(args, query, key);\n }\n switch (args.requestType) {\n case 'save':\n promise = this.dataManager.update(key, args.data, query.fromTable, query, args.previousData);\n break;\n }\n args[pr] = promise;\n this.parent.notify(events.crudAction, args);\n };\n /** @hidden */\n Data.prototype.saveChanges = function (changes, key, original) {\n var query = this.generateQuery().requiresCount();\n if ('result' in this.parent.dataSource) {\n var state = void 0;\n state = this.getStateEventArgument(query);\n var deff = new Deferred();\n var args = {\n requestType: 'batchsave', changes: changes, key: key, query: query,\n endEdit: deff.resolve\n };\n this.setState({ isPending: true, resolver: deff.resolve });\n this.parent.trigger(events.dataSourceChanged, args);\n return deff.promise;\n }\n else {\n var promise = this.dataManager.saveChanges(changes, key, query.fromTable, query, original);\n return promise;\n }\n };\n Data.prototype.getKey = function (keys) {\n if (keys && keys.length) {\n return keys[0];\n }\n return undefined;\n };\n /** @hidden */\n Data.prototype.isRemote = function () {\n return this.dataManager.dataSource.offline !== true && this.dataManager.dataSource.url !== undefined;\n };\n Data.prototype.addRows = function (e) {\n for (var i = e.records.length; i > 0; i--) {\n this.dataManager.dataSource.json.splice(e.toIndex, 0, e.records[i - 1]);\n }\n };\n Data.prototype.removeRows = function (e) {\n var json = this.dataManager.dataSource.json;\n this.dataManager.dataSource.json = json.filter(function (value, index) { return e.records.indexOf(value) === -1; });\n };\n Data.prototype.getColumnByField = function (field) {\n var col;\n return (this.parent.columnModel).some(function (column) {\n col = column;\n return column.field === field;\n }) && col;\n };\n Data.prototype.destroy = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off(events.rowsAdded, this.addRows);\n this.parent.off(events.rowsRemoved, this.removeRows);\n this.parent.off(events.dataSourceModified, this.initDataManager);\n this.parent.off(events.dataSourceModified, this.destroy);\n this.parent.off(events.updateData, this.crudActions);\n this.parent.off(events.addDeleteAction, this.getData);\n };\n Data.prototype.getState = function () {\n return this.dataState;\n };\n Data.prototype.setState = function (state) {\n return this.dataState = state;\n };\n Data.prototype.getStateEventArgument = function (query) {\n var adaptr = new UrlAdaptor();\n var dm = new DataManager({ url: '', adaptor: new UrlAdaptor });\n var state = adaptr.processQuery(dm, query);\n var data = JSON.parse(state.data);\n return extend(data, state.pvtData);\n };\n Data.prototype.eventPromise = function (args, query, key) {\n var _this = this;\n var state;\n var dataArgs = args;\n state = this.getStateEventArgument(query);\n var def = new Deferred();\n var deff = new Deferred();\n if (args.requestType !== undefined && this.dataState.isDataChanged !== false) {\n state.action = args;\n if (args.requestType === 'save' || args.requestType === 'delete') {\n var editArgs = args;\n editArgs.key = key;\n editArgs.state = state;\n this.setState({ isPending: true, resolver: deff.resolve });\n dataArgs.endEdit = deff.resolve;\n this.parent.trigger(events.dataSourceChanged, editArgs);\n deff.promise.then(function (e) {\n _this.setState({ isPending: true, resolver: def.resolve, group: state.group, aggregates: state.aggregates });\n _this.parent.trigger(events.dataStateChange, state);\n });\n }\n else {\n this.setState({ isPending: true, resolver: def.resolve, group: state.group, aggregates: state.aggregates });\n this.parent.trigger(events.dataStateChange, state);\n }\n }\n else {\n this.setState({});\n def.resolve(this.parent.dataSource);\n }\n return def;\n };\n return Data;\n}());\nexport { Data };\n","import { merge } from '@syncfusion/ej2-base';\n/**\n * Row\n * @hidden\n */\nvar Row = /** @class */ (function () {\n function Row(options) {\n merge(this, options);\n }\n Row.prototype.clone = function () {\n var row = new Row({});\n merge(row, this);\n row.cells = this.cells.map(function (cell) { return cell.clone(); });\n return row;\n };\n return Row;\n}());\nexport { Row };\n","import { merge } from '@syncfusion/ej2-base';\n/**\n * Cell\n * @hidden\n */\nvar Cell = /** @class */ (function () {\n function Cell(options) {\n this.isSpanned = false;\n merge(this, options);\n }\n Cell.prototype.clone = function () {\n var cell = new Cell({});\n merge(cell, this);\n return cell;\n };\n return Cell;\n}());\nexport { Cell };\n","import { isNullOrUndefined, attributes } from '@syncfusion/ej2-base';\nimport { iterateArrayOrObject } from '../base/util';\nimport { CellType } from '../base/enum';\n/**\n * `CellMergeRender` module.\n * @hidden\n */\nvar CellMergeRender = /** @class */ (function () {\n function CellMergeRender(serviceLocator, parent) {\n this.serviceLocator = serviceLocator;\n this.parent = parent;\n }\n CellMergeRender.prototype.render = function (cellArgs, row, i, td) {\n var cellRendererFact = this.serviceLocator.getService('cellRendererFactory');\n var cellRenderer = cellRendererFact.getCellRenderer(row.cells[i].cellType || CellType.Data);\n var span = row.cells[i].cellSpan ? row.cells[i].cellSpan :\n (cellArgs.colSpan + i) <= row.cells.length ? cellArgs.colSpan : row.cells.length - i;\n var visible = 0;\n for (var j = i + 1; j < i + span && j < row.cells.length; j++) {\n if (row.cells[j].visible === false) {\n visible++;\n }\n else {\n row.cells[j].isSpanned = true;\n }\n }\n if (visible > 0) {\n for (var j = i + span; j < i + span + visible && j < row.cells.length; j++) {\n row.cells[j].isSpanned = true;\n }\n if (i + span + visible >= row.cells.length) {\n span -= (i + span + visible) - row.cells.length;\n }\n }\n if (row.cells[i].cellSpan) {\n row.data[cellArgs.column.field] = row.cells[i].spanText;\n td = cellRenderer.render(row.cells[i], row.data, { 'index': !isNullOrUndefined(row.index) ? row.index.toString() : '' });\n }\n if (span > 1) {\n attributes(td, { 'colSpan': span.toString(), 'aria-colSpan': span.toString() });\n }\n if (this.parent.enableColumnVirtualization && !row.cells[i].cellSpan &&\n !this.containsKey(cellArgs.column.field, cellArgs.data[cellArgs.column.field])) {\n this.backupMergeCells(cellArgs.column.field, cellArgs.data[cellArgs.column.field], cellArgs.colSpan);\n }\n return td;\n };\n CellMergeRender.prototype.backupMergeCells = function (fName, data, span) {\n this.setMergeCells(this.generteKey(fName, data), span);\n };\n CellMergeRender.prototype.generteKey = function (fname, data) {\n return fname + '__' + data.toString();\n };\n CellMergeRender.prototype.splitKey = function (key) {\n return key.split('__');\n };\n CellMergeRender.prototype.containsKey = function (fname, data) {\n return this.getMergeCells().hasOwnProperty(this.generteKey(fname, data));\n };\n CellMergeRender.prototype.getMergeCells = function () {\n return this.parent.mergeCells;\n };\n CellMergeRender.prototype.setMergeCells = function (key, span) {\n this.parent.mergeCells[key] = span;\n };\n CellMergeRender.prototype.updateVirtualCells = function (rows) {\n var mCells = this.getMergeCells();\n for (var _i = 0, _a = Object.keys(mCells); _i < _a.length; _i++) {\n var key = _a[_i];\n var value = mCells[key];\n var merge = this.splitKey(key);\n var columnIndex = this.getIndexFromAllColumns(merge[0]);\n var vColumnIndices = this.parent.getColumnIndexesInView();\n var span = value - (vColumnIndices[0] - columnIndex);\n if (columnIndex < vColumnIndices[0] && span > 1) {\n for (var _b = 0, rows_1 = rows; _b < rows_1.length; _b++) {\n var row = rows_1[_b];\n if (row.data[merge[0]].toString() === merge[1].toString()) {\n row.cells[0].cellSpan = span;\n row.cells[0].spanText = merge[1];\n break;\n }\n }\n }\n }\n return rows;\n };\n CellMergeRender.prototype.getIndexFromAllColumns = function (field) {\n var index = iterateArrayOrObject(this.parent.getVisibleColumns(), function (item, index) {\n if (item.field === field) {\n return index;\n }\n return undefined;\n })[0];\n return index;\n };\n return CellMergeRender;\n}());\nexport { CellMergeRender };\n","import { isNullOrUndefined, extend, getValue, addClass } from '@syncfusion/ej2-base';\nimport { attributes as addAttributes } from '@syncfusion/ej2-base';\nimport { rowDataBound, queryCellInfo } from '../base/constant';\nimport { setStyleAndAttributes } from '../base/util';\nimport { CellType } from '../base/enum';\nimport { CellMergeRender } from './cell-merge-renderer';\n/**\n * RowRenderer class which responsible for building row content.\n * @hidden\n */\nvar RowRenderer = /** @class */ (function () {\n function RowRenderer(serviceLocator, cellType, parent) {\n this.cellType = cellType;\n this.serviceLocator = serviceLocator;\n this.parent = parent;\n this.element = this.parent.createElement('tr', { attrs: { role: 'row' } });\n }\n /**\n * Function to render the row content based on Column[] and data.\n * @param {Column[]} columns\n * @param {Object} data?\n * @param {{[x:string]:Object}} attributes?\n * @param {string} rowTemplate?\n */\n RowRenderer.prototype.render = function (row, columns, attributes, rowTemplate, cloneNode) {\n return this.refreshRow(row, columns, attributes, rowTemplate, cloneNode);\n };\n /**\n * Function to refresh the row content based on Column[] and data.\n * @param {Column[]} columns\n * @param {Object} data?\n * @param {{[x:string]:Object}} attributes?\n * @param {string} rowTemplate?\n */\n RowRenderer.prototype.refresh = function (row, columns, isChanged, attributes, rowTemplate) {\n if (isChanged) {\n row.data = extend({}, row.changes);\n this.refreshMergeCells(row);\n }\n var node = this.parent.element.querySelector('[data-uid=' + row.uid + ']');\n var tr = this.refreshRow(row, columns, attributes, rowTemplate);\n var cells = [].slice.call(tr.cells);\n node.innerHTML = '';\n for (var _i = 0, cells_1 = cells; _i < cells_1.length; _i++) {\n var cell = cells_1[_i];\n node.appendChild(cell);\n }\n };\n RowRenderer.prototype.refreshRow = function (row, columns, attributes, rowTemplate, cloneNode) {\n var tr = !isNullOrUndefined(cloneNode) ? cloneNode : this.element.cloneNode();\n var rowArgs = { data: row.data };\n var cellArgs = { data: row.data };\n var attrCopy = extend({}, attributes, {});\n var chekBoxEnable = this.parent.getColumns().filter(function (col) { return col.type === 'checkbox' && col.field; })[0];\n var value = false;\n if (chekBoxEnable) {\n value = getValue(chekBoxEnable.field, rowArgs.data);\n }\n if (row.isDataRow) {\n row.isSelected = this.parent.getSelectedRowIndexes().indexOf(row.index) > -1 || value;\n }\n if (row.isDataRow && this.parent.isCheckBoxSelection\n && this.parent.checkAllRows === 'Check' && this.parent.enableVirtualization) {\n row.isSelected = true;\n if (this.parent.getSelectedRowIndexes().indexOf(row.index) === -1) {\n this.parent.getSelectedRowIndexes().push(row.index);\n }\n }\n this.buildAttributeFromRow(tr, row);\n addAttributes(tr, attrCopy);\n setStyleAndAttributes(tr, row.attributes);\n var cellRendererFact = this.serviceLocator.getService('cellRendererFactory');\n for (var i = 0, len = row.cells.length; i < len; i++) {\n var cell = row.cells[i];\n cell.isSelected = row.isSelected;\n var cellRenderer = cellRendererFact.getCellRenderer(row.cells[i].cellType || CellType.Data);\n var attrs = { 'index': !isNullOrUndefined(row.index) ? row.index.toString() : '' };\n if (row.isExpand && row.cells[i].cellType === CellType.DetailExpand) {\n attrs['class'] = 'e-detailrowexpand';\n }\n var td = cellRenderer.render(row.cells[i], row.data, attrs);\n if (row.cells[i].cellType !== CellType.Filter) {\n if (row.cells[i].cellType === CellType.Data || row.cells[i].cellType === CellType.CommandColumn) {\n this.parent.trigger(queryCellInfo, extend(cellArgs, {\n cell: td, column: cell.column, colSpan: 1,\n foreignKeyData: row.cells[i].foreignKeyData\n }));\n if (cellArgs.colSpan > 1 || row.cells[i].cellSpan > 1) {\n var cellMerge = new CellMergeRender(this.serviceLocator, this.parent);\n td = cellMerge.render(cellArgs, row, i, td);\n }\n }\n if (!row.cells[i].isSpanned) {\n tr.appendChild(td);\n }\n }\n }\n var args = { row: tr, rowHeight: this.parent.rowHeight };\n if (row.isDataRow) {\n this.parent.trigger(rowDataBound, extend(rowArgs, args));\n }\n if (this.parent.enableVirtualization) {\n rowArgs.rowHeight = this.parent.rowHeight;\n }\n if (rowArgs.rowHeight) {\n tr.style.height = rowArgs.rowHeight + 'px';\n }\n else if (this.parent.rowHeight && tr.querySelector('.e-headercell')) {\n tr.style.height = this.parent.rowHeight + 'px';\n }\n if (row.cssClass) {\n tr.classList.add(row.cssClass);\n }\n if (this.parent.element.scrollHeight > this.parent.height && this.parent.aggregates.length) {\n for (var i = 0; i < this.parent.aggregates.length; i++) {\n var property = 'properties';\n var column = 'columns';\n if (this.parent.aggregates[i][property][column][0].footerTemplate) {\n var summarycell = tr.querySelectorAll('.e-summarycell');\n if (summarycell.length) {\n var lastSummaryCell = (summarycell[summarycell.length - 1]);\n addClass([lastSummaryCell], ['e-lastsummarycell']);\n }\n }\n }\n }\n return tr;\n };\n RowRenderer.prototype.refreshMergeCells = function (row) {\n for (var _i = 0, _a = row.cells; _i < _a.length; _i++) {\n var cell = _a[_i];\n cell.isSpanned = false;\n }\n return row;\n };\n /**\n * Function to check and add alternative row css class.\n * @param {Element} tr\n * @param {{[x:string]:Object}} attr\n */\n RowRenderer.prototype.buildAttributeFromRow = function (tr, row) {\n var attr = {};\n var prop = { 'rowindex': 'aria-rowindex', 'dataUID': 'data-uid', 'ariaSelected': 'aria-selected' };\n var classes = [];\n if (row.isDataRow) {\n classes.push('e-row');\n }\n if (row.isAltRow) {\n classes.push('e-altrow');\n }\n if (!isNullOrUndefined(row.index)) {\n attr[prop.rowindex] = row.index;\n }\n if (row.rowSpan) {\n attr.rowSpan = row.rowSpan;\n }\n if (row.uid) {\n attr[prop.dataUID] = row.uid;\n }\n if (row.isSelected) {\n attr[prop.ariaSelected] = true;\n }\n if (row.visible === false) {\n classes.push('e-hide');\n }\n attr.class = classes;\n setStyleAndAttributes(tr, attr);\n };\n return RowRenderer;\n}());\nexport { RowRenderer };\n","import { isNullOrUndefined, getValue, setValue } from '@syncfusion/ej2-base';\nimport { Row } from '../models/row';\nimport { CellType } from '../base/enum';\nimport { Cell } from '../models/cell';\nimport { getUid } from '../base/util';\nimport { getForeignData } from '../../grid/base/util';\n/**\n * RowModelGenerator is used to generate grid data rows.\n * @hidden\n */\nvar RowModelGenerator = /** @class */ (function () {\n /**\n * Constructor for header renderer module\n */\n function RowModelGenerator(parent) {\n this.parent = parent;\n }\n RowModelGenerator.prototype.generateRows = function (data, args) {\n var rows = [];\n var startIndex = this.parent.enableVirtualization ? args.startIndex : 0;\n for (var i = 0, len = Object.keys(data).length; i < len; i++, startIndex++) {\n rows[i] = this.generateRow(data[i], startIndex);\n }\n return rows;\n };\n RowModelGenerator.prototype.ensureColumns = function () {\n //TODO: generate dummy column for group, detail here;\n var cols = [];\n if (this.parent.detailTemplate || this.parent.childGrid) {\n cols.push(this.generateCell({}, null, CellType.DetailExpand));\n }\n return cols;\n };\n RowModelGenerator.prototype.generateRow = function (data, index, cssClass, indent) {\n var options = {};\n options.foreignKeyData = {};\n options.uid = getUid('grid-row');\n options.data = data;\n options.index = index;\n options.indent = indent;\n options.isDataRow = true;\n options.isExpand = false;\n options.cssClass = cssClass;\n options.isAltRow = this.parent.enableAltRow ? index % 2 !== 0 : false;\n options.isSelected = this.parent.getSelectedRowIndexes().indexOf(index) > -1;\n this.refreshForeignKeyRow(options);\n var cells = this.ensureColumns();\n var row = new Row(options);\n row.cells = cells.concat(this.generateCells(options));\n return row;\n };\n RowModelGenerator.prototype.refreshForeignKeyRow = function (options) {\n this.parent.getForeignKeyColumns().forEach(function (col) {\n setValue(col.field, getForeignData(col, options.data), options.foreignKeyData);\n });\n };\n RowModelGenerator.prototype.generateCells = function (options) {\n var _this = this;\n var dummies = this.parent.getColumns();\n var tmp = [];\n dummies.forEach(function (dummy, index) {\n return tmp.push(_this.generateCell(dummy, options.uid, isNullOrUndefined(dummy.commands) ? undefined : CellType.CommandColumn, null, index, options.foreignKeyData));\n });\n return tmp;\n };\n RowModelGenerator.prototype.generateCell = function (column, rowId, cellType, colSpan, oIndex, foreignKeyData) {\n var opt = {\n 'visible': column.visible,\n 'isDataCell': !isNullOrUndefined(column.field || column.template),\n 'isTemplate': !isNullOrUndefined(column.template),\n 'rowID': rowId,\n 'column': column,\n 'cellType': !isNullOrUndefined(cellType) ? cellType : CellType.Data,\n 'colSpan': colSpan,\n 'commands': column.commands,\n 'isForeignKey': column.isForeignColumn && column.isForeignColumn(),\n 'foreignKeyData': column.isForeignColumn && column.isForeignColumn() && getValue(column.field, foreignKeyData)\n };\n if (opt.isDataCell || opt.column.type === 'checkbox') {\n opt.index = this.parent.getColumnIndexByField(column.field);\n }\n return new Cell(opt);\n };\n RowModelGenerator.prototype.refreshRows = function (input) {\n var _this = this;\n input.forEach(function (row) {\n _this.refreshForeignKeyRow(row);\n row.cells = _this.generateCells(row);\n });\n return input;\n };\n return RowModelGenerator;\n}());\nexport { RowModelGenerator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Row } from '../models/row';\nimport { Column } from '../models/column';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { calculateAggregate } from '../base/util';\nimport { CellType } from '../base/enum';\nimport { Cell } from '../models/cell';\n/**\n * Summary row model generator\n * @hidden\n */\nvar SummaryModelGenerator = /** @class */ (function () {\n /**\n * Constructor for Summary row model generator\n */\n function SummaryModelGenerator(parent) {\n this.parent = parent;\n }\n SummaryModelGenerator.prototype.getData = function () {\n var _this = this;\n var rows = [];\n this.parent.aggregates.slice().forEach(function (row) {\n var columns = row.columns.filter(function (column) {\n return !(column.footerTemplate || column.groupFooterTemplate || column.groupCaptionTemplate)\n || _this.columnSelector(column);\n });\n if (columns.length) {\n rows.push({ columns: columns });\n }\n });\n return rows;\n };\n SummaryModelGenerator.prototype.columnSelector = function (column) {\n return column.footerTemplate !== undefined;\n };\n SummaryModelGenerator.prototype.getColumns = function (start, end) {\n var columns = [];\n if (this.parent.allowGrouping) {\n this.parent.groupSettings.columns.forEach(function (value) { return columns.push(new Column({})); });\n }\n if (this.parent.detailTemplate || !isNullOrUndefined(this.parent.childGrid)) {\n columns.push(new Column({}));\n }\n columns.push.apply(columns, this.parent.getColumns());\n return isNullOrUndefined(start) ? columns : columns.slice(start, end);\n };\n SummaryModelGenerator.prototype.generateRows = function (input, args, start, end) {\n var _this = this;\n if (this.parent.currentViewData.length === 0) {\n return [];\n }\n var data = this.buildSummaryData(input, args);\n var rows = [];\n this.getData().forEach(function (row, index) {\n rows.push(_this.getGeneratedRow(row, data[index], args ? args.level : undefined, start, end));\n });\n return rows;\n };\n SummaryModelGenerator.prototype.getGeneratedRow = function (summaryRow, data, raw, start, end) {\n var _this = this;\n var tmp = [];\n var indents = this.getIndentByLevel(raw);\n var isDetailGridAlone = !isNullOrUndefined(this.parent.childGrid);\n var indentLength = this.parent.groupSettings.columns.length + (this.parent.detailTemplate ||\n !isNullOrUndefined(this.parent.childGrid) ? 1 : 0);\n this.getColumns(start, end).forEach(function (value, index) { return tmp.push(_this.getGeneratedCell(value, summaryRow, index >= indentLength ? _this.getCellType() : CellType.Indent, indents[index], isDetailGridAlone)); });\n var row = new Row({ data: data, attributes: { class: 'e-summaryrow' } });\n row.cells = tmp;\n row.visible = tmp.some(function (cell) { return cell.isDataCell && cell.visible; });\n return row;\n };\n SummaryModelGenerator.prototype.getGeneratedCell = function (column, summaryRow, cellType, indent, isDetailGridAlone) {\n //Get the summary column by display\n var sColumn = summaryRow.columns.filter(function (scolumn) { return scolumn.columnName === column.field; })[0];\n var attrs = { 'style': { 'textAlign': column.textAlign } };\n if (indent) {\n attrs.class = indent;\n }\n if (isNullOrUndefined(indent) && isDetailGridAlone) {\n attrs.class = 'e-detailindentcelltop';\n }\n var opt = {\n 'visible': column.visible,\n 'isDataCell': !isNullOrUndefined(sColumn),\n 'isTemplate': sColumn && !isNullOrUndefined(sColumn.footerTemplate\n || sColumn.groupFooterTemplate || sColumn.groupCaptionTemplate),\n 'column': sColumn || {},\n 'attributes': attrs,\n 'cellType': cellType\n };\n return new Cell(opt);\n };\n SummaryModelGenerator.prototype.buildSummaryData = function (data, args) {\n var _this = this;\n var dummy = [];\n var summaryRows = this.getData();\n var single = {};\n var key = '';\n summaryRows.forEach(function (row) {\n single = {};\n row.columns.forEach(function (column) {\n single = _this.setTemplate(column, (args && args.aggregates) ? args : data, single);\n });\n dummy.push(single);\n });\n return dummy;\n };\n SummaryModelGenerator.prototype.getIndentByLevel = function (data) {\n return this.parent.groupSettings.columns.map(function () { return 'e-indentcelltop'; });\n };\n SummaryModelGenerator.prototype.setTemplate = function (column, data, single) {\n var _this = this;\n var types = column.type;\n var helper = {};\n var formatFn = column.getFormatter() || (function () { return function (a) { return a; }; })();\n var group = data;\n if (!(types instanceof Array)) {\n types = [column.type];\n }\n types.forEach(function (type) {\n var key = column.field + ' - ' + type.toLowerCase();\n var disp = column.columnName;\n var val = type !== 'Custom' && group.aggregates && key in group.aggregates ? group.aggregates[key] :\n calculateAggregate(type, group.aggregates ? group : data, column, _this.parent);\n single[disp] = single[disp] || {};\n single[disp][key] = val;\n single[disp][type] = !isNullOrUndefined(val) ? formatFn(val) : ' ';\n if (group.field) {\n single[disp].field = group.field;\n single[disp].key = group.key;\n }\n });\n helper.format = column.getFormatter();\n column.setTemplate(helper);\n return single;\n };\n SummaryModelGenerator.prototype.getCellType = function () {\n return CellType.Summary;\n };\n return SummaryModelGenerator;\n}());\nexport { SummaryModelGenerator };\nvar GroupSummaryModelGenerator = /** @class */ (function (_super) {\n __extends(GroupSummaryModelGenerator, _super);\n function GroupSummaryModelGenerator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n GroupSummaryModelGenerator.prototype.columnSelector = function (column) {\n return column.groupFooterTemplate !== undefined;\n };\n GroupSummaryModelGenerator.prototype.getIndentByLevel = function (level) {\n if (level === void 0) { level = this.parent.groupSettings.columns.length; }\n return this.parent.groupSettings.columns.map(function (v, indx) { return indx <= level - 1 ? '' : 'e-indentcelltop'; });\n };\n GroupSummaryModelGenerator.prototype.getCellType = function () {\n return CellType.GroupSummary;\n };\n return GroupSummaryModelGenerator;\n}(SummaryModelGenerator));\nexport { GroupSummaryModelGenerator };\nvar CaptionSummaryModelGenerator = /** @class */ (function (_super) {\n __extends(CaptionSummaryModelGenerator, _super);\n function CaptionSummaryModelGenerator() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n CaptionSummaryModelGenerator.prototype.columnSelector = function (column) {\n return column.groupCaptionTemplate !== undefined;\n };\n CaptionSummaryModelGenerator.prototype.getData = function () {\n var initVal = { columns: [] };\n return [_super.prototype.getData.call(this).reduce(function (prev, cur) {\n prev.columns = prev.columns.concat(cur.columns);\n return prev;\n }, initVal)];\n };\n CaptionSummaryModelGenerator.prototype.isEmpty = function () {\n return (this.getData()[0].columns || []).length === 0;\n };\n CaptionSummaryModelGenerator.prototype.getCellType = function () {\n return CellType.CaptionSummary;\n };\n return CaptionSummaryModelGenerator;\n}(SummaryModelGenerator));\nexport { CaptionSummaryModelGenerator };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Row } from '../models/row';\nimport { isNullOrUndefined, extend, setValue } from '@syncfusion/ej2-base';\nimport { CellType } from '../base/enum';\nimport { RowModelGenerator } from '../services/row-model-generator';\nimport { GroupSummaryModelGenerator, CaptionSummaryModelGenerator } from '../services/summary-model-generator';\nimport { getForeignData } from '../../grid/base/util';\n/**\n * GroupModelGenerator is used to generate group caption rows and data rows.\n * @hidden\n */\nvar GroupModelGenerator = /** @class */ (function (_super) {\n __extends(GroupModelGenerator, _super);\n function GroupModelGenerator(parent) {\n var _this = _super.call(this, parent) || this;\n _this.rows = [];\n _this.index = 0;\n _this.parent = parent;\n _this.summaryModelGen = new GroupSummaryModelGenerator(parent);\n _this.captionModelGen = new CaptionSummaryModelGenerator(parent);\n return _this;\n }\n GroupModelGenerator.prototype.generateRows = function (data, args) {\n if (this.parent.groupSettings.columns.length === 0) {\n return _super.prototype.generateRows.call(this, data, args);\n }\n this.rows = [];\n this.index = this.parent.enableVirtualization ? args.startIndex : 0;\n for (var i = 0, len = data.length; i < len; i++) {\n this.getGroupedRecords(0, data[i], data.level);\n }\n this.index = 0;\n return this.rows;\n };\n GroupModelGenerator.prototype.getGroupedRecords = function (index, data, raw) {\n var level = raw;\n if (isNullOrUndefined(data.items)) {\n if (isNullOrUndefined(data.GroupGuid)) {\n this.rows = this.rows.concat(this.generateDataRows(data, index));\n }\n else {\n for (var j = 0, len = data.length; j < len; j++) {\n this.getGroupedRecords(index, data[j], data.level);\n }\n }\n }\n else {\n this.rows = this.rows.concat(this.generateCaptionRow(data, index));\n if (data.items && data.items.length) {\n this.getGroupedRecords(index + 1, data.items, data.items.level);\n }\n if (this.parent.aggregates.length) {\n (_a = this.rows).push.apply(_a, this.summaryModelGen.generateRows(data, { level: level }));\n }\n }\n var _a;\n };\n GroupModelGenerator.prototype.getCaptionRowCells = function (field, indent, data) {\n var _this = this;\n var cells = [];\n var visibles = [];\n var column = this.parent.getColumnByField(field);\n var indexes = this.parent.getColumnIndexesInView();\n if (this.parent.enableColumnVirtualization) {\n column = this.parent.columns.filter(function (c) { return c.field === field; })[0];\n }\n var groupedLen = this.parent.groupSettings.columns.length;\n var gObj = this.parent;\n if (!this.parent.enableColumnVirtualization || indexes.indexOf(indent) !== -1) {\n for (var i = 0; i < indent; i++) {\n cells.push(this.generateIndentCell());\n }\n cells.push(this.generateCell({}, null, CellType.Expand));\n }\n indent = this.parent.enableColumnVirtualization ? 1 :\n (this.parent.getVisibleColumns().length + groupedLen + (gObj.detailTemplate || gObj.childGrid ? 1 : 0) -\n indent + (this.parent.getVisibleColumns().length ? -1 : 0));\n //Captionsummary cells will be added here. \n if (this.parent.aggregates.length && !this.captionModelGen.isEmpty()) {\n var captionCells = this.captionModelGen.generateRows(data)[0];\n extend(data, captionCells.data);\n var cIndex_1 = 0;\n captionCells.cells.some(function (cell, index) { cIndex_1 = index; return cell.visible && cell.isDataCell; });\n visibles = captionCells.cells.slice(cIndex_1).filter(function (cell) { return cell.visible; });\n if (captionCells.visible && visibles[0].column.field === this.parent.getVisibleColumns()[0].field) {\n visibles = visibles.slice(1);\n }\n if (this.parent.getVisibleColumns().length === 1) {\n visibles = [];\n }\n indent = indent - visibles.length;\n }\n var cols = (!this.parent.enableColumnVirtualization ? [column] : this.parent.getColumns());\n var wFlag = true;\n cols.forEach(function (col, index) {\n var tmpFlag = wFlag && indexes.indexOf(indent) !== -1;\n if (tmpFlag) {\n wFlag = false;\n }\n var cellType = !_this.parent.enableColumnVirtualization || tmpFlag ?\n CellType.GroupCaption : CellType.GroupCaptionEmpty;\n indent = _this.parent.enableColumnVirtualization && cellType === CellType.GroupCaption ? indent + groupedLen : indent;\n cells.push(_this.generateCell(column, null, cellType, indent));\n });\n cells.push.apply(cells, visibles);\n return cells;\n };\n GroupModelGenerator.prototype.generateCaptionRow = function (data, indent) {\n var options = {};\n var tmp = [];\n var col = this.parent.getColumnByField(data.field);\n options.data = extend({}, data);\n if (col) {\n options.data.field = data.field;\n }\n options.isDataRow = false;\n var row = new Row(options);\n row.indent = indent;\n this.getForeignKeyData(row);\n row.cells = this.getCaptionRowCells(data.field, indent, row.data);\n return row;\n };\n GroupModelGenerator.prototype.getForeignKeyData = function (row) {\n var data = row.data;\n var col = this.parent.getColumnByField(data.field);\n if (col && col.isForeignColumn && col.isForeignColumn()) {\n setValue('foreignKey', col.valueAccessor(col.foreignKeyValue, getForeignData(col, {}, data.key)[0], col), row.data);\n }\n };\n GroupModelGenerator.prototype.generateDataRows = function (data, indent) {\n var rows = [];\n var indexes = this.parent.getColumnIndexesInView();\n for (var i = 0, len = data.length; i < len; i++) {\n rows[i] = this.generateRow(data[i], this.index, i ? undefined : 'e-firstchildrow', indent);\n for (var j = 0; j < indent; j++) {\n if (this.parent.enableColumnVirtualization && indexes.indexOf(indent) === -1) {\n continue;\n }\n rows[i].cells.unshift(this.generateIndentCell());\n }\n this.index++;\n }\n return rows;\n };\n GroupModelGenerator.prototype.generateIndentCell = function () {\n return this.generateCell({}, null, CellType.Indent);\n };\n GroupModelGenerator.prototype.refreshRows = function (input) {\n var _this = this;\n var indexes = this.parent.getColumnIndexesInView();\n input.forEach(function (row) {\n if (row.isDataRow) {\n row.cells = _this.generateCells(row);\n for (var j = 0; j < row.indent; j++) {\n if (_this.parent.enableColumnVirtualization && indexes.indexOf(row.indent) === -1) {\n continue;\n }\n row.cells.unshift(_this.generateIndentCell());\n }\n }\n else {\n var cRow = _this.generateCaptionRow(row.data, row.indent);\n row.cells = cRow.cells;\n }\n });\n return input;\n };\n return GroupModelGenerator;\n}(RowModelGenerator));\nexport { GroupModelGenerator };\n","import { Droppable } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, extend } from '@syncfusion/ej2-base';\nimport { setStyleAttribute, remove } from '@syncfusion/ej2-base';\nimport { getUpdateUsingRaf, appendChildren } from '../base/util';\nimport * as events from '../base/constant';\nimport { RowRenderer } from './row-renderer';\nimport { CellMergeRender } from './cell-merge-renderer';\nimport { RowModelGenerator } from '../services/row-model-generator';\nimport { GroupModelGenerator } from '../services/group-model-generator';\nimport { getScrollBarWidth } from '../base/util';\n/**\n * Content module is used to render grid content\n * @hidden\n */\nvar ContentRender = /** @class */ (function () {\n /**\n * Constructor for content renderer module\n */\n function ContentRender(parent, serviceLocator) {\n var _this = this;\n this.rows = [];\n this.freezeRows = [];\n this.movableRows = [];\n this.isLoaded = true;\n this.drop = function (e) {\n _this.parent.notify(events.columnDrop, { target: e.target, droppedElement: e.droppedElement });\n remove(e.droppedElement);\n };\n this.rafCallback = function (args) {\n var arg = args;\n return function () {\n _this.ariaService.setBusy(_this.getPanel().firstChild, false);\n if (_this.parent.isDestroyed) {\n return;\n }\n var rows = _this.rows.slice(0);\n if (_this.parent.getFrozenColumns() !== 0) {\n rows = args.isFrozen ? _this.freezeRows : _this.movableRows;\n }\n _this.parent.notify(events.contentReady, { rows: rows, args: arg });\n if (_this.isLoaded) {\n _this.parent.trigger(events.dataBound, {});\n if (_this.parent.allowTextWrap) {\n _this.parent.notify(events.freezeRender, { case: 'textwrap' });\n }\n }\n if (arg) {\n var action = (arg.requestType || '').toLowerCase() + '-complete';\n _this.parent.notify(action, arg);\n if (args.requestType === 'batchsave') {\n args.cancel = false;\n _this.parent.trigger(events.actionComplete, args);\n }\n }\n if (_this.isLoaded) {\n _this.parent.hideSpinner();\n }\n };\n };\n this.parent = parent;\n this.serviceLocator = serviceLocator;\n this.ariaService = this.serviceLocator.getService('ariaService');\n this.generator = this.getModelGenerator();\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.columnVisibilityChanged, this.setVisible, this);\n this.parent.on(events.colGroupRefresh, this.colGroupRefresh, this);\n this.parent.on(events.uiUpdate, this.enableAfterRender, this);\n }\n /**\n * The function is used to render grid content div\n */\n ContentRender.prototype.renderPanel = function () {\n var gObj = this.parent;\n var div = this.parent.createElement('div', { className: 'e-gridcontent' });\n var innerDiv = this.parent.createElement('div', {\n className: 'e-content'\n });\n this.ariaService.setOptions(innerDiv, { busy: false });\n div.appendChild(innerDiv);\n this.setPanel(div);\n gObj.element.appendChild(div);\n };\n /**\n * The function is used to render grid content table\n */\n ContentRender.prototype.renderTable = function () {\n var contentDiv = this.getPanel();\n contentDiv.appendChild(this.createContentTable('_content_table'));\n this.setTable(contentDiv.querySelector('.e-table'));\n this.ariaService.setOptions(this.getTable(), {\n multiselectable: this.parent.selectionSettings.type === 'Multiple'\n });\n this.initializeContentDrop();\n if (this.parent.frozenRows) {\n this.parent.getHeaderContent().classList.add('e-frozenhdrcont');\n }\n };\n /**\n * The function is used to create content table elements\n * @return {Element}\n * @hidden\n */\n ContentRender.prototype.createContentTable = function (id) {\n var innerDiv = this.getPanel().firstChild;\n var table = this.parent.createElement('table', {\n className: 'e-table', attrs: {\n cellspacing: '0.25px', role: 'grid',\n id: this.parent.element.id + id\n }\n });\n this.setColGroup(this.parent.element.querySelector('.e-gridheader').querySelector('colgroup').cloneNode(true));\n table.appendChild(this.getColGroup());\n table.appendChild(this.parent.createElement('tbody'));\n innerDiv.appendChild(table);\n return innerDiv;\n };\n ContentRender.prototype.splitRows = function (idx) {\n if (this.parent.getFrozenColumns()) {\n if (idx === 0) {\n this.freezeRows = this.rows;\n this.freezeRowElements = this.rowElements;\n }\n else {\n this.movableRows = this.rows;\n }\n }\n };\n /**\n * Refresh the content of the Grid.\n * @return {void}\n */\n // tslint:disable-next-line:max-func-body-length\n ContentRender.prototype.refreshContentRows = function (args) {\n var _this = this;\n if (args === void 0) { args = {}; }\n var gObj = this.parent;\n if (gObj.currentViewData.length === 0) {\n return;\n }\n var dataSource = gObj.currentViewData;\n var frag = document.createDocumentFragment();\n var hdrfrag = document.createDocumentFragment();\n var columns = gObj.getColumns();\n var tr;\n var hdrTbody;\n var frzCols = gObj.getFrozenColumns();\n var row = new RowRenderer(this.serviceLocator, null, this.parent);\n this.rowElements = [];\n this.rows = [];\n var fCont = this.getPanel().querySelector('.e-frozencontent');\n var mCont = this.getPanel().querySelector('.e-movablecontent');\n var cont = this.getPanel().querySelector('.e-content');\n var modelData = this.generator.generateRows(dataSource, args);\n if (isNullOrUndefined(modelData[0].cells[0])) {\n mCont.querySelector('tbody').innerHTML = '';\n }\n var idx = modelData[0].cells[0].index;\n // tslint:disable-next-line:no-any\n if (this.parent.registeredTemplate && this.parent.registeredTemplate.template) {\n this.parent.destroyTemplate(['template']);\n }\n if (this.parent.enableColumnVirtualization) {\n var cellMerge = new CellMergeRender(this.serviceLocator, this.parent);\n cellMerge.updateVirtualCells(modelData);\n }\n if (frzCols && idx >= frzCols) {\n this.tbody = mCont.querySelector('tbody');\n }\n else {\n this.tbody = this.getTable().querySelector('tbody');\n }\n for (var i = 0, len = modelData.length; i < len; i++) {\n if (!gObj.rowTemplate) {\n tr = row.render(modelData[i], columns);\n if (gObj.frozenRows && i < gObj.frozenRows) {\n hdrfrag.appendChild(tr);\n }\n else {\n frag.appendChild(tr);\n }\n }\n else {\n var elements = gObj.getRowTemplate()(extend({ index: i }, dataSource[i]), gObj, 'rowTemplate');\n if (elements[0].tagName === 'TBODY') {\n for (var j = 0; j < elements.length; j++) {\n var isTR = elements[j].nodeName.toLowerCase() === 'tr';\n if (isTR || (elements[j].querySelectorAll && elements[j].querySelectorAll('tr').length)) {\n tr = isTR ? elements[j] : elements[j].querySelector('tr');\n }\n }\n if (gObj.frozenRows && i < gObj.frozenRows) {\n hdrfrag.appendChild(tr);\n }\n else {\n frag.appendChild(tr);\n }\n }\n else {\n if (gObj.frozenRows && i < gObj.frozenRows) {\n tr = appendChildren(hdrfrag, elements);\n }\n else {\n // frag.appendChild(tr);\n tr = appendChildren(frag, elements);\n }\n }\n }\n this.rows.push(modelData[i]);\n if (modelData[i].isDataRow) {\n //detailrowvisible \n var td = tr.querySelectorAll('.e-rowcell:not(.e-hide)')[0];\n if (td) {\n td.classList.add('e-detailrowvisible');\n }\n this.rowElements.push(tr);\n }\n this.ariaService.setOptions(this.getTable(), { colcount: gObj.getColumns().length.toString() });\n }\n this.splitRows(idx);\n if (gObj.frozenRows) {\n hdrTbody = frzCols ? gObj.getHeaderContent().querySelector(idx === 0 ? '.e-frozenheader'\n : '.e-movableheader').querySelector('tbody') : gObj.getHeaderTable().querySelector('tbody');\n hdrTbody.innerHTML = '';\n hdrTbody.appendChild(hdrfrag);\n }\n if (gObj.frozenRows && idx === 0 && cont.offsetHeight === Number(gObj.height)) {\n cont.style.height = (cont.offsetHeight - hdrTbody.offsetHeight) + 'px';\n }\n if (frzCols && idx === 0) {\n this.getPanel().firstChild.style.overflowY = 'hidden';\n }\n args.rows = this.rows.slice(0);\n args.isFrozen = this.parent.getFrozenColumns() !== 0 && !args.isFrozen;\n this.index = idx;\n getUpdateUsingRaf(function () {\n _this.parent.notify(events.beforeFragAppend, args);\n if (!_this.parent.enableVirtualization) {\n remove(_this.tbody);\n _this.tbody = _this.parent.createElement('tbody');\n }\n if (frzCols) {\n _this.tbody.appendChild(frag);\n if (_this.index === 0) {\n _this.isLoaded = false;\n fCont.querySelector('table').appendChild(_this.tbody);\n }\n else {\n if (_this.tbody.childElementCount < 1) {\n _this.tbody.appendChild(_this.parent.createElement('tr').appendChild(_this.parent.createElement('td')));\n }\n _this.isLoaded = true;\n mCont.querySelector('table').appendChild(_this.tbody);\n fCont.style.height = ((mCont.offsetHeight) - getScrollBarWidth()) + 'px';\n mCont.style.overflowY = _this.parent.height !== 'auto' ? 'scroll' : 'auto';\n fCont.style.borderRightWidth = '1px';\n }\n }\n else {\n _this.appendContent(_this.tbody, frag, args);\n }\n if (frzCols && idx === 0) {\n _this.refreshContentRows(extend({}, args));\n }\n frag = null;\n }, this.rafCallback(extend({}, args)));\n };\n ContentRender.prototype.appendContent = function (tbody, frag, args) {\n tbody.appendChild(frag);\n this.getTable().appendChild(tbody);\n };\n /**\n * Get the content div element of grid\n * @return {Element}\n */\n ContentRender.prototype.getPanel = function () {\n return this.contentPanel;\n };\n /**\n * Set the content div element of grid\n * @param {Element} panel\n */\n ContentRender.prototype.setPanel = function (panel) {\n this.contentPanel = panel;\n };\n /**\n * Get the content table element of grid\n * @return {Element}\n */\n ContentRender.prototype.getTable = function () {\n return this.contentTable;\n };\n /**\n * Set the content table element of grid\n * @param {Element} table\n */\n ContentRender.prototype.setTable = function (table) {\n this.contentTable = table;\n };\n /**\n * Get the Row collection in the Grid.\n * @returns {Row[] | HTMLCollectionOf}\n */\n ContentRender.prototype.getRows = function () {\n return this.parent.getFrozenColumns() ? this.freezeRows : this.rows;\n };\n /**\n * Get the Movable Row collection in the Freeze pane Grid.\n * @returns {Row[] | HTMLCollectionOf}\n */\n ContentRender.prototype.getMovableRows = function () {\n return this.movableRows;\n };\n /**\n * Get the content table data row elements\n * @return {Element}\n */\n ContentRender.prototype.getRowElements = function () {\n return this.parent.getFrozenColumns() ? this.freezeRowElements : this.rowElements;\n };\n /**\n * Get the Freeze pane movable content table data row elements\n * @return {Element}\n */\n ContentRender.prototype.getMovableRowElements = function () {\n return this.rowElements;\n };\n /**\n * Get the content table data row elements\n * @return {Element}\n */\n ContentRender.prototype.setRowElements = function (elements) {\n this.rowElements = elements;\n };\n /**\n * Get the header colgroup element\n * @returns {Element}\n */\n ContentRender.prototype.getColGroup = function () {\n return this.colgroup;\n };\n /**\n * Set the header colgroup element\n * @param {Element} colgroup\n * @returns {Element}\n */\n ContentRender.prototype.setColGroup = function (colGroup) {\n return this.colgroup = colGroup;\n };\n /**\n * Function to hide content table column based on visible property\n * @param {Column[]} columns?\n */\n ContentRender.prototype.setVisible = function (columns) {\n var gObj = this.parent;\n var frzCols = gObj.getFrozenColumns();\n var rows = [];\n if (frzCols) {\n var fRows = this.freezeRows;\n var mRows = this.movableRows;\n var rowLen = fRows.length;\n var cellLen = void 0;\n for (var i = 0, row = void 0; i < rowLen; i++) {\n cellLen = mRows[i].cells.length;\n row = fRows[i].clone();\n for (var j = 0; j < cellLen; j++) {\n row.cells.push(mRows[i].cells[j]);\n }\n rows.push(row);\n }\n }\n else {\n rows = this.getRows();\n }\n var element;\n var testRow;\n rows.some(function (r) { if (r.isDataRow) {\n testRow = r;\n } return r.isDataRow; });\n var tasks = [];\n for (var c = 0, clen = columns.length; c < clen; c++) {\n var column = columns[c];\n var idx = this.parent.getNormalizedColumnIndex(column.uid);\n //used canSkip method to skip unwanted visible toggle operation. \n if (this.canSkip(column, testRow, idx)) {\n continue;\n }\n var displayVal = column.visible === true ? '' : 'none';\n if (frzCols) {\n if (idx < frzCols) {\n setStyleAttribute(this.getColGroup().childNodes[idx], { 'display': displayVal });\n }\n else {\n var mTable = gObj.getContent().querySelector('.e-movablecontent').querySelector('colgroup');\n setStyleAttribute(mTable.childNodes[idx - frzCols], { 'display': displayVal });\n }\n }\n else {\n setStyleAttribute(this.getColGroup().childNodes[idx], { 'display': displayVal });\n }\n }\n this.refreshContentRows({ requestType: 'refresh' });\n };\n ContentRender.prototype.colGroupRefresh = function () {\n if (this.getColGroup()) {\n var colGroup = this.parent.element.querySelector('.e-gridheader').querySelector('colgroup').cloneNode(true);\n this.getTable().replaceChild(colGroup, this.getColGroup());\n this.setColGroup(colGroup);\n }\n };\n ContentRender.prototype.initializeContentDrop = function () {\n var gObj = this.parent;\n var drop = new Droppable(gObj.getContent(), {\n accept: '.e-dragclone',\n drop: this.drop\n });\n };\n ContentRender.prototype.canSkip = function (column, row, index) {\n /**\n * Skip the toggle visiblity operation when one of the following success\n * 1. Grid has empty records\n * 2. column visible property is unchanged\n * 3. cell`s isVisible property is same as column`s visible property.\n */\n return isNullOrUndefined(row) || //(1)\n isNullOrUndefined(column.visible) || //(2) \n row.cells[index].visible === column.visible; //(3)\n };\n ContentRender.prototype.getModelGenerator = function () {\n return this.generator = this.parent.allowGrouping ? new GroupModelGenerator(this.parent) : new RowModelGenerator(this.parent);\n };\n ContentRender.prototype.renderEmpty = function (tbody) {\n this.getTable().appendChild(tbody);\n if (this.parent.frozenRows) {\n this.parent.getHeaderContent().querySelector('tbody').innerHTML = '';\n }\n };\n ContentRender.prototype.setSelection = function (uid, set, clearAll) {\n if (this.parent.getFrozenColumns()) {\n this.getMovableRows().filter(function (row) { return clearAll || uid === row.uid; }).forEach(function (row) { return row.isSelected = set; });\n }\n this.getRows().filter(function (row) { return clearAll || uid === row.uid; })\n .forEach(function (row) {\n row.isSelected = set;\n row.cells.forEach(function (cell) { return cell.isSelected = set; });\n });\n };\n ContentRender.prototype.getRowByIndex = function (index) {\n return this.parent.getDataRows()[index];\n };\n ContentRender.prototype.getVirtualRowIndex = function (index) {\n return index;\n };\n ContentRender.prototype.getMovableRowByIndex = function (index) {\n return this.parent.getMovableDataRows()[index];\n };\n ContentRender.prototype.enableAfterRender = function (e) {\n if (e.module === 'group' && e.enable) {\n this.generator = this.getModelGenerator();\n }\n };\n return ContentRender;\n}());\nexport { ContentRender };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { setStyleAttribute, closest as getClosest, remove } from '@syncfusion/ej2-base';\nimport { classList } from '@syncfusion/ej2-base';\nimport { CellType } from '../base/enum';\nimport { RowRenderer } from './row-renderer';\nimport { Cell } from '../models/cell';\nimport { Row } from '../models/row';\nimport * as events from '../base/constant';\nimport { Draggable, Droppable } from '@syncfusion/ej2-base';\nimport { parentsUntil, wrap } from '../base/util';\n/**\n * Content module is used to render grid content\n * @hidden\n */\nvar HeaderRender = /** @class */ (function () {\n /**\n * Constructor for header renderer module\n */\n function HeaderRender(parent, serviceLocator) {\n var _this = this;\n this.frzIdx = 0;\n this.helper = function (e) {\n var gObj = _this.parent;\n var target = e.sender.target;\n var parentEle = parentsUntil(target, 'e-headercell');\n if (!(gObj.allowReordering || gObj.allowGrouping) || (!isNullOrUndefined(parentEle)\n && parentEle.querySelectorAll('.e-checkselectall').length > 0)) {\n return false;\n }\n var visualElement = _this.parent.createElement('div', { className: 'e-cloneproperties e-dragclone e-headerclone' });\n var element = target.classList.contains('e-headercell') ? target : parentEle;\n if (!element || (!gObj.allowReordering && element.classList.contains('e-stackedheadercell'))) {\n return false;\n }\n var height = element.offsetHeight;\n var headercelldiv = element.querySelector('.e-headercelldiv') || element.querySelector('.e-stackedheadercelldiv');\n var col;\n if (headercelldiv) {\n if (element.querySelector('.e-stackedheadercelldiv')) {\n col = gObj.getStackedHeaderColumnByHeaderText(headercelldiv.innerText.trim(), gObj.columns);\n }\n else {\n col = gObj.getColumnByUid(headercelldiv.getAttribute('e-mappinguid'));\n }\n _this.column = col;\n visualElement.setAttribute('e-mappinguid', _this.column.uid);\n }\n if (col && !isNullOrUndefined(col.headerTemplate)) {\n if (col.headerTemplate.indexOf('#') !== -1) {\n visualElement.innerHTML = document.querySelector(col.headerTemplate).innerHTML.trim();\n }\n else {\n visualElement.innerHTML = col.headerTemplate;\n }\n }\n else {\n visualElement.innerHTML = headercelldiv ?\n col.headerText : element.firstElementChild.innerHTML;\n }\n visualElement.style.width = element.offsetWidth + 'px';\n visualElement.style.height = element.offsetHeight + 'px';\n visualElement.style.lineHeight = (height - 6).toString() + 'px';\n gObj.element.appendChild(visualElement);\n return visualElement;\n };\n this.dragStart = function (e) {\n var gObj = _this.parent;\n gObj.element.querySelector('.e-gridpopup').style.display = 'none';\n gObj.notify(events.columnDragStart, { target: e.target, column: _this.column, event: e.event });\n };\n this.drag = function (e) {\n var gObj = _this.parent;\n var target = e.target;\n if (target) {\n var closest = getClosest(target, '.e-grid');\n var cloneElement = _this.parent.element.querySelector('.e-cloneproperties');\n if (!closest || closest.getAttribute('id') !== gObj.element.getAttribute('id')) {\n classList(cloneElement, ['e-notallowedcur'], ['e-defaultcur']);\n if (gObj.allowReordering) {\n gObj.element.querySelector('.e-reorderuparrow').style.display = 'none';\n gObj.element.querySelector('.e-reorderdownarrow').style.display = 'none';\n }\n return;\n }\n gObj.notify(events.columnDrag, { target: e.target, column: _this.column, event: e.event });\n }\n };\n this.dragStop = function (e) {\n var gObj = _this.parent;\n var cancel;\n gObj.element.querySelector('.e-gridpopup').style.display = 'none';\n if ((!parentsUntil(e.target, 'e-headercell') && !parentsUntil(e.target, 'e-groupdroparea')) ||\n (!gObj.allowReordering && parentsUntil(e.target, 'e-headercell')) ||\n (!e.helper.getAttribute('e-mappinguid') && parentsUntil(e.target, 'e-groupdroparea'))) {\n remove(e.helper);\n cancel = true;\n }\n gObj.notify(events.columnDragStop, { target: e.target, event: e.event, column: _this.column, cancel: cancel });\n };\n this.drop = function (e) {\n var gObj = _this.parent;\n var uid = e.droppedElement.getAttribute('e-mappinguid');\n var closest = getClosest(e.target, '.e-grid');\n remove(e.droppedElement);\n if (closest && closest.getAttribute('id') !== gObj.element.getAttribute('id') ||\n !(gObj.allowReordering || gObj.allowGrouping)) {\n return;\n }\n gObj.notify(events.headerDrop, { target: e.target, uid: uid });\n };\n this.parent = parent;\n this.serviceLocator = serviceLocator;\n this.ariaService = this.serviceLocator.getService('ariaService');\n this.widthService = this.serviceLocator.getService('widthService');\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.columnVisibilityChanged, this.setVisible, this);\n this.parent.on(events.columnPositionChanged, this.colPosRefresh, this);\n }\n /**\n * The function is used to render grid header div\n */\n HeaderRender.prototype.renderPanel = function () {\n var div = this.parent.createElement('div', { className: 'e-gridheader' });\n var innerDiv = this.parent.createElement('div', { className: 'e-headercontent' });\n div.appendChild(innerDiv);\n this.setPanel(div);\n this.parent.element.appendChild(div);\n };\n /**\n * The function is used to render grid header table\n */\n HeaderRender.prototype.renderTable = function () {\n var headerDiv = this.getPanel();\n headerDiv.appendChild(this.createHeaderTable());\n this.setTable(headerDiv.querySelector('.e-table'));\n if (!this.parent.getFrozenColumns()) {\n this.initializeHeaderDrag();\n this.initializeHeaderDrop();\n }\n this.parent.notify(events.headerRefreshed, { rows: this.rows, args: { isFrozen: this.parent.getFrozenColumns() !== 0 } });\n };\n /**\n * Get the header content div element of grid\n * @return {Element}\n */\n HeaderRender.prototype.getPanel = function () {\n return this.headerPanel;\n };\n /**\n * Set the header content div element of grid\n * @param {Element} panel\n */\n HeaderRender.prototype.setPanel = function (panel) {\n this.headerPanel = panel;\n };\n /**\n * Get the header table element of grid\n * @return {Element}\n */\n HeaderRender.prototype.getTable = function () {\n return this.headerTable;\n };\n /**\n * Set the header table element of grid\n * @param {Element} table\n */\n HeaderRender.prototype.setTable = function (table) {\n this.headerTable = table;\n };\n /**\n * Get the header colgroup element\n * @returns {Element}\n */\n HeaderRender.prototype.getColGroup = function () {\n return this.colgroup;\n };\n /**\n * Set the header colgroup element\n * @param {Element} colgroup\n * @returns {Element}\n */\n HeaderRender.prototype.setColGroup = function (colGroup) {\n return this.colgroup = colGroup;\n };\n /**\n * Get the header row element collection.\n * @return {Element[]}\n */\n HeaderRender.prototype.getRows = function () {\n var table = this.getTable();\n return table.tHead.rows;\n };\n /**\n * The function is used to create header table elements\n * @return {Element}\n * @hidden\n */\n HeaderRender.prototype.createHeaderTable = function () {\n var table = this.createTable();\n var innerDiv = this.getPanel().firstChild;\n innerDiv.appendChild(table);\n return innerDiv;\n };\n /**\n * @hidden\n */\n HeaderRender.prototype.createTable = function () {\n var gObj = this.parent;\n var columns = gObj.getColumns();\n var table = this.parent.createElement('table', { className: 'e-table', attrs: { cellspacing: '0.25px', role: 'grid' } });\n var innerDiv = this.getPanel().firstChild;\n var findHeaderRow = this.createHeaderContent();\n var thead = findHeaderRow.thead;\n var tbody = this.parent.createElement('tbody', { className: this.parent.frozenRows ? '' : 'e-hide' });\n this.caption = this.parent.createElement('caption', { innerHTML: this.parent.element.id + '_header_table', className: 'e-hide' });\n var colGroup = this.parent.createElement('colgroup');\n var rowBody = this.parent.createElement('tr');\n var bodyCell;\n var rows = this.rows = findHeaderRow.rows;\n var rowRenderer = new RowRenderer(this.serviceLocator, CellType.Header, this.parent);\n for (var i = 0, len = rows.length; i < len; i++) {\n for (var j = 0, len_1 = rows[i].cells.length; j < len_1; j++) {\n var cell = rows[i].cells[j];\n bodyCell = this.parent.createElement('td');\n rowBody.appendChild(bodyCell);\n }\n }\n if (gObj.allowFiltering || gObj.allowSorting || gObj.allowGrouping) {\n table.classList.add('e-sortfilter');\n }\n this.updateColGroup(colGroup);\n tbody.appendChild(rowBody);\n table.appendChild(this.setColGroup(colGroup));\n table.appendChild(thead);\n table.appendChild(tbody);\n table.appendChild(this.caption);\n this.ariaService.setOptions(table, { colcount: gObj.getColumns().length.toString() });\n return table;\n };\n HeaderRender.prototype.createHeaderContent = function () {\n var gObj = this.parent;\n var columns = gObj.getColumns();\n var thead = this.parent.createElement('thead');\n var colHeader = this.parent.createElement('tr', { className: 'e-columnheader' });\n var rowRenderer = new RowRenderer(this.serviceLocator, CellType.Header, gObj);\n rowRenderer.element = colHeader;\n var rows = [];\n var headerRow;\n this.colDepth = this.getObjDepth();\n for (var i = 0, len = this.colDepth; i < len; i++) {\n rows[i] = this.generateRow(i);\n rows[i].cells = [];\n }\n rows = this.ensureColumns(rows);\n rows = this.getHeaderCells(rows);\n for (var i = 0, len = this.colDepth; i < len; i++) {\n headerRow = rowRenderer.render(rows[i], columns);\n if (this.parent.rowHeight && headerRow.querySelector('.e-headercell')) {\n headerRow.style.height = this.parent.rowHeight + 'px';\n }\n thead.appendChild(headerRow);\n }\n var findHeaderRow = {\n thead: thead,\n rows: rows\n };\n return findHeaderRow;\n };\n HeaderRender.prototype.updateColGroup = function (colGroup) {\n var cols = this.parent.getColumns();\n var col;\n var indexes = this.parent.getColumnIndexesInView();\n if (this.parent.allowGrouping) {\n for (var i = 0, len = this.parent.groupSettings.columns.length; i < len; i++) {\n if (this.parent.enableColumnVirtualization && indexes.indexOf(i) === -1) {\n continue;\n }\n col = this.parent.createElement('col');\n colGroup.appendChild(col);\n }\n }\n if (this.parent.detailTemplate || this.parent.childGrid) {\n col = this.parent.createElement('col');\n colGroup.appendChild(col);\n }\n for (var i = 0, len = cols.length; i < len; i++) {\n col = this.parent.createElement('col');\n if (cols[i].visible === false) {\n setStyleAttribute(col, { 'display': 'none' });\n }\n colGroup.appendChild(col);\n }\n return colGroup;\n };\n HeaderRender.prototype.ensureColumns = function (rows) {\n //TODO: generate dummy column for group, detail, stacked row here; ensureColumns here\n var gObj = this.parent;\n var indexes = this.parent.getColumnIndexesInView();\n for (var i = 0, len = rows.length; i < len; i++) {\n if (gObj.allowGrouping) {\n for (var c = 0, len_2 = gObj.groupSettings.columns.length; c < len_2; c++) {\n if (this.parent.enableColumnVirtualization && indexes.indexOf(c) === -1) {\n continue;\n }\n rows[i].cells.push(this.generateCell({}, CellType.HeaderIndent));\n }\n }\n if (gObj.detailTemplate || gObj.childGrid) {\n rows[i].cells.push(this.generateCell({}, CellType.DetailHeader));\n }\n }\n return rows;\n };\n HeaderRender.prototype.getHeaderCells = function (rows) {\n var column;\n var thead = this.parent.getHeaderTable() && this.parent.getHeaderTable().querySelector('thead');\n var cols = this.parent.enableColumnVirtualization ? this.parent.getColumns() : this.parent.columns;\n this.frzIdx = 0;\n for (var i = 0, len = cols.length; i < len; i++) {\n rows = this.appendCells(cols[i], rows, 0, i === 0, false, i === (len - 1), thead);\n }\n return rows;\n };\n HeaderRender.prototype.appendCells = function (cols, rows, index, isFirstObj, isFirstCol, isLastCol, isMovable) {\n var lastCol = isLastCol ? 'e-lastcell' : '';\n var frzCols = this.parent.getFrozenColumns();\n if (!cols.columns) {\n if (!frzCols || (frzCols\n && ((!isMovable && (this.frzIdx < this.parent.frozenColumns || cols.isFrozen))\n || (isMovable && this.frzIdx >= this.parent.frozenColumns && !cols.isFrozen)))) {\n rows[index].cells.push(this.generateCell(cols, CellType.Header, this.colDepth - index, (isFirstObj ? '' : (isFirstCol ? 'e-firstcell' : '')) + lastCol, index, this.parent.getColumnIndexByUid(cols.uid)));\n }\n this.frzIdx++;\n }\n else {\n var colSpan = this.getCellCnt(cols, 0);\n if (colSpan) {\n var frzObj = this.refreshFrozenHdr(cols.columns, { isPartial: false, isComp: true, cnt: 0 });\n if (!frzCols || (frzCols\n && ((!isMovable && (this.parent.frozenColumns - this.frzIdx > 0 || (frzObj.isPartial)))\n || (isMovable && (colSpan + this.frzIdx > this.parent.frozenColumns && !frzObj.isComp))))) {\n rows[index].cells.push(new Cell({\n cellType: CellType.StackedHeader, column: cols,\n colSpan: this.getColSpan(colSpan, isMovable, frzObj.cnt)\n }));\n }\n }\n for (var i = 0, len = cols.columns.length; i < len; i++) {\n rows = this.appendCells(cols.columns[i], rows, index + 1, isFirstObj, i === 0, i === (len - 1) && isLastCol, isMovable);\n }\n }\n return rows;\n };\n HeaderRender.prototype.refreshFrozenHdr = function (cols, frzObj) {\n for (var i = 0; i < cols.length; i++) {\n if (cols[i].columns) {\n frzObj = this.refreshFrozenHdr(cols[i].columns, frzObj);\n }\n else {\n if (cols[i].isFrozen) {\n frzObj.isPartial = true;\n frzObj.cnt++;\n }\n frzObj.isComp = frzObj.isComp && (cols[i].isFrozen ||\n this.parent.getColumnIndexByField(cols[i].field) < this.parent.frozenColumns);\n }\n }\n return frzObj;\n };\n HeaderRender.prototype.getColSpan = function (colSpan, isMovable, frozenCnt) {\n var frzCol = this.parent.frozenColumns;\n if (this.parent.getFrozenColumns() && this.frzIdx + colSpan > frzCol) {\n if (isMovable) {\n colSpan = colSpan - (frzCol > this.frzIdx ? frzCol - this.frzIdx : 0) - frozenCnt;\n }\n else {\n colSpan = colSpan - (colSpan - (frzCol > this.frzIdx ? frzCol + frozenCnt - this.frzIdx : frozenCnt));\n }\n }\n return colSpan;\n };\n HeaderRender.prototype.generateRow = function (index) {\n return new Row({});\n };\n HeaderRender.prototype.generateCell = function (column, cellType, rowSpan, className, rowIndex, colIndex) {\n var opt = {\n 'visible': column.visible,\n 'isDataCell': false,\n 'isTemplate': !isNullOrUndefined(column.headerTemplate),\n 'rowID': '',\n 'column': column,\n 'cellType': cellType,\n 'rowSpan': rowSpan,\n 'className': className,\n 'index': rowIndex,\n 'colIndex': colIndex\n };\n if (!opt.rowSpan || opt.rowSpan < 2) {\n delete opt.rowSpan;\n }\n return new Cell(opt);\n };\n /**\n * Function to hide header table column based on visible property\n * @param {Column[]} columns?\n */\n HeaderRender.prototype.setVisible = function (columns) {\n var gObj = this.parent;\n var rows = [].slice.call(this.getRows()); //NodeList -> Array \n var displayVal = '';\n var idx;\n var className;\n var element;\n var frzCols = gObj.getFrozenColumns();\n for (var c = 0, clen = columns.length; c < clen; c++) {\n var column = columns[c];\n idx = gObj.getNormalizedColumnIndex(column.uid);\n if (column.visible === false) {\n displayVal = 'none';\n }\n if (frzCols) {\n if (idx < frzCols) {\n setStyleAttribute(this.getColGroup().children[idx], { 'display': displayVal });\n }\n else {\n var mTblColGrp = gObj.getHeaderContent().querySelector('.e-movableheader').querySelector('colgroup');\n setStyleAttribute(mTblColGrp.children[idx - frzCols], { 'display': displayVal });\n }\n }\n else {\n setStyleAttribute(this.getColGroup().children[idx], { 'display': displayVal });\n }\n this.refreshUI();\n }\n };\n HeaderRender.prototype.colPosRefresh = function () {\n this.refreshUI();\n };\n /**\n * Refresh the header of the Grid.\n * @returns {void}\n */\n HeaderRender.prototype.refreshUI = function () {\n var headerDiv = this.getPanel();\n var table = this.getTable();\n var frzCols = this.parent.getFrozenColumns();\n remove(this.getTable());\n table.removeChild(table.firstChild);\n table.removeChild(table.childNodes[0]);\n var colGroup = this.parent.createElement('colgroup');\n var findHeaderRow = this.createHeaderContent();\n this.rows = findHeaderRow.rows;\n table.insertBefore(findHeaderRow.thead, table.firstChild);\n this.updateColGroup(colGroup);\n table.insertBefore(this.setColGroup(colGroup), table.firstChild);\n this.setTable(table);\n this.appendContent(table);\n this.parent.notify(events.colGroupRefresh, {});\n this.widthService.setWidthToColumns();\n this.parent.updateDefaultCursor();\n if (!frzCols) {\n this.initializeHeaderDrag();\n }\n var rows = [].slice.call(headerDiv.querySelectorAll('tr.e-columnheader'));\n for (var _i = 0, rows_1 = rows; _i < rows_1.length; _i++) {\n var row = rows_1[_i];\n var gCells = [].slice.call(row.querySelectorAll('.e-grouptopleftcell'));\n if (gCells.length) {\n gCells[gCells.length - 1].classList.add('e-lastgrouptopleftcell');\n }\n }\n if (!frzCols) {\n this.parent.notify(events.headerRefreshed, { rows: this.rows, args: { isFrozen: this.parent.getFrozenColumns() !== 0 } });\n }\n if (this.parent.allowTextWrap && this.parent.textWrapSettings.wrapMode === 'Header') {\n wrap(rows, true);\n }\n };\n HeaderRender.prototype.appendContent = function (table) {\n this.getPanel().firstChild.appendChild(table);\n };\n HeaderRender.prototype.getObjDepth = function () {\n var max = 0;\n var cols = this.parent.columns;\n for (var i = 0, len = cols.length; i < len; i++) {\n var depth = this.checkDepth(cols[i], 0);\n if (max < depth) {\n max = depth;\n }\n }\n return max + 1;\n };\n HeaderRender.prototype.checkDepth = function (col, index) {\n var max = index;\n var indices = [];\n if (col.columns) {\n index++;\n for (var i = 0, len = col.columns.length; i < len; i++) {\n indices[i] = this.checkDepth(col.columns[i], index);\n }\n for (var j = 0; j < indices.length; j++) {\n if (max < indices[j]) {\n max = indices[j];\n }\n }\n index = max;\n }\n return index;\n };\n HeaderRender.prototype.getCellCnt = function (col, cnt) {\n if (col.columns) {\n for (var i = 0, len = col.columns.length; i < len; i++) {\n cnt = this.getCellCnt(col.columns[i], cnt);\n }\n }\n else {\n if (col.visible) {\n cnt++;\n }\n }\n return cnt;\n };\n HeaderRender.prototype.initializeHeaderDrag = function () {\n var gObj = this.parent;\n if (!(this.parent.allowReordering || (this.parent.allowGrouping && this.parent.groupSettings.showDropArea))) {\n return;\n }\n var headerRows = [].slice.call(gObj.getHeaderContent().querySelectorAll('.e-columnheader'));\n for (var i = 0, len = headerRows.length; i < len; i++) {\n var drag = new Draggable(headerRows[i], {\n dragTarget: '.e-headercell',\n distance: 5,\n helper: this.helper,\n dragStart: this.dragStart,\n drag: this.drag,\n dragStop: this.dragStop,\n abort: '.e-rhandler'\n });\n }\n };\n HeaderRender.prototype.initializeHeaderDrop = function () {\n var gObj = this.parent;\n var drop = new Droppable(gObj.getHeaderContent(), {\n accept: '.e-dragclone',\n drop: this.drop\n });\n };\n return HeaderRender;\n}());\nexport { HeaderRender };\n","import { isNullOrUndefined, extend } from '@syncfusion/ej2-base';\nimport { doesImplementInterface, setStyleAndAttributes, appendChildren } from '../base/util';\nimport { createCheckBox } from '@syncfusion/ej2-buttons';\nimport { foreignKeyData } from '../base/constant';\n/**\n * CellRenderer class which responsible for building cell content.\n * @hidden\n */\nvar CellRenderer = /** @class */ (function () {\n function CellRenderer(parent, locator) {\n this.localizer = locator.getService('localization');\n this.formatter = locator.getService('valueFormatter');\n this.parent = parent;\n this.element = this.parent.createElement('TD', { className: 'e-rowcell', attrs: { role: 'gridcell', tabindex: '-1' } });\n this.rowChkBox = this.parent.createElement('input', { className: 'e-checkselect', attrs: { 'type': 'checkbox' } });\n }\n /**\n * Function to return the wrapper for the TD content\n * @returns string\n */\n CellRenderer.prototype.getGui = function () {\n return '';\n };\n /**\n * Function to format the cell value.\n * @param {Column} column\n * @param {Object} value\n * @param {Object} data\n */\n CellRenderer.prototype.format = function (column, value, data) {\n if (!isNullOrUndefined(column.format)) {\n value = this.formatter.toView(value, column.getFormatter());\n }\n return isNullOrUndefined(value) ? '' : value.toString();\n };\n CellRenderer.prototype.evaluate = function (node, cell, data, attributes, fData) {\n var result;\n if (cell.column.template) {\n var literals = ['index'];\n var dummyData = extend({}, data, (_a = {}, _a[foreignKeyData] = fData, _a));\n result = cell.column.getColumnTemplate()(extend({ 'index': attributes[literals[0]] }, dummyData), this.parent, 'template');\n appendChildren(node, result);\n result = null;\n node.setAttribute('aria-label', node.innerText + ' is template cell' + ' column header ' +\n cell.column.headerText);\n return false;\n }\n return true;\n var _a;\n };\n /**\n * Function to invoke the custom formatter available in the column object.\n * @param {Column} column\n * @param {Object} value\n * @param {Object} data\n */\n CellRenderer.prototype.invokeFormatter = function (column, value, data) {\n if (!isNullOrUndefined(column.formatter)) {\n if (doesImplementInterface(column.formatter, 'getValue')) {\n var formatter = column.formatter;\n value = new formatter().getValue(column, data);\n }\n else if (typeof column.formatter === 'function') {\n value = column.formatter(column, data);\n }\n else {\n value = column.formatter.getValue(column, data);\n }\n }\n return value;\n };\n /**\n * Function to render the cell content based on Column object.\n * @param {Column} column\n * @param {Object} data\n * @param {{[x:string]:Object}} attributes?\n * @param {Element}\n */\n CellRenderer.prototype.render = function (cell, data, attributes) {\n return this.refreshCell(cell, data, attributes);\n };\n /**\n * Function to refresh the cell content based on Column object.\n * @param {Column} column\n * @param {Object} data\n * @param {{[x:string]:Object}} attributes?\n * @param {Element}\n */\n CellRenderer.prototype.refreshTD = function (td, cell, data, attributes) {\n var node = this.refreshCell(cell, data, attributes);\n td.innerHTML = '';\n var elements = [].slice.call(node.childNodes);\n for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {\n var elem = elements_1[_i];\n td.appendChild(elem);\n }\n };\n CellRenderer.prototype.refreshCell = function (cell, data, attributes) {\n var node = this.element.cloneNode();\n var column = cell.column;\n var fData;\n if (cell.isForeignKey) {\n fData = cell.foreignKeyData[0] || (_a = {}, _a[column.foreignKeyValue] = column.format ? null : '', _a);\n }\n //Prepare innerHtml\n var innerHtml = this.getGui();\n var value = cell.isForeignKey ? this.getValue(column.foreignKeyValue, fData, column) :\n this.getValue(column.field, data, column);\n if (column.type === 'date' && !isNullOrUndefined(value)) {\n value = new Date(value);\n }\n value = this.format(column, value, data);\n innerHtml = value.toString();\n if (column.type === 'boolean' && !column.displayAsCheckBox) {\n var localeStr = (value !== 'true' && value !== 'false') ? null : value === 'true' ? 'True' : 'False';\n innerHtml = localeStr ? this.localizer.getConstant(localeStr) : innerHtml;\n }\n var fromFormatter = this.invokeFormatter(column, value, data);\n innerHtml = !isNullOrUndefined(column.formatter) ? isNullOrUndefined(fromFormatter) ? '' : fromFormatter.toString() : innerHtml;\n node.setAttribute('aria-label', (innerHtml === '' ? 'empty' : innerHtml) + ' column header ' + cell.column.headerText);\n if (!isNullOrUndefined(cell.column.headerText)) {\n node.setAttribute('aria-label', innerHtml + ' column header ' + cell.column.headerText);\n }\n if (this.evaluate(node, cell, data, attributes, fData) && column.type !== 'checkbox') {\n this.appendHtml(node, innerHtml, column.getDomSetter ? column.getDomSetter() : 'innerHTML');\n }\n else if (column.type === 'checkbox') {\n node.classList.add('e-gridchkbox');\n node.setAttribute('aria-label', 'checkbox');\n if (this.parent.selectionSettings.persistSelection) {\n value = value === 'true';\n }\n else {\n value = false;\n }\n var checkWrap = createCheckBox(this.parent.createElement, false, { checked: value, label: ' ' });\n checkWrap.insertBefore(this.rowChkBox.cloneNode(), checkWrap.firstChild);\n node.appendChild(checkWrap);\n }\n if (this.parent.checkAllRows === 'Check' && this.parent.enableVirtualization) {\n cell.isSelected = true;\n }\n this.setAttributes(node, cell, attributes);\n if (column.type === 'boolean' && column.displayAsCheckBox) {\n var checked = isNaN(parseInt(value.toString(), 10)) ? value === 'true' : parseInt(value.toString(), 10) > 0;\n var checkWrap = createCheckBox(this.parent.createElement, false, { checked: checked, label: ' ' });\n node.innerHTML = '';\n checkWrap.classList.add('e-checkbox-disabled');\n node.appendChild(checkWrap);\n node.setAttribute('aria-label', checked + ' column header ' + cell.column.headerText);\n }\n return node;\n var _a;\n };\n /**\n * Function to specifies how the result content to be placed in the cell.\n * @param {Element} node\n * @param {string|Element} innerHtml\n * @returns Element\n */\n CellRenderer.prototype.appendHtml = function (node, innerHtml, property) {\n if (property === void 0) { property = 'innerHTML'; }\n node[property] = innerHtml;\n return node;\n };\n /**\n * @hidden\n */\n CellRenderer.prototype.setAttributes = function (node, cell, attributes) {\n var column = cell.column;\n this.buildAttributeFromCell(node, cell, column.type === 'checkbox');\n setStyleAndAttributes(node, attributes);\n setStyleAndAttributes(node, cell.attributes);\n if (column.customAttributes) {\n setStyleAndAttributes(node, column.customAttributes);\n }\n if (column.textAlign) {\n node.style.textAlign = column.textAlign;\n }\n if (column.clipMode === 'Clip') {\n node.classList.add('e-gridclip');\n }\n else if (column.clipMode === 'EllipsisWithTooltip') {\n node.classList.add('e-ellipsistooltip');\n }\n };\n CellRenderer.prototype.buildAttributeFromCell = function (node, cell, isCheckBoxType) {\n var attr = {};\n var prop = { 'colindex': 'aria-colindex' };\n var classes = [];\n if (cell.colSpan) {\n attr.colSpan = cell.colSpan;\n }\n if (cell.rowSpan) {\n attr.rowSpan = cell.rowSpan;\n }\n if (cell.isTemplate) {\n classes.push('e-templatecell');\n }\n if (cell.isSelected) {\n classes.push.apply(classes, ['e-selectionbackground', 'e-active']);\n if (isCheckBoxType) {\n node.querySelector('.e-frame').classList.add('e-check');\n }\n }\n if (!isNullOrUndefined(cell.index)) {\n attr[prop.colindex] = cell.index;\n }\n if (!cell.visible) {\n classes.push('e-hide');\n }\n attr.class = classes;\n setStyleAndAttributes(node, attr);\n };\n CellRenderer.prototype.getValue = function (field, data, column) {\n return column.valueAccessor(field, data, column);\n };\n return CellRenderer;\n}());\nexport { CellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { isNullOrUndefined, extend } from '@syncfusion/ej2-base';\nimport { attributes } from '@syncfusion/ej2-base';\nimport { setStyleAndAttributes, appendChildren } from '../base/util';\nimport { CellRenderer } from './cell-renderer';\nimport { AriaService } from '../services/aria-service';\nimport { createCheckBox } from '@syncfusion/ej2-buttons';\nimport { headerCellInfo } from '../base/constant';\n/**\n * HeaderCellRenderer class which responsible for building header cell content.\n * @hidden\n */\nvar HeaderCellRenderer = /** @class */ (function (_super) {\n __extends(HeaderCellRenderer, _super);\n function HeaderCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent\n .createElement('TH', { className: 'e-headercell', attrs: { role: 'columnheader', tabindex: '-1' } });\n _this.ariaService = new AriaService();\n _this.hTxtEle = _this.parent.createElement('span', { className: 'e-headertext' });\n _this.sortEle = _this.parent.createElement('div', { className: 'e-sortfilterdiv e-icons' });\n _this.gui = _this.parent.createElement('div');\n _this.chkAllBox = _this.parent.createElement('input', { className: 'e-checkselectall', attrs: { 'type': 'checkbox' } });\n return _this;\n }\n /**\n * Function to return the wrapper for the TH content.\n * @returns string\n */\n HeaderCellRenderer.prototype.getGui = function () {\n return this.gui.cloneNode();\n };\n /**\n * Function to render the cell content based on Column object.\n * @param {Column} column\n * @param {Object} data\n * @param {Element}\n */\n HeaderCellRenderer.prototype.render = function (cell, data, attributes) {\n var node = this.element.cloneNode();\n var fltrMenuEle = this.parent.createElement('div', { className: 'e-filtermenudiv e-icons e-icon-filter' });\n return this.prepareHeader(cell, node, fltrMenuEle);\n };\n /**\n * Function to refresh the cell content based on Column object.\n * @param {Cell} cell\n * @param {Element} node\n */\n HeaderCellRenderer.prototype.refresh = function (cell, node) {\n this.clean(node);\n var fltrMenuEle = this.parent.createElement('div', { className: 'e-filtermenudiv e-icons e-icon-filter' });\n return this.prepareHeader(cell, node, fltrMenuEle);\n };\n HeaderCellRenderer.prototype.clean = function (node) {\n node.innerHTML = '';\n };\n HeaderCellRenderer.prototype.prepareHeader = function (cell, node, fltrMenuEle) {\n var column = cell.column;\n var ariaAttr = {};\n //Prepare innerHtml\n var innerDIV = this.getGui();\n attributes(innerDIV, {\n 'e-mappinguid': column.uid,\n 'class': 'e-headercelldiv'\n });\n if (column.type !== 'checkbox') {\n var value = column.headerText;\n var headerText = this.hTxtEle.cloneNode();\n headerText[column.getDomSetter()] = value;\n innerDIV.appendChild(headerText);\n }\n else {\n column.editType = 'booleanedit';\n var checkAllWrap = createCheckBox(this.parent.createElement, false, { checked: false, label: ' ' });\n checkAllWrap.insertBefore(this.chkAllBox.cloneNode(), checkAllWrap.firstChild);\n innerDIV.appendChild(checkAllWrap);\n innerDIV.classList.add('e-headerchkcelldiv');\n }\n this.buildAttributeFromCell(node, cell);\n this.appendHtml(node, innerDIV);\n node.appendChild(this.sortEle.cloneNode());\n if ((this.parent.allowFiltering && this.parent.filterSettings.type !== 'FilterBar') &&\n (column.allowFiltering && !isNullOrUndefined(column.field)) &&\n !(this.parent.showColumnMenu && column.showColumnMenu)) {\n attributes(fltrMenuEle, {\n 'e-mappinguid': 'e-flmenu-' + column.uid,\n });\n node.classList.add('e-fltr-icon');\n var matchFlColumns = [];\n if (this.parent.filterSettings.columns.length && this.parent.filterSettings.columns.length !== matchFlColumns.length) {\n for (var index = 0; index < this.parent.columns.length; index++) {\n for (var count = 0; count < this.parent.filterSettings.columns.length; count++) {\n if (this.parent.filterSettings.columns[count].field === column.field) {\n fltrMenuEle.classList.add('e-filtered');\n matchFlColumns.push(column.field);\n break;\n }\n }\n }\n }\n node.appendChild(fltrMenuEle.cloneNode());\n }\n if (cell.className) {\n node.classList.add(cell.className);\n }\n if (column.customAttributes) {\n setStyleAndAttributes(node, column.customAttributes);\n }\n if (column.allowSorting) {\n ariaAttr.sort = 'none';\n }\n if (column.allowGrouping) {\n ariaAttr.grabbed = false;\n }\n node = this.extendPrepareHeader(column, node);\n var result;\n var gridObj = this.parent;\n var colIndex = gridObj.getColumnIndexByField(column.field);\n if (!isNullOrUndefined(column.headerTemplate)) {\n result = column.getHeaderTemplate()(extend({ 'index': colIndex }, column), gridObj, 'headerTemplate');\n node.firstElementChild.innerHTML = '';\n appendChildren(node.firstElementChild, result);\n }\n this.ariaService.setOptions(node, ariaAttr);\n if (!isNullOrUndefined(column.headerTextAlign) || !isNullOrUndefined(column.textAlign)) {\n var alignment = column.headerTextAlign || column.textAlign;\n innerDIV.style.textAlign = alignment;\n if (alignment === 'Right' || alignment === 'Left') {\n node.classList.add(alignment === 'Right' ? 'e-rightalign' : 'e-leftalign');\n }\n else if (alignment === 'Center') {\n node.classList.add('e-centeralign');\n }\n }\n if (column.clipMode === 'Clip') {\n node.classList.add('e-gridclip');\n }\n else if (column.clipMode === 'EllipsisWithTooltip') {\n node.classList.add('e-ellipsistooltip');\n }\n node.setAttribute('aria-rowspan', (!isNullOrUndefined(cell.rowSpan) ? cell.rowSpan : 1).toString());\n node.setAttribute('aria-colspan', '1');\n this.parent.trigger(headerCellInfo, { cell: cell, node: node });\n return node;\n };\n HeaderCellRenderer.prototype.extendPrepareHeader = function (column, node) {\n if (this.parent.showColumnMenu && column.showColumnMenu && !isNullOrUndefined(column.field)) {\n var element = (this.parent.createElement('div', { className: 'e-icons e-columnmenu' }));\n var matchFilteredColumns = [];\n if (this.parent.filterSettings.columns.length && this.parent.filterSettings.columns.length !== matchFilteredColumns.length) {\n for (var i = 0; i < this.parent.columns.length; i++) {\n for (var j = 0; j < this.parent.filterSettings.columns.length; j++) {\n if (this.parent.filterSettings.columns[j].field === column.field) {\n element.classList.add('e-filtered');\n matchFilteredColumns.push(column.field);\n break;\n }\n }\n }\n }\n node.classList.add('e-fltr-icon');\n node.appendChild(element);\n }\n if (this.parent.allowResizing) {\n var handler = this.parent.createElement('div');\n handler.className = column.allowResizing ? 'e-rhandler e-rcursor' : 'e-rsuppress';\n node.appendChild(handler);\n }\n return node;\n };\n /**\n * Function to specifies how the result content to be placed in the cell.\n * @param {Element} node\n * @param {string|Element} innerHtml\n * @returns Element\n */\n HeaderCellRenderer.prototype.appendHtml = function (node, innerHtml) {\n node.appendChild(innerHtml);\n return node;\n };\n return HeaderCellRenderer;\n}(CellRenderer));\nexport { HeaderCellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { CellRenderer } from './cell-renderer';\nimport { headerCellInfo } from '../base/constant';\n/**\n * StackedHeaderCellRenderer class which responsible for building stacked header cell content.\n * @hidden\n */\nvar StackedHeaderCellRenderer = /** @class */ (function (_super) {\n __extends(StackedHeaderCellRenderer, _super);\n function StackedHeaderCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent.createElement('TH', {\n className: 'e-headercell e-stackedheadercell', attrs: {\n role: 'columnheader',\n tabindex: '-1'\n }\n });\n return _this;\n }\n /**\n * Function to render the cell content based on Column object.\n * @param {Column} column\n * @param {Object} data\n * @param {Element}\n */\n StackedHeaderCellRenderer.prototype.render = function (cell, data, attributes) {\n var node = this.element.cloneNode();\n var div = this.parent.createElement('div', { className: 'e-stackedheadercelldiv' });\n node.appendChild(div);\n div.innerHTML = cell.column.headerText;\n if (cell.column.toolTip) {\n node.setAttribute('title', cell.column.toolTip);\n }\n if (!isNullOrUndefined(cell.column.textAlign)) {\n div.style.textAlign = cell.column.textAlign;\n }\n node.setAttribute('colspan', cell.colSpan.toString());\n node.setAttribute('aria-colspan', cell.colSpan.toString());\n node.setAttribute('aria-rowspan', '1');\n this.parent.trigger(headerCellInfo, { cell: cell, node: node });\n return node;\n };\n return StackedHeaderCellRenderer;\n}(CellRenderer));\nexport { StackedHeaderCellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { setStyleAndAttributes } from '../base/util';\nimport { CellRenderer } from './cell-renderer';\n/**\n * IndentCellRenderer class which responsible for building group indent cell.\n * @hidden\n */\nvar IndentCellRenderer = /** @class */ (function (_super) {\n __extends(IndentCellRenderer, _super);\n function IndentCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent.createElement('TD', { className: 'e-indentcell' });\n return _this;\n }\n /**\n * Function to render the indent cell\n * @param {Cell} cell\n * @param {Object} data\n */\n IndentCellRenderer.prototype.render = function (cell, data) {\n var node = this.element.cloneNode();\n setStyleAndAttributes(node, cell.attributes);\n return node;\n };\n return IndentCellRenderer;\n}(CellRenderer));\nexport { IndentCellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { CellRenderer } from './cell-renderer';\nimport { appendChildren, templateCompiler } from '../base/util';\n/**\n * GroupCaptionCellRenderer class which responsible for building group caption cell.\n * @hidden\n */\nvar GroupCaptionCellRenderer = /** @class */ (function (_super) {\n __extends(GroupCaptionCellRenderer, _super);\n function GroupCaptionCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent\n .createElement('TD', { className: 'e-groupcaption', attrs: { role: 'gridcell', tabindex: '-1' } });\n return _this;\n }\n /**\n * Function to render the cell content based on Column object.\n * @param {Cell} cell\n * @param {Object} data\n */\n GroupCaptionCellRenderer.prototype.render = function (cell, data) {\n var node = this.element.cloneNode();\n var gObj = this.parent;\n var result;\n var helper = {};\n var fKeyValue;\n data.headerText = cell.column.headerText;\n if (cell.isForeignKey) {\n fKeyValue = this.format(cell.column, cell.column.valueAccessor('foreignKey', data, cell.column));\n }\n var value = cell.isForeignKey ? fKeyValue : cell.column.enableGroupByFormat ? data.key :\n this.format(cell.column, cell.column.valueAccessor('key', data, cell.column));\n if (!isNullOrUndefined(gObj.groupSettings.captionTemplate)) {\n if (gObj.groupSettings.captionTemplate.indexOf('#') !== -1) {\n result = templateCompiler(document.querySelector(gObj.groupSettings.captionTemplate).innerHTML.trim())(data);\n }\n else {\n result = templateCompiler(gObj.groupSettings.captionTemplate)(data);\n }\n appendChildren(node, result);\n }\n else {\n node.innerHTML = cell.column.headerText + ': ' + value + ' - ' + data.count + ' ' +\n (data.count < 2 ? this.localizer.getConstant('Item') : this.localizer.getConstant('Items'));\n }\n node.setAttribute('colspan', cell.colSpan.toString());\n node.setAttribute('aria-label', node.innerHTML + ' is groupcaption cell');\n node.setAttribute('title', node.innerHTML);\n return node;\n };\n return GroupCaptionCellRenderer;\n}(CellRenderer));\nexport { GroupCaptionCellRenderer };\n/**\n * GroupCaptionEmptyCellRenderer class which responsible for building group caption empty cell.\n * @hidden\n */\nvar GroupCaptionEmptyCellRenderer = /** @class */ (function (_super) {\n __extends(GroupCaptionEmptyCellRenderer, _super);\n function GroupCaptionEmptyCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent.createElement('TD', { className: 'e-groupcaption' });\n return _this;\n }\n /**\n * Function to render the cell content based on Column object.\n * @param {Cell} cell\n * @param {Object} data\n */\n GroupCaptionEmptyCellRenderer.prototype.render = function (cell, data) {\n var node = this.element.cloneNode();\n node.innerHTML = ' ';\n node.setAttribute('colspan', cell.colSpan.toString());\n return node;\n };\n return GroupCaptionEmptyCellRenderer;\n}(CellRenderer));\nexport { GroupCaptionEmptyCellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { IndentCellRenderer } from './indent-cell-renderer';\n/**\n * ExpandCellRenderer class which responsible for building group expand cell.\n * @hidden\n */\nvar ExpandCellRenderer = /** @class */ (function (_super) {\n __extends(ExpandCellRenderer, _super);\n function ExpandCellRenderer() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * Function to render the expand cell\n * @param {Cell} cell\n * @param {Object} data\n */\n ExpandCellRenderer.prototype.render = function (cell, data) {\n var node = this.element.cloneNode();\n node.className = 'e-recordplusexpand';\n node.setAttribute('ej-mappingname', data.field);\n node.setAttribute('ej-mappingvalue', data.key);\n node.setAttribute('aria-expanded', 'true');\n node.setAttribute('tabindex', '-1');\n node.appendChild(this.parent.createElement('div', { className: 'e-icons e-gdiagonaldown e-icon-gdownarrow' }));\n return node;\n };\n return ExpandCellRenderer;\n}(IndentCellRenderer));\nexport { ExpandCellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { CellRenderer } from './cell-renderer';\n/**\n * HeaderIndentCellRenderer class which responsible for building header indent cell.\n * @hidden\n */\nvar HeaderIndentCellRenderer = /** @class */ (function (_super) {\n __extends(HeaderIndentCellRenderer, _super);\n function HeaderIndentCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent.createElement('TH', { className: 'e-grouptopleftcell' });\n return _this;\n }\n /**\n * Function to render the indent cell\n * @param {Cell} cell\n * @param {Object} data\n */\n HeaderIndentCellRenderer.prototype.render = function (cell, data) {\n var node = this.element.cloneNode();\n node.appendChild(this.parent.createElement('div', { className: 'e-headercelldiv e-emptycell', innerHTML: '' }));\n return node;\n };\n return HeaderIndentCellRenderer;\n}(CellRenderer));\nexport { HeaderIndentCellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { CellRenderer } from './cell-renderer';\n/**\n * DetailHeaderIndentCellRenderer class which responsible for building detail header indent cell.\n * @hidden\n */\nvar DetailHeaderIndentCellRenderer = /** @class */ (function (_super) {\n __extends(DetailHeaderIndentCellRenderer, _super);\n function DetailHeaderIndentCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent.createElement('TH', { className: 'e-detailheadercell' });\n return _this;\n }\n /**\n * Function to render the detail indent cell\n * @param {Cell} cell\n * @param {Object} data\n */\n DetailHeaderIndentCellRenderer.prototype.render = function (cell, data) {\n var node = this.element.cloneNode();\n node.appendChild(this.parent.createElement('div', { className: 'e-emptycell' }));\n return node;\n };\n return DetailHeaderIndentCellRenderer;\n}(CellRenderer));\nexport { DetailHeaderIndentCellRenderer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { CellRenderer } from './cell-renderer';\n/**\n * ExpandCellRenderer class which responsible for building group expand cell.\n * @hidden\n */\nvar DetailExpandCellRenderer = /** @class */ (function (_super) {\n __extends(DetailExpandCellRenderer, _super);\n function DetailExpandCellRenderer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.element = _this.parent.createElement('TD', {\n className: 'e-detailrowcollapse',\n attrs: { 'aria-expanded': 'false', role: 'gridcell', tabindex: '-1' }\n });\n return _this;\n }\n /**\n * Function to render the detail expand cell\n */\n DetailExpandCellRenderer.prototype.render = function (cell, data, attributes) {\n var node = this.element.cloneNode();\n if (attributes && !isNullOrUndefined(attributes['class'])) {\n node.className = '';\n node.className = attributes['class'];\n node.appendChild(this.parent.createElement('div', { className: 'e-icons e-dtdiagonaldown e-icon-gdownarrow' }));\n }\n else {\n node.appendChild(this.parent.createElement('div', { className: 'e-icons e-dtdiagonalright e-icon-grightarrow' }));\n }\n return node;\n };\n return DetailExpandCellRenderer;\n}(CellRenderer));\nexport { DetailExpandCellRenderer };\n","import { remove } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, extend } from '@syncfusion/ej2-base';\nimport { DataManager, Query, Deferred, Predicate, DataUtil } from '@syncfusion/ej2-data';\nimport { ValueFormatter } from '../services/value-formatter';\nimport { RenderType, CellType } from '../base/enum';\nimport { Data } from '../actions/data';\nimport { Row } from '../models/row';\nimport { Cell } from '../models/cell';\nimport * as events from '../base/constant';\nimport { prepareColumns, setFormatter, getDatePredicate } from '../base/util';\nimport { ContentRender } from '../renderer/content-renderer';\nimport { HeaderRender } from '../renderer/header-renderer';\nimport { CellRenderer } from '../renderer/cell-renderer';\nimport { HeaderCellRenderer } from '../renderer/header-cell-renderer';\nimport { StackedHeaderCellRenderer } from '../renderer/stacked-cell-renderer';\nimport { IndentCellRenderer } from '../renderer/indent-cell-renderer';\nimport { GroupCaptionCellRenderer, GroupCaptionEmptyCellRenderer } from '../renderer/caption-cell-renderer';\nimport { ExpandCellRenderer } from '../renderer/expand-cell-renderer';\nimport { HeaderIndentCellRenderer } from '../renderer/header-indent-renderer';\nimport { DetailHeaderIndentCellRenderer } from '../renderer/detail-header-indent-renderer';\nimport { DetailExpandCellRenderer } from '../renderer/detail-expand-cell-renderer';\n/**\n * Content module is used to render grid content\n * @hidden\n */\nvar Render = /** @class */ (function () {\n /**\n * Constructor for render module\n */\n function Render(parent, locator) {\n this.emptyGrid = false;\n this.parent = parent;\n this.locator = locator;\n this.data = new Data(parent, locator);\n this.l10n = locator.getService('localization');\n this.ariaService = this.locator.getService('ariaService');\n this.renderer = this.locator.getService('rendererFactory');\n this.addEventListener();\n }\n /**\n * To initialize grid header, content and footer rendering\n */\n Render.prototype.render = function () {\n var gObj = this.parent;\n this.headerRenderer = this.renderer.getRenderer(RenderType.Header);\n this.contentRenderer = this.renderer.getRenderer(RenderType.Content);\n this.headerRenderer.renderPanel();\n this.contentRenderer.renderPanel();\n if (gObj.getColumns().length) {\n this.headerRenderer.renderTable();\n this.contentRenderer.renderTable();\n this.emptyRow(false);\n }\n this.refreshDataManager();\n };\n /**\n * Refresh the entire Grid.\n * @return {void}\n */\n Render.prototype.refresh = function (e) {\n if (e === void 0) { e = { requestType: 'refresh' }; }\n this.parent.notify(e.requestType + \"-begin\", e);\n this.parent.trigger(events.actionBegin, e);\n if (e.cancel) {\n this.parent.notify(events.cancelBegin, e);\n return;\n }\n this.refreshDataManager(e);\n };\n Render.prototype.refreshComplete = function (e) {\n this.parent.trigger(events.actionComplete, e);\n };\n /**\n * The function is used to refresh the dataManager\n * @return {void}\n */\n Render.prototype.refreshDataManager = function (args) {\n var _this = this;\n if (args === void 0) { args = {}; }\n if (args.requestType !== 'virtualscroll') {\n this.parent.showSpinner();\n }\n this.emptyGrid = false;\n var dataManager;\n var isFActon = this.isNeedForeignAction();\n this.ariaService.setBusy(this.parent.getContent().firstChild, true);\n if (isFActon) {\n var deffered = new Deferred();\n dataManager = this.getFData(deffered);\n }\n if (!dataManager) {\n dataManager = this.data.getData(args, this.data.generateQuery().requiresCount());\n }\n else {\n dataManager = dataManager.then(function (e) {\n var query = _this.data.generateQuery().requiresCount();\n if (_this.emptyGrid) {\n var def = new Deferred();\n def.resolve({ result: [], count: 0 });\n return def.promise;\n }\n return _this.data.getData(args, query);\n });\n }\n if (this.parent.getForeignKeyColumns().length && (!isFActon || this.parent.searchSettings.key.length)) {\n var deffered_1 = new Deferred();\n dataManager = dataManager.then(function (e) {\n _this.parent.notify(events.getForeignKeyData, { dataManager: dataManager, result: e, promise: deffered_1 });\n return deffered_1.promise;\n });\n }\n if (this.parent.groupSettings.disablePageWiseAggregates && this.parent.groupSettings.columns.length) {\n dataManager = dataManager.then(function (e) { return _this.validateGroupRecords(e); });\n }\n dataManager.then(function (e) { return _this.dataManagerSuccess(e, args); })\n .catch(function (e) { return _this.dataManagerFailure(e, args); });\n };\n Render.prototype.getFData = function (deferred) {\n this.parent.notify(events.getForeignKeyData, { isComplex: true, promise: deferred });\n return deferred.promise;\n };\n Render.prototype.isNeedForeignAction = function () {\n var gObj = this.parent;\n return !!((gObj.allowFiltering && gObj.filterSettings.columns.length) ||\n (gObj.searchSettings.key.length)) && this.foreignKey(this.parent.getForeignKeyColumns());\n };\n Render.prototype.foreignKey = function (columns) {\n var _this = this;\n return columns.some(function (col) {\n var fbool = false;\n fbool = _this.parent.filterSettings.columns.some(function (value) {\n return col.foreignKeyValue === value.field;\n });\n return !!(fbool || _this.parent.searchSettings.key.length);\n });\n };\n Render.prototype.sendBulkRequest = function (args) {\n var _this = this;\n var promise = this.data.saveChanges(args.changes, this.parent.getPrimaryKeyFieldNames()[0], args.original);\n var query = this.data.generateQuery().requiresCount();\n if (this.data.dataManager.dataSource.offline) {\n this.refreshDataManager({ requestType: 'batchsave' });\n return;\n }\n else {\n promise.then(function (e) {\n _this.data.getData(args, query)\n .then(function (e) { return _this.dmSuccess(e, args); })\n .catch(function (e) { return _this.dmFailure(e, args); });\n })\n .catch(function (e) { return _this.dmFailure(e, args); });\n }\n };\n Render.prototype.dmSuccess = function (e, args) {\n this.dataManagerSuccess(e, args);\n };\n Render.prototype.dmFailure = function (e, args) {\n this.dataManagerFailure(e, args);\n };\n /**\n * Render empty row to Grid which is used at the time to represent to no records.\n * @return {void}\n * @hidden\n */\n Render.prototype.renderEmptyRow = function () {\n this.emptyRow(true);\n };\n Render.prototype.emptyRow = function (isTrigger) {\n var gObj = this.parent;\n var tbody = this.contentRenderer.getTable().querySelector('tbody');\n var tr;\n remove(tbody);\n tbody = this.parent.createElement('tbody');\n tr = this.parent.createElement('tr', { className: 'e-emptyrow' });\n tr.appendChild(this.parent.createElement('td', {\n innerHTML: this.l10n.getConstant('EmptyRecord'),\n attrs: { colspan: gObj.getColumns().length.toString() }\n }));\n tbody.appendChild(tr);\n this.contentRenderer.renderEmpty(tbody);\n if (isTrigger) {\n this.parent.trigger(events.dataBound, {});\n this.parent.notify(events.onEmpty, { rows: [new Row({ isDataRow: true, cells: [new Cell({ isDataCell: true, visible: true })] })] });\n }\n };\n Render.prototype.dynamicColumnChange = function () {\n if (this.parent.getCurrentViewRecords().length) {\n this.updateColumnType(this.parent.getCurrentViewRecords()[0]);\n }\n };\n Render.prototype.updateColumnType = function (record) {\n var columns = this.parent.getColumns();\n var value;\n var data = record && record.items ? record.items[0] : record;\n var fmtr = this.locator.getService('valueFormatter');\n for (var i = 0, len = columns.length; i < len; i++) {\n value = DataUtil.getObject(columns[i].field || '', data);\n if (columns[i].isForeignColumn() && columns[i].columnData) {\n value = DataUtil.getObject(columns[i].foreignKeyValue || '', columns[i].columnData[0]);\n }\n if (!isNullOrUndefined(value)) {\n this.isColTypeDef = true;\n if (!columns[i].type) {\n columns[i].type = value.getDay ? (value.getHours() > 0 || value.getMinutes() > 0 ||\n value.getSeconds() > 0 || value.getMilliseconds() > 0 ? 'datetime' : 'date') : typeof (value);\n }\n }\n else {\n columns[i].type = columns[i].type || null;\n }\n var valueFormatter = new ValueFormatter();\n if (columns[i].format && (columns[i].format.skeleton || columns[i].format.format)) {\n columns[i].setFormatter(valueFormatter.getFormatFunction(columns[i].format));\n columns[i].setParser(valueFormatter.getParserFunction(columns[i].format));\n }\n if (typeof (columns[i].format) === 'string') {\n setFormatter(this.locator, columns[i]);\n }\n else if (!columns[i].format && columns[i].type === 'number') {\n columns[i].setParser(fmtr.getParserFunction({ format: 'n2' }));\n }\n }\n };\n Render.prototype.dataManagerSuccess = function (e, args) {\n var gObj = this.parent;\n gObj.trigger(events.beforeDataBound, e);\n var len = Object.keys(e.result).length;\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.isEdit = false;\n this.parent.notify(events.tooltipDestroy, {});\n gObj.currentViewData = e.result;\n if (!len && e.count && gObj.allowPaging) {\n gObj.prevPageMoving = true;\n gObj.pageSettings.totalRecordsCount = e.count;\n gObj.pageSettings.currentPage = Math.ceil(e.count / gObj.pageSettings.pageSize);\n gObj.dataBind();\n return;\n }\n if (!gObj.getColumns().length && len) {\n this.updatesOnInitialRender(e);\n }\n if (!this.isColTypeDef && gObj.getCurrentViewRecords()) {\n this.updateColumnType(gObj.getCurrentViewRecords()[0]);\n }\n this.parent.notify(events.dataReady, extend({ count: e.count, result: e.result, aggregates: e.aggregates }, args));\n if (gObj.groupSettings.columns.length || (args && args.requestType === 'ungrouping')) {\n this.headerRenderer.refreshUI();\n }\n if (len) {\n this.contentRenderer.refreshContentRows(args);\n }\n else {\n if (!gObj.getColumns().length) {\n gObj.element.innerHTML = '';\n alert(this.l10n.getConstant('EmptyDataSourceError')); //ToDO: change this alert as dialog\n return;\n }\n this.contentRenderer.setRowElements([]);\n this.renderEmptyRow();\n if (args) {\n var action = (args.requestType || '').toLowerCase() + '-complete';\n this.parent.notify(action, args);\n }\n this.parent.hideSpinner();\n }\n this.parent.notify(events.toolbarRefresh, {});\n };\n Render.prototype.dataManagerFailure = function (e, args) {\n this.ariaService.setOptions(this.parent.getContent().firstChild, { busy: false, invalid: true });\n this.parent.trigger(events.actionFailure, { error: e });\n this.parent.hideSpinner();\n if (args.requestType === 'save' || args.requestType === 'delete'\n || args.name === 'bulk-save') {\n return;\n }\n this.parent.currentViewData = [];\n this.renderEmptyRow();\n };\n Render.prototype.updatesOnInitialRender = function (e) {\n this.buildColumns(e.result[0]);\n prepareColumns(this.parent.columns);\n this.headerRenderer.renderTable();\n this.contentRenderer.renderTable();\n this.parent.notify(events.autoCol, {});\n };\n Render.prototype.buildColumns = function (record) {\n var columns = Object.keys(record);\n var cols = [];\n for (var i = 0, len = columns.length; i < len; i++) {\n cols[i] = { 'field': columns[i] };\n if (this.parent.enableColumnVirtualization) {\n cols[i].width = !isNullOrUndefined(cols[i].width) ? cols[i].width : 200;\n }\n }\n this.parent.columns = cols;\n };\n Render.prototype.instantiateRenderer = function () {\n this.renderer.addRenderer(RenderType.Header, new HeaderRender(this.parent, this.locator));\n this.renderer.addRenderer(RenderType.Content, new ContentRender(this.parent, this.locator));\n var cellrender = this.locator.getService('cellRendererFactory');\n cellrender.addCellRenderer(CellType.Header, new HeaderCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.Data, new CellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.StackedHeader, new StackedHeaderCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.Indent, new IndentCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.GroupCaption, new GroupCaptionCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.GroupCaptionEmpty, new GroupCaptionEmptyCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.Expand, new ExpandCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.HeaderIndent, new HeaderIndentCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.StackedHeader, new StackedHeaderCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.DetailHeader, new DetailHeaderIndentCellRenderer(this.parent, this.locator));\n cellrender.addCellRenderer(CellType.DetailExpand, new DetailExpandCellRenderer(this.parent, this.locator));\n };\n Render.prototype.addEventListener = function () {\n var _this = this;\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.initialLoad, this.instantiateRenderer, this);\n this.parent.on(events.modelChanged, this.refresh, this);\n this.parent.on(events.refreshComplete, this.refreshComplete, this);\n this.parent.on(events.bulkSave, this.sendBulkRequest, this);\n this.parent.on(events.showEmptyGrid, function () { _this.emptyGrid = true; }, this);\n this.parent.on(events.autoCol, this.dynamicColumnChange, this);\n };\n /** @hidden */\n Render.prototype.validateGroupRecords = function (e) {\n var _this = this;\n var index = e.result.length - 1;\n if (index < 0) {\n return Promise.resolve(e);\n }\n var group0 = e.result[0];\n var groupN = e.result[index];\n var predicate = [];\n var addWhere = function (input) {\n [group0, groupN].forEach(function (group) {\n return predicate.push(new Predicate('field', '==', group.field).and(_this.getPredicate('key', 'equal', group.key)));\n });\n input.where(Predicate.or(predicate));\n };\n var query = new Query();\n addWhere(query);\n var curDm = new DataManager(e.result);\n var curFilter = curDm.executeLocal(query);\n var newQuery = this.data.generateQuery(true);\n var rPredicate = [];\n if (this.data.isRemote()) {\n [group0, groupN].forEach(function (group) {\n return rPredicate.push(_this.getPredicate(group.field, 'equal', group.key));\n });\n newQuery.where(Predicate.or(rPredicate));\n }\n else {\n addWhere(newQuery);\n }\n var deferred = new Deferred();\n this.data.getData({}, newQuery).then(function (r) {\n _this.updateGroupInfo(curFilter, r.result);\n deferred.resolve(e);\n }).catch(function (e) { return deferred.reject(e); });\n return deferred.promise;\n };\n Render.prototype.getPredicate = function (key, operator, value) {\n if (value instanceof Date) {\n return getDatePredicate({ field: key, operator: operator, value: value });\n }\n return new Predicate(key, operator, value);\n };\n Render.prototype.updateGroupInfo = function (current, untouched) {\n var _this = this;\n var dm = new DataManager(untouched);\n current.forEach(function (element, index, array) {\n var uGroup = dm.executeLocal(new Query()\n .where(new Predicate('field', '==', element.field).and(_this.getPredicate('key', 'equal', element.key))))[0];\n element.count = uGroup.count;\n var itemGroup = element.items;\n var uGroupItem = uGroup.items;\n if (itemGroup.GroupGuid) {\n element.items = _this.updateGroupInfo(element.items, uGroup.items);\n }\n _this.parent.aggregates.forEach(function (row) {\n return row.columns.forEach(function (column) {\n var types = column.type instanceof Array ? column.type : [column.type];\n types.forEach(function (type) {\n var key = column.field + ' - ' + type.toLowerCase();\n var data = itemGroup.level ? uGroupItem.records : uGroup.items;\n var context = _this.parent;\n if (type === 'Custom') {\n element.aggregates[key] = column.customAggregate ?\n column.customAggregate.call(context, data, column) : '';\n }\n else {\n element.aggregates[key] = DataUtil.aggregates[type.toLowerCase()](data, column.field);\n }\n });\n });\n });\n });\n return current;\n };\n return Render;\n}());\nexport { Render };\n","import { isNullOrUndefined, getEnumValue } from '@syncfusion/ej2-base';\nimport { CellType } from '../base/enum';\n/**\n * CellRendererFactory\n * @hidden\n */\nvar CellRendererFactory = /** @class */ (function () {\n function CellRendererFactory() {\n this.cellRenderMap = {};\n }\n CellRendererFactory.prototype.addCellRenderer = function (name, type) {\n name = typeof name === 'string' ? name : getEnumValue(CellType, name);\n if (isNullOrUndefined(this.cellRenderMap[name])) {\n this.cellRenderMap[name] = type;\n }\n };\n CellRendererFactory.prototype.getCellRenderer = function (name) {\n name = typeof name === 'string' ? name : getEnumValue(CellType, name);\n if (isNullOrUndefined(this.cellRenderMap[name])) {\n throw \"The cellRenderer \" + name + \" is not found\";\n }\n else {\n return this.cellRenderMap[name];\n }\n };\n return CellRendererFactory;\n}());\nexport { CellRendererFactory };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\n/**\n * ServiceLocator\n * @hidden\n */\nvar ServiceLocator = /** @class */ (function () {\n function ServiceLocator() {\n this.services = {};\n }\n ServiceLocator.prototype.register = function (name, type) {\n if (isNullOrUndefined(this.services[name])) {\n this.services[name] = type;\n }\n };\n ServiceLocator.prototype.getService = function (name) {\n if (isNullOrUndefined(this.services[name])) {\n throw \"The service \" + name + \" is not registered\";\n }\n return this.services[name];\n };\n return ServiceLocator;\n}());\nexport { ServiceLocator };\n","import { isNullOrUndefined, getEnumValue } from '@syncfusion/ej2-base';\nimport { RenderType } from '../base/enum';\n/**\n * RendererFactory\n * @hidden\n */\nvar RendererFactory = /** @class */ (function () {\n function RendererFactory() {\n this.rendererMap = {};\n }\n RendererFactory.prototype.addRenderer = function (name, type) {\n var rName = getEnumValue(RenderType, name);\n if (isNullOrUndefined(this.rendererMap[rName])) {\n this.rendererMap[rName] = type;\n }\n };\n RendererFactory.prototype.getRenderer = function (name) {\n var rName = getEnumValue(RenderType, name);\n if (isNullOrUndefined(this.rendererMap[rName])) {\n throw \"The renderer \" + rName + \" is not found\";\n }\n else {\n return this.rendererMap[rName];\n }\n };\n return RendererFactory;\n}());\nexport { RendererFactory };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { formatUnit } from '@syncfusion/ej2-base';\nimport { columnWidthChanged } from '../base/constant';\nimport { Column } from '../models/column';\n/**\n * ColumnWidthService\n * @hidden\n */\nvar ColumnWidthService = /** @class */ (function () {\n function ColumnWidthService(parent) {\n this.parent = parent;\n }\n ColumnWidthService.prototype.setWidthToColumns = function () {\n var _this = this;\n var i = 0;\n var indexes = this.parent.getColumnIndexesInView();\n var wFlag = true;\n if (this.parent.allowGrouping) {\n for (var len = this.parent.groupSettings.columns.length; i < len; i++) {\n if (this.parent.enableColumnVirtualization && indexes.indexOf(i) === -1) {\n wFlag = false;\n continue;\n }\n this.setColumnWidth(new Column({ width: '30px' }), i);\n }\n }\n if (this.parent.detailTemplate || this.parent.childGrid) {\n this.setColumnWidth(new Column({ width: '30px' }), i);\n }\n this.parent.getColumns().forEach(function (column, index) {\n _this.setColumnWidth(column, wFlag ? undefined : index);\n });\n };\n ColumnWidthService.prototype.setColumnWidth = function (column, index, module) {\n var columnIndex = isNullOrUndefined(index) ? this.parent.getNormalizedColumnIndex(column.uid) : index;\n var cWidth = this.getWidth(column);\n if (cWidth !== null) {\n this.setWidth(cWidth, columnIndex);\n if ((this.parent.allowResizing && module === 'resize') || (this.parent.getFrozenColumns() && this.parent.allowResizing)) {\n this.setWidthToTable();\n }\n this.parent.notify(columnWidthChanged, { index: columnIndex, width: cWidth, column: column, module: module });\n }\n };\n ColumnWidthService.prototype.setWidth = function (width, index) {\n if (typeof (width) === 'string' && width.indexOf('%') !== -1) {\n var elementWidth = this.parent.element.offsetWidth;\n width = parseInt(width, 10) / 100 * (elementWidth);\n }\n var header = this.parent.getHeaderTable();\n var content = this.parent.getContentTable();\n var fWidth = formatUnit(width);\n var headerCol;\n var frzCols = this.parent.getFrozenColumns();\n var mHdr = this.parent.getHeaderContent().querySelector('.e-movableheader');\n if (frzCols && index >= frzCols && mHdr && mHdr.querySelector('colgroup')) {\n headerCol = mHdr.querySelector('colgroup').children[index - frzCols];\n }\n else {\n headerCol = header.querySelector('colgroup').children[index];\n }\n if (headerCol) {\n headerCol.style.width = fWidth;\n }\n var contentCol;\n if (frzCols && index >= frzCols) {\n contentCol = this.parent.getContent().querySelector('.e-movablecontent')\n .querySelector('colgroup').children[index - frzCols];\n }\n else {\n contentCol = content.querySelector('colgroup').children[index];\n }\n if (contentCol) {\n contentCol.style.width = fWidth;\n }\n var edit = content.querySelector('.e-table.e-inline-edit');\n if (edit) {\n if (edit.querySelector('colgroup').children[index]) {\n edit.querySelector('colgroup').children[index].style.width = fWidth;\n }\n }\n };\n ColumnWidthService.prototype.getSiblingsHeight = function (element) {\n var previous = this.getHeightFromDirection(element, 'previous');\n var next = this.getHeightFromDirection(element, 'next');\n return previous + next;\n };\n ColumnWidthService.prototype.getHeightFromDirection = function (element, direction) {\n var sibling = element[direction + 'ElementSibling'];\n var result = 0;\n var classList = ['e-gridheader', 'e-gridfooter', 'e-groupdroparea', 'e-gridpager', 'e-toolbar'];\n while (sibling) {\n if (classList.some(function (value) { return sibling.classList.contains(value); })) {\n result += sibling.offsetHeight;\n }\n sibling = sibling[direction + 'ElementSibling'];\n }\n return result;\n };\n ColumnWidthService.prototype.getWidth = function (column) {\n if (isNullOrUndefined(column.width) && this.parent.allowResizing) {\n column.width = 200;\n }\n if (!column.width) {\n return null;\n }\n var width = parseInt(column.width.toString(), 10);\n if (column.minWidth && width < parseInt(column.minWidth.toString(), 10)) {\n return column.minWidth;\n }\n else if ((column.maxWidth && width > parseInt(column.maxWidth.toString(), 10))) {\n return column.maxWidth;\n }\n else {\n return column.width;\n }\n };\n ColumnWidthService.prototype.getTableWidth = function (columns) {\n var tWidth = 0;\n for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {\n var column = columns_1[_i];\n var cWidth = this.getWidth(column);\n if (column.visible !== false && cWidth !== null) {\n tWidth += parseInt(cWidth.toString(), 10);\n }\n }\n return tWidth;\n };\n ColumnWidthService.prototype.setWidthToFrozenTable = function () {\n var columns = this.parent.getColumns();\n columns.splice(this.parent.getFrozenColumns(), columns.length);\n var freezeWidth = formatUnit(this.getTableWidth(columns));\n this.parent.getHeaderTable().style.width = freezeWidth;\n this.parent.getContentTable().style.width = freezeWidth;\n };\n ColumnWidthService.prototype.setWidthToMovableTable = function () {\n var columns = this.parent.getColumns();\n columns.splice(0, this.parent.getFrozenColumns());\n var movableWidth = formatUnit(this.getTableWidth(columns));\n if (this.parent.getHeaderContent().querySelector('.e-movableheader').firstElementChild) {\n this.parent.getHeaderContent().querySelector('.e-movableheader').firstElementChild.style.width\n = movableWidth;\n }\n this.parent.getContent().querySelector('.e-movablecontent').firstElementChild.style.width =\n movableWidth;\n };\n ColumnWidthService.prototype.setWidthToTable = function () {\n var tWidth = formatUnit(this.getTableWidth(this.parent.getColumns()));\n if (this.parent.getFrozenColumns()) {\n this.setWidthToFrozenTable();\n this.setWidthToMovableTable();\n }\n else {\n if (this.parent.detailTemplate || this.parent.childGrid) {\n this.setColumnWidth(new Column({ width: '30px' }));\n }\n this.parent.getHeaderTable().style.width = tWidth;\n this.parent.getContentTable().style.width = tWidth;\n }\n var edit = this.parent.element.querySelector('.e-table.e-inline-edit');\n if (edit) {\n edit.style.width = tWidth;\n }\n };\n return ColumnWidthService;\n}());\nexport { ColumnWidthService };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { EventHandler, getValue, closest, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { addClass, removeClass, extend, Browser } from '@syncfusion/ej2-base';\nimport { CellType } from '../base/enum';\nimport * as event from '../base/constant';\n/**\n * FocusStrategy class\n * @hidden\n */\nvar FocusStrategy = /** @class */ (function () {\n function FocusStrategy(parent) {\n this.currentInfo = {};\n this.oneTime = true;\n this.swap = {};\n this.forget = true;\n this.skipFocus = true;\n this.focusByClick = false;\n this.prevIndexes = {};\n this.parent = parent;\n this.addEventListener();\n }\n FocusStrategy.prototype.focusCheck = function (e) {\n var target = e.target;\n this.focusByClick = true;\n this.skipFocus = target.classList.contains('e-grid');\n };\n FocusStrategy.prototype.onFocus = function () {\n if (this.parent.isDestroyed || Browser.isDevice || this.parent.enableVirtualization) {\n return;\n }\n this.setActive(this.parent.frozenRows === 0, this.parent.frozenColumns !== 0);\n var current = this.getContent().matrix.get(0, -1, [0, 1], null, this.getContent().validator());\n this.getContent().matrix.select(current[0], current[1]);\n if (this.skipFocus) {\n this.focus();\n this.skipFocus = false;\n }\n };\n FocusStrategy.prototype.passiveFocus = function (e) {\n if (this.parent.isDestroyed) {\n return;\n }\n if (e.target && e.target.classList.contains('e-detailcell')) {\n this.currentInfo.skipAction = false;\n addClass([this.currentInfo.element], ['e-focused', 'e-focus']);\n }\n };\n FocusStrategy.prototype.onBlur = function (e) {\n if ((this.parent.isEdit || e && (!e.relatedTarget || closest(e.relatedTarget, '.e-grid')))) {\n return;\n }\n this.removeFocus();\n this.skipFocus = false;\n this.currentInfo.skipAction = false;\n if (this.getContent().getFocusInfo().elementToFocus) {\n this.getContent().getFocusInfo().elementToFocus.tabIndex = 0;\n }\n };\n FocusStrategy.prototype.onClick = function (e, force) {\n var isContent = !isNullOrUndefined(closest(e.target, '.e-gridcontent'));\n var isHeader = !isNullOrUndefined(closest(e.target, '.e-gridheader'));\n isContent = isContent && isHeader ? !isContent : isContent;\n var isFrozen = !isNullOrUndefined(closest(e.target, '.e-frozencontent')) ||\n !isNullOrUndefined(closest(e.target, '.e-frozenheader'));\n if (!isContent && isNullOrUndefined(closest(e.target, '.e-gridheader')) ||\n e.target.classList.contains('e-content')) {\n return;\n }\n this.setActive(isContent, isFrozen);\n if (!isContent && isNullOrUndefined(closest(e.target, '.e-gridheader')) ||\n e.target.classList.contains('e-filtermenudiv')) {\n this.clearOutline();\n return;\n }\n var beforeArgs = { cancel: false, byKey: false, byClick: !isNullOrUndefined(e.target), clickArgs: e };\n this.parent.notify(event.beforeCellFocused, beforeArgs);\n if (beforeArgs.cancel || closest(e.target, '.e-inline-edit')) {\n return;\n }\n this.setActive(isContent, isFrozen);\n if (this.getContent()) {\n var returnVal = this.getContent().onClick(e, force);\n if (returnVal === false) {\n return;\n }\n this.focus();\n }\n };\n FocusStrategy.prototype.onKeyPress = function (e) {\n if (this.skipOn(e)) {\n return;\n }\n var beforeArgs = { cancel: false, byKey: true, byClick: false, keyArgs: e };\n this.parent.notify(event.beforeCellFocused, beforeArgs);\n if (beforeArgs.cancel) {\n return;\n }\n var bValue = this.getContent().matrix.current;\n this.currentInfo.outline = true;\n var swapInfo = this.getContent().jump(e.action, bValue);\n this.swap = swapInfo;\n if (swapInfo.swap) {\n this.setActive(!swapInfo.toHeader, swapInfo.toFrozen);\n this.getContent().matrix.current = this.getContent().getNextCurrent(bValue, swapInfo, this.active, e.action);\n this.prevIndexes = {};\n }\n this.setActiveByKey(e.action, this.getContent());\n var returnVal = this.getContent().onKeyPress(e);\n if (returnVal === false) {\n this.clearIndicator();\n return;\n }\n e.preventDefault();\n this.focus(e);\n };\n FocusStrategy.prototype.skipOn = function (e) {\n var target = e.target;\n if (!target) {\n return false;\n }\n if (this.currentInfo.skipAction) {\n this.clearIndicator();\n return true;\n }\n if (['pageUp', 'pageDown'].indexOf(e.action) > -1) {\n this.clearIndicator();\n return true;\n }\n return (e.action === 'delete'\n || (this.parent.editSettings.mode !== 'Batch' && (this.parent.isEdit || ['insert', 'f2'].indexOf(e.action) > -1))\n || (closest(document.activeElement, '.e-filterbarcell') !== null ||\n closest(document.activeElement, '#' + this.parent.element.id + '_searchbar') !== null\n && ['enter', 'leftArrow', 'rightArrow',\n 'shiftLeft', 'shiftRight', 'ctrlPlusA'].indexOf(e.action) > -1)\n || (closest(target, '.e-gridcontent') === null && closest(target, '.e-gridheader') === null)\n || (e.action === 'space' && (!target.classList.contains('e-gridchkbox') && closest(target, '.e-gridchkbox') === null\n && closest(target, '.e-headerchkcelldiv') === null)));\n };\n FocusStrategy.prototype.getFocusedElement = function () {\n return this.currentInfo.elementToFocus;\n };\n FocusStrategy.prototype.getContent = function () {\n return this.active || this.content;\n };\n FocusStrategy.prototype.setActive = function (content, isFrozen) {\n this.active = content ? isFrozen ? this.fContent : this.content :\n isFrozen ? this.fHeader : this.header;\n };\n FocusStrategy.prototype.setFocusedElement = function (element) {\n var _this = this;\n this.currentInfo.elementToFocus = element;\n setTimeout(function () { return _this.currentInfo.elementToFocus.focus(); }, 0);\n };\n FocusStrategy.prototype.focus = function (e) {\n this.removeFocus();\n this.addFocus(this.getContent().getFocusInfo(), e);\n };\n FocusStrategy.prototype.removeFocus = function (e) {\n if (!this.currentInfo.element) {\n return;\n }\n removeClass([this.currentInfo.element, this.currentInfo.elementToFocus], ['e-focused', 'e-focus']);\n this.currentInfo.element.tabIndex = -1;\n };\n FocusStrategy.prototype.addFocus = function (info, e) {\n this.currentInfo = info;\n this.currentInfo.outline = info.outline && !isNullOrUndefined(e);\n if (!info.element) {\n return;\n }\n var isFocused = info.elementToFocus.classList.contains('e-focus');\n if (isFocused) {\n return;\n }\n if (this.currentInfo.outline) {\n addClass([info.element], ['e-focused']);\n }\n addClass([info.elementToFocus], ['e-focus']);\n info.element.tabIndex = 0;\n if (!isFocused) {\n this.setFocusedElement(info.elementToFocus);\n }\n this.parent.notify(event.cellFocused, {\n element: info.elementToFocus,\n parent: info.element,\n indexes: this.getContent().matrix.current,\n byKey: !isNullOrUndefined(e),\n byClick: isNullOrUndefined(e),\n keyArgs: e,\n isJump: this.swap.swap,\n container: this.getContent().getInfo(e),\n outline: !isNullOrUndefined(e),\n swapInfo: this.swap\n });\n var _a = this.getContent().matrix.current, rowIndex = _a[0], cellIndex = _a[1];\n this.prevIndexes = { rowIndex: rowIndex, cellIndex: cellIndex };\n this.focusedColumnUid = this.parent.getColumnByIndex(cellIndex).uid;\n this.focusByClick = false;\n };\n FocusStrategy.prototype.refreshMatrix = function (content) {\n var _this = this;\n return function (e) {\n if (content && (e.args && e.args.isFrozen) && !_this.fContent) {\n _this.fContent = new FixedContentFocus(_this.parent);\n }\n else if (content && !_this.content) {\n _this.content = new ContentFocus(_this.parent);\n }\n if (!content && (e.args && e.args.isFrozen) && !_this.fHeader) {\n _this.fHeader = new FixedHeaderFocus(_this.parent);\n }\n else if (!content && !_this.header) {\n _this.header = new HeaderFocus(_this.parent);\n }\n var cFocus = content ? (e.args && e.args.isFrozen) ? _this.fContent : _this.content :\n (e.args && e.args.isFrozen) ? _this.fHeader : _this.header;\n var rows = content ? e.rows.slice(_this.parent.frozenRows) : e.rows;\n var updateRow = content ? e.rows.slice(0, _this.parent.frozenRows) : e.rows;\n var matrix = cFocus.matrix.generate(updateRow, cFocus.selector);\n cFocus.matrix.generate(rows, cFocus.selector);\n cFocus.generateRows(updateRow, { matrix: matrix, handlerInstance: (e.args && e.args.isFrozen) ? _this.fHeader : _this.header });\n if (!Browser.isDevice && !_this.focusByClick && e && e.args && e.args.requestType === 'paging') {\n _this.skipFocus = false;\n _this.parent.element.focus();\n }\n if (e && e.args && e.args.requestType === 'virtualscroll') {\n if (_this.currentInfo.uid) {\n var index_1;\n var bool = e.rows.some(function (row, i) {\n index_1 = i;\n return row.uid === _this.currentInfo.uid;\n });\n if (bool) {\n _this.content.matrix.current[0] = index_1;\n _this.content.matrix.current[1] = _this.parent.getColumnIndexByUid(_this.focusedColumnUid) || 0;\n _this.focus();\n }\n }\n }\n };\n };\n FocusStrategy.prototype.addEventListener = function () {\n var _this = this;\n if (this.parent.isDestroyed) {\n return;\n }\n EventHandler.add(this.parent.element, 'mousedown', this.focusCheck, this);\n EventHandler.add(this.parent.element, 'focus', this.onFocus, this);\n this.parent.element.addEventListener('focus', this.passiveHandler = function (e) { return _this.passiveFocus(e); }, true);\n EventHandler.add(this.parent.element, 'focusout', this.onBlur, this);\n this.parent.on(event.keyPressed, this.onKeyPress, this);\n this.parent.on(event.click, this.onClick, this);\n this.parent.on(event.contentReady, this.refreshMatrix(true), this);\n this.parent.on(event.headerRefreshed, this.refreshMatrix(), this);\n this.parent.on('close-edit', this.restoreFocus, this);\n ['start-edit', 'start-add'].forEach(function (evt) { return _this.parent.on(evt, _this.clearIndicator, _this); });\n ['sorting'].forEach(function (action) { return _this.parent.on(action + \"-complete\", _this.restoreFocus, _this); });\n this.parent.on(event.batchAdd, this.refreshMatrix(true), this);\n this.parent.on(event.batchCancel, this.refreshMatrix(true), this);\n this.parent.on(event.batchDelete, this.refreshMatrix(true), this);\n this.parent.on(event.detailDataBound, this.refreshMatrix(true), this);\n this.parent.on(event.onEmpty, this.refreshMatrix(true), this);\n this.parent.on(event.cellFocused, this.internalCellFocus, this);\n };\n FocusStrategy.prototype.removeEventListener = function () {\n var _this = this;\n if (this.parent.isDestroyed) {\n return;\n }\n EventHandler.remove(this.parent.element, 'mousedown', this.focusCheck);\n EventHandler.remove(this.parent.element, 'focus', this.onFocus);\n EventHandler.remove(this.parent.element, 'focusout', this.onBlur);\n this.parent.element.removeEventListener('focus', this.passiveHandler, true);\n this.parent.off(event.keyPressed, this.onKeyPress);\n this.parent.off(event.click, this.onClick);\n this.parent.off(event.contentReady, this.refreshMatrix(true));\n this.parent.off(event.headerRefreshed, this.refreshMatrix());\n this.parent.off('close-edit', this.restoreFocus);\n ['start-edit', 'start-add'].forEach(function (evt) { return _this.parent.off(evt, _this.clearOutline); });\n ['sorting'].forEach(function (action) { return _this.parent.off(action + \"-complete\", _this.restoreFocus); });\n this.parent.off(event.batchAdd, this.refreshMatrix(true));\n this.parent.off(event.batchDelete, this.refreshMatrix(true));\n this.parent.off(event.batchCancel, this.refreshMatrix(true));\n this.parent.off(event.detailDataBound, this.refreshMatrix(true));\n this.parent.off(event.onEmpty, this.refreshMatrix(true));\n this.parent.off(event.cellFocused, this.internalCellFocus);\n };\n FocusStrategy.prototype.destroy = function () {\n this.removeEventListener();\n };\n FocusStrategy.prototype.restoreFocus = function () {\n this.addFocus(this.getContent().getFocusInfo());\n };\n FocusStrategy.prototype.clearOutline = function () {\n this.getContent().matrix.current = this.getContent().matrix.get(0, -1, [0, 1], 'downArrow', this.getContent().validator());\n this.clearIndicator();\n };\n FocusStrategy.prototype.clearIndicator = function () {\n if (!this.currentInfo.element || !this.currentInfo.elementToFocus) {\n return;\n }\n removeClass([this.currentInfo.element, this.currentInfo.elementToFocus], ['e-focus', 'e-focused']);\n };\n FocusStrategy.prototype.getPrevIndexes = function () {\n var forget = this.forget;\n this.forget = false;\n return forget ? { rowIndex: null, cellIndex: null } : this.prevIndexes;\n };\n FocusStrategy.prototype.forgetPrevious = function () {\n this.forget = true;\n };\n FocusStrategy.prototype.setActiveByKey = function (action, active) {\n var _this = this;\n if (this.parent.frozenColumns === 0 && this.parent.frozenRows === 0) {\n return;\n }\n var info;\n var actions = {\n 'home': function () { return ({ toHeader: !info.isContent, toFrozen: true }); },\n 'end': function () { return ({ toHeader: !info.isContent, toFrozen: false }); },\n 'ctrlHome': function () { return ({ toHeader: true, toFrozen: _this.parent.frozenColumns !== 0 }); },\n 'ctrlEnd': function () { return ({ toHeader: false, toFrozen: false }); }\n };\n if (!(action in actions)) {\n return;\n }\n info = active.getInfo();\n var swap = actions[action]();\n this.setActive(!swap.toHeader, swap.toFrozen);\n this.getContent().matrix.current = active.matrix.current;\n };\n FocusStrategy.prototype.internalCellFocus = function (e) {\n if (!(e.byKey && e.container.isContent && e.keyArgs.action === 'enter'\n && (e.parent.classList.contains('e-detailcell') ||\n e.parent.classList.contains('e-unboundcell') || e.parent.classList.contains('e-templatecell')))) {\n return;\n }\n this.clearIndicator();\n var focusEle = this.getContent().getFocusable(this.getFocusedElement());\n this.setFocusedElement(focusEle);\n this.currentInfo.skipAction = true;\n };\n return FocusStrategy;\n}());\nexport { FocusStrategy };\n/**\n * Create matrix from row collection which act as mental model for cell navigation\n * @hidden\n */\nvar Matrix = /** @class */ (function () {\n function Matrix() {\n this.matrix = [];\n this.current = [];\n }\n Matrix.prototype.set = function (rowIndex, columnIndex, allow) {\n rowIndex = Math.max(0, Math.min(rowIndex, this.rows));\n columnIndex = Math.max(0, Math.min(columnIndex, this.columns));\n this.matrix[rowIndex] = this.matrix[rowIndex] || [];\n this.matrix[rowIndex][columnIndex] = allow ? 1 : 0;\n };\n Matrix.prototype.get = function (rowIndex, columnIndex, navigator, action, validator) {\n var tmp = columnIndex;\n if (rowIndex + navigator[0] < 0) {\n return [rowIndex, columnIndex];\n }\n rowIndex = Math.max(0, Math.min(rowIndex + navigator[0], this.rows));\n columnIndex = Math.max(0, Math.min(columnIndex + navigator[1], this.matrix[rowIndex].length - 1));\n if (tmp + navigator[1] > this.matrix[rowIndex].length - 1 && validator(rowIndex, columnIndex, action)) {\n return [rowIndex, tmp];\n }\n var first = this.first(this.matrix[rowIndex], columnIndex, navigator, true, action);\n columnIndex = first === null ? tmp : first;\n var val = getValue(rowIndex + \".\" + columnIndex, this.matrix);\n return this.inValid(val) || !validator(rowIndex, columnIndex, action) ?\n this.get(rowIndex, tmp, navigator, action, validator) : [rowIndex, columnIndex];\n };\n Matrix.prototype.first = function (vector, index, navigator, moveTo, action) {\n if (((index < 0 || index === vector.length) && this.inValid(vector[index])\n && (action !== 'upArrow' && action !== 'downArrow')) || !vector.some(function (v) { return v === 1; })) {\n return null;\n }\n return !this.inValid(vector[index]) ? index :\n this.first(vector, (['upArrow', 'downArrow', 'shiftUp', 'shiftDown'].indexOf(action) !== -1) ? moveTo ? 0 : ++index : index + navigator[1], navigator, false, action);\n };\n Matrix.prototype.select = function (rowIndex, columnIndex) {\n rowIndex = Math.max(0, Math.min(rowIndex, this.rows));\n columnIndex = Math.max(0, Math.min(columnIndex, this.matrix[rowIndex].length - 1));\n this.current = [rowIndex, columnIndex];\n };\n Matrix.prototype.generate = function (rows, selector) {\n var _this = this;\n this.rows = rows.length - 1;\n this.matrix = [];\n rows.forEach(function (row, rIndex) {\n var cells = row.cells.filter(function (c) { return c.isSpanned !== true; });\n _this.columns = Math.max(cells.length - 1, _this.columns | 0);\n cells.forEach(function (cell, cIndex) {\n _this.set(rIndex, cIndex, selector(row, cell));\n });\n });\n return this.matrix;\n };\n Matrix.prototype.inValid = function (value) {\n return value === 0 || value === undefined;\n };\n return Matrix;\n}());\nexport { Matrix };\n/**\n * @hidden\n */\nvar ContentFocus = /** @class */ (function () {\n function ContentFocus(parent) {\n var _this = this;\n this.matrix = new Matrix();\n this.parent = parent;\n this.keyActions = {\n 'rightArrow': [0, 1],\n 'tab': [0, 1],\n 'leftArrow': [0, -1],\n 'shiftTab': [0, -1],\n 'upArrow': [-1, 0],\n 'downArrow': [1, 0],\n 'shiftUp': [-1, 0],\n 'shiftDown': [1, 0],\n 'shiftRight': [0, 1],\n 'shiftLeft': [0, -1],\n 'enter': [1, 0],\n 'shiftEnter': [-1, 0]\n };\n this.indexesByKey = function (action) {\n var opt = {\n 'home': [_this.matrix.current[0], -1, 0, 1],\n 'end': [_this.matrix.current[0], _this.matrix.columns + 1, 0, -1],\n 'ctrlHome': [0, -1, 0, 1],\n 'ctrlEnd': [_this.matrix.rows, _this.matrix.columns + 1, 0, -1]\n };\n return opt[action] || null;\n };\n }\n ContentFocus.prototype.getTable = function () {\n return (this.parent.frozenColumns ?\n this.parent.getContent().querySelector('.e-movablecontent .e-table') :\n this.parent.getContentTable());\n };\n ContentFocus.prototype.onKeyPress = function (e) {\n var navigator = this.keyActions[e.action];\n var current = this.getCurrentFromAction(e.action, navigator, e.action in this.keyActions, e);\n if (!current) {\n return;\n }\n if ((['tab', 'shiftTab'].indexOf(e.action) > -1 && this.matrix.current || []).toString() === current.toString()) {\n if (current.toString() === [this.matrix.rows, this.matrix.columns].toString() ||\n current.toString() === [0, 0].toString()) {\n return false;\n }\n }\n this.matrix.select(current[0], current[1]);\n };\n ContentFocus.prototype.getCurrentFromAction = function (action, navigator, isPresent, e) {\n if (navigator === void 0) { navigator = [0, 0]; }\n if (!isPresent && !this.indexesByKey(action)) {\n return null;\n }\n if (!this.shouldFocusChange(e)) {\n return this.matrix.current;\n }\n var _a = this.indexesByKey(action) || this.matrix.current.concat(navigator), rowIndex = _a[0], cellIndex = _a[1], rN = _a[2], cN = _a[3];\n var current = this.matrix.get(rowIndex, cellIndex, [rN, cN], action, this.validator());\n return current;\n };\n ContentFocus.prototype.onClick = function (e, force) {\n var target = e.target;\n target = (target.classList.contains('e-rowcell') ? target : closest(target, 'td'));\n target = target ? target : closest(e.target, 'td.e-detailrowcollapse')\n || closest(e.target, 'td.e-detailrowexpand');\n target = closest(e.target, 'td.e-detailcell') ?\n isNullOrUndefined(closest(closest(e.target, '.e-grid'), 'td.e-detailcell')) ? null : target : target;\n target = target && closest(target, 'table').classList.contains('e-table') ? target : null;\n if (!target) {\n return false;\n }\n var _a = [target.parentElement.rowIndex, target.cellIndex], rowIndex = _a[0], cellIndex = _a[1];\n var _b = this.matrix.current, oRowIndex = _b[0], oCellIndex = _b[1];\n var val = getValue(rowIndex + \".\" + cellIndex, this.matrix.matrix);\n if (this.matrix.inValid(val) || (!force && oRowIndex === rowIndex && oCellIndex === cellIndex)) {\n return false;\n }\n this.matrix.select(rowIndex, cellIndex);\n };\n ContentFocus.prototype.getFocusInfo = function () {\n var info = {};\n var _a = this.matrix.current, _b = _a[0], rowIndex = _b === void 0 ? 0 : _b, _c = _a[1], cellIndex = _c === void 0 ? 0 : _c;\n this.matrix.current = [rowIndex, cellIndex];\n info.element = !isNullOrUndefined(this.getTable().rows[rowIndex]) ? this.getTable().rows[rowIndex].cells[cellIndex] : null;\n if (!info.element) {\n return info;\n }\n info.elementToFocus = !info.element.classList.contains('e-unboundcell') && !info.element.classList.contains('e-detailcell')\n ? this.getFocusable(info.element) : info.element;\n info.outline = true;\n info.uid = info.element.parentElement.getAttribute('data-uid');\n return info;\n };\n ContentFocus.prototype.getFocusable = function (element) {\n var query = 'button, [href], input:not([type=\"hidden\"]), select, textarea, [tabindex]:not([tabindex=\"-1\"])';\n if (this.parent.isEdit) {\n query = 'input:not([type=\"hidden\"]), select:not([aria-hidden=\"true\"]), textarea';\n }\n var child = [].slice.call(element.querySelectorAll(query));\n /* Select the first focusable child element\n * if no child found then select the cell itself.\n * if Grid is in editable state, check for editable control inside child.\n */\n return child.length ? child[0] : element;\n };\n ContentFocus.prototype.selector = function (row, cell) {\n var types = [CellType.Expand, CellType.GroupCaption, CellType.CaptionSummary, CellType.GroupSummary];\n return ((row.isDataRow && cell.visible && (cell.isDataCell || cell.isTemplate))\n || (row.isDataRow && cell.cellType === CellType.DetailExpand)\n || (!row.isDataRow && types.indexOf(cell.cellType) > -1)\n || (cell.column && cell.column.type === 'checkbox')\n || (cell.cellType === CellType.CommandColumn))\n && !(row.edit === 'delete' && row.isDirty);\n };\n ContentFocus.prototype.jump = function (action, current) {\n var frozenSwap = this.parent.frozenColumns > 0 &&\n ((action === 'leftArrow' || action === 'shiftTab') && current[1] === 0);\n var enterFrozen = this.parent.frozenRows !== 0 && action === 'shiftEnter';\n var info = {\n swap: ((action === 'upArrow' || enterFrozen) && current[0] === 0) || frozenSwap,\n toHeader: (action === 'upArrow' || enterFrozen) && current[0] === 0,\n toFrozen: frozenSwap\n };\n return info;\n };\n ContentFocus.prototype.getNextCurrent = function (previous, swap, active, action) {\n if (previous === void 0) { previous = []; }\n var current = [];\n if (action === 'rightArrow' || action === 'tab') {\n current[0] = previous[0];\n current[1] = -1;\n }\n else if (action === 'downArrow' || action === 'enter') {\n current[0] = -1;\n current[1] = previous[1];\n }\n return current;\n };\n ContentFocus.prototype.generateRows = function (rows, optionals) {\n var matrix = optionals.matrix, handlerInstance = optionals.handlerInstance;\n var len = handlerInstance.matrix.matrix.length;\n var defaultLen = this.parent.allowFiltering && this.parent.filterSettings.type === 'FilterBar' ? len + 1 : len;\n handlerInstance.matrix.matrix = handlerInstance.matrix.matrix.slice(0, defaultLen); //Header matrix update.\n handlerInstance.matrix.rows = defaultLen;\n (_a = handlerInstance.matrix.matrix).push.apply(_a, matrix);\n handlerInstance.matrix.rows += matrix.length;\n var _a;\n };\n ContentFocus.prototype.getInfo = function (e) {\n var info = this.getFocusInfo();\n var _a = this.matrix.current, rIndex = _a[0], cIndex = _a[1];\n var isData = info.element.classList.contains('e-rowcell');\n var isSelectable = isData || (e && e.action !== 'enter' && (info.element.classList.contains('e-detailrowcollapse')\n || info.element.classList.contains('e-detailrowexpand')));\n var _b = [Math.min(parseInt(info.element.parentElement.getAttribute('aria-rowindex'), 10), rIndex),\n Math.min(parseInt(info.element.getAttribute('aria-colindex'), 10), cIndex)], rowIndex = _b[0], cellIndex = _b[1];\n return { isContent: true, isDataCell: isData, indexes: [rowIndex, cellIndex], isSelectable: isSelectable };\n };\n ContentFocus.prototype.validator = function () {\n var table = this.getTable();\n return function (rowIndex, cellIndex, action) {\n var cell = table.rows[rowIndex].cells[cellIndex];\n if (action === 'enter' || action === 'shiftEnter') {\n return cell.classList.contains('e-rowcell');\n }\n if ((action === 'shiftUp' || action === 'shiftDown') && cell.classList.contains('e-rowcell')) {\n return true;\n }\n else if (action !== 'shiftUp' && action !== 'shiftDown') {\n return cell.getBoundingClientRect().width !== 0;\n }\n return false;\n };\n };\n ContentFocus.prototype.shouldFocusChange = function (e) {\n var _a = this.matrix.current, _b = _a[0], rIndex = _b === void 0 ? -1 : _b, _c = _a[1], cIndex = _c === void 0 ? -1 : _c;\n if (rIndex < 0 || cIndex < 0) {\n return true;\n }\n var cell = getValue(rIndex + \".cells.\" + cIndex, this.getTable().rows);\n if (!cell) {\n return true;\n }\n return e.action === 'enter' || e.action === 'shiftEnter' ?\n cell.classList.contains('e-rowcell') && !cell.classList.contains('e-unboundcell')\n && !cell.classList.contains('e-templatecell') && !cell.classList.contains('e-detailcell') : true;\n };\n return ContentFocus;\n}());\nexport { ContentFocus };\n/**\n * @hidden\n */\nvar HeaderFocus = /** @class */ (function (_super) {\n __extends(HeaderFocus, _super);\n function HeaderFocus(parent) {\n return _super.call(this, parent) || this;\n }\n HeaderFocus.prototype.getTable = function () {\n return (this.parent.frozenColumns ? this.parent.getHeaderContent().querySelector('.e-movableheader .e-table') :\n this.parent.getHeaderTable());\n };\n HeaderFocus.prototype.onClick = function (e) {\n var target = e.target;\n target = (target.classList.contains('e-headercell') ? target : closest(target, 'th'));\n if (!target && this.parent.frozenRows !== 0) {\n target = (e.target.classList.contains('e-rowcell') ? e.target :\n closest(e.target, 'td'));\n }\n if (!target) {\n return;\n }\n var _a = [target.parentElement.rowIndex, target.cellIndex], rowIndex = _a[0], cellIndex = _a[1];\n var val = getValue(rowIndex + \".\" + cellIndex, this.matrix.matrix);\n if (this.matrix.inValid(val)) {\n return false;\n }\n this.matrix.select(target.parentElement.rowIndex, target.cellIndex);\n };\n HeaderFocus.prototype.getFocusInfo = function () {\n var info = {};\n var _a = this.matrix.current, _b = _a[0], rowIndex = _b === void 0 ? 0 : _b, _c = _a[1], cellIndex = _c === void 0 ? 0 : _c;\n info.element = this.getTable().rows[rowIndex].cells[cellIndex];\n info.elementToFocus = this.getFocusable(info.element);\n info.outline = !info.element.classList.contains('e-filterbarcell');\n return info;\n };\n HeaderFocus.prototype.selector = function (row, cell) {\n return (cell.visible && (cell.column.field !== undefined || cell.isTemplate)) || cell.column.type === 'checkbox' ||\n cell.cellType === CellType.StackedHeader;\n };\n HeaderFocus.prototype.jump = function (action, current) {\n var frozenSwap = this.parent.frozenColumns > 0 &&\n (action === 'leftArrow' || action === 'shiftTab') && current[1] === 0;\n var enterFrozen = this.parent.frozenRows !== 0 && action === 'enter';\n return {\n swap: ((action === 'downArrow' || enterFrozen) && current[0] === this.matrix.matrix.length - 1) ||\n frozenSwap,\n toHeader: frozenSwap,\n toFrozen: frozenSwap\n };\n };\n HeaderFocus.prototype.getNextCurrent = function (previous, swap, active, action) {\n if (previous === void 0) { previous = []; }\n var current1 = [];\n if (action === 'upArrow' || action === 'shiftEnter') {\n current1[0] = this.matrix.matrix.length;\n current1[1] = previous[1];\n }\n else if (action === 'rightArrow' || action === 'tab') {\n current1[0] = previous[0];\n current1[1] = -1;\n }\n return current1;\n };\n HeaderFocus.prototype.generateRows = function (rows) {\n var _this = this;\n var length = this.matrix.matrix.length;\n if (this.parent.allowFiltering && this.parent.filterSettings.type === 'FilterBar') {\n this.matrix.rows = ++this.matrix.rows;\n rows[0].cells.forEach(function (cell, cIndex) {\n return _this.matrix.set(length, cIndex, cell.visible && cell.column.allowFiltering !== false);\n });\n }\n };\n HeaderFocus.prototype.getInfo = function (e) {\n return extend(_super.prototype.getInfo.call(this, e), { isContent: false, isHeader: true });\n };\n HeaderFocus.prototype.validator = function () {\n return function () { return true; };\n };\n HeaderFocus.prototype.shouldFocusChange = function (e) {\n var _a = this.matrix.current, rIndex = _a[0], cIndex = _a[1];\n if (rIndex < 0 || cIndex < 0) {\n return true;\n }\n var cell = getValue(rIndex + \".cells.\" + cIndex, this.getTable().rows);\n if (!cell) {\n return true;\n }\n return e.action === 'enter' || e.action === 'altDownArrow' ? !cell.classList.contains('e-headercell') : true;\n };\n return HeaderFocus;\n}(ContentFocus));\nexport { HeaderFocus };\nvar FixedContentFocus = /** @class */ (function (_super) {\n __extends(FixedContentFocus, _super);\n function FixedContentFocus() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n FixedContentFocus.prototype.getTable = function () {\n return this.parent.getContent().querySelector('.e-frozencontent .e-table');\n };\n FixedContentFocus.prototype.jump = function (action, current) {\n var enterFrozen = this.parent.frozenRows !== 0 && action === 'shiftEnter';\n return {\n swap: (action === 'upArrow' || enterFrozen) && current[0] === 0\n || ((action === 'tab' || action === 'rightArrow') && current[1] === this.matrix.columns),\n toHeader: (action === 'upArrow' || enterFrozen) && current[0] === 0,\n toFrozen: (action === 'upArrow' || enterFrozen) && current[0] === 0\n };\n };\n FixedContentFocus.prototype.getNextCurrent = function (previous, swap, active, action) {\n if (previous === void 0) { previous = []; }\n var current2 = [];\n if (action === 'leftArrow' || action === 'shiftTab') {\n current2[0] = previous[0];\n current2[1] = active.matrix.columns + 1;\n }\n else if (action === 'downArrow' || action === 'enter') {\n current2[0] = -1;\n current2[1] = previous[1];\n }\n return current2;\n };\n return FixedContentFocus;\n}(ContentFocus));\nexport { FixedContentFocus };\nvar FixedHeaderFocus = /** @class */ (function (_super) {\n __extends(FixedHeaderFocus, _super);\n function FixedHeaderFocus() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n FixedHeaderFocus.prototype.jump = function (action, current) {\n var enterFrozen = this.parent.frozenRows !== 0 && action === 'enter';\n return {\n swap: (action === 'downArrow' || enterFrozen) && current[0] === this.matrix.matrix.length - 1\n || ((action === 'rightArrow' || action === 'tab') && current[1] === this.matrix.columns),\n toHeader: (action === 'rightArrow' || action === 'tab') && current[1] === this.matrix.columns,\n toFrozen: (action === 'downArrow' || enterFrozen) && current[0] === this.matrix.matrix.length - 1\n };\n };\n FixedHeaderFocus.prototype.getTable = function () {\n return (this.parent.getHeaderContent().querySelector('.e-frozenheader .e-table'));\n };\n FixedHeaderFocus.prototype.getNextCurrent = function (previous, swap, active, action) {\n if (previous === void 0) { previous = []; }\n var current3 = [];\n if (action === 'leftArrow' || action === 'shiftTab') {\n current3[0] = previous[0];\n current3[1] = active.matrix.columns + 1;\n }\n else if (action === 'upArrow' || action === 'shiftEnter') {\n current3[0] = this.matrix.matrix.length;\n current3[1] = previous[1];\n }\n return current3;\n };\n return FixedHeaderFocus;\n}(HeaderFocus));\nexport { FixedHeaderFocus };\n/** @hidden */\nvar SearchBox = /** @class */ (function () {\n function SearchBox(searchBox) {\n this.searchBox = searchBox;\n }\n SearchBox.prototype.searchFocus = function (args) {\n args.target.parentElement.classList.add('e-input-focus');\n };\n SearchBox.prototype.searchBlur = function (args) {\n args.target.parentElement.classList.remove('e-input-focus');\n };\n SearchBox.prototype.wireEvent = function () {\n if (this.searchBox) {\n EventHandler.add(this.searchBox, 'focus', this.searchFocus, this);\n EventHandler.add(this.searchBox, 'blur', this.searchBlur, this);\n }\n };\n SearchBox.prototype.unWireEvent = function () {\n if (this.searchBox) {\n EventHandler.remove(this.searchBox, 'focus', this.searchFocus);\n EventHandler.remove(this.searchBox, 'blur', this.searchBlur);\n }\n };\n return SearchBox;\n}());\nexport { SearchBox };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Property, ChildProperty } from '@syncfusion/ej2-base';\n/**\n * Configures the paging behavior of the Grid.\n */\nvar PageSettings = /** @class */ (function (_super) {\n __extends(PageSettings, _super);\n function PageSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(12)\n ], PageSettings.prototype, \"pageSize\", void 0);\n __decorate([\n Property(8)\n ], PageSettings.prototype, \"pageCount\", void 0);\n __decorate([\n Property(1)\n ], PageSettings.prototype, \"currentPage\", void 0);\n __decorate([\n Property()\n ], PageSettings.prototype, \"totalRecordsCount\", void 0);\n __decorate([\n Property(false)\n ], PageSettings.prototype, \"enableQueryString\", void 0);\n __decorate([\n Property(false)\n ], PageSettings.prototype, \"pageSizes\", void 0);\n __decorate([\n Property(null)\n ], PageSettings.prototype, \"template\", void 0);\n return PageSettings;\n}(ChildProperty));\nexport { PageSettings };\n","var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n};\nimport { Browser, EventHandler } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, isUndefined, addClass, removeClass } from '@syncfusion/ej2-base';\nimport { remove, closest } from '@syncfusion/ej2-base';\nimport { Query } from '@syncfusion/ej2-data';\nimport { setCssInGridPopUp, getPosition, parentsUntil, addRemoveActiveClasses, removeAddCboxClasses } from '../base/util';\nimport * as events from '../base/constant';\nimport { RenderType } from '../base/enum';\n/**\n * The `Selection` module is used to handle cell and row selection.\n */\nvar Selection = /** @class */ (function () {\n /**\n * Constructor for the Grid selection module\n * @hidden\n */\n function Selection(parent, selectionSettings, locator) {\n //Internal variables \n /**\n * @hidden\n */\n this.selectedRowIndexes = [];\n /**\n * @hidden\n */\n this.selectedRowCellIndexes = [];\n /**\n * @hidden\n */\n this.selectedRecords = [];\n this.preventFocus = false;\n this.isMultiShiftRequest = false;\n this.isMultiCtrlRequest = false;\n this.enableSelectMultiTouch = false;\n this.selectedRowState = {};\n this.totalRecordsCount = 0;\n this.chkAllCollec = [];\n this.isCheckedOnAdd = false;\n this.persistSelectedData = [];\n this.isCancelDeSelect = false;\n this.isPreventCellSelect = false;\n this.disableUI = false;\n this.parent = parent;\n this.selectionSettings = selectionSettings;\n this.factory = locator.getService('rendererFactory');\n this.focus = locator.getService('focus');\n this.addEventListener();\n }\n Selection.prototype.initializeSelection = function () {\n EventHandler.add(this.parent.getContent(), 'mousedown', this.mouseDownHandler, this);\n };\n /**\n * The function used to trigger onActionBegin\n * @return {void}\n * @hidden\n */\n Selection.prototype.onActionBegin = function (args, type) {\n this.parent.trigger(type, this.fDataUpdate(args));\n };\n Selection.prototype.fDataUpdate = function (args) {\n if (args.cellIndex || args.rowIndex) {\n var rowObj = this.getRowObj(isNullOrUndefined(args.rowIndex) ? isNullOrUndefined(args.cellIndex) ?\n this.currentIndex : args.cellIndex.rowIndex : args.rowIndex);\n args.foreignKeyData = rowObj.foreignKeyData;\n }\n return args;\n };\n /**\n * The function used to trigger onActionComplete\n * @return {void}\n * @hidden\n */\n Selection.prototype.onActionComplete = function (args, type) {\n this.parent.trigger(type, this.fDataUpdate(args));\n };\n /**\n * For internal use only - Get the module name.\n * @private\n */\n Selection.prototype.getModuleName = function () {\n return 'selection';\n };\n /**\n * To destroy the selection\n * @return {void}\n * @hidden\n */\n Selection.prototype.destroy = function () {\n var gridElement = this.parent.element;\n if (!gridElement || (!gridElement.querySelector('.e-gridheader') && !gridElement.querySelector('.e-gridcontent'))) {\n return;\n }\n this.hidePopUp();\n this.clearSelection();\n this.removeEventListener();\n EventHandler.remove(this.parent.getContent(), 'mousedown', this.mouseDownHandler);\n };\n Selection.prototype.isEditing = function () {\n return (this.parent.editSettings.mode === 'Normal' || (this.parent.editSettings.mode === 'Batch' &&\n this.parent.editModule.formObj && !this.parent.editModule.formObj.validate())) &&\n this.parent.isEdit && !this.parent.isPersistSelection;\n };\n Selection.prototype.getSelectedMovableRow = function (index) {\n var gObj = this.parent;\n if (gObj.getFrozenColumns()) {\n return gObj.getMovableRowByIndex(index);\n }\n return null;\n };\n /**\n * Selects a row by the given index.\n * @param {number} index - Defines the row index.\n * @param {boolean} isToggle - If set to true, then it toggles the selection.\n * @return {void}\n */\n Selection.prototype.selectRow = function (index, isToggle) {\n var gObj = this.parent;\n var selectedRow = gObj.getRowByIndex(index);\n var selectedMovableRow = this.getSelectedMovableRow(index);\n var selectData = gObj.getCurrentViewRecords()[index];\n if (gObj.enableVirtualization && gObj.allowGrouping && gObj.groupSettings.columns.length && selectedRow) {\n selectData = gObj.getRowObjectFromUID(selectedRow.getAttribute('data-uid')).data;\n }\n if (!this.isRowType() || !selectedRow || this.isEditing()) {\n // if (this.isEditing()) {\n // gObj.selectedRowIndex = index;\n // }\n return;\n }\n var isRowSelected = selectedRow.hasAttribute('aria-selected');\n isToggle = !isToggle ? isToggle :\n !this.selectedRowIndexes.length ? false :\n (this.selectedRowIndexes.length === 1 ? (index === this.selectedRowIndexes[0]) : false);\n var args;\n var can = 'cancel';\n if (!isToggle) {\n args = {\n data: selectData, rowIndex: index, isCtrlPressed: this.isMultiCtrlRequest,\n isShiftPressed: this.isMultiShiftRequest, row: selectedRow,\n previousRow: gObj.getRows()[this.prevRowIndex], previousRowIndex: this.prevRowIndex, target: this.target, cancel: false\n };\n args = this.addMovableArgs(args, selectedMovableRow);\n this.onActionBegin(args, events.rowSelecting);\n }\n if (!isNullOrUndefined(args) && args[can] === true) {\n return;\n }\n this.clearRow();\n if (!isToggle) {\n this.updateRowSelection(selectedRow, index);\n if (gObj.getFrozenColumns()) {\n this.updateRowSelection(selectedMovableRow, index);\n }\n gObj.selectedRowIndex = index;\n }\n if (!isToggle) {\n args = {\n data: selectData, rowIndex: index,\n row: selectedRow, previousRow: gObj.getRows()[this.prevRowIndex],\n previousRowIndex: this.prevRowIndex, target: this.target\n };\n args = this.addMovableArgs(args, selectedMovableRow);\n this.onActionComplete(args, events.rowSelected);\n }\n this.updateRowProps(index);\n };\n Selection.prototype.addMovableArgs = function (targetObj, mRow) {\n if (this.parent.getFrozenColumns()) {\n var mObj = { mRow: mRow, previousMovRow: this.parent.getMovableRows()[this.prevRowIndex] };\n targetObj = __assign({}, targetObj, mObj);\n }\n return targetObj;\n };\n /**\n * Selects a range of rows from start and end row indexes.\n * @param {number} startIndex - Specifies the start row index.\n * @param {number} endIndex - Specifies the end row index.\n * @return {void}\n */\n Selection.prototype.selectRowsByRange = function (startIndex, endIndex) {\n this.selectRows(this.getCollectionFromIndexes(startIndex, endIndex));\n this.parent.selectedRowIndex = endIndex;\n };\n /**\n * Selects a collection of rows by index.\n * @param {number[]} rowIndexes - Specifies an array of row indexes.\n * @return {void}\n */\n Selection.prototype.selectRows = function (rowIndexes) {\n var gObj = this.parent;\n var rowIndex = !this.isSingleSel() ? rowIndexes[0] : rowIndexes[rowIndexes.length - 1];\n var selectedRow = gObj.getRowByIndex(rowIndex);\n var selectedMovableRow = this.getSelectedMovableRow(rowIndex);\n var frzCols = gObj.getFrozenColumns();\n var can = 'cancel';\n var selectedData = gObj.getCurrentViewRecords()[rowIndexes[0]];\n if (!this.isRowType() || this.isEditing()) {\n return;\n }\n var args = {\n rowIndexes: rowIndexes, row: selectedRow, rowIndex: rowIndex, target: this.target,\n prevRow: gObj.getRows()[this.prevRowIndex], previousRowIndex: this.prevRowIndex,\n isCtrlPressed: this.isMultiCtrlRequest, isShiftPressed: this.isMultiShiftRequest,\n data: selectedData\n };\n args = this.addMovableArgs(args, selectedMovableRow);\n this.onActionBegin(args, events.rowSelecting);\n if (!isNullOrUndefined(args) && args[can] === true) {\n return;\n }\n this.clearRow();\n gObj.selectedRowIndex = rowIndexes.slice(-1)[0];\n if (!this.isSingleSel()) {\n for (var _i = 0, rowIndexes_1 = rowIndexes; _i < rowIndexes_1.length; _i++) {\n var rowIdx = rowIndexes_1[_i];\n this.updateRowSelection(gObj.getRowByIndex(rowIdx), rowIdx);\n if (frzCols) {\n this.updateRowSelection(gObj.getMovableRowByIndex(rowIdx), rowIdx);\n }\n this.updateRowProps(rowIndex);\n }\n }\n else {\n this.updateRowSelection(gObj.getRowByIndex(rowIndex), rowIndex);\n if (frzCols) {\n this.updateRowSelection(gObj.getMovableRowByIndex(rowIndex), rowIndex);\n }\n this.updateRowProps(rowIndex);\n }\n args = {\n rowIndexes: rowIndexes, row: selectedRow, rowIndex: rowIndex, target: this.target,\n prevRow: gObj.getRows()[this.prevRowIndex], previousRowIndex: this.prevRowIndex,\n data: selectedData\n };\n args = this.addMovableArgs(args, selectedMovableRow);\n this.onActionComplete(args, events.rowSelected);\n };\n /**\n * Select rows with existing row selection by passing row indexes.\n * @param {number} startIndex - Specifies the row indexes.\n * @return {void}\n * @hidden\n */\n Selection.prototype.addRowsToSelection = function (rowIndexes) {\n var gObj = this.parent;\n var can = 'cancel';\n var selectedRow = !this.isSingleSel() ? gObj.getRowByIndex(rowIndexes[0]) :\n gObj.getRowByIndex(rowIndexes[rowIndexes.length - 1]);\n var selectedMovableRow = !this.isSingleSel() ? this.getSelectedMovableRow(rowIndexes[0]) :\n this.getSelectedMovableRow(rowIndexes[rowIndexes.length - 1]);\n var frzCols = gObj.getFrozenColumns();\n if (!this.isRowType() || this.isEditing()) {\n return;\n }\n var args;\n for (var _i = 0, rowIndexes_2 = rowIndexes; _i < rowIndexes_2.length; _i++) {\n var rowIndex = rowIndexes_2[_i];\n var rowObj = this.getRowObj(rowIndex);\n var isUnSelected = this.selectedRowIndexes.indexOf(rowIndex) > -1;\n gObj.selectedRowIndex = rowIndex;\n if (isUnSelected) {\n this.rowDeselect(events.rowDeselecting, [rowIndex], [rowObj.data], [selectedRow], [rowObj.foreignKeyData]);\n this.selectedRowIndexes.splice(this.selectedRowIndexes.indexOf(rowIndex), 1);\n this.selectedRecords.splice(this.selectedRecords.indexOf(selectedRow), 1);\n selectedRow.removeAttribute('aria-selected');\n this.addRemoveClassesForRow(selectedRow, false, null, 'e-selectionbackground', 'e-active');\n if (selectedMovableRow) {\n this.selectedRecords.splice(this.selectedRecords.indexOf(selectedMovableRow), 1);\n selectedMovableRow.removeAttribute('aria-selected');\n this.addRemoveClassesForRow(selectedMovableRow, false, null, 'e-selectionbackground', 'e-active');\n }\n this.rowDeselect(events.rowDeselected, [rowIndex], [rowObj.data], [selectedRow], [rowObj.foreignKeyData], [selectedMovableRow]);\n }\n else {\n args = {\n data: rowObj.data, rowIndex: rowIndex, row: selectedRow, target: this.target,\n prevRow: gObj.getRows()[this.prevRowIndex], previousRowIndex: this.prevRowIndex,\n isCtrlPressed: this.isMultiCtrlRequest, isShiftPressed: this.isMultiShiftRequest,\n foreignKeyData: rowObj.foreignKeyData\n };\n args = this.addMovableArgs(args, selectedMovableRow);\n this.onActionBegin(args, events.rowSelecting);\n if (!isNullOrUndefined(args) && args[can] === true) {\n return;\n }\n if (this.isSingleSel()) {\n this.clearRow();\n }\n this.updateRowSelection(selectedRow, rowIndex);\n if (frzCols) {\n this.updateRowSelection(selectedMovableRow, rowIndex);\n }\n }\n if (!isUnSelected) {\n args = {\n data: rowObj.data, rowIndex: rowIndex, row: selectedRow, target: this.target,\n prevRow: gObj.getRows()[this.prevRowIndex], previousRowIndex: this.prevRowIndex,\n foreignKeyData: rowObj.foreignKeyData\n };\n args = this.addMovableArgs(args, selectedMovableRow);\n this.onActionComplete(args, events.rowSelected);\n }\n this.updateRowProps(rowIndex);\n if (this.isSingleSel()) {\n break;\n }\n }\n };\n Selection.prototype.getCollectionFromIndexes = function (startIndex, endIndex) {\n var indexes = [];\n var _a = (startIndex < endIndex) ?\n { i: startIndex, max: endIndex } : { i: endIndex, max: startIndex }, i = _a.i, max = _a.max;\n for (; i <= max; i++) {\n indexes.push(i);\n }\n if (startIndex > endIndex) {\n indexes.reverse();\n }\n return indexes;\n };\n Selection.prototype.clearRow = function () {\n this.clearRowSelection();\n this.selectedRowIndexes = [];\n this.selectedRecords = [];\n this.parent.selectedRowIndex = -1;\n if (this.isSingleSel() && this.parent.isPersistSelection) {\n this.selectedRowState = {};\n }\n };\n Selection.prototype.updateRowProps = function (startIndex) {\n this.prevRowIndex = startIndex;\n this.isRowSelected = this.selectedRowIndexes.length && true;\n };\n Selection.prototype.updatePersistCollection = function (selectedRow, chkState) {\n var _this = this;\n if (this.parent.isPersistSelection && !isNullOrUndefined(selectedRow)) {\n var rowObj = this.getRowObj(selectedRow);\n var pKey_1 = rowObj.data ? rowObj.data[this.primaryKey] : null;\n if (pKey_1 === null) {\n return;\n }\n rowObj.isSelected = chkState;\n if (chkState) {\n this.selectedRowState[pKey_1] = chkState;\n if (!this.persistSelectedData.some(function (data) { return data[_this.primaryKey] === pKey_1; })) {\n this.persistSelectedData.push(rowObj.data);\n }\n }\n else {\n this.updatePersistDelete(pKey_1);\n }\n }\n };\n Selection.prototype.updatePersistDelete = function (pKey) {\n var _this = this;\n delete (this.selectedRowState[pKey]);\n var index;\n var isPresent = this.persistSelectedData.some(function (data, i) {\n index = i;\n return data[_this.primaryKey] === pKey;\n });\n if (isPresent) {\n this.persistSelectedData.splice(index, 1);\n }\n };\n Selection.prototype.updateCheckBoxes = function (row, chkState) {\n if (!isNullOrUndefined(row)) {\n var chkBox = row.querySelector('.e-checkselect');\n if (!isNullOrUndefined(chkBox)) {\n removeAddCboxClasses(chkBox.nextElementSibling, chkState);\n if (isNullOrUndefined(this.checkedTarget) || (!isNullOrUndefined(this.checkedTarget)\n && !this.checkedTarget.classList.contains('e-checkselectall'))) {\n this.setCheckAllState(parseInt(row.getAttribute('aria-rowindex'), 10));\n }\n }\n }\n };\n Selection.prototype.updateRowSelection = function (selectedRow, startIndex) {\n if (!selectedRow) {\n return;\n }\n this.selectedRowIndexes.push(startIndex);\n var len = this.selectedRowIndexes.length;\n if (this.parent.getFrozenColumns() && len > 1) {\n if ((this.selectedRowIndexes[len - 2] === this.selectedRowIndexes[len - 1])) {\n this.selectedRowIndexes.pop();\n }\n }\n this.selectedRecords.push(selectedRow);\n selectedRow.setAttribute('aria-selected', 'true');\n this.updatePersistCollection(selectedRow, true);\n this.updateCheckBoxes(selectedRow, true);\n this.addRemoveClassesForRow(selectedRow, true, null, 'e-selectionbackground', 'e-active');\n if (!this.preventFocus) {\n var target = this.focus.getPrevIndexes().cellIndex ?\n selectedRow.cells[this.focus.getPrevIndexes().cellIndex] :\n selectedRow.querySelector('.e-selectionbackground:not(.e-hide)');\n if (!target) {\n return;\n }\n this.focus.onClick({ target: target }, true);\n }\n };\n /**\n * Deselects the currently selected rows and cells.\n * @return {void}\n */\n Selection.prototype.clearSelection = function () {\n if (!this.parent.isPersistSelection || (this.parent.isPersistSelection && !this.parent.isEdit) ||\n (!isNullOrUndefined(this.checkedTarget) && this.checkedTarget.classList.contains('e-checkselectall'))) {\n var span = this.parent.element.querySelector('.e-gridpopup').querySelector('span');\n if (span.classList.contains('e-rowselect')) {\n span.classList.remove('e-spanclicked');\n }\n this.clearRowSelection();\n this.clearCellSelection();\n this.enableSelectMultiTouch = false;\n }\n };\n /**\n * Deselects the currently selected rows.\n * @return {void}\n */\n Selection.prototype.clearRowSelection = function () {\n var _this = this;\n if (this.isRowSelected) {\n var gObj = this.parent;\n var rows = this.parent.getDataRows();\n var data = [];\n var row = [];\n var mRow = [];\n var rowIndex = [];\n var frzCols = gObj.getFrozenColumns();\n var foreignKeyData = [];\n var currentViewData = this.parent.getCurrentViewRecords();\n for (var i = 0, len = this.selectedRowIndexes.length; i < len; i++) {\n var currentRow = this.parent.getDataRows()[this.selectedRowIndexes[i]];\n var rowObj = this.getRowObj(currentRow);\n if (rowObj) {\n data.push(rowObj.data);\n row.push(currentRow);\n rowIndex.push(this.selectedRowIndexes[i]);\n foreignKeyData.push(rowObj.foreignKeyData);\n }\n if (frzCols) {\n mRow.push(gObj.getMovableRows()[this.selectedRowIndexes[i]]);\n }\n }\n this.rowDeselect(events.rowDeselecting, rowIndex, data, row, foreignKeyData, mRow);\n if (this.isCancelDeSelect === true) {\n return;\n }\n rows.filter(function (record) { return record.hasAttribute('aria-selected'); }).forEach(function (ele) {\n if (!_this.disableUI) {\n ele.removeAttribute('aria-selected');\n _this.addRemoveClassesForRow(ele, false, true, 'e-selectionbackground', 'e-active');\n }\n _this.updatePersistCollection(ele, false);\n _this.updateCheckBoxes(ele);\n });\n for (var i = 0, len = this.selectedRowIndexes.length; i < len; i++) {\n var movableRow = this.getSelectedMovableRow(this.selectedRowIndexes[i]);\n if (movableRow) {\n if (!this.disableUI) {\n movableRow.removeAttribute('aria-selected');\n this.addRemoveClassesForRow(movableRow, false, true, 'e-selectionbackground', 'e-active');\n }\n this.updatePersistCollection(movableRow, false);\n }\n }\n this.selectedRowIndexes = [];\n this.selectedRecords = [];\n this.isRowSelected = false;\n this.parent.selectedRowIndex = -1;\n this.rowDeselect(events.rowDeselected, rowIndex, data, row, foreignKeyData, mRow);\n }\n };\n Selection.prototype.rowDeselect = function (type, rowIndex, data, row, foreignKeyData, mRow) {\n var cancl = 'cancel';\n this.updatePersistCollection(row[0], false);\n var rowDeselectObj = { rowIndex: rowIndex, data: data, row: row, foreignKeyData: foreignKeyData, cancel: false };\n this.parent.trigger(type, this.parent.getFrozenColumns() ? __assign({}, rowDeselectObj, { mRow: mRow }) : rowDeselectObj);\n this.isCancelDeSelect = rowDeselectObj[cancl];\n this.updateCheckBoxes(row[0]);\n };\n Selection.prototype.getRowObj = function (row) {\n if (row === void 0) { row = this.currentIndex; }\n if (isNullOrUndefined(row)) {\n return {};\n }\n if (typeof row === 'number') {\n row = this.parent.getRowByIndex(row);\n }\n if (row) {\n return this.parent.getRowObjectFromUID(row.getAttribute('data-uid')) || {};\n }\n return {};\n };\n Selection.prototype.getSelectedMovableCell = function (cellIndex) {\n var gObj = this.parent;\n var frzCols = gObj.getFrozenColumns();\n if (frzCols) {\n if (cellIndex.cellIndex >= frzCols) {\n return gObj.getMovableCellFromIndex(cellIndex.rowIndex, this.getColIndex(cellIndex.rowIndex, cellIndex.cellIndex));\n }\n return null;\n }\n return null;\n };\n /**\n * Selects a cell by the given index.\n * @param {IIndex} cellIndex - Defines the row and column indexes.\n * @param {boolean} isToggle - If set to true, then it toggles the selection.\n * @return {void}\n */\n Selection.prototype.selectCell = function (cellIndex, isToggle) {\n if (!this.isCellType()) {\n return;\n }\n var gObj = this.parent;\n var selectedCell = this.getSelectedMovableCell(cellIndex);\n var args;\n var cncl = 'cancel';\n if (!selectedCell) {\n selectedCell = gObj.getCellFromIndex(cellIndex.rowIndex, this.getColIndex(cellIndex.rowIndex, cellIndex.cellIndex));\n }\n var selectedTable;\n var cIdx;\n this.currentIndex = cellIndex.rowIndex;\n var selectedData = gObj.getCurrentViewRecords()[this.currentIndex];\n if (!this.isCellType() || !selectedCell || this.isEditing()) {\n return;\n }\n var isCellSelected = selectedCell.classList.contains('e-cellselectionbackground');\n isToggle = !isToggle ? isToggle : (!isUndefined(this.prevCIdxs) &&\n cellIndex.rowIndex === this.prevCIdxs.rowIndex && cellIndex.cellIndex === this.prevCIdxs.cellIndex &&\n isCellSelected);\n if (!isToggle) {\n args = {\n data: selectedData, cellIndex: cellIndex, currentCell: selectedCell,\n isCtrlPressed: this.isMultiCtrlRequest, isShiftPressed: this.isMultiShiftRequest, previousRowCellIndex: this.prevECIdxs,\n previousRowCell: this.prevECIdxs ?\n this.getCellIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) : undefined,\n cancel: false\n };\n this.onActionBegin(args, events.cellSelecting);\n }\n if (!isNullOrUndefined(args) && args[cncl] === true) {\n return;\n }\n this.clearCell();\n if (!isToggle) {\n this.updateCellSelection(selectedCell, cellIndex.rowIndex, cellIndex.cellIndex);\n }\n this.updateCellProps(cellIndex, cellIndex);\n if (!isToggle) {\n this.onActionComplete({\n data: selectedData, cellIndex: cellIndex, currentCell: selectedCell,\n previousRowCellIndex: this.prevECIdxs, selectedRowCellIndex: this.selectedRowCellIndexes,\n previousRowCell: this.prevECIdxs ?\n this.getCellIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) : undefined\n }, events.cellSelected);\n }\n };\n Selection.prototype.getCellIndex = function (rIdx, cIdx) {\n return (this.parent.getFrozenColumns() ? (cIdx >= this.parent.getFrozenColumns() ? this.parent.getMovableCellFromIndex(rIdx, cIdx)\n : this.parent.getCellFromIndex(rIdx, cIdx)) : this.parent.getCellFromIndex(rIdx, cIdx));\n };\n /**\n * Selects a range of cells from start and end indexes.\n * @param {IIndex} startIndex - Specifies the row and column's start index.\n * @param {IIndex} endIndex - Specifies the row and column's end index.\n * @return {void}\n */\n Selection.prototype.selectCellsByRange = function (startIndex, endIndex) {\n if (!this.isCellType()) {\n return;\n }\n var gObj = this.parent;\n var selectedCell = this.getSelectedMovableCell(startIndex);\n var frzCols = gObj.getFrozenColumns();\n if (!selectedCell) {\n selectedCell = gObj.getCellFromIndex(startIndex.rowIndex, startIndex.cellIndex);\n }\n var min;\n var max;\n var stIndex = startIndex;\n var edIndex = endIndex = endIndex ? endIndex : startIndex;\n var cellIndexes;\n this.currentIndex = startIndex.rowIndex;\n var cncl = 'cancel';\n var selectedData = gObj.getCurrentViewRecords()[this.currentIndex];\n if (this.isSingleSel() || !this.isCellType() || this.isEditing()) {\n return;\n }\n var args = {\n data: selectedData, cellIndex: startIndex, currentCell: selectedCell,\n isCtrlPressed: this.isMultiCtrlRequest, isShiftPressed: this.isMultiShiftRequest, previousRowCellIndex: this.prevECIdxs,\n previousRowCell: this.prevECIdxs ? this.getCellIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) : undefined\n };\n this.onActionBegin(args, events.cellSelecting);\n if (!isNullOrUndefined(args) && args[cncl] === true) {\n return;\n }\n this.clearCell();\n if (startIndex.rowIndex > endIndex.rowIndex) {\n var temp = startIndex;\n startIndex = endIndex;\n endIndex = temp;\n }\n for (var i = startIndex.rowIndex; i <= endIndex.rowIndex; i++) {\n if (this.selectionSettings.cellSelectionMode !== 'Box') {\n min = i === startIndex.rowIndex ? (startIndex.cellIndex) : 0;\n max = i === endIndex.rowIndex ? (endIndex.cellIndex) : this.getLastColIndex(i);\n }\n else {\n min = startIndex.cellIndex;\n max = endIndex.cellIndex;\n }\n cellIndexes = [];\n for (var j = min < max ? min : max, len = min > max ? min : max; j <= len; j++) {\n if (frzCols) {\n if (j < frzCols) {\n selectedCell = gObj.getCellFromIndex(i, j);\n }\n else {\n selectedCell = gObj.getMovableCellFromIndex(i, j);\n }\n }\n else {\n selectedCell = gObj.getCellFromIndex(i, j);\n }\n if (!selectedCell) {\n continue;\n }\n cellIndexes.push(j);\n this.updateCellSelection(selectedCell);\n this.addAttribute(selectedCell);\n }\n this.selectedRowCellIndexes.push({ rowIndex: i, cellIndexes: cellIndexes });\n }\n this.updateCellProps(stIndex, edIndex);\n this.onActionComplete({\n data: selectedData, cellIndex: startIndex, currentCell: selectedCell,\n previousRowCellIndex: this.prevECIdxs, selectedRowCellIndex: this.selectedRowCellIndexes,\n previousRowCell: this.prevECIdxs ? this.getCellIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) : undefined\n }, events.cellSelected);\n };\n /**\n * Selects a collection of cells by row and column indexes.\n * @param {ISelectedCell[]} rowCellIndexes - Specifies the row and column indexes.\n * @return {void}\n */\n Selection.prototype.selectCells = function (rowCellIndexes) {\n if (!this.isCellType()) {\n return;\n }\n var gObj = this.parent;\n var selectedCell = this.getSelectedMovableCell(rowCellIndexes[0]);\n var frzCols = gObj.getFrozenColumns();\n if (!selectedCell) {\n selectedCell = gObj.getCellFromIndex(rowCellIndexes[0].rowIndex, rowCellIndexes[0].cellIndexes[0]);\n }\n this.currentIndex = rowCellIndexes[0].rowIndex;\n var selectedData = gObj.getCurrentViewRecords()[this.currentIndex];\n if (this.isSingleSel() || !this.isCellType() || this.isEditing()) {\n return;\n }\n this.onActionBegin({\n data: selectedData, cellIndex: rowCellIndexes[0].cellIndexes[0],\n currentCell: selectedCell, isCtrlPressed: this.isMultiCtrlRequest,\n isShiftPressed: this.isMultiShiftRequest, previousRowCellIndex: this.prevECIdxs,\n previousRowCell: this.prevECIdxs ? this.getCellIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) : undefined\n }, events.cellSelecting);\n for (var i = 0, len = rowCellIndexes.length; i < len; i++) {\n for (var j = 0, cellLen = rowCellIndexes[i].cellIndexes.length; j < cellLen; j++) {\n if (frzCols) {\n if (rowCellIndexes[i].cellIndexes[j] < frzCols) {\n selectedCell = gObj.getCellFromIndex(rowCellIndexes[i].rowIndex, rowCellIndexes[i].cellIndexes[j]);\n }\n else {\n selectedCell = gObj.getMovableCellFromIndex(rowCellIndexes[i].rowIndex, rowCellIndexes[i].cellIndexes[j]);\n }\n }\n else {\n selectedCell = gObj.getCellFromIndex(rowCellIndexes[i].rowIndex, rowCellIndexes[i].cellIndexes[j]);\n }\n if (!selectedCell) {\n continue;\n }\n this.updateCellSelection(selectedCell);\n this.addAttribute(selectedCell);\n this.addRowCellIndex({ rowIndex: rowCellIndexes[i].rowIndex, cellIndex: rowCellIndexes[i].cellIndexes[j] });\n }\n }\n this.updateCellProps({ rowIndex: rowCellIndexes[0].rowIndex, cellIndex: rowCellIndexes[0].cellIndexes[0] }, { rowIndex: rowCellIndexes[0].rowIndex, cellIndex: rowCellIndexes[0].cellIndexes[0] });\n this.onActionComplete({\n data: selectedData, cellIndex: rowCellIndexes[0].cellIndexes[0],\n currentCell: selectedCell,\n previousRowCellIndex: this.prevECIdxs, selectedRowCellIndex: this.selectedRowCellIndexes,\n previousRowCell: this.prevECIdxs ? this.getCellIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) : undefined\n }, events.cellSelected);\n };\n /**\n * Select cells with existing cell selection by passing row and column index.\n * @param {IIndex} startIndex - Defines the collection of row and column index.\n * @return {void}\n * @hidden\n */\n Selection.prototype.addCellsToSelection = function (cellIndexes) {\n if (!this.isCellType()) {\n return;\n }\n var gObj = this.parent;\n var selectedTable;\n var cIdx;\n var selectedCell;\n var frzCols = gObj.getFrozenColumns();\n var index;\n this.currentIndex = cellIndexes[0].rowIndex;\n var selectedData = gObj.getCurrentViewRecords()[this.currentIndex];\n if (this.isSingleSel() || !this.isCellType() || this.isEditing()) {\n return;\n }\n var rowObj;\n if (frzCols && cellIndexes[0].cellIndex >= frzCols) {\n rowObj = gObj.getMovableRowsObject()[cellIndexes[0].rowIndex];\n }\n else {\n rowObj = this.getRowObj(cellIndexes[0].rowIndex);\n }\n var foreignKeyData = [];\n for (var _i = 0, cellIndexes_1 = cellIndexes; _i < cellIndexes_1.length; _i++) {\n var cellIndex = cellIndexes_1[_i];\n for (var i = 0, len = this.selectedRowCellIndexes.length; i < len; i++) {\n if (this.selectedRowCellIndexes[i].rowIndex === cellIndex.rowIndex) {\n index = i;\n break;\n }\n }\n selectedCell = this.getSelectedMovableCell(cellIndex);\n if (!selectedCell) {\n selectedCell = gObj.getCellFromIndex(cellIndex.rowIndex, this.getColIndex(cellIndex.rowIndex, cellIndex.cellIndex));\n }\n foreignKeyData.push(rowObj.cells[frzCols && cellIndexes[0].cellIndex >= frzCols\n ? cellIndex.cellIndex - frzCols : cellIndex.cellIndex].foreignKeyData);\n var args = {\n data: selectedData, cellIndex: cellIndexes[0],\n isShiftPressed: this.isMultiShiftRequest, previousRowCellIndex: this.prevECIdxs,\n currentCell: selectedCell, isCtrlPressed: this.isMultiCtrlRequest,\n previousRowCell: this.prevECIdxs ?\n gObj.getCellFromIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) : undefined,\n };\n var isUnSelected = index > -1;\n if (isUnSelected) {\n var selectedCellIdx = this.selectedRowCellIndexes[index].cellIndexes;\n if (selectedCellIdx.indexOf(cellIndex.cellIndex) > -1) {\n this.cellDeselect(events.cellDeselecting, [{ rowIndex: cellIndex.rowIndex, cellIndexes: [cellIndex.cellIndex] }], selectedData, [selectedCell], foreignKeyData);\n selectedCellIdx.splice(selectedCellIdx.indexOf(cellIndex.cellIndex), 1);\n selectedCell.classList.remove('e-cellselectionbackground');\n selectedCell.removeAttribute('aria-selected');\n this.cellDeselect(events.cellDeselected, [{ rowIndex: cellIndex.rowIndex, cellIndexes: [cellIndex.cellIndex] }], selectedData, [selectedCell], foreignKeyData);\n }\n else {\n isUnSelected = false;\n this.onActionBegin(args, events.cellSelecting);\n this.addRowCellIndex({ rowIndex: cellIndex.rowIndex, cellIndex: cellIndex.cellIndex });\n this.updateCellSelection(selectedCell);\n this.addAttribute(selectedCell);\n }\n }\n else {\n this.onActionBegin(args, events.cellSelecting);\n this.updateCellSelection(selectedCell, cellIndex.rowIndex, cellIndex.cellIndex);\n }\n this.updateCellProps(cellIndex, cellIndex);\n if (!isUnSelected) {\n this.onActionComplete({\n data: selectedData, cellIndex: cellIndexes[0], currentCell: selectedCell,\n previousRowCell: this.prevECIdxs ? this.getCellIndex(this.prevECIdxs.rowIndex, this.prevECIdxs.cellIndex) :\n undefined, previousRowCellIndex: this.prevECIdxs, selectedRowCellIndex: this.selectedRowCellIndexes\n }, events.cellSelected);\n }\n }\n };\n Selection.prototype.getColIndex = function (rowIndex, index) {\n var cells;\n var frzCols = this.parent.getFrozenColumns();\n if (frzCols) {\n if (index >= frzCols) {\n cells = this.parent.getMovableDataRows()[rowIndex].querySelectorAll('td.e-rowcell');\n }\n }\n if (!cells) {\n cells = this.parent.getDataRows()[rowIndex].querySelectorAll('td.e-rowcell');\n }\n for (var m = 0; m < cells.length; m++) {\n var colIndex = parseInt(cells[m].getAttribute('aria-colindex'), 10);\n if (colIndex === index) {\n if (frzCols) {\n if (index >= frzCols) {\n m += frzCols;\n }\n }\n return m;\n }\n }\n return -1;\n };\n Selection.prototype.getLastColIndex = function (rowIndex) {\n var cells = this.parent.getFrozenColumns() ? this.parent.getMovableDataRows()[rowIndex].querySelectorAll('td.e-rowcell')\n : this.parent.getDataRows()[rowIndex].querySelectorAll('td.e-rowcell');\n return parseInt(cells[cells.length - 1].getAttribute('aria-colindex'), 10);\n };\n Selection.prototype.clearCell = function () {\n this.clearCellSelection();\n };\n Selection.prototype.cellDeselect = function (type, cellIndexes, data, cells, foreignKeyData) {\n var cancl = 'cancel';\n if (cells[0] && cells[0].classList.contains('e-gridchkbox')) {\n this.updateCheckBoxes(closest(cells[0], 'tr'));\n }\n var args = {\n cells: cells, data: data, cellIndexes: cellIndexes, foreignKeyData: foreignKeyData, cancel: false\n };\n this.parent.trigger(type, args);\n this.isPreventCellSelect = args[cancl];\n };\n Selection.prototype.updateCellSelection = function (selectedCell, rowIndex, cellIndex) {\n if (!isNullOrUndefined(rowIndex)) {\n this.addRowCellIndex({ rowIndex: rowIndex, cellIndex: cellIndex });\n }\n selectedCell.classList.add('e-cellselectionbackground');\n if (selectedCell.classList.contains('e-gridchkbox')) {\n this.updateCheckBoxes(closest(selectedCell, 'tr'), true);\n }\n this.addAttribute(selectedCell);\n };\n Selection.prototype.addAttribute = function (cell) {\n this.target = cell;\n if (!isNullOrUndefined(cell)) {\n cell.setAttribute('aria-selected', 'true');\n if (!this.preventFocus) {\n this.focus.onClick({ target: cell }, true);\n }\n }\n };\n Selection.prototype.updateCellProps = function (startIndex, endIndex) {\n this.prevCIdxs = startIndex;\n this.prevECIdxs = endIndex;\n this.isCellSelected = this.selectedRowCellIndexes.length && true;\n };\n Selection.prototype.addRowCellIndex = function (rowCellIndex) {\n var isRowAvail;\n var index;\n for (var i = 0, len = this.selectedRowCellIndexes.length; i < len; i++) {\n if (this.selectedRowCellIndexes[i].rowIndex === rowCellIndex.rowIndex) {\n isRowAvail = true;\n index = i;\n break;\n }\n }\n if (isRowAvail) {\n if (this.selectedRowCellIndexes[index].cellIndexes.indexOf(rowCellIndex.cellIndex) < 0) {\n this.selectedRowCellIndexes[index].cellIndexes.push(rowCellIndex.cellIndex);\n }\n }\n else {\n this.selectedRowCellIndexes.push({ rowIndex: rowCellIndex.rowIndex, cellIndexes: [rowCellIndex.cellIndex] });\n }\n };\n /**\n * Deselects the currently selected cells.\n * @return {void}\n */\n Selection.prototype.clearCellSelection = function () {\n if (this.isCellSelected) {\n var gObj = this.parent;\n var selectedCells = this.getSelectedCellsElement();\n var rowCell = this.selectedRowCellIndexes;\n var data = [];\n var cells = [];\n var foreignKeyData = [];\n var currentViewData = gObj.getCurrentViewRecords();\n var selectedTable = void 0;\n var frzCols = gObj.getFrozenColumns();\n for (var i = 0, len = rowCell.length; i < len; i++) {\n data.push(currentViewData[rowCell[i].rowIndex]);\n var rowObj = this.getRowObj(rowCell[i].rowIndex);\n for (var j = 0, cLen = rowCell[i].cellIndexes.length; j < cLen; j++) {\n if (frzCols) {\n if (rowCell[i].cellIndexes[j] < frzCols) {\n cells.push(gObj.getCellFromIndex(rowCell[i].rowIndex, rowCell[i].cellIndexes[j]));\n }\n else {\n cells.push(gObj.getMovableCellFromIndex(rowCell[i].rowIndex, rowCell[i].cellIndexes[j]));\n }\n }\n else {\n foreignKeyData.push(rowObj.cells[rowCell[i].cellIndexes[j]].foreignKeyData);\n cells.push(gObj.getCellFromIndex(rowCell[i].rowIndex, rowCell[i].cellIndexes[j]));\n }\n }\n }\n this.cellDeselect(events.cellDeselecting, rowCell, data, cells, foreignKeyData);\n if (this.isPreventCellSelect === true) {\n return;\n }\n for (var i = 0, len = selectedCells.length; i < len; i++) {\n selectedCells[i].classList.remove('e-cellselectionbackground');\n selectedCells[i].removeAttribute('aria-selected');\n }\n this.selectedRowCellIndexes = [];\n this.isCellSelected = false;\n this.cellDeselect(events.cellDeselected, rowCell, data, cells, foreignKeyData);\n }\n };\n Selection.prototype.getSelectedCellsElement = function () {\n var gObj = this.parent;\n var rows = gObj.getDataRows();\n var mRows;\n if (gObj.getFrozenColumns()) {\n mRows = gObj.getMovableDataRows();\n rows = gObj.addMovableRows(rows, mRows);\n }\n var cells = [];\n for (var i = 0, len = rows.length; i < len; i++) {\n cells = cells.concat([].slice.call(rows[i].querySelectorAll('.e-cellselectionbackground')));\n }\n return cells;\n };\n Selection.prototype.mouseMoveHandler = function (e) {\n e.preventDefault();\n var gBRect = this.parent.element.getBoundingClientRect();\n var x1 = this.x;\n var y1 = this.y;\n var position = getPosition(e);\n var x2 = position.x - gBRect.left;\n var y2 = position.y - gBRect.top;\n var tmp;\n var target = closest(e.target, 'tr');\n this.isDragged = true;\n if (!this.isCellDrag) {\n if (!target) {\n target = closest(document.elementFromPoint(this.parent.element.offsetLeft + 2, e.clientY), 'tr');\n }\n if (x1 > x2) {\n tmp = x2;\n x2 = x1;\n x1 = tmp;\n }\n if (y1 > y2) {\n tmp = y2;\n y2 = y1;\n y1 = tmp;\n }\n this.element.style.left = x1 + 'px';\n this.element.style.top = y1 + 'px';\n this.element.style.width = x2 - x1 + 'px';\n this.element.style.height = y2 - y1 + 'px';\n }\n if (target && !e.ctrlKey && !e.shiftKey) {\n var rowIndex = parseInt(target.getAttribute('aria-rowindex'), 10);\n if (!this.isCellDrag) {\n this.selectRowsByRange(this.startIndex, rowIndex);\n }\n else {\n var td = parentsUntil(e.target, 'e-rowcell');\n if (td) {\n this.selectLikeExcel(rowIndex, parseInt(td.getAttribute('aria-colindex'), 10));\n }\n }\n }\n };\n Selection.prototype.selectLikeExcel = function (rowIndex, cellIndex) {\n this.clearCellSelection();\n this.selectCellsByRange({ rowIndex: this.startIndex, cellIndex: this.startCellIndex }, { rowIndex: rowIndex, cellIndex: cellIndex });\n };\n Selection.prototype.mouseUpHandler = function (e) {\n document.body.classList.remove('e-disableuserselect');\n if (this.element) {\n remove(this.element);\n }\n EventHandler.remove(this.parent.getContent(), 'mousemove', this.mouseMoveHandler);\n EventHandler.remove(document.body, 'mouseup', this.mouseUpHandler);\n this.isDragged = false;\n };\n Selection.prototype.mouseDownHandler = function (e) {\n var target = e.target;\n var gObj = this.parent;\n var isDrag;\n var gridElement = parentsUntil(target, 'e-grid');\n if (gridElement && gridElement.id !== gObj.element.id) {\n return;\n }\n if (e.shiftKey || e.ctrlKey) {\n e.preventDefault();\n }\n if (target.classList.contains('e-rowcell') && !e.shiftKey && !e.ctrlKey) {\n if (gObj.selectionSettings.cellSelectionMode === 'Box' && !this.isRowType() && !this.isSingleSel()) {\n this.isCellDrag = true;\n isDrag = true;\n }\n else if (gObj.allowRowDragAndDrop) {\n if (!this.isRowType() || this.isSingleSel() || closest(target, 'td').classList.contains('e-selectionbackground')) {\n this.isDragged = false;\n return;\n }\n isDrag = true;\n this.element = this.parent.createElement('div', { className: 'e-griddragarea' });\n gObj.getContent().appendChild(this.element);\n }\n if (isDrag) {\n var tr = closest(e.target, 'tr');\n this.startIndex = parseInt(tr.getAttribute('aria-rowindex'), 10);\n this.startCellIndex = parseInt(parentsUntil(target, 'e-rowcell').getAttribute('aria-colindex'), 10);\n document.body.classList.add('e-disableuserselect');\n var gBRect = gObj.element.getBoundingClientRect();\n var postion = getPosition(e);\n this.x = postion.x - gBRect.left;\n this.y = postion.y - gBRect.top;\n EventHandler.add(gObj.getContent(), 'mousemove', this.mouseMoveHandler, this);\n EventHandler.add(document.body, 'mouseup', this.mouseUpHandler, this);\n }\n }\n };\n Selection.prototype.clearSelAfterRefresh = function (e) {\n if (e.requestType !== 'virtualscroll' && !this.parent.isPersistSelection) {\n this.clearSelection();\n }\n };\n /**\n * @hidden\n */\n Selection.prototype.addEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.uiUpdate, this.enableAfterRender, this);\n this.parent.on(events.initialEnd, this.initializeSelection, this);\n this.parent.on(events.rowSelectionComplete, this.onActionComplete, this);\n this.parent.on(events.cellSelectionComplete, this.onActionComplete, this);\n this.parent.on(events.inBoundModelChanged, this.onPropertyChanged, this);\n this.parent.on(events.cellFocused, this.onCellFocused, this);\n this.parent.on(events.beforeFragAppend, this.clearSelAfterRefresh, this);\n this.parent.on(events.columnPositionChanged, this.columnPositionChanged, this);\n this.parent.on(events.contentReady, this.initialEnd, this);\n this.actionBeginFunction = this.actionBegin.bind(this);\n this.actionCompleteFunction = this.actionComplete.bind(this);\n this.parent.addEventListener(events.actionBegin, this.actionBeginFunction);\n this.parent.addEventListener(events.actionComplete, this.actionCompleteFunction);\n this.parent.on(events.rowsRemoved, this.rowsRemoved, this);\n this.parent.on(events.headerRefreshed, this.refreshHeader, this);\n this.addEventListener_checkbox();\n };\n /**\n * @hidden\n */\n Selection.prototype.removeEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off(events.uiUpdate, this.enableAfterRender);\n this.parent.off(events.initialEnd, this.initializeSelection);\n this.parent.off(events.rowSelectionComplete, this.onActionComplete);\n this.parent.off(events.cellSelectionComplete, this.onActionComplete);\n this.parent.off(events.inBoundModelChanged, this.onPropertyChanged);\n this.parent.off(events.cellFocused, this.onCellFocused);\n this.parent.off(events.beforeFragAppend, this.clearSelAfterRefresh);\n this.parent.off(events.columnPositionChanged, this.columnPositionChanged);\n this.parent.removeEventListener(events.actionBegin, this.actionBeginFunction);\n this.parent.removeEventListener(events.actionComplete, this.actionCompleteFunction);\n this.parent.off(events.rowsRemoved, this.rowsRemoved);\n this.parent.off(events.headerRefreshed, this.refreshHeader);\n this.removeEventListener_checkbox();\n };\n Selection.prototype.columnPositionChanged = function () {\n if (!this.parent.isPersistSelection) {\n this.clearSelection();\n }\n };\n Selection.prototype.refreshHeader = function () {\n this.setCheckAllState();\n };\n Selection.prototype.rowsRemoved = function (e) {\n for (var i = 0; i < e.records.length; i++) {\n delete (this.selectedRowState[e.records[i][this.primaryKey]]);\n --this.totalRecordsCount;\n }\n this.setCheckAllState();\n };\n ;\n Selection.prototype.beforeFragAppend = function (e) {\n if (e.requestType !== 'virtualscroll' && !this.parent.isPersistSelection) {\n this.clearSelection();\n }\n };\n ;\n Selection.prototype.getCheckAllBox = function () {\n return this.parent.getHeaderContent().querySelector('.e-checkselectall');\n };\n Selection.prototype.enableAfterRender = function (e) {\n if (e.module === this.getModuleName() && e.enable) {\n this.render();\n }\n };\n Selection.prototype.render = function (e) {\n EventHandler.add(this.parent.getContent(), 'mousedown', this.mouseDownHandler, this);\n };\n Selection.prototype.onPropertyChanged = function (e) {\n if (e.module !== this.getModuleName()) {\n return;\n }\n var gObj = this.parent;\n if (!isNullOrUndefined(e.properties.type) && this.selectionSettings.type === 'Single') {\n if (this.selectedRowCellIndexes.length > 1) {\n this.clearCellSelection();\n }\n if (this.selectedRowIndexes.length > 1) {\n this.clearRowSelection();\n }\n this.enableSelectMultiTouch = false;\n this.hidePopUp();\n }\n if (!isNullOrUndefined(e.properties.mode) ||\n !isNullOrUndefined(e.properties.cellSelectionMode)) {\n this.clearSelection();\n }\n this.checkBoxSelectionChanged();\n this.initPerisistSelection();\n };\n Selection.prototype.hidePopUp = function () {\n if (this.parent.element.querySelector('.e-gridpopup').querySelectorAll('.e-rowselect').length) {\n this.parent.element.querySelector('.e-gridpopup').style.display = 'none';\n }\n };\n Selection.prototype.initialEnd = function () {\n this.parent.off(events.contentReady, this.initialEnd);\n this.selectRow(this.parent.selectedRowIndex);\n };\n Selection.prototype.checkBoxSelectionChanged = function () {\n this.parent.off(events.contentReady, this.checkBoxSelectionChanged);\n var gobj = this.parent;\n var checkboxColumn = gobj.getColumns().filter(function (col) { return col.type === 'checkbox'; });\n if (checkboxColumn.length > 0) {\n gobj.isCheckBoxSelection = true;\n this.chkField = checkboxColumn[0].field;\n this.totalRecordsCount = this.parent.pageSettings.totalRecordsCount;\n if (isNullOrUndefined(this.totalRecordsCount)) {\n this.totalRecordsCount = this.parent.getCurrentViewRecords().length;\n }\n if (this.isSingleSel()) {\n gobj.selectionSettings.type = 'Multiple';\n gobj.dataBind();\n }\n else {\n this.initPerisistSelection();\n }\n }\n if (!gobj.isCheckBoxSelection) {\n this.chkField = null;\n this.initPerisistSelection();\n }\n };\n Selection.prototype.initPerisistSelection = function () {\n var gobj = this.parent;\n if (this.parent.selectionSettings.persistSelection && this.parent.getPrimaryKeyFieldNames().length > 0) {\n gobj.isPersistSelection = true;\n this.ensureCheckboxFieldSelection();\n }\n else if (this.parent.getPrimaryKeyFieldNames().length > 0) {\n gobj.isPersistSelection = false;\n this.ensureCheckboxFieldSelection();\n }\n else {\n gobj.isPersistSelection = false;\n this.selectedRowState = {};\n }\n };\n Selection.prototype.ensureCheckboxFieldSelection = function () {\n var gobj = this.parent;\n this.primaryKey = this.parent.getPrimaryKeyFieldNames()[0];\n if (!gobj.enableVirtualization && this.chkField\n && ((gobj.isPersistSelection && Object.keys(this.selectedRowState).length === 0) ||\n !gobj.isPersistSelection)) {\n var data = this.parent.getDataModule();\n var query = new Query().where(this.chkField, 'equal', true);\n var dataManager = data.getData({}, query);\n var proxy_1 = this;\n this.parent.showSpinner();\n dataManager.then(function (e) {\n proxy_1.dataSuccess(e.result);\n proxy_1.refreshPersistSelection();\n proxy_1.parent.hideSpinner();\n });\n }\n };\n Selection.prototype.dataSuccess = function (res) {\n for (var i = 0; i < res.length; i++) {\n if (isNullOrUndefined(this.selectedRowState[res[i][this.primaryKey]]) && res[i][this.chkField]) {\n this.selectedRowState[res[i][this.primaryKey]] = res[i][this.chkField];\n }\n }\n this.persistSelectedData = res;\n };\n Selection.prototype.setRowSelection = function (state) {\n if (!this.parent.getDataModule().isRemote()) {\n if (state) {\n for (var _i = 0, _a = this.getData(); _i < _a.length; _i++) {\n var data = _a[_i];\n this.selectedRowState[data[this.primaryKey]] = true;\n }\n }\n else {\n this.selectedRowState = {};\n }\n // (this.getData()).forEach(function (data) {\n // this.selectedRowState[data[this.primaryKey]] = true;\n // })\n }\n };\n Selection.prototype.getData = function () {\n return this.parent.getDataModule().dataManager.dataSource.json;\n };\n Selection.prototype.refreshPersistSelection = function () {\n var rows = this.parent.getRows();\n if (rows.length > 0 && (this.parent.isPersistSelection || this.chkField)) {\n var indexes = [];\n for (var j = 0; j < rows.length; j++) {\n var rowObj = this.getRowObj(rows[j]);\n var pKey = rowObj ? rowObj.data[this.primaryKey] : null;\n if (pKey === null) {\n return;\n }\n var checkState = void 0;\n var chkBox = rows[j].querySelector('.e-checkselect');\n if (this.selectedRowState[pKey] || (this.parent.checkAllRows === 'Check' && this.chkAllCollec.indexOf(pKey) < 0)\n || (this.parent.checkAllRows === 'Uncheck' && this.chkAllCollec.indexOf(pKey) > 0)\n || (this.parent.checkAllRows === 'Intermediate' && !isNullOrUndefined(this.chkField) && rowObj.data[this.chkField])) {\n indexes.push(parseInt(rows[j].getAttribute('aria-rowindex'), 10));\n checkState = true;\n }\n else {\n checkState = false;\n if (this.checkedTarget !== chkBox && this.parent.isCheckBoxSelection) {\n removeAddCboxClasses(chkBox.nextElementSibling, checkState);\n }\n }\n this.updatePersistCollection(rows[j], checkState);\n }\n this.isSingleSel() && indexes.length > 0 ? this.selectRow(indexes[0], true) : this.selectRows(indexes);\n }\n if (this.parent.isCheckBoxSelection && this.parent.getCurrentViewRecords().length > 0) {\n this.setCheckAllState();\n }\n };\n Selection.prototype.actionBegin = function (e) {\n if (e.requestType === 'save' && this.parent.isPersistSelection) {\n var editChkBox = this.parent.element.querySelector('.e-edit-checkselect');\n if (!isNullOrUndefined(editChkBox)) {\n var row = closest(editChkBox, '.e-editedrow');\n if (row) {\n if (this.parent.editSettings.mode === 'Dialog') {\n row = this.parent.element.querySelector('.e-dlgeditrow');\n }\n var rowObj = this.getRowObj(row);\n if (!rowObj) {\n return;\n }\n this.selectedRowState[rowObj.data[this.primaryKey]] = rowObj.isSelected = editChkBox.checked;\n }\n else {\n this.isCheckedOnAdd = editChkBox.checked;\n }\n }\n }\n };\n Selection.prototype.actionComplete = function (e) {\n var _this = this;\n if (e.requestType === 'save' && this.parent.isPersistSelection) {\n if (e.action === 'add' && this.isCheckedOnAdd) {\n var rowObj = this.parent.getRowObjectFromUID(this.parent.getRows()[e.selectedRow].getAttribute('data-uid'));\n this.selectedRowState[rowObj.data[this.primaryKey]] = rowObj.isSelected = this.isCheckedOnAdd;\n }\n this.refreshPersistSelection();\n }\n if (e.requestType === 'delete' && this.parent.isPersistSelection) {\n e.data.slice().forEach(function (data) {\n if (!isNullOrUndefined(data[_this.primaryKey])) {\n _this.updatePersistDelete(data[_this.primaryKey]);\n }\n });\n this.setCheckAllState();\n this.totalRecordsCount = this.parent.pageSettings.totalRecordsCount;\n }\n };\n Selection.prototype.onDataBound = function () {\n if (!this.parent.enableVirtualization && this.parent.isPersistSelection) {\n this.refreshPersistSelection();\n }\n };\n Selection.prototype.checkSelectAllAction = function (checkState) {\n var cRenderer = this.getRenderer();\n var editForm = this.parent.element.querySelector('.e-gridform');\n this.checkedTarget = this.getCheckAllBox();\n if (checkState && this.parent.getCurrentViewRecords().length) {\n this.selectRowsByRange(cRenderer.getVirtualRowIndex(0), cRenderer.getVirtualRowIndex(this.parent.getCurrentViewRecords().length));\n this.parent.checkAllRows = 'Check';\n }\n else {\n this.clearSelection();\n this.parent.checkAllRows = 'Uncheck';\n }\n this.chkAllCollec = [];\n if (this.parent.isPersistSelection) {\n var rows = this.parent.getRows();\n for (var i = 0; i < rows.length; i++) {\n this.updatePersistCollection(rows[i], checkState);\n }\n if (this.parent.checkAllRows === 'Uncheck') {\n this.setRowSelection(false);\n this.persistSelectedData = this.parent.getDataModule().isRemote() ? this.persistSelectedData : [];\n }\n else if (this.parent.checkAllRows === 'Check') {\n this.setRowSelection(true);\n this.persistSelectedData = !this.parent.getDataModule().isRemote() ? this.getData().slice() : this.persistSelectedData;\n }\n }\n if (!isNullOrUndefined(editForm)) {\n var editChkBox = editForm.querySelector('.e-edit-checkselect');\n removeAddCboxClasses(editChkBox.nextElementSibling, checkState);\n }\n };\n Selection.prototype.checkSelectAll = function (checkBox) {\n var _this = this;\n var stateStr = this.getCheckAllStatus(checkBox);\n var state = stateStr === 'Check';\n if (stateStr === 'Intermediate') {\n state = this.parent.getCurrentViewRecords().some(function (data) {\n return data[_this.primaryKey] in _this.selectedRowState;\n });\n }\n this.checkSelectAllAction(!state);\n this.target = null;\n if (this.parent.getCurrentViewRecords().length > 0) {\n this.setCheckAllState();\n }\n this.triggerChkChangeEvent(checkBox, !state);\n };\n Selection.prototype.getCheckAllStatus = function (ele) {\n var classes = ele ? ele.nextElementSibling.classList :\n this.getCheckAllBox().nextElementSibling.classList;\n var status;\n if (classes.contains('e-check')) {\n status = 'Check';\n }\n else if (classes.contains('e-uncheck')) {\n status = 'Uncheck';\n }\n else if (classes.contains('e-stop')) {\n status = 'Intermediate';\n }\n else {\n status = 'None';\n }\n return status;\n };\n Selection.prototype.checkSelect = function (checkBox) {\n var target = closest(this.checkedTarget, '.e-rowcell');\n var checkObj = checkBox;\n this.isMultiCtrlRequest = true;\n var rIndex = parseInt(target.parentElement.getAttribute('aria-rowindex'), 10);\n if (this.parent.isPersistSelection && this.parent.element.querySelectorAll('.e-addedrow').length > 0) {\n ++rIndex;\n }\n this.rowCellSelectionHandler(rIndex, parseInt(target.getAttribute('aria-colindex'), 10));\n this.moveIntoUncheckCollection(closest(target, '.e-row'));\n this.setCheckAllState();\n this.isMultiCtrlRequest = false;\n this.triggerChkChangeEvent(checkBox, checkBox.nextElementSibling.classList.contains('e-check'));\n };\n Selection.prototype.moveIntoUncheckCollection = function (row) {\n if (this.parent.checkAllRows === 'Check' || this.parent.checkAllRows === 'Uncheck') {\n var rowObj = this.getRowObj(row);\n var pKey = rowObj && rowObj.data ? rowObj.data[this.primaryKey] : null;\n if (!pKey) {\n return;\n }\n if (this.chkAllCollec.indexOf(pKey) < 0) {\n this.chkAllCollec.push(pKey);\n }\n else {\n this.chkAllCollec.splice(this.chkAllCollec.indexOf(pKey), 1);\n }\n }\n };\n Selection.prototype.triggerChkChangeEvent = function (checkBox, checkState) {\n this.parent.trigger(events.checkBoxChange, {\n checked: checkState, selectedRowIndexes: this.parent.getSelectedRowIndexes(),\n target: checkBox\n });\n if (!this.parent.isEdit) {\n this.checkedTarget = null;\n }\n };\n Selection.prototype.updateSelectedRowIndex = function (index) {\n if (this.parent.isCheckBoxSelection && this.parent.enableVirtualization && !this.parent.getDataModule().isRemote()) {\n if (this.parent.checkAllRows === 'Check') {\n this.selectedRowIndexes = [];\n for (var data = 0; data < this.getData().length; data++) {\n this.selectedRowIndexes.push(data);\n }\n }\n else if (this.parent.checkAllRows === 'Uncheck') {\n this.selectedRowIndexes = [];\n }\n else {\n if (index && this.parent.getRowByIndex(index).getAttribute('aria-selected') === 'false') {\n var selectedVal = this.selectedRowIndexes.indexOf(index);\n this.selectedRowIndexes.splice(selectedVal, 1);\n }\n }\n }\n };\n ;\n Selection.prototype.setCheckAllState = function (index, isInteraction) {\n if (this.parent.isCheckBoxSelection) {\n var checkedLen = Object.keys(this.selectedRowState).length;\n if (!this.parent.isPersistSelection) {\n checkedLen = this.selectedRecords.length;\n this.totalRecordsCount = this.parent.getCurrentViewRecords().length;\n }\n if (this.getCheckAllBox()) {\n var spanEle = this.getCheckAllBox().nextElementSibling;\n removeClass([spanEle], ['e-check', 'e-stop', 'e-uncheck']);\n if (checkedLen === this.totalRecordsCount && this.totalRecordsCount || (this.parent.enableVirtualization\n && !this.parent.allowPaging && !this.parent.getDataModule().isRemote() && checkedLen === this.getData().length)) {\n addClass([spanEle], ['e-check']);\n if (isInteraction) {\n this.getRenderer().setSelection(null, true, true);\n }\n this.parent.checkAllRows = 'Check';\n }\n else if (checkedLen === 0 || this.parent.getCurrentViewRecords().length === 0) {\n addClass([spanEle], ['e-uncheck']);\n if (isInteraction) {\n this.getRenderer().setSelection(null, false, true);\n }\n this.parent.checkAllRows = 'Uncheck';\n if (checkedLen === 0 && this.parent.getCurrentViewRecords().length === 0) {\n addClass([spanEle.parentElement], ['e-checkbox-disabled']);\n }\n else {\n removeClass([spanEle.parentElement], ['e-checkbox-disabled']);\n }\n }\n else {\n addClass([spanEle], ['e-stop']);\n this.parent.checkAllRows = 'Intermediate';\n }\n if (this.parent.enableVirtualization && !this.parent.allowPaging && !this.parent.getDataModule().isRemote()) {\n this.updateSelectedRowIndex(index);\n }\n }\n }\n };\n Selection.prototype.clickHandler = function (e) {\n var target = e.target;\n this.isMultiCtrlRequest = e.ctrlKey || this.enableSelectMultiTouch;\n this.isMultiShiftRequest = e.shiftKey;\n this.popUpClickHandler(e);\n var chkSelect = false;\n this.preventFocus = true;\n var checkBox;\n var checkWrap = parentsUntil(target, 'e-checkbox-wrapper');\n if (checkWrap && checkWrap.querySelectorAll('.e-checkselect,.e-checkselectall').length > 0) {\n checkBox = checkWrap.querySelector('input[type=\"checkbox\"]');\n chkSelect = true;\n }\n target = parentsUntil(target, 'e-rowcell');\n if ((target && target.parentElement.classList.contains('e-row') && !this.parent.selectionSettings.checkboxOnly) || chkSelect) {\n if (this.parent.isCheckBoxSelection) {\n this.isMultiCtrlRequest = true;\n }\n this.target = target;\n if (!isNullOrUndefined(checkBox)) {\n this.checkedTarget = checkBox;\n if (checkBox.classList.contains('e-checkselectall')) {\n this.checkSelectAll(checkBox);\n }\n else {\n this.checkSelect(checkBox);\n this.target = closest(target, '.e-rowcell');\n }\n }\n else {\n var rIndex = parseInt(target.parentElement.getAttribute('aria-rowindex'), 10);\n if (this.parent.isPersistSelection && this.parent.element.querySelectorAll('.e-addedrow').length > 0) {\n ++rIndex;\n }\n this.rowCellSelectionHandler(rIndex, parseInt(target.getAttribute('aria-colindex'), 10));\n if (this.parent.isCheckBoxSelection) {\n this.moveIntoUncheckCollection(closest(target, '.e-row'));\n this.setCheckAllState();\n }\n }\n if (!this.parent.isCheckBoxSelection && Browser.isDevice && !this.isSingleSel()) {\n this.showPopup(e);\n }\n }\n this.isMultiCtrlRequest = false;\n this.isMultiShiftRequest = false;\n this.preventFocus = false;\n };\n Selection.prototype.popUpClickHandler = function (e) {\n var target = e.target;\n if (closest(target, '.e-headercell') || e.target.classList.contains('e-rowcell') ||\n closest(target, '.e-gridpopup')) {\n if (target.classList.contains('e-rowselect')) {\n if (!target.classList.contains('e-spanclicked')) {\n target.classList.add('e-spanclicked');\n this.enableSelectMultiTouch = true;\n }\n else {\n target.classList.remove('e-spanclicked');\n this.enableSelectMultiTouch = false;\n this.parent.element.querySelector('.e-gridpopup').style.display = 'none';\n }\n }\n }\n else {\n this.parent.element.querySelector('.e-gridpopup').style.display = 'none';\n }\n };\n Selection.prototype.showPopup = function (e) {\n setCssInGridPopUp(this.parent.element.querySelector('.e-gridpopup'), e, 'e-rowselect e-icons e-icon-rowselect' +\n (!this.isSingleSel() && (this.selectedRecords.length > (this.parent.getFrozenColumns() ? 2 : 1)\n || this.selectedRowCellIndexes.length > 1) ? ' e-spanclicked' : ''));\n };\n Selection.prototype.rowCellSelectionHandler = function (rowIndex, cellIndex) {\n if ((!this.isMultiCtrlRequest && !this.isMultiShiftRequest) || this.isSingleSel()) {\n if (!this.isDragged) {\n this.selectRow(rowIndex, true);\n }\n this.selectCell({ rowIndex: rowIndex, cellIndex: cellIndex }, true);\n }\n else if (this.isMultiShiftRequest) {\n this.selectRowsByRange(isUndefined(this.prevRowIndex) ? rowIndex : this.prevRowIndex, rowIndex);\n this.selectCellsByRange(isUndefined(this.prevCIdxs) ? { rowIndex: rowIndex, cellIndex: cellIndex } : this.prevCIdxs, { rowIndex: rowIndex, cellIndex: cellIndex });\n }\n else {\n this.addRowsToSelection([rowIndex]);\n this.addCellsToSelection([{ rowIndex: rowIndex, cellIndex: cellIndex }]);\n }\n this.isDragged = false;\n };\n Selection.prototype.onCellFocused = function (e) {\n if (this.parent.frozenRows && e.container.isHeader && e.byKey) {\n if (e.keyArgs.action === 'upArrow') {\n if (this.parent.allowFiltering) {\n e.isJump = e.element.tagName === 'INPUT' ? true : false;\n }\n else {\n e.isJump = e.element.tagName === 'TH' ? true : false;\n }\n }\n else {\n if (e.keyArgs.action === 'downArrow') {\n var rIdx = Number(e.element.parentElement.getAttribute('aria-rowindex'));\n e.isJump = rIdx === 0 ? true : false;\n }\n else {\n if (e.keyArgs.action === 'ctrlHome') {\n e.isJump = true;\n }\n }\n }\n }\n var clear = this.parent.getFrozenColumns() ? (((e.container.isHeader && e.element.tagName !== 'TD' && e.isJump) ||\n ((e.container.isContent || e.element.tagName === 'TD') && !(e.container.isSelectable || e.element.tagName === 'TD')))\n && !(e.byKey && e.keyArgs.action === 'space')) : ((e.container.isHeader && e.isJump) ||\n (e.container.isContent && !e.container.isSelectable)) && !(e.byKey && e.keyArgs.action === 'space');\n var headerAction = (e.container.isHeader && e.element.tagName !== 'TD' && !closest(e.element, '.e-rowcell'))\n && !(e.byKey && e.keyArgs.action === 'space');\n if (!e.byKey || clear) {\n if (clear && !this.parent.isCheckBoxSelection) {\n this.clearSelection();\n }\n return;\n }\n var _a = e.container.isContent ? e.container.indexes : e.indexes, rowIndex = _a[0], cellIndex = _a[1];\n var prev = this.focus.getPrevIndexes();\n if (this.parent.frozenRows) {\n if (e.container.isHeader && (e.element.tagName === 'TD' || closest(e.element, '.e-rowcell'))) {\n var thLen = this.parent.getHeaderTable().querySelector('thead').childElementCount;\n rowIndex -= thLen;\n prev.rowIndex = prev.rowIndex ? prev.rowIndex - thLen : null;\n }\n else {\n rowIndex += this.parent.frozenRows;\n prev.rowIndex = prev.rowIndex === 0 || !isNullOrUndefined(prev.rowIndex) ? prev.rowIndex + this.parent.frozenRows : null;\n }\n if (this.parent.getFrozenColumns()) {\n var cIdx = Number(e.element.getAttribute('aria-colindex'));\n prev.cellIndex = prev.cellIndex ? (prev.cellIndex === cellIndex ? cIdx : cIdx - 1) : null;\n cellIndex = cIdx;\n }\n }\n if (headerAction || (['ctrlPlusA', 'escape'].indexOf(e.keyArgs.action) === -1 && e.keyArgs.action !== 'space' &&\n rowIndex === prev.rowIndex && cellIndex === prev.cellIndex)) {\n return;\n }\n this.preventFocus = true;\n switch (e.keyArgs.action) {\n case 'downArrow':\n case 'upArrow':\n case 'enter':\n case 'shiftEnter':\n this.applyDownUpKey(rowIndex, cellIndex);\n break;\n case 'rightArrow':\n case 'leftArrow':\n this.applyRightLeftKey(rowIndex, cellIndex);\n break;\n case 'shiftDown':\n case 'shiftUp':\n this.shiftDownKey(rowIndex, cellIndex);\n break;\n case 'shiftLeft':\n case 'shiftRight':\n this.applyShiftLeftRightKey(rowIndex, cellIndex);\n break;\n case 'home':\n case 'end':\n cellIndex = e.keyArgs.action === 'end' ? this.getLastColIndex(rowIndex) : 0;\n this.applyHomeEndKey(rowIndex, cellIndex);\n break;\n case 'ctrlHome':\n case 'ctrlEnd':\n this.applyCtrlHomeEndKey(rowIndex, cellIndex);\n break;\n case 'escape':\n this.clearSelection();\n break;\n case 'ctrlPlusA':\n this.ctrlPlusA();\n break;\n case 'space':\n this.applySpaceSelection(e.element);\n break;\n }\n this.preventFocus = false;\n };\n /**\n * Apply ctrl + A key selection\n * @return {void}\n * @hidden\n */\n Selection.prototype.ctrlPlusA = function () {\n if (this.isRowType() && !this.isSingleSel()) {\n this.selectRowsByRange(0, this.parent.getRows().length - 1);\n }\n if (this.isCellType() && !this.isSingleSel()) {\n this.selectCellsByRange({ rowIndex: 0, cellIndex: 0 }, { rowIndex: this.parent.getRows().length - 1, cellIndex: this.parent.getColumns().length - 1 });\n }\n };\n Selection.prototype.applySpaceSelection = function (target) {\n if (target.classList.contains('e-checkselectall')) {\n this.checkedTarget = target;\n this.checkSelectAll(this.checkedTarget);\n }\n else {\n if (target.classList.contains('e-checkselect')) {\n this.checkedTarget = target;\n this.checkSelect(this.checkedTarget);\n }\n }\n };\n Selection.prototype.applyDownUpKey = function (rowIndex, cellIndex) {\n var gObj = this.parent;\n if (this.parent.isCheckBoxSelection && this.parent.checkAllRows === 'Check') {\n this.checkSelectAllAction(false);\n this.checkedTarget = null;\n }\n if (this.isRowType()) {\n if (this.parent.frozenRows) {\n this.selectRow(rowIndex, true);\n this.applyUpDown(gObj.selectedRowIndex);\n }\n else {\n this.selectRow(rowIndex, true);\n this.applyUpDown(gObj.selectedRowIndex);\n }\n }\n if (this.isCellType()) {\n this.selectCell({ rowIndex: rowIndex, cellIndex: cellIndex }, true);\n }\n };\n Selection.prototype.applyUpDown = function (rowIndex) {\n if (rowIndex < 0) {\n return;\n }\n if (!this.target) {\n this.target = this.parent.getRows()[0].children[this.parent.groupSettings.columns.length || 0];\n }\n var cIndex = parseInt(this.target.getAttribute('aria-colindex'), 10);\n var frzCols = this.parent.getFrozenColumns();\n if (frzCols) {\n if (cIndex >= frzCols) {\n this.target =\n this.contentRenderer.getMovableRowByIndex(rowIndex).querySelectorAll('.e-rowcell')[cIndex - frzCols];\n }\n else {\n this.target = this.contentRenderer.getRowByIndex(rowIndex).querySelectorAll('.e-rowcell')[cIndex];\n }\n }\n else {\n this.target = this.contentRenderer.getRowByIndex(rowIndex).querySelectorAll('.e-rowcell')[cIndex];\n }\n this.addAttribute(this.target);\n };\n Selection.prototype.applyRightLeftKey = function (rowIndex, cellIndex) {\n var gObj = this.parent;\n if (this.isCellType()) {\n this.selectCell({ rowIndex: rowIndex, cellIndex: cellIndex }, true);\n this.addAttribute(this.target);\n }\n };\n Selection.prototype.applyHomeEndKey = function (rowIndex, cellIndex) {\n if (this.isCellType()) {\n this.selectCell({ rowIndex: rowIndex, cellIndex: cellIndex }, true);\n }\n else {\n this.addAttribute(this.parent.getCellFromIndex(rowIndex, cellIndex));\n }\n };\n /**\n * Apply shift+down key selection\n * @return {void}\n * @hidden\n */\n Selection.prototype.shiftDownKey = function (rowIndex, cellIndex) {\n var gObj = this.parent;\n this.isMultiShiftRequest = true;\n if (this.isRowType() && !this.isSingleSel()) {\n if (!isUndefined(this.prevRowIndex)) {\n this.selectRowsByRange(this.prevRowIndex, rowIndex);\n this.applyUpDown(rowIndex);\n }\n else {\n this.selectRow(0, true);\n }\n }\n if (this.isCellType() && !this.isSingleSel()) {\n this.selectCellsByRange(this.prevCIdxs || { rowIndex: 0, cellIndex: 0 }, { rowIndex: rowIndex, cellIndex: cellIndex });\n }\n this.isMultiShiftRequest = false;\n };\n Selection.prototype.applyShiftLeftRightKey = function (rowIndex, cellIndex) {\n var gObj = this.parent;\n this.isMultiShiftRequest = true;\n this.selectCellsByRange(this.prevCIdxs, { rowIndex: rowIndex, cellIndex: cellIndex });\n this.isMultiShiftRequest = false;\n };\n Selection.prototype.applyCtrlHomeEndKey = function (rowIndex, cellIndex) {\n if (this.isRowType()) {\n this.selectRow(rowIndex, true);\n this.addAttribute(this.parent.getCellFromIndex(rowIndex, cellIndex));\n }\n if (this.isCellType()) {\n this.selectCell({ rowIndex: rowIndex, cellIndex: cellIndex }, true);\n }\n };\n Selection.prototype.addRemoveClassesForRow = function (row, isAdd, clearAll) {\n var args = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n args[_i - 3] = arguments[_i];\n }\n if (row) {\n var cells = [].slice.call(row.querySelectorAll('.e-rowcell'));\n var cell = row.querySelector('.e-detailrowcollapse') || row.querySelector('.e-detailrowexpand');\n if (cell) {\n cells.push(cell);\n }\n addRemoveActiveClasses.apply(void 0, [cells, isAdd].concat(args));\n }\n this.getRenderer().setSelection(row ? row.getAttribute('data-uid') : null, isAdd, clearAll);\n };\n Selection.prototype.isRowType = function () {\n return this.selectionSettings.mode === 'Row' || this.selectionSettings.mode === 'Both';\n };\n Selection.prototype.isCellType = function () {\n return this.selectionSettings.mode === 'Cell' || this.selectionSettings.mode === 'Both';\n };\n Selection.prototype.isSingleSel = function () {\n return this.selectionSettings.type === 'Single';\n };\n Selection.prototype.getRenderer = function () {\n if (isNullOrUndefined(this.contentRenderer)) {\n this.contentRenderer = this.factory.getRenderer(RenderType.Content);\n }\n return this.contentRenderer;\n };\n /**\n * Gets the collection of selected records.\n * @return {Object[]}\n */\n Selection.prototype.getSelectedRecords = function () {\n var selectedData = [];\n if (!this.selectionSettings.persistSelection) {\n selectedData = this.parent.getRowsObject().filter(function (row) { return row.isSelected; })\n .map(function (m) { return m.data; });\n }\n else {\n selectedData = this.persistSelectedData;\n }\n return selectedData;\n };\n Selection.prototype.addEventListener_checkbox = function () {\n this.parent.on(events.dataReady, this.dataReady, this);\n this.onDataBoundFunction = this.onDataBound.bind(this);\n this.parent.addEventListener(events.dataBound, this.onDataBoundFunction);\n this.parent.on(events.contentReady, this.checkBoxSelectionChanged, this);\n this.actionCompleteFunc = this.actionCompleteHandler.bind(this);\n this.parent.addEventListener(events.actionComplete, this.actionCompleteFunc);\n this.parent.on(events.click, this.clickHandler, this);\n };\n Selection.prototype.removeEventListener_checkbox = function () {\n this.parent.off(events.dataReady, this.dataReady);\n this.parent.removeEventListener(events.dataBound, this.onDataBoundFunction);\n this.parent.removeEventListener(events.actionComplete, this.actionCompleteFunc);\n this.parent.off(events.click, this.clickHandler);\n };\n Selection.prototype.dataReady = function (e) {\n if (e.requestType !== 'virtualscroll' && !this.parent.isPersistSelection) {\n this.disableUI = true;\n this.clearSelection();\n this.disableUI = false;\n }\n };\n Selection.prototype.actionCompleteHandler = function (e) {\n if (e.requestType === 'save' && this.parent.isPersistSelection) {\n this.refreshPersistSelection();\n }\n };\n return Selection;\n}());\nexport { Selection };\n","import { extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport * as events from '../base/constant';\nimport { isActionPrevent } from '../base/util';\n/**\n * The `Search` module is used to handle search action.\n */\nvar Search = /** @class */ (function () {\n /**\n * Constructor for Grid search module.\n * @hidden\n */\n function Search(parent) {\n this.parent = parent;\n this.addEventListener();\n }\n /**\n * Searches Grid records by given key.\n *\n * > You can customize the default search action by using [`searchSettings`](./api-grid.html#searchsettings-searchsettingsmodel).\n * @param {string} searchString - Defines the key.\n * @return {void}\n */\n Search.prototype.search = function (searchString) {\n var gObj = this.parent;\n searchString = isNullOrUndefined(searchString) ? '' : searchString;\n if (isActionPrevent(gObj)) {\n gObj.notify(events.preventBatch, { instance: this, handler: this.search, arg1: searchString });\n return;\n }\n if (searchString !== gObj.searchSettings.key) {\n gObj.searchSettings.key = searchString.toString();\n gObj.dataBind();\n }\n else if (this.refreshSearch) {\n gObj.refresh();\n }\n };\n /**\n * @hidden\n */\n Search.prototype.addEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.inBoundModelChanged, this.onPropertyChanged, this);\n this.parent.on(events.searchComplete, this.onSearchComplete, this);\n this.parent.on(events.destroy, this.destroy, this);\n this.actionCompleteFunc = this.onActionComplete.bind(this);\n this.parent.addEventListener(events.actionComplete, this.actionCompleteFunc);\n };\n /**\n * @hidden\n */\n Search.prototype.removeEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off(events.inBoundModelChanged, this.onPropertyChanged);\n this.parent.off(events.searchComplete, this.onSearchComplete);\n this.parent.off(events.destroy, this.destroy);\n this.parent.removeEventListener(events.actionComplete, this.actionCompleteFunc);\n };\n /**\n * To destroy the print\n * @return {void}\n * @hidden\n */\n Search.prototype.destroy = function () {\n this.removeEventListener();\n };\n /**\n * @hidden\n */\n Search.prototype.onPropertyChanged = function (e) {\n if (e.module !== this.getModuleName()) {\n return;\n }\n if (!isNullOrUndefined(e.properties.key)) {\n this.parent.notify(events.modelChanged, {\n requestType: 'searching', type: events.actionBegin, searchString: this.parent.searchSettings.key\n });\n }\n else {\n this.parent.notify(events.modelChanged, {\n requestType: 'searching', type: events.actionBegin\n });\n }\n };\n /**\n * The function used to trigger onActionComplete\n * @return {void}\n * @hidden\n */\n Search.prototype.onSearchComplete = function (e) {\n this.parent.trigger(events.actionComplete, extend(e, {\n searchString: this.parent.searchSettings.key, requestType: 'searching', type: events.actionComplete\n }));\n };\n Search.prototype.onActionComplete = function (e) {\n this.refreshSearch = e.requestType !== 'searching';\n };\n /**\n * For internal use only - Get the module name.\n * @private\n */\n Search.prototype.getModuleName = function () {\n return 'search';\n };\n return Search;\n}());\nexport { Search };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { iterateArrayOrObject, isActionPrevent } from '../base/util';\nimport * as events from '../base/constant';\n/**\n * The `ShowHide` module is used to control column visibility.\n */\nvar ShowHide = /** @class */ (function () {\n /**\n * Constructor for the show hide module.\n * @hidden\n */\n function ShowHide(parent) {\n this.parent = parent;\n }\n /**\n * Shows a column by column name.\n * @param {string|string[]} columnName - Defines a single or collection of column names to show.\n * @param {string} showBy - Defines the column key either as field name or header text.\n * @return {void}\n */\n ShowHide.prototype.show = function (columnName, showBy) {\n var keys = this.getToggleFields(columnName);\n var columns = this.getColumns(keys, showBy);\n this.parent.notify(events.tooltipDestroy, { module: 'edit' });\n columns.forEach(function (value) {\n value.visible = true;\n });\n this.setVisible(columns);\n };\n /**\n * Hides a column by column name.\n * @param {string|string[]} columnName - Defines a single or collection of column names to hide.\n * @param {string} hideBy - Defines the column key either as field name or header text.\n * @return {void}\n */\n ShowHide.prototype.hide = function (columnName, hideBy) {\n var keys = this.getToggleFields(columnName);\n var columns = this.getColumns(keys, hideBy);\n this.parent.notify(events.tooltipDestroy, { module: 'edit' });\n columns.forEach(function (value) {\n value.visible = false;\n });\n this.setVisible(columns);\n };\n ShowHide.prototype.getToggleFields = function (key) {\n var finalized = [];\n if (typeof key === 'string') {\n finalized = [key];\n }\n else {\n finalized = key;\n }\n return finalized;\n };\n ShowHide.prototype.getColumns = function (keys, getKeyBy) {\n var _this = this;\n var columns = iterateArrayOrObject(keys, function (key, index) {\n return iterateArrayOrObject(_this.parent.getColumns(), function (item, index) {\n if (item[getKeyBy] === key) {\n return item;\n }\n return undefined;\n })[0];\n });\n return columns;\n };\n /**\n * Shows or hides columns by given column collection.\n * @private\n * @param {Column[]} columns - Specifies the columns.\n * @return {void}\n */\n ShowHide.prototype.setVisible = function (columns) {\n if (isActionPrevent(this.parent)) {\n this.parent.notify(events.preventBatch, {\n instance: this, handler: this.setVisible,\n arg1: columns\n });\n return;\n }\n columns = isNullOrUndefined(columns) ? this.parent.getColumns() : columns;\n if (this.parent.allowSelection && this.parent.getSelectedRecords().length) {\n this.parent.clearSelection();\n }\n this.parent.notify(events.columnVisibilityChanged, columns);\n if (this.parent.columnQueryMode !== 'All') {\n this.parent.refresh();\n }\n };\n return ShowHide;\n}());\nexport { ShowHide };\n","import { Browser, EventHandler } from '@syncfusion/ej2-base';\nimport { addClass, removeClass } from '@syncfusion/ej2-base';\nimport { formatUnit, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { getScrollBarWidth, getUpdateUsingRaf } from '../base/util';\nimport { scroll, contentReady, uiUpdate, onEmpty, headerRefreshed } from '../base/constant';\nimport { ColumnWidthService } from '../services/width-controller';\n/**\n * The `Scroll` module is used to handle scrolling behaviour.\n */\nvar Scroll = /** @class */ (function () {\n /**\n * Constructor for the Grid scrolling.\n * @hidden\n */\n function Scroll(parent) {\n this.lastScrollTop = 0;\n //To maintain scroll state on grid actions.\n this.previousValues = { top: 0, left: 0 };\n this.oneTimeReady = true;\n this.parent = parent;\n this.widthService = new ColumnWidthService(parent);\n this.addEventListener();\n }\n /**\n * For internal use only - Get the module name.\n * @private\n */\n Scroll.prototype.getModuleName = function () {\n return 'scroll';\n };\n /**\n * @hidden\n */\n Scroll.prototype.setWidth = function () {\n this.parent.element.style.width = formatUnit(this.parent.width);\n if (this.parent.toolbarModule && this.parent.toolbarModule.toolbar &&\n this.parent.toolbarModule.toolbar.element) {\n this.parent.toolbarModule.toolbar.refreshOverflow();\n }\n };\n /**\n * @hidden\n */\n Scroll.prototype.setHeight = function () {\n var mHdrHeight = 0;\n var content = this.parent.getContent().firstChild;\n if (this.parent.frozenRows && this.parent.height !== 'auto') {\n mHdrHeight =\n this.parent.getHeaderContent().querySelector('tbody').offsetHeight;\n content.style.height = formatUnit(this.parent.height - mHdrHeight);\n }\n else {\n content.style.height = formatUnit(this.parent.height);\n }\n this.ensureOverflow(content);\n };\n /**\n * @hidden\n */\n Scroll.prototype.setPadding = function () {\n var content = this.parent.getHeaderContent();\n var scrollWidth = Scroll.getScrollBarWidth() - this.getThreshold();\n var cssProps = this.getCssProperties();\n content.firstChild.style[cssProps.border] = scrollWidth > 0 ? '1px' : '0px';\n content.style[cssProps.padding] = scrollWidth > 0 ? scrollWidth + 'px' : '0px';\n };\n /**\n * @hidden\n */\n Scroll.prototype.removePadding = function (rtl) {\n var cssProps = this.getCssProperties(rtl);\n this.parent.getHeaderContent().firstChild.style[cssProps.border] = '';\n this.parent.getHeaderContent().firstChild.parentElement.style[cssProps.padding] = '';\n };\n /**\n * Refresh makes the Grid adoptable with the height of parent container.\n *\n * > The [`height`](./api-grid.html#height) must be set to 100%.\n * @return\n */\n Scroll.prototype.refresh = function () {\n if (this.parent.height !== '100%') {\n return;\n }\n var content = this.parent.getContent();\n this.parent.element.style.height = '100%';\n var height = this.widthService.getSiblingsHeight(content);\n content.style.height = 'calc(100% - ' + height + 'px)'; //Set the height to the '.e-gridcontent';\n };\n Scroll.prototype.getThreshold = function () {\n /* Some browsers places the scroller outside the content,\n * hence the padding should be adjusted.*/\n var appName = Browser.info.name;\n if (appName === 'mozilla') {\n return 0.5;\n }\n return 1;\n };\n /**\n * @hidden\n */\n Scroll.prototype.addEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(onEmpty, this.wireEvents, this);\n this.parent.on(contentReady, this.wireEvents, this);\n this.parent.on(uiUpdate, this.onPropertyChanged, this);\n this.parent.on(headerRefreshed, this.setScrollLeft, this);\n };\n /**\n * @hidden\n */\n Scroll.prototype.removeEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off(onEmpty, this.wireEvents);\n this.parent.off(contentReady, this.wireEvents);\n this.parent.off(uiUpdate, this.onPropertyChanged);\n this.parent.off(headerRefreshed, this.setScrollLeft);\n };\n Scroll.prototype.setScrollLeft = function () {\n if (this.parent.frozenColumns) {\n this.parent.headerModule.getMovableHeader().scrollLeft = this.previousValues.left;\n }\n };\n Scroll.prototype.onContentScroll = function (scrollTarget) {\n var _this = this;\n var element = scrollTarget;\n var isHeader = element.classList.contains('e-headercontent');\n return function (e) {\n if (_this.content.querySelector('tbody') === null || _this.parent.isPreventScrollEvent) {\n return;\n }\n var target = e.target;\n var left = target.scrollLeft;\n var sLimit = target.scrollWidth;\n var isFooter = target.classList.contains('e-summarycontent');\n if (_this.previousValues.left === left) {\n _this.previousValues.top = !isHeader ? _this.previousValues.top : target.scrollTop;\n return;\n }\n element.scrollLeft = left;\n if (isFooter) {\n _this.header.scrollLeft = left;\n }\n _this.previousValues.left = left;\n _this.parent.notify(scroll, { left: left });\n };\n };\n Scroll.prototype.onFreezeContentScroll = function (scrollTarget) {\n var _this = this;\n var element = scrollTarget;\n return function (e) {\n if (_this.content.querySelector('tbody') === null) {\n return;\n }\n var target = e.target;\n var top = target.scrollTop;\n if (_this.previousValues.top === top) {\n return;\n }\n element.scrollTop = top;\n _this.previousValues.top = top;\n if (_this.parent.isDestroyed) {\n return;\n }\n };\n };\n Scroll.prototype.onWheelScroll = function (scrollTarget) {\n var _this = this;\n var element = scrollTarget;\n return function (e) {\n if (_this.content.querySelector('tbody') === null) {\n return;\n }\n var top = element.scrollTop + (e.deltaMode === 1 ? e.deltaY * 30 : e.deltaY);\n if (_this.previousValues.top === top) {\n return;\n }\n e.preventDefault();\n _this.parent.getContent().querySelector('.e-frozencontent').scrollTop = top;\n element.scrollTop = top;\n _this.previousValues.top = top;\n };\n };\n Scroll.prototype.onTouchScroll = function (scrollTarget) {\n var _this = this;\n var element = scrollTarget;\n return function (e) {\n if (e.pointerType === 'mouse') {\n return;\n }\n var cont;\n var mHdr;\n var pageXY = _this.getPointXY(e);\n var top = element.scrollTop + (_this.pageXY.y - pageXY.y);\n var left = element.scrollLeft + (_this.pageXY.x - pageXY.x);\n if (_this.parent.getHeaderContent().contains(e.target)) {\n mHdr = _this.parent.getFrozenColumns() ?\n _this.parent.getHeaderContent().querySelector('.e-movableheader') : _this.parent.getHeaderContent().firstChild;\n if (_this.previousValues.left === left || (left < 0 || (mHdr.scrollWidth - mHdr.clientWidth) < left)) {\n return;\n }\n e.preventDefault();\n mHdr.scrollLeft = left;\n element.scrollLeft = left;\n _this.pageXY.x = pageXY.x;\n _this.previousValues.left = left;\n }\n else {\n cont = _this.parent.getContent().querySelector('.e-frozencontent');\n if (_this.previousValues.top === top || (top < 0 || (cont.scrollHeight - cont.clientHeight) < top)) {\n return;\n }\n e.preventDefault();\n cont.scrollTop = top;\n element.scrollTop = top;\n _this.pageXY.y = pageXY.y;\n _this.previousValues.top = top;\n }\n };\n };\n Scroll.prototype.setPageXY = function () {\n var _this = this;\n return function (e) {\n if (e.pointerType === 'mouse') {\n return;\n }\n _this.pageXY = _this.getPointXY(e);\n };\n };\n Scroll.prototype.getPointXY = function (e) {\n var pageXY = { x: 0, y: 0 };\n if (e.touches && e.touches.length) {\n pageXY.x = e.touches[0].pageX;\n pageXY.y = e.touches[0].pageY;\n }\n else {\n pageXY.x = e.pageX;\n pageXY.y = e.pageY;\n }\n return pageXY;\n };\n Scroll.prototype.wireEvents = function () {\n var _this = this;\n if (this.oneTimeReady) {\n var frzCols = this.parent.getFrozenColumns();\n this.content = this.parent.getContent().firstChild;\n this.header = this.parent.getHeaderContent().firstChild;\n var mCont = this.content.querySelector('.e-movablecontent');\n var fCont = this.content.querySelector('.e-frozencontent');\n var mHdr = this.header.querySelector('.e-movableheader');\n if (this.parent.frozenRows) {\n EventHandler.add(frzCols ? mHdr : this.header, 'touchstart pointerdown', this.setPageXY(), this);\n EventHandler.add(frzCols ? mHdr : this.header, 'touchmove pointermove', this.onTouchScroll(frzCols ? mCont : this.content), this);\n }\n if (frzCols) {\n EventHandler.add(mCont, 'scroll', this.onContentScroll(mHdr), this);\n EventHandler.add(mCont, 'scroll', this.onFreezeContentScroll(fCont), this);\n EventHandler.add(fCont, 'scroll', this.onFreezeContentScroll(mCont), this);\n EventHandler.add(mHdr, 'scroll', this.onContentScroll(mCont), this);\n EventHandler.add(fCont, 'wheel', this.onWheelScroll(mCont), this);\n EventHandler.add(fCont, 'touchstart pointerdown', this.setPageXY(), this);\n EventHandler.add(fCont, 'touchmove pointermove', this.onTouchScroll(mCont), this);\n }\n else {\n EventHandler.add(this.content, 'scroll', this.onContentScroll(this.header), this);\n EventHandler.add(this.header, 'scroll', this.onContentScroll(this.content), this);\n }\n if (this.parent.aggregates.length) {\n EventHandler.add(this.parent.getFooterContent().firstChild, 'scroll', this.onContentScroll(this.content), this);\n }\n this.refresh();\n this.oneTimeReady = false;\n }\n var table = this.parent.getContentTable();\n var sLeft;\n var sHeight;\n var clientHeight;\n getUpdateUsingRaf(function () {\n sLeft = _this.header.scrollLeft;\n sHeight = table.scrollHeight;\n clientHeight = _this.parent.getContent().clientHeight;\n }, function () {\n if (!_this.parent.enableVirtualization) {\n if (sHeight < clientHeight) {\n addClass(table.querySelectorAll('tr:last-child td'), 'e-lastrowcell');\n if (_this.parent.getFrozenColumns()) {\n addClass(_this.parent.getContent().querySelector('.e-movablecontent').querySelectorAll('tr:last-child td'), 'e-lastrowcell');\n }\n }\n if ((_this.parent.frozenRows > 0 || _this.parent.frozenColumns > 0) && _this.header.querySelector('.e-movableheader')) {\n _this.header.querySelector('.e-movableheader').scrollLeft = _this.previousValues.left;\n }\n else {\n _this.header.scrollLeft = _this.previousValues.left;\n }\n _this.content.scrollLeft = _this.previousValues.left;\n _this.content.scrollTop = _this.previousValues.top;\n }\n if (!_this.parent.enableColumnVirtualization) {\n _this.content.scrollLeft = sLeft;\n }\n if (_this.parent.frozenColumns && _this.header.querySelector('.e-movableheader')) {\n _this.header.querySelector('.e-movableheader').scrollLeft =\n _this.content.querySelector('.e-movablecontent').scrollLeft;\n }\n });\n this.parent.isPreventScrollEvent = false;\n };\n /**\n * @hidden\n */\n Scroll.prototype.getCssProperties = function (rtl) {\n var css = {};\n var enableRtl = isNullOrUndefined(rtl) ? this.parent.enableRtl : rtl;\n css.border = enableRtl ? 'borderLeftWidth' : 'borderRightWidth';\n css.padding = enableRtl ? 'paddingLeft' : 'paddingRight';\n return css;\n };\n Scroll.prototype.ensureOverflow = function (content) {\n if (this.parent.getFrozenColumns()) {\n content.querySelector('.e-movablecontent').style.overflowY = this.parent.height === 'auto' ? 'auto' : 'scroll';\n }\n else {\n content.style.overflowY = this.parent.height === 'auto' ? 'auto' : 'scroll';\n }\n };\n Scroll.prototype.onPropertyChanged = function (e) {\n if (e.module !== this.getModuleName()) {\n return;\n }\n this.setPadding();\n this.oneTimeReady = true;\n if (this.parent.height === 'auto') {\n this.removePadding();\n }\n this.wireEvents();\n this.setHeight();\n this.setWidth();\n };\n /**\n * @hidden\n */\n Scroll.prototype.destroy = function () {\n var gridElement = this.parent.element;\n if (!gridElement || (!gridElement.querySelector('.e-gridheader') && !gridElement.querySelector('.e-gridcontent'))) {\n return;\n }\n this.removeEventListener();\n //Remove padding\n this.removePadding();\n removeClass([this.parent.getHeaderContent().firstChild], 'e-headercontent');\n removeClass([this.parent.getContent().firstChild], 'e-content');\n //Remove height\n this.parent.getContent().firstChild.style.height = '';\n //Remove width\n this.parent.element.style.width = '';\n //Remove Dom event\n EventHandler.remove(this.parent.getContent().firstChild, 'scroll', this.onContentScroll);\n };\n /**\n * Function to get the scrollbar width of the browser.\n * @return {number}\n * @hidden\n */\n Scroll.getScrollBarWidth = function () {\n return getScrollBarWidth();\n };\n return Scroll;\n}());\nexport { Scroll };\n","import { print as printWindow, createElement, detach } from '@syncfusion/ej2-base';\nimport { removeElement, getActualProperties, getActualPropFromColl } from '../base/util';\nimport { Grid } from '../base/grid';\nimport * as events from '../base/constant';\n/**\n *\n * The `Print` module is used to handle print action.\n */\nvar Print = /** @class */ (function () {\n /**\n * Constructor for the Grid print module\n * @hidden\n */\n function Print(parent, scrollModule) {\n this.isAsyncPrint = false;\n this.printing = 'isPrinting';\n this.parent = parent;\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.contentReady, this.contentReady.bind(this));\n this.parent.addEventListener(events.actionBegin, this.actionBegin.bind(this));\n this.parent.on(events.onEmpty, this.onEmpty.bind(this));\n this.scrollModule = scrollModule;\n }\n /**\n * By default, prints all the Grid pages and hides the pager.\n * > You can customize print options using the\n * [`printMode`](./api-grid.html#printmode-string).\n * @return {void}\n */\n Print.prototype.print = function () {\n this.renderPrintGrid();\n this.printWind = window.open('', 'print', 'height=' + window.outerHeight + ',width=' + window.outerWidth + ',tabbar=no');\n this.printWind.moveTo(0, 0);\n this.printWind.resizeTo(screen.availWidth, screen.availHeight);\n };\n Print.prototype.onEmpty = function () {\n if (this.isPrintGrid()) {\n this.contentReady();\n }\n };\n Print.prototype.actionBegin = function () {\n if (this.isPrintGrid()) {\n this.isAsyncPrint = true;\n }\n };\n Print.prototype.renderPrintGrid = function () {\n var gObj = this.parent;\n var elem = 'element';\n var printGridModel = {};\n var element = createElement('div', {\n id: this.parent.element.id + '_print', className: gObj.element.className + ' e-print-grid'\n });\n document.body.appendChild(element);\n for (var _i = 0, _a = Print.printGridProp; _i < _a.length; _i++) {\n var key = _a[_i];\n if (key === 'columns') {\n printGridModel[key] = getActualPropFromColl(gObj[key]);\n }\n else if (key === 'allowPaging') {\n printGridModel[key] = this.parent.printMode === 'CurrentPage';\n }\n else {\n printGridModel[key] = getActualProperties(gObj[key]);\n }\n }\n var printGrid = new Grid(printGridModel);\n printGrid.appendTo(element);\n printGrid[this.printing] = true;\n printGrid.trigger = gObj.trigger;\n };\n Print.prototype.contentReady = function () {\n if (this.isPrintGrid()) {\n var gObj = this.parent;\n if (this.isAsyncPrint) {\n this.printGrid();\n return;\n }\n var args = {\n requestType: 'print',\n element: gObj.element,\n selectedRows: gObj.getContentTable().querySelectorAll('tr[aria-selected=\"true\"]'),\n cancel: false\n };\n if (!this.isAsyncPrint) {\n gObj.trigger(events.beforePrint, args);\n }\n if (args.cancel) {\n detach(gObj.element);\n return;\n }\n else if (!this.isAsyncPrint) {\n this.printGrid();\n }\n }\n };\n Print.prototype.printGrid = function () {\n var gObj = this.parent;\n // Pager eleement process based on primt mode\n if (gObj.allowPaging && gObj.printMode === 'CurrentPage') {\n gObj.element.querySelector('.e-gridpager').style.display = 'none';\n }\n // Height adjustment on print grid\n if (gObj.height !== 'auto') {\n var cssProps = this.scrollModule.getCssProperties();\n var contentDiv = gObj.element.querySelector('.e-content');\n var headerDiv = gObj.element.querySelector('.e-gridheader');\n contentDiv.style.height = 'auto';\n contentDiv.style.overflowY = 'auto';\n headerDiv.style[cssProps.padding] = '';\n headerDiv.firstElementChild.style[cssProps.border] = '';\n }\n // Grid alignment adjustment on grouping\n if (gObj.allowGrouping) {\n if (!gObj.groupSettings.columns.length) {\n gObj.element.querySelector('.e-groupdroparea').style.display = 'none';\n }\n else {\n this.removeColGroup(gObj.groupSettings.columns.length, gObj.element);\n removeElement(gObj.element, '.e-grouptopleftcell');\n removeElement(gObj.element, '.e-recordpluscollapse');\n removeElement(gObj.element, '.e-indentcell');\n removeElement(gObj.element, '.e-recordplusexpand');\n }\n }\n // hide horizontal scroll\n gObj.element.querySelector('.e-content').style.overflowX = 'hidden';\n //hide filter bar in print grid\n if (gObj.allowFiltering && gObj.filterSettings.type === 'FilterBar') {\n gObj.element.querySelector('.e-filterbar').style.display = 'none';\n }\n // Hide the waiting popup\n var waitingPop = gObj.element.querySelectorAll('.e-spin-show');\n if (waitingPop.length > 0) {\n waitingPop[0].classList.add('e-spin-hide');\n waitingPop[0].classList.remove('e-spin-show');\n }\n if (gObj[this.printing]) {\n detach(gObj.element);\n }\n gObj.element.classList.remove('e-print-grid');\n this.printWind = printWindow(gObj.element, this.printWind);\n gObj[this.printing] = false;\n var args = {\n element: gObj.element\n };\n gObj.trigger(events.printComplete, args);\n };\n Print.prototype.removeColGroup = function (depth, element) {\n var groupCaption = element.querySelectorAll('.e-groupcaption');\n var colSpan = groupCaption[depth - 1].getAttribute('colspan');\n for (var i = 0; i < groupCaption.length; i++) {\n groupCaption[i].setAttribute('colspan', colSpan);\n }\n var colGroups = element.querySelectorAll('colgroup');\n for (var i = 0; i < colGroups.length; i++) {\n for (var j = 0; j < depth; j++) {\n colGroups[i].childNodes[j].style.display = 'none';\n }\n }\n };\n Print.prototype.isPrintGrid = function () {\n return this.parent.element.id.indexOf('_print') > 0 && this.parent[this.printing];\n };\n /**\n * To destroy the print\n * @return {void}\n * @hidden\n */\n Print.prototype.destroy = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off(events.contentReady, this.contentReady.bind(this));\n this.parent.removeEventListener(events.actionBegin, this.actionBegin.bind(this));\n this.parent.off(events.onEmpty, this.onEmpty.bind(this));\n };\n /**\n * For internal use only - Get the module name.\n * @private\n */\n Print.prototype.getModuleName = function () {\n return 'print';\n };\n Print.printGridProp = [\n 'aggregates', 'allowGrouping', 'allowFiltering', 'allowMultiSorting', 'allowReordering', 'allowSorting',\n 'allowTextWrap', 'childGrid', 'columns', 'currentViewData', 'dataSource', 'detailTemplate', 'enableAltRow',\n 'enableColumnVirtualization', 'filterSettings', 'gridLines',\n 'groupSettings', 'height', 'locale', 'pageSettings', 'printMode', 'query', 'queryString',\n 'rowHeight', 'rowTemplate', 'sortSettings', 'textWrapSettings', 'allowPaging',\n events.beforePrint, events.printComplete\n ];\n return Print;\n}());\nexport { Print };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { compile } from '@syncfusion/ej2-base';\nimport { getEnumValue } from '@syncfusion/ej2-base';\nimport { CellType } from '../base/enum';\nimport { Property, Collection, ChildProperty } from '@syncfusion/ej2-base';\nimport { ValueFormatter } from '../services/value-formatter';\n/**\n * Configures the Grid's aggregate column.\n */\nvar AggregateColumn = /** @class */ (function (_super) {\n __extends(AggregateColumn, _super);\n function AggregateColumn() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.templateFn = {};\n return _this;\n }\n /**\n * @hidden\n */\n AggregateColumn.prototype.setFormatter = function (cultureName) {\n var valueFormatter = new ValueFormatter(cultureName);\n if (this.format && (this.format.skeleton || this.format.format)) {\n this.formatFn = valueFormatter.getFormatFunction(this.format);\n }\n };\n /**\n * @hidden\n */\n AggregateColumn.prototype.getFormatter = function () {\n return this.formatFn;\n };\n /**\n * @hidden\n */\n AggregateColumn.prototype.setTemplate = function (helper) {\n if (helper === void 0) { helper = {}; }\n if (this.footerTemplate !== undefined) {\n this.templateFn[getEnumValue(CellType, CellType.Summary)] = { fn: compile(this.footerTemplate, helper),\n property: 'footerTemplate' };\n }\n if (this.groupFooterTemplate !== undefined) {\n this.templateFn[getEnumValue(CellType, CellType.GroupSummary)] = { fn: compile(this.groupFooterTemplate, helper),\n property: 'groupFooterTemplate' };\n }\n if (this.groupCaptionTemplate !== undefined) {\n this.templateFn[getEnumValue(CellType, CellType.CaptionSummary)] = { fn: compile(this.groupCaptionTemplate, helper),\n property: 'groupCaptionTemplate' };\n }\n };\n /**\n * @hidden\n */\n AggregateColumn.prototype.getTemplate = function (type) {\n return this.templateFn[getEnumValue(CellType, type)];\n };\n /**\n * @hidden\n */\n AggregateColumn.prototype.setPropertiesSilent = function (prop) {\n this.setProperties(prop, true);\n };\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"type\", void 0);\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"field\", void 0);\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"columnName\", void 0);\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"format\", void 0);\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"footerTemplate\", void 0);\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"groupFooterTemplate\", void 0);\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"groupCaptionTemplate\", void 0);\n __decorate([\n Property()\n ], AggregateColumn.prototype, \"customAggregate\", void 0);\n return AggregateColumn;\n}(ChildProperty));\nexport { AggregateColumn };\n/**\n * Configures the aggregate rows.\n */\nvar AggregateRow = /** @class */ (function (_super) {\n __extends(AggregateRow, _super);\n function AggregateRow() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Collection([], AggregateColumn)\n ], AggregateRow.prototype, \"columns\", void 0);\n return AggregateRow;\n}(ChildProperty));\nexport { AggregateRow };\n","import { Browser, remove } from '@syncfusion/ej2-base';\nimport * as events from '../base/constant';\n/**\n * The `Clipboard` module is used to handle clipboard copy action.\n */\nvar Clipboard = /** @class */ (function () {\n /**\n * Constructor for the Grid clipboard module\n * @hidden\n */\n function Clipboard(parent) {\n this.copyContent = '';\n this.isSelect = false;\n this.parent = parent;\n this.addEventListener();\n }\n /**\n * @hidden\n */\n Clipboard.prototype.addEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.contentReady, this.initialEnd, this);\n this.parent.on(events.keyPressed, this.keyDownHandler, this);\n };\n /**\n * @hidden\n */\n Clipboard.prototype.removeEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off(events.keyPressed, this.keyDownHandler);\n };\n Clipboard.prototype.initialEnd = function () {\n this.parent.off(events.contentReady, this.initialEnd);\n this.clipBoardTextArea = this.parent.createElement('textarea', {\n className: 'e-clipboard',\n styles: 'opacity: 0',\n attrs: { readonly: 'true', tabindex: '-1', 'aria-label': 'clipboard' }\n });\n this.parent.element.appendChild(this.clipBoardTextArea);\n };\n Clipboard.prototype.keyDownHandler = function (e) {\n if (e.action === 'ctrlPlusC') {\n this.copy();\n }\n else if (e.action === 'ctrlShiftPlusH') {\n this.copy(true);\n }\n };\n Clipboard.prototype.setCopyData = function (withHeader) {\n if (window.getSelection().toString() === '') {\n var isFrozen = this.parent.getFrozenColumns();\n this.clipBoardTextArea.value = this.copyContent = '';\n var mRows = void 0;\n var rows = this.parent.getRows();\n if (isFrozen) {\n mRows = this.parent.getMovableDataRows();\n }\n if (this.parent.selectionSettings.mode !== 'Cell') {\n var selectedIndexes = this.parent.getSelectedRowIndexes().sort(function (a, b) { return a - b; });\n if (withHeader) {\n var headerTextArray = [];\n for (var i = 0; i < this.parent.getVisibleColumns().length; i++) {\n headerTextArray[i] = this.parent.getVisibleColumns()[i].headerText;\n }\n this.getCopyData(headerTextArray, false, '\\t', withHeader);\n this.copyContent += '\\n';\n }\n for (var i = 0; i < selectedIndexes.length; i++) {\n if (i > 0) {\n this.copyContent += '\\n';\n }\n var cells = [].slice.call(rows[selectedIndexes[i]].querySelectorAll('.e-rowcell'));\n if (isFrozen) {\n cells.push.apply(cells, [].slice.call(mRows[selectedIndexes[i]].querySelectorAll('.e-rowcell')));\n }\n this.getCopyData(cells, false, '\\t', withHeader);\n }\n }\n else {\n var obj = this.checkBoxSelection();\n if (obj.status) {\n if (withHeader) {\n var headers = [];\n for (var i = 0; i < obj.colIndexes.length; i++) {\n headers.push(this.parent.getColumnHeaderByIndex(obj.colIndexes[i]));\n }\n this.getCopyData(headers, false, '\\t', withHeader);\n this.copyContent += '\\n';\n }\n for (var i = 0; i < obj.rowIndexes.length; i++) {\n if (i > 0) {\n this.copyContent += '\\n';\n }\n var cells = [].slice.call(rows[obj.rowIndexes[i]].\n querySelectorAll('.e-cellselectionbackground'));\n if (isFrozen) {\n cells.push.apply(cells, [].slice.call(mRows[obj.rowIndexes[i]].querySelectorAll('.e-cellselectionbackground')));\n }\n this.getCopyData(cells, false, '\\t', withHeader);\n }\n }\n else {\n this.getCopyData([].slice.call(this.parent.element.querySelectorAll('.e-cellselectionbackground')), true, '\\n', withHeader);\n }\n }\n var args = {\n data: this.copyContent,\n cancel: false,\n };\n this.parent.trigger(events.beforeCopy, args);\n if (args.cancel) {\n return;\n }\n this.clipBoardTextArea.value = this.copyContent = args.data;\n if (!Browser.userAgent.match(/ipad|ipod|iphone/i)) {\n this.clipBoardTextArea.select();\n }\n else {\n this.clipBoardTextArea.setSelectionRange(0, this.clipBoardTextArea.value.length);\n }\n this.isSelect = true;\n }\n };\n Clipboard.prototype.getCopyData = function (cells, isCell, splitKey, withHeader) {\n var isElement = typeof cells[0] !== 'string';\n for (var j = 0; j < cells.length; j++) {\n if (withHeader && isCell) {\n this.copyContent += this.parent.getColumns()[parseInt(cells[j].getAttribute('aria-colindex'), 10)].headerText + '\\n';\n }\n if (isElement) {\n if (!cells[j].classList.contains('e-hide')) {\n this.copyContent += cells[j].textContent;\n }\n }\n else {\n this.copyContent += cells[j];\n }\n if (j < cells.length - 1) {\n this.copyContent += splitKey;\n }\n }\n };\n /**\n * Copy selected rows or cells data into clipboard.\n * @param {boolean} withHeader - Specifies whether the column header data need to be copied or not.\n */\n Clipboard.prototype.copy = function (withHeader) {\n if (document.queryCommandSupported('copy')) {\n this.setCopyData(withHeader);\n document.execCommand('copy');\n this.clipBoardTextArea.blur();\n }\n if (this.isSelect) {\n window.getSelection().removeAllRanges();\n this.isSelect = false;\n }\n };\n /**\n * For internal use only - Get the module name.\n * @private\n */\n Clipboard.prototype.getModuleName = function () {\n return 'clipboard';\n };\n /**\n * To destroy the clipboard\n * @return {void}\n * @hidden\n */\n Clipboard.prototype.destroy = function () {\n this.removeEventListener();\n if (this.clipBoardTextArea) {\n remove(this.clipBoardTextArea);\n }\n };\n Clipboard.prototype.checkBoxSelection = function () {\n var gridObj = this.parent;\n var obj = { status: false };\n if (gridObj.selectionSettings.mode === 'Cell') {\n var rowCellIndxes = gridObj.getSelectedRowCellIndexes();\n var str = void 0;\n var isBox = void 0;\n var rowIndexes = [];\n var i = void 0;\n for (i = 0; i < rowCellIndxes.length; i++) {\n if (rowCellIndxes[i].cellIndexes.length) {\n rowIndexes.push(rowCellIndxes[i].rowIndex);\n }\n if (rowCellIndxes[i].cellIndexes.length) {\n if (!str) {\n str = JSON.stringify(rowCellIndxes[i].cellIndexes.sort());\n }\n if (str !== JSON.stringify(rowCellIndxes[i].cellIndexes.sort())) {\n break;\n }\n }\n }\n rowIndexes.sort();\n if (i === rowCellIndxes.length && rowIndexes[rowIndexes.length - 1] - rowIndexes[0] === rowIndexes.length - 1) {\n obj = { status: true, rowIndexes: rowIndexes, colIndexes: rowCellIndxes[0].cellIndexes };\n }\n }\n return obj;\n };\n return Clipboard;\n}());\nexport { Clipboard };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, ChildProperty, Browser, closest, extend } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined, setValue, getValue } from '@syncfusion/ej2-base';\nimport { addClass, removeClass, append, classList } from '@syncfusion/ej2-base';\nimport { Property, Collection, Complex, Event, NotifyPropertyChanges, L10n } from '@syncfusion/ej2-base';\nimport { EventHandler, KeyboardEvents } from '@syncfusion/ej2-base';\nimport { DataUtil } from '@syncfusion/ej2-data';\nimport { createSpinner, hideSpinner, showSpinner, Tooltip } from '@syncfusion/ej2-popups';\nimport { iterateArrayOrObject, prepareColumns, parentsUntil, wrap, templateCompiler, refreshForeignData, getRowHeight } from './util';\nimport * as events from '../base/constant';\nimport { Render } from '../renderer/render';\nimport { RenderType } from './enum';\nimport { RowRenderer } from '../renderer/row-renderer';\nimport { CellRenderer } from '../renderer/cell-renderer';\nimport { CellRendererFactory } from '../services/cell-render-factory';\nimport { ServiceLocator } from '../services/service-locator';\nimport { ValueFormatter } from '../services/value-formatter';\nimport { RendererFactory } from '../services/renderer-factory';\nimport { ColumnWidthService } from '../services/width-controller';\nimport { AriaService } from '../services/aria-service';\nimport { FocusStrategy } from '../services/focus-strategy';\nimport { PageSettings } from '../models/page-settings';\nimport { Selection } from '../actions/selection';\nimport { Search } from '../actions/search';\nimport { ShowHide } from '../actions/show-hide';\nimport { Scroll } from '../actions/scroll';\nimport { Print } from '../actions/print';\nimport { AggregateRow } from '../models/aggregate';\nimport { Clipboard } from '../actions/clipboard';\n/**\n * Represents the field name and direction of sort column.\n */\nvar SortDescriptor = /** @class */ (function (_super) {\n __extends(SortDescriptor, _super);\n function SortDescriptor() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], SortDescriptor.prototype, \"field\", void 0);\n __decorate([\n Property()\n ], SortDescriptor.prototype, \"direction\", void 0);\n return SortDescriptor;\n}(ChildProperty));\nexport { SortDescriptor };\n/**\n * Configures the sorting behavior of Grid.\n */\nvar SortSettings = /** @class */ (function (_super) {\n __extends(SortSettings, _super);\n function SortSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Collection([], SortDescriptor)\n ], SortSettings.prototype, \"columns\", void 0);\n __decorate([\n Property(true)\n ], SortSettings.prototype, \"allowUnsort\", void 0);\n return SortSettings;\n}(ChildProperty));\nexport { SortSettings };\n/**\n * Represents the predicate for the filter column.\n */\nvar Predicate = /** @class */ (function (_super) {\n __extends(Predicate, _super);\n function Predicate() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], Predicate.prototype, \"field\", void 0);\n __decorate([\n Property()\n ], Predicate.prototype, \"operator\", void 0);\n __decorate([\n Property()\n ], Predicate.prototype, \"value\", void 0);\n __decorate([\n Property()\n ], Predicate.prototype, \"matchCase\", void 0);\n __decorate([\n Property()\n ], Predicate.prototype, \"ignoreAccent\", void 0);\n __decorate([\n Property()\n ], Predicate.prototype, \"predicate\", void 0);\n __decorate([\n Property({})\n ], Predicate.prototype, \"actualFilterValue\", void 0);\n __decorate([\n Property({})\n ], Predicate.prototype, \"actualOperator\", void 0);\n __decorate([\n Property()\n ], Predicate.prototype, \"type\", void 0);\n __decorate([\n Property()\n ], Predicate.prototype, \"ejpredicate\", void 0);\n return Predicate;\n}(ChildProperty));\nexport { Predicate };\n/**\n * Configures the filtering behavior of the Grid.\n */\nvar FilterSettings = /** @class */ (function (_super) {\n __extends(FilterSettings, _super);\n function FilterSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Collection([], Predicate)\n ], FilterSettings.prototype, \"columns\", void 0);\n __decorate([\n Property('FilterBar')\n ], FilterSettings.prototype, \"type\", void 0);\n __decorate([\n Property()\n ], FilterSettings.prototype, \"mode\", void 0);\n __decorate([\n Property(true)\n ], FilterSettings.prototype, \"showFilterBarStatus\", void 0);\n __decorate([\n Property(1500)\n ], FilterSettings.prototype, \"immediateModeDelay\", void 0);\n __decorate([\n Property()\n ], FilterSettings.prototype, \"operators\", void 0);\n __decorate([\n Property(false)\n ], FilterSettings.prototype, \"ignoreAccent\", void 0);\n return FilterSettings;\n}(ChildProperty));\nexport { FilterSettings };\n/**\n * Configures the selection behavior of the Grid.\n */\nvar SelectionSettings = /** @class */ (function (_super) {\n __extends(SelectionSettings, _super);\n function SelectionSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Row')\n ], SelectionSettings.prototype, \"mode\", void 0);\n __decorate([\n Property('Flow')\n ], SelectionSettings.prototype, \"cellSelectionMode\", void 0);\n __decorate([\n Property('Single')\n ], SelectionSettings.prototype, \"type\", void 0);\n __decorate([\n Property(false)\n ], SelectionSettings.prototype, \"checkboxOnly\", void 0);\n __decorate([\n Property(false)\n ], SelectionSettings.prototype, \"persistSelection\", void 0);\n return SelectionSettings;\n}(ChildProperty));\nexport { SelectionSettings };\n/**\n * Configures the search behavior of the Grid.\n */\nvar SearchSettings = /** @class */ (function (_super) {\n __extends(SearchSettings, _super);\n function SearchSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property([])\n ], SearchSettings.prototype, \"fields\", void 0);\n __decorate([\n Property('')\n ], SearchSettings.prototype, \"key\", void 0);\n __decorate([\n Property('contains')\n ], SearchSettings.prototype, \"operator\", void 0);\n __decorate([\n Property(true)\n ], SearchSettings.prototype, \"ignoreCase\", void 0);\n __decorate([\n Property(false)\n ], SearchSettings.prototype, \"ignoreAccent\", void 0);\n return SearchSettings;\n}(ChildProperty));\nexport { SearchSettings };\n/**\n * Configures the row drop settings of the Grid.\n */\nvar RowDropSettings = /** @class */ (function (_super) {\n __extends(RowDropSettings, _super);\n function RowDropSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property()\n ], RowDropSettings.prototype, \"targetID\", void 0);\n return RowDropSettings;\n}(ChildProperty));\nexport { RowDropSettings };\n/**\n * Configures the text wrap settings of the Grid.\n */\nvar TextWrapSettings = /** @class */ (function (_super) {\n __extends(TextWrapSettings, _super);\n function TextWrapSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property('Both')\n ], TextWrapSettings.prototype, \"wrapMode\", void 0);\n return TextWrapSettings;\n}(ChildProperty));\nexport { TextWrapSettings };\n/**\n * Configures the group behavior of the Grid.\n */\nvar GroupSettings = /** @class */ (function (_super) {\n __extends(GroupSettings, _super);\n function GroupSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(true)\n ], GroupSettings.prototype, \"showDropArea\", void 0);\n __decorate([\n Property(false)\n ], GroupSettings.prototype, \"showToggleButton\", void 0);\n __decorate([\n Property(false)\n ], GroupSettings.prototype, \"showGroupedColumn\", void 0);\n __decorate([\n Property(true)\n ], GroupSettings.prototype, \"showUngroupButton\", void 0);\n __decorate([\n Property(false)\n ], GroupSettings.prototype, \"disablePageWiseAggregates\", void 0);\n __decorate([\n Property([])\n ], GroupSettings.prototype, \"columns\", void 0);\n __decorate([\n Property()\n ], GroupSettings.prototype, \"captionTemplate\", void 0);\n return GroupSettings;\n}(ChildProperty));\nexport { GroupSettings };\n/**\n * Configures the edit behavior of the Grid.\n */\nvar EditSettings = /** @class */ (function (_super) {\n __extends(EditSettings, _super);\n function EditSettings() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n __decorate([\n Property(false)\n ], EditSettings.prototype, \"allowAdding\", void 0);\n __decorate([\n Property(false)\n ], EditSettings.prototype, \"allowEditing\", void 0);\n __decorate([\n Property(false)\n ], EditSettings.prototype, \"allowDeleting\", void 0);\n __decorate([\n Property('Normal')\n ], EditSettings.prototype, \"mode\", void 0);\n __decorate([\n Property(true)\n ], EditSettings.prototype, \"allowEditOnDblClick\", void 0);\n __decorate([\n Property(true)\n ], EditSettings.prototype, \"showConfirmDialog\", void 0);\n __decorate([\n Property(false)\n ], EditSettings.prototype, \"showDeleteConfirmDialog\", void 0);\n return EditSettings;\n}(ChildProperty));\nexport { EditSettings };\n/**\n * Represents the Grid component.\n * ```html\n *
\n * \n * ```\n */\nvar Grid = /** @class */ (function (_super) {\n __extends(Grid, _super);\n /**\n * Constructor for creating the component\n * @hidden\n */\n function Grid(options, element) {\n var _this = _super.call(this, options, element) || this;\n _this.isPreventScrollEvent = false;\n _this.inViewIndexes = [];\n _this.freezeRefresh = Component.prototype.refresh;\n /**\n * Gets the currently visible records of the Grid.\n */\n _this.currentViewData = [];\n /** @hidden */\n _this.prevPageMoving = false;\n _this.needsID = true;\n setValue('mergePersistData', _this.mergePersistGridData, _this);\n return _this;\n }\n /**\n * Get the properties to be maintained in the persisted state.\n * @return {string}\n * @hidden\n */\n Grid.prototype.getPersistData = function () {\n var _this = this;\n var keyEntity = ['pageSettings', 'sortSettings',\n 'filterSettings', 'groupSettings', 'columns', 'searchSettings', 'selectedRowIndex'];\n var ignoreOnPersist = {\n pageSettings: ['template', 'pageSizes', 'enableQueryString', 'totalRecordsCount', 'pageCount'],\n filterSettings: ['type', 'mode', 'showFilterBarStatus', 'immediateModeDelay', 'ignoreAccent'],\n groupSettings: ['showDropArea', 'showToggleButton', 'showGroupedColumn', 'showUngroupButton',\n 'disablePageWiseAggregates', 'hideCaptionCount'],\n searchSettings: ['fields', 'operator', 'ignoreCase'],\n sortSettings: [], columns: [], selectedRowIndex: []\n };\n var ignoreOnColumn = ['filter', 'edit', 'filterBarTemplate', 'headerTemplate', 'template',\n 'commandTemplate', 'commands', 'dataSource'];\n keyEntity.forEach(function (value) {\n var currentObject = _this[value];\n for (var _i = 0, _a = ignoreOnPersist[value]; _i < _a.length; _i++) {\n var val = _a[_i];\n delete currentObject[val];\n }\n });\n this.ignoreInArrays(ignoreOnColumn, this.columns);\n return this.addOnPersist(keyEntity);\n };\n Grid.prototype.ignoreInArrays = function (ignoreOnColumn, columns) {\n var _this = this;\n columns.forEach(function (column) {\n if (column.columns) {\n _this.ignoreInColumn(ignoreOnColumn, column);\n _this.ignoreInArrays(ignoreOnColumn, column.columns);\n }\n else {\n _this.ignoreInColumn(ignoreOnColumn, column);\n }\n });\n };\n Grid.prototype.ignoreInColumn = function (ignoreOnColumn, column) {\n ignoreOnColumn.forEach(function (val) {\n delete column[val];\n column.filter = {};\n });\n };\n /**\n * To provide the array of modules needed for component rendering\n * @return {ModuleDeclaration[]}\n * @hidden\n */\n Grid.prototype.requiredModules = function () {\n var modules = [];\n if (this.isDestroyed) {\n return modules;\n }\n if (this.allowFiltering) {\n modules.push({\n member: 'filter',\n args: [this, this.filterSettings, this.serviceLocator]\n });\n }\n if (this.allowExcelExport) {\n modules.push({\n member: 'ExcelExport',\n args: [this]\n });\n }\n if (this.allowPdfExport) {\n modules.push({\n member: 'PdfExport',\n args: [this]\n });\n }\n if (this.allowSorting) {\n modules.push({\n member: 'sort',\n args: [this, this.sortSettings, this.sortedColumns, this.serviceLocator]\n });\n }\n if (this.allowPaging) {\n modules.push({\n member: 'pager',\n args: [this, this.pageSettings]\n });\n }\n if (this.allowSelection) {\n modules.push({\n member: 'selection',\n args: [this, this.selectionSettings, this.serviceLocator]\n });\n }\n modules.push({\n member: 'resize',\n args: [this]\n });\n if (this.allowReordering) {\n modules.push({\n member: 'reorder',\n args: [this]\n });\n }\n if (this.allowRowDragAndDrop) {\n modules.push({\n member: 'rowDragAndDrop',\n args: [this]\n });\n }\n if (this.allowGrouping) {\n modules.push({\n member: 'group',\n args: [this, this.groupSettings, this.sortedColumns, this.serviceLocator]\n });\n }\n if (this.aggregates.length) {\n modules.push({ member: 'aggregate', args: [this, this.serviceLocator] });\n }\n if (this.isDetail()) {\n modules.push({\n member: 'detailRow',\n args: [this, this.serviceLocator]\n });\n }\n if (this.toolbar || this.toolbarTemplate) {\n modules.push({\n member: 'toolbar',\n args: [this, this.serviceLocator]\n });\n }\n if (this.enableVirtualization || this.enableColumnVirtualization) {\n modules.push({\n member: 'virtualscroll',\n args: [this, this.serviceLocator]\n });\n }\n if (this.getFrozenColumns() || this.frozenRows) {\n modules.push({ member: 'freeze', args: [this, this.serviceLocator] });\n }\n if (this.isCommandColumn(this.columns)) {\n modules.push({\n member: 'commandColumn',\n args: [this, this.serviceLocator]\n });\n }\n if (this.editSettings.allowAdding || this.editSettings.allowDeleting || this.editSettings.allowEditing) {\n modules.push({\n member: 'edit',\n args: [this, this.serviceLocator]\n });\n }\n this.extendRequiredModules(modules);\n return modules;\n };\n Grid.prototype.extendRequiredModules = function (modules) {\n if (this.contextMenuItems) {\n modules.push({\n member: 'contextMenu',\n args: [this, this.serviceLocator]\n });\n }\n if (this.showColumnMenu) {\n modules.push({\n member: 'columnMenu',\n args: [this, this.serviceLocator]\n });\n }\n if (this.showColumnChooser) {\n modules.push({\n member: 'columnChooser',\n args: [this, this.serviceLocator]\n });\n }\n if (this.isForeignKeyEnabled(this.columns)) {\n modules.push({ member: 'foreignKey', args: [this, this.serviceLocator] });\n }\n };\n /**\n * For internal use only - Initialize the event handler;\n * @private\n */\n Grid.prototype.preRender = function () {\n this.serviceLocator = new ServiceLocator;\n this.initProperties();\n this.initializeServices();\n };\n Grid.prototype.initProperties = function () {\n /* tslint:disable */\n this.isInitial = true;\n this.sortedColumns = [];\n this.inViewIndexes = [];\n this.mediaCol = [];\n this.isInitialLoad = false;\n this.mergeCells = {};\n this.isEdit = false;\n this.checkAllRows = 'None';\n this.isCheckBoxSelection = false;\n this.isPersistSelection = false;\n this.freezeRefresh = Component.prototype.refresh;\n this.filterOperators = {\n contains: 'contains', endsWith: 'endswith', equal: 'equal', greaterThan: 'greaterthan', greaterThanOrEqual: 'greaterthanorequal',\n lessThan: 'lessthan', lessThanOrEqual: 'lessthanorequal', notEqual: 'notequal', startsWith: 'startswith'\n };\n this.defaultLocale = {\n EmptyRecord: 'No records to display',\n True: 'true',\n False: 'false',\n InvalidFilterMessage: 'Invalid Filter Data',\n GroupDropArea: 'Drag a column header here to group its column',\n UnGroup: 'Click here to ungroup',\n GroupDisable: 'Grouping is disabled for this column',\n FilterbarTitle: '\\'s filter bar cell',\n EmptyDataSourceError: 'DataSource must not be empty at initial load since columns are generated from dataSource in AutoGenerate Column Grid',\n // Toolbar Items\n Add: 'Add',\n Edit: 'Edit',\n Cancel: 'Cancel',\n Update: 'Update',\n Delete: 'Delete',\n Print: 'Print',\n Pdfexport: 'PDF Export',\n Excelexport: 'Excel Export',\n Wordexport: 'Word Export',\n Csvexport: 'CSV Export',\n Search: 'Search',\n Columnchooser: 'Columns',\n Save: 'Save',\n Item: 'item',\n Items: 'items',\n EditOperationAlert: 'No records selected for edit operation',\n DeleteOperationAlert: 'No records selected for delete operation',\n SaveButton: 'Save',\n OKButton: 'OK',\n CancelButton: 'Cancel',\n EditFormTitle: 'Details of ',\n AddFormTitle: 'Add New Record',\n BatchSaveConfirm: 'Are you sure you want to save changes?',\n BatchSaveLostChanges: 'Unsaved changes will be lost. Are you sure you want to continue?',\n ConfirmDelete: 'Are you sure you want to Delete Record?',\n CancelEdit: 'Are you sure you want to Cancel the changes?',\n ChooseColumns: 'Choose Column',\n SearchColumns: 'search columns',\n Matchs: 'No Matches Found',\n FilterButton: 'Filter',\n ClearButton: 'Clear',\n StartsWith: 'Starts With',\n EndsWith: 'Ends With',\n Contains: 'Contains',\n Equal: 'Equal',\n NotEqual: 'Not Equal',\n LessThan: 'Less Than',\n LessThanOrEqual: 'Less Than Or Equal',\n GreaterThan: 'Greater Than',\n GreaterThanOrEqual: 'Greater Than Or Equal',\n ChooseDate: 'Choose a Date',\n EnterValue: 'Enter the value',\n Copy: 'Copy',\n Group: 'Group by this column',\n Ungroup: 'Ungroup by this column',\n autoFitAll: 'Auto Fit all columns',\n autoFit: 'Auto Fit this column',\n Export: 'Export',\n FirstPage: 'First Page',\n LastPage: 'Last Page',\n PreviousPage: 'Previous Page',\n NextPage: 'Next Page',\n SortAscending: 'Sort Ascending',\n SortDescending: 'Sort Descending',\n EditRecord: 'Edit Record',\n DeleteRecord: 'Delete Record',\n FilterMenu: 'Filter',\n SelectAll: 'Select All',\n Blanks: 'Blanks',\n FilterTrue: 'True',\n FilterFalse: 'False',\n NoResult: 'No Matches Found',\n ClearFilter: 'Clear Filter',\n NumberFilter: 'Number Filters',\n TextFilter: 'Text Filters',\n DateFilter: 'Date Filters',\n MatchCase: 'Match Case',\n Between: 'Between',\n CustomFilter: 'Custom Filter',\n CustomFilterPlaceHolder: 'Enter the value',\n CustomFilterDatePlaceHolder: 'Choose a date',\n AND: 'AND',\n OR: 'OR',\n ShowRowsWhere: 'Show rows where:'\n };\n this.keyConfigs = {\n downArrow: 'downarrow',\n upArrow: 'uparrow',\n rightArrow: 'rightarrow',\n leftArrow: 'leftarrow',\n shiftDown: 'shift+downarrow',\n shiftUp: 'shift+uparrow',\n shiftRight: 'shift+rightarrow',\n shiftLeft: 'shift+leftarrow',\n home: 'home',\n end: 'end',\n escape: 'escape',\n ctrlHome: 'ctrl+home',\n ctrlEnd: 'ctrl+end',\n pageUp: 'pageup',\n pageDown: 'pagedown',\n ctrlAltPageUp: 'ctrl+alt+pageup',\n ctrlAltPageDown: 'ctrl+alt+pagedown',\n altPageUp: 'alt+pageup',\n altPageDown: 'alt+pagedown',\n altDownArrow: 'alt+downarrow',\n altUpArrow: 'alt+uparrow',\n ctrlDownArrow: 'ctrl+downarrow',\n ctrlUpArrow: 'ctrl+uparrow',\n ctrlPlusA: 'ctrl+A',\n ctrlPlusP: 'ctrl+P',\n insert: 'insert',\n delete: 'delete',\n f2: 'f2',\n enter: 'enter',\n ctrlEnter: 'ctrl+enter',\n shiftEnter: 'shift+enter',\n tab: 'tab',\n shiftTab: 'shift+tab',\n space: 'space',\n ctrlPlusC: 'ctrl+C',\n ctrlShiftPlusH: 'ctrl+shift+H'\n };\n /* tslint:enable */\n };\n /**\n * For internal use only - To Initialize the component rendering.\n * @private\n */\n Grid.prototype.render = function () {\n this.ariaService.setOptions(this.element, { role: 'grid' });\n createSpinner({ target: this.element }, this.createElement);\n this.renderModule = new Render(this, this.serviceLocator);\n this.getMediaColumns();\n this.searchModule = new Search(this);\n this.scrollModule = new Scroll(this);\n this.notify(events.initialLoad, {});\n this.trigger(events.load);\n prepareColumns(this.columns, this.enableColumnVirtualization);\n this.getColumns();\n this.processModel();\n this.gridRender();\n this.wireEvents();\n this.addListener();\n this.updateDefaultCursor();\n this.updateStackedFilter();\n this.showSpinner();\n this.notify(events.initialEnd, {});\n };\n /**\n * By default, grid shows the spinner for all its actions. You can use this method to show spinner at your needed time.\n */\n Grid.prototype.showSpinner = function () {\n showSpinner(this.element);\n };\n /**\n * Manually showed spinner needs to hide by `hideSpinnner`.\n */\n Grid.prototype.hideSpinner = function () {\n hideSpinner(this.element);\n };\n Grid.prototype.updateStackedFilter = function () {\n if (this.allowFiltering && this.filterSettings.type === 'FilterBar' &&\n this.getHeaderContent().querySelectorAll('.e-stackedheadercell').length) {\n this.getHeaderContent().classList.add('e-stackedfilter');\n }\n else {\n this.getHeaderContent().classList.remove('e-stackedfilter');\n }\n };\n Grid.prototype.getMediaColumns = function () {\n if (!this.enableColumnVirtualization) {\n var gcol = this.getColumns();\n this.getShowHideService = this.serviceLocator.getService('showHideService');\n if (!isNullOrUndefined(gcol)) {\n for (var index = 0; index < gcol.length; index++) {\n if (!isNullOrUndefined(gcol[index].hideAtMedia)) {\n this.mediaCol.push(gcol[index]);\n var media = window.matchMedia(gcol[index].hideAtMedia);\n this.mediaQueryUpdate(index, media);\n media.addListener(this.mediaQueryUpdate.bind(this, index));\n }\n }\n }\n }\n };\n /**\n * @hidden\n */\n Grid.prototype.mediaQueryUpdate = function (columnIndex, e) {\n var col = this.getColumns()[columnIndex];\n col.visible = e.matches;\n if (this.isInitialLoad) {\n if (col.visible) {\n this.showHider.show(col.headerText, 'headerText');\n }\n else {\n this.showHider.hide(col.headerText, 'headerText');\n }\n }\n };\n Grid.prototype.refreshMediaCol = function () {\n this.isInitialLoad = true;\n if (this.aggregates.length && this.element.scrollHeight > this.height) {\n var footerContent = this.element.querySelector('.e-gridfooter');\n addClass([footerContent], ['e-footerpadding']);\n }\n };\n /**\n * For internal use only - Initialize the event handler\n * @private\n */\n Grid.prototype.eventInitializer = function () {\n //eventInitializer\n };\n /**\n * Destroys the component (detaches/removes all event handlers, attributes, classes, and empties the component element).\n * @method destroy\n * @return {void}\n */\n Grid.prototype.destroy = function () {\n var gridElement = this.element;\n if (!gridElement) {\n return;\n }\n var hasGridChild = gridElement.querySelector('.e-gridheader') &&\n gridElement.querySelector('.e-gridcontent') ? true : false;\n if (hasGridChild) {\n this.unwireEvents();\n }\n this.removeListener();\n this.notify(events.destroy, {});\n this.destroyDependentModules();\n if (hasGridChild) {\n _super.prototype.destroy.call(this);\n }\n this.toolTipObj.destroy();\n var modules = ['renderModule', 'headerModule', 'contentModule', 'valueFormatterService',\n 'serviceLocator', 'ariaService', 'keyboardModule', 'widthService', 'searchModule', 'showHider',\n 'scrollModule', 'printModule', 'clipboardModule', 'focusModule'];\n for (var i = 0; i < modules.length; i++) {\n if (this[modules[i]]) {\n this[modules[i]] = null;\n }\n }\n this.element.innerHTML = '';\n classList(this.element, [], ['e-rtl', 'e-gridhover', 'e-responsive', 'e-default', 'e-device', 'e-grid-min-height']);\n };\n Grid.prototype.destroyDependentModules = function () {\n var gridElement = this.element;\n if (!gridElement || (!gridElement.querySelector('.e-gridheader') && !gridElement.querySelector('.e-gridcontent'))) {\n return;\n }\n this.scrollModule.destroy();\n this.keyboardModule.destroy();\n this.focusModule.destroy();\n };\n /**\n * For internal use only - Get the module name.\n * @private\n */\n Grid.prototype.getModuleName = function () {\n return 'grid';\n };\n /**\n * Called internally if any of the property value changed.\n * @hidden\n */\n /* tslint:disable-next-line:max-line-length */\n Grid.prototype.onPropertyChanged = function (newProp, oldProp) {\n var requireRefresh = false;\n var requireGridRefresh = false;\n var checkCursor;\n var args = { requestType: 'refresh' };\n if (this.isDestroyed) {\n return;\n }\n var properties = Object.keys(newProp);\n if (properties.indexOf('columns') > -1) {\n this.updateColumnObject();\n requireGridRefresh = true;\n }\n for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {\n var prop = properties_1[_i];\n switch (prop) {\n case 'allowPaging':\n this.notify(events.uiUpdate, { module: 'pager', enable: this.allowPaging });\n requireRefresh = true;\n break;\n case 'pageSettings':\n this.notify(events.inBoundModelChanged, { module: 'pager', properties: newProp.pageSettings });\n if (isNullOrUndefined(newProp.pageSettings.currentPage) && isNullOrUndefined(newProp.pageSettings.totalRecordsCount)\n || !isNullOrUndefined(oldProp.pageSettings) &&\n ((newProp.pageSettings.currentPage !== oldProp.pageSettings.currentPage)\n && !this.enableColumnVirtualization && !this.enableVirtualization\n && this.pageSettings.totalRecordsCount <= this.pageSettings.pageSize)) {\n requireRefresh = true;\n }\n break;\n case 'currencyCode':\n case 'locale':\n _super.prototype.refresh.call(this);\n break;\n case 'allowSorting':\n this.notify(events.uiUpdate, { module: 'sort', enable: this.allowSorting });\n requireRefresh = true;\n checkCursor = true;\n break;\n case 'allowFiltering':\n this.updateStackedFilter();\n this.notify(events.uiUpdate, { module: 'filter', enable: this.allowFiltering });\n requireRefresh = true;\n if (this.filterSettings.type !== 'FilterBar') {\n this.refreshHeader();\n }\n break;\n case 'height':\n case 'width':\n this.notify(events.uiUpdate, { module: 'scroll', properties: { width: newProp.width, height: newProp.height } });\n break;\n case 'allowReordering':\n this.headerModule.refreshUI();\n checkCursor = true;\n break;\n case 'allowRowDragAndDrop':\n this.notify(events.uiUpdate, { module: 'rowDragAndDrop', enable: this.allowRowDragAndDrop });\n break;\n case 'allowSelection':\n this.notify(events.uiUpdate, { module: 'selection', enable: this.allowSelection });\n break;\n case 'rowTemplate':\n this.rowTemplateFn = templateCompiler(this.rowTemplate);\n requireRefresh = true;\n break;\n case 'detailTemplate':\n this.detailTemplateFn = templateCompiler(this.detailTemplate);\n requireRefresh = true;\n break;\n case 'allowGrouping':\n this.notify(events.uiUpdate, { module: 'group', enable: this.allowGrouping });\n this.headerModule.refreshUI();\n requireRefresh = true;\n checkCursor = true;\n break;\n case 'childGrid':\n requireRefresh = true;\n break;\n case 'toolbar':\n this.notify(events.uiUpdate, { module: 'toolbar' });\n break;\n case 'groupSettings':\n if (!(isNullOrUndefined(newProp.groupSettings.showDropArea))) {\n this.headerModule.refreshUI();\n requireRefresh = true;\n checkCursor = true;\n }\n this.notify(events.inBoundModelChanged, {\n module: 'group', properties: newProp.groupSettings,\n oldProperties: oldProp.groupSettings\n });\n break;\n case 'aggregates':\n if (!this.aggregates.length && this.allowGrouping && this.groupSettings.columns.length) {\n requireRefresh = true;\n }\n this.notify(events.uiUpdate, { module: 'aggregate', properties: newProp });\n break;\n case 'frozenColumns':\n case 'frozenRows':\n this.freezeRefresh();\n break;\n case 'enableVirtualization':\n _super.prototype.refresh.call(this);\n break;\n default:\n this.extendedPropertyChange(prop, newProp);\n }\n }\n if (checkCursor) {\n this.updateDefaultCursor();\n }\n if (requireGridRefresh) {\n this.refresh();\n if (this.frozenColumns || this.frozenRows) {\n this.freezeRefresh();\n }\n }\n else if (requireRefresh) {\n this.notify(events.modelChanged, args);\n requireRefresh = false;\n }\n };\n /* tslint:disable-next-line:max-line-length */\n Grid.prototype.extendedPropertyChange = function (prop, newProp) {\n switch (prop) {\n case 'enableRtl':\n this.updateRTL();\n if (this.allowPaging) {\n this.element.querySelector('.e-gridpager').ej2_instances[0].enableRtl = newProp.enableRtl;\n this.element.querySelector('.e-gridpager').ej2_instances[0].dataBind();\n }\n if (this.height !== 'auto') {\n this.scrollModule.removePadding(!newProp.enableRtl);\n this.scrollModule.setPadding();\n }\n if (this.toolbar) {\n this.toolbarModule.getToolbar().ej2_instances[0].enableRtl = newProp.enableRtl;\n this.toolbarModule.getToolbar().ej2_instances[0].dataBind();\n }\n if (this.contextMenuItems) {\n this.contextMenuModule.getContextMenu().ej2_instances[0].enableRtl = newProp.enableRtl;\n this.contextMenuModule.getContextMenu().ej2_instances[0].dataBind();\n }\n if (this.showColumnMenu) {\n this.columnMenuModule.getColumnMenu().ej2_instances[0].enableRtl = newProp.enableRtl;\n this.columnMenuModule.getColumnMenu().ej2_instances[0].dataBind();\n }\n this.notify(events.rtlUpdated, {});\n break;\n case 'enableAltRow':\n this.renderModule.refresh();\n break;\n case 'allowResizing':\n this.headerModule.refreshUI();\n this.updateResizeLines();\n break;\n case 'rowHeight':\n if (this.rowHeight) {\n addClass([this.element], 'e-grid-min-height');\n }\n else {\n removeClass([this.element], 'e-grid-min-height');\n }\n this.renderModule.refresh();\n this.headerModule.refreshUI();\n break;\n case 'gridLines':\n this.updateGridLines();\n break;\n case 'showColumnMenu':\n this.headerModule.refreshUI();\n this.notify(events.uiUpdate, { module: 'columnMenu', enable: true });\n break;\n case 'columnMenuItems':\n this.notify(events.uiUpdate, { module: 'columnMenu', enable: this.columnMenuItems });\n break;\n case 'contextMenuItems':\n this.notify(events.uiUpdate, { module: 'contextMenu', enable: this.contextMenuItems });\n break;\n case 'showColumnChooser':\n this.notify(events.uiUpdate, { module: 'columnChooser', enable: this.showColumnChooser });\n break;\n case 'filterSettings':\n this.updateStackedFilter();\n this.notify(events.inBoundModelChanged, { module: 'filter', properties: newProp.filterSettings });\n break;\n case 'searchSettings':\n this.notify(events.inBoundModelChanged, { module: 'search', properties: newProp.searchSettings });\n break;\n case 'sortSettings':\n this.notify(events.inBoundModelChanged, { module: 'sort' });\n break;\n case 'selectionSettings':\n this.notify(events.inBoundModelChanged, { module: 'selection', properties: newProp.selectionSettings });\n break;\n case 'editSettings':\n this.notify(events.inBoundModelChanged, { module: 'edit', properties: newProp.editSettings });\n break;\n case 'allowTextWrap':\n case 'textWrapSettings':\n if (this.allowTextWrap) {\n this.applyTextWrap();\n }\n else {\n this.removeTextWrap();\n }\n this.notify(events.freezeRender, { case: 'textwrap', isModeChg: (prop === 'textWrapSettings') });\n break;\n case 'dataSource':\n var pending_1 = this.getDataModule().getState();\n if (pending_1.isPending) {\n var gResult_1 = !isNullOrUndefined(this.dataSource) ? this.dataSource.result : [];\n (pending_1.group || []).forEach(function (name) {\n gResult_1 = DataUtil.group(gResult_1, name, pending_1.aggregates || []);\n });\n this.dataSource = {\n result: gResult_1, count: this.dataSource.count,\n aggregates: this.dataSource.aggregates\n };\n pending_1.resolver(this.dataSource);\n }\n else {\n this.getDataModule().setState({ isDataChanged: false });\n this.notify(events.dataSourceModified, {});\n this.renderModule.refresh();\n }\n break;\n case 'enableHover':\n var action = newProp.enableHover ? addClass : removeClass;\n action([this.element], 'e-gridhover');\n break;\n }\n };\n /**\n * @private\n */\n Grid.prototype.setProperties = function (prop, muteOnChange) {\n _super.prototype.setProperties.call(this, prop, muteOnChange);\n if (this.filterModule && muteOnChange) {\n this.filterModule.refreshFilter();\n }\n };\n /**\n * @hidden\n */\n Grid.prototype.updateDefaultCursor = function () {\n var headerRows = [].slice.call(this.element.querySelectorAll('.e-columnheader'));\n for (var _i = 0, headerRows_1 = headerRows; _i < headerRows_1.length; _i++) {\n var row = headerRows_1[_i];\n if (this.allowSorting || (this.allowGrouping && this.groupSettings.showDropArea) || this.allowReordering) {\n row.classList.remove('e-defaultcursor');\n }\n else {\n row.classList.add('e-defaultcursor');\n }\n }\n };\n Grid.prototype.updateColumnModel = function (columns) {\n for (var i = 0, len = columns.length; i < len; i++) {\n if (columns[i].columns) {\n this.updateColumnModel(columns[i].columns);\n }\n else {\n this.columnModel.push(columns[i]);\n }\n }\n this.updateFrozenColumns();\n };\n Grid.prototype.updateFrozenColumns = function () {\n var cols = this.columnModel;\n var count = 0;\n for (var i = 0, len = cols.length; i < len; i++) {\n if (cols[i].isFrozen) {\n cols.splice(this.frozenColumns + count, 0, cols.splice(i, 1)[0]);\n count++;\n }\n }\n };\n /**\n * Gets the columns from the Grid.\n * @return {Column[]}\n */\n Grid.prototype.getColumns = function (isRefresh) {\n var _this = this;\n var inview = this.inViewIndexes.map(function (v) { return v - _this.groupSettings.columns.length; }).filter(function (v) { return v > -1; });\n var vLen = inview.length;\n if (!this.enableColumnVirtualization || isNullOrUndefined(this.columnModel) || this.columnModel.length === 0 || isRefresh) {\n this.columnModel = [];\n this.updateColumnModel(this.columns);\n }\n var columns = vLen === 0 ? this.columnModel :\n this.columnModel.slice(inview[0], inview[vLen - 1] + 1);\n return columns;\n };\n /**\n * @private\n */\n Grid.prototype.getStackedHeaderColumnByHeaderText = function (stackedHeader, col) {\n for (var i = 0; i < col.length; i++) {\n var individualColumn = col[i];\n if (individualColumn.field === stackedHeader || individualColumn.headerText === stackedHeader) {\n this.stackedColumn = individualColumn;\n break;\n }\n else if (individualColumn.columns) {\n this.getStackedHeaderColumnByHeaderText(stackedHeader, individualColumn.columns);\n }\n }\n return this.stackedColumn;\n };\n /**\n * @private\n */\n Grid.prototype.getColumnIndexesInView = function () {\n return this.inViewIndexes;\n };\n /**\n * @private\n */\n Grid.prototype.getLocaleConstants = function () {\n return this.defaultLocale;\n };\n /**\n * @private\n */\n Grid.prototype.setColumnIndexesInView = function (indexes) {\n this.inViewIndexes = indexes;\n };\n /**\n * Gets the visible columns from the Grid.\n * @return {Column[]}\n */\n Grid.prototype.getVisibleColumns = function () {\n var cols = [];\n for (var _i = 0, _a = this.columnModel; _i < _a.length; _i++) {\n var col = _a[_i];\n if (col.visible) {\n cols.push(col);\n }\n }\n return cols;\n };\n /**\n * Gets the header div of the Grid.\n * @return {Element}\n */\n Grid.prototype.getHeaderContent = function () {\n return this.headerModule.getPanel();\n };\n /**\n * Sets the header div of the Grid to replace the old header.\n * @param {Element} element - Specifies the Grid header.\n * @return {void}\n */\n Grid.prototype.setGridHeaderContent = function (element) {\n this.headerModule.setPanel(element);\n };\n /**\n * Gets the content table of the Grid.\n * @return {Element}\n */\n Grid.prototype.getContentTable = function () {\n return this.contentModule.getTable();\n };\n /**\n * Sets the content table of the Grid to replace the old content table.\n * @param {Element} element - Specifies the Grid content table.\n * @return {void}\n */\n Grid.prototype.setGridContentTable = function (element) {\n this.contentModule.setTable(element);\n };\n /**\n * Gets the content div of the Grid.\n * @return {Element}\n */\n Grid.prototype.getContent = function () {\n return this.contentModule.getPanel();\n };\n /**\n * Sets the content div of the Grid to replace the old Grid content.\n * @param {Element} element - Specifies the Grid content.\n * @return {void}\n */\n Grid.prototype.setGridContent = function (element) {\n this.contentModule.setPanel(element);\n };\n /**\n * Gets the header table element of the Grid.\n * @return {Element}\n */\n Grid.prototype.getHeaderTable = function () {\n return this.headerModule.getTable();\n };\n /**\n * Sets the header table of the Grid to replace the old one.\n * @param {Element} element - Specifies the Grid header table.\n * @return {void}\n */\n Grid.prototype.setGridHeaderTable = function (element) {\n this.headerModule.setTable(element);\n };\n /**\n * Gets the footer div of the Grid.\n * @return {Element}\n */\n Grid.prototype.getFooterContent = function () {\n if (isNullOrUndefined(this.footerElement)) {\n this.footerElement = this.element.getElementsByClassName('e-gridfooter')[0];\n }\n return this.footerElement;\n };\n /**\n * Gets the footer table element of the Grid.\n * @return {Element}\n */\n Grid.prototype.getFooterContentTable = function () {\n if (isNullOrUndefined(this.footerElement)) {\n this.footerElement = this.element.getElementsByClassName('e-gridfooter')[0];\n }\n return this.footerElement.firstChild.firstChild;\n };\n /**\n * Gets the pager of the Grid.\n * @return {Element}\n */\n Grid.prototype.getPager = function () {\n return this.gridPager; //get element from pager\n };\n /**\n * Sets the pager of the Grid to replace the old pager.\n * @param {Element} element - Specifies the Grid pager.\n * @return {void}\n */\n Grid.prototype.setGridPager = function (element) {\n this.gridPager = element;\n };\n /**\n * Gets a row by index.\n * @param {number} index - Specifies the row index.\n * @return {Element}\n */\n Grid.prototype.getRowByIndex = function (index) {\n return this.contentModule.getRowByIndex(index);\n };\n /**\n * Gets a movable tables row by index.\n * @param {number} index - Specifies the row index.\n * @return {Element}\n */\n Grid.prototype.getMovableRowByIndex = function (index) {\n return this.contentModule.getMovableRowByIndex(index);\n };\n /**\n * Gets all the data rows of the Grid.\n * @return {Element[]}\n */\n Grid.prototype.getRows = function () {\n return this.contentModule.getRowElements();\n };\n /**\n * Get a row information based on cell\n * @param {Element}\n * @return RowInfo\n */\n Grid.prototype.getRowInfo = function (target) {\n var ele = target;\n var args = { target: target };\n if (!isNullOrUndefined(target) && isNullOrUndefined(parentsUntil(ele, 'e-detailrowcollapse')\n && isNullOrUndefined(parentsUntil(ele, 'e-recordplusexpand'))) && !this.isEdit) {\n var cell = closest(ele, '.e-rowcell');\n if (!cell) {\n return args;\n }\n var cellIndex = parseInt(cell.getAttribute('aria-colindex'), 10);\n if (!isNullOrUndefined(cell) && !isNaN(cellIndex)) {\n var row_1 = closest(cell, '.e-row');\n var rowIndex = parseInt(row_1.getAttribute('aria-rowindex'), 10);\n var frzCols = this.getFrozenColumns();\n var isMovable = frzCols ? cellIndex >= frzCols : false;\n var rows = (isMovable ?\n this.contentModule.getMovableRows() : this.contentModule.getRows());\n var rowsObject = rows.filter(function (r) { return r.uid === row_1.getAttribute('data-uid'); });\n var rowData = rowsObject[0].data;\n var column = rowsObject[0].cells[isMovable ? cellIndex - frzCols : cellIndex].column;\n args = { cell: cell, cellIndex: cellIndex, row: row_1, rowIndex: rowIndex, rowData: rowData, column: column, target: target };\n }\n }\n return args;\n };\n /**\n * Gets the Grid's movable content rows from frozen grid.\n * @return {Element[]}\n */\n Grid.prototype.getMovableRows = function () {\n return this.contentModule.getMovableRowElements();\n };\n /**\n * Gets all the Grid's data rows.\n * @return {Element[]}\n */\n Grid.prototype.getDataRows = function () {\n var rows = [].slice.call(this.getContentTable().querySelector('tbody').children);\n if (this.frozenRows) {\n var freezeRows = [].slice.call(this.getHeaderTable().querySelector('tbody').children);\n rows = this.addMovableRows(freezeRows, rows);\n }\n var dataRows = this.generateDataRows(rows);\n return dataRows;\n };\n /**\n * @hidden\n */\n Grid.prototype.addMovableRows = function (fRows, mrows) {\n for (var i = 0, len = mrows.length; i < len; i++) {\n fRows.push(mrows[i]);\n }\n return fRows;\n };\n Grid.prototype.generateDataRows = function (rows) {\n var dRows = [];\n for (var i = 0, len = rows.length; i < len; i++) {\n if (rows[i].classList.contains('e-row') && !rows[i].classList.contains('e-hiddenrow')) {\n dRows.push(rows[i]);\n }\n }\n return dRows;\n };\n /**\n * Gets all the Grid's movable table data rows.\n * @return {Element[]}\n */\n Grid.prototype.getMovableDataRows = function () {\n var rows = [].slice.call(this.getContent().querySelector('.e-movablecontent').querySelector('tbody').children);\n if (this.frozenRows) {\n var freezeRows = [].slice.call(this.getHeaderContent().querySelector('.e-movableheader').querySelector('tbody').children);\n rows = this.addMovableRows(freezeRows, rows);\n }\n var dataRows = this.generateDataRows(rows);\n return dataRows;\n };\n /**\n * Updates particular cell value based on the given primary key value.\n * > Primary key column must be specified using `columns.isPrimaryKey` property.\n * @param {string| number} key - Specifies the PrimaryKey value of dataSource.\n * @param {string } field - Specifies the field name which you want to update.\n * @param {string | number | boolean | Date} value - To update new value for the particular cell.\n */\n Grid.prototype.setCellValue = function (key, field, value) {\n var cells = 'cells';\n var rowData = 'data';\n var rowIdx = 'index';\n var rowuID = 'uid';\n var fieldIdx;\n var col;\n var tr;\n var mTr;\n var pkName = this.getPrimaryKeyFieldNames()[0];\n var cell = new CellRenderer(this, this.serviceLocator);\n var selectedRow = {};\n var movableSelectedRow = {};\n var rowObjects = this.contentModule.getRows();\n var movableRowObjects = this.contentModule.getMovableRows();\n fieldIdx = this.getColumnIndexByField(field);\n col = this.getColumnByField(field);\n selectedRow = rowObjects.filter(function (r) {\n return getValue(pkName, r.data) === key;\n })[0];\n movableSelectedRow = movableRowObjects.filter(function (r) {\n return getValue(pkName, r.data) === key;\n })[0];\n tr = !isNullOrUndefined(selectedRow) ? this.element.querySelector('[data-uid=' + selectedRow[rowuID] + ']') : null;\n mTr = !isNullOrUndefined(movableSelectedRow) ? this.element.querySelector('[data-uid=' + movableSelectedRow[rowuID] + ']') : null;\n if (!isNullOrUndefined(tr)) {\n setValue(field, value, selectedRow[rowData]);\n var td = !isNullOrUndefined(tr.childNodes[fieldIdx]) ?\n tr.childNodes[fieldIdx] : mTr.childNodes[fieldIdx - this.frozenColumns];\n if (!isNullOrUndefined(td)) {\n var sRow = selectedRow[cells][fieldIdx];\n var mRow = void 0;\n if (this.frozenColumns) {\n mRow = movableSelectedRow[cells][fieldIdx - this.frozenColumns];\n }\n cell.refreshTD(td, !isNullOrUndefined(sRow) ? sRow : mRow, selectedRow[rowData]);\n /* tslint:disable:no-string-literal */\n if (!isNullOrUndefined(movableSelectedRow) && !isNullOrUndefined(movableSelectedRow['changes'])) {\n movableSelectedRow['changes'][field] = value;\n }\n /* tslint:disable:no-string-literal */\n this.trigger(events.queryCellInfo, {\n cell: td, column: col, data: selectedRow[rowData]\n });\n }\n }\n else {\n return;\n }\n };\n /**\n * Updates and refresh the particular row values based on the given primary key value.\n * > Primary key column must be specified using `columns.isPrimaryKey` property.\n * @param {string| number} key - Specifies the PrimaryKey value of dataSource.\n * @param {Object} rowData - To update new data for the particular row.\n */\n Grid.prototype.setRowData = function (key, rowData) {\n var rwdata = 'data';\n var rowuID = 'uid';\n var rowObjects = this.contentModule.getRows();\n var selectedRow;\n var pkName = this.getPrimaryKeyFieldNames()[0];\n var rowRenderer = new RowRenderer(this.serviceLocator, null, this);\n selectedRow = rowObjects.filter(function (r) {\n return getValue(pkName, r.data) === key;\n })[0];\n if (!isNullOrUndefined(selectedRow) && this.element.querySelectorAll('[data-uid=' + selectedRow[rowuID] + ']').length) {\n selectedRow.changes = rowData;\n refreshForeignData(selectedRow, this.getForeignKeyColumns(), selectedRow.changes);\n rowRenderer.refresh(selectedRow, this.getColumns(), true);\n }\n else {\n return;\n }\n };\n /**\n * Gets a cell by row and column index.\n * @param {number} rowIndex - Specifies the row index.\n * @param {number} columnIndex - Specifies the column index.\n * @return {Element}\n */\n Grid.prototype.getCellFromIndex = function (rowIndex, columnIndex) {\n return this.getDataRows()[rowIndex].querySelectorAll('.e-rowcell')[columnIndex];\n };\n /**\n * Gets a movable table cell by row and column index.\n * @param {number} rowIndex - Specifies the row index.\n * @param {number} columnIndex - Specifies the column index.\n * @return {Element}\n */\n Grid.prototype.getMovableCellFromIndex = function (rowIndex, columnIndex) {\n return this.getMovableDataRows()[rowIndex].querySelectorAll('.e-rowcell')[columnIndex - this.getFrozenColumns()];\n };\n /**\n * Gets a column header by column index.\n * @param {number} index - Specifies the column index.\n * @return {Element}\n */\n Grid.prototype.getColumnHeaderByIndex = function (index) {\n return this.getHeaderTable().querySelectorAll('.e-headercell')[index];\n };\n /**\n * @hidden\n */\n Grid.prototype.getRowObjectFromUID = function (uid) {\n var rows = this.contentModule.getRows();\n var row = this.rowObject(rows, uid);\n if (this.getFrozenColumns()) {\n if (!row) {\n row = this.rowObject(this.contentModule.getMovableRows(), uid);\n return row;\n }\n }\n return row;\n };\n Grid.prototype.rowObject = function (rows, uid) {\n for (var _i = 0, rows_1 = rows; _i < rows_1.length; _i++) {\n var row = rows_1[_i];\n if (row.uid === uid) {\n return row;\n }\n }\n return null;\n };\n /**\n * @hidden\n */\n Grid.prototype.getRowsObject = function () {\n return this.contentModule.getRows();\n };\n /**\n * @hidden\n */\n Grid.prototype.getMovableRowsObject = function () {\n return this.contentModule.getMovableRows();\n };\n /**\n * Gets a column header by column name.\n * @param {string} field - Specifies the column name.\n * @return {Element}\n */\n Grid.prototype.getColumnHeaderByField = function (field) {\n return this.getColumnHeaderByUid(this.getColumnByField(field).uid);\n };\n /**\n * Gets a column header by UID.\n * @param {string} field - Specifies the column uid.\n * @return {Element}\n */\n Grid.prototype.getColumnHeaderByUid = function (uid) {\n return this.getHeaderContent().querySelector('[e-mappinguid=' + uid + ']').parentElement;\n };\n /**\n * @hidden\n */\n Grid.prototype.getColumnByIndex = function (index) {\n var column;\n this.getColumns().some(function (col, i) {\n column = col;\n return i === index;\n });\n return column;\n };\n /**\n * Gets a Column by column name.\n * @param {string} field - Specifies the column name.\n * @return {Column}\n */\n Grid.prototype.getColumnByField = function (field) {\n return iterateArrayOrObject(this.getColumns(), function (item, index) {\n if (item.field === field) {\n return item;\n }\n return undefined;\n })[0];\n };\n /**\n * Gets a column index by column name.\n * @param {string} field - Specifies the column name.\n * @return {number}\n */\n Grid.prototype.getColumnIndexByField = function (field) {\n var cols = this.getColumns();\n for (var i = 0; i < cols.length; i++) {\n if (cols[i].field === field) {\n return i;\n }\n }\n return -1;\n };\n /**\n * Gets a column by UID.\n * @param {string} uid - Specifies the column UID.\n * @return {Column}\n */\n Grid.prototype.getColumnByUid = function (uid) {\n return iterateArrayOrObject(this.getColumns(), function (item, index) {\n if (item.uid === uid) {\n return item;\n }\n return undefined;\n })[0];\n };\n /**\n * Gets a column index by UID.\n * @param {string} uid - Specifies the column UID.\n * @return {number}\n */\n Grid.prototype.getColumnIndexByUid = function (uid) {\n var index = iterateArrayOrObject(this.getColumns(), function (item, index) {\n if (item.uid === uid) {\n return index;\n }\n return undefined;\n })[0];\n return !isNullOrUndefined(index) ? index : -1;\n };\n /**\n * Gets UID by column name.\n * @param {string} field - Specifies the column name.\n * @return {string}\n */\n Grid.prototype.getUidByColumnField = function (field) {\n return iterateArrayOrObject(this.getColumns(), function (item, index) {\n if (item.field === field) {\n return item.uid;\n }\n return undefined;\n })[0];\n };\n /**\n * Gets TH index by column uid value.\n * @private\n * @param {string} uid - Specifies the column uid.\n * @return {number}\n */\n Grid.prototype.getNormalizedColumnIndex = function (uid) {\n var index = this.getColumnIndexByUid(uid);\n if (this.allowGrouping) {\n index += this.groupSettings.columns.length;\n }\n if (this.isDetail()) {\n index++;\n }\n /**\n * TODO: index normalization based on the stacked header, grouping and detailTemplate\n * and frozen should be handled here\n */\n return index;\n };\n /**\n * Gets the collection of column fields.\n * @return {string[]}\n */\n Grid.prototype.getColumnFieldNames = function () {\n var columnNames = [];\n var column;\n for (var i = 0, len = this.getColumns().length; i < len; i++) {\n column = this.getColumns()[i];\n if (column.visible) {\n columnNames.push(column.field);\n }\n }\n return columnNames;\n };\n /**\n * Gets a compiled row template.\n * @return {Function}\n * @private\n */\n Grid.prototype.getRowTemplate = function () {\n return this.rowTemplateFn;\n };\n /**\n * Gets a compiled detail row template.\n * @private\n * @return {Function}\n */\n Grid.prototype.getDetailTemplate = function () {\n return this.detailTemplateFn;\n };\n /**\n * Get the names of the primary key columns of the Grid.\n * @return {string[]}\n */\n Grid.prototype.getPrimaryKeyFieldNames = function () {\n var keys = [];\n this.columnModel.forEach(function (column) {\n if (column.isPrimaryKey) {\n keys.push(column.field);\n }\n });\n return keys;\n };\n /**\n * Refreshes the Grid header and content.\n */\n Grid.prototype.refresh = function () {\n this.headerModule.refreshUI();\n this.updateStackedFilter();\n this.renderModule.refresh();\n };\n /**\n * Refreshes the Grid header.\n */\n Grid.prototype.refreshHeader = function () {\n this.headerModule.refreshUI();\n };\n /**\n * Gets the collection of selected rows.\n * @return {Element[]}\n */\n Grid.prototype.getSelectedRows = function () {\n return this.selectionModule ? this.selectionModule.selectedRecords : [];\n };\n /**\n * Gets the collection of selected row indexes.\n * @return {number[]}\n */\n Grid.prototype.getSelectedRowIndexes = function () {\n return this.selectionModule ? this.selectionModule.selectedRowIndexes : [];\n };\n /**\n * Gets the collection of selected row and cell indexes.\n * @return {number[]}\n */\n Grid.prototype.getSelectedRowCellIndexes = function () {\n return this.selectionModule.selectedRowCellIndexes;\n };\n /**\n * Gets the collection of selected records.\n * @return {Object[]}\n */\n Grid.prototype.getSelectedRecords = function () {\n return this.selectionModule.getSelectedRecords();\n };\n /**\n * Gets the data module.\n * @return {Data}\n */\n Grid.prototype.getDataModule = function () {\n return this.renderModule.data;\n };\n /**\n * Shows a column by its column name.\n * @param {string|string[]} keys - Defines a single or collection of column names.\n * @param {string} showBy - Defines the column key either as field name or header text.\n * @return {void}\n */\n Grid.prototype.showColumns = function (keys, showBy) {\n showBy = showBy ? showBy : 'headerText';\n this.showHider.show(keys, showBy);\n };\n /**\n * Hides a column by column name.\n * @param {string|string[]} keys - Defines a single or collection of column names.\n * @param {string} hideBy - Defines the column key either as field name or header text.\n * @return {void}\n */\n Grid.prototype.hideColumns = function (keys, hideBy) {\n hideBy = hideBy ? hideBy : 'headerText';\n this.showHider.hide(keys, hideBy);\n };\n /**\n * @hidden\n */\n Grid.prototype.getFrozenColumns = function () {\n return this.frozenColumns + this.getFrozenCount(this.columns, 0);\n };\n /**\n * @hidden\n */\n Grid.prototype.getVisibleFrozenColumns = function () {\n return this.getVisibleFrozenColumnsCount() + this.getVisibleFrozenCount(this.columns, 0);\n };\n Grid.prototype.getVisibleFrozenColumnsCount = function () {\n var visibleFrozenColumns = 0;\n var col = this.columns;\n for (var i = 0; i < this.frozenColumns; i++) {\n if (col[i].visible) {\n visibleFrozenColumns++;\n }\n }\n return visibleFrozenColumns;\n };\n Grid.prototype.getVisibleFrozenCount = function (cols, cnt) {\n for (var i = 0, len = cols.length; i < len; i++) {\n if (cols[i].columns) {\n cnt = this.getVisibleFrozenCount(cols[i].columns, cnt);\n }\n else {\n if (cols[i].isFrozen && cols[i].visible) {\n cnt++;\n }\n }\n }\n return cnt;\n };\n Grid.prototype.getFrozenCount = function (cols, cnt) {\n for (var i = 0, len = cols.length; i < len; i++) {\n if (cols[i].columns) {\n cnt = this.getFrozenCount(cols[i].columns, cnt);\n }\n else {\n if (cols[i].isFrozen) {\n cnt++;\n }\n }\n }\n return cnt;\n };\n /**\n * Navigates to the specified target page.\n * @param {number} pageNo - Defines the page number to navigate.\n * @return {void}\n */\n Grid.prototype.goToPage = function (pageNo) {\n this.pagerModule.goToPage(pageNo);\n };\n /**\n * Defines the text of external message.\n * @param {string} message - Defines the message to update.\n * @return {void}\n */\n Grid.prototype.updateExternalMessage = function (message) {\n this.pagerModule.updateExternalMessage(message);\n };\n /**\n * Sorts a column with the given options.\n * @param {string} columnName - Defines the column name to be sorted.\n * @param {SortDirection} direction - Defines the direction of sorting field.\n * @param {boolean} isMultiSort - Specifies whether the previous sorted columns are to be maintained.\n * @return {void}\n */\n Grid.prototype.sortColumn = function (columnName, direction, isMultiSort) {\n this.sortModule.sortColumn(columnName, direction, isMultiSort);\n };\n /**\n * Clears all the sorted columns of the Grid.\n * @return {void}\n */\n Grid.prototype.clearSorting = function () {\n this.sortModule.clearSorting();\n };\n /**\n * Remove sorted column by field name.\n * @param {string} field - Defines the column field name to remove sort.\n * @return {void}\n * @hidden\n */\n Grid.prototype.removeSortColumn = function (field) {\n this.sortModule.removeSortColumn(field);\n };\n /**\n * Filters grid row by column name with the given options.\n * @param {string} fieldName - Defines the field name of the column.\n * @param {string} filterOperator - Defines the operator to filter records.\n * @param {string | number | Date | boolean} filterValue - Defines the value used to filter records.\n * @param {string} predicate - Defines the relationship between one filter query and another by using AND or OR predicate.\n * @param {boolean} matchCase - If match case is set to true, the grid filters the records with exact match. if false, it filters case\n * insensitive records (uppercase and lowercase letters treated the same).\n * @param {boolean} ignoreAccent - If ignoreAccent set to true,\n * then filter ignores the diacritic characters or accents while filtering.\n * @param {string} actualFilterValue - Defines the actual filter value for the filter column.\n * @param {string} actualOperator - Defines the actual filter operator for the filter column.\n * @return {void}\n */\n Grid.prototype.filterByColumn = function (fieldName, filterOperator, filterValue, predicate, matchCase, ignoreAccent, actualFilterValue, actualOperator) {\n this.filterModule.filterByColumn(fieldName, filterOperator, filterValue, predicate, matchCase, ignoreAccent, actualFilterValue, actualOperator);\n };\n /**\n * Clears all the filtered rows of the Grid.\n * @return {void}\n */\n Grid.prototype.clearFiltering = function () {\n this.filterModule.clearFiltering();\n };\n /**\n * Removes filtered column by field name.\n * @param {string} field - Defines column field name to remove filter.\n * @param {boolean} isClearFilterBar - Specifies whether the filter bar value needs to be cleared.\n * @return {void}\n * @hidden\n */\n Grid.prototype.removeFilteredColsByField = function (field, isClearFilterBar) {\n this.filterModule.removeFilteredColsByField(field, isClearFilterBar);\n };\n /**\n * Selects a row by given index.\n * @param {number} index - Defines the row index.\n * @param {boolean} isToggle - If set to true, then it toggles the selection.\n * @return {void}\n */\n Grid.prototype.selectRow = function (index, isToggle) {\n this.selectionModule.selectRow(index, isToggle);\n };\n /**\n * Selects a collection of rows by indexes.\n * @param {number[]} rowIndexes - Specifies the row indexes.\n * @return {void}\n */\n Grid.prototype.selectRows = function (rowIndexes) {\n this.selectionModule.selectRows(rowIndexes);\n };\n /**\n * Deselects the current selected rows and cells.\n * @return {void}\n */\n Grid.prototype.clearSelection = function () {\n this.selectionModule.clearSelection();\n };\n /**\n * Selects a cell by the given index.\n * @param {IIndex} cellIndex - Defines the row and column indexes.\n * @param {boolean} isToggle - If set to true, then it toggles the selection.\n * @return {void}\n */\n Grid.prototype.selectCell = function (cellIndex, isToggle) {\n this.selectionModule.selectCell(cellIndex, isToggle);\n };\n /**\n * Searches Grid records using the given key.\n * You can customize the default search option by using the\n * [`searchSettings`](./api-searchSettings.html).\n * @param {string} searchString - Defines the key.\n * @return {void}\n */\n Grid.prototype.search = function (searchString) {\n this.searchModule.search(searchString);\n };\n /**\n * By default, prints all the pages of the Grid and hides the pager.\n * > You can customize print options using the\n * [`printMode`](./api-grid.html#printmode-string).\n * @return {void}\n */\n Grid.prototype.print = function () {\n this.printModule.print();\n };\n /**\n * Delete a record with Given options. If fieldname and data is not given then grid will delete the selected record.\n * > `editSettings.allowDeleting` should be true.\n * @param {string} fieldname - Defines the primary key field, 'Name of the column'.\n * @param {Object} data - Defines the JSON data of the record to be deleted.\n */\n Grid.prototype.deleteRecord = function (fieldname, data) {\n this.editModule.deleteRecord(fieldname, data);\n };\n /**\n * To edit any particular row by TR element.\n * @param {HTMLTableRowElement} tr - Defines the table row to be edited.\n */\n Grid.prototype.startEdit = function () {\n this.editModule.startEdit();\n };\n /**\n * If Grid is in editable state, you can save a record by invoking endEdit.\n */\n Grid.prototype.endEdit = function () {\n this.editModule.endEdit();\n };\n /**\n * Cancels edited state.\n */\n Grid.prototype.closeEdit = function () {\n this.editModule.closeEdit();\n };\n /**\n * Adds a new record to the Grid. Without passing parameters, it adds empty rows.\n * > `editSettings.allowEditing` should be true.\n * @param {Object} data - Defines the new add record data.\n * @param {number} index - Defines the row index to be added\n */\n Grid.prototype.addRecord = function (data, index) {\n this.editModule.addRecord(data, index);\n };\n /**\n * Delete any visible row by TR element.\n * @param {HTMLTableRowElement} tr - Defines the table row element.\n */\n Grid.prototype.deleteRow = function (tr) {\n this.editModule.deleteRow(tr);\n };\n /**\n * Copy the selected rows or cells data into clipboard.\n * @param {boolean} withHeader - Specifies whether the column header text needs to be copied along with rows or cells.\n */\n Grid.prototype.copy = function (withHeader) {\n this.clipboardModule.copy(withHeader);\n };\n /**\n * @hidden\n */\n Grid.prototype.recalcIndentWidth = function () {\n if (!this.getHeaderTable().querySelector('.e-emptycell')) {\n return;\n }\n if ((!this.groupSettings.columns.length && !this.isDetail()) ||\n this.getHeaderTable().querySelector('.e-emptycell').getAttribute('indentRefreshed') ||\n !this.getContentTable()) {\n return;\n }\n var indentWidth = this.getHeaderTable().querySelector('.e-emptycell').parentElement.offsetWidth;\n var headerCol = [].slice.call(this.getHeaderTable().querySelector('colgroup').childNodes);\n var contentCol = [].slice.call(this.getContentTable().querySelector('colgroup').childNodes);\n var perPixel = indentWidth / 30;\n var i = 0;\n if (perPixel >= 1) {\n indentWidth = (30 / perPixel);\n }\n if (this.enableColumnVirtualization) {\n indentWidth = 30;\n }\n while (i < this.groupSettings.columns.length) {\n headerCol[i].style.width = indentWidth + 'px';\n contentCol[i].style.width = indentWidth + 'px';\n this.notify(events.columnWidthChanged, { index: i, width: indentWidth });\n i++;\n }\n if (this.isDetail()) {\n headerCol[i].style.width = indentWidth + 'px';\n contentCol[i].style.width = indentWidth + 'px';\n this.notify(events.columnWidthChanged, { index: i, width: indentWidth });\n }\n this.getHeaderTable().querySelector('.e-emptycell').setAttribute('indentRefreshed', 'true');\n };\n /**\n * Changes the Grid column positions by field names.\n * @param {string} fromFName - Defines the origin field name.\n * @param {string} toFName - Defines the destination field name.\n * @return {void}\n */\n Grid.prototype.reorderColumns = function (fromFName, toFName) {\n this.reorderModule.reorderColumns(fromFName, toFName);\n };\n /**\n * Changes the column width to automatically fit its content to ensure that the width shows the content without wrapping/hiding.\n * > * This method ignores the hidden columns.\n * > * Uses the `autoFitColumns` method in the `dataBound` event to resize at initial rendering.\n * @param {string |string[]} fieldNames - Defines the column names.\n * @return {void}\n *\n *\n * ```typescript\n *
\n * \n * ```\n *\n */\n Grid.prototype.autoFitColumns = function (fieldNames) {\n this.resizeModule.autoFitColumns(fieldNames);\n };\n /**\n * @hidden\n */\n Grid.prototype.createColumnchooser = function (x, y, target) {\n this.columnChooserModule.renderColumnChooser(x, y, target);\n };\n Grid.prototype.initializeServices = function () {\n this.serviceLocator.register('widthService', this.widthService = new ColumnWidthService(this));\n this.serviceLocator.register('cellRendererFactory', new CellRendererFactory);\n this.serviceLocator.register('rendererFactory', new RendererFactory);\n this.serviceLocator.register('localization', this.localeObj = new L10n(this.getModuleName(), this.defaultLocale, this.locale));\n this.serviceLocator.register('valueFormatter', this.valueFormatterService = new ValueFormatter(this.locale));\n this.serviceLocator.register('showHideService', this.showHider = new ShowHide(this));\n this.serviceLocator.register('ariaService', this.ariaService = new AriaService());\n this.serviceLocator.register('focus', this.focusModule = new FocusStrategy(this));\n };\n Grid.prototype.processModel = function () {\n var _this = this;\n var gCols = this.groupSettings.columns;\n var sCols = this.sortSettings.columns;\n var flag;\n var j;\n if (this.allowGrouping) {\n var _loop_1 = function (i, len) {\n j = 0;\n for (var sLen = sCols.length; j < sLen; j++) {\n if (sCols[j].field === gCols[i]) {\n flag = true;\n break;\n }\n }\n if (!flag) {\n sCols.push({ field: gCols[i], direction: 'Ascending' });\n }\n else {\n if (this_1.allowSorting) {\n this_1.sortedColumns.push(sCols[j].field);\n }\n else {\n sCols[j].direction = 'Ascending';\n }\n }\n if (!this_1.groupSettings.showGroupedColumn) {\n var column = this_1.enableColumnVirtualization ?\n this_1.columns.filter(function (c) { return c.field === gCols[i]; })[0] : this_1.getColumnByField(gCols[i]);\n column.visible = false;\n }\n };\n var this_1 = this;\n for (var i = 0, len = gCols.length; i < len; i++) {\n _loop_1(i, len);\n }\n }\n if (!gCols.length) {\n sCols.forEach(function (col) {\n _this.sortedColumns.push(col.field);\n });\n }\n this.rowTemplateFn = templateCompiler(this.rowTemplate);\n this.detailTemplateFn = templateCompiler(this.detailTemplate);\n if (!isNullOrUndefined(this.parentDetails)) {\n var value = isNullOrUndefined(this.parentDetails.parentKeyFieldValue) ? 'undefined' :\n this.parentDetails.parentKeyFieldValue;\n this.query.where(this.queryString, 'equal', value, true);\n }\n this.initForeignColumn();\n };\n Grid.prototype.initForeignColumn = function () {\n if (this.isForeignKeyEnabled(this.getColumns())) {\n this.notify(events.initForeignKeyColumn, this.getForeignKeyColumns());\n }\n };\n Grid.prototype.gridRender = function () {\n this.updateRTL();\n if (this.enableHover) {\n this.element.classList.add('e-gridhover');\n }\n if (Browser.isDevice) {\n this.element.classList.add('e-device');\n }\n if (this.rowHeight) {\n this.element.classList.add('e-grid-min-height');\n }\n classList(this.element, ['e-responsive', 'e-default'], []);\n var rendererFactory = this.serviceLocator.getService('rendererFactory');\n this.headerModule = rendererFactory.getRenderer(RenderType.Header);\n this.contentModule = rendererFactory.getRenderer(RenderType.Content);\n this.printModule = new Print(this, this.scrollModule);\n this.clipboardModule = new Clipboard(this);\n this.renderModule.render();\n this.eventInitializer();\n this.createGridPopUpElement();\n this.widthService.setWidthToColumns();\n this.updateGridLines();\n this.applyTextWrap();\n this.createTooltip(); //for clip mode ellipsis\n };\n Grid.prototype.dataReady = function () {\n this.scrollModule.setWidth();\n this.scrollModule.setHeight();\n if (this.height !== 'auto') {\n this.scrollModule.setPadding();\n }\n };\n Grid.prototype.updateRTL = function () {\n if (this.enableRtl) {\n this.element.classList.add('e-rtl');\n }\n else {\n this.element.classList.remove('e-rtl');\n }\n };\n Grid.prototype.createGridPopUpElement = function () {\n var popup = this.createElement('div', { className: 'e-gridpopup', styles: 'display:none;' });\n var content = this.createElement('div', { className: 'e-content', attrs: { tabIndex: '-1' } });\n append([content, this.createElement('div', { className: 'e-uptail e-tail' })], popup);\n content.appendChild(this.createElement('span'));\n append([content, this.createElement('div', { className: 'e-downtail e-tail' })], popup);\n this.element.appendChild(popup);\n };\n Grid.prototype.updateGridLines = function () {\n classList(this.element, [], ['e-verticallines', 'e-horizontallines', 'e-hidelines', 'e-bothlines']);\n switch (this.gridLines) {\n case 'Horizontal':\n this.element.classList.add('e-horizontallines');\n break;\n case 'Vertical':\n this.element.classList.add('e-verticallines');\n break;\n case 'None':\n this.element.classList.add('e-hidelines');\n break;\n case 'Both':\n this.element.classList.add('e-bothlines');\n break;\n }\n this.updateResizeLines();\n };\n Grid.prototype.updateResizeLines = function () {\n if (this.allowResizing &&\n !(this.gridLines === 'Vertical' || this.gridLines === 'Both')) {\n this.element.classList.add('e-resize-lines');\n }\n else {\n this.element.classList.remove('e-resize-lines');\n }\n };\n /**\n * The function is used to apply text wrap\n * @return {void}\n * @hidden\n */\n Grid.prototype.applyTextWrap = function () {\n if (this.allowTextWrap) {\n var headerRows = [].slice.call(this.element.querySelectorAll('.e-columnheader'));\n switch (this.textWrapSettings.wrapMode) {\n case 'Header':\n wrap(this.element, false);\n wrap(this.getContent(), false);\n wrap(headerRows, true);\n break;\n case 'Content':\n wrap(this.getContent(), true);\n wrap(this.element, false);\n wrap(headerRows, false);\n break;\n default:\n wrap(this.element, true);\n wrap(this.getContent(), false);\n wrap(headerRows, false);\n }\n }\n };\n /**\n * The function is used to remove text wrap\n * @return {void}\n * @hidden\n */\n Grid.prototype.removeTextWrap = function () {\n wrap(this.element, false);\n var headerRows = [].slice.call(this.element.querySelectorAll('.e-columnheader'));\n wrap(headerRows, false);\n wrap(this.getContent(), false);\n };\n /**\n * The function is used to add Tooltip to the grid cell that has ellipsiswithtooltip clip mode.\n * @return {void}\n * @hidden\n */\n Grid.prototype.createTooltip = function () {\n this.toolTipObj = new Tooltip({ opensOn: 'custom', content: '' }, this.element);\n };\n Grid.prototype.getTooltipStatus = function (element) {\n var width;\n var headerTable = this.getHeaderTable();\n var contentTable = this.getContentTable();\n var headerDivTag = 'e-gridheader';\n var contentDivTag = 'e-gridcontent';\n var htable = this.createTable(headerTable, headerDivTag, 'header');\n var ctable = this.createTable(headerTable, headerDivTag, 'content');\n var td = element;\n var table = headerTable.contains(element) ? htable : ctable;\n var ele = headerTable.contains(element) ? 'th' : 'tr';\n table.querySelector(ele).className = element.className;\n table.querySelector(ele).innerHTML = element.innerHTML;\n width = table.querySelector(ele).getBoundingClientRect().width;\n document.body.removeChild(htable);\n document.body.removeChild(ctable);\n if (width > element.getBoundingClientRect().width) {\n return true;\n }\n return false;\n };\n Grid.prototype.mouseMoveHandler = function (e) {\n if (this.isEllipsisTooltip()) {\n var element = parentsUntil(e.target, 'e-ellipsistooltip');\n if (element) {\n if (element.getAttribute('aria-describedby')) {\n return;\n }\n if (this.getTooltipStatus(element)) {\n if (element.getElementsByClassName('e-headertext').length) {\n this.toolTipObj.content = element.getElementsByClassName('e-headertext')[0].innerText;\n }\n else {\n this.toolTipObj.content = element.innerText;\n }\n this.toolTipObj.open(element);\n }\n else {\n this.toolTipObj.close();\n }\n }\n else {\n this.toolTipObj.close();\n }\n }\n };\n Grid.prototype.isEllipsisTooltip = function () {\n var cols = this.getColumns();\n for (var i = 0; i < cols.length; i++) {\n if (cols[i].clipMode === 'EllipsisWithTooltip') {\n return true;\n }\n }\n return false;\n };\n Grid.prototype.scrollHandler = function () {\n if (this.isEllipsisTooltip()) {\n this.toolTipObj.close();\n }\n };\n /**\n * To create table for ellipsiswithtooltip\n * @hidden\n */\n Grid.prototype.createTable = function (table, tag, type) {\n var myTableDiv = this.createElement('div');\n myTableDiv.className = this.element.className;\n myTableDiv.style.cssText = 'display: inline-block;visibility:hidden;position:absolute';\n var mySubDiv = this.createElement('div');\n mySubDiv.className = tag;\n var myTable = this.createElement('table');\n myTable.className = table.className;\n myTable.style.cssText = 'table-layout: auto;width: auto';\n var ele = (type === 'header') ? 'th' : 'td';\n var myTr = this.createElement('tr');\n var mytd = this.createElement(ele);\n myTr.appendChild(mytd);\n myTable.appendChild(myTr);\n mySubDiv.appendChild(myTable);\n myTableDiv.appendChild(mySubDiv);\n document.body.appendChild(myTableDiv);\n return myTableDiv;\n };\n /**\n * Binding events to the element while component creation.\n * @hidden\n */\n Grid.prototype.wireEvents = function () {\n EventHandler.add(this.element, 'click', this.mouseClickHandler, this);\n EventHandler.add(this.element, 'touchend', this.mouseClickHandler, this);\n EventHandler.add(this.element, 'focusout', this.focusOutHandler, this);\n EventHandler.add(this.getContent(), 'dblclick', this.dblClickHandler, this);\n if (this.allowKeyboard) {\n this.element.tabIndex = this.element.tabIndex === -1 ? 0 : this.element.tabIndex;\n }\n this.keyboardModule = new KeyboardEvents(this.element, {\n keyAction: this.keyActionHandler.bind(this),\n keyConfigs: this.keyConfigs,\n eventName: 'keydown'\n });\n EventHandler.add(this.getContent().firstElementChild, 'scroll', this.scrollHandler, this);\n EventHandler.add(this.element, 'mousemove', this.mouseMoveHandler, this);\n };\n /**\n * Unbinding events from the element while component destroy.\n * @hidden\n */\n Grid.prototype.unwireEvents = function () {\n EventHandler.remove(this.element, 'click', this.mouseClickHandler);\n EventHandler.remove(this.element, 'touchend', this.mouseClickHandler);\n EventHandler.remove(this.element, 'focusout', this.focusOutHandler);\n EventHandler.remove(this.getContent().firstElementChild, 'scroll', this.scrollHandler);\n EventHandler.remove(this.element, 'mousemove', this.mouseMoveHandler);\n };\n /**\n * @hidden\n */\n Grid.prototype.addListener = function () {\n if (this.isDestroyed) {\n return;\n }\n this.on(events.dataReady, this.dataReady, this);\n this.on(events.contentReady, this.recalcIndentWidth, this);\n this.on(events.headerRefreshed, this.recalcIndentWidth, this);\n this.dataBoundFunction = this.refreshMediaCol.bind(this);\n this.addEventListener(events.dataBound, this.dataBoundFunction);\n };\n /**\n * @hidden\n */\n Grid.prototype.removeListener = function () {\n if (this.isDestroyed) {\n return;\n }\n this.off(events.dataReady, this.dataReady);\n this.off(events.contentReady, this.recalcIndentWidth);\n this.off(events.headerRefreshed, this.recalcIndentWidth);\n this.removeEventListener(events.dataBound, this.dataBoundFunction);\n };\n /**\n * Get current visible data of grid.\n * @return {Object[]}\n * @hidden\n */\n Grid.prototype.getCurrentViewRecords = function () {\n return (this.allowGrouping && this.groupSettings.columns.length && this.currentViewData.length) ?\n this.currentViewData.records : this.currentViewData;\n };\n Grid.prototype.mouseClickHandler = function (e) {\n if (this.isChildGrid(e) || (parentsUntil(e.target, 'e-gridpopup') && e.touches) ||\n this.element.querySelectorAll('.e-cloneproperties').length || this.checkEdit(e)) {\n return;\n }\n if (((!this.allowRowDragAndDrop && (parentsUntil(e.target, 'e-gridcontent') ||\n e.target.tagName === 'TD')) || (!(this.allowGrouping || this.allowReordering) &&\n parentsUntil(e.target, 'e-gridheader'))) && e.touches) {\n return;\n }\n if (parentsUntil(e.target, 'e-gridheader') && this.allowRowDragAndDrop) {\n e.preventDefault();\n }\n this.notify(events.click, e);\n };\n Grid.prototype.checkEdit = function (e) {\n var tr = parentsUntil(e.target, 'e-row');\n var isEdit = this.editSettings.mode !== 'Batch' &&\n this.isEdit && tr && (tr.classList.contains('e-editedrow') || tr.classList.contains('e-addedrow'));\n return !parentsUntil(e.target, 'e-unboundcelldiv') && (isEdit || (parentsUntil(e.target, 'e-rowcell') &&\n parentsUntil(e.target, 'e-rowcell').classList.contains('e-editedbatchcell')));\n };\n Grid.prototype.dblClickHandler = function (e) {\n var grid = parentsUntil(e.target, 'e-grid');\n if (isNullOrUndefined(grid) || grid.id !== this.element.id || closest(e.target, '.e-unboundcelldiv')) {\n return;\n }\n var args = this.getRowInfo(e.target);\n args.target = e.target;\n this.trigger(events.recordDoubleClick, args);\n this.notify(events.dblclick, e);\n };\n Grid.prototype.focusOutHandler = function (e) {\n if (this.isChildGrid(e)) {\n return;\n }\n if (!parentsUntil(e.target, 'e-grid')) {\n this.element.querySelector('.e-gridpopup').style.display = 'None';\n }\n var filterClear = this.element.querySelector('.e-cancel:not(.e-hide)');\n if (filterClear) {\n filterClear.classList.add('e-hide');\n }\n if ((!e.relatedTarget || !parentsUntil(e.relatedTarget, 'e-grid'))\n && !this.keyPress && this.editSettings.mode === 'Batch' && this.isEdit && !Browser.isDevice) {\n this.editModule.saveCell();\n this.notify(events.editNextValCell, {});\n }\n this.keyPress = false;\n };\n Grid.prototype.isChildGrid = function (e) {\n var gridElement = parentsUntil(e.target, 'e-grid');\n if (gridElement && gridElement.id !== this.element.id) {\n return true;\n }\n return false;\n };\n Grid.prototype.mergePersistGridData = function () {\n var data = window.localStorage.getItem(this.getModuleName() + this.element.id);\n if (!(isNullOrUndefined(data) || (data === ''))) {\n var dataObj = JSON.parse(data);\n var keys = Object.keys(dataObj);\n this.isProtectedOnChange = true;\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var key = keys_1[_i];\n if ((typeof this[key] === 'object') && !isNullOrUndefined(this[key])) {\n if (Array.isArray(this[key]) && key === 'columns') {\n this.mergeColumns(dataObj[key], this[key]);\n this[key] = dataObj[key];\n }\n else {\n extend(this[key], dataObj[key]);\n }\n }\n else {\n this[key] = dataObj[key];\n }\n }\n this.isProtectedOnChange = false;\n }\n };\n Grid.prototype.mergeColumns = function (storedColumn, columns) {\n var _this = this;\n storedColumn.forEach(function (col, index, arr) {\n var ind;\n var localCol = _this.getColumnByField(col.field) ||\n columns.some(function (element, i) {\n ind = i;\n return element.headerText === col.headerText;\n }) && columns[ind];\n if (!isNullOrUndefined(localCol)) {\n if (localCol.columns && localCol.columns.length) {\n _this.mergeColumns(col.columns, localCol.columns);\n }\n else {\n arr[index] = extend({}, localCol, col, true);\n }\n }\n });\n };\n Grid.prototype.isDetail = function () {\n return !isNullOrUndefined(this.detailTemplate) || !isNullOrUndefined(this.childGrid);\n };\n Grid.prototype.isCommandColumn = function (columns) {\n var _this = this;\n return columns.some(function (col) {\n if (col.columns) {\n return _this.isCommandColumn(col.columns);\n }\n return !!(col.commands || col.commandsTemplate);\n });\n };\n Grid.prototype.isForeignKeyEnabled = function (columns) {\n var _this = this;\n return columns.some(function (col) {\n if (col.columns) {\n return _this.isForeignKeyEnabled(col.columns);\n }\n return !!(col.dataSource && col.foreignKeyValue);\n });\n };\n Grid.prototype.keyActionHandler = function (e) {\n this.keyPress = true;\n if (this.isChildGrid(e) ||\n (this.isEdit && e.action !== 'escape' && e.action !== 'enter' && e.action !== 'shiftEnter'\n && e.action !== 'tab' && e.action !== 'shiftTab')) {\n return;\n }\n if (this.allowKeyboard) {\n if (e.action === 'ctrlPlusP') {\n e.preventDefault();\n this.print();\n }\n this.notify(events.keyPressed, e);\n }\n };\n /**\n * @hidden\n */\n Grid.prototype.setInjectedModules = function (modules) {\n this.injectedModules = modules;\n };\n Grid.prototype.updateColumnObject = function () {\n prepareColumns(this.columns, this.enableColumnVirtualization);\n this.initForeignColumn();\n this.notify(events.autoCol, {});\n };\n /**\n * Gets the foreign columns from Grid.\n * @return {Column[]}\n */\n Grid.prototype.getForeignKeyColumns = function () {\n return this.getColumns().filter(function (col) {\n return col.isForeignColumn();\n });\n };\n /**\n * @hidden\n */\n Grid.prototype.getRowHeight = function () {\n return this.rowHeight ? this.rowHeight : getRowHeight(this.element);\n };\n /**\n * Refreshes the Grid column changes.\n */\n Grid.prototype.refreshColumns = function () {\n this.isPreventScrollEvent = true;\n this.updateColumnObject();\n this.refresh();\n };\n /**\n * Export Grid data to Excel file(.xlsx).\n * @param {ExcelExportProperties} excelExportProperties - Defines the export properties of the Grid.\n * @param {boolean} isMultipleExport - Define to enable multiple export.\n * @param {workbook} workbook - Defines the Workbook if multiple export is enabled.\n * @param {boolean} isBlob - If 'isBlob' set to true, then it will be returned as blob data.\n * @return {Promise}\n */\n Grid.prototype.excelExport = function (excelExportProperties, isMultipleExport, \n /* tslint:disable-next-line:no-any */\n workbook, isBlob) {\n return this.excelExportModule.Map(this, excelExportProperties, isMultipleExport, workbook, false, isBlob);\n };\n /**\n * Export Grid data to CSV file.\n * @param {ExcelExportProperties} excelExportProperties - Defines the export properties of the Grid.\n * @param {boolean} isMultipleExport - Define to enable multiple export.\n * @param {workbook} workbook - Defines the Workbook if multiple export is enabled.\n * @param {boolean} isBlob - If 'isBlob' set to true, then it will be returned as blob data.\n * @return {Promise}\n *\n */\n Grid.prototype.csvExport = function (excelExportProperties, \n /* tslint:disable-next-line:no-any */\n isMultipleExport, workbook, isBlob) {\n return this.excelExportModule.Map(this, excelExportProperties, isMultipleExport, workbook, true, isBlob);\n };\n /**\n * Export Grid data to PDF document.\n * @param {pdfExportProperties} PdfExportProperties - Defines the export properties of the Grid.\n * @param {isMultipleExport} isMultipleExport - Define to enable multiple export.\n * @param {pdfDoc} pdfDoc - Defined the Pdf Document if multiple export is enabled.\n * @param {boolean} isBlob - If 'isBlob' set to true, then it will be returned as blob data.\n * @return {Promise}\n *\n */\n Grid.prototype.pdfExport = function (pdfExportProperties, \n /* tslint:disable-next-line:no-any */\n isMultipleExport, pdfDoc, isBlob) {\n return this.pdfExportModule.Map(this, pdfExportProperties, isMultipleExport, pdfDoc, isBlob);\n };\n /**\n * Groups a column by column name.\n * @param {string} columnName - Defines the column name to group.\n * @return {void}\n */\n Grid.prototype.groupColumn = function (columnName) {\n this.groupModule.groupColumn(columnName);\n };\n /**\n * Ungroups a column by column name.\n * @param {string} columnName - Defines the column name to ungroup.\n * @return {void}\n */\n Grid.prototype.ungroupColumn = function (columnName) {\n this.groupModule.ungroupColumn(columnName);\n };\n /**\n * @hidden\n */\n Grid.prototype.isContextMenuOpen = function () {\n return this.contextMenuModule && this.contextMenuModule.isOpen;\n };\n /**\n * @hidden\n */\n Grid.prototype.ensureModuleInjected = function (module) {\n return this.getInjectedModules().indexOf(module) >= 0;\n };\n /**\n * Destroys the given template reference.\n * @param {string[]} propertyNames - Defines the collection of template name.\n */\n Grid.prototype.destroyTemplate = function (propertyNames) {\n this.clearTemplate(propertyNames);\n };\n __decorate([\n Property([])\n ], Grid.prototype, \"columns\", void 0);\n __decorate([\n Property(true)\n ], Grid.prototype, \"enableAltRow\", void 0);\n __decorate([\n Property(true)\n ], Grid.prototype, \"enableHover\", void 0);\n __decorate([\n Property(true)\n ], Grid.prototype, \"allowKeyboard\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowTextWrap\", void 0);\n __decorate([\n Complex({}, TextWrapSettings)\n ], Grid.prototype, \"textWrapSettings\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowPaging\", void 0);\n __decorate([\n Complex({}, PageSettings)\n ], Grid.prototype, \"pageSettings\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"enableVirtualization\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"enableColumnVirtualization\", void 0);\n __decorate([\n Complex({}, SearchSettings)\n ], Grid.prototype, \"searchSettings\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowSorting\", void 0);\n __decorate([\n Property(true)\n ], Grid.prototype, \"allowMultiSorting\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowExcelExport\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowPdfExport\", void 0);\n __decorate([\n Complex({}, SortSettings)\n ], Grid.prototype, \"sortSettings\", void 0);\n __decorate([\n Property(true)\n ], Grid.prototype, \"allowSelection\", void 0);\n __decorate([\n Property(-1)\n ], Grid.prototype, \"selectedRowIndex\", void 0);\n __decorate([\n Complex({}, SelectionSettings)\n ], Grid.prototype, \"selectionSettings\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowFiltering\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowReordering\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowResizing\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowRowDragAndDrop\", void 0);\n __decorate([\n Complex({}, RowDropSettings)\n ], Grid.prototype, \"rowDropSettings\", void 0);\n __decorate([\n Complex({}, FilterSettings)\n ], Grid.prototype, \"filterSettings\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"allowGrouping\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"showColumnMenu\", void 0);\n __decorate([\n Complex({}, GroupSettings)\n ], Grid.prototype, \"groupSettings\", void 0);\n __decorate([\n Complex({}, EditSettings)\n ], Grid.prototype, \"editSettings\", void 0);\n __decorate([\n Collection([], AggregateRow)\n ], Grid.prototype, \"aggregates\", void 0);\n __decorate([\n Property(false)\n ], Grid.prototype, \"showColumnChooser\", void 0);\n __decorate([\n Property('auto')\n ], Grid.prototype, \"height\", void 0);\n __decorate([\n Property('auto')\n ], Grid.prototype, \"width\", void 0);\n __decorate([\n Property('Default')\n ], Grid.prototype, \"gridLines\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"rowTemplate\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"detailTemplate\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"childGrid\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"queryString\", void 0);\n __decorate([\n Property('AllPages')\n ], Grid.prototype, \"printMode\", void 0);\n __decorate([\n Property([])\n ], Grid.prototype, \"dataSource\", void 0);\n __decorate([\n Property(null)\n ], Grid.prototype, \"rowHeight\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"query\", void 0);\n __decorate([\n Property('USD')\n ], Grid.prototype, \"currencyCode\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"toolbar\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"contextMenuItems\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"columnMenuItems\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"toolbarTemplate\", void 0);\n __decorate([\n Property()\n ], Grid.prototype, \"pagerTemplate\", void 0);\n __decorate([\n Property(0)\n ], Grid.prototype, \"frozenRows\", void 0);\n __decorate([\n Property(0)\n ], Grid.prototype, \"frozenColumns\", void 0);\n __decorate([\n Property('All')\n ], Grid.prototype, \"columnQueryMode\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"created\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"destroyed\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"load\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowDataBound\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"queryCellInfo\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"headerCellInfo\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"actionBegin\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"actionComplete\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"actionFailure\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"dataBound\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"recordDoubleClick\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowSelecting\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowSelected\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowDeselecting\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowDeselected\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"cellSelecting\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"cellSelected\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"cellDeselecting\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"cellDeselected\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"columnDragStart\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"columnDrag\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"columnDrop\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"printComplete\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforePrint\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"pdfQueryCellInfo\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"pdfHeaderQueryCellInfo\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"excelQueryCellInfo\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"excelHeaderQueryCellInfo\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforeExcelExport\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"excelExportComplete\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforePdfExport\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"pdfExportComplete\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"detailDataBound\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowDragStart\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowDrag\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"rowDrop\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"toolbarClick\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforeOpenColumnChooser\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"batchAdd\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"batchDelete\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"batchCancel\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforeBatchAdd\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforeBatchDelete\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforeBatchSave\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beginEdit\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"cellEdit\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"cellSave\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"cellSaved\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"resizeStart\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"resizing\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"resizeStop\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforeDataBound\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"contextMenuOpen\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"contextMenuClick\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"columnMenuOpen\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"columnMenuClick\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"checkBoxChange\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"beforeCopy\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"dataStateChange\", void 0);\n __decorate([\n Event()\n ], Grid.prototype, \"dataSourceChanged\", void 0);\n Grid = __decorate([\n NotifyPropertyChanges\n ], Grid);\n return Grid;\n}(Component));\nexport { Grid };\nGrid.Inject(Selection);\n","import { Browser } from '@syncfusion/ej2-base';\nimport { extend, isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { closest, classList } from '@syncfusion/ej2-base';\nimport { setCssInGridPopUp, getActualPropFromColl, isActionPrevent, iterateExtend } from '../base/util';\nimport * as events from '../base/constant';\nimport { AriaService } from '../services/aria-service';\n/**\n *\n * The `Sort` module is used to handle sorting action.\n */\nvar Sort = /** @class */ (function () {\n /**\n * Constructor for Grid sorting module\n * @hidden\n */\n function Sort(parent, sortSettings, sortedColumns, locator) {\n this.contentRefresh = true;\n this.isModelChanged = true;\n this.aria = new AriaService();\n this.parent = parent;\n this.sortSettings = sortSettings;\n this.sortedColumns = sortedColumns;\n this.focus = locator.getService('focus');\n this.addEventListener();\n }\n /**\n * The function used to update sortSettings\n * @return {void}\n * @hidden\n */\n Sort.prototype.updateModel = function () {\n var sortedColumn = { field: this.columnName, direction: this.direction };\n var index;\n var gCols = this.parent.groupSettings.columns;\n var flag = false;\n if (!this.isMultiSort) {\n if (!gCols.length) {\n this.sortSettings.columns = [sortedColumn];\n }\n else {\n var sortedCols = [];\n for (var i = 0, len = gCols.length; i < len; i++) {\n index = this.getSortedColsIndexByField(gCols[i], sortedCols);\n if (this.columnName === gCols[i]) {\n flag = true;\n sortedCols.push(sortedColumn);\n }\n else {\n var sCol = this.getSortColumnFromField(gCols[i]);\n sortedCols.push({ field: sCol.field, direction: sCol.direction });\n }\n }\n if (!flag) {\n sortedCols.push(sortedColumn);\n }\n this.sortSettings.columns = sortedCols;\n }\n }\n else {\n index = this.getSortedColsIndexByField(this.columnName);\n if (index > -1) {\n this.sortSettings.columns.splice(index, 1);\n }\n this.sortSettings.columns.push(sortedColumn);\n this.sortSettings.columns = this.sortSettings.columns;\n }\n this.parent.dataBind();\n this.lastSortedCol = this.columnName;\n };\n /**\n * The function used to trigger onActionComplete\n * @return {void}\n * @hidden\n */\n Sort.prototype.onActionComplete = function (e) {\n var args = !this.isRemove ? {\n columnName: this.columnName, direction: this.direction, requestType: 'sorting', type: events.actionComplete\n } : { requestType: 'sorting', type: events.actionComplete };\n this.isRemove = false;\n this.parent.trigger(events.actionComplete, extend(e, args));\n };\n /**\n * Sorts a column with the given options.\n * @param {string} columnName - Defines the column name to sort.\n * @param {SortDirection} direction - Defines the direction of sorting field.\n * @param {boolean} isMultiSort - Specifies whether the previously sorted columns are to be maintained.\n * @return {void}\n */\n Sort.prototype.sortColumn = function (columnName, direction, isMultiSort) {\n var gObj = this.parent;\n if (this.parent.getColumnByField(columnName).allowSorting === false || this.parent.isContextMenuOpen()) {\n return;\n }\n if (!gObj.allowMultiSorting) {\n isMultiSort = gObj.allowMultiSorting;\n }\n if (this.isActionPrevent()) {\n gObj.notify(events.preventBatch, {\n instance: this, handler: this.sortColumn,\n arg1: columnName, arg2: direction, arg3: isMultiSort\n });\n return;\n }\n this.backupSettings();\n this.columnName = columnName;\n this.direction = direction;\n this.isMultiSort = isMultiSort;\n this.removeSortIcons();\n var column = gObj.getColumnHeaderByField(columnName);\n this.updateSortedCols(columnName, isMultiSort);\n this.updateModel();\n };\n Sort.prototype.backupSettings = function () {\n this.lastSortedCols = iterateExtend(this.sortSettings.columns);\n this.lastCols = this.sortedColumns;\n };\n Sort.prototype.restoreSettings = function () {\n this.isModelChanged = false;\n this.isMultiSort = true;\n this.parent.setProperties({ sortSettings: { columns: this.lastSortedCols } }, true);\n //this.parent.sortSettings.columns = this.lastSortedCols; \n this.sortedColumns = this.lastCols;\n this.isModelChanged = true;\n };\n Sort.prototype.updateSortedCols = function (columnName, isMultiSort) {\n if (!isMultiSort) {\n if (this.parent.allowGrouping) {\n for (var i = 0, len = this.sortedColumns.length; i < len; i++) {\n if (this.parent.groupSettings.columns.indexOf(this.sortedColumns[i]) < 0) {\n this.sortedColumns.splice(i, 1);\n len--;\n i--;\n }\n }\n }\n else {\n this.sortedColumns.splice(0, this.sortedColumns.length);\n }\n }\n if (this.sortedColumns.indexOf(columnName) < 0) {\n this.sortedColumns.push(columnName);\n }\n };\n /**\n * @hidden\n */\n Sort.prototype.onPropertyChanged = function (e) {\n if (e.module !== this.getModuleName()) {\n return;\n }\n if (this.contentRefresh) {\n var args = this.sortSettings.columns.length ? {\n columnName: this.columnName, direction: this.direction, requestType: 'sorting', type: events.actionBegin\n } : { requestType: 'sorting', type: events.actionBegin, cancel: false };\n this.parent.notify(events.modelChanged, args);\n }\n this.refreshSortSettings();\n this.removeSortIcons();\n this.addSortIcons();\n };\n Sort.prototype.refreshSortSettings = function () {\n var _this = this;\n this.sortedColumns = [];\n this.sortSettings.columns.forEach(function (e) {\n _this.sortedColumns.push(e.field);\n });\n };\n /**\n * Clears all the sorted columns of the Grid.\n * @return {void}\n */\n Sort.prototype.clearSorting = function () {\n var cols = getActualPropFromColl(this.sortSettings.columns);\n if (this.isActionPrevent()) {\n this.parent.notify(events.preventBatch, { instance: this, handler: this.clearSorting });\n return;\n }\n for (var i = 0, len = cols.length; i < len; i++) {\n this.removeSortColumn(cols[i].field);\n }\n };\n Sort.prototype.isActionPrevent = function () {\n return isActionPrevent(this.parent);\n };\n /**\n * Remove sorted column by field name.\n * @param {string} field - Defines the column field name to remove sort.\n * @return {void}\n * @hidden\n */\n Sort.prototype.removeSortColumn = function (field) {\n var gObj = this.parent;\n var cols = this.sortSettings.columns;\n if (this.sortedColumns.indexOf(field) < 0) {\n return;\n }\n if (this.isActionPrevent()) {\n this.parent.notify(events.preventBatch, { instance: this, handler: this.removeSortColumn, arg1: field });\n return;\n }\n this.backupSettings();\n this.removeSortIcons();\n for (var i = 0, len = cols.length; i < len; i++) {\n if (cols[i].field === field) {\n if (gObj.allowGrouping && gObj.groupSettings.columns.indexOf(cols[i].field) > -1) {\n continue;\n }\n this.sortedColumns.splice(this.sortedColumns.indexOf(cols[i].field), 1);\n cols.splice(i, 1);\n this.isRemove = true;\n if (this.isModelChanged) {\n this.parent.notify(events.modelChanged, {\n requestType: 'sorting', type: events.actionBegin\n });\n }\n break;\n }\n }\n this.addSortIcons();\n };\n Sort.prototype.getSortedColsIndexByField = function (field, sortedColumns) {\n var cols = sortedColumns ? sortedColumns : this.sortSettings.columns;\n for (var i = 0, len = cols.length; i < len; i++) {\n if (cols[i].field === field) {\n return i;\n }\n }\n return -1;\n };\n /**\n * For internal use only - Get the module name.\n * @private\n */\n Sort.prototype.getModuleName = function () {\n return 'sort';\n };\n Sort.prototype.initialEnd = function () {\n this.parent.off(events.contentReady, this.initialEnd);\n if (this.parent.getColumns().length && this.sortSettings.columns.length) {\n var gObj = this.parent;\n this.contentRefresh = false;\n this.isMultiSort = this.sortSettings.columns.length > 1;\n for (var _i = 0, _a = gObj.sortSettings.columns; _i < _a.length; _i++) {\n var col = _a[_i];\n if (this.sortedColumns.indexOf(col.field) > -1) {\n this.sortColumn(col.field, col.direction, true);\n }\n }\n this.isMultiSort = false;\n this.contentRefresh = true;\n }\n };\n /**\n * @hidden\n */\n Sort.prototype.addEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.on(events.contentReady, this.initialEnd, this);\n this.parent.on(events.sortComplete, this.onActionComplete, this);\n this.parent.on(events.inBoundModelChanged, this.onPropertyChanged, this);\n this.parent.on(events.click, this.clickHandler, this);\n this.parent.on(events.headerRefreshed, this.refreshSortIcons, this);\n this.parent.on(events.keyPressed, this.keyPressed, this);\n this.parent.on(events.cancelBegin, this.cancelBeginEvent, this);\n };\n /**\n * @hidden\n */\n Sort.prototype.removeEventListener = function () {\n if (this.parent.isDestroyed) {\n return;\n }\n this.parent.off(events.sortComplete, this.onActionComplete);\n this.parent.off(events.inBoundModelChanged, this.onPropertyChanged);\n this.parent.off(events.click, this.clickHandler);\n this.parent.off(events.headerRefreshed, this.refreshSortIcons);\n this.parent.off(events.keyPressed, this.keyPressed);\n this.parent.off(events.cancelBegin, this.cancelBeginEvent);\n };\n /**\n * To destroy the sorting\n * @return {void}\n * @hidden\n */\n Sort.prototype.destroy = function () {\n this.isModelChanged = false;\n var gridElement = this.parent.element;\n if (!gridElement || (!gridElement.querySelector('.e-gridheader') && !gridElement.querySelector('.e-gridcontent'))) {\n return;\n }\n if (this.parent.element.querySelector('.e-gridpopup').querySelectorAll('.e-sortdirect').length) {\n this.parent.element.querySelector('.e-gridpopup').style.display = 'none';\n }\n this.clearSorting();\n this.isModelChanged = true;\n this.removeEventListener();\n };\n Sort.prototype.cancelBeginEvent = function (e) {\n if (e.requestType === 'sorting') {\n this.restoreSettings();\n this.refreshSortIcons();\n this.isMultiSort = true;\n }\n };\n Sort.prototype.clickHandler = function (e) {\n this.popUpClickHandler(e);\n var target = closest(e.target, '.e-headercell');\n if (target && !e.target.classList.contains('e-grptogglebtn') &&\n !e.target.classList.contains('e-stackedheadercell') &&\n !e.target.classList.contains('e-stackedheadercelldiv') &&\n !(target.classList.contains('e-resized')) &&\n !e.target.classList.contains('e-rhandler') &&\n !e.target.classList.contains('e-columnmenu') &&\n !e.target.classList.contains('e-filtermenudiv')) {\n var gObj = this.parent;\n var colObj = gObj.getColumnByUid(target.querySelector('.e-headercelldiv').getAttribute('e-mappinguid'));\n var direction = !target.querySelectorAll('.e-ascending').length ? 'Ascending' :\n 'Descending';\n if (colObj.type !== 'checkbox') {\n this.initiateSort(target, e, colObj);\n if (Browser.isDevice) {\n this.showPopUp(e);\n }\n }\n }\n if (target) {\n target.classList.remove('e-resized');\n }\n };\n Sort.prototype.keyPressed = function (e) {\n var ele = e.target;\n if (!this.parent.isEdit && (e.action === 'enter' || e.action === 'ctrlEnter' || e.action === 'shiftEnter')\n && closest(ele, '.e-headercell')) {\n var target = this.focus.getFocusedElement();\n if (isNullOrUndefined(target) || !target.classList.contains('e-headercell')\n || !target.querySelector('.e-headercelldiv')) {\n return;\n }\n var col = this.parent.getColumnByUid(target.querySelector('.e-headercelldiv').getAttribute('e-mappinguid'));\n this.initiateSort(target, e, col);\n }\n };\n Sort.prototype.initiateSort = function (target, e, column) {\n var gObj = this.parent;\n var field = column.field;\n var direction = !target.querySelectorAll('.e-ascending').length ? 'Ascending' :\n 'Descending';\n if (e.shiftKey || (this.sortSettings.allowUnsort && target.querySelectorAll('.e-descending').length)\n && !(gObj.groupSettings.columns.indexOf(field) > -1)) {\n this.removeSortColumn(field);\n }\n else {\n this.sortColumn(field, direction, e.ctrlKey || this.enableSortMultiTouch);\n }\n };\n Sort.prototype.showPopUp = function (e) {\n var target = closest(e.target, '.e-headercell');\n if (!isNullOrUndefined(target) || this.parent.isContextMenuOpen()) {\n setCssInGridPopUp(this.parent.element.querySelector('.e-gridpopup'), e, 'e-sortdirect e-icons e-icon-sortdirect' + (this.sortedColumns.length > 1 ? ' e-spanclicked' : ''));\n }\n };\n Sort.prototype.popUpClickHandler = function (e) {\n var target = e.target;\n if (closest(target, '.e-headercell') || e.target.classList.contains('e-rowcell') ||\n closest(target, '.e-gridpopup')) {\n if (target.classList.contains('e-sortdirect')) {\n if (!target.classList.contains('e-spanclicked')) {\n target.classList.add('e-spanclicked');\n this.enableSortMultiTouch = true;\n }\n else {\n target.classList.remove('e-spanclicked');\n this.enableSortMultiTouch = false;\n this.parent.element.querySelector('.e-gridpopup').style.display = 'none';\n }\n }\n }\n else {\n this.parent.element.querySelector('.e-gridpopup').style.display = 'none';\n }\n };\n Sort.prototype.addSortIcons = function () {\n var gObj = this.parent;\n var header;\n var filterElement;\n var cols = this.sortSettings.columns;\n var fieldNames = this.parent.getColumns().map(function (c) { return c.field; });\n for (var i = 0, len = cols.length; i < len; i++) {\n if (fieldNames.indexOf(cols[i].field) === -1) {\n continue;\n }\n header = gObj.getColumnHeaderByField(cols[i].field);\n this.aria.setSort(header, cols[i].direction);\n if (this.isMultiSort && cols.length > 1) {\n header.querySelector('.e-headercelldiv').insertBefore(this.parent.createElement('span', { className: 'e-sortnumber', innerHTML: (i + 1).toString() }), header.querySelector('.e-headertext'));\n }\n filterElement = header.querySelector('.e-sortfilterdiv');\n if (cols[i].direction === 'Ascending') {\n classList(filterElement, ['e-ascending', 'e-icon-ascending'], []);\n }\n else {\n classList(filterElement, ['e-descending', 'e-icon-descending'], []);\n }\n }\n };\n Sort.prototype.removeSortIcons = function (position) {\n var gObj = this.parent;\n var header;\n var cols = this.sortSettings.columns;\n var fieldNames = this.parent.getColumns().map(function (c) { return c.field; });\n for (var i = position ? position : 0, len = !isNullOrUndefined(position) ? position + 1 : cols.length; i < len; i++) {\n header = gObj.getColumnHeaderByField(cols[i].field);\n if (gObj.allowGrouping && gObj.groupSettings.columns.indexOf(cols[i].field) > -1 &&\n (isNullOrUndefined(header) || !header.querySelector('.e-sortfilterdiv'))) {\n continue;\n }\n if (fieldNames.indexOf(cols[i].field) === -1) {\n continue;\n }\n this.aria.setSort(header, 'none');\n classList(header.querySelector('.e-sortfilterdiv'), [], ['e-descending', 'e-icon-descending', 'e-ascending', 'e-icon-ascending']);\n if (header.querySelector('.e-sortnumber')) {\n header.querySelector('.e-headercelldiv').removeChild(header.querySelector('.e-sortnumber'));\n }\n }\n };\n Sort.prototype.getSortColumnFromField = function (field) {\n for (var i = 0, len = this.sortSettings.columns.length; i < len; i++) {\n if (this.sortSettings.columns[i].field === field) {\n return this.sortSettings.columns[i];\n }\n }\n return false;\n };\n Sort.prototype.updateAriaAttr = function () {\n var fieldNames = this.parent.getColumns().map(function (c) { return c.field; });\n for (var _i = 0, _a = this.sortedColumns; _i < _a.length; _i++) {\n var col = _a[_i];\n if (fieldNames.indexOf(col) === -1) {\n continue;\n }\n var header = this.parent.getColumnHeaderByField(col);\n this.aria.setSort(header, this.getSortColumnFromField(col).direction);\n }\n };\n Sort.prototype.refreshSortIcons = function () {\n this.removeSortIcons();\n this.isMultiSort = true;\n this.removeSortIcons();\n this.addSortIcons();\n this.isMultiSort = false;\n this.updateAriaAttr();\n };\n return Sort;\n}());\nexport { Sort };\n","import { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { EventHandler } from '@syncfusion/ej2-base';\nimport { classList, append } from '@syncfusion/ej2-base';\n/**\n * `NumericContainer` module handles rendering and refreshing numeric container.\n */\nvar NumericContainer = /** @class */ (function () {\n /**\n * Constructor for numericContainer module\n * @hidden\n */\n function NumericContainer(pagerModule) {\n this.pagerModule = pagerModule;\n }\n /**\n * The function is used to render numericContainer\n * @hidden\n */\n NumericContainer.prototype.render = function () {\n this.pagerElement = this.pagerModule.element;\n this.renderNumericContainer();\n this.refreshNumericLinks();\n this.wireEvents();\n };\n /**\n * Refreshes the numeric container of Pager.\n */\n NumericContainer.prototype.refresh = function () {\n this.pagerModule.updateTotalPages();\n if (this.links.length) {\n this.updateLinksHtml();\n }\n this.updateStyles();\n };\n /**\n * The function is used to refresh refreshNumericLinks\n * @hidden\n */\n NumericContainer.prototype.refreshNumericLinks = function () {\n var link;\n var pagerObj = this.pagerModule;\n var div = pagerObj.element.querySelector('.e-numericcontainer');\n var frag = document.createDocumentFragment();\n div.innerHTML = '';\n for (var i = 1; i <= pagerObj.pageCount; i++) {\n link = this.pagerModule.createElement('a', {\n className: 'e-link e-numericitem e-spacing e-pager-default',\n attrs: { role: 'link', tabindex: '-1', 'aria-label': 'Goto Page ' + i,\n href: 'javascript:void(0);', name: 'Goto page' + i }\n });\n if (pagerObj.currentPage === i) {\n classList(link, ['e-currentitem', 'e-active'], ['e-pager-default']);\n }\n frag.appendChild(link);\n }\n div.appendChild(frag);\n this.links = [].slice.call(div.childNodes);\n };\n /**\n * Binding events to the element while component creation\n * @hidden\n */\n NumericContainer.prototype.wireEvents = function () {\n EventHandler.add(this.pagerElement, 'click', this.clickHandler, this);\n };\n /**\n * Unbinding events from the element while component destroy\n * @hidden\n */\n NumericContainer.prototype.unwireEvents = function () {\n EventHandler.remove(this.pagerElement, 'click', this.clickHandler);\n };\n /**\n * To destroy the PagerMessage\n * @method destroy\n * @return {void}\n * @hidden\n */\n NumericContainer.prototype.destroy = function () {\n this.unwireEvents();\n };\n NumericContainer.prototype.renderNumericContainer = function () {\n this.element = this.pagerModule.createElement('div', {\n className: 'e-pagercontainer', attrs: { 'role': 'navigation' }\n });\n this.renderFirstNPrev(this.element);\n this.renderPrevPagerSet(this.element);\n this.element.appendChild(this.pagerModule.createElement('div', { className: 'e-numericcontainer' }));\n this.renderNextPagerSet(this.element);\n this.renderNextNLast(this.element);\n this.pagerModule.element.appendChild(this.element);\n };\n NumericContainer.prototype.renderFirstNPrev = function (pagerContainer) {\n this.first = this.pagerModule.createElement('div', {\n className: 'e-first e-icons e-icon-first',\n attrs: {\n title: this.pagerModule.getLocalizedLabel('firstPageTooltip'),\n 'aria-label': this.pagerModule.getLocalizedLabel('firstPageTooltip'),\n tabindex: '-1'\n }\n });\n this.prev = this.pagerModule.createElement('div', {\n className: 'e-prev e-icons e-icon-prev',\n attrs: {\n title: this.pagerModule.getLocalizedLabel('previousPageTooltip'),\n 'aria-label': this.pagerModule.getLocalizedLabel('previousPageTooltip'),\n tabindex: '-1'\n }\n });\n append([this.first, this.prev], pagerContainer);\n };\n NumericContainer.prototype.renderPrevPagerSet = function (pagerContainer) {\n var prevPager = this.pagerModule.createElement('div');\n this.PP = this.pagerModule.createElement('a', {\n className: 'e-link e-pp e-spacing', innerHTML: '...',\n attrs: {\n title: this.pagerModule.getLocalizedLabel('previousPagerTooltip'), role: 'link',\n 'aria-label': this.pagerModule.getLocalizedLabel('previousPagerTooltip'),\n tabindex: '-1',\n name: this.pagerModule.getLocalizedLabel('previousPagerTooltip'),\n href: 'javascript:void(0);'\n }\n });\n prevPager.appendChild(this.PP);\n pagerContainer.appendChild(prevPager);\n };\n NumericContainer.prototype.renderNextPagerSet = function (pagerContainer) {\n var nextPager = this.pagerModule.createElement('div');\n this.NP = this.pagerModule.createElement('a', {\n className: 'e-link e-np e-spacing',\n innerHTML: '...', attrs: {\n title: this.pagerModule.getLocalizedLabel('nextPagerTooltip'), role: 'link',\n 'aria-label': this.pagerModule.getLocalizedLabel('nextPagerTooltip'),\n tabindex: '-1',\n name: this.pagerModule.getLocalizedLabel('nextPagerTooltip'),\n href: 'javascript:void(0);'\n }\n });\n nextPager.appendChild(this.NP);\n pagerContainer.appendChild(nextPager);\n };\n NumericContainer.prototype.renderNextNLast = function (pagerContainer) {\n this.next = this.pagerModule.createElement('div', {\n className: 'e-next e-icons e-icon-next',\n attrs: {\n title: this.pagerModule.getLocalizedLabel('nextPageTooltip'),\n 'aria-label': this.pagerModule.getLocalizedLabel('nextPageTooltip'),\n tabindex: '-1'\n }\n });\n this.last = this.pagerModule.createElement('div', {\n className: 'e-last e-icons e-icon-last',\n attrs: {\n title: this.pagerModule.getLocalizedLabel('lastPageTooltip'),\n 'aria-label': this.pagerModule.getLocalizedLabel('lastPageTooltip'),\n tabindex: '-1'\n }\n });\n append([this.next, this.last], pagerContainer);\n };\n NumericContainer.prototype.clickHandler = function (e) {\n var pagerObj = this.pagerModule;\n var target = e.target;\n pagerObj.previousPageNo = pagerObj.currentPage;\n if (!target.classList.contains('e-disable') && !isNullOrUndefined(target.getAttribute('index'))) {\n pagerObj.currentPage = parseInt(target.getAttribute('index'), 10);\n pagerObj.dataBind();\n }\n return false;\n };\n NumericContainer.prototype.updateLinksHtml = function () {\n var pagerObj = this.pagerModule;\n var currentPageSet;\n var pageNo;\n pagerObj.currentPage = pagerObj.totalPages === 1 ? 1 : pagerObj.currentPage;\n if (pagerObj.currentPage > pagerObj.totalPages && pagerObj.totalPages) {\n pagerObj.currentPage = pagerObj.totalPages;\n }\n currentPageSet = parseInt((pagerObj.currentPage / pagerObj.pageCount).toString(), 10);\n if (pagerObj.currentPage % pagerObj.pageCount === 0 && currentPageSet > 0) {\n currentPageSet = currentPageSet - 1;\n }\n for (var i = 0; i < pagerObj.pageCount; i++) {\n pageNo = (currentPageSet * pagerObj.pageCount) + 1 + i;\n if (pageNo <= pagerObj.totalPages) {\n this.links[i].style.display = '';\n this.links[i].setAttribute('index', pageNo.toString());\n this.links[i].innerHTML = !pagerObj.customText ? pageNo.toString() : pagerObj.customText + pageNo;\n if (pagerObj.currentPage !== pageNo) {\n this.links[i].classList.add('e-pager-default');\n }\n else {\n this.links[i].classList.remove('e-pager-default');\n }\n }\n else {\n this.links[i].innerHTML = !pagerObj.customText ? pageNo.toString() : pagerObj.customText + pageNo;\n this.links[i].style.display = 'none';\n }\n classList(this.links[i], [], ['e-currentitem', 'e-active']);\n }\n this.first.setAttribute('index', '1');\n this.last.setAttribute('index', pagerObj.totalPages.toString());\n this.prev.setAttribute('index', (pagerObj.currentPage - 1).toString());\n this.next.setAttribute('index', (pagerObj.currentPage + 1).toString());\n this.pagerElement.querySelector('.e-mfirst').setAttribute('index', '1');\n this.pagerElement.querySelector('.e-mlast').setAttribute('index', pagerObj.totalPages.toString());\n this.pagerElement.querySelector('.e-mprev').setAttribute('index', (pagerObj.currentPage - 1).toString());\n this.pagerElement.querySelector('.e-mnext').setAttribute('index', (pagerObj.currentPage + 1).toString());\n this.PP.setAttribute('index', (parseInt(this.links[0].getAttribute('index'), 10) - pagerObj.pageCount).toString());\n this.NP.setAttribute('index', (parseInt(this.links[this.links.length - 1].getAttribute('index'), 10) + 1).toString());\n };\n NumericContainer.prototype.updateStyles = function () {\n this.updateFirstNPrevStyles();\n this.updatePrevPagerSetStyles();\n this.updateNextPagerSetStyles();\n this.updateNextNLastStyles();\n if (this.links.length) {\n classList(this.links[(this.pagerModule.currentPage - 1) % this.pagerModule.pageCount], ['e-currentitem', 'e-active'], []);\n }\n };\n NumericContainer.prototype.updateFirstNPrevStyles = function () {\n var firstPage = ['e-firstpage', 'e-pager-default'];\n var firstPageDisabled = ['e-firstpagedisabled', 'e-disable'];\n var prevPage = ['e-prevpage', 'e-pager-default'];\n var prevPageDisabled = ['e-prevpagedisabled', 'e-disable'];\n if (this.pagerModule.totalPages > 0 && this.pagerModule.currentPage > 1) {\n classList(this.prev, prevPage, prevPageDisabled);\n classList(this.first, firstPage, firstPageDisabled);\n classList(this.pagerElement.querySelector('.e-mfirst'), firstPage, firstPageDisabled);\n classList(this.pagerElement.querySelector('.e-mprev'), prevPage, prevPageDisabled);\n }\n else {\n classList(this.prev, prevPageDisabled, prevPage);\n classList(this.first, firstPageDisabled, firstPage);\n classList(this.pagerElement.querySelector('.e-mprev'), prevPageDisabled, prevPage);\n classList(this.pagerElement.querySelector('.e-mfirst'), firstPageDisabled, firstPage);\n }\n };\n NumericContainer.prototype.updatePrevPagerSetStyles = function () {\n if (this.pagerModule.currentPage > this.pagerModule.pageCount) {\n classList(this.PP, ['e-numericitem', 'e-pager-default'], ['e-nextprevitemdisabled', 'e-disable']);\n }\n else {\n classList(this.PP, ['e-nextprevitemdisabled', 'e-disable'], ['e-numericitem', 'e-pager-default']);\n }\n };\n NumericContainer.prototype.updateNextPagerSetStyles = function () {\n var pagerObj = this.pagerModule;\n var firstPage = this.links[0].innerHTML.replace(pagerObj.customText, '');\n if (!firstPage.length || !this.links.length || (parseInt(firstPage, 10) + pagerObj.pageCount > pagerObj.totalPages)) {\n classList(this.NP, ['e-nextprevitemdisabled', 'e-disable'], ['e-numericitem', 'e-pager-default']);\n }\n else {\n classList(this.NP, ['e-numericitem', 'e-pager-default'], ['e-nextprevitemdisabled', 'e-disable']);\n }\n };\n NumericContainer.prototype.updateNextNLastStyles = function () {\n var lastPage = ['e-lastpage', 'e-pager-default'];\n var lastPageDisabled = ['e-lastpagedisabled', 'e-disable'];\n var nextPage = ['e-nextpage', 'e-pager-default'];\n var nextPageDisabled = ['e-nextpagedisabled', 'e-disable'];\n var pagerObj = this.pagerModule;\n if (pagerObj.currentPage === pagerObj.totalPages || pagerObj.totalRecordsCount === 0) {\n classList(this.last, lastPageDisabled, lastPage);\n classList(this.next, nextPageDisabled, nextPage);\n classList(this.pagerElement.querySelector('.e-mlast'), lastPageDisabled, lastPage);\n classList(this.pagerElement.querySelector('.e-mnext'), nextPageDisabled, nextPage);\n }\n else {\n classList(this.last, lastPage, lastPageDisabled);\n classList(this.next, nextPage, nextPageDisabled);\n classList(this.pagerElement.querySelector('.e-mlast'), lastPage, lastPageDisabled);\n classList(this.pagerElement.querySelector('.e-mnext'), nextPage, nextPageDisabled);\n }\n };\n return NumericContainer;\n}());\nexport { NumericContainer };\n","import { append } from '@syncfusion/ej2-base';\n/**\n * `PagerMessage` module is used to display pager information.\n */\nvar PagerMessage = /** @class */ (function () {\n /**\n * Constructor for externalMessage module\n * @hidden\n */\n function PagerMessage(pagerModule) {\n this.pagerModule = pagerModule;\n }\n /**\n * The function is used to render pager message\n * @hidden\n */\n PagerMessage.prototype.render = function () {\n var div = this.pagerModule\n .createElement('div', { className: 'e-parentmsgbar', attrs: { 'aria-label': 'Pager Information' } });\n this.pageNoMsgElem = this.pagerModule.createElement('span', { className: 'e-pagenomsg', styles: 'textalign:right' });\n this.pageCountMsgElem = this.pagerModule.createElement('span', { className: 'e-pagecountmsg', styles: 'textalign:right' });\n append([this.pageNoMsgElem, this.pageCountMsgElem], div);\n this.pagerModule.element.appendChild(div);\n this.refresh();\n };\n /**\n * Refreshes the pager information.\n */\n PagerMessage.prototype.refresh = function () {\n var pagerObj = this.pagerModule;\n this.pageNoMsgElem.textContent = this.format(pagerObj.getLocalizedLabel('currentPageInfo'), [pagerObj.totalRecordsCount === 0 ? 0 :\n pagerObj.currentPage, pagerObj.totalPages || 0]) + ' ';\n this.pageCountMsgElem.textContent = this.format(pagerObj.getLocalizedLabel('totalItemsInfo'), [pagerObj.totalRecordsCount || 0]);\n this.pageNoMsgElem.parentElement.setAttribute('aria-label', this.pageNoMsgElem.textContent + this.pageCountMsgElem.textContent);\n };\n /**\n * Hides the Pager information.\n */\n PagerMessage.prototype.hideMessage = function () {\n if (this.pageNoMsgElem) {\n this.pageNoMsgElem.style.display = 'none';\n }\n if (this.pageCountMsgElem) {\n this.pageCountMsgElem.style.display = 'none';\n }\n };\n /**\n * Shows the Pager information.\n */\n PagerMessage.prototype.showMessage = function () {\n if (!this.pageNoMsgElem) {\n this.render();\n }\n this.pageNoMsgElem.style.display = '';\n this.pageCountMsgElem.style.display = '';\n };\n /**\n * To destroy the PagerMessage\n * @method destroy\n * @return {void}\n * @hidden\n */\n PagerMessage.prototype.destroy = function () {\n //destroy\n };\n PagerMessage.prototype.format = function (str, args) {\n var regx;\n for (var i = 0; i < args.length; i++) {\n regx = new RegExp('\\\\{' + (i) + '\\\\}', 'gm');\n str = str.replace(regx, args[i].toString());\n }\n return str;\n };\n return PagerMessage;\n}());\nexport { PagerMessage };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nimport { Component, L10n, Browser } from '@syncfusion/ej2-base';\nimport { compile as templateCompiler } from '@syncfusion/ej2-base';\nimport { isNullOrUndefined } from '@syncfusion/ej2-base';\nimport { Property, Event, NotifyPropertyChanges } from '@syncfusion/ej2-base';\nimport { NumericContainer } from './numeric-container';\nimport { PagerMessage } from './pager-message';\nimport { appendChildren } from '../grid/base/util';\n/**\n * Represents the `Pager` component.\n * ```html\n *