@mescius/wijmo.grid.sheet 5.20232.939

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015-esm.js ADDED
@@ -0,0 +1,14 @@
1
+ /*!
2
+ *
3
+ * Wijmo Library 5.20232.939
4
+ * https://developer.mescius.com/wijmo
5
+ *
6
+ * Copyright(c) MESCIUS inc. All rights reserved.
7
+ *
8
+ * Licensed under the End-User License Agreement For MESCIUS Wijmo Software.
9
+ * us.sales@mescius.com
10
+ * https://developer.mescius.com/wijmo/licensing
11
+ *
12
+ */
13
+
14
+ import{isBoolean,isInt,isString,CollectionView,DataType,Point,SortDescription,ObservableArray,Control,addClass,removeClass,hasClass,culture,Event,EventArgs,PropertyChangedEventArgs,isNumber,tryCast,isNullOrWhiteSpace,toggleClass,setSelectionRange,removeChild,NotifyCollectionChangedEventArgs,NotifyCollectionChangedAction,Key,CancelEventArgs,Globalize,isDate,escapeRegExp,enable,asString,changeType,closest,showPopup,asType,CollectionViewGroup,contains,setCss,isPrimitive,escapeHtml,Clipboard,Tooltip,Color,isObject,isArray,isFirefox,asNumber,asInt,assert,toHeaderCase,_deprecated,_addCultureInfo,asBoolean,asEnum,Aggregate,_getModule,_registerModule}from"@mescius/wijmo";import{Row,Column,CellRange,GridPanel,SelectionMode,FlexGrid,GroupRow,CellEditEndingEventArgs,CellRangeEventArgs,_NewRowTemplate,HitTestInfo,CellFactory,CellType,DataMapEditor,RowColFlags,_SelectionHandler,HeadersVisibility,AllowDragging,AllowResizing,AllowSorting,KeyAction,SelectedState}from"@mescius/wijmo.grid";import{ColumnFilter,FilterType,ValueFilter,ConditionFilter,ValueFilterEditor,ColumnFilterEditor,FlexGridFilter}from"@mescius/wijmo.grid.filter";import{Menu}from"@mescius/wijmo.input";import{Workbook}from"@mescius/wijmo.xlsx";import{FlexGridXlsxConverter,_blobToBuffer}from"@mescius/wijmo.grid.xlsx";import*as mInput from"@mescius/wijmo.input";import*as mXlsx from"@mescius/wijmo.xlsx";import*as selfModule from"@mescius/wijmo.grid.sheet";export function softInput(){return _getModule("wijmo.input")}export function softXlsx(){return _getModule("wijmo.xlsx")}export var _ErrorMessages={InvalidCellRef:"Invalid cell reference.",InvalidSheetRef:"Invalid sheet reference.",InvalidTableRef:"Invalid table reference.",InvalidTableColRef:"Invalid table column reference.",InvalidParameters:"Invalid parameters.",BadExpression:"Bad expression.",CircRef:"Circular reference.",InvalidParameter:e=>`Invalid parameter: "${e}".`,ParameterIsOutOfRange:e=>`Parameter is out of range: "${e}".`,RowIsOutOfTableRange:e=>`The row is out of the table (${e}) range.`,UnkFuncName:e=>`The function "${e}" has not supported in FlexSheet yet.`,DefNameInvalidSheet:e=>`The defined name item works in "${e}". It does not work in current sheet.`,InvalidTable:e=>`The Table(${e}) is not located in any sheet.`,InvalidExpression:e=>`Invalid Expression: ${e}`,Atan2ArgsLessThanZero:"The x number and y number can't both be zero for the atan2 function.",RateCriteriaFails:"It is not able to calculate the rate with current parameters.",RangesMustBeTheSame:"The row span and column span of each cell range has to be same with each other.",TooFewParameters:"Too few parameters.",TooManyParameters:"Too many parameters.",ExpressionExpected:"Expression expected.",UnbalancedParenthesis:"Unbalanced parenthesis.",UnbalancedSquareBrackets:"Unbalanced square brackets.",TableReferencesExpected:"Table references expected.",IdentifierExpected:"Identifier expected.",CantFindFinalQuote:"Can't find final quote.",IllegalCrossSheetReference:"Illegal cross sheet reference.",CantFindFinalDateDelimiter:'Can\'t find final date delimiter ("#").',CellRefMustBeInSameSheet:"The cell reference must be in the same sheet.",SyntaxError:"Syntax error."};var _KnownErrors;!function(e){e.Div="#DIV/0!";e.Name="#NAME?";e.Ref="#REF!";e.Num="#NUM!";e.Val="#VALUE!";e.Null="#NULL!";e.NA="#N/A"}(_KnownErrors||(_KnownErrors={}));export class FormulaError{constructor(e,t){this._error=e;this._data=t}get error(){return this._error}get data(){return this._data}toString(){return this._error||(this._data||"").toString()}}export class DivideByZeroError extends FormulaError{constructor(e){super(_KnownErrors.Div,e)}}export class NameError extends FormulaError{constructor(e){super(_KnownErrors.Name,e)}}export class ReferenceError extends FormulaError{constructor(e){super(_KnownErrors.Ref,e)}}export class NumericError extends FormulaError{constructor(e){super(_KnownErrors.Num,e)}}export class ValueError extends FormulaError{constructor(e){super(_KnownErrors.Val,e)}}export class NotAvailableError extends FormulaError{constructor(e){super(_KnownErrors.NA,e)}}export class NullError extends FormulaError{constructor(e){super(_KnownErrors.Null,e)}}export class UnknownError extends FormulaError{constructor(e){super("",e)}}export class SyntaxError extends FormulaError{constructor(e){super("#SYNTAX",e)}}export class _FormulaErrorHelper{static asError(e){return e instanceof FormulaError?e:"string"==typeof e?this.fromString(e):null}static fromString(e){e=e.toUpperCase();if(this._errTypeMap[e])switch(e){case _KnownErrors.Div:return new DivideByZeroError;case _KnownErrors.Name:return new NameError;case _KnownErrors.NA:return new NotAvailableError;case _KnownErrors.Null:return new NullError;case _KnownErrors.Num:return new NumericError;case _KnownErrors.Ref:return new ReferenceError;case _KnownErrors.Val:return new ValueError}return null}}_FormulaErrorHelper._errTypeMap=(()=>{var e={};Object.keys(_KnownErrors).forEach(t=>e[_KnownErrors[t]]=1);return e})();export class Table{constructor(e,t,i,o,l){this._showHeaderRow=!0;this._showTotalRow=!1;this._showBandedColumns=!1;this._showBandedRows=!0;this._alterFirstColumn=!1;this._alterLastColumn=!1;this._orgHeaderCellsContent=[];if(!t.isValid)throw"The range of this table is invalid.";this._name=e;this._range=t.clone();this._style=i;null!=o&&o.length>0&&this._pushTableColumns(o);if(null!=l){null!=l.showHeaderRow&&(this._showHeaderRow=l.showHeaderRow);null!=l.showTotalRow&&(this._showTotalRow=l.showTotalRow);null!=l.showBandedColumns&&(this._showBandedColumns=l.showBandedColumns);null!=l.showBandedRows&&(this._showBandedRows=l.showBandedRows);null!=l.alterFirstColumn&&(this._alterFirstColumn=l.alterFirstColumn);null!=l.alterLastColumn&&(this._alterLastColumn=l.alterLastColumn)}}get name(){return this._name}set name(e){if(null==e||""===e)throw"The name of the Table should not be empty.";if(this._name.toLowerCase()!==e.toLowerCase()){let t=this._name;this._name=e;if(this._owner){let i;!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(i=new _TableSettingAction(this._owner,this));this._owner._updateFormulasWithNameUpdating(t,e,!0);if(i){i.saveNewState();this._owner.undoStack._addAction(i);i=null}}}}get sheet(){return this._sheet}get style(){return this._style}set style(e){if(e.name!==this._style.name){let t;this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this));this._style=e;if(this._owner){if(t){t.saveNewState();this._owner.undoStack._addAction(t);t=null}this._owner.refresh()}}}get showHeaderRow(){return this._showHeaderRow}set showHeaderRow(e){if(e!==this._showHeaderRow){let t,i=this._showHeaderRow;this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this));this._showHeaderRow=e;if(this._owner)try{this._owner.beginUpdate();this._adjustTableRangeWithHeaderRow();if(t){t.saveNewState();this._owner.undoStack._addAction(t)}}catch(e){this._showHeaderRow=i;throw e}finally{t=null;this._owner.endUpdate()}}}get showTotalRow(){return this._showTotalRow}set showTotalRow(e){if(e!==this._showTotalRow){let t,i=this._showTotalRow;this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this));this._showTotalRow=e;if(this._owner)try{this._owner.beginUpdate();this._adjustTableRangeWithTotalRow();if(t){t.saveNewState();this._owner.undoStack._addAction(t)}}catch(e){this._showTotalRow=i;throw e}finally{t=null;this._owner.endUpdate()}}}get showBandedColumns(){return this._showBandedColumns}set showBandedColumns(e){if(e!==this._showBandedColumns){let t;this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this));this._showBandedColumns=e;if(this._owner){if(t){t.saveNewState();this._owner.undoStack._addAction(t);t=null}this._owner.refresh()}}}get showBandedRows(){return this._showBandedRows}set showBandedRows(e){if(e!==this._showBandedRows){let t;this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this));this._showBandedRows=e;if(this._owner){if(t){t.saveNewState();this._owner.undoStack._addAction(t);t=null}this._owner.refresh()}}}get alterFirstColumn(){return this._alterFirstColumn}set alterFirstColumn(e){if(e!==this._alterFirstColumn){let t;this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this));this._alterFirstColumn=e;if(this._owner){if(t){t.saveNewState();this._owner.undoStack._addAction(t);t=null}this._owner.refresh()}}}get alterLastColumn(){return this._alterLastColumn}set alterLastColumn(e){if(e!==this._alterLastColumn){let t;this._owner&&!this._owner._isUndoing&&this._owner.undoStack.stackSize>0&&(t=new _TableSettingAction(this._owner,this));this._alterLastColumn=e;if(this._owner){if(t){t.saveNewState();this._owner.undoStack._addAction(t);t=null}this._owner.refresh()}}}_isHeaderRow(e){return this._showHeaderRow&&e===this._range.topRow}_getTableRange(){return this._range}_getColumns(){return this._columns||[]}getRange(e=TableSection.All,t){let i;switch(e){case TableSection.Data:i=this._getDataRange();break;case TableSection.Header:i=this._getHeaderRange();break;case TableSection.Footer:i=this._getFooterRange();break;default:i=this._range.clone()}if(null!=t&&i){let e=this._getColumnIndex(t);if(null==e)return null;i.col=i.col2=i.leftCol+e}return i}getColumns(){return this._columns?this._columns.slice():[]}insertRows(e,t,i=!0){let o=!1;null==t&&(t=1);if(!isInt(t)||t<1)return!1;if(0===e&&this._showHeaderRow||e===this._range.rowSpan-1&&this._showTotalRow||e<0||e>=this._range.rowSpan)return!1;if(this._owner){let l=this.getRange(),s=this._flex;this._owner.beginUpdate();if(i){let e=new CellRange(l.bottomRow+1,l.col,l.bottomRow+1,l.col2);if(this._sheet._canShiftCells(e)){let i=this._sheet._needAddRowCountForInsertTableRows(t,l);if(s.collectionView){let e=s.itemsSource instanceof CollectionView;s.collectionView.beginUpdate();for(let t=0;t<i;t++)e?s.itemsSource.sourceCollection.push({}):s.itemsSource.push({});s.collectionView.endUpdate(!0)}else for(let e=0;e<i;e++)s.rows.push(new Row);this._sheet._moveDownCells(t,e);o=!0}}else this._canInsertRowsWithoutShift(t)&&(o=!0);if(o){this._sheet._moveDownCellsWithinTable(e,t,l);this._updateTableRange(0,t,0,0)}this._owner.endUpdate()}else{this._updateTableRange(0,t,0,0);o=!0}return o}deleteRows(e,t,i=!0){null==t&&(t=1);if(isInt(t)&&!(t<1)&&!(0===e&&this._showHeaderRow||e===this._range.rowSpan-1&&this._showTotalRow||e<0||e>=this._range.rowSpan||e+t>this._range.rowSpan-(this._showTotalRow?1:0)))if(this._owner){let o,l=!1,s=this.getRange();this._owner.beginUpdate();if(i){o=new CellRange(s.bottomRow+1,s.col,s.bottomRow+1,s.col2);this._sheet._canShiftCells(o)&&(l=!0)}else l=!0;if(l){this._sheet._moveUpCellsWithinTable(e,t,s);i&&this._sheet._moveUpCells(t,o);this._updateTableRange(0,-t,0,0)}this._owner.endUpdate()}else this._updateTableRange(0,-t,0,0)}_addColumn(e,t){if(e<=0||e>this._columns.length)throw"The column index is out of range.";t=this._getUniqueColumnName(e,t);let i=new TableColumn(t);i._attach(this);this._columns.splice(e,0,i);if(this.showHeaderRow&&this._owner&&this._sheet){let i=this.getRange();this._flex.setCellData(i.topRow,i.leftCol+e,t)}}_updateCell(e,t,i){if(null==this._style)return;let o=e-this._range.topRow,l=t-this._range.leftCol,s=this._getTableCellAppliedStyles(o,l);this._applyStylesForCell(s,i)}_updateTableRange(e,t,i,o){if(this._range.row<=this._range.row2){this._range.row+=e;this._range.row2+=t}else{this._range.row2+=e;this._range.row+=t}if(this._range.col<=this._range.col2){this._range.col+=i;this._range.col2+=o}else{this._range.col2+=i;this._range.col+=o}}_setTableRange(e,t){this._range=e;if(null!=t){this._columns.splice(0,this._columns.length);for(let e=0;e<t.length;e++)this._columns.push(t[e])}}_updateColumnName(e,t,i=!0){let o=this._columns[e];if(!o||!o.name||o.name!==t){t=this._getUniqueColumnName(null,t);o.name=t;if(this._showHeaderRow&&this._owner&&this._sheet&&i){this._flex.setCellData(this._range.topRow,this._range.leftCol+e,t)}}}_updateColumnTotalRowContent(e,t){null==t&&(t=this._columns.indexOf(e));if(t<0)return;let i;if(e.totalRowFunction){let t=this._getSubtotalFunction(e.totalRowFunction.toLowerCase());i=null!=t?"=subtotal("+t+",["+e.name+"])":"="===e.totalRowFunction[0]?e.totalRowFunction:"="+e.totalRowFunction}else if(0===t){e.totalRowLabel||(e.totalRowLabel="Total");i=e.totalRowLabel}else i=e.totalRowLabel;if(this._owner&&this._sheet){this._flex.setCellData(this._range.bottomRow,this._range.leftCol+t,i,!1)}}_attachSheet(e){if(this._sheet&&this._owner)return;this._sheet=e;this._owner=e._owner;if(null==this._owner)return;if(this._owner._containsMergedCells(this._range,e))throw"Table does not allow the merged cell within the table.";let t=this.getRange();null==this._style&&(this._style=this._owner.getBuiltInTableStyle("TableStyleMedium9"));null!=this._columns&&0!==this._columns.length||this._generateColumns(this._showHeaderRow);try{this._owner.beginUpdate();this._showHeaderRow&&1===t.rowSpan&&this._adjustTableRangeWithHeaderRow();this._showTotalRow&&this._updateTotalRow()}finally{this._attached=!0;this._owner.endUpdate()}}_detachSheet(){this._attached=!1;this._sheet=null;this._owner=null}get _flex(){return this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid}_pushTableColumns(e){this._columns=[];for(let t=0;t<e.length;t++){let i=e[t];i._attach(this);this._columns.push(i)}}_generateColumns(e){if(!this._range.isValid)throw"The range of the table is invalid.";this._columns=[];for(let t=0;t<this._range.columnSpan;t++){let i,o,l=null,s=this._sheet.grid.columns[this._range.leftCol+t],n=this._range.topRow*this._sheet.grid.columns.length+this._range.leftCol+t,r=this._flex;if(1===this._range.rowSpan)i=this._getUniqueColumnName(t+1);else{null==(i=l=this._sheet.grid.getCellData(this._range.topRow,this._range.leftCol+t,!1))&&(i="");_isFormula(i)&&(i=this._owner.evaluate(i,"",this._sheet,!1));o=this._sheet._styledCells[n];let e=this._owner._formatEvaluatedResult(i,s,o?o.format:"");null!=i&&""==e||(i=e);i=this._getUniqueColumnName(t+1,i.toString())}if(e&&this._range.rowSpan>1){this._orgHeaderCellsContent[t]=this._sheet.grid.getCellData(this._range.topRow,this._range.leftCol+t,!1);isNaN(+i)||s.format||o&&o.format||(o?o.format="@":this._sheet._styledCells[n]={format:"@"});r.setCellData(this._range.topRow,this._range.leftCol+t,s.dataType===DataType.Boolean&&isBoolean(l)?l:i,!1)}let a=new TableColumn(i);a._attach(this);0===t?a._totalRowLabel="Total":t===this._range.columnSpan-1&&(a._totalRowFunction="Sum");this._columns.push(a)}}_getTableCellAppliedStyles(e,t){let i={},o=0,l=!1,s=!1;this._showHeaderRow&&(o=1);this._showHeaderRow&&0===e?l=!0:this._showTotalRow&&e===this._range.rowSpan-1&&(s=!0);this._extendStyle(i,this._style.wholeTableStyle,e,t,l,s);if(!l&&!s){if(this._showBandedColumns&&(null!=this._style.firstBandedColumnStyle||null!=this._style.secondBandedColumnStyle)){let o,n;t%((o=this._style.firstBandedColumnStyle?null==this._style.firstBandedColumnStyle.size?1:this._style.firstBandedColumnStyle.size:1)+(n=this._style.secondBandedColumnStyle?null==this._style.secondBandedColumnStyle.size?1:this._style.secondBandedColumnStyle.size:1))>=o?this._style.secondBandedColumnStyle&&this._extendStyle(i,this._style.secondBandedRowStyle,e,t,l,s):this._style.firstBandedColumnStyle&&this._extendStyle(i,this._style.firstBandedColumnStyle,e,t,l,s)}if(this._showBandedRows&&(null!=this._style.firstBandedRowStyle||null!=this._style.secondBandedRowStyle)){let n,r;(e-o)%((n=this._style.firstBandedRowStyle?null==this._style.firstBandedRowStyle.size?1:this._style.firstBandedRowStyle.size:1)+(r=this._style.secondBandedRowStyle?null==this._style.secondBandedRowStyle.size?1:this._style.secondBandedRowStyle.size:1))>=n?this._style.secondBandedRowStyle&&this._extendStyle(i,this._style.secondBandedRowStyle,e,t,l,s):this._style.firstBandedRowStyle&&this._extendStyle(i,this._style.firstBandedRowStyle,e,t,l,s)}}this._alterLastColumn&&t===this._range.columnSpan-1&&this._style.lastColumnStyle&&this._extendStyle(i,this._style.lastColumnStyle,e,t,l,s);this._alterFirstColumn&&0===t&&this._style.firstColumnStyle&&this._extendStyle(i,this._style.firstColumnStyle,e,t,l,s);if(l){this._style.headerRowStyle&&this._extendStyle(i,this._style.headerRowStyle,e,t,l,s);t===this._range.columnSpan-1&&this._style.lastHeaderCellStyle&&this._extendStyle(i,this._style.lastHeaderCellStyle,e,t,l,s);0===t&&this._style.firstHeaderCellStyle&&this._extendStyle(i,this._style.firstHeaderCellStyle,e,t,l,s)}else if(s){this._style.totalRowStyle&&this._extendStyle(i,this._style.totalRowStyle,e,t,l,s);t===this._range.columnSpan-1&&this._style.lastTotalCellStyle&&this._extendStyle(i,this._style.lastTotalCellStyle,e,t,l,s);0===t&&this._style.firstTotalCellStyle&&this._extendStyle(i,this._style.firstTotalCellStyle,e,t,l,s)}return i}_applyStylesForCell(e,t){let i=t.style;for(let t in e){let o=e[t];o&&(i[t]=o)}}_extendStyle(e,t,i,o,l,s){for(let n in t){let r=t[n];null!==r&&(n.indexOf("borderTop")>-1?(0===i||s)&&(e[n]=r):n.indexOf("borderBottom")>-1?(i===this._range.rowSpan-1||l)&&(e[n]=r):n.indexOf("borderLeft")>-1?0===o&&(e[n]=r):n.indexOf("borderRight")>-1?o===this._range.columnSpan-1&&(e[n]=r):n.indexOf("borderHorizontal")>-1?i<this._range.rowSpan-1&&("borderHorizontalStyle"===n?e.borderBottomStyle=r:"borderHorizontalWidth"===n?e.borderBottomWidth=r:e.borderBottomColor=r):n.indexOf("borderVertical")>-1?o<this._range.columnSpan-1&&("borderVerticalStyle"===n?e.borderRightStyle=r:"borderVerticalWidth"===n?e.borderRightWidth=r:e.borderRightColor=r):e[n]=r)}}_getSubtotalFunction(e){switch(e){case"average":return"101";case"countnums":return"102";case"count":return"103";case"max":return"104";case"min":return"105";case"stddev":return"107";case"sum":return"109";case"var":return"110"}return null}_checkColumnNameExist(e){let t=this.getColumns();for(let i=0;i<t.length;i++){if(t[i].name.toLowerCase()===e.toLowerCase())return!0}return!1}_adjustTableRangeWithHeaderRow(){let e=this._flex;if(this._showHeaderRow){if(this._sheet._needMoveDownTable(this)){let t=this.getRange(),i=new CellRange(t.bottomRow+1,t.col,t.bottomRow+1,t.col2);if(!this._sheet._canShiftCells(i))throw"The operation is not allowed. The operation is attempting to shift the cells in a table or a merged cell on the current sheet.";if(1===this._sheet._needAddRowCountForInsertTableRows(1,t))if(e.collectionView){e.collectionView.beginUpdate();e.itemsSource instanceof CollectionView?e.itemsSource.sourceCollection.push({}):e.itemsSource.push({});e.collectionView.endUpdate(!0)}else e.rows.push(new Row);this._sheet._moveDownCells(1,i);this._sheet._moveDownTable(this)}this._range.row<=this._range.row2?this._range.row-=1:this._range.row2-=1;for(let t=0;t<this._columns.length;t++){let i=this._columns[t];this._orgHeaderCellsContent[t]=e.getCellData(this._range.topRow,this._range.leftCol+t,!1);e.setCellData(this._range.topRow,this._range.leftCol+t,i.name)}}else{for(let t=this._range.leftCol;t<=this._range.rightCol;t++)e.setCellData(this._range.topRow,t,"");this._range.row<=this._range.row2?this._range.row+=1:this._range.row2+=1}}_adjustTableRangeWithTotalRow(){let e=this._sheet===this._owner.selectedSheet?this._owner:this._sheet.grid,t=this.getRange(),i=new CellRange(t.bottomRow+1,t.col,t.bottomRow+1,t.col2);if(this._showTotalRow){if(this._sheet._canShiftCells(i)){if(1===this._sheet._needAddRowCountForInsertTableRows(1,t))if(e.collectionView){e.collectionView.beginUpdate();e.itemsSource instanceof CollectionView?e.itemsSource.sourceCollection.push({}):e.itemsSource.push({});e.collectionView.endUpdate(!0)}else e.rows.push(new Row);this._sheet._moveDownCells(1,i);this._owner._updateAffectedFormula(this._range.bottomRow+1,1,!0,!0,this.getRange())}else if(!this._beneathRowIsEmpty())throw"The operation is not allowed. The operation is attempting to shift the cells in a table or a merged cell on the current sheet.";this._range.row<=this._range.row2?this._range.row2+=1:this._range.row+=1;this._updateTotalRow()}else{for(let t=this._range.leftCol;t<=this._range.rightCol;t++)e.setCellData(this._range.bottomRow,t,"");if(this._sheet._canShiftCells(i)){this._owner._updateAffectedFormula(this._range.bottomRow,1,!1,!0,this.getRange());this._sheet._moveUpCells(1,i)}this._range.row<=this._range.row2?this._range.row2-=1:this._range.row-=1}}_updateTotalRow(){if(this.showTotalRow)for(let e=0;e<this._columns.length;e++){let t=this._columns[e];this._updateColumnTotalRowContent(t,e)}}_getUniqueColumnName(e,t){null!=t&&""!==t||(t="Column"+e);if(this._checkColumnNameExist(t)){let e=1,i=t+e;for(;this._checkColumnNameExist(i);)i=t+ ++e;t=i}return t}_moveColumns(e,t){if(!this._columns)return;let i=this._columns[e];this._columns.splice(e,1);t<0&&(t=this._columns.length);this._columns.splice(t,0,i)}_canInsertRowsWithoutShift(e){let t=this._flex;if(this._range.bottomRow+e>=t.rows.length)return!1;for(let i=1;i<=e;i++){let e=this._range.bottomRow+i;for(let i=this._range.leftCol;i<=this._range.rightCol;i++){let o=t.getCellData(e,i,!1),l=this._sheet.getCellStyle(e,i);if(null!=o&&""!==o||null!=l)return!1}}return!0}_beneathRowIsEmpty(){let e=this._range.bottomRow+1,t=this._flex;if(e>=t.rows.length)return!1;for(let i=this._range.leftCol;i<=this._range.rightCol;i++){let o=t.getCellData(this._range.bottomRow+1,i,!1);if(null!=o&&""!==o)return!1;if(null!=this._sheet.getCellStyle(this._range.bottomRow+1,i))return!1;if(this._sheet.findTable(e,i))return null;let l=e*t.columns.length+i;if(null!=this._sheet._mergedRanges[l])return!1}return!0}_getDataRange(){let e=this._range.topRow,t=this._range.bottomRow;this._showHeaderRow&&(e+=1);this._showTotalRow&&(t-=1);return new CellRange(e,this._range.leftCol,t,this._range.rightCol)}_getHeaderRange(){return this._showHeaderRow?new CellRange(this._range.topRow,this._range.leftCol,this._range.topRow,this._range.rightCol):null}_getFooterRange(){return this._showTotalRow?new CellRange(this._range.bottomRow,this._range.leftCol,this._range.bottomRow,this._range.rightCol):null}_getColumnIndex(e){let t;if(isInt(e)&&e>=0&&e<this._columns.length)t=e;else{let i;e instanceof TableColumn?i=e.name.toLowerCase():isString(e)&&""!==e&&(i=e.toLowerCase());let o=this.getColumns();for(let e=0;e<o.length;e++)if(o[e].name.toLowerCase()===i){t=e;break}}return t}}export class TableColumn{constructor(e,t,i,o=!0){this._name=e;this._totalRowLabel=t;this._totalRowFunction=i;null!=o&&(this._showFilterButton=o)}get table(){return this._table}get name(){return this._name}set name(e){e!==this._name&&(this._name=e)}get totalRowLabel(){return this._totalRowLabel}set totalRowLabel(e){if(e!==this._totalRowLabel){this._totalRowLabel=e;this._updateTableTotalInfo()}}get totalRowFunction(){return this._totalRowFunction}set totalRowFunction(e){if(e!==this._totalRowFunction){this._totalRowFunction=e;this._updateTableTotalInfo()}}get showFilterButton(){return this._showFilterButton}set showFilterButton(e){this._showFilterButton!==e&&(this._showFilterButton=e)}_attach(e){this._table=e}_updateTableTotalInfo(){if(this._table&&this._table.showTotalRow){this._table._updateColumnTotalRowContent(this);this._table._owner&&this._table._owner.refresh()}}}export class TableStyle{constructor(e,t=!1){this._name=e;this._isBuiltIn=t}get name(){return this._name}set name(e){e!==this._name&&(this._name=e)}get wholeTableStyle(){return this._wholeTableStyle}set wholeTableStyle(e){this._wholeTableStyle=e}get firstBandedColumnStyle(){return this._firstBandedColumnStyle}set firstBandedColumnStyle(e){this._firstBandedColumnStyle=e}get secondBandedColumnStyle(){return this._secondBandedColumnStyle}set secondBandedColumnStyle(e){this._secondBandedColumnStyle=e}get firstBandedRowStyle(){return this._firstBandedRowStyle}set firstBandedRowStyle(e){this._firstBandedRowStyle=e}get secondBandedRowStyle(){return this._secondBandedRowStyle}set secondBandedRowStyle(e){this._secondBandedRowStyle=e}get firstColumnStyle(){return this._firstColumnStyle}set firstColumnStyle(e){this._firstColumnStyle=e}get lastColumnStyle(){return this._lastColumnStyle}set lastColumnStyle(e){this._lastColumnStyle=e}get headerRowStyle(){return this._headerRowStyle}set headerRowStyle(e){this._headerRowStyle=e}get totalRowStyle(){return this._totalRowStyle}set totalRowStyle(e){this._totalRowStyle=e}get firstHeaderCellStyle(){return this._firstHeaderCellStyle}set firstHeaderCellStyle(e){this._firstHeaderCellStyle=e}get lastHeaderCellStyle(){return this._lastHeaderCellStyle}set lastHeaderCellStyle(e){this._lastHeaderCellStyle=e}get firstTotalCellStyle(){return this._firstTotalCellStyle}set firstTotalCellStyle(e){this._firstTotalCellStyle=e}get lastTotalCellStyle(){return this._lastTotalCellStyle}set lastTotalCellStyle(e){this._lastTotalCellStyle=e}get isBuiltIn(){return this._isBuiltIn}}export var TableSection;!function(e){e[e.All=0]="All";e[e.Data=1]="Data";e[e.Header=2]="Header";e[e.Footer=3]="Footer"}(TableSection||(TableSection={}));export class _UndoAction{constructor(e){this._owner=e;this._sheetUuid=e.selectedSheet?e.selectedSheet._uid:-1}get sheetUid(){return this._sheetUuid}undo(){throw"This abstract method must be overridden."}redo(){throw"This abstract method must be overridden."}saveNewState(){throw"This abstract method must be overridden."}}export class _EditAction extends _UndoAction{constructor(e,t){super(e);this._isPaste=!1;this._selections=t?[t]:e.selectedSheet.selectionRanges.length>0?e.selectedSheet.selectionRanges.slice():[e.selection.clone()];this._mergeAction=new _CellMergeAction(e);this._cellStyleAction=new _CellStyleAction(e);this._saveValues(!0)}get isPaste(){return this._isPaste}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){if(!this._saveValues(!1))return!1;this._mergeAction.saveNewState();this._cellStyleAction.saveNewState();return this._checkActionState()}markIsPaste(){this._isPaste=!0}updateForPasting(e){var t=this._selections[this._selections.length-1],i=this._owner.getCellData(e.row,e.col,!!this._owner.columns[e.col].dataMap);if(!t){t=this._owner.selection;this._selections=[t]}i=null==i?"":i;this._oldValues["r"+e.row+"_c"+e.col]={row:e.row,col:e.col,value:i};t.row=Math.min(t.topRow,e.topRow);t.row2=Math.max(t.bottomRow,e.bottomRow);t.col=Math.min(t.leftCol,e.leftCol);t.col2=Math.max(t.rightCol,e.rightCol)}_storeDeletedTables(e){null==this._deletedTables&&(this._deletedTables=[]);this._deletedTables.push(e)}_checkActionState(){var e=this,t=!1;Object.keys(e._oldValues).forEach(i=>{var o,l;if(!t){o=e._oldValues[i];l=e._newValues[i];o&&l&&o.value!==l.value&&(t=!0)}});return t||e._mergeAction._checkActionState()||e._cellStyleAction._checkActionState()}_saveValues(e){let t={};for(let e=0;e<this._selections.length;e++){let i=this._selections[e];for(let e=i.topRow;e<=i.bottomRow;e++)if(!(e<0))for(let o=i.leftCol;o<=i.rightCol;o++){let i=this._owner.columns[o];if(!i)return!1;let l=this._owner.getCellData(e,o,!!i.dataMap);l=null==l?"":l;t["r"+e+"_c"+o]={row:e,col:o,value:l}}}e?this._oldValues=t:this._newValues=t;return!0}_handleUndoRedo(e){let t=this;t._owner._clearCalcEngine();t._owner.selectedSheet.selectionRanges.clear();t._owner.deferUpdate(()=>{let i,o=e?t._oldValues:t._newValues;if(t._deletedTables&&t._deletedTables.length>0)for(let i=0;i<t._deletedTables.length;i++){let o=t._deletedTables[i];e?t._owner.selectedSheet.tables.push(o):t._owner.selectedSheet.tables.remove(o)}for(let e=0;e<t._selections.length;e++){let i=t._selections[e];t._owner.selectedSheet.selectionRanges.push(i)}Object.keys(o).forEach(e=>{let i=o[e];t._owner.setCellData(i.row,i.col,i.value)});t._affectedFormulas&&(i=e?t._affectedFormulas.oldFormulas:t._affectedFormulas.newFormulas);if(i&&i.length>0)for(let e=0;e<i.length;e++){let o=i[e];t._owner.setCellData(o.point.x,o.point.y,o.formula)}if(e){t._mergeAction.undo();t._cellStyleAction.undo()}else{t._mergeAction.redo();t._cellStyleAction.redo()}t._owner.refresh(!1)})}}export class _ColumnResizeAction extends _UndoAction{constructor(e,t,i){super(e);this._panel=t;this._colIndex=i;this._oldColWidth=t.columns[i].width}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._newColWidth=this._panel.columns[this._colIndex].width;return this._oldColWidth!==this._newColWidth}_handleUndoRedo(e){var t=this._panel.columns[this._colIndex];t&&(t.width=e?this._oldColWidth:this._newColWidth)}}export class _RowResizeAction extends _UndoAction{constructor(e,t,i){super(e);this._panel=t;this._rowIndex=i;this._oldRowHeight=t.rows[i].height}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._newRowHeight=this._panel.rows[this._rowIndex].height;return this._oldRowHeight!==this._newRowHeight}_handleUndoRedo(e){var t=this._panel.rows[this._rowIndex];t&&(t.height=e?this._oldRowHeight:this._newRowHeight)}}export class _ColumnsChangedAction extends _UndoAction{constructor(e,t,i,o){super(e);this._delSubActions=[];this._columnIndex=t;this._count=i;this._isAdding=o;this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._saveValues(!1);return!0}_saveValues(e){var t=[],i=[];if(null==this._isAdding)for(let e=0;e<this._owner.columns.length;e++)t.push(this._owner.columns[e]);else if(e&&!this._isAdding||!e&&this._isAdding)for(let e=this._columnIndex;e<this._columnIndex+this._count&&e<this._owner.columns.length;e++)t.push(this._owner.columns[e]);if(this._owner.selectedSheet.tables&&this._owner.selectedSheet.tables.length>0)for(let e=0;e<this._owner.selectedSheet.tables.length;e++){let t=this._owner.selectedSheet.tables[e];t&&t.sheet.name===this._owner.selectedSheet.name&&i.push({name:t.name,range:t.getRange(),columns:t.getColumns()})}let o={columns:t,sortList:this._owner.sortManager._cloneSortList(this._owner.sortManager._committedList),styledCells:this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null,mergedCells:this._owner.selectedSheet?this._owner.selectedSheet._cloneMergedCells():null,tableRanges:i,selection:this._owner.selection,filterDef:this._owner.selectedSheet._filterDefinition};e?this._oldValue=o:this._newValue=o}_handleUndoRedo(e,t=!0){let i=this,o=e?i._oldValue:i._newValue;if(i._owner.selectedSheet)if(this._delSubActions.length)i._owner.deferUpdate(()=>{if(e)for(let t=this._delSubActions.length-1;t>=0;t--){this._delSubActions[t]._handleUndoRedo(e,!1)}else for(let t=0;t<this._delSubActions.length;t++){this._delSubActions[t]._handleUndoRedo(e,!1)}});else{try{t&&this._owner.beginUpdate();let l,s,n;i._owner._isUndoing=!0;i._owner._clearCalcEngine();i._owner.finishEditing();if(null==i._isAdding){i._owner.columns.clear();i._columnIndex=0}i._owner.selectedSheet._styledCells=null;i._owner.selectedSheet._mergedRanges.length=0;i._owner.columns.beginUpdate();if(o.columns&&o.columns.length>0)for(let e=0;e<o.columns.length;e++){let t=o.columns[e];if(t&&t.isVisible){i._owner.columns.insert(i._columnIndex+e,t);if(i._owner.itemsSource&&(l=i._owner.rows[i._owner._getDataRowsOffset()-1])){l._ubv||(l._ubv={});l._ubv[t._hash]=t.header}}}else for(let e=i._columnIndex+i._count-1;e>=i._columnIndex;e--){let t=i._owner.columns[e];t&&t.isVisible&&i._owner.columns.removeAt(e)}i._owner.columns.endUpdate();i._owner.selectedSheet._styledCells=i._owner._cloneObject(o.styledCells);for(let e=0;e<o.mergedCells.length;e++)i._owner.selectedSheet._mergedRanges[e]=o.mergedCells[e];for(let e=0;e<o.tableRanges.length;e++){let t=o.tableRanges[e],l=i._owner._getTable(t.name);l&&l._setTableRange(t.range,t.columns)}i._affectedFormulas&&(s=e?i._affectedFormulas.oldFormulas:i._affectedFormulas.newFormulas);if(s&&s.length>0)for(let e=0;e<s.length;e++){let t=s[e];null!=t.point?t.sheet.name===i._owner.selectedSheet.name?i._owner.setCellData(t.point.x,t.point.y,t.formula):t.sheet.grid.setCellData(t.point.x,t.point.y,t.formula):t.row._ubv[t.column._hash]=t.formula}if(i._deletedTables&&i._deletedTables.length>0)for(let t=0;t<i._deletedTables.length;t++){let o=i._deletedTables[t];e?i._owner.selectedSheet.tables.push(o):i._owner.selectedSheet.tables.remove(o)}i._affectedDefinedNameVals&&(n=e?i._affectedDefinedNameVals.oldDefinedNameVals:i._affectedDefinedNameVals.newDefinedNameVals);if(n&&n.length>0)for(let e=0;e<n.length;e++){let t=n[e],o=i._owner.definedNames._getIndexByName(t.name);o>-1&&(i._owner.definedNames[o].value=t.value)}i._owner.selectedSheet.grid.wj_sheetInfo.styledCells=i._owner.selectedSheet._styledCells;i._owner.selectedSheet.grid.wj_sheetInfo.mergedRanges=i._owner.selectedSheet._mergedRanges}finally{t&&this._owner.endUpdate()}i._owner._copyColumnsToSelectedSheet();i._owner.sortManager.sortDescriptions.sourceCollection=o.sortList.slice();if(i._owner.selectedSheet._filterDefinition!==o.filterDef){i._owner._isUndoing=!0;i._owner.selectedSheet._filterDefinition=o.filterDef;i._owner.selectedSheet._applyFilterSetting();i._owner._isUndoing=!1;i._owner.filter.apply()}i._owner.sortManager.commitSort(!1);i._owner.selection=o.selection;i._owner._isUndoing=!1}}}export class _RowsChangedAction extends _UndoAction{constructor(e,t,i,o){super(e);this._delSubActions=[];this._headerRowIndex=-1;if(e.itemsSource){this._headerRowAtTop=e._headerRowAtTop();if(!this._headerRowAtTop)for(let t=0;t<e.rows.length;t++)if(e.rows[t]instanceof HeaderRow){this._headerRowIndex=t;break}}this._rowIndex=t;this._count=i;this._isAdding=o;this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._saveValues(!1);return!0}addDeleteSubAction(e){this._delSubActions.push(e)}_saveValues(e){let t,i,o=[],l=[],s=[];if(null==this._isAdding)if(this._owner.itemsSource){t=this._owner.itemsSource instanceof CollectionView?this._owner.itemsSource.sourceCollection.slice():this._owner.itemsSource.slice();for(let e=0;e<this._owner.columns.length;e++)l.push(this._owner.columns[e])}else for(let e=0;e<this._owner.rows.length;e++)o.push(this._owner.rows[e]);else{if(e&&!this._isAdding||!e&&this._isAdding)for(let e=this._rowIndex;e<this._rowIndex+this._count&&e<this._owner.rows.length;e++){let t=this._owner.rows[e];t.isVisible||this._isAdding?o.push(t):o.push(null)}this._owner.collectionView&&this._owner.collectionView.sortDescriptions.length>0&&(i=this._owner.collectionView._view.slice())}if(this._owner.selectedSheet.tables&&this._owner.selectedSheet.tables.length>0)for(let e=0;e<this._owner.selectedSheet.tables.length;e++){let t=this._owner.selectedSheet.tables[e];t&&t.sheet.name===this._owner.selectedSheet.name&&s.push({name:t.name,range:t.getRange(),setting:{showHeaderRow:t.showHeaderRow,showTotalRow:t.showTotalRow}})}let n={rows:o,columns:l,itemsSource:t,styledCells:this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null,mergedCells:this._owner.selectedSheet?this._owner.selectedSheet._cloneMergedCells():null,tableSettings:s,selection:this._owner.selection,dataView:i,scrollPosition:this._owner.scrollPosition};e?this._oldValue=n:this._newValue=n}_handleUndoRedo(e,t=!0){var i,o=this,l=!!o._owner.itemsSource,s=e?o._oldValue:o._newValue;if(o._owner.selectedSheet)if(this._delSubActions.length)o._owner.deferUpdate(()=>{if(e)for(let t=this._delSubActions.length-1;t>=0;t--){this._delSubActions[t]._handleUndoRedo(e,!1)}else{for(let t=0;t<this._delSubActions.length;t++){this._delSubActions[t]._handleUndoRedo(e,!1)}o._owner.selection=this._newValue.selection}});else{try{t&&o._owner.beginUpdate();o._owner._isUndoing=!0;o._owner._clearCalcEngine();o._owner.finishEditing();if(null==o._isAdding){o._owner.itemsSource&&o._owner.columns.clear();o._owner.rows.clear();o._rowIndex=0}o._owner.selectedSheet._styledCells=null;o._owner.selectedSheet._mergedRanges.length=0;if(null==this._isAdding&&l){i=o._owner.autoGenerateColumns;o._owner.autoGenerateColumns=!1;o._owner.collectionView.beginUpdate();if(o._owner.itemsSource instanceof CollectionView){let e=[0,o._owner.itemsSource.sourceCollection.length].concat(s.itemsSource);Array.prototype.splice.apply(o._owner.itemsSource.sourceCollection,e)}else o._owner.itemsSource=s.itemsSource.slice();o._owner.columns.beginUpdate();for(let e=0;e<s.columns.length;e++)o._owner.columns.push(s.columns[e]);o._owner.columns.endUpdate();o._owner.collectionView.endUpdate(!0);o._owner.autoGenerateColumns=i}else{o._owner.rows.beginUpdate();if(l){i=o._owner.autoGenerateColumns;o._owner.autoGenerateColumns=!1;o._owner.collectionView.beginUpdate()}let e=o._owner.collectionView,t=e instanceof CollectionView?e:null;if(s.rows&&s.rows.length>0){let i;if(l){let e=o._owner._getDataRowsOffset();i=Math.max(o._rowIndex-e,0);!o._isAdding&&!o._headerRowAtTop&&o._owner._headerRowAtTop()&&o._rowIndex>=e&&i<o._headerRowIndex&&i++}for(let n=0;n<s.rows.length;n++){let r=s.rows[n];if(r)if(l&&r.dataItem){let l=null!=r.dataItem._itemIdx?r.dataItem._itemIdx:i+n;o._owner._updateItemIndexForInsertingRow(e.sourceCollection,l,1);e.sourceCollection.splice(l,0,r.dataItem);if(t&&t.trackChanges){let e=t.itemsRemoved.indexOf(r.dataItem)>=0;e&&t.itemsRemoved.remove(r.dataItem);!e&&t.itemsAdded.indexOf(r.dataItem)<=0&&t.itemsAdded.push(r.dataItem)}}else o._owner.rows.insert(o._rowIndex+n,r)}}else{let i=o._rowIndex;!o._isAdding&&!o._headerRowAtTop&&o._owner._headerRowAtTop()&&i<o._headerRowIndex&&i++;for(let s=i+o._count-1;s>=i;s--){let i=o._owner.rows[s];if(i)if(l&&i.dataItem){let l=null!=i.dataItem._itemIdx?i.dataItem._itemIdx:s-o._owner._getDataRowsOffset();e.sourceCollection.splice(l,1);o._owner._updateItemIndexForRemovingRow(e.sourceCollection,l);if(t&&t.trackChanges){let e=t.itemsAdded.indexOf(i.dataItem)>=0;e&&t.itemsAdded.remove(i.dataItem);!e&&t.itemsRemoved.indexOf(i.dataItem)<0&&t.itemsRemoved.push(i.dataItem)}}else o._owner.rows.removeAt(s)}}if(l){o._owner._lastCount=o._owner.collectionView.itemCount;o._owner.collectionView.endUpdate(!0);o._owner.selectedSheet._dataView=o._owner.collectionView._view.slice();if(s.dataView&&s.dataView.length>0){o._owner.collectionView._view=s.dataView;o._owner.collectionView._pgView=o._owner.collectionView._getPageView();if(!(o._owner.itemsSource instanceof CollectionView)){o._owner.selectedSheet.grid.collectionView._view=s.dataView;o._owner.selectedSheet.grid.collectionView._pgView=o._owner.selectedSheet.grid.collectionView._getPageView()}o._owner._bindGrid(!1);o._owner.selectedSheet.grid._bindGrid(!1)}o._owner.autoGenerateColumns=i}o._owner.rows.endUpdate()}o._owner.selectedSheet._styledCells=o._owner._cloneObject(s.styledCells);for(let e=0;e<s.mergedCells.length;e++)o._owner.selectedSheet._mergedRanges[e]=s.mergedCells[e];for(let e=0;e<s.tableSettings.length;e++){let t=s.tableSettings[e],i=o._owner._getTable(t.name);if(i){i._showHeaderRow=t.setting.showHeaderRow;i._showTotalRow=t.setting.showTotalRow;i._setTableRange(t.range)}}let n,r;o._affectedFormulas&&(n=e?o._affectedFormulas.oldFormulas:o._affectedFormulas.newFormulas);if(n&&n.length>0)for(let e=0;e<n.length;e++){let t=n[e];null!=t.point?t.sheet.name===o._owner.selectedSheet.name?o._owner.setCellData(t.point.x,t.point.y,t.formula):t.sheet.grid.setCellData(t.point.x,t.point.y,t.formula):t.row._ubv[t.column._hash]=t.formula}if(o._deletedTables&&o._deletedTables.length>0)for(let t=0;t<o._deletedTables.length;t++){let i=o._deletedTables[t];e?o._owner.selectedSheet.tables.push(i):o._owner.selectedSheet.tables.remove(i)}o._affectedDefinedNameVals&&(r=e?o._affectedDefinedNameVals.oldDefinedNameVals:o._affectedDefinedNameVals.newDefinedNameVals);if(r&&r.length>0)for(let e=0;e<r.length;e++){let t=r[e],i=o._owner.definedNames._getIndexByName(t.name);i>-1&&(o._owner.definedNames[i].value=t.value)}o._owner.selectedSheet.grid.wj_sheetInfo.styledCells=o._owner.selectedSheet._styledCells;o._owner.selectedSheet.grid.wj_sheetInfo.mergedRanges=o._owner.selectedSheet._mergedRanges;o._owner.selection=s.selection;o._owner.scrollPosition=s.scrollPosition;o._owner._isUndoing=!1}finally{t&&o._owner.endUpdate()}o._owner._copyRowsToSelectedSheet()}}}export class _CellStyleAction extends _UndoAction{constructor(e,t){super(e);this._oldStyledCells=t?e._cloneObject(t):e.selectedSheet?e._cloneObject(e.selectedSheet._styledCells):null}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._newStyledCells=this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null;return!0}_checkActionState(){return null!=this._oldStyledCells&&null==this._newStyledCells||null==this._oldStyledCells&&null!=this._newStyledCells||null!=this._oldStyledCells&&null!=this._newStyledCells&&this._oldStyledCells.length!==this._newStyledCells.length}_handleUndoRedo(e){var t;if(this._owner.selectedSheet){t=e?this._oldStyledCells:this._newStyledCells;this._owner.selectedSheet._styledCells=this._owner._cloneObject(t);this._owner.selectedSheet.grid.wj_sheetInfo.styledCells=this._owner.selectedSheet._styledCells;this._owner.refresh(!1)}}}export class _CellMergeAction extends _UndoAction{constructor(e){super(e);this._oldMergedCells=e.selectedSheet?e.selectedSheet._cloneMergedCells():null}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._newMergedCells=this._owner.selectedSheet?this._owner.selectedSheet._cloneMergedCells():null;return!0}_handleUndoRedo(e){var t,i;if(this._owner.selectedSheet){t=e?this._oldMergedCells:this._newMergedCells;this._owner._clearCalcEngine();if(t){this._owner.selectedSheet._mergedRanges.length=0;for(i=0;i<t.length;i++)this._owner.selectedSheet._mergedRanges[i]=t[i]}this._owner.selectedSheet.grid.wj_sheetInfo.mergedRanges=this._owner.selectedSheet._mergedRanges;this._owner.refresh(!0)}}_checkActionState(){let e,t,i;if(null!=this._oldMergedCells&&null==this._newMergedCells||null==this._oldMergedCells&&null!=this._newMergedCells)return!0;if(null!=this._oldMergedCells&&null!=this._newMergedCells&&this._oldMergedCells.length!==this._newMergedCells.length)return!0;if(null!=this._oldMergedCells&&null!=this._newMergedCells&&this._oldMergedCells.length===this._newMergedCells.length)for(e=0;e<this._oldMergedCells.length;e++){i=this._oldMergedCells[e];t=this._oldMergedCells[e];if(!i.equals(t))return!0}return!1}}export class _SortColumnAction extends _UndoAction{constructor(e){super(e);this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._saveValues(!1);return!0}_saveValues(e){let t,i,o,l=[];for(let e=0;e<this._owner.columns.length;e++)l.push(this._owner.columns[e]);if(this._owner.itemsSource){let t=this._owner._getDataRowsOffset();i=[];for(let e=0;e<this._owner.rows.length-t;e++){let o=this._owner.rows[e+t],l=o.dataItem;if(l){i[null!=l._itemIdx?l._itemIdx:e]=o.visible}}e&&(o=this._owner.collectionView._view.slice())}else{t=[];for(let e=0;e<this._owner.rows.length;e++)t.push(this._owner.rows[e])}let s={sortList:this._owner.sortManager._committedList.slice(),rows:t,columns:l,selection:this._owner.selection.clone(),formulas:this._owner._scanFormulas(),styledCells:this._owner.selectedSheet?this._owner._cloneObject(this._owner.selectedSheet._styledCells):null,rowsVisible:i,dataView:o};e?this._oldValue=s:this._newValue=s}_handleUndoRedo(e){let t=this,i=e?t._oldValue:t._newValue,o=!!t._owner.itemsSource,l=this._owner.itemsSource instanceof CollectionView;if(t._owner.selectedSheet){t._owner._isUndoing=!0;t._owner.deferUpdate(()=>{t._owner._clearCalcEngine();t._owner.sortManager.sortDescriptions.sourceCollection=i.sortList.slice();t._owner.sortManager.commitSort(!1);t._owner.selectedSheet._styledCells=t._owner._cloneObject(i.styledCells);if(o){if(i.dataView&&i.dataView.length>0){t._owner.collectionView._view=i.dataView;t._owner.collectionView._pgView=t._owner.collectionView._getPageView();if(!l){t._owner.selectedSheet.grid.collectionView._view=i.dataView;t._owner.selectedSheet.grid.collectionView._pgView=t._owner.selectedSheet.grid.collectionView._getPageView()}t._owner._bindGrid(!1);t._owner.selectedSheet.grid._bindGrid(!1)}}else{t._owner.rows.clear();t._owner.selectedSheet.grid.rows.clear();for(let e=0;e<i.rows.length;e++){let o=i.rows[e];t._owner.selectedSheet.grid.rows.push(o);t._owner.rows.push(o)}t._owner.columns.clear();for(let e=0;e<i.columns.length;e++){let o=i.columns[e];t._owner.columns.push(o)}t._owner._resetFormulas(i.formulas)}t._owner._isUndoing=!1})}}}export class _MoveCellsAction extends _UndoAction{constructor(e,t,i,o){super(e);if(e.selectedSheet){0===t.topRow&&t.bottomRow===e.rows.length-1?this._isDraggingColumns=!0:this._isDraggingColumns=!1;this._isCopyCells=o;this._dragRange=t;this._dropRange=i;this._saveValues(!0)}}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){if(!this._owner.selectedSheet)return!1;if(this._dropRange){this._saveValues(!1);return!0}return!1}_saveValues(e){let t=[],i={};for(let e=this._dropRange.topRow;e<=this._dropRange.bottomRow;e++)for(let o=this._dropRange.leftCol;o<=this._dropRange.rightCol;o++){this._isDraggingColumns&&(i[o]||(i[o]={dataType:this._owner.columns[o].dataType,align:this._owner.columns[o].align,format:this._owner.columns[o].format}));let l=e*this._owner.columns.length+o,s=this._owner.selectedSheet._styledCells[l]?this._owner._cloneObject(this._owner.selectedSheet._styledCells[l]):null,n=this._owner.getCellData(e,o,!1);t.push({rowIndex:e,columnIndex:o,cellContent:n,cellStyle:s})}if(e){this._oldDroppingCells=t;this._oldDroppingColumnSetting=i}else{this._newDroppingCells=t;this._newDroppingColumnSetting=i}if(this._isCopyCells){if(this._isDraggingColumns)if(e)for(let e=this._dragRange.topRow;e<=this._dragRange.bottomRow;e++)for(let t=this._dragRange.leftCol;t<=this._dragRange.rightCol;t++){let i=this._owner.selectedSheet.findTable(e,t);if(i&&i._isHeaderRow(e)){let o=i._getTableRange(),l=i._getColumns();this._draggingTableColumns||(this._draggingTableColumns=[]);this._draggingTableColumns.push({rowIndex:e,columnIndex:t,cellContent:l[t-o.leftCol].name})}}else if(this._draggingTableColumns&&this._draggingTableColumns.length>0&&this._draggingTableColumns&&this._draggingTableColumns.length>0)for(let e=0;e<this._draggingTableColumns.length;e++){let t=this._draggingTableColumns[e],i=this._owner.selectedSheet.findTable(t.rowIndex,t.columnIndex);if(i&&i._isHeaderRow(t.rowIndex)){let e=i._getTableRange(),o=i._getColumns();t.updatedCellContent=o[t.columnIndex-e.leftCol].name}}}else if(e){this._draggingCells=[];this._draggingColumnSetting={};for(let e=this._dragRange.topRow;e<=this._dragRange.bottomRow;e++)for(let t=this._dragRange.leftCol;t<=this._dragRange.rightCol;t++){this._isDraggingColumns&&(this._draggingColumnSetting[t]||(this._draggingColumnSetting[t]={dataType:this._owner.columns[t].dataType,align:this._owner.columns[t].align,format:this._owner.columns[t].format}));let i=e*this._owner.columns.length+t,o=this._owner.selectedSheet._styledCells[i]?this._owner._cloneObject(this._owner.selectedSheet._styledCells[i]):null,l=this._owner.getCellData(e,t,!1);this._draggingCells.push({rowIndex:e,columnIndex:t,cellContent:l,cellStyle:o})}}else if(this._isDraggingColumns&&this._draggingCells&&this._draggingCells.length>0)for(let e=0;e<this._draggingCells.length;e++){let t=this._draggingCells[e],i=this._owner.selectedSheet.findTable(t.rowIndex,t.columnIndex);if(i&&i._isHeaderRow(t.rowIndex)){let e=i._getTableRange(),o=i._getColumns();t.updatedCellContent=o[t.columnIndex-e.leftCol].name}}}_handleUndoRedo(e){var t=this,i=e?t._oldDroppingCells:t._newDroppingCells,o=e?t._oldDroppingColumnSetting:t._newDroppingColumnSetting;if(t._owner.selectedSheet){t._owner._clearCalcEngine();t._owner.deferUpdate(()=>{let l,s;t._affectedFormulas&&(l=e?t._affectedFormulas.oldFormulas:t._affectedFormulas.newFormulas);if(l&&l.length>0)for(let e=0;e<l.length;e++){let i=l[e];i.sheet.name===t._owner.selectedSheet.name?t._owner.setCellData(i.point.x,i.point.y,i.formula):i.sheet.grid.setCellData(i.point.x,i.point.y,i.formula)}t._affectedDefinedNameVals&&(s=e?t._affectedDefinedNameVals.oldDefinedNameVals:t._affectedDefinedNameVals.newDefinedNameVals);if(s&&s.length>0)for(let e=0;e<s.length;e++){let i=s[e],o=t._owner.definedNames._getIndexByName(i.name);o>-1&&(t._owner.definedNames[o].value=i.value)}for(let e=0;e<i.length;e++){let o=i[e];t._owner.setCellData(o.rowIndex,o.columnIndex,o.cellContent);let l=t._owner.selectedSheet.findTable(o.rowIndex,o.columnIndex);if(l&&l._isHeaderRow(o.rowIndex)){let e=l._getTableRange();l._getColumns()[o.columnIndex-e.leftCol].name=o.cellContent}let s=o.rowIndex*t._owner.columns.length+o.columnIndex;o.cellStyle?t._owner.selectedSheet._styledCells[s]=o.cellStyle:delete t._owner.selectedSheet._styledCells[s]}t._isDraggingColumns&&o&&Object.keys(o).forEach(e=>{t._owner.columns[+e].dataType=o[+e].dataType?o[+e].dataType:DataType.Object;t._owner.columns[+e].align=o[+e].align;t._owner.columns[+e].format=o[+e].format});if(t._isCopyCells){if(t._draggingTableColumns&&t._draggingTableColumns.length>0)for(let i=0;i<t._draggingTableColumns.length;i++){let o=t._draggingTableColumns[i],l=t._owner.selectedSheet.findTable(o.rowIndex,o.columnIndex);if(l&&l._isHeaderRow(o.rowIndex)){let i=l._getTableRange(),s=l._getColumns();t._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:o.updatedCellContent);s[o.columnIndex-i.leftCol].name=e?o.cellContent:o.updatedCellContent}}}else{for(let i=0;i<t._draggingCells.length;i++){let o=t._draggingCells[i],l=t._owner.selectedSheet.findTable(o.rowIndex,o.columnIndex);if(l){let i=l._getTableRange(),s=l._getColumns();if(l._isHeaderRow(o.rowIndex)){t._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:o.updatedCellContent);s[o.columnIndex-i.leftCol].name=e?o.cellContent:o.updatedCellContent}else t._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:null)}else t._owner.setCellData(o.rowIndex,o.columnIndex,e?o.cellContent:null);let s=o.rowIndex*t._owner.columns.length+o.columnIndex;e?o.cellStyle&&(t._owner.selectedSheet._styledCells[s]=o.cellStyle):t._owner.selectedSheet._styledCells[s]&&delete t._owner.selectedSheet._styledCells[s]}t._isDraggingColumns&&t._draggingColumnSetting&&Object.keys(t._draggingColumnSetting).forEach(i=>{t._owner.columns[+i].dataType=e&&t._draggingColumnSetting[+i].dataType?t._draggingColumnSetting[+i].dataType:DataType.Object;t._owner.columns[+i].align=e?t._draggingColumnSetting[+i].align:null;t._owner.columns[+i].format=e?t._draggingColumnSetting[+i].format:null});if(e){if(t._isDraggingColumns)if(t._dragRange.leftCol<t._dropRange.leftCol){let e=t._dragRange.leftCol;for(let i=t._dropRange.leftCol;i<=t._dropRange.rightCol;i++){t._owner._updateColumnFiler(i,e);e++}}else{let e=t._dragRange.rightCol;for(let i=t._dropRange.rightCol;i>=t._dropRange.leftCol;i--){t._owner._updateColumnFiler(i,e);e--}}}else if(t._isDraggingColumns)if(t._dragRange.leftCol>t._dropRange.leftCol){let e=t._dropRange.leftCol;for(let i=t._dragRange.leftCol;i<=t._dragRange.rightCol;i++){t._owner._updateColumnFiler(i,e);e++}}else{let e=t._dropRange.rightCol;for(let i=t._dragRange.rightCol;i>=t._dragRange.leftCol;i--){t._owner._updateColumnFiler(i,e);e--}}}})}}}export class _CutAction extends _UndoAction{constructor(e){super(e);this._oldValues=[];this._mergeAction=new _CellMergeAction(e);this._celltyleAction=new _CellStyleAction(e);this._cutSheet=e._copiedSheet;this._selection=e.selection;this._cutSelection=e.selectionMode===SelectionMode.ListBox?e._getSelectionForListBoxMode(this._cutSheet.grid):e._copiedRanges[0];this._saveCutValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._cutSheet===this._owner.selectedSheet?this._owner:this._cutSheet.grid;this._saveCutValues(!1);this._newValues=[];for(let e=this._selection.topRow;e<=this._selection.bottomRow;e++)for(let t=this._selection.leftCol;t<=this._selection.rightCol;t++){if(!this._owner.columns[t])return!1;let i=this._owner.getCellData(e,t,!!this._owner.columns[t].dataMap);i=null==i?"":i;this._newValues.push({row:e,col:t,value:i})}this._mergeAction.saveNewState();this._celltyleAction.saveNewState();return!0}updateForPasting(e){var t=this._owner.getCellData(e.row,e.col,!!this._owner.columns[e.col].dataMap);t=null==t?"":t;this._oldValues.push({row:e.row,col:e.col,value:t});this._selection.row=Math.min(this._selection.topRow,e.topRow);this._selection.row2=Math.max(this._selection.bottomRow,e.bottomRow);this._selection.col=Math.min(this._selection.leftCol,e.leftCol);this._selection.col2=Math.max(this._selection.rightCol,e.rightCol)}_saveCutValues(e){let t=this._cutSheet===this._owner.selectedSheet?this._owner:this._cutSheet.grid,i=[];for(let e=this._cutSelection.topRow;e<=this._cutSelection.bottomRow;e++)if(null!=t.rows[e])for(let o=this._cutSelection.leftCol;o<=this._cutSelection.rightCol;o++){let l=t.getCellData(e,o,!!t.columns[o].dataMap);""===(l=null==l?"":l)&&t.columns[o].dataMap&&(l=null);i.push({row:e,col:o,value:l})}e?this._oldCutValues=i:this._newCutValues=i}_handleUndoRedo(e){var t=this,i=e?t._oldCutValues:t._newCutValues,o=e?t._oldValues:t._newValues;t._owner._clearCalcEngine();t._owner.selectedSheet.selectionRanges.clear();t._owner.deferUpdate(()=>{var l,s,n=t._cutSheet===t._owner.selectedSheet?t._owner:t._cutSheet.grid;t._owner.selectedSheet.selectionRanges.push(t._selection);for(l=0;l<i.length;l++){s=i[l];n.setCellData(s.row,s.col,s.value)}for(l=0;l<o.length;l++){s=o[l];t._owner.setCellData(s.row,s.col,s.value)}if(e){t._mergeAction.undo();t._celltyleAction.undo()}else{t._mergeAction.redo();t._celltyleAction.redo()}t._owner.refresh(!1)})}}export class _TableSettingAction extends _UndoAction{constructor(e,t){super(e);this._table=t;this._saveValues(!0)}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._saveValues(!1);return!0}_saveValues(e){var t={name:this._table.name,style:this._table.style,showHeaderRow:this._table.showHeaderRow,showTotalRow:this._table.showTotalRow,showbandedRows:this._table.showBandedRows,showBandedColumns:this._table.showBandedColumns,alterFirstColumn:this._table.alterFirstColumn,alterLastColumn:this._table.alterLastColumn};e?this._oldTableSetting=t:this._newTableSetting=t}_handleUndoRedo(e){var t=e?this._oldTableSetting:this._newTableSetting;this._owner.beginUpdate();this._owner._isUndoing=!0;this._table.name=t.name;this._table.style=t.style;this._table.showHeaderRow=t.showHeaderRow;this._table.showTotalRow=t.showTotalRow;this._table.showBandedRows=t.showbandedRows;this._table.showBandedColumns=t.showBandedColumns;this._table.alterFirstColumn=t.alterFirstColumn;this._table.alterLastColumn=t.alterLastColumn;this._owner._isUndoing=!1;this._owner.endUpdate()}}export class _TableAction extends _UndoAction{constructor(e,t){super(e);this._addedTable=t;t.showHeaderRow&&(this._orgHeaderCellsContent=t._orgHeaderCellsContent.slice())}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}_handleUndoRedo(e){e?this._owner.selectedSheet.tables.remove(this._addedTable):this._owner.selectedSheet.tables.push(this._addedTable);if(this._addedTable.showHeaderRow){let t=this._addedTable.getRange(),i=this._addedTable.getColumns();for(let o=0;o<t.columnSpan;o++)this._owner.setCellData(t.topRow,t.leftCol+o,e?this._orgHeaderCellsContent[o]:i[o].name)}this._owner.refresh()}}export class _FilteringAction extends _UndoAction{constructor(e){super(e);this._oldFilterDefinition=e.filter.filterDefinition;this._oldRowsVisible=this._getRowsVisible()}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._newFilterDefinition=this._owner.filter.filterDefinition;this._newRowsVisible=this._getRowsVisible();return!0}_handleUndoRedo(e){let t=e?this._oldFilterDefinition:this._newFilterDefinition;if(this._owner.filter.filterDefinition!==t){this._owner._isUndoing=!0;this._owner.selectedSheet._filterDefinition=t;this._owner.selectedSheet._applyFilterSetting();this._owner._isUndoing=!1;this._owner.filter.apply()}else this._setRowVisible(e)}_getRowsVisible(){let e,t=[],i=0;for(;i<this._owner.rows.length;i++)(e=this._owner.rows[i])&&t.push(e.visible);return t}_setRowVisible(e){let t,i=e?this._oldRowsVisible:this._newRowsVisible,o=0;for(;o<i.length;o++)(t=this._owner.rows[o])&&(t.visible=i[o])}}export class _FillAction extends _UndoAction{constructor(e,t){super(e);this._fillSource=t.clone();this._oldCellSettings=e._orgCellSettings}undo(){this._handleUndoRedo(!0)}redo(){this._handleUndoRedo(!1)}saveNewState(){this._fillRange=this._owner.selection.clone();this._newCellSettings=this._owner._getCellSettingsForFill(this._fillSource,this._fillRange);return!0}_handleUndoRedo(e){let t,i,o,l,s,n,r=e?this._oldCellSettings:this._newCellSettings,a=e?this._fillSource:this._fillRange;this._owner.beginUpdate();n=this._fillRange.topRow<this._fillSource.topRow?new CellRange(this._fillRange.topRow,this._fillRange.col,this._fillSource.topRow-1,this._fillRange.col2):this._fillRange.leftCol===this._fillSource.leftCol&&this._fillRange.rightCol===this._fillSource.rightCol?new CellRange(this._fillSource.bottomRow+1,this._fillRange.col,this._fillRange.bottomRow,this._fillRange.col2):this._fillRange.leftCol<this._fillSource.leftCol?new CellRange(this._fillRange.row,this._fillRange.leftCol,this._fillRange.row2,this._fillSource.leftCol-1):new CellRange(this._fillRange.row,this._fillSource.rightCol+1,this._fillRange.row2,this._fillRange.rightCol);this._owner._resetMergedRange(n);if(r&&r.length>0)for(t=0;t<r.length;t++){o=(i=r[t]).row;l=i.col;s=o*this._owner.columns.length+l;this._owner.selectedSheet._styledCells[s]=i.style;this._owner.setCellData(o,l,i.value);i.mergedCell&&this._owner.mergeRange(i.mergedCell)}this._owner.selection=a;this._owner.endUpdate()}}export class SortManager{constructor(e){this._owner=e;this._sortDescriptions=new CollectionView;this._committedList=[new ColumnSortDescription(-1,!0)];this._sortDescriptions.newItemCreator=()=>new ColumnSortDescription(-1,!0)}get sortDescriptions(){return this._sortDescriptions}set sortDescriptions(e){this._sortDescriptions=e;this.commitSort()}addSortLevel(e,t=!0){var i=this._sortDescriptions.addNew();null!=e&&!isNaN(e)&&isInt(e)&&(i.columnIndex=e);i.ascending=t;this._sortDescriptions.commitNew()}deleteSortLevel(e){var t;(t=null!=e?this._getSortItem(e):this._sortDescriptions.currentItem)&&this._sortDescriptions.remove(t)}copySortLevel(){var e=this._sortDescriptions.currentItem;if(e){var t=this._sortDescriptions.addNew();t.columnIndex=parseInt(e.columnIndex);t.ascending=e.ascending;this._sortDescriptions.commitNew()}}editSortLevel(e,t){null!=e&&(this._sortDescriptions.currentItem.columnIndex=e);null!=t&&(this._sortDescriptions.currentItem.ascending=t)}moveSortLevel(e){var t=this._sortDescriptions.currentItem;if(t){var i=this._sortDescriptions.sourceCollection,o=i.indexOf(t),l=o+e;if(o>-1&&l>-1){i.splice(o,1);i.splice(l,0,t);this._sortDescriptions.refresh();this._sortDescriptions.moveCurrentTo(t)}}}checkSortItemExists(e){for(var t=0,i=this._sortDescriptions.itemCount;t<i;t++)if(+this._sortDescriptions.items[t].columnIndex===e)return t;return-1}commitSort(e=!0){var t,i,o,l,s,n,r,a,h,d,u,c,_,g,f,w=this._owner,m=this._owner.itemsSource instanceof CollectionView,p={};if(this._owner.selectedSheet&&0!==this._owner.columns.length){var C=null==this._owner.selectedSheet.grid.collectionView;w._needCopyToSheet=!1;n=w.selectedSheet._unboundSortDesc;e&&w.undoStack.stackSize>0&&(r=new _SortColumnAction(w));this._sortDescriptions.itemCount>0?this._committedList=this._cloneSortList(this._sortDescriptions.items):this._committedList=[new ColumnSortDescription(-1,!0)];if(w.collectionView){w._isSorting=!0;w.beginUpdate();(a=w.editableCollectionView)&&a.currentEditItem&&-1!==a.items.indexOf(a.currentEditItem)&&!this._isEmpty(a.currentEditItem)&&a.commitEdit();w.collectionView.beginUpdate();C||w.selectedSheet.grid.collectionView.beginUpdate();(o=w.collectionView.sortDescriptions).clear();h=w.selection.clone();d=w.scrollPosition;f=w._getDataRowsOffset();let e=[];if(!w._isUndoing&&!w._isDeletingColumns)for(s=0;s<w.rows.length-f;s++)(g=(_=w.rows[s+f]).dataItem)&&(e[c=null!=g._itemIdx?g._itemIdx:s]=_.visible);m||(l=C?w.collectionView.sortDescriptions:w.selectedSheet.grid.collectionView.sortDescriptions).clear();w.collectionView.sourceCollection.map((e,t)=>{null==e._itemIdx&&(e._itemIdx=t)});w.select(h,!1);w.scrollPosition=d;if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){w.collectionView.useStableSort=!0;m||C||(w.selectedSheet.grid.collectionView.useStableSort=!0)}for(s=0;s<this._sortDescriptions.itemCount;s++)if((t=this._sortDescriptions.items[s]).columnIndex>-1&&t.columnIndex<w.columns.length){i=new SortDescription(w.columns[t.columnIndex].binding,t.ascending);o.push(i);m||l.push(i)}w.selectedSheet.selectionRanges.clear();w.collectionView.endUpdate(!1);C||w.selectedSheet.grid.collectionView.endUpdate(!1);h=w.selection.clone();d=w.scrollPosition;u=w.collectionView._view.slice();const n=Array(u.length);for(s=0;s<u.length;s++){s!==(g=u[s])._itemIdx&&w._updateFormulaForReorderingRows(g._itemIdx+f,s+f);w._updateCellStyleForReorderingRows(g._itemIdx+f,s+f,p);n[s+f]=w._heights[g._itemIdx+f]}w.setHeights(n);w.updateRowHeights();if(e.length)for(s=0;s<w.rows.length-f;s++)if(g=(_=w.rows[s+f]).dataItem){c=null!=g._itemIdx?g._itemIdx:s;_.visible=e[c]}u.map((e,t)=>{e._itemIdx=t});w.selectedSheet._styledCells=p;w.select(h,!1);w.scrollPosition=d;w.endUpdate();w._copyColumnsToSelectedSheet();w._isSorting=!1}else{n.clear();for(s=0;s<this._sortDescriptions.itemCount;s++)(t=this._sortDescriptions.items[s]).columnIndex>-1&&n.push(new _UnboundSortDescription(w.columns[t.columnIndex],t.ascending));!w.filter||!w._isUndoing&&w.filter._isActive()||setTimeout(()=>{w._checkCollectionOwner(w.columns,!1);w.filter.apply()},10)}if(r){r.saveNewState();w.undoStack._addAction(r)}w._copiedRanges=null;w._needCopyToSheet=!0}}cancelSort(){this._sortDescriptions.sourceCollection=this._committedList.slice()}clearSort(){this._sortDescriptions.sourceCollection=[];this.commitSort()}_getSortItem(e){var t=this.checkSortItemExists(e);if(t>-1)return this._sortDescriptions.items[t]}_cloneSortList(e){for(var t=[],i=0;i<e.length;i++)t[i]=e[i].clone();return t}_updateSortDescriptions(e,t,i=!0){let o,l;for(o=this._sortDescriptions.items.length-1;o>=0;o--){l=this._sortDescriptions.items[o];i?l.columnIndex>e&&(l.columnIndex+=t):l.columnIndex>=e+t?l.columnIndex-=t:l.columnIndex>=e&&this._sortDescriptions.remove(l)}}_handleColumnMoving(e,t){this._sortDescriptions.items.forEach(i=>{if(!(i.columnIndex<0))if(i.columnIndex===e)i.columnIndex=t;else{i.columnIndex>e&&i.columnIndex--;i.columnIndex>=t&&i.columnIndex++}})}_isEmpty(e){var t=Object.prototype.hasOwnProperty;if(null==e)return!0;if(e.length>0)return!1;if(0===e.length)return!0;for(var i in e)if(t.call(e,i))return!1;return!0}}export class ColumnSortDescription{constructor(e,t){this._columnIndex=e;this._ascending=t}get columnIndex(){return this._columnIndex}set columnIndex(e){this._columnIndex=+e}get ascending(){return this._ascending}set ascending(e){this._ascending=e}clone(){return new ColumnSortDescription(this._columnIndex,this._ascending)}}_addCultureInfo("FlexSheet",{insertRow:"Insert Row",deleteRow:"Delete Rows",insertCol:"Insert Column",deleteCol:"Delete Columns",convertTable:"Convert To Table",insertSheet:"Insert",deleteSheet:"Delete",renameSheet:"Rename",copyCells:"Copy Cells",fillSeries:"Fill Series",fillFormat:"Fill Formatting Only",fillWithoutFormat:"Fill Without Formatting"});var _FlexSheetAggregate,_SubtotalFunction,FlexSheetFunctions=[{name:"abs",description:"Returns the absolute value of a number."},{name:"acos",description:"Returns the arccosine of a number."},{name:"address",description:"Obtains the address of a cell in a worksheet by given specified row and column numbers."},{name:"and",description:"Returns TRUE if all of its arguments are TRUE."},{name:"asin",description:"Returns the arcsine of a number."},{name:"atan",description:"Returns the arctangent of a number."},{name:"atan2",description:"Returns the arctangent from x- and y-coordinates."},{name:"average",description:"Returns the average of its arguments."},{name:"ceiling",description:"Rounds a number to the nearest integer or to the nearest multiple of significance."},{name:"char",description:"Returns the character specified by the code number."},{name:"choose",description:"Chooses a value from a list of values."},{name:"code",description:"Returns a numeric code for the first character in a text string."},{name:"column",description:"Returns the column number of a reference."},{name:"columns",description:"Returns the number of columns in a reference."},{name:"concat",description:"Joins several text items into one text item."},{name:"concatenate",description:"Joins several text items into one text item."},{name:"cos",description:"Returns the cosine of a number."},{name:"count",description:"Counts how many numbers are in the list of arguments."},{name:"counta",description:"Counts how many values are in the list of arguments."},{name:"countblank",description:"Counts the number of blank cells within a range."},{name:"countif",description:"Counts the number of cells within a range that meet the given criteria."},{name:"countifs",description:"Counts the number of cells within a range that meet multiple criteria."},{name:"date",description:"Returns the serial number of a particular date."},{name:"datedif",description:"Calculates the number of days, months, or years between two dates."},{name:"day",description:"Converts a serial number to a day of the month."},{name:"dcount",description:"Counts the cells that contain numbers in a database."},{name:"exp",description:"Returns e raised to the power of a given number."},{name:"exact",description:"Compares two text strings and returns TRUE if they are exactly the same, FALSE otherwise."},{name:"false",description:"Returns the logical value FALSE."},{name:"find",description:"Finds one text value within another (case-sensitive)."},{name:"floor",description:"Rounds a number down, toward zero."},{name:"hlookup",description:"Looks in the top row of an array and returns the value of the indicated cell."},{name:"hour",description:"Converts a serial number to an hour."},{name:"if",description:"Specifies a logical test to perform."},{name:"iferror",description:"Returns a value you specify if a formula evaluates to an error; otherwise, it returns the result of the formula."},{name:"index",description:"Uses an index to choose a value from a reference."},{name:"indirect",description:"Returns the reference specified by a text string. References are immediately evaluated to display their contents."},{name:"isblank",description:"Checks if value refers to an empty cell."},{name:"iserr",description:"Checks if value is an error (#VALUE!, #REF!, #DIV/0!, #NUM!, #NAME?, or #NULL!) excluding #N/A, and returns TRUE or FALSE."},{name:"iserror",description:"Checks if value is an error (#N/A, #VALUE!, #REF!, #DIV/0!, #NUM!, #NAME?, or #NULL!), and returns TRUE or FALSE."},{name:"left",description:"Returns the leftmost characters from a text value."},{name:"len",description:"Returns the number of characters in a text string."},{name:"ln",description:"Returns the natural logarithm of a number."},{name:"lower",description:"Converts text to lowercase."},{name:"max",description:"Returns the maximum value in a list of arguments."},{name:"mid",description:"Returns a specific number of characters from a text string starting at the position you specify."},{name:"min",description:"Returns the minimum value in a list of arguments."},{name:"mod",description:"Returns the remainder from division."},{name:"month",description:"Converts a serial number to a month."},{name:"not",description:"Reverses the logic of its argument."},{name:"now",description:"Returns the current date and time formatted as a date and time."},{name:"or",description:"Returns TRUE if any argument is TRUE."},{name:"pi",description:"Returns the value of pi."},{name:"power",description:"Returns the result of a number raised to a power."},{name:"product",description:"Multiplies its arguments."},{name:"proper",description:"Capitalizes the first letter in each word of a text value."},{name:"rand",description:"Returns a random number between 0 and 1."},{name:"rank",description:"Returns the rank of a number in a list of numbers."},{name:"rate",description:"Returns the interest rate per period of an annuity."},{name:"replace",description:"Replaces characters within text."},{name:"rept",description:"Repeats text a given number of times."},{name:"right",description:"Returns the rightmost characters from a text value."},{name:"round",description:"Rounds a number to a specified number of digits."},{name:"rounddown",description:"Rounds a number down, toward zero."},{name:"roundup",description:"Rounds a number up, away from zero."},{name:"row",description:"Returns the row number of a reference."},{name:"rows",description:"Returns the number of rows in a reference."},{name:"search",description:"Finds one text value within another (not case-sensitive)."},{name:"sin",description:"Returns the sine of the given angle."},{name:"sqrt",description:"Returns a positive square root."},{name:"stdev",description:"Estimates standard deviation based on a sample."},{name:"stdevp",description:"Calculates standard deviation based on the entire population."},{name:"substitute",description:"Substitutes new text for old text in a text string."},{name:"subtotal",description:"Returns a subtotal in a list or database."},{name:"sum",description:"Adds its arguments."},{name:"sumif",description:"Adds the cells specified by a given criteria."},{name:"sumifs",description:"Adds the cells in a range that meet multiple criteria."},{name:"sumproduct",description:"Multiplies corresponding components in the given arrays, and returns the sum of those products."},{name:"tan",description:"Returns the tangent of a number."},{name:"text",description:"Formats a number and converts it to text."},{name:"time",description:"Returns the serial number of a particular time."},{name:"today",description:"Returns the current date formatted as a date."},{name:"trim",description:"Removes spaces from text."},{name:"true",description:"Returns the logical value TRUE."},{name:"trunc",description:"Truncates a number to an integer."},{name:"upper",description:"Converts text to uppercase."},{name:"value",description:"Converts a text argument to a number."},{name:"var",description:"Estimates variance based on a sample."},{name:"varp",description:"Calculates variance based on the entire population."},{name:"vlookup",description:"Looks in the first column of an array and returns the value of the indicated cell."},{name:"year",description:"Converts a serial number to a year."}];export class FlexSheet extends FlexGrid{constructor(e,t){super(e,t);this._heights=[];this._selectedSheetIndex=-1;this._columnHeaderClicked=!1;this._addingSheet=!1;this._mouseMoveHdl=this._mouseMove.bind(this);this._clickHdl=this._click.bind(this);this._touchStartHdl=this._touchStart.bind(this);this._touchEndHdl=this._touchEnd.bind(this);this._keydownHdl=this._keydown.bind(this);this._isContextMenuKeyDown=!1;this._isClicking=!1;this._builtInTableStylesCache=null;this._needCopyToSheet=!0;this._isSorting=!1;this._fillingData=!1;this._enableDragDrop=!0;this._enableFormulas=!0;this._headerRowRemoved=!1;this._clearCalcCacheOnRefresh=!0;this._copyingTo=!1;this._ignoreBindGrid=!1;this._loadingFromWorkbook=!1;this.insertedColumnIndex=0;this.dropzonePrevHit=-1;this.selectedSheetChanged=new Event;this.draggingRowColumn=new Event;this.droppingRowColumn=new Event;this.beginDroppingRowColumn=new Event;this.endDroppingRowColumn=new Event;this.loaded=new Event;this.unknownFunction=new Event;this.sheetCleared=new Event;this.prepareChangingRow=new Event;this.prepareChangingColumn=new Event;this.rowChanged=new Event;this.columnChanged=new Event;this.autoFilling=new Event;this.autoFilled=new Event;this._updateScrollPos=!1;t&&null!=t.allowAutoFill||(this._allowAutoFill=!0);this._needCopyToSheet=!1;this._colorThemes=["FFFFFF","000000","EEECE1","1F497D","4F818D","C0504D","9BBB59","8064A2","4BACC6","F79646"];this._eCt.style.backgroundColor="white";addClass(this.hostElement,"wj-flexsheet");setCss(this.hostElement,{fontFamily:"Arial"});this._cf=new _FlexSheetCellFactory;this._bndSortConverter=this._sheetSortConverter.bind(this);this._selHdl=new _FlexSheetSelectionHandler(this);this.quickAutoSize=!1;this._init();this.showSort=!1;this.allowSorting=AllowSorting.None;this.showGroups=!1;this.showMarquee=!0;this.showSelectedHeaders=HeadersVisibility.All;this.allowResizing=AllowResizing.Both;this.allowDragging=AllowDragging.None;this.keyActionTab=KeyAction.CycleOut;this._needCopyToSheet=!0}_getProductInfo(){return"R20I,FlexSheet"}get sheets(){this._sheets||(this._sheets=new SheetCollection);return this._sheets}get selectedSheetIndex(){return this._selectedSheetIndex}set selectedSheetIndex(e){if(e!==this._selectedSheetIndex){this._showSheet(e);this._sheets.selectedIndex=e}}get selectedSheet(){return this._selectedSheetIndex>=0?this._sheets[this._selectedSheetIndex]:null}get isFunctionListOpen(){return this._functionListHost&&"none"!==this._functionListHost.style.display}get isTabHolderVisible(){return this._tabHolder.visible}set isTabHolderVisible(e){if(e!==this._tabHolder.visible){this._updateDivContainerHeight(e);e?this._eFocus.removeAttribute("tabindex"):this._eFocus.tabIndex=this._orgTabIndex;this._tabHolder.visible=e;this.invalidate()}}get undoStack(){return this._undoStack}get sortManager(){return this._sortManager}get filter(){return this._filter}get showFilterIcons(){return!!this._filter&&this._filter.showFilterIcons}set showFilterIcons(e){this._filter&&this._filter.showFilterIcons!==e&&(this._filter.showFilterIcons=e)}get calculationPrecision(){let e=this._precision;return null==e?14:e}set calculationPrecision(e){if(e!==this._precision){this._precision=e;this.invalidate()}}get definedNames(){this._defNames||(this._defNames=new DefinedNameCollection(this));return this._defNames}get enableDragDrop(){return this._enableDragDrop}set enableDragDrop(e){this._enableDragDrop=e}get enableFormulas(){return this._enableFormulas}set enableFormulas(e){if(this._enableFormulas!==e){this._enableFormulas=e;this.refresh()}}get allowAutoFill(){return this._allowAutoFill}set allowAutoFill(e){this._allowAutoFill=asBoolean(e)}get _lastSelMovePos(){return this._lsmPos}set _lastSelMovePos(e){this._lsmPos=e?e.clone():null}_setvalidateEdits(e){super._setvalidateEdits(e);for(let t=0;t<this.sheets.length;t++)this.sheets[t].grid&&(this.sheets[t].grid.validateEdits=e)}onSelectedSheetChanged(e){this.selectedSheetChanged.raise(this,e)}onDraggingRowColumn(e){this.draggingRowColumn.raise(this,e)}onDroppingRowColumn(e){_deprecated("droppingRowColumn","beginDroppingRowColumn and endDroppingRowColumn");this.droppingRowColumn.raise(this,new EventArgs)}onBeginDroppingRowColumn(e){this.beginDroppingRowColumn.raise(this,e)}onEndDroppingRowColumn(e){this.endDroppingRowColumn.raise(this,e)}onLoaded(e){if(this._toRefresh){clearTimeout(this._toRefresh);this._toRefresh=null}this._toRefresh=setTimeout(()=>{this._setFlexSheetToDirty();this.invalidate()},10);this.loaded.raise(this,new EventArgs)}onUnknownFunction(e){this.unknownFunction.raise(this,e)}onSheetCleared(e){this.sheetCleared.raise(this,e)}onPrepareChangingRow(e){this.prepareChangingRow.raise(this,e)}onPrepareChangingColumn(e){this.prepareChangingColumn.raise(this,e)}onRowChanged(e){this.rowChanged.raise(this,e)}onColumnChanged(e){this.columnChanged.raise(this,e)}onAutoFilling(e){this.autoFilling.raise(this,e)}onAutoFilled(e){this.autoFilled.raise(this,e)}refresh(e=!0){if(this.selectedSheet&&this.selectedSheet.grid.rows&&this._items&&this.selectedSheet.grid.rows.length<this._items.length){const e=this._items.length-this.selectedSheet.grid.rows.length;for(let t=0;t<=e;t++)this.selectedSheet.grid.rows.push(new Row)}this.hostElement&&!this.isUpdating&&this._updateDivContainerHeight(this.isTabHolderVisible);if(!this.preserveSelectedState&&this.selectedSheet){this.selectedSheet.selectionRanges.clear();this.selectedSheet.selectionRanges.push(this.selection)}if(e){this._clearCalcCacheOnRefresh&&this._clearCalcEngine();this._clearCalcCacheOnRefresh=!0}this._lastVisibleFrozenRow=-1;if(this.rows.frozen>0)for(let e=this.rows.frozen-1;e>=0;e--)if(this.rows[e]&&this.rows[e].isVisible){this._lastVisibleFrozenRow=e;break}this._lastVisibleFrozenColumn=-1;if(this.columns.frozen>0)for(let e=this.columns.frozen-1;e>=0;e--)if(this.columns[e]&&this.columns[e].isVisible){this._lastVisibleFrozenColumn=e;break}if(this.selectedSheet){if(this.selectedSheet._freezeHiddenRows&&this.selectedSheet._freezeHiddenRows.length>0)for(let e=0;e<this.selectedSheet._freezeHiddenRows.length;e++){let t=this.rows[e];t instanceof HeaderRow||!this.selectedSheet._freezeHiddenRows[e]||(t.visible=!1)}if(this.selectedSheet._freezeHiddenCols&&this.selectedSheet._freezeHiddenCols.length>0)for(let e=0;e<this.selectedSheet._freezeHiddenCols.length;e++)this.selectedSheet._freezeHiddenCols[e]&&(this.columns[e].visible=!1)}super.refresh(e);if(this.hostElement&&!this.isUpdating){this._tabHolder.adjustSize();this._tabHolder.isDisabled=this.isDisabled;this._tabHolder.sheetControl.isDisabled=this.isDisabled}}setCellData(e,t,i,o=!1,l=!0,s=!1){var n=_isFormula(i);n&&this.evaluate(i,null,this.sheets[this.selectedSheetIndex]);this._clearCalcEngine();return this.cells.setCellData(e,t,i,o&&!n,l,s)||this._getHasValidation()}containsFocus(){return this.isFunctionListOpen||super.containsFocus()}addUnboundSheet(e,t,i,o,l){var s=this._addSheet(e,t,i,o,l);0===s.selectionRanges.length&&s.selectionRanges.push(this.selection);return s}addBoundSheet(e,t,i,o){var l=this._addSheet(e,0,0,i,o);if(t){l.itemsSource=t;this.childItemsPath&&(l.grid.childItemsPath=this.childItemsPath)}0===l.selectionRanges.length&&l.selectionRanges.push(this.selection);return l}applyCellsStyle(e,t,i=!1){var o,l,s,n,r,a=null!=t&&t.length>0,h=t||[this.selection];if(this.selectedSheet)if(e||!this._cloneStyle){if(h){if(t||i)i&&!this._cloneStyle&&(this._cloneStyle=this._cloneObject(this.selectedSheet._styledCells));else{this.undoStack.stackSize>0&&(r=new _CellStyleAction(this,this._cloneStyle));this._cloneStyle=null}for(n=0;n<h.length;n++)for(o=(s=h[n]).topRow;o<=s.bottomRow;o++)for(l=s.leftCol;l<=s.rightCol;l++)this._applyStyleForCell(o,l,e,a);if(r){r.saveNewState();this._undoStack._addAction(r)}}t||this.refresh(!1)}else{this.selectedSheet._styledCells=this._cloneObject(this._cloneStyle);this._cloneStyle=null;this.refresh(!1)}}freezeAtCursor(){let e,t;if(this.selectedSheet){this.selectedSheet._freezeHiddenRows=null;this.selectedSheet._freezeHiddenCols=null;if(this.selection&&0===this.rows.frozen&&0===this.columns.frozen){if(this._ptScrl.y<0){this.selectedSheet._freezeHiddenRows=[];for(let e=0;e<this.selection.topRow-1;e++){let t=this.rows[e];if(!(t instanceof HeaderRow)){if(!(t._pos+this._ptScrl.y<0&&t.visible))break;t.visible=!1;this.selectedSheet._freezeHiddenRows[e]=!0}}}if(this._ptScrl.x<0){this.selectedSheet._freezeHiddenCols=[];for(let e=0;e<this.selection.leftCol-1;e++){let t=this.columns[e];if(!(t._pos+this._ptScrl.x<0&&t.visible))break;t.visible=!1;this.selectedSheet._freezeHiddenCols[e]=!0}}e=this.selection.leftCol>0?this.selection.leftCol:0;t=this.selection.topRow>0?this.selection.topRow:0}else{for(let e=0;e<this.rows.frozen-1&&e<this.rows.length;e++)this.rows[e].visible=!0;for(let e=0;e<this.columns.frozen-1&&e<this.columns.length;e++)this.columns[e].visible=!0;this._filter.apply();e=0;t=0}this.rows.frozen=this.selectedSheet.grid.rows.frozen=t;this.columns.frozen=this.selectedSheet.grid.columns.frozen=e;setTimeout(()=>{this._setFlexSheetToDirty();this.invalidate();this.scrollIntoView(this.selection.topRow,this.selection.leftCol)},10)}}showColumnFilter(){var e=this.selection.col>0?this.selection.col:0;this.columns.length>0&&this._filter.editColumnFilter(this.columns[e])}clear(){this.beginUpdate();this.selection=new CellRange;this.sheets.clear();this._selectedSheetIndex=-1;this.columns.clear();this.rows.clear();this.columnHeaders.columns.clear();this.rowHeaders.rows.clear();this._undoStack.clear();this._ptScrl=new Point;this._clearCalcEngine();this._defNames&&this._defNames.clear();this._builtInTableStylesCache=null;this._copiedRanges=null;this._copiedSheet=null;this._isCutting=!1;this._cutValue=null;this._reservedContent=null;this._lastVisibleFrozenRow=-1;this._lastVisibleFrozenColumn=-1;this._loadingFromWorkbook||this.addUnboundSheet();this.endUpdate()}getSelectionFormatState(){var e,t,i=this.rows.length,o=this.columns.length,l={isBold:!1,isItalic:!1,isUnderline:!1,textAlign:"left",isMergedCell:!1,verticalAlign:"top"};if(0===i||0===o)return l;if(this.selection){if(this.selection.row>=i||this.selection.row2>=i||this.selection.col>=o||this.selection.col2>=o)return l;for(e=this.selection.topRow;e<=this.selection.bottomRow;e++)for(t=this.selection.leftCol;t<=this.selection.rightCol;t++)this._checkCellFormat(e,t,l)}return l}insertRows(e,t){var i,o,l,s=isNumber(e)&&e>=0?e:this.selection&&this.selection.topRow>-1?this.selection.topRow:0,n=isNumber(t)?t:1,r=this.rows[s];if(!this.selectedSheet)return;this.rows.length>0?s>=this.rows.length&&(s=this.rows.length-1):s=0;let a=this.collectionView,h=this.editableCollectionView,d=a instanceof CollectionView?a:null;this._clearCalcEngine();this.finishEditing();h&&h.currentEditItem&&h.commitEdit();0===s&&r&&r.constructor===HeaderRow&&(s=1);this.onPrepareChangingRow(new RowColumnChangedEventArgs(s,n,!0,!1));this.undoStack.stackSize>0&&(i=new _RowsChangedAction(this,s,n,!0));this._updateCellsForUpdatingRow(this.rows.length,s,n);if(!this.collectionView||0===this.collectionView.sortDescriptions.length){o=this._updateAffectedFormula(s,n,!0,!0);l=this._updateAffectedNamedRanges(s,n,!0,!0)}if(i){i._affectedFormulas=o;i._affectedDefinedNameVals=l}let u=null==this.selectedSheet.grid.collectionView;this.beginUpdate();if(a){let e,t=this.itemsSource instanceof CollectionView,i=this.autoGenerateColumns;this.selectedSheet._dataView=this.collectionView._view.slice();this.autoGenerateColumns=!1;this.collectionView.beginUpdate();this.rows[0]instanceof _NewRowTemplate&&this.rows[1]instanceof HeaderRow?this._heights.splice(2,0,...Array(n).map(()=>null)):this._heights.splice(s,0,...Array(n).map(()=>null));if(!t){e=this.selectedSheet.grid.autoGenerateColumns;this.selectedSheet.grid.autoGenerateColumns=!1;u||this.selectedSheet.grid.collectionView.beginUpdate()}let o=Math.max(s-this._getDataRowsOffset(),0);this.collectionView.moveCurrentToPosition(o);for(let e=0;e<n;e++){let e=d&&d.newItemCreator?d.newItemCreator():{};a.sourceCollection.splice(o,0,e);d&&d.trackChanges&&d.itemsAdded.push(e);if(!t){let t=this.selectedSheet.grid.itemsSource;t&&this.itemsSource!==t&&t.splice(o,0,e)}this.selectedSheet._dataView.splice(o,0,e)}this._updateItemIndexForInsertingRow(this.collectionView.sourceCollection,o,n);if(!t){u||this.selectedSheet.grid.collectionView.endUpdate(!0);this.selectedSheet.grid.autoGenerateColumns=e}let l=this.collectionView._idx;this.collectionView.endUpdate(!0);this.updateRowHeights();if(this.collectionView.sortDescriptions.length>0){this.collectionView._view=this.selectedSheet._dataView;this.collectionView._pgView=this.collectionView._getPageView();this.collectionView._idx=l;if(!t&&!u){this.selectedSheet.grid.collectionView._view=this.selectedSheet._dataView;this.selectedSheet.grid.collectionView._pgView=this.selectedSheet.grid.collectionView._getPageView();this.collectionView._idx=l}this._bindGrid(!1);this.selectedSheet.grid._bindGrid(!1)}setTimeout(()=>{this._filter.apply()});this.autoGenerateColumns=i}else{this.rows.beginUpdate();for(let e=0;e<n;e++)this.rows.insert(s,new Row);let e=this.selectedSheet._freezeHiddenRows;if(e&&e.length)for(let t=s+n;t<this.rows.length;t++)e[t]||(this.rows[t].visible=!0);this.rows.endUpdate()}this._updateTablesForUpdatingRow(s,n);this.selection&&-1!==this.selection.row&&-1!==this.selection.col||this.select(new CellRange(0,0),!1);if(i){i.saveNewState();this._undoStack._addAction(i)}this.onRowChanged(new RowColumnChangedEventArgs(s,n,!0,!1));this.endUpdate()}deleteRows(e,t){if(!this.selectedSheet||this.rows.length<1)return;let i=e,o=isArray(e);if(!o)if(isNumber(e)){if((t=isNumber(t)?t:1)<1)return;i=[new CellRange(e,-1,e+t-1,-1)]}else o=(i=this._selections()).length>1;let l=!!this.collectionView;if(l){let e=[];i.forEach(t=>{if(t.row>=0&&t.row2>=0)for(let i=t.topRow,o=t.bottomRow;i<=o;i++)(this.rows[i]instanceof HeaderRow||this.rows[i]instanceof _NewRowTemplate)&&e.push(i)});e.forEach(e=>_RangesHelper.excludeRow(i,e))}if(!(i=_RangesHelper.validateRowRanges(i,this.rows.length)).length)return;i.forEach(e=>{e.col=e.col2=-1});this._clearCalcEngine();this.finishEditing();let s,n=this.selection.topRow,r=o?new RowColumnChangedEventArgs(i,!1,!1):new RowColumnChangedEventArgs(i[0].topRow,i[0].rowSpan,!1,!1);this.onPrepareChangingRow(r);this.undoStack.stackSize>0&&(s=new _RowsChangedAction(this,null,null,!1));let a,h,d=l&&this.itemsSource instanceof CollectionView,u=null==this.selectedSheet.grid.collectionView,c=0;this.beginUpdate();this._isDeletingRows=!0;if(l){this.selectedSheet._dataView=this.collectionView._view.slice();a=this.autoGenerateColumns;this.autoGenerateColumns=!1;this.collectionView.beginUpdate();if(!d){h=this.selectedSheet.grid.autoGenerateColumns;this.selectedSheet.grid.autoGenerateColumns=!1;u||this.selectedSheet.grid.collectionView.beginUpdate()}}else this.rows.beginUpdate();for(let e=i.length-1;e>=0;e--){let t,o=i[e],l=new CellRangeEventArgs(this.cells,o);if(this.onDeletingRow(l)){if(s){(t=new _RowsChangedAction(this,o.topRow,o.rowSpan,!1))._affectedFormulas=this._updateAffectedFormula(o.bottomRow,o.rowSpan,!1,!0);t._affectedDefinedNameVals=this._updateAffectedNamedRanges(o.bottomRow,o.rowSpan,!1,!0);t._deletedTables=this._updateTablesForUpdatingRow(o.topRow,o.rowSpan,!0);s.addDeleteSubAction(t)}this._updateCellsForUpdatingRow(this.rows.length,o.topRow,o.rowSpan,!0);for(let e=o.bottomRow;e>=o.topRow;e--){let t=this.rows[e];if(!t||t.isVisible){c++;if(t.dataItem&&this.editableCollectionView){let i;this.editableCollectionView.remove(t.dataItem);const o=this.selectedSheet._dataView.indexOf(t.dataItem);this.selectedSheet._dataView.splice(o,1);const l=Array.from(this.rows).map(e=>e.height);l.splice(e,1);this.setHeights(l);d||(i=this.itemsSource.indexOf(t.dataItem));this._updateItemIndexForRemovingRow(this.collectionView.sourceCollection,i)}else this.rows.removeAt(e)}}t&&t.saveNewState();this.onDeletedRow(l)}}if(l){if(!d){u||this.selectedSheet.grid.collectionView.endUpdate(c>0);this.selectedSheet.grid.autoGenerateColumns=h}this.collectionView.endUpdate(c>0);this.updateRowHeights();if(this.collectionView.sortDescriptions.length>0){this.collectionView._view=this.selectedSheet._dataView;this.collectionView._pgView=this.collectionView._getPageView();if(!d&&!u){this.selectedSheet.grid.collectionView._view=this.selectedSheet._dataView;this.selectedSheet.grid.collectionView._pgView=this.selectedSheet.grid.collectionView._getPageView()}this._bindGrid(!1);this.selectedSheet.grid._bindGrid(!1)}this.autoGenerateColumns=a}else this.rows.endUpdate();this.selectedSheet.selectionRanges.clear();let _,g=this.rows.length;if(0===g)_=new CellRange;else if(this.selection.topRow>=g)_=new CellRange(g-1,0,g-1,this.columns.length-1);else{let e=n;this.selection.topRow>=0&&(e=Math.min(e,this.selection.topRow));_=new CellRange(e,0,e,this.columns.length-1)}this.select(_,!1);0===g&&"move"===this.hostElement.style.cursor&&(this.hostElement.style.cursor="default");if(s){s.saveNewState();this._undoStack._addAction(s)}this.onRowChanged(r);this._isDeletingRows=!1;this.endUpdate()}insertColumns(e,t){var i,o,l,s=isNumber(e)&&e>=0?e:this.selection&&this.selection.leftCol>-1?this.selection.leftCol:0,n=isNumber(t)?t:1;if(this.selectedSheet){this.columns.length>0?s>=this.columns.length&&(s=this.columns.length-1):s=0;this._clearCalcEngine();this.finishEditing();this.onPrepareChangingColumn(new RowColumnChangedEventArgs(s,n,!0,!0));this.undoStack.stackSize>0&&(i=new _ColumnsChangedAction(this,s,n,!0));this._updateCellsForUpdatingColumn(this.columns.length,s,n);o=this._updateAffectedFormula(s,n,!0,!1);l=this._updateAffectedNamedRanges(s,n,!0,!1);if(i){i._affectedFormulas=o;i._affectedDefinedNameVals=l}this.deferUpdate(()=>{this.columns.beginUpdate();for(let e=0;e<n;e++){let e=new Column;e.isRequired=!1;if(this.itemsSource){e.binding=this._getUniqueColumnName();let t=this.rows[this._getDataRowsOffset()-1];if(t){t._ubv||(t._ubv={});t._ubv[e._hash]=FlexSheet._getHeaderRowText(e)}}this.columns.insert(s,e)}this.columns.endUpdate();this.selectedSheet._filterDefinition=this._filter.filterDefinition;this.selectedSheet.grid.columns._dirty=!1;this._sortManager._updateSortDescriptions(s,n);this._sortManager.commitSort(!1);this._updateTablesForUpdatingColumn(s,n);this.selection&&-1!==this.selection.row&&-1!==this.selection.col||this.select(new CellRange(0,0),!1);if(i){i.saveNewState();this._undoStack._addAction(i)}this.onColumnChanged(new RowColumnChangedEventArgs(s,n,!0,!0))});this.updateRowHeights()}}deleteColumns(e,t){if(!this.selectedSheet)return;let i=e,o=isArray(e);if(!o)if(isNumber(e)){if((t=isNumber(t)?t:1)<1)return;i=[new CellRange(-1,e,-1,e+t-1)]}else o=(i=this._selections()).length>1;if(!(i=_RangesHelper.validateColumnRanges(i,this.columns.length)).length)return;let l=this.selection.leftCol,s=0;i.forEach(e=>{s+=e.columnSpan;e.row=e.row2=-1});this._clearCalcEngine();this.finishEditing();let n,r=o?new RowColumnChangedEventArgs(i,!1,!0):new RowColumnChangedEventArgs(i[0].leftCol,i[0].columnSpan,!1,!0);this.onPrepareChangingColumn(r);this.undoStack.stackSize>0&&(n=new _ColumnsChangedAction(this,null,null,!1));this.beginUpdate();this._isDeletingColumns=!0;let a=this.filter?this.filter._filters:null,h=!1;this.columns.beginUpdate();for(let e=i.length-1;e>=0;e--){let t,o=i[e];if(n){(t=new _ColumnsChangedAction(this,o.leftCol,o.columnSpan,!1))._affectedFormulas=this._updateAffectedFormula(o.rightCol,o.columnSpan,!1,!1);t._affectedDefinedNameVals=this._updateAffectedNamedRanges(o.rightCol,o.columnSpan,!1,!1);t._deletedTables=this._updateTablesForUpdatingColumn(o.leftCol,o.columnSpan,!0);n._delSubActions.push(t)}this._updateCellsForUpdatingColumn(this.columns.length,o.leftCol,o.columnSpan,!0);for(let e=o.rightCol;e>=o.leftCol;e--){const t=this.columns[e];if(t.isVisible){if(a)for(let e=0;e<a.length;e++)if(a[e].column===t){a.splice(e,1);h=!0;break}this.columns.removeAt(e);this._sortManager.deleteSortLevel(e)}}this._sortManager._updateSortDescriptions(o.leftCol,o.columnSpan,!1)}this.columns.endUpdate();if(h){for(let e=0;e<this.columns.length;e++)this.columns[e].isVisible&&this.filter._updateColumnFilter(this.columns[e]);this.filter.apply()}this.selectedSheet._filterDefinition=this._filter.filterDefinition;this.selectedSheet.grid.columns._dirty=!1;this._sortManager.commitSort(!1);this.selectedSheet.selectionRanges.clear();let d,u=this.columns.length;if(0===u){d=new CellRange;"move"===this.hostElement.style.cursor&&(this.hostElement.style.cursor="default")}else if(this.selection.leftCol>=u)d=new CellRange(0,u-1,this.rows.length-1,u-1);else{let e=l-s+1;e=Math.max(e,i[0].leftCol);e=Math.min(e,this.selection.leftCol);d=new CellRange(this.selection.row,e,this.selection.row2,e)}this.select(d,!1);if(n){this._undoStack._addAction(n);n._delSubActions.forEach(e=>e.saveNewState())}this.onColumnChanged(r);this._isDeletingColumns=!1;this.endUpdate();this.updateRowHeights()}mergeRange(e,t=!1){var i,o,l,s,n,r=e||this.selection,a=-1,h=-1;if(this.selectedSheet){if(r){if(1===r.rowSpan&&1===r.columnSpan)return;for(i=r.topRow;i<=r.bottomRow;i++)for(o=r.leftCol;o<=r.rightCol;o++)if(this.selectedSheet.findTable(i,o))return;if(!e&&!t){this.undoStack.stackSize>0&&(n=new _CellMergeAction(this));this.hostElement.focus()}if(!this._resetMergedRange(r)){for(i=r.topRow;i<=r.bottomRow;i++)if((l=this.rows[i])&&l.isVisible){a=i;break}for(o=r.leftCol;o<=r.rightCol;o++)if((s=this.columns[o])&&s.isVisible){h=o;break}a>-1&&h>-1&&this.selectedSheet._mergedRanges.push(new CellRange(a,h,r.bottomRow,r.rightCol))}if(n){n.saveNewState();this._undoStack._addAction(n)}}e||this.refresh()}}getMergedRange(e,t,i,o=!0){var l,s,n,r,a=this.selectedSheet?this.selectedSheet._getMergedRange(t,i):null;if(e===this.cells&&a){if(!a.isSingleCell&&(this.rows.frozen>0||this.columns.frozen>0)&&(a.topRow<this.rows.frozen&&a.bottomRow>=this.rows.frozen||a.leftCol<this.columns.frozen&&a.rightCol>=this.columns.frozen)){l=a.topRow;s=a.bottomRow;n=a.leftCol;r=a.rightCol;t>=this.rows.frozen&&a.topRow<this.rows.frozen&&(l=this.rows.frozen);t<this.rows.frozen&&a.bottomRow>=this.rows.frozen&&(s=this.rows.frozen-1);s>=this.rows.length&&(s=this.rows.length-1);i>=this.columns.frozen&&a.leftCol<this.columns.frozen&&(n=this.columns.frozen);i<this.columns.frozen&&a.rightCol>=this.columns.frozen&&(r=this.columns.frozen-1);r>=this.columns.length&&(r=this.columns.length-1);return new CellRange(l,n,s,r)}return a.bottomRow>=this.rows.length?new CellRange(a.topRow,a.leftCol,this.rows.length-1,a.rightCol):a.rightCol>=this.columns.length?new CellRange(a.topRow,a.leftCol,a.bottomRow,this.columns.length-1):a.clone()}return super.getMergedRange(e,t,i,o)}evaluate(e,t,i,o=!0){let l=this._evaluate(e,t,i);return o&&null!=l&&!isPrimitive(l)?l instanceof FormulaError?l.error:l.value:l}getCellValue(e,t,i=!1,o){var l=o&&o!==this.selectedSheet?o.grid.columns[t]:this.columns[t],s=this._getCellStyle(e,t,o),n=s&&s.format||null,r=o&&o!==this.selectedSheet?o.grid.getCellData(e,t,!1):this.getCellData(e,t,!1);if(isString(r)){let i=o||this.selectedSheet;if(i){let o=i.findTable(e,t);if(o&&o._isHeaderRow(e))return r}var a=_FormulaErrorHelper.asError(r);if(a)return a;if(_isFormula(r)&&(r=this._evaluate(r,null,o,e,t))instanceof FormulaError)return r}if(i){n||null==r||isPrimitive(r)||(n=r.format);r=this._formatEvaluatedResult(r,l,n)}else null==r||isPrimitive(r)||(r=r.value);return 0===i?r:null==r?"":r}showFunctionList(e){if(this._enableFormulas){this._functionTarget=tryCast(e,HTMLInputElement);if(this._functionTarget&&this._functionTarget.value&&"="===this._functionTarget.value[0]){this._functionList._cv.filter=e=>{var t,i=e.actualvalue.toLowerCase(),o=this._getCurrentFormulaIndex(this._functionTarget.value);-1===o&&(o=0);return(t=this._functionTarget.value.substr(o+1).trim().toLowerCase()).length>0&&0===i.indexOf(t)||"="===this._functionTarget.value};this._functionList.selectedIndex=0;let t=this._cumulativeOffset(e),i=this._cumulativeOffset(this._root),o=t.y+e.clientHeight+2+(hasClass(e,"wj-grid-editor")?this._ptScrl.y:0),l=t.x+(hasClass(e,"wj-grid-editor")?this._ptScrl.x:0);setCss(this._functionListHost,{height:this._functionList._cv.items.length>5?"218px":"auto",display:this._functionList._cv.items.length>0?"block":"none",top:"",left:""});this._functionListHost.scrollTop=0;this._functionListHost.offsetHeight+o>i.y+this._root.offsetHeight?o=o-e.clientHeight-this._functionListHost.offsetHeight-5:o+=5;this._functionListHost.offsetWidth+l>i.x+this._root.offsetWidth&&(l=i.x+this._root.offsetWidth-this._functionListHost.offsetWidth);setCss(this._functionListHost,{top:o,left:l})}else this.hideFunctionList()}}hideFunctionList(){this._functionListHost.style.display="none"}selectPreviousFunction(){this._functionList.selectedIndex>0&&this._functionList.selectedIndex--}selectNextFunction(){this._functionList.selectedIndex<this._functionList.itemsSource.length&&this._functionList.selectedIndex++}applyFunctionToCell(){if(this._functionTarget){let e=this._getCurrentFormulaIndex(this._functionTarget.value);-1===e?e=this._functionTarget.value.indexOf("="):e+=1;this._functionTarget.value=this._functionTarget.value.substring(0,e)+this._functionList.selectedValue+"(";"="!==this._functionTarget.value[0]&&(this._functionTarget.value="="+this._functionTarget.value);this._functionTarget.focus();this.hideFunctionList()}}save(e,t){var i=this._saveToWorkbook(t);e&&i.save(e);return i}saveAsync(e,t,i,o){var l=this._saveToWorkbook(o);l.saveAsync(e,t,i);return l}saveToWorkbookOM(e){return this._saveToWorkbook(e)._serialize()}load(e){if(e instanceof Blob)_blobToBuffer(e,t=>{e=null;let i=new mXlsx.Workbook;i.load(t);t=null;this._loadFromWorkbook(i);i=null});else if(e instanceof mXlsx.Workbook){this._loadFromWorkbook(e);e=null}else{if(!(e instanceof ArrayBuffer||isString(e)))throw"Invalid workbook.";let t=new mXlsx.Workbook;t.load(e);e=null;this._loadFromWorkbook(t);t=null}}loadAsync(e,t,i){if(e instanceof Blob)_blobToBuffer(e,o=>{e=null;let l=new mXlsx.Workbook;l.loadAsync(o,()=>{this._loadFromWorkbook(l);t&&t(l);o=null;l=null},i)});else if(e instanceof mXlsx.Workbook){this._loadFromWorkbook(e);t&&t(e);e=null}else{if(!(e instanceof ArrayBuffer||isString(e)))throw"Invalid workbook.";let o=new mXlsx.Workbook;o.loadAsync(e,()=>{e=null;this._loadFromWorkbook(o);t&&t(o);o=null},i)}}loadFromWorkbookOM(e){var t;e instanceof mXlsx.Workbook?t=e:(t=new mXlsx.Workbook)._deserialize(e);this._loadFromWorkbook(t)}undo(){setTimeout(()=>{this._undoStack.undo()},100)}redo(){setTimeout(()=>{this._undoStack.redo()},100)}select(e,t=!0){var i,o,l;if(isNumber(e)&&isNumber(t)){e=new CellRange(e,t);this._lastSelMovePos=e;t=!0}else this._lastSelMovePos=null;if(e.rowSpan!==this.rows.length&&e.columnSpan!==this.columns.length)for(o=e.topRow;o<=e.bottomRow;o++)for(l=e.leftCol;l<=e.rightCol;l++)if((i=this.getMergedRange(this.cells,o,l))&&!e.equals(i)){if(e.row<=e.row2){e.row=Math.min(e.topRow,i.topRow);e.row2=Math.max(e.bottomRow,i.bottomRow)}else{e.row=Math.max(e.bottomRow,i.bottomRow);e.row2=Math.min(e.topRow,i.topRow)}if(e.col<=e.col2){e.col=Math.min(e.leftCol,i.leftCol);e.col2=Math.max(e.rightCol,i.rightCol)}else{e.col=Math.max(e.rightCol,i.rightCol);e.col2=Math.min(e.leftCol,i.leftCol)}}this._isPasting&&this.collectionView&&(this.collectionView._pendingRefresh=!1);!this._enableMulSel&&this.selectedSheet&&this.selectedSheet.selectionRanges.clear();return super.select(e,t)}addCustomFunction(e,t,i,o,l){_deprecated("addCustomFunction","addFunction");this._calcEngine.addCustomFunction(e,t,o,l);this._addCustomFunctionDescription(e,i)}addFunction(e,t,i,o,l){this._calcEngine.addFunction(e,t,o,l);this._addCustomFunctionDescription(e,i)}dispose(){var e=window.navigator.userAgent;this._needCopyToSheet=!1;this.removeEventListener(document.body,"mousemove",this._mouseMoveHdl);this.removeEventListener(document.body,"keydown",this._keydownHdl);this.removeEventListener(document.body,"click",this._clickHdl);if(e.match(/iPad/i)||e.match(/iPhone/i)){this.removeEventListener(document.body,"touchstart",this._touchStartHdl);this.removeEventListener(document.body,"touchend",this._touchEndHdl)}this._filter&&this._filter.filterApplied.removeAllHandlers();this.hideFunctionList();if(!this.itemsSource){let e=this._selHdl.selection;e.row=e.row2=-1}super.dispose()}getClipString(e){var t,i,o,l,s,n,r="",a=!0;if(!this.selectedSheet)return super.getClipString(e);this._isCutting=!1;if(!e)if(this.selectedSheet.selectionRanges.length>1){if(this._isMultipleRowsSelected()){r="";(t=this._selections()).sort(this._sortByRow);for(o=0;o<t.length;o++){r&&(r+="\n");r+=this.getClipString(t[o])}return r}if(this._isMultipleColumnsSelected()){r="";(t=this._selections()).sort(this._sortByColumn);for(i=(l=t[0]).topRow,a=!0;i<=l.bottomRow;i++){a||(r+="\n");a=!1;for(o=0,c=!0;o<t.length;o++){s=t[o];c||(r+="\t");c=!1;r+=this.getClipString(new CellRange(i,s.col,i,s.col2))}}return r}assert(!1,"Copy or Cut operation cannot be used on multiple selections.")}else{let t=this.selectionMode;if(t!=SelectionMode.ListBox){let e=this.rows;for(let i=0;i<e.length;i++)if(e[i].isSelected){t=SelectionMode.ListBox;break}}e=this.selection;switch(t){case SelectionMode.Row:case SelectionMode.RowRange:e.col=0;e.col2=this.columns.length-1;break;case SelectionMode.ListBox:e.col=0;e.col2=this.columns.length-1;for(var h=0;h<this.rows.length;h++)if(this.rows[h].isSelected&&this.rows[h].isVisible){e.row=e.row2=h;r&&(r+="\n");r+=this.getClipString(e)}return r}}if(!(e=asType(e,CellRange)).isValid)return"";var d=e.topRow;for(a=!0;d<=e.bottomRow;d++)if(this.rows[d].isVisible){a||(r+="\n");a=!1;for(var u=e.leftCol,c=!0;u<=e.rightCol;u++)if(this.columns[u].isVisible){c||(r+="\t");c=!1;(n=(n=this.getCellValue(d,u,!0).toString()).replace(/\t/g," ")).indexOf("\n")>-1&&(n='"'+n.replace(/"/g,'""')+'"');r+=n}}return r}setClipString(e,t){let i=null==t,o=!1;if(!this.selectedSheet){super.setClipString(e,t);return}t=t?asType(t,CellRange):this.selection;let l=e=asString(e).replace(/\r\n/g,"\n").replace(/\r/g,"\n"),s=this._edtHdl._parseClipString(asString(e));i&&!t.isSingleCell&&s.length&&this._edtHdl._expandClipRows(s,t);let n=this._containsMultiLineText(s);if((!this._copiedRanges||0===this._copiedRanges.length||l.trim()!==this._getRangeString(this._copiedRanges,this._copiedSheet).trim()&&!this._containsRandFormula(this._copiedRanges,this._copiedSheet)||this._cutValue)&&!n){if(l!==this._cutValue){this._cutValue=null;super.setClipString(e)}this._copiedRanges=null;this._copiedSheet=null;return}if(this._copiedRanges){var r=this._getRangeString(this._copiedRanges,this._copiedSheet,!1)+"\r\n";r=asString(r).replace(/\r\n/g,"\n").replace(/\r/g,"\n");s=this._edtHdl._parseClipString(asString(r));i&&!t.isSingleCell&&s.length&&this._edtHdl._expandClipRows(s,t)}let a=t.topRow+s.length-1;a>=this.rows.length&&(a=this.rows.length-1);let h=t.leftCol;if(s.length)for(let e=h,t=0;e<this.columns.length&&t<s[0].length;e++){this.columns[e].visible&&t++;h=e}let d=new CellRange(t.topRow,t.leftCol,a,h);if(!this.onPasting(new CellRangeEventArgs(this.cells,d,e))){this._cutValue=null;this._copiedRanges=null;this._copiedSheet=null;return}this.beginUpdate();let u=s.length>1,c=this.editableCollectionView;c&&u&&c.beginUpdate();if(n||!this._copiedRanges||this._copiedRanges.length>1||0===this._copiedRanges.length){let e=0,i=this._copiedRanges&&this._copiedRanges.length>1?this._copiedRanges[0]:new CellRange,l=i.topRow;for(let n=0,r=t.topRow;n<s.length&&r<this.rows.length;n++,r++){let a=this.rows[r];if(!a.isVisible){n--;continue}if(a.isReadOnly)continue;let h=s[n],_=i.leftCol,g=a.dataItem;if(a instanceof _NewRowTemplate){u&&(a.dataItem=c.addNew());let e=this.newRowAtTop?u?0:n:r,t=new CellRangeEventArgs(this.cells,new CellRange(e,-1));if(!this.onRowEditStarting(t)){r--;u&&c.cancelNew();continue}this.onRowEditStarted(t)}for(let i=0,s=t.leftCol;i<h.length&&s<this.columns.length;i++,s++){if(!this.columns[s].isVisible){i--;continue}if(this.columns[s].isReadOnly)continue;let t=h[i];if(!this.columns[s].isReadOnly&&!a.isReadOnly){let i=t.length;i>1&&'"'==t[0]&&'"'==t[i-1]&&t.indexOf("\n")>-1&&(t=t.substr(1,i-2));o=this._postSetClipStringProcess(g,t,r,s,e,l,_,c)||o;d.row2=Math.max(d.row2,r+e);d.col2=Math.max(d.col2,s)}_>=0&&_++}l>=0&&l++;if(u&&a instanceof _NewRowTemplate){a.dataItem=null;r--;e++;let t=new CellRangeEventArgs(this.cells,new CellRange(this.newRowAtTop?0:r,-1));this.onRowEditEnding(t);this.onRowEditEnded(t);c.commitNew()}}}else if(this._copiedRanges&&1===this._copiedRanges.length){let e=this.selectedSheet===this._copiedSheet?this:this._copiedSheet.grid,i=0,l=0,n=this.selectionMode===SelectionMode.ListBox?this._getSelectionForListBoxMode(e):this._copiedRanges[0];for(let r=0,a=t.topRow;r<s.length&&a<this.rows.length;r++,a++){let h=this.rows[a],_=0;if(!h.isVisible){r--;continue}if(h.isReadOnly)continue;for(;e.rows[n.topRow+l]&&!e.rows[n.topRow+l].isVisible;)l++;l>=n.rowSpan&&(l%=n.rowSpan);if(!e.rows[n.topRow+l])break;let g=a-n.topRow-l,f=s[r],w=h.dataItem;if(h instanceof _NewRowTemplate){u&&(h.dataItem=c.addNew());let e=this.newRowAtTop?u?0:r:a,t=new CellRangeEventArgs(this.cells,new CellRange(e,-1));if(!this.onRowEditStarting(t)){a--;u&&c.cancelNew();continue}this.onRowEditStarted(t)}for(let s=0,r=t.leftCol;s<f.length&&r<this.columns.length;s++,r++){if(!this.columns[r]||!this.columns[r].isVisible){s--;continue}if(this.columns[r].isReadOnly)continue;_>=n.columnSpan&&(_%=n.columnSpan);if(!e.columns[n.leftCol+_])break;let t=r-n.leftCol-_;if(!this.columns[r].isReadOnly&&!h.isReadOnly){let h=f[s],u=this._getCellStyle(n.topRow+l,n.leftCol+_,this._copiedSheet);if(_isFormula(h)&&(0!==g||0!==t))try{let e=this._calcEngine.parse(h),i=new CellRange(n.topRow+l,n.leftCol+_),o=new CellRange(n.topRow+l+g,n.leftCol+_+t),s=!(this._isCutting&&!e._refersTo(n));e._moveCellRangeExp(this.selectedSheetIndex,i,o,!1,s)&&(h="="+e._getStringExpression())}catch(e){}e.columns[n.leftCol+_].format&&!this.columns[r].format&&(u?u.format||(u.format=e.columns[n.leftCol+_].format):u={format:e.columns[n.leftCol+_].format});o=this._postSetClipStringProcess(w,h,a,r,i,n.topRow+l,n.leftCol+_,c,u)||o;d.row2=Math.max(d.row2,a+i);d.col2=Math.max(d.col2,r)}_++}l++;if(u&&h instanceof _NewRowTemplate){h.dataItem=null;a--;i++;let e=new CellRangeEventArgs(this.cells,new CellRange(this.newRowAtTop?0:a,-1));this.onRowEditEnding(e);this.onRowEditEnded(e);c.commitNew()}}}if(this._isCutting){this._delCutData(s.length,s[0].length);this._isCutting=!1;this._cutValue=l;this._copiedRanges=null;this._copiedSheet=null}if(c&&u){c.currentEditItem&&c.commitEdit();c.endUpdate(!0)}else if(c&&o){let e=c.currentAddItem;!e&&0===t.row&&this.newRowAtTop&&this.rows[0]instanceof _NewRowTemplate&&(e=this.rows[0].dataItem);if(e){c.editItem(e);this._edtHdl._edItem=e}c.refresh()}this.endUpdate();this.select(d);this.onPasted(new CellRangeEventArgs(this.cells,d))}getBuiltInTableStyle(e){var t;null==this._builtInTableStylesCache&&(this._builtInTableStylesCache={});if(null==(t=this._builtInTableStylesCache[e.toLowerCase()])){t=this._createBuiltInTableStyle(e);Object.freeze(t);this._builtInTableStylesCache[e.toLowerCase()]=t}return t}onSortingColumn(e){return!1}_getCvIndex(e){return e>-1&&this.collectionView?this.rows[e]instanceof HeaderRow?e:super._getCvIndex(e):-1}_headerRowAtTop(){let e=this._getDataRowsOffset();return e>0&&this.rows[e-1]instanceof HeaderRow}_getDataRowsOffset(){let e=0;this.allowAddNew&&this.newRowAtTop&&e++;this.rows[e]instanceof HeaderRow&&e++;return e}_bindGrid(e){if(!this._ignoreBindGrid)if(this.itemsSource)super._bindGrid(e);else if(!this.rows.length){let e=this._selHdl.selection;e.row=e.row2=-1}}_init(){let e=window.navigator.userAgent,mouseUp=e=>{document.removeEventListener("mouseup",mouseUp);this._mouseUp(e)};this.hostElement.setAttribute("tabindex","-1");this._divContainer=this.hostElement.querySelector('[wj-part="container"]');this._tabHolder=new _TabHolder(this.hostElement.querySelector('[wj-part="tab-holder"]'),this);this._sheets.selectedSheetChanged.addHandler(this._selectedSheetChange,this);this._sheets.collectionChanged.addHandler(this._sourceChange,this);this._sheets.sheetVisibleChanged.addHandler(this._sheetVisibleChange,this);this._sheets.sheetCleared.addHandler(this.onSheetCleared,this);this._contextMenu=new _SheetContextMenu(this.hostElement.querySelector('[wj-part="context-menu"]'),this);this._tabHolder.addEventListener(this._tabHolder.hostElement,"mousedown",()=>{e.match(/iPad/i)||e.match(/iPhone/i)||this._hideContextMenu()});this._gpCells=new FlexSheetPanel(this,CellType.Cell,this.rows,this.columns,this._eCt);this._gpCHdr=new FlexSheetPanel(this,CellType.ColumnHeader,this._hdrRows,this.columns,this._eCHdrCt);this._gpRHdr=new FlexSheetPanel(this,CellType.RowHeader,this.rows,this._hdrCols,this._eRHdrCt);this._gpTL=new FlexSheetPanel(this,CellType.TopLeft,this._hdrRows,this._hdrCols,this._eTLCt);this._syncSelection=this._flexSheetSyncSelection.bind(this);this._sortManager=new SortManager(this);this._filter=new FlexSheetFilter(this);this._filter.filterApplied.addHandler(()=>{if(this.selectedSheet){this.selectedSheet._filterDefinition=this._filter.filterDefinition;if(this.selectedSheet.itemsSource){this.selectedSheet._storeRowSettings();this.selectedSheet._setRowSettings()}}});this._calcEngine=new _CalcEngine(this);this._calcEngine.unknownFunction.addHandler((e,t)=>{this.onUnknownFunction(t)},this);this._initFuncsList();this._undoStack=new UndoStack(this);this.loadedRows.addHandler(()=>{if(this.collectionView&&!(this.rows[0]instanceof HeaderRow)&&!this._headerRowRemoved){let e=new HeaderRow;e.isReadOnly=!0;for(let t=0;t<this.columns.length;t++){let i=this.columns[t];e._ubv||(e._ubv={});e._ubv[i._hash]=FlexSheet._getHeaderRowText(i)}this.rows[0]instanceof _NewRowTemplate&&this.newRowAtTop?this.rows.insert(1,e):this.rows.insert(0,e)}this._filter&&this._filter.apply()});this.itemsSourceChanged.addHandler(()=>{var e;for(e=0;e<this.columns.length;e++)this.columns[e].isRequired=!1;this.collectionView&&this.collectionView.currentChanged.removeHandler(null,this)});this.copied.addHandler((e,t)=>{var i;if(this.selectedSheet){this._copiedSheet=this.selectedSheet;this._needCopyToSheet=!0;if(this.selectedSheet.selectionRanges.length>1)if(this._isMultipleRowsSelected()){(i=this.selectedSheet.selectionRanges.slice(0)).sort(this._sortByRow);this._copiedRanges=i}else if(this._isMultipleColumnsSelected()){(i=this.selectedSheet.selectionRanges.slice(0)).sort(this._sortByColumn);this._copiedRanges=i}else assert(!1,"Copy operation cannot be used on multiple selections.");else this._copiedRanges=[t.range]}});this.rows.collectionChanged.addHandler((e,t)=>{this._clearForEmptySheet("rows");this.itemsSource||!this.selectedSheet||!this._needCopyToSheet||this._isCopying||this._isUndoing||t.item instanceof _NewRowTemplate||this._copyRowsToSelectedSheet();this.itemsSource&&this.selectedSheet&&t.action===NotifyCollectionChangedAction.Remove&&t.item instanceof HeaderRow&&!this._draggingSingleRow&&(this._headerRowRemoved=!0)},this);this.columns.collectionChanged.addHandler((e,t)=>{this._clearForEmptySheet("columns");this.selectedSheet&&this._needCopyToSheet&&!this._isCopying&&!this._isUndoing&&this._copyColumnsToSelectedSheet()},this);this.addEventListener(this.hostElement,"mousedown",e=>{document.addEventListener("mouseup",mouseUp);this._isDescendant(this._divContainer,e.target)&&this._mouseDown(e)},!0);this.addEventListener(this.hostElement,"dragend",()=>{this._columnHeaderClicked=!1;this._htDown=null;this._enableMulSel=!1;this.selectedSheet._addSelection(this.selection)});this.addEventListener(this.hostElement,"contextmenu",e=>{if(!e.defaultPrevented&&this.selectedSheet){if(!this.activeEditor){let t,i,o=this.selection;if(this._isContextMenuKeyDown&&o.row>-1&&o.col>-1&&this.rows.length>0&&this.columns.length>0){let e=this.columns[o.col],l=this.rows[o.row],s=this._cumulativeOffset(this.hostElement),n=this._cumulativeScrollOffset(this.hostElement),r=e.pos+this._eCt.offsetLeft+s.x+e.renderSize/2+this._ptScrl.x,a=l.pos+this._eCt.offsetTop+s.y+l.renderSize/2+this._ptScrl.y;i=new Point(r-n.x,a-n.y);t=this.hitTest(r,a)}else t=this.hitTest(e);e.preventDefault();if(t&&t.cellType!==CellType.None){let o,l=this.columns.length-1,s=this.rows.length-1;switch(t.cellType){case CellType.TopLeft:o=new CellRange(Math.min(0,s),Math.min(0,l),s,l);break;case CellType.RowHeader:o=new CellRange(t.row,Math.min(0,l),t.row,l);break;case CellType.ColumnHeader:o=new CellRange(this.itemsSource&&this.rows[0]&&!this.rows[0].isVisible?1:Math.min(0,s),t.col,s,t.col);break;case CellType.Cell:o=new CellRange(t.row,t.col)}(o&&this.selection.contains(o)||t.cellType===CellType.RowHeader&&this._isRowSelected(t.row)||t.cellType===CellType.ColumnHeader&&this._isColumnSelected(t.col)||t.cellType===CellType.Cell&&this._isCellSelected(t.row,t.col))&&(o=null);if(o){if(this.selectedSheet){this.selectedSheet.selectionRanges.clear();this.selectedSheet.selectionRanges.push(o)}this.selection=o}this._contextMenu.show(e,i)}}this._isContextMenuKeyDown=!1}});this.prepareCellForEdit.addHandler(this._prepareCellForEditHandler,this);this.cellEditEnded.addHandler((e,t)=>{(!t.data||46!==t.data.keyCode&&8!==t.data.keyCode)&&setTimeout(()=>{this.hideFunctionList()},200)});this.cellEditEnding.addHandler((e,t)=>{if(t.cancel||t.data&&(46===t.data.keyCode||8===t.data.keyCode))return;let i=this.getCellData(t.row,t.col,!1),o=this.cellFactory.getEditorValue(this);if((null==i||""===i)&&null!=o&&""!==o&&!isNaN(+o)){let e=this._updateFormulaBoundaryForEditingCell(t.row,t.col);this._undoStack._pendingAction&&this._undoStack._pendingAction instanceof _EditAction&&(this._undoStack._pendingAction._affectedFormulas=e)}this._clearCalcEngine();this._clearCalcCacheOnRefresh=!1});this.rowEditEnding.addHandler((e,t)=>{let i=this.collectionView;if(i&&this.selectedSheet){let e=i.sortDescriptions.length>0,t=this._filter&&this._filter._isActive();(e||this.selectedSheet._dataView||t)&&(this.selectedSheet._dataView=i._view.slice());e&&(this.selectedSheet._scrollPosition=this.scrollPosition)}});this.rowEditEnded.addHandler((e,t)=>{let i=this.collectionView;if(i&&this.selectedSheet){this.selectedSheet._dataView&&(this.selectedSheet._dataView=i._view.slice());let e=i.sortDescriptions.length>0,t=this._filter&&this._filter._isActive();if(e||t){i._view=this.selectedSheet._dataView;i._pgView=i._getPageView();if(!(this.itemsSource instanceof CollectionView)&&null!=this.selectedSheet.grid.collectionView){this.selectedSheet.grid.collectionView._view=this.selectedSheet._dataView;this.selectedSheet.grid.collectionView._pgView=this.selectedSheet.grid.collectionView._getPageView()}if(this.refreshOnEdit){this._isPasting||this._bindGrid(!1);this.selectedSheet.grid._bindGrid(!1)}}e&&(this.scrollPosition=this.selectedSheet._scrollPosition)}});this.pasting.addHandler(()=>{this._needCopyToSheet=!1;this._isPasting=!0});this.pasted.addHandler(()=>{let e=this.collectionView,t=this.selectedSheet;e&&t&&t._dataView&&t._dataView.length!==e._view.length&&(t._dataView=e._view.slice());this.selection;this._needCopyToSheet=!0;this._isPasting=!1;this._clearCalcEngine()});this.resizingColumn.addHandler(()=>{this._resizing=!0});this.resizingRow.addHandler(()=>{this._resizing=!0});this.resizedColumn.addHandler(()=>{this._resizing=!1});this.resizedRow.addHandler(()=>{this._resizing=!1});this.selectionChanged.addHandler(()=>{let e=this.selection;e.rightCol>=this.columns.length&&(this.selection=new CellRange(e.row,Math.min(e.col,this.columns.length-1),e.row2,Math.min(this.selection.col2,this.columns.length-1)));this._enableMulSel||this._isCopying||!this.selectedSheet||this.selectedSheet.selectionRanges.clear()});this.draggingRow.addHandler(()=>this._draggingSingleRow=!0);this.draggedRow.addHandler(()=>this._draggingSingleRow=!1);this.addEventListener(this.hostElement,"keydown",e=>{var t,i,o=!1,l=!1;if(e.ctrlKey){if(89===e.keyCode){this.finishEditing();this.redo();e.preventDefault()}if(90===e.keyCode){this.finishEditing();this.undo();e.preventDefault()}if(this.selectedSheet&&65===e.keyCode){this._isClicking=!0;this.selectedSheet.selectionRanges.clear();this.selectedSheet.selectionRanges.push(this.selection);this._isClicking=!1}if(67===e.keyCode||45==e.keyCode){if(this.activeEditor){this._copiedRanges=null;this._copiedSheet=null}this._cutValue=null}if(88===e.keyCode&&!this.activeEditor){e.stopPropagation();if(this.selectionMode===SelectionMode.ListBox)for(var s=0;s<this.rows.length;s++)if(this.rows[s].isSelected)if(o){if(l)continue;assert(!1,"Cut operation cannot be used on multiple selections.")}else{o=!0;l=!0}else l&&(l=!1);if(this.selectedSheet.selectionRanges.length>1)assert(!1,"Cut operation cannot be used on multiple selections.");else{this.finishEditing();t=new CellRangeEventArgs(this.cells,this.selection);if(this.onCopying(t)){this._cutValue=null;i=this.getClipString();this._isCutting=!0;Clipboard.copy(i);this.onCopied(t)}}}e.keyCode!==Key.Space||!this.selection.isValid||this.selectionMode!==SelectionMode.CellRange&&this.selectionMode!==SelectionMode.MultiRange||this.select(new CellRange(0,this.selection.col,this.rows.length-1,this.selection.col))}e.keyCode===Key.Escape&&this._hideContextMenu();(93===e.keyCode||e.shiftKey&&121===e.keyCode)&&(this._contextMenu.visible&&!isFirefox()?this._isContextMenuKeyDown=!1:this._isContextMenuKeyDown=!0)});this.addEventListener(document.body,"keydown",this._keydownHdl,!0);this.addEventListener(document.body,"click",this._clickHdl);this.addEventListener(document.body,"mousemove",this._mouseMoveHdl);this.draggedColumn.addHandler((e,t)=>{this.sortManager._handleColumnMoving(t.data.col,t.col)});if(e.match(/iPad/i)||e.match(/iPhone/i)){this.addEventListener(document.body,"touchstart",this._touchStartHdl);this.addEventListener(document.body,"touchend",this._touchEndHdl)}}_flexSheetSyncSelection(e){if(this.collectionView&&this.selectionMode!=SelectionMode.None){let t=this.selection,i=t.row>-1&&t.row<this.rows.length?this.rows[t.row]:null,o=i?i.dataItem:null;if(this.collectionView instanceof CollectionView&&this.collectionView.isUpdating)return;(i instanceof HeaderRow||this.newRowAtTop&&i instanceof _NewRowTemplate||o instanceof CollectionViewGroup)&&(o=null);if((o!=this.collectionView.currentItem||e)&&(!this.editableCollectionView||!this.editableCollectionView.currentAddItem)){let e=this._getRowIndex(this.collectionView.currentPosition);if(e!=t.row){t.row=t.row2=e;this.select(t,!1);this.selectionMode&&!this._copyingTo&&this.scrollIntoView(t.row,-1)}}}}_initFuncsList(){this._functionListHost=document.createElement("div");addClass(this._functionListHost,"wj-flexsheet-formula-list");document.querySelector("body").appendChild(this._functionListHost);this._functionListHost.style.display="none";this._functionListHost.style.position="absolute";this._functionList=new mInput.ListBox(this._functionListHost);this._functionList.isContentHtml=!0;this._functionList.itemsSource=this._getFunctions();this._functionList.displayMemberPath="displayValue";this._functionList.selectedValuePath="actualvalue";this.addEventListener(this._functionListHost,"click",this.applyFunctionToCell.bind(this));this.addEventListener(this._functionListHost,"keydown",e=>{if(e.keyCode===Key.Escape){this.hideFunctionList();this.hostElement.focus();e.preventDefault()}if(e.keyCode===Key.Enter){this.applyFunctionToCell();this.hostElement.focus();e.preventDefault();e.stopPropagation()}})}_getFunctions(){for(var e,t=[],i=0;i<FlexSheetFunctions.length;i++){e=FlexSheetFunctions[i];t.push({displayValue:'<div class="wj-flexsheet-formula-name">'+e.name+'</div><div class="wj-flexsheet-formula-description">'+e.description+"</div>",actualvalue:e.name})}return t}_addCustomFunctionDescription(e,t){for(var i={displayValue:'<div class="wj-flexsheet-formula-name">'+e+"</div>"+(t?'<div class="wj-flexsheet-formula-description">'+t+"</div>":""),actualvalue:e},o=this._functionList.itemsSource,l=-1,s=0;s<o.length;s++)if(o[s].actualvalue===e){l=s;break}l>-1?o.splice(l,1,i):o.push(i)}_getCurrentFormulaIndex(e){var t=-1;["+","-","*","/","^","(","&"].forEach(i=>{var o=e.lastIndexOf(i);"/"===i&&(o>=2&&"#N"===e.substr(o-2,2)||o>=4&&"#DIV"===e.substr(o-4,4))||o>t&&(t=o)});return t}_prepareCellForEditHandler(){var e=this._edtHdl._edt;if(e){this.addEventListener(e,"keydown",e=>{if(this.isFunctionListOpen)switch(e.keyCode){case Key.Up:this.selectPreviousFunction();e.preventDefault();e.stopPropagation();break;case Key.Down:this.selectNextFunction();e.preventDefault();e.stopPropagation();break;case Key.Tab:case Key.Enter:this.applyFunctionToCell();e.preventDefault();e.stopPropagation();break;case Key.Escape:this.hideFunctionList();e.preventDefault();e.stopPropagation()}});this.addEventListener(e,"keyup",t=>{(t.keyCode>40||t.keyCode<32)&&t.keyCode!==Key.Tab&&t.keyCode!==Key.Escape&&setTimeout(()=>{this.showFunctionList(e)},0)})}}_addSheet(e,t,i,o,l){let s=new Sheet(this,l,e,t,i);s.name||s._setValidName(this.sheets.getUniqueNameOnInit());if("number"==typeof o){o<0&&(o=0);o>=this.sheets.length&&(o=this.sheets.length)}else o=this.sheets.length;this.sheets.insert(o,s);return s}_showSheet(e){if(!(!this.sheets||!this.sheets.length||e>=this.sheets.length||e<0||e===this.selectedSheetIndex||this.sheets[e]&&!this.sheets[e].visible)){this.beginUpdate();this.finishEditing();this._clearCalcEngine();this._isCopying=!0;if(this.selectedSheetIndex>-1&&this.selectedSheetIndex<this.sheets.length&&!this._sheets._exchangingPosition){this._copyingTo=!0;try{this._copyTo(this.sheets[this.selectedSheetIndex])}finally{this._copyingTo=!1}}if(this.sheets[e]){this._selectedSheetIndex=e;this._copyFrom(this.sheets[e])}this._isCopying=!1;this.endUpdate();this._filter.closeEditor()}}_selectedSheetChange(e,t){this.beginUpdate();this._showSheet(t.newValue);this._clearCalcCacheOnRefresh=!1;this.endUpdate();this.onSelectedSheetChanged(t)}_sourceChange(e,t){if(!this.sheets._exchangingPosition){this.beginUpdate();if(t.action===NotifyCollectionChangedAction.Add||t.action===NotifyCollectionChangedAction.Change){t.item._attachOwner(this);if(t.action===NotifyCollectionChangedAction.Add){this._addingSheet=!0;t.index<=this.selectedSheetIndex&&(this._selectedSheetIndex+=1)}else t.index===this.selectedSheetIndex&&this._copyFrom(t.item);this.selectedSheetIndex=t.index}else if(t.action===NotifyCollectionChangedAction.Reset){for(var i=0;i<this.sheets.length;i++)this.sheets[i]._attachOwner(this);if(this.sheets.length>0){0===this.selectedSheetIndex&&this._copyFrom(this.selectedSheet);this.selectedSheetIndex=0}else{this.rows.clear();this.columns.clear();this._selectedSheetIndex=-1}}else if(this.sheets.length>0){if(this.selectedSheetIndex===t.index){this._selectedSheetIndex=-1;this.sheets._setCurrentIdx(-1);this.selectedSheetIndex=t.index>this.sheets.length-1?this.sheets.length-1:t.index}else if(this.selectedSheetIndex>t.index){this._selectedSheetIndex--;this.sheets._setCurrentIdx(this._selectedSheetIndex)}}else{this.rows.clear();this.columns.clear();this._selectedSheetIndex=-1}this._updateDivContainerHeight(this.isTabHolderVisible);this.endUpdate()}}_sheetVisibleChange(e,t){t.item.visible||this._loadingFromWorkbook||t.index===this.selectedSheetIndex&&(this.selectedSheetIndex===this.sheets.length-1?this.selectedSheetIndex=t.index-1:this.selectedSheetIndex=t.index+1)}_applyStyleForCell(e,t,i,o=!1){let l=this.rows[e];if(null==l||l instanceof HeaderRow||!l.isVisible&&!o)return;let s=e*this.columns.length+t,n=this.selectedSheet._getMergedRange(e,t);n&&(s=n.topRow*this.columns.length+n.leftCol);let r=this.selectedSheet._styledCells[s];r||(r=this.selectedSheet._styledCells[s]={});Object.keys(i).forEach(e=>{let t=i[e];("className"===e&&"normal"===t||("fontStyle"===e||"fontWeight"===e||"textDecoration"===e)&&"none"===t)&&(t="");r[e]=null===t||""===t?void 0:t||r[e]})}_checkCellFormat(e,t,i){var o,l,s=e*this.columns.length+t;if(this.selectedSheet){if(o=this.selectedSheet._getMergedRange(e,t)){i.isMergedCell=!0;s=o.topRow*this.columns.length+o.leftCol}if(l=this.selectedSheet._styledCells[s]){i.isBold=i.isBold||"bold"===l.fontWeight;i.isItalic=i.isItalic||"italic"===l.fontStyle;i.isUnderline=i.isUnderline||"underline"===l.textDecoration;i.verticalAlign=l.verticalAlign||"top"}e===this.selection.row&&t===this.selection.col&&(l&&l.textAlign?i.textAlign=l.textAlign:t>-1&&(i.textAlign=this.columns[t].getAlignment()||i.textAlign))}}_resetMergedRange(e){var t,i,o,l,s=!1;for(t=e.topRow;t<=e.bottomRow;t++)for(i=e.leftCol;i<=e.rightCol;i++)if(l=this.selectedSheet._getMergedRange(t,i)){s=!0;o=this.selectedSheet._mergedRanges.indexOf(l);this.selectedSheet._mergedRanges.splice(o,1)}return s}_updateCellsForUpdatingRow(e,t,i,o){var l,s,n,r,a,h,d,u=e*this.columns.length;if(o)for(s=l=t*this.columns.length;s<u;s++){n=s-i*this.columns.length;if(r=this.selectedSheet._styledCells[s]){s>=(t+i)*this.columns.length&&(this.selectedSheet._styledCells[n]=r);delete this.selectedSheet._styledCells[s]}}else{l=t*this.columns.length-1;for(s=u-1;s>l;s--){n=s+this.columns.length*i;if(r=this.selectedSheet._styledCells[s]){this.selectedSheet._styledCells[n]=r;delete this.selectedSheet._styledCells[s]}}}if(this.selectedSheet._mergedRanges.length>0)for(h=this.selectedSheet._mergedRanges.length-1;h>=0;h--){a=this.selectedSheet._mergedRanges[h];if(o)if((d=t+i-1)<a.topRow){a.row-=i;a.row2-=i}else if(d>=a.topRow&&d<=a.bottomRow)if(t<=a.topRow&&d>=a.bottomRow)this.selectedSheet._mergedRanges.splice(h,1);else if(t<a.topRow)if(a.row<=a.row2){a.row+=t-a.topRow;a.row2-=i}else{a.row2+=t-a.topRow;a.row-=i}else t===a.topRow&&i===a.rowSpan?this.selectedSheet._mergedRanges.splice(h,1):a.row<=a.row2?a.row2-=i:a.row-=i;else t<=a.topRow?this.selectedSheet._mergedRanges.splice(h,1):t<=a.bottomRow&&(a.row<=a.row2?a.row2+=t-a.bottomRow-1:a.row+=t-a.bottomRow-1);else if(t<=a.topRow){a.row+=i;a.row2+=i}else t>a.topRow&&t<=a.bottomRow&&(a.row<=a.row2?a.row2+=i:a.row+=i)}}_updateCellsForUpdatingColumn(e,t,i,o){var l,s,n,r,a,h,d,u=this.rows.length*e;if(o)for(l=t;l<u;l++){s=l-i*(Math.floor(l/e)+((r=l%e)>=t?1:0));if(n=this.selectedSheet._styledCells[l]){(r<t||r>=t+i)&&(this.selectedSheet._styledCells[s]=n);delete this.selectedSheet._styledCells[l]}}else for(l=u-1;l>=t;l--){s=Math.floor(l/e)*i+l+((r=l%e)>=t?i:0);if(n=this.selectedSheet._styledCells[l]){this.selectedSheet._styledCells[s]=n;delete this.selectedSheet._styledCells[l]}}if(this.selectedSheet._mergedRanges.length>0)for(h=this.selectedSheet._mergedRanges.length-1;h>=0;h--){a=this.selectedSheet._mergedRanges[h];if(o)if((d=t+i-1)<a.leftCol){a.col-=i;a.col2-=i}else if(d>=a.leftCol&&d<=a.rightCol)if(t<=a.leftCol&&d>=a.rightCol)this.selectedSheet._mergedRanges.splice(h,1);else if(t<a.leftCol)if(a.col<=a.col2){a.col+=t-a.leftCol;a.col2-=i}else{a.col2+=t-a.leftCol;a.col-=i}else t===a.leftCol&&i===a.columnSpan?this.selectedSheet._mergedRanges.splice(h,1):a.col<=a.col2?a.col2-=i:a.col-=i;else t<=a.leftCol?this.selectedSheet._mergedRanges.splice(h,1):t<=a.rightCol&&(a.col<=a.col2?a.col2-=a.rightCol-t+1:a.col-=a.rightCol-t+1);else if(t<=a.leftCol){a.col+=i;a.col2+=i}else t>a.leftCol&&t<=a.rightCol&&(a.col<=a.col2?a.col2+=i:a.col+=i)}}_cloneObject(e){var t;if(null==e||!isObject(e))return e;t={};for(var i in e)e.hasOwnProperty(i)&&null!=e[i]&&(e[i].clone?t[i]=e[i].clone():t[i]=this._cloneObject(e[i]));return t}_evaluate(e,t,i,o,l){if(e&&e.length>1&&this._enableFormulas){e="="===e[0]?e:"="+e;let s=this._calcEngine.evaluate(e,t,i,o,l);isPrimitive(s)?isNumber(s)&&(s=this._calcEngine.round(s)):s&&isNumber(s.value)&&(s.value=this._calcEngine.round(s.value));return s}return e}_clearAndCheckItemsOwner(e){if(e&&e.length){let t=e[0]._list;e.clear();this._checkCollectionOwner(t)}}_checkCollectionOwner(e,t=!0){if(e&&e.length&&(!e[0]._list||!t&&e[0]._list!=e))for(let t=0,i=e.length;t<i;t++)e[t]._setList(e)}_checkCollectionsOwner(){this._checkCollectionOwner(this.columns,!1);this._checkCollectionOwner(this.rows,!1);this._checkCollectionOwner(this.columnFooters.columns,!1);this._checkCollectionOwner(this.columnFooters.rows,!1);this._checkCollectionOwner(this.columnHeaders.columns,!1);this._checkCollectionOwner(this.columnHeaders.rows,!1);this._checkCollectionOwner(this.rowHeaders.columns,!1);this._checkCollectionOwner(this.rowHeaders.rows,!1)}_copyTo(e){var t,i=e.grid.autoGenerateColumns;this.beginUpdate();e._storeRowSettings();this._selHdl.extendedSelection.clear();t=this.selection.clone();e.grid.select(new CellRange,!1);this._clearAndCheckItemsOwner(e.grid.rows);this._clearAndCheckItemsOwner(e.grid.columns);this._clearAndCheckItemsOwner(e.grid.columnHeaders.columns);this._clearAndCheckItemsOwner(e.grid.rowHeaders.rows);e._ownerHeaderRowRemoved=this._headerRowRemoved;if(this.itemsSource){e.grid.autoGenerateColumns=!1;e.itemsSource=this.itemsSource;this.collectionView.sortDescriptions.length>0&&(e._dataView=this.collectionView._view.slice());e.grid.collectionView.beginUpdate()}else{e.itemsSource=null;for(var o=0;o<this.rows.length;o++)e.grid.rows.push(this.rows[o])}e._sortList=this.sortManager._committedList.slice();e._getFilterSetting();for(var l=0;l<this.columns.length;l++)e.grid.columns.push(this.columns[l]);if(e.grid.collectionView){this._resetMappedColumns(e.grid);e.grid.collectionView.endUpdate(!0)}e.grid.autoGenerateColumns=i;e.grid.rows.frozen=this.rows.frozen;e.grid.columns.frozen=this.columns.frozen;e.grid.allowAddNew=this.allowAddNew;null!=this.newRowAtTop&&(e.grid.newRowAtTop=this.newRowAtTop);e.grid.select(t,!1);e._scrollPosition=this.scrollPosition;this._setFlexSheetToDirty();this.endUpdate()}_copyFrom(e,t=!0){var i,o=this.autoGenerateColumns;this._isCopying=!0;this._dragable=!1;t&&this.beginUpdate();this.itemsSource=null;this._clearAndCheckItemsOwner(this.rows);this._clearAndCheckItemsOwner(this.columns);this._clearAndCheckItemsOwner(this.columnHeaders.columns);this._clearAndCheckItemsOwner(this.rowHeaders.rows);i=e.grid.selection.clone();this._selHdl.select(new CellRange,!1);e.selectionRanges.length>1&&(this.selectionMode===SelectionMode.CellRange||this.selectionMode===SelectionMode.MultiRange)&&(this._enableMulSel=!0);this._headerRowRemoved=e._ownerHeaderRowRemoved;if(e.itemsSource){this.autoGenerateColumns=!1;this._ignoreBindGrid=isArray(e.itemsSource)||e.itemsSource instanceof CollectionView;this.itemsSource=e.itemsSource;this._ignoreBindGrid=!1;this.collectionView.beginUpdate()}else for(let t=0;t<e.grid.rows.length;t++)this.rows.push(e.grid.rows[t]);for(let t=0;t<e.grid.columns.length;t++){let i=e.grid.columns[t];i.isRequired=!1;this.columns.push(i)}this.sortManager.sortDescriptions.sourceCollection=e._sortList.slice();this.sortManager._committedList=e._sortList.slice();if(this.collectionView){if(e.grid.collectionView){this.collectionView.sortDescriptions.clear();e.grid.collectionView.sortDescriptions.forEach(e=>this.collectionView.sortDescriptions.push(e))}this.collectionView.moveCurrentToPosition(this._getCvIndex(i.row));this._resetMappedColumns(this);this.collectionView.endUpdate(!0);if(e._dataView){this.collectionView._view=e._dataView;this.collectionView._pgView=this.collectionView._getPageView();if(!(this.itemsSource instanceof CollectionView)){e.grid.collectionView._view=e._dataView;e.grid.collectionView._pgView=e.grid.collectionView._getPageView()}this._bindGrid(!1);e.grid._bindGrid(!1)}this.collectionView.collectionChanged.addHandler((e,t)=>{t.action===NotifyCollectionChangedAction.Reset&&setTimeout(()=>{this.invalidate()},10)},this)}if(this.rows.length&&this.columns.length){this._selHdl.select(i,!1);if(this.selectionMode===SelectionMode.MultiRange){this._selHdl.extendedSelection.beginUpdate();for(var l=0;l<e.selectionRanges.length;l++)this.selection.equals(e.selectionRanges[l])||this._selHdl.extendedSelection.push(e.selectionRanges[l]);this._selHdl.extendedSelection.endUpdate()}}e._applyFilterSetting();for(let t=0;t<this.rows.length;t++){let i=e._rowSettings[t];if(i){let e=this.rows[t],o=e instanceof HeaderRow;e.height=i.height;e.allowMerging=i.allowMerging;e.visible=i.visible;e instanceof GroupRow&&(e.isCollapsed=!!i.isCollapsed);e.isSelected=!!i.isSelected;e.isReadOnly=o||!!i.readOnly}}this.autoGenerateColumns=o;this.rows.frozen=e.grid.rows.frozen;this.columns.frozen=e.grid.columns.frozen;this._isCopying=!1;if(t){this.cells.hostElement.style.overflow="hidden";this._setFlexSheetToDirty();this.endUpdate();if(this._addingSheet){clearTimeout(this._toRefresh);this._toRefresh=setTimeout(()=>{this._setFlexSheetToDirty();this.invalidate()},Control._REFRESH_INTERVAL);this._addingSheet=!1}}this._updateScrollPos=!0}onUpdatedLayout(e){if(this._updateScrollPos){this.cells.hostElement.style.overflow="";this._updateScrollPos=!1;let e=this.selectedSheet;if(e){this.scrollPosition=e._scrollPosition;this._ptScrl=e._scrollPosition}}super.onUpdatedLayout(e)}_resetMappedColumns(e){var t,i,o=0;e._mappedColumns=null;if(e.collectionView){i=e.collectionView.sortDescriptions;for(;o<i.length;o++)if((t=e.columns.getColumn(i[o].property))&&t.dataMap){e._mappedColumns||(e._mappedColumns={});e._mappedColumns[t.binding]=t.dataMap}}}_loadFromWorkbook(e){if(null!=e.sheets&&0!==e.sheets.length){this._loadingFromWorkbook=!0;this.beginUpdate();this.clear();this._reservedContent=e.reservedContent;if(e.colorThemes&&e.colorThemes.length>0)for(let t=0;t<this._colorThemes.length;t++)this._colorThemes[t]=e.colorThemes[t];for(let t=0,i=e.sheets.length;t<i;t++){this.addUnboundSheet("",0,0);let i=this.selectedSheet,o=i.grid,l=o.wj_sheetInfo={};FlexGridXlsxConverter.load(o,e,{sheetIndex:t,includeColumnHeaders:!1});i.name=l.name;i.visible=l.visible;i._styledCells=l.styledCells;if(l.mergedRanges){for(let e=0;e<l.mergedRanges.length;e++)i._mergedRanges[e]=l.mergedRanges[e];l.mergedRanges=i._mergedRanges}this._copyFrom(i);if(l.tables&&l.tables.length>0)for(let e=0;e<l.tables.length;e++)this._parseFromWorkbookTable(l.tables[e],i)}null!=e.activeWorksheet&&e.activeWorksheet>-1&&e.activeWorksheet<this.sheets.length?this.selectedSheetIndex=e.activeWorksheet:this.selectedSheetIndex=0;e.definedNames&&e.definedNames.forEach(e=>{this.definedNames.push(new DefinedName(this,e.name,e.value,e.sheetName))});this.endUpdate();this._loadingFromWorkbook=!1;this.onLoaded()}}_saveToWorkbook(e){if(0===this.sheets.length)throw"The flexsheet is empty.";let t=!(!e||!e.includeFormulaValues),i=e&&e.convertHtmlEntities,o=this._saveSheetToWorkbook(0,t,i);for(let e=1;e<this.sheets.length;e++){let l=this._saveSheetToWorkbook(e,t,i);o._addWorkSheet(l.sheets[0],e)}o.sheets.forEach(e=>e.rightToLeft=this.rightToLeft);o.activeWorksheet=this.selectedSheetIndex;o.reservedContent=this._reservedContent;for(let e=0;e<this.definedNames.length;e++){let t=this.definedNames[e],i=new mXlsx.DefinedName;i.name=t.name;i.value=t.value;i.sheetName=t.sheetName;o.definedNames.push(i)}let l=this._colorThemes;if(l&&l.length>0)for(let e=0;e<l.length;e++)o.colorThemes[e]=l[e];return o}_saveSheetToWorkbook(e,t,i){let o=this.sheets[e],l=o.grid.wj_sheetInfo;t&&(l.evaluateFormula=e=>this.evaluate(e,null,o));if(this.selectedSheetIndex===e){o._storeRowSettings();this._copyRowsToSelectedSheet()}o._setRowSettings();if(o.tables.length>0){l.tables=[];for(let e=0;e<o.tables.length;e++)l.tables.push(this._parseToWorkbookTable(o.tables[e]))}let s=FlexGridXlsxConverter.save(o.grid,{sheetName:o.name,sheetVisible:o.visible,includeColumnHeaders:!1,convertHtmlEntities:i});this._checkTableHeaderRow(o.tables,s);l.evaluateFormula=null;return s}_mouseDown(e){var t,i,o=window.navigator.userAgent,l=this.hitTest(e);this.selectedSheet&&(this.selectedSheet._scrollPosition=this.scrollPosition);l.cellType!==CellType.None&&(this._isClicking=!0);if(this._dragable){this._isDragging=!0;this.createDropzone(e);this.onDraggingRowColumn(new DraggingRowColumnEventArgs(this.selection.clone(),this._draggingRow,e.shiftKey));e.preventDefault()}else if("crosshair"!==this.hostElement.style.cursor||null!=this._fillingMarker){if(this.selectionMode===SelectionMode.CellRange||this.selectionMode===SelectionMode.MultiRange){if(e.ctrlKey){if(!this._enableMulSel){this._enableMulSel=!0;0===this.selectedSheet.selectionRanges.length&&this.selectedSheet.selectionRanges.push(this.selection)}}else if(l.cellType!==CellType.None){if(this.selectedSheet)if(l.cellType===CellType.TopLeft){this.selectedSheet.selectionRanges.clear();this.selectedSheet._addSelection(new CellRange(0,0,this.rows.length-1,this.columns.length-1))}else 3===e.which&&this._isCellSelected(l.row,l.col)||this.selectedSheet.selectionRanges.clear();this._enableMulSel&&this.refresh(!1);this._enableMulSel=!1}}else{this._enableMulSel=!1;this.selectedSheet&&this.selectedSheet.selectionRanges.clear()}this._htDown=l;if(0!==this.rows.length&&0!==this.columns.length){o.match(/iPad/i)||o.match(/iPhone/i)||this._hideContextMenu();if(3!==e.which&&(this.selectionMode===SelectionMode.CellRange||this.selectionMode===SelectionMode.MultiRange)&&(l.cellType===CellType.ColumnHeader||l.cellType===CellType.None)&&!(l.col>-1&&this.columns[l.col].isSelected)&&hasClass(e.target,"wj-cell")&&!l.edgeRight){this._columnHeaderClicked=!0;i=this.itemsSource&&this.rows[0]&&!this.rows[0].isVisible?1:0;e.target.focus();if(e.shiftKey)this._multiSelectColumns(l);else{t=new CellRange(i,l.col,this.rows.length-1,l.col);if(3===e.which&&this.selection.contains(t))return;this.select(t)}this._eCt.children[i]&&this._eCt.children[i].children[l.col]&&this._eCt.children[i].children[l.col].focus()}}}else{this.finishEditing();this._fillingData=!0;this._fillingPoint=new Point(e.clientX-this.scrollPosition.x,e.clientY-this.scrollPosition.y);this._fillingSource=this.selection.clone();this._fillingMarker=document.createElement("div");setCss(this._fillingMarker,{position:"absolute",display:"none",border:"2px dashed"});this._root.appendChild(this._fillingMarker);this._fillingTooltip=new Tooltip;e.preventDefault()}}_mouseMove(e){var t,i=this.hitTest(e),o=this.selection.clone(),l=this.rows.length,s=this.columns.length,n=this.hostElement.style.cursor;if(0!==this.rows.length&&0!==this.columns.length)if(this._isDragging){this.hostElement.style.cursor="move";this.updateDropzone(e)}else if(!this._isClicking&&i.edgeBottom&&i.edgeRight&&i.row===o.bottomRow&&i.col===o.rightCol&&this.allowAutoFill)this.hostElement.style.cursor="crosshair";else if(this._fillingData){this.hostElement.style.cursor="crosshair";this._showFillMarker(e)}else{t=this.itemsSource?0===o.topRow||1===o.topRow:0===o.topRow;if(!this._isClicking&&o&&i.cellType!==CellType.None&&!this.itemsSource&&!this.isReadOnly&&this._enableDragDrop&&(!this._filter||!this._filter._isEditorOpened())){this._draggingColumn=t&&o.bottomRow===l-1;this._draggingRow=0===o.leftCol&&o.rightCol===s-1;if(i.cellType===CellType.Cell){this._draggingColumn&&((i.col===o.leftCol-1||i.col===o.rightCol)&&i.edgeRight||i.row===l-1&&i.edgeBottom)&&(n="move");this._draggingRow&&!this._containsGroupRows(o)&&((i.row===o.topRow-1||i.row===o.bottomRow)&&i.edgeBottom||i.col===s-1&&i.edgeRight)&&(n="move")}else i.cellType===CellType.ColumnHeader?i.edgeBottom&&(this._draggingColumn&&i.col>=o.leftCol&&i.col<=o.rightCol?n="move":this._draggingRow&&0===o.topRow&&(n="move")):i.cellType===CellType.RowHeader&&i.edgeRight&&(this._draggingColumn&&0===o.leftCol?n="move":this._draggingRow&&i.row>=o.topRow&&i.row<=o.bottomRow&&!this._containsGroupRows(o)&&(n="move"));this._dragable="move"===n;this.hostElement.style.cursor=n}if(this._htDown&&this._htDown.panel){i=new HitTestInfo(this._htDown.panel,e);this._multiSelectColumns(i);i.cellType===CellType.Cell&&this.scrollIntoView(i.row,i.col)}}else{this._dragable=!1;i.cellType===CellType.Cell&&(this.hostElement.style.cursor="default")}}_mouseUp(e){try{if(this._isDragging){if(this._dropRange&&!this._draggingCells.equals(this._dropRange)){let t=new DroppingRowColumnEventArgs(this._dropRange.clone(),this._draggingRow),i=new CancelEventArgs;this.onBeginDroppingRowColumn(t);i.cancel=t.cancel;t.cancel||this._handleDropping(e);this.onEndDroppingRowColumn(i)}}else if(this._fillingData){let e=AutoFillOperation.CopyContent,t=this._fillingRange,i=this._fillingSource;this._orgCellSettings=null;if(this._fillingRange&&this._fillingRange.isValid){assert(this._canDoFillOperation(),"To do this, all the merged cells need be the same size.");i.leftCol===t.leftCol&&i.rightCol===t.rightCol?i.row!==i.row2&&(e=AutoFillOperation.FillSeries):i.col!==i.col2&&(e=AutoFillOperation.FillSeries);this._orgCellSettings=this._getCellSettingsForFill();let o=new _FillAction(this,this._fillingSource);this._undoStack._addAction(o);e=AutoFillOperation.CopyFormat|e;if(this._fillData(e)){let t=this._root.appendChild(document.createElement("div")),i=new _SmartTag(t,this,e,{operationSelected:e=>{this._fillData(e.operation)},cancelled:()=>{t.parentElement.removeChild(t);i.dispose();i=null;o.saveNewState();this.focus()}})}}}}finally{this._draggingSingleRow=!1;if(this._isDragging){this._draggingCells=null;this._dropRange=null;this.destroyDropzone(e);this._isDragging=!1;this._draggingColumn=!1;this._draggingRow=!1}if(this._htDown&&this._htDown.cellType!==CellType.None&&this.selectedSheet){this.selection.isValid&&this.selectedSheet._addSelection(this.selection);this._enableMulSel=!1}if(this._fillingData){this._fillingData=!1;this._fillingPoint=null;this._fillingRange=null;this._root.removeChild(this._fillingMarker);this._fillingMarker=null;this._fillingTooltip.hide();this._fillingTooltip=null;this.hostElement.style.cursor="default"}this._isClicking=!1;this._columnHeaderClicked=!1;this._htDown=null}}_click(){var e=window.navigator.userAgent;e.match(/iPad/i)||e.match(/iPhone/i)||this._hideContextMenu();setTimeout(()=>{this.hideFunctionList()},200)}_touchStart(e){hasClass(e.target,"wj-context-menu-item")||this._hideContextMenu();this._longClickTimer=setTimeout(()=>{var t;if(this._isDescendant(this._divContainer,e.target)&&(t=this.hitTest(e))&&t.cellType!==CellType.None&&!this._resizing){if(t.cellType===CellType.TopLeft){this.selection=new CellRange(0,0,this.rows.length-1,this.columns.length-1);if(this.selectedSheet){this.selectedSheet.selectionRanges.clear();this.selectedSheet.selectionRanges.push(this.selection)}}this._contextMenu.show(null,new Point(e.pageX+10,e.pageY+10))}},500)}_touchEnd(){clearTimeout(this._longClickTimer)}_keydown(e){if(e.defaultPrevented)return;if((this._isDescendant(this.hostElement,e.target)||this.hostElement===e.target)&&!this._edtHdl.activeEditor&&!(e.target instanceof HTMLInputElement)&&this.selectedSheet&&(e.keyCode===Key.Delete||e.keyCode===Key.Back)){this._delSeletionContent(e);e.preventDefault()}let t=this._contextMenu.visible?this._contextMenu:this._tabHolder.sheetControl._contextMenu.visible?this._tabHolder.sheetControl._contextMenu:null;if(t){e.keyCode===Key.Down&&t.moveToNext();e.keyCode===Key.Up&&t.moveToPrev();e.keyCode===Key.Home&&t.moveToFirst();e.keyCode===Key.End&&t.moveToLast();e.keyCode===Key.Enter&&t.handleContextMenu();e.preventDefault()}}createDropzone(e){const t=new Tooltip({gap:0}),i=document.createElement("div");i.style.position="absolute";i.style.display="block";i.style.borderStyle="dotted";i.style.cursor="move";i.style.zIndex="1";i.style.opacity="0.5";this.dropzoneMarker=i;this._draggingTooltip=t;this._draggingCells=this.selection;this._root.appendChild(i);this.selectedSheet&&this.selectedSheet.selectionRanges.clear()}updateDropzoneArea(e){const t=this._draggingColumn,i=this._root,o=this.dropzoneMarker,l={col:0,row:0};t?l.col=e.hit<this.dropzonePrevHit?e.start:e.end:l.row=e.hit<this.dropzonePrevHit?e.start:e.end;this.scrollIntoView(l.row,l.col);const s=t?{start:this.cells.getCellBoundingRect(0,e.start),hit:this.cells.getCellBoundingRect(0,e.hit),end:this.cells.getCellBoundingRect(0,e.end)}:{start:this.cells.getCellBoundingRect(e.start,0),hit:this.cells.getCellBoundingRect(e.hit,0),end:this.cells.getCellBoundingRect(e.end,0)};let n,r={};if(t){n=`${FlexSheet.convertNumberToAlpha(e.start)} : ${FlexSheet.convertNumberToAlpha(e.end)}`;r={top:this._eCHdr.offsetHeight,left:i.scrollLeft,height:this.cells.height};s.hit.top=s.hit.bottom+i.scrollTop+8;if(this.rightToLeft){r.left=s.end.left-this.controlRect.left+i.scrollLeft;r.width=s.start.right-s.end.left}else{r.left+=s.start.left-this.controlRect.left;r.width=s.end.right-s.start.left}}else{n=`${e.start+1} : ${e.end+1}`;r={top:s.start.top-this.controlRect.top+i.scrollTop,width:this.cells.width,height:s.end.bottom-s.start.top};s.hit.top=s.hit.bottom;this.rightToLeft?r.right=this._eRHdr.offsetWidth:r.left=this._eRHdr.offsetWidth}if(this._dropRange)if(t){this._dropRange.col=e.start;this._dropRange.col2=e.end}else{this._dropRange.row=e.start;this._dropRange.row2=e.end}else this._dropRange=t?new CellRange(0,e.start,this.rows.length-1,e.end):new CellRange(e.start,0,e.end,this.columns.length-1);setCss(o,r);this._draggingTooltip.show(this.hostElement,n,s.hit);this.dropzonePrevHit=e.hit}updateDropzone(e){const t=new HitTestInfo(this.cells,e),i=this.rightToLeft,o=this._draggingColumn,l=o?t.col:t.row,s=this.dropzonePrevHit,n=this.selection,r=o?this.columns.length:this.rows.length;if(-1===l||l===s)return;this.dropzone||(this.dropzone=o?{left:l-n.leftCol,right:n.rightCol-l}:{left:l-n.topRow,right:n.bottomRow-l});const a={start:l-this.dropzone.left,hit:l,end:l+this.dropzone.right};if(a.start<0||a.end>r-1)return;const h=o?i?{start:this.cells.getCellBoundingRect(0,a.end),end:this.cells.getCellBoundingRect(0,a.start)}:{start:this.cells.getCellBoundingRect(0,a.start),end:this.cells.getCellBoundingRect(0,a.end)}:{start:this.cells.getCellBoundingRect(a.start,0),end:this.cells.getCellBoundingRect(a.end,0)},d={top:this.controlRect.top+this._eCHdr.offsetHeight,right:this.controlRect.right,bottom:this.controlRect.bottom,left:this.controlRect.left};let u;if(o){i?d.right-=this._eRHdr.offsetWidth:d.left+=this._eRHdr.offsetWidth;(d.left>=h.start.right||d.right<=h.end.left)&&(u=!0)}else(d.top>=h.start.bottom||d.bottom<=h.end.top)&&(u=!0);clearTimeout(this.dropzoneTimeout);u?this.dropzoneTimeout=setTimeout(()=>{this.updateDropzoneArea(a);this.updateDropzone(e)},100):this.updateDropzoneArea(a)}destroyDropzone(e){if(this.dropzoneMarker){this._root.removeChild(this.dropzoneMarker);this.dropzoneMarker=null}if(this.dropzoneTimeout){clearTimeout(this.dropzoneTimeout);this.dropzoneTimeout=null}if(this._draggingTooltip){this._draggingTooltip.hide();this._draggingTooltip=null}this.dropzone=null;this.dropzonePrevHit=-1}_showFillMarker(e){let t=new HitTestInfo(this.cells,e);if(t.row>-1&&t.col>-1){let i,o,l,s,n=e.clientX-this.scrollPosition.x-this._fillingPoint.x,r=e.clientY-this.scrollPosition.y-this._fillingPoint.y;if(Math.abs(n)>=Math.abs(r)){i=this._fillingSource.topRow;l=this._fillingSource.bottomRow;o=n>=0?this._fillingSource.leftCol:t.col;s=n>=0?t.col:this._fillingSource.rightCol}else{i=r>=0?this._fillingSource.topRow:t.row;l=r>=0?t.row:this._fillingSource.bottomRow;o=this._fillingSource.leftCol;s=this._fillingSource.rightCol}this._fillingRange=new CellRange(i,o,l,s);this._updateFillingMarquee();this.scrollIntoView(t.row,t.col);this._showFillTooltip()}}_updateMarquee(){super._updateMarquee();this._updateFillingMarquee()}_updateFillingMarquee(){let e=this._fillingMarker,t=this._fillingRange;if(!e||!t)return;let i=this.cells.getCellBoundingRect(t.row,t.col,!0),o=this.cells.getCellBoundingRect(t.row2,t.col2,!0);if(this.rows.frozen){let e=Math.min(this.rows.length,this.rows.frozen),l=this.cells.getCellBoundingRect(e-1,0,!0);t.topRow>=e&&i.top<l.bottom&&(i.top=l.bottom);t.bottomRow>=e&&o.bottom<l.bottom&&(o.height=l.bottom-o.top)}if(this.columns.frozen){let e=Math.min(this.columns.length,this.columns.frozen),l=this.cells.getCellBoundingRect(0,e-1,!0);if(this.rightToLeft){t.leftCol>=e&&i.right>l.left&&(i.left=l.left-i.width);t.rightCol>=e&&o.left>l.left&&(o.left=l.left)}else{t.leftCol>=e&&i.left<l.right&&(i.left=l.right);t.rightCol>=e&&o.right<l.right&&(o.width=l.right-o.left)}}let l=this.cells.hostElement;setCss(e,{left:i.left+l.offsetLeft,top:i.top+l.offsetTop,width:o.right-i.left,height:o.bottom-i.top,display:"",zIndex:this.rows.frozen||this.columns.frozen?"3":""})}_showFillTooltip(){let e,t,i,o,l,s,n,r,a,h,d,u,c=this._fillingSource,_=this._fillingRange;this._fillingTooltip.hide();if(!_.equals(c)&&!c.contains(_)){if(t=c.leftCol===_.leftCol&&c.rightCol===_.rightCol){if(_.bottomRow>c.bottomRow){(e=this.cells.getCellBoundingRect(_.bottomRow,_.rightCol)).top=e.bottom+10;i=_.bottomRow-c.topRow}else{(e=this.cells.getCellBoundingRect(_.topRow,_.rightCol)).top+=10;i=_.topRow-c.topRow}e.left=e.right;(o=i%c.rowSpan)<0&&(o+=c.rowSpan);c.row===c.row2&&(l=!0);a=this.selectedSheet.getCellStyle(c.topRow+o,c.leftCol);h=this.getMergedRange(this.cells,c.topRow+o,c.leftCol);d=this.columns[c.leftCol];u=a&&a.format?a.format:d.format;if(l)r=_isFormula(r=this.getCellData(h?h.topRow:c.topRow+o,c.leftCol,!1))?"":Globalize.format(r,u);else{s=this.getCellData(c.topRow+o,c.leftCol,!1);if(isNumber(s)||isDate(s))if(n=this._getFillSeries(t,0,o)){r=this._getFillData(o,i,c,t,n,!0);r=Globalize.format(r,u)}else r="";else _isFormula(r=s)&&(r="")}}else{if(_.rightCol>c.rightCol){e=this.cells.getCellBoundingRect(_.bottomRow,_.rightCol);i=_.rightCol-c.leftCol}else{e=this.cells.getCellBoundingRect(_.bottomRow,_.leftCol);i=_.leftCol-c.leftCol}e.top=e.bottom+10;(o=i%c.columnSpan)<0&&(o+=c.columnSpan);c.col===c.col2&&(l=!0);a=this.selectedSheet.getCellStyle(c.topRow,c.leftCol+o);h=this.getMergedRange(this.cells,c.topRow,c.leftCol+o);d=this.columns[c.leftCol+o];u=a&&a.format?a.format:d.format;if(l)r=_isFormula(r=this.getCellData(c.topRow,h?h.leftCol:c.leftCol+o,!1))?"":Globalize.format(r,u);else{s=this.getCellData(c.topRow,c.leftCol+o,!1);if(isNumber(s)||isDate(s))if(n=this._getFillSeries(t,0,o)){r=this._getFillData(o,i,c,t,n,!0);r=Globalize.format(r,u)}else r="";else _isFormula(r=s)&&(r="")}}e.top+=this.cells.hostElement.offsetTop;this._fillingTooltip.show(this.hostElement,r,e)}}_selections(){var e=[];if(!this.selectedSheet)return e;if(this.selectionMode==SelectionMode.ListBox)for(let t=0,i=this.rows.length,o=this.columns.length-1;t<i;t++)this.rows[t].isSelected&&e.push(new CellRange(t,0,t,o));else e=this.selectedSheet.selectionRanges.slice();return e.length?e:[this.selection]}_isCellSelected(e,t){return this._selections().some(i=>i.contains(e,t))}_isColumnSelected(e){return this._selections().some(t=>t.containsColumn(e)&&0===t.row&&t.row2===this.rows.length-1)}_isRowSelected(e){return this._selections().some(t=>t.containsRow(e)&&0===t.col&&t.col2===this.columns.length-1)}_handleDropping(e){var t,i,o,l,s,n,r;if(this.selectedSheet&&this._draggingCells&&this._dropRange&&!this._containsMergedCells(this._draggingCells)&&!this._containsMergedCells(this._dropRange)){this._clearCalcEngine();if(this._draggingColumn&&this._draggingCells.leftCol>this._dropRange.leftCol||this._draggingRow&&this._draggingCells.topRow>this._dropRange.topRow)if(e.shiftKey){if(!this._allowExchangeCells(this._draggingRow,!0)){console.warn("Can not complete operation: You are attempting to change a position of table row or column in a way that is not allowed.");return}if(this._draggingColumn){l=this._dropRange.leftCol;for(i=this._draggingCells.leftCol;i<=this._draggingCells.rightCol;i++){this.columns.moveElement(i,l);l++}this._exchangeTableColumns(!0)}else if(this._draggingRow){o=this._dropRange.topRow;for(t=this._draggingCells.topRow;t<=this._draggingCells.bottomRow;t++){this.rows.moveElement(t,o);o++}}this._exchangeCellStyle(!0)}else{this.undoStack.stackSize>0&&(s=new _MoveCellsAction(this,this._draggingCells,this._dropRange,e.ctrlKey));o=this._dropRange.topRow;for(t=this._draggingCells.topRow;t<=this._draggingCells.bottomRow;t++){l=this._dropRange.leftCol;for(i=this._draggingCells.leftCol;i<=this._draggingCells.rightCol;i++){this._moveCellContent(t,i,o,l,e.ctrlKey);if(this._draggingColumn&&o===this._dropRange.topRow){this.columns[l].dataType=this.columns[i].dataType?this.columns[i].dataType:DataType.Object;this.columns[l].align=this.columns[i].align;this.columns[l].format=this.columns[i].format;if(!e.ctrlKey){this.columns[i].dataType=DataType.Object;this.columns[i].align=null;this.columns[i].format=null}}l++}o++}if(this._draggingColumn&&!e.ctrlKey){l=this._dropRange.leftCol;for(i=this._draggingCells.leftCol;i<=this._draggingCells.rightCol;i++){this._updateColumnFiler(i,l);l++}}}else if(this._draggingColumn&&this._draggingCells.leftCol<this._dropRange.leftCol||this._draggingRow&&this._draggingCells.topRow<this._dropRange.topRow)if(e.shiftKey){if(!this._allowExchangeCells(this._draggingRow,!1)){console.warn("Can not complete operation: You are attempting to change a position of table row or column in a way that is not allowed.");return}if(this._draggingColumn){l=this._dropRange.rightCol;for(i=this._draggingCells.rightCol;i>=this._draggingCells.leftCol;i--){this.columns.moveElement(i,l);l--}this._exchangeTableColumns(!1)}else if(this._draggingRow){o=this._dropRange.bottomRow;for(t=this._draggingCells.bottomRow;t>=this._draggingCells.topRow;t--){this.rows.moveElement(t,o);o--}}this._exchangeCellStyle(!1)}else{this.undoStack.stackSize>0&&(s=new _MoveCellsAction(this,this._draggingCells,this._dropRange,e.ctrlKey));o=this._dropRange.bottomRow;for(t=this._draggingCells.bottomRow;t>=this._draggingCells.topRow;t--){l=this._dropRange.rightCol;for(i=this._draggingCells.rightCol;i>=this._draggingCells.leftCol;i--){this._moveCellContent(t,i,o,l,e.ctrlKey);if(this._draggingColumn&&o===this._dropRange.bottomRow){this.columns[l].dataType=this.columns[i].dataType?this.columns[i].dataType:DataType.Object;this.columns[l].align=this.columns[i].align;this.columns[l].format=this.columns[i].format;if(!e.ctrlKey){this.columns[i].dataType=DataType.Object;this.columns[i].align=null;this.columns[i].format=null}}l--}o--}if(this._draggingColumn&&!e.ctrlKey){l=this._dropRange.rightCol;for(i=this._draggingCells.rightCol;i>=this._draggingCells.leftCol;i--){this._updateColumnFiler(i,l);l--}}}if(!e.ctrlKey){n=this._updateFormulaForDropping(e.shiftKey);r=this._updateNamedRangesForDropping(e.shiftKey)}if(s&&s.saveNewState()){s._affectedFormulas=n;s._affectedDefinedNameVals=r;this._undoStack._addAction(s)}if(this._undoStack._pendingAction){this._undoStack._pendingAction._affectedFormulas=n;this._undoStack._pendingAction._affectedDefinedNameVals=r}this.select(this._dropRange);this.selectedSheet._addSelection(this.selection);this.hostElement.focus()}}_moveCellContent(e,t,i,o,l){var s,n=this.getCellData(e,t,!1),r=e*this.columns.length+t,a=i*this.columns.length+o,h=this.selectedSheet._styledCells[r],d=!0;let u=this.selectedSheet.findTable(i,o);if(u&&u._isHeaderRow(i)){let e=u.getRange(),t=u.getColumns(),i=o-e.leftCol;s=t[i].name;null==n||""===n?d=!1:t[i].name=n+""}if(d){if(l&&_isFormula(n)&&a-r!=0)try{let l=this._calcEngine.parse(n);l._moveCellRangeExp(this.selectedSheetIndex,new CellRange(e,t),new CellRange(i,o),!1,!0)&&(n="="+l._getStringExpression())}catch(e){}this.setCellData(i,o,n)}else d=!0;h?this.selectedSheet._styledCells[a]=this._cloneObject(h):delete this.selectedSheet._styledCells[a];if(l){let o=this.selectedSheet.findTable(e,t);if(o){let l=o._getTableRange();if(o===u&&e===i&&o._isHeaderRow(e)){let e=t-l.leftCol;o._updateColumnName(e,n)}}}else{delete this.selectedSheet._styledCells[r];let o=this.selectedSheet.findTable(e,t);if(o){let l=o._getTableRange();if(o===u&&e===i&&o._isHeaderRow(e)){let e=t-l.leftCol;o._updateColumnName(e,s);return}if(o.showHeaderRow&&e===l.topRow)return}this.setCellData(e,t,null)}}_allowExchangeCells(e,t){let i=this.selectedSheet.tables;for(let t=0;t<i.length;t++){let o,l,s,n,r=i[t];if(e){o=r.getRange(TableSection.Data);n=this._draggingCells.rowSpan;l=new CellRange(this._draggingCells.topRow,o.leftCol,this._draggingCells.bottomRow,o.rightCol);s=new CellRange(this._dropRange.topRow,o.leftCol,this._dropRange.bottomRow,o.rightCol)}else{o=r.getRange();n=this._draggingCells.columnSpan;l=new CellRange(o.topRow,this._draggingCells.leftCol,o.bottomRow,this._draggingCells.rightCol);s=new CellRange(o.topRow,this._dropRange.leftCol,o.bottomRow,this._dropRange.rightCol)}if(o.intersects(l)&&!o.contains(l)||o.intersects(s)&&!o.contains(s)||o.contains(l)&&!o.contains(s)||!o.contains(l)&&o.contains(s))return!1}return!0}_exchangeTableColumns(e){let t=this.selectedSheet.tables;for(let i=0;i<t.length;i++){let o=t[i],l=o.getRange();if(l.leftCol<=this._draggingCells.leftCol&&l.rightCol>=this._draggingCells.rightCol){let t=(e?this._draggingCells.leftCol:this._draggingCells.rightCol)-l.leftCol,i=(e?this._dropRange.leftCol:this._dropRange.rightCol)-l.leftCol;for(let l=0;l<this._draggingCells.columnSpan;l++){o._moveColumns(t,i);if(e){t++;i++}else{t--;i--}}}}}_exchangeCellStyle(e){let t=[];for(let e=this._draggingCells.topRow;e<=this._draggingCells.bottomRow;e++)for(let i=this._draggingCells.leftCol;i<=this._draggingCells.rightCol;i++){let o=e*this.columns.length+i;if(this.selectedSheet._styledCells[o]){t.push(this._cloneObject(this.selectedSheet._styledCells[o]));delete this.selectedSheet._styledCells[o]}else t.push(void 0)}if(e){if(this._draggingColumn){let e=this._draggingCells.rightCol-this._draggingCells.leftCol+1;for(let t=this._draggingCells.leftCol-1;t>=this._dropRange.leftCol;t--)for(let i=0;i<this.rows.length;i++){let o=i*this.columns.length+t,l=i*this.columns.length+t+e;if(this.selectedSheet._styledCells[o]){this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[o]);delete this.selectedSheet._styledCells[o]}else delete this.selectedSheet._styledCells[l]}}else if(this._draggingRow){let e=this._draggingCells.bottomRow-this._draggingCells.topRow+1;for(let t=this._draggingCells.topRow-1;t>=this._dropRange.topRow;t--)for(let i=0;i<this.columns.length;i++){let o=t*this.columns.length+i,l=(t+e)*this.columns.length+i;if(this.selectedSheet._styledCells[o]){this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[o]);delete this.selectedSheet._styledCells[o]}else delete this.selectedSheet._styledCells[l]}}}else if(this._draggingColumn){let e=this._draggingCells.rightCol-this._draggingCells.leftCol+1;for(let t=this._draggingCells.rightCol+1;t<=this._dropRange.rightCol;t++)for(let i=0;i<this.rows.length;i++){let o=i*this.columns.length+t,l=i*this.columns.length+t-e;if(this.selectedSheet._styledCells[o]){this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[o]);delete this.selectedSheet._styledCells[o]}else delete this.selectedSheet._styledCells[l]}}else if(this._draggingRow){let e=this._draggingCells.bottomRow-this._draggingCells.topRow+1;for(let t=this._draggingCells.bottomRow+1;t<=this._dropRange.bottomRow;t++)for(let i=0;i<this.columns.length;i++){let o=t*this.columns.length+i,l=(t-e)*this.columns.length+i;if(this.selectedSheet._styledCells[o]){this.selectedSheet._styledCells[l]=this._cloneObject(this.selectedSheet._styledCells[o]);delete this.selectedSheet._styledCells[o]}else delete this.selectedSheet._styledCells[l]}}for(let e=this._dropRange.topRow,i=0;e<=this._dropRange.bottomRow;e++)for(let o=this._dropRange.leftCol;o<=this._dropRange.rightCol;o++){let l=e*this.columns.length+o;t[i]?this.selectedSheet._styledCells[l]=t[i]:delete this.selectedSheet._styledCells[l];i++}}_containsMergedCells(e,t){if(!(t=t||this.selectedSheet))return!1;for(let i=0;i<t._mergedRanges.length;i++){let o=t._mergedRanges[i];if(e.intersects(o))return!0}return!1}_multiSelectColumns(e){if(e&&this._columnHeaderClicked){let t=new CellRange(e.row,e.col);t.row=this.itemsSource&&this.rows[0]&&!this.rows[0].isVisible?1:0;t.row2=this.rows.length-1;t.col2=this.selection.col2;this.select(t)}}_cumulativeOffset(e){let t=0,i=0;do{t+=e.offsetTop||0;i+=e.offsetLeft||0;e=e.offsetParent}while(e);return new Point(i,t)}_cumulativeScrollOffset(e){let t=0,i=0;do{t+=e.scrollTop||0;i+=e.scrollLeft||0;e=e.offsetParent}while(e&&!(e instanceof HTMLBodyElement));t+=document.body.scrollTop||document.documentElement.scrollTop;i+=document.body.scrollLeft||document.documentElement.scrollLeft;return new Point(i,t)}_checkHitWithinSelection(e){if(null!=e&&e.cellType===CellType.Cell){let t=this.getMergedRange(this.cells,e.row,e.col);if(t&&t.contains(this.selection))return!0;if(this.selection.row===e.row&&this.selection.col===e.col)return!0}return!1}_clearForEmptySheet(e){if(this.selectedSheet&&0===this[e].length&&!0!==this._isCopying&&!0!==this._isUndoing&&!0!==this._isSorting){this.selectedSheet._mergedRanges.length=0;this.selectedSheet._styledCells=null;this._isDeletingRows||this.select(new CellRange)}}_containsGroupRows(e){for(let t=e.topRow;t<=e.bottomRow;t++){if(this.rows[t]instanceof GroupRow)return!0}return!1}_delSeletionContent(e){if(this.isReadOnly)return;if(this.allowDelete&&this.selection.isValid&&0===this.selection.leftCol&&this.selection.rightCol===this.columns.length-1){this.deleteRows(this._selections());return}let t,i=this.editableCollectionView,o=!1,l=!1,s=this.scrollPosition;this.beginUpdate();let n=new _EditAction(this);this.undoStack.stackSize>0&&(n=new _EditAction(this));let r=this._selections();for(let s=0;s<r.length;s++){t=r[s];let a=new CellRange,h=new CellEditEndingEventArgs(this.cells,a,e),d=this.selectedSheet.tables.length;if(d>0)for(let e=d-1;e>=0;e--){let i=this.selectedSheet.tables[e];if(t.contains(i.getRange())){n&&n._storeDeletedTables(i);this.selectedSheet.tables.remove(i)}}for(let e=t.topRow;e<=t.bottomRow;e++){let s=this.rows[e];if(s&&!s.isReadOnly&&(s.visible||this.selectedSheet._freezeHiddenRows&&this.selectedSheet._freezeHiddenRows[e]))for(let n=t.leftCol;n<=t.rightCol;n++){let t=this._getBindingColumn(this.cells,e,this.columns[n]);if(t&&!t.isReadOnly&&(!1===t.isRequired||null==t.isRequired&&t.dataType==DataType.String)&&(t.visible||this.selectedSheet._freezeHiddenCols&&this.selectedSheet._freezeHiddenCols[n])){let t=this.getCellData(e,n,!1);if(null!=t){a.setRange(e,n);h.cancel=!1;h.previousData=t;if(this.onBeginningEdit(h)){if(i){if(!o){o=!0;i.beginUpdate()}i.editItem(s.dataItem);this._edtHdl._edItem=i.currentEditItem}this.setCellData(e,n,void 0,!1);l=!0;this.onCellEditEnding(h);this.onCellEditEnded(h)}}}}}if(o){i.endUpdate(!0);i._pendingRefresh=!1;t.rowSpan>1&&i.commitEdit()}}if(l&&n){n.saveNewState();this._undoStack._addAction(n)}this.selection=t;this.scrollPosition=s;this.endUpdate()}_updateAffectedFormula(e,t,i,o,l){let s=[],n=[],r=this.selection.clone();this.selectedSheet._storeRowSettings();this.beginUpdate();for(let r=0;r<this.sheets.length;r++){let a=this.sheets[r],h=a.grid;for(let d=0;d<h.rows.length;d++)for(let u=0;u<h.columns.length;u++){let c=h.getCellData(d,u,!1);if(_isFormula(c)){let _=this._updateCellRef(c,r,e,t,i,o,l);if(_){s.push({sheet:a,point:new Point(d,u),formula:c});let l=d,g=u;if(r===this.selectedSheetIndex){o?d>=e&&(i?l+=t:l-=t):u>=e&&(i?g+=t:g-=t);if(!i&&(o&&d<=e&&d>=e-t+1||!o&&u<=e&&u>=e-t+1))continue}h.setCellData(d,u,_,!1);n.push({sheet:a,point:new Point(l,g),formula:_})}}}}this.select(r,!1);this.endUpdate();return{oldFormulas:s,newFormulas:n}}_updateAffectedNamedRanges(e,t,i,o){let l=[],s=[];const n=[];for(let r=0;r<this.definedNames.length;r++){let a=this.definedNames[r],h=a.value;if(h&&isString(h)){let r=this._updateCellRef(h,this.selectedSheetIndex,e,t,i,o);if("object"==typeof r&&null!==r)n.push(r.name);else if(r){l.push({name:a.name,value:h});a.value=r;s.push({name:a.name,value:r})}}}n.forEach(e=>this.definedNames.remove(this.definedNames.find(t=>t.name==e)));return{oldDefinedNameVals:l,newDefinedNameVals:s}}_updateFormulaBoundaryForEditingCell(e,t){let i=[],o=[];this.beginUpdate();for(let l=e;l<this.rows.length;l++){let s=this.getCellData(l,t,!1);if(_isFormula(s)){let n=this._updateCellBoundary(s,e,t);if(n){i.push({point:new Point(l,t),formula:s});this.setCellData(l,t,n,!1);o.push({point:new Point(l,t),formula:n})}}}for(let l=t;l<this.columns.length;l++){let s=this.getCellData(e,l,!1);if(_isFormula(s)){let n=this._updateCellBoundary(s,e,t);if(n){i.push({point:new Point(e,l),formula:s});this.setCellData(e,l,n,!1);o.push({point:new Point(e,l),formula:n})}}}this.endUpdate();return{oldFormulas:i,newFormulas:o}}_updateColumnFiler(e,t){for(var i=JSON.parse(this._filter.filterDefinition),o=0;o<i.filters.length;o++){var l=i.filters[o];if(l.columnIndex===e){l.columnIndex=t;break}}this._filter.filterDefinition=JSON.stringify(i)}_isDescendant(e,t){for(var i=t.parentNode;null!=i;){if(i===e)return!0;i=i.parentNode}return!1}_clearCalcEngine(){this._calcEngine.clearExpressionCache()}_getRangeString(e,t,i=!0){var o,l,s,n,r,a="",h=!0,d=t&&t!==this.selectedSheet?t.grid:this;if(isArray(e))if(e.length>1){if(this._isMultipleRowsSelected(e,t)){a="";for(l=0;l<e.length;l++){a&&(a+="\n");a+=this._getRangeString(e[l],t)}return a}if(!this._isMultipleColumnsSelected(e,t))return"";a="";for(o=0,h=!0;o<d.rows.length;o++){h||(a+="\n");h=!1;for(l=0,g=!0;l<e.length;l++){(s=e[l].clone()).row=s.row2=o;g||(a+="\t");g=!1;a+=this._getRangeString(e[l],t)}return a}}else{r=e[0];switch(this.selectionMode){case SelectionMode.Row:case SelectionMode.RowRange:r.col=0;r.col2=t.grid.columns.length-1;break;case SelectionMode.ListBox:r.col=0;r.col2=t.grid.columns.length-1;for(var u=0;u<t.grid.rows.length;u++)if(t.grid.rows[u].isSelected&&t.grid.rows[u].isVisible){r.row=r.row2=u;a&&(a+="\n");a+=this._getRangeString(r,t)}return a}}for(var c=(r=asType(isArray(e)?e[0]:e,CellRange)).topRow;c<=r.bottomRow;c++)if(d.rows[c]&&d.rows[c].isVisible){h||(a+="\n");h=!1;for(var _=r.leftCol,g=!0;_<=r.rightCol;_++)if(d.columns[_]&&d.columns[_].isVisible){g||(a+="\t");g=!1;var f=this._getCellStyle(c,_,t),w=f?f.format:"",m=d.columns[_];if(i){_isFormula(n=d.getCellData(c,_,!1))&&(n=this._evaluate(n,null,t,c,_));n=this._formatEvaluatedResult(n,m,w)}else{n=d.getCellData(c,_,!1);isDate(n)&&(n=Globalize.format(n,w||m.format));m.dataMap&&(n=m.dataMap.getDisplayValue(n))}(n=(n=null==n?"":n.toString()).replace(/\t/g," ")).indexOf("\n")>-1&&(n='"'+n.replace(/"/g,'""')+'"');a+=n}}return a}_getSelectionForListBoxMode(e){let t,i=0;for(;i<e.rows.length;i++)e.rows[i].isSelected&&(t?t.row2=i:t=new CellRange(i,0,i,e.columns.length-1));return t}_containsRandFormula(e,t){for(var i=0;i<e.length;i++)for(var o=e[i],l=o.topRow;l<=o.bottomRow&&l<t.grid.rows.length;l++)for(var s=o.leftCol;s<=o.rightCol&&s<t.grid.columns.length;s++){var n=t.grid.getCellData(l,s,!1);if(_isFormula(n)&&-1!==n.search(/rand/i))return!0}return!1}_isMultipleRowsSelected(e,t){var i,o,l;e&&e.length>1?l=e:this.selectedSheet.selectionRanges.length>1&&(l=this.selectedSheet.selectionRanges);i=l[0];for(var s=1;s<l.length;s++)if((o=l[s]).leftCol!==i.leftCol||o.rightCol!==i.rightCol)return!1;return!0}_isMultipleColumnsSelected(e,t){var i,o,l;e&&e.length>1?l=e:this.selectedSheet.selectionRanges.length>1&&(l=this.selectedSheet.selectionRanges);i=l[0];for(var s=0;s<l.length;s++)if((o=l[s]).topRow!==i.topRow||o.bottomRow!==i.bottomRow)return!1;return!0}_postSetClipStringProcess(e,t,i,o,l,s,n,r,a){var h,d=new CellRangeEventArgs(this.cells,new CellRange(i+l,o),t);if(this.onPastingCell(d)){if(s>=0&&n>=0&&this._copiedSheet&&(h=this._copiedSheet._getMergedRange(s,n))&&h.topRow===s&&h.leftCol===n){var u=i+h.rowSpan-1;u=u<this.rows.length?u:this.rows.length-1;var c=o+h.columnSpan-1;c=c<this.columns.length?c:this.columns.length-1;let e=new CellRange(i,o,u,c);for(let t=e.topRow;t<=e.bottomRow;t++)for(let i=e.leftCol;i<=e.rightCol;i++){let o=this.getMergedRange(this.cells,t,i);if(null!=o&&!o.equals(e)){console.error("We can't paste the merged cell to another merged cell.");return!1}}this.mergeRange(new CellRange(i,o,u,c),!0)}r&&r.editItem(e);var _=this.cells.setCellData(i,o,a&&a.format?new _ValWithFormat(d.data,a.format):d.data);if(_){if(isString(d.data)&&"\n"!==d.data){var g=d.data.match(/\n/g);if(g&&g.length>0){a?a.whiteSpace="pre":a={whiteSpace:"pre"};this.rows[i].height=this.rows.defaultSize*(g.length+1)}}var f=i*this.columns.length+o;this.selectedSheet._styledCells[f]=a?this._cloneObject(a):void 0;this.onPastedCell(d)}}return _}_delCutData(e,t){let i,o=this._copiedSheet===this.selectedSheet?this:this._copiedSheet.grid,l=this.selection;for(let s=(i=this.selectionMode===SelectionMode.ListBox?this._getSelectionForListBoxMode(o):this._copiedRanges[0]).topRow;s<=i.bottomRow;s++)if(null!=o.rows[s]&&!o.rows[s].isReadOnly)for(let n=i.leftCol;n<=i.rightCol;n++)if(this._copiedSheet!==this.selectedSheet||s<l.topRow||s>l.topRow+e-1||n<l.leftCol||n>l.leftCol+t-1||o.rows[l.topRow]instanceof _NewRowTemplate){let e=o._getBindingColumn(o.cells,s,o.columns[n]);e.isReadOnly||0!=e.isRequired&&(null!=e.isRequired||e.dataType!=DataType.String)||o.getCellData(s,n,!0)&&(e.dataMap||o.rows[s].dataMap?o.setCellData(s,n,null,!0):o.setCellData(s,n,"",!0))}}_containsMultiLineText(e){for(var t=0;t<e.length;t++)for(var i=e[t],o=0;o<i.length;o++)if(i[o].indexOf("\n")>0)return!0;return!1}_sortByRow(e,t){return e.topRow>t.topRow?1:e.topRow<t.topRow?-1:0}_sortByColumn(e,t){return e.leftCol>t.leftCol?1:e.leftCol<t.leftCol?-1:0}_setFlexSheetToDirty(){this.columns._dirty=!0;this.rows._dirty=!0;this.rowHeaders.columns._dirty=!0;this.rowHeaders.rows._dirty=!0;this.columnHeaders.columns._dirty=!0;this.columnHeaders.rows._dirty=!0}static convertNumberToAlpha(e){var t,i,o="";if(e>=0)do{t=Math.floor(e/26);i=e%26;o=String.fromCharCode(i+65)+o;e=t-1}while(t);return o}_updateFormulaForReorderingRows(e,t,i=!1){var o,l,s=i?e-t:t-e;this.beginUpdate();for(var n=0;n<this.columns.length;n++)if(_isFormula(o=this.getCellData(t,n,!1))&&0!==s){try{l=this._calcEngine.parse(o)}catch(e){continue}l._updateCellRangeExpForReorderingRows(s)&&this.setCellData(t,n,"="+l._getStringExpression())}this.endUpdate()}_updateFormulaForDropping(e){var t,i,o,l,s,n,r,a,h,d=[],u=[];this.beginUpdate();for(o=0;o<this.sheets.length;o++){i=(t=this.sheets[o]).grid;for(l=0;l<i.rows.length;l++)for(n=0;n<i.columns.length;n++)if(_isFormula(a=i.getCellData(l,n,!1))&&(h=this._updateCellRefForDropping(a,o,e))){i.setCellData(l,n,h,!1);if(e&&o===this.selectedSheetIndex){s=i.rows[l];r=i.columns[n];d.push({sheet:t,row:s,column:r,formula:a});u.push({sheet:t,row:s,column:r,formula:h})}else{d.push({sheet:t,point:new Point(l,n),formula:a});u.push({sheet:t,point:new Point(l,n),formula:h})}}}this.endUpdate();return{oldFormulas:d,newFormulas:u}}_updateNamedRangesForDropping(e){var t,i,o,l,s=[],n=[];for(t=0;t<this.definedNames.length;t++)if((o=(i=this.definedNames[t]).value)&&isString(o)&&(l=this._updateCellRefForDropping(o,this.selectedSheetIndex,e))){s.push({name:i.name,value:o});i.value=l;n.push({name:i.name,value:l})}return{oldDefinedNameVals:s,newDefinedNameVals:n}}_updateCellRefForDropping(e,t,i=!1){let o;try{o=this._calcEngine.parse(e)}catch(e){return null}return o._moveCellRangeExp(t,this._draggingCells,this._dropRange,i)?"="+o._getStringExpression():null}_updateCellStyleForReorderingRows(e,t,i){let o,l,s,n=this.columns.length;for(o=0;o<n;o++)(s=this._getCellStyle(e,o))&&(i[l=t*n+o]=s)}_scanFormulas(){for(var e=[],t=0;t<this.rows.length;t++)for(var i=0;i<this.columns.length;i++){var o=this.getCellData(t,i,!1);_isFormula(o)&&e.push({row:t,column:i,formula:o})}return e}_resetFormulas(e){e&&this.deferUpdate(()=>{for(var t=0;t<e.length;t++){var i=e[t];this.setCellData(i.row,i.column,i.formula)}})}_getCellStyle(e,t,i){return(i=i||this.selectedSheet)?i.getCellStyle(e,t):null}_getSheet(e){if(null==e)return null;e=e.toLowerCase();for(let t=0;t<this.sheets.length;t++){let i=this.sheets[t];if(i.name.toLowerCase()===e)return i}return null}_validateSheetName(e){return!!this._getSheet(e)}_sheetNameChanged(e,t){if(!this._loadingFromWorkbook){this.definedNames._updateSheetName(e,t);this._updateFormulasWithNameUpdating(e,t)}}_updateFormulasTableColumn(e,t,i,o){if(i===o)return;this.beginUpdate();let l=new RegExp(`${e.name}\\[${i}\\]`,"g"),s=`${e.name}[${o}]`,n=new RegExp(`\\[${i}\\]`,"g"),r=`[${i}]`,a=`[${o}]`;for(let t=0;t<this.sheets.length;t++){let i=this.sheets[t],o=i.grid;for(let t=0;t<o.rows.length;t++)for(let h=0;h<o.columns.length;h++){let d=o.getCellData(t,h,!1);if(_isFormula(d)&&d.indexOf("[")>=0){if((d=d.replace(l,s)).indexOf(r)>=0){let o=i.findTable(t,h);o&&o.name===e.name&&(d=d.replace(n,a))}o.setCellData(t,h,d,!1)}}}e._updateColumnName(t-e._getTableRange().leftCol,o,!1);this.endUpdate()}_updateFormulasWithNameUpdating(e,t,i=!1){if(!this.sheets.length)return;let o=i?/\[/:/\w/,l=this.selection.clone();this.selectedSheet._storeRowSettings();this.beginUpdate();for(let l=0;l<this.sheets.length;l++){let s=this.sheets[l].grid;for(let l=0;l<s.rows.length;l++)for(let n=0;n<s.columns.length;n++){let r=s.getCellData(l,n,!1);if(_isFormula(r)){let a=!1,h=r.indexOf(e),d=new RegExp(e,"g");for(;h>-1;){let l="",s="";h>0&&(l=r[h-1]);h+e.length<r.length&&(s=r[h+e.length]);if(!/\w/.test(l)&&(i&&o.test(s)||!i&&!o.test(s))){r=r.replace(d,(i,o)=>o===h?t:e);a=!0}h=r.indexOf(e,h+e.length)}a&&s.setCellData(l,n,r,!1)}}}this.selection=l;this.endUpdate()}_updateTablesForUpdatingRow(e,t,i){var o,l,s,n,r;if(this.selectedSheet.tables.length>0)for(o=this.selectedSheet.tables.length-1;o>=0;o--){s=(l=this.selectedSheet.tables[o]).getRange();if(i){if((n=e+t-1)<s.topRow)l._updateTableRange(-t,-t,0,0);else if(n>=s.topRow&&n<=s.bottomRow){if(e<=s.topRow&&n===s.bottomRow){null==r&&(r=[]);r.push(l);this.selectedSheet.tables.remove(l);continue}if(e<s.topRow){l.showHeaderRow&&(l._showHeaderRow=!1);l._updateTableRange(e-s.topRow,-t,0,0)}else{e===s.topRow&&l.showHeaderRow&&(l._showHeaderRow=!1);n===s.bottomRow&&l.showTotalRow&&(l._showTotalRow=!1);l._updateTableRange(0,-t,0,0)}}else if(e<=s.topRow){null==r&&(r=[]);r.push(l);this.selectedSheet.tables.remove(l)}else if(e<=s.bottomRow){l.showTotalRow&&(l._showTotalRow=!1);l._updateTableRange(0,e-s.bottomRow-1,0,0)}}else e<=s.topRow?l._updateTableRange(t,t,0,0):e>s.topRow&&e<=s.bottomRow&&l._updateTableRange(0,t,0,0)}return r}_updateTablesForUpdatingColumn(e,t,i){var o,l,s,n,r,a,h,d;if(this.selectedSheet.tables.length>0)for(o=this.selectedSheet.tables.length-1;o>=0;o--){s=(l=this.selectedSheet.tables[o]).getRange();if(i){if((n=e+t-1)<s.leftCol)l._updateTableRange(0,0,-t,-t);else if(n>=s.leftCol&&n<=s.rightCol){if(e<=s.leftCol&&n===s.rightCol){null==d&&(d=[]);d.push(l);this.selectedSheet.tables.remove(l);continue}if(e<s.leftCol){r=t-s.leftCol+e;a=s.leftCol;l._updateTableRange(0,0,e-s.leftCol,-t)}else{r=t;a=e;l._updateTableRange(0,0,0,-r)}l._columns.splice(a-s.leftCol,r)}else if(e<=s.leftCol){null==d&&(d=[]);d.push(l);this.selectedSheet.tables.remove(l)}else if(e<=s.rightCol){r=s.rightCol-e+1;l._updateTableRange(0,0,0,-r);l._columns.splice(e,r)}}else if(e<=s.leftCol)l._updateTableRange(0,0,t,t);else if(e>s.leftCol&&e<=s.rightCol){l._updateTableRange(0,0,0,t);a=e-s.leftCol;for(h=0;h<t;h++)l._addColumn(a+h)}}return d}_updateDivContainerHeight(e){let t=this._divContainer.parentElement.clientHeight;e&&(t-=this._tabHolder.getSheetBlanketSize());this._divContainer.style.height=t+"px"}_isDisableDeleteRow(e,t){var i,o,l;if(this.selectedSheet.tables.length>0)for(i=0;i<this.selectedSheet.tables.length;i++){l=(o=this.selectedSheet.tables[i]).getRange();if(o.showHeaderRow&&l.topRow>=e&&l.topRow<=t)return!0}return!1}_copy(e,t){var i,o;if("columns"==e){super._copy(e,t);if(this.itemsSource&&(i=this.rows[0])instanceof HeaderRow){i._ubv=null;i._ubv={};for(var l=0;l<this.columns.length;l++){o=this.columns[l];i._ubv[o._hash]=FlexSheet._getHeaderRowText(o)}}return!0}return!1}_getTableSheetIndex(e,t){this.sheets;for(let i=0;i<e.length;i++)if(e[i].indexOf(t)>-1)return i;return-1}_sheetSortConverter(e,t,i,o){_isFormula(i=super._sortConverter(e,t,i,o))&&(i=this.evaluate(i));return i}_formatEvaluatedResult(e,t,i){if(isPrimitive(e)){t.dataMap&&(e=t.dataMap.getDisplayValue(e));let o=i||t.format;if(!isInt(e)||o||t.dataMap){isDate(e)&&_isExclusiveNumericFormat(o)?e=FlexSheet._toOADate(e):o&&"@"!==o&&isString(e)&&(+e).toString()===e&&(e=+e);e=null!=e?Globalize.format(e,o):""}else e=e.toString()}else if(e){if(e instanceof FormulaError)return e.error;let o=i||e.format||t.format;if(!isInt(e.value)||o||t.dataMap){isDate(e.value)&&_isExclusiveNumericFormat(o)?e.value=FlexSheet._toOADate(e.value):isString(e.value)&&(+e.value).toString()===e.value&&(e.value=+e.value);e=null!=e.value?Globalize.format(e.value,o):""}else e=e.value.toString()}return e}_updateCellRef(e,t,i,o,l,s,n){let r;try{r=this._calcEngine.parse(e)}catch(e){return null}const a=r;if(!l&&this._isDeletingColumns&&this.definedNames&&this.definedNames.length&&a._cells){const{_col:t,_col2:l}=this.selection,{_col:s,_col2:n}=a._cells,[r,h]=[i,i-o+1],[d,u]=[Math.max(s,n),Math.min(s,n)];if(u>=h&&d<=r){const t=this.definedNames.find(t=>t.value==e);if(t){const e=this.sheets[this.selectedSheetIndex].name,i=t.sheetName;if(i&&i===e||null==i&&t.value.includes(e))return{name:t.name}}}}return r._updateCellRangeExp(t,i,o,l,s,n)?"="+r._getStringExpression():null}_updateCellBoundary(e,t,i){let o;try{o=this._calcEngine.parse(e)}catch(e){return null}return o instanceof _FunctionExpression&&o._updateCellBoundary(t,i)?"="+o._getStringExpression():null}_fillData(e=AutoFillOperation.CopyFormat|AutoFillOperation.FillSeries){let t=this._fillingRange||this.selection,i=this._fillingSource,o=0!=(e&AutoFillOperation.CopyFormat),l=0!=(e&AutoFillOperation.CopyContent),s=0!=(e&AutoFillOperation.FillSeries),n=i.leftCol===t.leftCol&&i.rightCol===t.rightCol,r=[],a=new AutoFillingEventArgs(t,e);this.onAutoFilling(a);if(a.cancel)return!1;this.beginUpdate();this._resetCellsForFillRange(e);for(let a=0;a<t.rowSpan;a++){let h=t.topRow+a,d=h-i.topRow,u=d%i.rowSpan;if(this.rows[h].visible){u<0&&(u+=i.rowSpan);for(let c=0;c<t.columnSpan;c++){let _=t.leftCol+c,g=_-i.leftCol;if(d>=0&&d<i.rowSpan&&g>=0&&g<i.columnSpan)continue;let f=g%i.columnSpan;f<0&&(f+=i.columnSpan);let w,m=!1,p=this.getMergedRange(this.cells,i.topRow+u,i.leftCol+f);if(p&&(m=p.topRow===i.topRow+u&&p.leftCol===i.leftCol+f)){this.getMergedRange(this.cells,h,_)||this.mergeRange(new CellRange(h,_,h+p.rowSpan-1,_+p.columnSpan-1))}if(o){let e=this.selectedSheet.getCellStyle(i.topRow+u,i.leftCol+f),t=e?this._cloneObject(e):null,o=h*this.columns.length+_;this.selectedSheet._styledCells[o]=t}if((!p||m)&&(!this.isReadOnly&&!this.rows[h].isReadOnly&&!this.columns[_].isReadOnly))if(l)_isFormula(w=this.getCellData(i.topRow+u,i.leftCol+f,!1))?this._fillFormula(w,i.topRow+u,i.leftCol+f,h,_):this.setCellData(h,_,w);else if(s){let t,o;if(n){t=c;o=u}else{t=a;o=f}if(null==(w=this.getCellData(i.topRow+u,i.leftCol+f,!1))||isString(w)){_isFormula(w)?this._fillFormula(w,i.topRow+u,i.leftCol+f,h,_):this.setCellData(h,_,w);r[t]=null}else{r[t]||(r[t]=this._getFillSeries(n,t,o));let l=r[t];if(l){if(n){w=this._getFillData(u,d,i,n,l,null!=e||0===t);l.endIndex===i.topRow+u&&(r[t]=null)}else{w=this._getFillData(f,g,i,n,l,null!=e||0===t);l.endIndex===i.leftCol+f&&(r[t]=null)}this.setCellData(h,_,w)}}}}}}this._fillingRange&&this.select(this._fillingRange,!1);this.endUpdate();this.onAutoFilled(a);return!0}_getFillData(e,t,i,o,l,s){let n,r,a=l.items;if(1===a.length&&!s)return a[0];n=o?Math.floor(t/i.rowSpan)*l.itemIndexes[l.itemIndexes.length-1]+i.topRow+e-l.startIndex+1:Math.floor(t/i.columnSpan)*l.itemIndexes[l.itemIndexes.length-1]+i.leftCol+e-l.startIndex+1;r=this._getLinearBestFitTrendData(a,l.itemIndexes,n);"date"===l.type&&(r=FlexSheet._fromOADate(r));return r}_fillFormula(e,t,i,o,l){let s,n,r;try{s=this._calcEngine.parse(e);n=new CellRange(t,i);r=new CellRange(o,l);s._moveCellRangeExp(this.selectedSheetIndex,n,r,!1,!0)&&(e="="+s._getStringExpression())}catch(e){}finally{this.setCellData(o,l,e)}}_getFillSeries(e,t,i){let o,l,s,n,r,a,h,d,u=this._fillingSource,c=[],_=[];if(e){i=u.topRow+i;n=0;for(r=u.topRow;r<=u.bottomRow;r++){if(a=this.getMergedRange(this.cells,r,u.leftCol+t))if(h&&!a.equals(h)){n+=h.rowSpan;h=a;if(a.leftCol!==u.leftCol+t)continue}else{if(a.topRow!==r||a.leftCol!==u.leftCol+t)continue;n+=1;h=a}else if(h){n+=h.rowSpan;h=null}else n+=1;if(null!=(d=this.getCellData(r,u.leftCol+t,!1))&&""!==d)if(isNumber(d)||isDate(d)){o=isNumber(d)?"number":"date";isDate(d)&&(d=FlexSheet._toOADate(d));if(0===c.length){s=r;l=o;c.push(d);_.push(n)}else if(o===l){c.push(d);_.push(n)}else{if(i>=s&&i<=r)return{type:l,startIndex:s,endIndex:r-1,items:c,itemIndexes:_};c.splice(0,c.length);_.splice(0,_.length)}}else if(c.length>0){if(i>=s&&i<=r)return{type:l,startIndex:s,endIndex:r-1,items:c,itemIndexes:_};c.splice(0,c.length);_.splice(0,_.length)}}}else{i=u.leftCol+i;n=0;for(r=u.leftCol;r<=u.rightCol;r++){if(a=this.getMergedRange(this.cells,u.topRow+t,r))if(h&&!a.equals(h)){n+=h.columnSpan;h=a;if(a.topRow!==u.topRow+t)continue}else{if(a.leftCol!==r||a.topRow!==u.topRow+t)continue;n+=1;h=a}else if(h){n+=h.columnSpan;h=null}else n+=1;if(null!=(d=this.getCellData(u.topRow+t,r,!1))&&""!==d)if(isNumber(d)||isDate(d)){o=isNumber(d)?"number":"date";isDate(d)&&(d=FlexSheet._toOADate(d));if(0===c.length){s=r;l=o;c.push(d);_.push(n)}else if(o===l){c.push(d);_.push(n)}else{if(i>=s&&i<=r)return{type:l,startIndex:s,endIndex:r-1,items:c,itemIndexes:_};c.splice(0,c.length);_.splice(0,_.length)}}else if(c.length>0){if(i>=s&&i<=r)return{type:l,startIndex:s,endIndex:r-1,items:c,itemIndexes:_};c.splice(0,c.length);_.splice(0,_.length)}}}return c.length>0?{type:l,startIndex:s,endIndex:r-1,items:c,itemIndexes:_}:null}_getLinearBestFitTrendData(e,t,i){let o,l,s,n,r,a,h=0,d=0,u=0,c=0;if(1===(n=e.length))return e[0]+i-1;for(o=0;o<t.length;o++){h+=l=t[o];u+=l*l;d+=s=e[o];c+=l*s}return i*(r=(n*c-h*d)/(n*u-h*h))+(a=(d*u-h*c)/(n*u-h*h))}_getCellSettingsForFill(e,t){let i,o,l,s,n,r;e||(e=this._fillingSource);t||(t=this._fillingRange);n=[];for(i=t.topRow;i<=t.bottomRow;i++)for(o=t.leftCol;o<=t.rightCol;o++)if(!(i>=e.topRow&&i<=e.bottomRow&&o>=e.leftCol&&o<=e.rightCol)){l=this.getCellData(i,o,!1);s=this._cloneObject(this.selectedSheet.getCellStyle(i,o));(r=this.getMergedRange(this.cells,i,o))&&r.topRow===i&&r.leftCol===o||(r=null);n.push({row:i,col:o,value:l,style:s,mergedCell:r?r.clone():null})}return n}_resetCellsForFillRange(e){let t=0!=(e&AutoFillOperation.CopyFormat),i=0!=(e&AutoFillOperation.CopyContent),o=0!=(e&AutoFillOperation.FillSeries);if(this._orgCellSettings&&this._orgCellSettings.length>0)for(let e=0;e<this._orgCellSettings.length;e++){let l=this._orgCellSettings[e],s=l.row,n=l.col;if(!t){let e=s*this.columns.length+n;this.selectedSheet._styledCells[e]=l.style}i||o||this.setCellData(s,n,l.value)}}_canDoFillOperation(){let e,t,i,o,l,s,n,r,a,h,d,u,c,_,g,f=this._fillingSource,w=this._fillingRange,m=!1;for(e=f.topRow;e<=f.bottomRow;e++)for(t=f.leftCol;t<=f.rightCol;t++){h=this.getMergedRange(this.cells,e,t);if(d){if(!h||!d.equals(h)){m=!0;break}}else d=h}for(i=w.topRow;i<=w.bottomRow;i++){(o=(l=i-f.topRow)%f.rowSpan)<0&&(o+=f.rowSpan);o+=f.topRow;for(s=w.leftCol;s<=w.rightCol;s++){r=s-f.leftCol;if(!(l>=0&&l<f.rowSpan&&r>=0&&r<f.columnSpan)){(n=r%f.columnSpan)<0&&(n+=f.columnSpan);n+=f.leftCol;h=this.getMergedRange(this.cells,o,n);if(a=this.getMergedRange(this.cells,i,s)){if(m||!h)return!1;u=a?i-a.topRow:NaN;c=a?s-a.leftCol:NaN;_=h?o-h.topRow:NaN;g=h?n-h.leftCol:NaN;if(u!==_||c!==g)return!1}}}}return!0}_updateItemIndexForInsertingRow(e,t,i){for(let o=0;o<e.length;o++){let l=e[o];l&&null!=l._itemIdx&&l._itemIdx>=t&&(l._itemIdx+=i)}}_updateItemIndexForRemovingRow(e,t){for(let i=0;i<e.length;i++){let o=e[i];o&&null!=o._itemIdx&&o._itemIdx>=t&&(o._itemIdx-=1)}}_copyRowsToSelectedSheet(){if(this.selectedSheet){this.selectedSheet.grid.rows.clear();for(let e=0;e<this.rows.length;e++){let t=this.rows[e];this.selectedSheet.grid.rows.push(t);t._list=this.rows}setTimeout(()=>{this._setFlexSheetToDirty();this.invalidate()},10)}}_copyColumnsToSelectedSheet(){if(this.selectedSheet){this.selectedSheet.grid.columns.clear();for(let e=0;e<this.columns.length;e++){let t=this.columns[e];this.selectedSheet.grid.columns.push(t);t._setList(this.columns)}setTimeout(()=>{this._setFlexSheetToDirty();this.invalidate()},10)}}_getUniqueColumnName(){let e=this.insertedColumnIndex+1;for(;null!=this.columns.getColumn("col"+e);)e++;return`col${this.insertedColumnIndex=e}`}_hideContextMenu(){this._contextMenu.hide();this._tabHolder.sheetControl._contextMenu.hide()}_parseFromWorkbookTable(e,t){var i,o,l,s,n,r,a,h,d,u,c,_=t===this.selectedSheet?this:t.grid;l=(o=e.range.split(":"))[0];s=o[1];n=mXlsx.Workbook.tableAddress(l);i=new CellRange(n.row,n.col);r=mXlsx.Workbook.tableAddress(s);i.row2=r.row;i.col2=r.col;if(i.bottomRow>=t.rowCount){c=i.bottomRow-t.rowCount+1;for(g=0;g<c;g++)_.rows.push(new Row)}if(i.rightCol>=t.columnCount){c=i.rightCol-t.columnCount+1;for(g=0;g<c;g++)_.columns.push(new Column)}if(e.columns&&e.columns.length>0){a=[];for(var g=0;g<e.columns.length;g++){h=e.columns[g];a[g]=new TableColumn(h.name,h.totalRowLabel,h.totalRowFunction,h.showFilterButton)}}null!=e.style&&(d=this._isBuiltInStyleName(e.style.name)?this.getBuiltInTableStyle(e.style.name):this._parseFromWorkbookTableStyle(e.style));u=new Table(e.name,i,d,a,{showHeaderRow:e.showHeaderRow,showTotalRow:e.showTotalRow,showBandedColumns:e.showBandedColumns,showBandedRows:e.showBandedRows,alterFirstColumn:e.alterFirstColumn,alterLastColumn:e.alterLastColumn});t.tables.push(u);return u}_parseFromWorkbookTableStyle(e){var t=new TableStyle(e.name);null!=e.firstBandedColumnStyle&&(t.firstBandedColumnStyle=this._parseFromWorkbookTableStyleElement(e.firstBandedColumnStyle));null!=e.firstBandedRowStyle&&(t.firstBandedRowStyle=this._parseFromWorkbookTableStyleElement(e.firstBandedRowStyle));null!=e.firstColumnStyle&&(t.firstColumnStyle=this._parseFromWorkbookTableStyleElement(e.firstColumnStyle));null!=e.firstHeaderCellStyle&&(t.firstHeaderCellStyle=this._parseFromWorkbookTableStyleElement(e.firstHeaderCellStyle));null!=e.firstTotalCellStyle&&(t.firstTotalCellStyle=this._parseFromWorkbookTableStyleElement(e.firstTotalCellStyle));null!=e.headerRowStyle&&(t.headerRowStyle=this._parseFromWorkbookTableStyleElement(e.headerRowStyle));null!=e.lastColumnStyle&&(t.lastColumnStyle=this._parseFromWorkbookTableStyleElement(e.lastColumnStyle));null!=e.lastHeaderCellStyle&&(t.lastHeaderCellStyle=this._parseFromWorkbookTableStyleElement(e.lastHeaderCellStyle));null!=e.lastTotalCellStyle&&(t.lastTotalCellStyle=this._parseFromWorkbookTableStyleElement(e.lastTotalCellStyle));null!=e.secondBandedColumnStyle&&(t.secondBandedColumnStyle=this._parseFromWorkbookTableStyleElement(e.secondBandedColumnStyle));null!=e.secondBandedRowStyle&&(t.secondBandedRowStyle=this._parseFromWorkbookTableStyleElement(e.secondBandedRowStyle));null!=e.totalRowStyle&&(t.totalRowStyle=this._parseFromWorkbookTableStyleElement(e.totalRowStyle));null!=e.wholeTableStyle&&(t.wholeTableStyle=this._parseFromWorkbookTableStyleElement(e.wholeTableStyle));return t}_parseFromWorkbookTableStyleElement(e){var t;t={fontWeight:e.font&&e.font.bold?"bold":"none",fontStyle:e.font&&e.font.italic?"italic":"none",textDecoration:e.font&&e.font.underline?"underline":"none",fontFamily:e.font&&e.font.family?e.font.family:"",fontSize:e.font&&e.font.size?e.font.size+"px":"",color:e.font&&e.font.color?e.font.color:"",backgroundColor:e.fill&&e.fill.color?e.fill.color:""};if(e.borders){if(e.borders.left){FlexGridXlsxConverter._parseBorderStyle(e.borders.left.style,"Left",t);t.borderLeftColor=e.borders.left.color}if(e.borders.right){FlexGridXlsxConverter._parseBorderStyle(e.borders.right.style,"Right",t);t.borderRightColor=e.borders.right.color}if(e.borders.top){FlexGridXlsxConverter._parseBorderStyle(e.borders.top.style,"Top",t);t.borderTopColor=e.borders.top.color}if(e.borders.bottom){FlexGridXlsxConverter._parseBorderStyle(e.borders.bottom.style,"Bottom",t);t.borderBottomColor=e.borders.bottom.color}if(e.borders.vertical){FlexGridXlsxConverter._parseBorderStyle(e.borders.vertical.style,"Vertical",t);t.borderVerticalColor=e.borders.vertical.color}if(e.borders.horizontal){FlexGridXlsxConverter._parseBorderStyle(e.borders.horizontal.style,"Horizontal",t);t.borderHorizontalColor=e.borders.horizontal.color}}null!=e.size&&(t.size=e.size);return t}_parseToWorkbookTable(e){var t,i,o=new mXlsx.WorkbookTable,l=e.getRange(),s=e.getColumns();o.name=e.name;t=mXlsx.Workbook.xlsxAddress(l.topRow,l.leftCol);i=mXlsx.Workbook.xlsxAddress(l.bottomRow,l.rightCol);o.range=t+":"+i;if(null!=e.style)if(e.style.isBuiltIn){o.style=new mXlsx.WorkbookTableStyle;o.style.name=e.style.name}else o.style=this._parseToWorkbookTableStyle(e.style);o.showBandedColumns=e.showBandedColumns;o.showBandedRows=e.showBandedRows;o.showHeaderRow=e.showHeaderRow;o.showTotalRow=e.showTotalRow;o.alterFirstColumn=e.alterFirstColumn;o.alterLastColumn=e.alterLastColumn;for(var n=0;n<s.length;n++){var r=s[n],a=new mXlsx.WorkbookTableColumn;a.name=r.name;a.totalRowLabel=r.totalRowLabel;a.totalRowFunction=r.totalRowFunction;a.showFilterButton=r.showFilterButton;o.columns.push(a)}return o}_parseToWorkbookTableStyle(e){var t=new mXlsx.WorkbookTableStyle;t.name=e.name;null!=e.firstBandedColumnStyle&&(t.firstBandedColumnStyle=this._parseToWorkbookTableStyleElement(e.firstBandedColumnStyle,!0));null!=e.firstBandedRowStyle&&(t.firstBandedRowStyle=this._parseToWorkbookTableStyleElement(e.firstBandedRowStyle,!0));null!=e.firstColumnStyle&&(t.firstColumnStyle=this._parseToWorkbookTableStyleElement(e.firstColumnStyle));null!=e.firstHeaderCellStyle&&(t.firstHeaderCellStyle=this._parseToWorkbookTableStyleElement(e.firstHeaderCellStyle));null!=e.firstTotalCellStyle&&(t.firstTotalCellStyle=this._parseToWorkbookTableStyleElement(e.firstTotalCellStyle));null!=e.headerRowStyle&&(t.headerRowStyle=this._parseToWorkbookTableStyleElement(e.headerRowStyle));null!=e.lastColumnStyle&&(t.lastColumnStyle=this._parseToWorkbookTableStyleElement(e.lastColumnStyle));null!=e.lastHeaderCellStyle&&(t.lastHeaderCellStyle=this._parseToWorkbookTableStyleElement(e.lastHeaderCellStyle));null!=e.lastTotalCellStyle&&(t.lastTotalCellStyle=this._parseToWorkbookTableStyleElement(e.lastTotalCellStyle));null!=e.secondBandedColumnStyle&&(t.secondBandedColumnStyle=this._parseToWorkbookTableStyleElement(e.secondBandedColumnStyle,!0));null!=e.secondBandedRowStyle&&(t.secondBandedRowStyle=this._parseToWorkbookTableStyleElement(e.secondBandedRowStyle,!0));null!=e.totalRowStyle&&(t.totalRowStyle=this._parseToWorkbookTableStyleElement(e.totalRowStyle));null!=e.wholeTableStyle&&(t.wholeTableStyle=this._parseToWorkbookTableStyleElement(e.wholeTableStyle));return t}_parseToWorkbookTableStyleElement(e,t=!1){var i,o=FlexGridXlsxConverter._parseCellStyle(e,!0);t?(i=new mXlsx.WorkbookTableBandedStyle).size=e.size:i=new mXlsx.WorkbookTableCommonStyle;i._deserialize(o);return i}_isBuiltInStyleName(e){var t;if(0===e.search(/TableStyleLight/i)){t=+e.substring(15);if(!isNaN(t)&&t>=1&&t<=21)return!0}else if(0===e.search(/TableStyleMedium/i)){t=+e.substring(16);if(!isNaN(t)&&t>=1&&t<=28)return!0}else if(0===e.search(/TableStyleDark/i)){t=+e.substring(14);if(!isNaN(t)&&t>=1&&t<=11)return!0}return!1}_getTable(e){e=e.substr(e.lastIndexOf("!")+1);for(var t=0;t<this.sheets.length;t++){let i=this.sheets[t].tables;for(let t=0;t<i.length;t++){let o=i[t];if(o.name.toLowerCase()===e.toLowerCase())return o}}return null}_checkTableHeaderRow(e,t){e.forEach(e=>{if(!e.showHeaderRow)return;let i=e.getRange(TableSection.Header);for(let o=i.row,l=i.leftCol;l<=i.rightCol;l++){let s=t.sheets[0].rows[o].cells[l];s.isDate=!1;if(null==s.value||""===s.value){let t=l-i.leftCol;s.value=e._getColumns()[t].name}}})}_getThemeColor(e,t){var i,o=this._colorThemes[e];if(null!=t){(i=new Color("#"+o).getHsl())[2]=t<0?i[2]*(1+t):i[2]*(1-t)+(1-1*(1-t));return Color.fromHsl(i[0],i[1],i[2]).toString()}return"#"+o}_createBuiltInTableStyle(e){var t;if(0===e.search(/TableStyleLight/i)){t=+e.substring(15);if(!isNaN(t)&&t>=1&&t<=21)return t<=7?this._generateTableLightStyle1(t-1,e,!0):t<=14?this._generateTableLightStyle2(t-8,e):this._generateTableLightStyle1(t-15,e,!1)}else if(0===e.search(/TableStyleMedium/i)){t=+e.substring(16);if(!isNaN(t)&&t>=1&&t<=28)return t<=7?this._generateTableMediumStyle1(t-1,e):t<=14?this._generateTableMediumStyle2(t-8,e):t<=21?this._generateTableMediumStyle3(t-15,e):this._generateTableMediumStyle4(t-22,e)}else if(0===e.search(/TableStyleDark/i)){t=+e.substring(14);if(!isNaN(t)&&t>=1&&t<=11)return t<=7?this._generateTableDarkStyle1(t-1,e):this._generateTableDarkStyle2(t-8,e)}return null}_generateTableLightStyle1(e,t,i){var o=new TableStyle(t,!0),l=0===e?1:e+3,s=i?"1px":"2px",n=i?"solid":"double",r=i?"1px":"3px";o.wholeTableStyle={borderTopColor:this._getThemeColor(l),borderTopStyle:"solid",borderTopWidth:"1px",borderBottomColor:this._getThemeColor(l),borderBottomStyle:"solid",borderBottomWidth:"1px"};o.firstColumnStyle={fontWeight:"bold"};o.lastColumnStyle={fontWeight:"bold"};o.headerRowStyle={borderBottomColor:this._getThemeColor(l),borderBottomStyle:"solid",borderBottomWidth:s,fontWeight:"bold"};o.totalRowStyle={borderTopColor:this._getThemeColor(l),borderTopStyle:n,borderTopWidth:r,fontWeight:"bold"};if(0===e){o.wholeTableStyle.color=this._getThemeColor(l);o.firstColumnStyle.color=this._getThemeColor(l);o.lastColumnStyle.color=this._getThemeColor(l);o.headerRowStyle.color=this._getThemeColor(l);o.totalRowStyle.color=this._getThemeColor(l);o.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.15)};o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.15)}}else{if(i){o.wholeTableStyle.color=this._getThemeColor(l,-.25);o.firstColumnStyle.color=this._getThemeColor(l,-.25);o.lastColumnStyle.color=this._getThemeColor(l,-.25);o.headerRowStyle.color=this._getThemeColor(l,-.25);o.totalRowStyle.color=this._getThemeColor(l,-.25)}else{o.wholeTableStyle.color=this._getThemeColor(1);o.firstColumnStyle.color=this._getThemeColor(1);o.lastColumnStyle.color=this._getThemeColor(1);o.headerRowStyle.color=this._getThemeColor(1);o.totalRowStyle.color=this._getThemeColor(1)}o.firstBandedRowStyle={backgroundColor:this._getThemeColor(l,.8)};o.firstBandedColumnStyle={backgroundColor:this._getThemeColor(l,.8)}}if(!i){o.wholeTableStyle.borderLeftColor=this._getThemeColor(l);o.wholeTableStyle.borderLeftStyle="solid";o.wholeTableStyle.borderLeftWidth="1px";o.wholeTableStyle.borderRightColor=this._getThemeColor(l);o.wholeTableStyle.borderRightStyle="solid";o.wholeTableStyle.borderRightWidth="1px";o.wholeTableStyle.borderHorizontalColor=this._getThemeColor(l);o.wholeTableStyle.borderHorizontalStyle="solid";o.wholeTableStyle.borderHorizontalWidth="1px";o.wholeTableStyle.borderVerticalColor=this._getThemeColor(l);o.wholeTableStyle.borderVerticalStyle="solid";o.wholeTableStyle.borderVerticalWidth="1px"}return o}_generateTableLightStyle2(e,t){var i=new TableStyle(t,!0),o=0===e?1:e+3;i.wholeTableStyle={borderTopColor:this._getThemeColor(o),borderTopStyle:"solid",borderTopWidth:"1px",borderBottomColor:this._getThemeColor(o),borderBottomStyle:"solid",borderBottomWidth:"1px",borderLeftColor:this._getThemeColor(o),borderLeftStyle:"solid",borderLeftWidth:"1px",borderRightColor:this._getThemeColor(o),borderRightStyle:"solid",borderRightWidth:"1px",color:this._getThemeColor(1)};i.firstBandedRowStyle={borderTopColor:this._getThemeColor(o),borderTopStyle:"solid",borderTopWidth:"1px"};i.secondBandedRowStyle={borderTopColor:this._getThemeColor(o),borderTopStyle:"solid",borderTopWidth:"1px"};i.firstBandedColumnStyle={borderLeftColor:this._getThemeColor(o),borderLeftStyle:"solid",borderLeftWidth:"1px"};i.secondBandedColumnStyle={borderLeftColor:this._getThemeColor(o),borderLeftStyle:"solid",borderLeftWidth:"1px"};i.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.headerRowStyle={backgroundColor:this._getThemeColor(o),fontWeight:"bold",color:this._getThemeColor(0)};i.totalRowStyle={borderTopColor:this._getThemeColor(o),borderTopStyle:"double",borderTopWidth:"3px",fontWeight:"bold",color:this._getThemeColor(1)};return i}_generateTableMediumStyle1(e,t){var i=new TableStyle(t,!0),o=0===e?1:e+3;i.wholeTableStyle={borderTopStyle:"solid",borderTopWidth:"1px",borderBottomStyle:"solid",borderBottomWidth:"1px",borderLeftStyle:"solid",borderLeftWidth:"1px",borderRightStyle:"solid",borderRightWidth:"1px",borderHorizontalStyle:"solid",borderHorizontalWidth:"1px",color:this._getThemeColor(1)};if(0===e){i.wholeTableStyle.borderTopColor=this._getThemeColor(o);i.wholeTableStyle.borderBottomColor=this._getThemeColor(o);i.wholeTableStyle.borderLeftColor=this._getThemeColor(o);i.wholeTableStyle.borderRightColor=this._getThemeColor(o);i.wholeTableStyle.borderHorizontalColor=this._getThemeColor(o);i.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.15)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.15)}}else{i.wholeTableStyle.borderTopColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderBottomColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderLeftColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderRightColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderHorizontalColor=this._getThemeColor(o,.4);i.firstBandedRowStyle={backgroundColor:this._getThemeColor(o,.8)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(o,.8)}}i.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.headerRowStyle={backgroundColor:this._getThemeColor(o),fontWeight:"bold",color:this._getThemeColor(0)};i.totalRowStyle={borderTopColor:this._getThemeColor(o),borderTopStyle:"double",borderTopWidth:"3px",fontWeight:"bold",color:this._getThemeColor(1)};return i}_generateTableMediumStyle2(e,t){var i=new TableStyle(t,!0),o=0===e?1:e+3;i.wholeTableStyle={borderVerticalStyle:"solid",borderVerticalWidth:"1px",borderVerticalColor:this._getThemeColor(0),borderHorizontalStyle:"solid",borderHorizontalWidth:"1px",borderHorizontalColor:this._getThemeColor(0),color:this._getThemeColor(1)};if(0===e){i.wholeTableStyle.backgroundColor=this._getThemeColor(0,-.15);i.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.35)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.35)}}else{i.wholeTableStyle.backgroundColor=this._getThemeColor(o,.8);i.firstBandedRowStyle={backgroundColor:this._getThemeColor(o,.6)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(o,.6)}}i.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(o)};i.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(o)};i.headerRowStyle={borderBottomColor:this._getThemeColor(0),borderBottomStyle:"solid",borderBottomWidth:"3px",backgroundColor:this._getThemeColor(o),fontWeight:"bold",color:this._getThemeColor(0)};i.totalRowStyle={borderTopColor:this._getThemeColor(0),borderTopStyle:"solid",borderTopWidth:"3px",backgroundColor:this._getThemeColor(o),fontWeight:"bold",color:this._getThemeColor(0)};return i}_generateTableMediumStyle3(e,t){var i=new TableStyle(t,!0),o=0===e?1:e+3;i.wholeTableStyle={borderTopStyle:"solid",borderTopWidth:"2px",borderTopColor:this._getThemeColor(1),borderBottomStyle:"solid",borderBottomWidth:"2px",borderBottomColor:this._getThemeColor(1),color:this._getThemeColor(1)};if(0===e){i.wholeTableStyle.borderLeftColor=this._getThemeColor(1);i.wholeTableStyle.borderLeftStyle="solid";i.wholeTableStyle.borderLeftWidth="1px";i.wholeTableStyle.borderRightColor=this._getThemeColor(1);i.wholeTableStyle.borderRightStyle="solid";i.wholeTableStyle.borderRightWidth="1px";i.wholeTableStyle.borderVerticalColor=this._getThemeColor(1);i.wholeTableStyle.borderVerticalStyle="solid";i.wholeTableStyle.borderVerticalWidth="1px";i.wholeTableStyle.borderHorizontalColor=this._getThemeColor(1);i.wholeTableStyle.borderHorizontalStyle="solid";i.wholeTableStyle.borderHorizontalWidth="1px"}i.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.35)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.35)};i.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(o)};i.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(o)};i.headerRowStyle={borderBottomColor:this._getThemeColor(1),borderBottomStyle:"solid",borderBottomWidth:"2px",backgroundColor:this._getThemeColor(o),fontWeight:"bold",color:this._getThemeColor(0)};i.totalRowStyle={borderTopColor:this._getThemeColor(1),borderTopStyle:"double",borderTopWidth:"3px"};return i}_generateTableMediumStyle4(e,t){var i=new TableStyle(t,!0),o=0===e?1:e+3;i.wholeTableStyle={borderTopStyle:"solid",borderTopWidth:"1px",borderBottomStyle:"solid",borderBottomWidth:"1px",borderLeftStyle:"solid",borderLeftWidth:"1px",borderRightStyle:"solid",borderRightWidth:"1px",borderVerticalStyle:"solid",borderVerticalWidth:"1px",borderHorizontalStyle:"solid",borderHorizontalWidth:"1px",color:this._getThemeColor(1)};if(0===e){i.wholeTableStyle.borderTopColor=this._getThemeColor(o);i.wholeTableStyle.borderBottomColor=this._getThemeColor(o);i.wholeTableStyle.borderLeftColor=this._getThemeColor(o);i.wholeTableStyle.borderRightColor=this._getThemeColor(o);i.wholeTableStyle.borderVerticalColor=this._getThemeColor(o);i.wholeTableStyle.borderHorizontalColor=this._getThemeColor(o);i.wholeTableStyle.backgroundColor=this._getThemeColor(0,-.15);i.firstBandedRowStyle={backgroundColor:this._getThemeColor(0,-.35)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(0,-.35)}}else{i.wholeTableStyle.borderTopColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderBottomColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderLeftColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderRightColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderVerticalColor=this._getThemeColor(o,.4);i.wholeTableStyle.borderHorizontalColor=this._getThemeColor(o,.4);i.wholeTableStyle.backgroundColor=this._getThemeColor(o,.8);i.firstBandedRowStyle={backgroundColor:this._getThemeColor(o,.6)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(o,.6)}}i.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.headerRowStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.totalRowStyle={borderTopColor:this._getThemeColor(o),borderTopStyle:"solid",borderTopWidth:"2px",fontWeight:"bold",color:this._getThemeColor(1)};return i}_generateTableDarkStyle1(e,t){var i=new TableStyle(t,!0),o=0===e?1:e+3,l=0===e?.25:-.25;i.wholeTableStyle={color:this._getThemeColor(0)};i.firstBandedRowStyle={backgroundColor:this._getThemeColor(o,l)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(o,l)};i.firstColumnStyle={borderRightColor:this._getThemeColor(0),borderRightStyle:"solid",borderRightWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(o,l)};i.lastColumnStyle={borderLeftColor:this._getThemeColor(0),borderLeftStyle:"solid",borderLeftWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(o,l)};i.headerRowStyle={borderBottomColor:this._getThemeColor(0),borderBottomStyle:"solid",borderBottomWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0),backgroundColor:this._getThemeColor(1)};i.totalRowStyle={borderTopColor:this._getThemeColor(0),borderTopStyle:"solid",borderTopWidth:"2px",fontWeight:"bold",color:this._getThemeColor(0)};if(0===e){i.wholeTableStyle.backgroundColor=this._getThemeColor(o,.5);i.totalRowStyle.backgroundColor=this._getThemeColor(o,.15)}else{i.wholeTableStyle.backgroundColor=this._getThemeColor(o);i.totalRowStyle.backgroundColor=this._getThemeColor(o,-.5)}return i}_generateTableDarkStyle2(e,t){var i=new TableStyle(t,!0),o=0===e?0:2*e+2,l=0===e?1:2*e+3,s=0===e?-.15:.8;i.wholeTableStyle={backgroundColor:this._getThemeColor(o,s)};i.firstBandedRowStyle={backgroundColor:this._getThemeColor(o,s-.2)};i.firstBandedColumnStyle={backgroundColor:this._getThemeColor(o,s-.2)};i.firstColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.lastColumnStyle={fontWeight:"bold",color:this._getThemeColor(1)};i.headerRowStyle={color:this._getThemeColor(0),backgroundColor:this._getThemeColor(l)};i.totalRowStyle={borderTopColor:this._getThemeColor(1),borderTopStyle:"double",borderTopWidth:"3px",fontWeight:"bold",color:this._getThemeColor(1)};return i}static _getHeaderRowText(e){let t=e.binding,i=e._hdr;null!=i&&""!=i.trim()||(i=toHeaderCase(t||""));return i}static _toOADate(e){let t,i=new Date(1900,0,0),o=Date.UTC(1900,0,0),l=i.getTime()-o-6e4*i.getTimezoneOffset(),s=6e4*(e.getTimezoneOffset()-i.getTimezoneOffset());t=(e.getTime()-i.getTime()-(0!==s?s-l:0))/864e5;return t+=t>59?1:0}static _fromOADate(e){let t,i,o,l=new Date(1900,0,0),s=Date.UTC(1900,0,0),n=l.getTime()-s-6e4*l.getTimezoneOffset();i=e>59?1:0;return 0!==(t=6e4*((o=new Date(l.getTime()+864e5*(e-i))).getTimezoneOffset()-l.getTimezoneOffset()))?new Date(l.getTime()+t-n+864e5*(e-i)):o}setHeights(e){this._heights=e}updateRowHeights(){if(this.collectionView)for(let e=0;e<this._heights.length;e++)this._heights[e]&&this.rows[e]&&(this.rows[e].height=this._heights[e])}}FlexSheet.controlTemplate='<div style="width:100%;height:100%"><div wj-part="container" style="width:100%; max-width: 100vw;">'+FlexGrid.controlTemplate+'</div><div wj-part="tab-holder" class="wj-tabholder" style="width:100%; min-width:100px"></div><div wj-part="context-menu" style="display:none;z-index:100"></div></div>';export class DraggingRowColumnEventArgs extends EventArgs{constructor(e,t,i){super();this._draggingRange=e;this._isDraggingRows=t;this._isShiftKey=i}get draggingRange(){return this._draggingRange}get isDraggingRows(){return this._isDraggingRows}get isShiftKey(){return this._isShiftKey}}export class DroppingRowColumnEventArgs extends CancelEventArgs{constructor(e,t){super();this._droppingRange=e;this._isDroppingRows=t}get droppingRange(){return this._droppingRange}get isDroppingRows(){return this._isDroppingRows}}export class UnknownFunctionEventArgs extends EventArgs{constructor(e,t){super();this._funcName=e;this._params=t}get funcName(){return this._funcName}get params(){return this._params}}export class RowColumnChangedEventArgs extends EventArgs{constructor(e,t,i,o){super();if(isArray(e)){this._ranges=e;this._added=t;if(1===e.length){let t=e[0];if(i){this._index=t.leftCol;this._count=t.columnSpan}else{this._index=t.topRow;this._count=t.rowSpan}}else{this._index=-1;this._count=-1}}else{this._index=e;this._count=t;this._added=i;this._ranges=o?[new CellRange(-1,this._index,-1,this._index+this._count-1)]:[new CellRange(this._index,-1,this._index+this._count-1,-1)]}}get ranges(){return this._ranges}get index(){return this._index}get count(){return this._count}get added(){return this._added}get isAdd(){_deprecated("RowColumnChangedEventArgs.isAdd","RowColumnChangedEventArgs.added");return this._added}}export class AutoFillingEventArgs extends CancelEventArgs{constructor(e,t){super();this._range=e;this._op=t}get range(){return this._range}get operation(){return this._op}}export class AutoFilledEventArgs extends EventArgs{constructor(e,t){super();this._range=e;this._op=t}get range(){return this._range}get operation(){return this._op}}export class FlexSheetPanel extends GridPanel{constructor(e,t,i,o,l){super(e,t,i,o,l);this._drkColors={}}getSelectedState(e,t,i){if(!this.grid)return;let o=this.grid.selectedSheet,l=o?o.selectionRanges:null,s=l?l.length:0,n=super.getSelectedState(e,t,i);if(n===SelectedState.None&&s>0){let i=this.grid.getMergedRange(this,e,t),o=this.columns.length-1,n=this.rows.length-1;for(let r=0;r<l.length;r++){let a=l[r];if(a&&a instanceof CellRange){if(this.cellType===CellType.Cell){if(i){if(i.contains(a.row,a.col))return r!==s-1||this.grid._isClicking?SelectedState.Selected:this.grid.showMarquee?SelectedState.None:SelectedState.Cursor;if(i.intersects(a))return SelectedState.Selected}if(a.row===e&&a.col===t)return r!==s-1||this.grid._isClicking?SelectedState.Selected:this.grid.showMarquee?SelectedState.None:SelectedState.Cursor;if(a.contains(e,t))return SelectedState.Selected}if(this.cellType===CellType.RowHeader&&this.grid.showSelectedHeaders&HeadersVisibility.Row&&t===o&&a.containsRow(e))return SelectedState.Selected;if(this.cellType===CellType.ColumnHeader&&this.grid.showSelectedHeaders&HeadersVisibility.Column&&e===n&&a.containsColumn(t))return SelectedState.Selected}}}return n}getCellData(e,t,i){if(isString(t)&&(t=this.columns.indexOf(t))<0)throw"Invalid column name or binding.";if(e>=this.rows.length||asNumber(t,!1,!0)>=this.columns.length)return null;if(this.cellType===CellType.RowHeader)return e+1+"";let o=this.columns[asNumber(t,!1,!0)],l=this.grid?this.grid._getBindingColumn(this,e,o):o,s=this.grid;if(this.cellType===CellType.ColumnHeader){let s=this.rows[e];if(s&&s._ubv&&null!=s._ubv[o._hash])return super.getCellData(e,t,i);let n=l.header;return null==l._hdr||l._hdr==l._orgHdr||n===l.binding||n===toHeaderCase(l.binding)?FlexSheet.convertNumberToAlpha(t):n}if(i&&(!l||!l.dataMap)){if(_isEditingCell(this.grid,e,t)){let i=super.getCellData(e,t,!1);return Globalize.format(i,null)}{let i=s&&s._getCellStyle(e,t);if(i&&i.format){let o=super.getCellData(e,t,!1);if(isDate(o)||isNumber(o))return Globalize.format(o,i.format)}}}return super.getCellData(e,t,i)}setCellData(e,t,i,o=!0,l=!0,s=!1){if(e>=this.rows.length||t>=this.columns.length)return!1;let n,r=this.grid,a=r?r._getBindingColumn(this,e,this.columns[t]):this.columns[t],h=this.rows[e];if(i instanceof _ValWithFormat){n=i.format;i=i.value}r&&r._isPasting&&(o=!0);let d=isString(i);if(r&&r.selectedSheet){let o=r.selectedSheet.findTable(e,t);if(o&&o._isHeaderRow(e)){if(null==i||d&&isNullOrWhiteSpace(i)&&!a.dataMap)return;if(!(h instanceof HeaderRow)){i=a.dataType===DataType.Boolean&&isBoolean(i)?i:i.toString();o._attached&&r._updateFormulasTableColumn(o,t,this.getCellData(e,t,!1)+"",i+"");return super.setCellData(e,t,i,!1,l,s)}h._ubv[a._hash]=i.toString()}}let u=d&&"'"===i[0],c=d&&_isFormula(i);if(o&&i&&a.dataType!==DataType.String&&d&&!u&&!c){let l=culture.Globalize;if(this.getCellData(e,t,!0)===i)return!0;let s=r?r._getCellStyle(e,t):null,h=n||s&&s.format||a.format,d=null;h&&/[yYMhsmt\:-]/.test(h)&&!/[pc]/.test(h)&&(d=Globalize.parseDate(i,h));null==d&&i.indexOf(l.calendar["/"])>=0&&(d=Globalize.parseDate(i,null));if(d)i=d;else{let s=!1,n=!1;if(isNullOrWhiteSpace(i)||!(n="%"===i[i.length-1])&&!(s=i.indexOf(l.numberFormat.currency.symbol)>=0)&&/[^-\d,\.]/.test(i))a.dataType===DataType.Boolean&&(i=changeType(i,DataType.Boolean,null));else{let l=changeType(i,DataType.Number,"");if(isNumber(l)){i=l;h||a.dataType&&a.dataType!==DataType.Number||(s?r.applyCellsStyle({format:"C"+(isInt(i)?"0":"")},[new CellRange(e,t)]):n&&r.applyCellsStyle({format:"P"+(isInt(100*i)?"0":"")},[new CellRange(e,t)]))}else o=!1}}}(c||u||!a.dataType&&i)&&(o=!1);if(""===i&&o&&a.dataType!==DataType.String&&!a.dataMap&&!h.dataMap){i=null;o=!1}if(!(h instanceof HeaderRow))return super.setCellData(e,t,i,o,l,s);h._ubv[a._hash]=i}_renderCell(e,t,i,o,l,s){let n=t*this.grid.columns.length+i,r=this.grid.getMergedRange(this,t,i),a=super._renderCell(e,t,i,o,l,s);if(this.cellType!==CellType.Cell)return a;if(r&&n>r.topRow*this.grid.columns.length+r.leftCol)return a;if(this.columns[i].renderSize<=0&&(!r||r.getRenderSize(this).width<=0))return a;let h=e.childNodes[s];if(h){let e=this.grid.selectedSheet;if(e&&!_isEditingCell(this.grid,t,i)){let o=e.findTable(t,i);o&&o._updateCell(t,i,h)}let o,l=e?e._styledCells[n]:null;if(hasClass(h,"wj-state-selected")||(o=hasClass(h,"wj-state-multi-selected"))){l&&l.backgroundColor&&(h.style.backgroundColor="");l&&l.color&&(h.style.color="");o&&l&&l.backgroundColor&&(h.style.backgroundColor=this._darker(l.backgroundColor))}else if(l){""!==l.backgroundColor&&(h.style.backgroundColor=l.backgroundColor);""!==l.color&&(h.style.color=l.color)}}return a}_darker(e){let t=this._drkColors[e];if(!t){let i=new Color(e).getHsl();this._drkColors[e]=t=Color.fromHsl(i[0],i[1],.75*i[2]).toString()}return t}}export class HeaderRow extends Row{constructor(){super();this.isReadOnly=!0}}export function _isFormula(e){return e&&"string"==typeof e&&e.length>1&&"="===e[0]&&"="!==e[1]}export function _isEditingCell(e,t,i){let o=e.editRange;return o&&o.contains(t,i)}function _isExclusiveNumericFormat(e){if(e){var t=e.match(/^[cdefgnprx](\d?)/i);if(t){let e=t[0][0].toLowerCase();return"d"!==e&&"e"!==e&&"f"!==e&&"g"!==e||!!t[1]}}return!1}export var AutoFillOperation;!function(e){e[e.CopyFormat=1]="CopyFormat";e[e.CopyContent=2]="CopyContent";e[e.FillSeries=4]="FillSeries"}(AutoFillOperation||(AutoFillOperation={}));class _RangesHelper{static validateRowRanges(e,t){return this._validateCellRanges(e,t,"topRow","bottomRow","row2")}static excludeRow(e,t){if(e&&e.length)for(let i=0;i<e.length;i++){let o=e[i];if(o.containsRow(t))if(1===o.rowSpan){e.splice(i);i--}else if(o.topRow===t)o.setRange(o.topRow+1,o.col,o.bottomRow,o.col2);else if(o.bottomRow===t)o.setRange(o.topRow,o.col,o.bottomRow-1,o.col2);else{e.splice(i,1,new CellRange(o.topRow,o.col,t-1,o.col2),new CellRange(t+1,o.col,o.bottomRow,o.col2));i++}}}static validateColumnRanges(e,t){return this._validateCellRanges(e,t,"leftCol","rightCol","col2")}static _validateCellRanges(e,t,i,o,l){let s=(e=e.filter(e=>e&&e[i]>=0&&e[o]>=0&&e[i]<t&&e[o]<t)).length;if(s>1){let t=[];for(let n=(e=e.sort((e,t)=>t[i]>=e[i]&&t[o]<=e[o]?-1:e[i]-t[i]))[0].clone(),r=1;r<s;r++){let a=e[r];if(a[i]>=n[i]&&a[o]<=n[o]);else if(a[i]<=n[o]+1)n[l]=a[o];else{t.push(n);n=a.clone()}r===s-1&&t.push(n)}e=t}return e}}class _ValWithFormat{constructor(e,t){this.value=e;this.format=t}}export class UndoStack{constructor(e){this.MAX_STACK_SIZE=500;this._stack=[];this._pointer=-1;this._resizingTriggered=!1;this.undoStackChanged=new Event;let t=this;t._owner=e;t._owner.prepareCellForEdit.addHandler(t._initCellEditAction,t);t._owner.cellEditEnded.addHandler((e,i)=>{t._pendingAction&&(!i.data||46!==i.data.keyCode&&8!==i.data.keyCode)&&t._pendingAction instanceof _EditAction&&!t._pendingAction.isPaste&&t._afterProcessCellEditAction(t)},t);t._owner.pasting.addHandler(t._initCellEditActionForPasting,t);t._owner.pastingCell.addHandler((e,i)=>{t._pendingAction&&(t._pendingAction instanceof _EditAction?t._pendingAction.updateForPasting(i.range):t._pendingAction instanceof _CutAction&&t._pendingAction.updateForPasting(i.range))},t);t._owner.pasted.addHandler(()=>{if(t._pendingAction)if(t._pendingAction instanceof _EditAction&&t._pendingAction.isPaste)t._afterProcessCellEditAction(t);else if(t._pendingAction instanceof _CutAction){t._pendingAction.saveNewState();t._addAction(t._pendingAction);t._pendingAction=null}},t);t._owner.resizingColumn.addHandler((e,i)=>{if(0!==t.stackSize&&t._owner.selectedSheet&&!t._resizingTriggered){t._pendingAction=new _ColumnResizeAction(t._owner,i.panel,i.col);t._resizingTriggered=!0}},t);t._owner.resizedColumn.addHandler((e,i)=>{t._pendingAction instanceof _ColumnResizeAction&&t._pendingAction.saveNewState()&&t._addAction(t._pendingAction);t._pendingAction=null;t._resizingTriggered=!1},t);t._owner.resizingRow.addHandler((e,i)=>{if(0!==t.stackSize&&t._owner.selectedSheet&&!t._resizingTriggered){t._pendingAction=new _RowResizeAction(t._owner,i.panel,i.row);t._resizingTriggered=!0}},t);t._owner.resizedRow.addHandler((e,i)=>{t._pendingAction instanceof _RowResizeAction&&t._pendingAction.saveNewState()&&t._addAction(t._pendingAction);t._pendingAction=null;t._resizingTriggered=!1},t);t._owner.draggingRowColumn.addHandler((e,i)=>{0!==t.stackSize&&t._owner.selectedSheet&&i.isShiftKey&&(i.isDraggingRows?t._pendingAction=new _RowsChangedAction(t._owner):t._pendingAction=new _ColumnsChangedAction(t._owner))},t);t._owner.endDroppingRowColumn.addHandler((e,i)=>{!i.cancel&&t._pendingAction&&t._pendingAction.saveNewState()&&t._addAction(t._pendingAction);t._pendingAction=null},t);t._owner.sheets.collectionChanged.addHandler((e,t)=>{if(t.action===NotifyCollectionChangedAction.Remove){for(let e=0;e<this._stack.length;e++)if(this._stack[e].sheetUid===t.item._uid){this._stack.splice(e,1);e--}this._pointer=Math.min(this._pointer,this._stack.length-1)}});t._owner.sheets.sheetCleared.addHandler(()=>this.clear())}get stackSize(){return null==this._stackSize?this.MAX_STACK_SIZE:this._stackSize}set stackSize(e){isNumber(e)&&(e<0?this._stackSize=0:e>this.MAX_STACK_SIZE?this._stackSize=this.MAX_STACK_SIZE:this._stackSize=Math.floor(e))}get canUndo(){return this._pointer>-1&&this._pointer<this._stack.length}get canRedo(){return this._pointer+1>-1&&this._pointer+1<this._stack.length}onUndoStackChanged(e){this.undoStackChanged.raise(this,e)}undo(){if(this.canUndo){let e=this._stack[this._pointer];this._beforeUndoRedo(e);e.undo();this._pointer--;this.onUndoStackChanged()}}redo(){if(this.canRedo){this._pointer++;let e=this._stack[this._pointer];this._beforeUndoRedo(e);e.redo();this.onUndoStackChanged()}}clear(){this._stack.length=0;this._pointer=-1}_addAction(e){this._stack.length>0&&this._stack.length>this._pointer+1&&this._stack.splice(this._pointer+1,this._stack.length-this._pointer-1);this._stack.length>=this.stackSize&&this._stack.splice(0,this._stack.length-this.stackSize+1);this._pointer=this._stack.length;this._stack.push(e);this.onUndoStackChanged()}_pop(){let e;if(this._pointer<0)return null;e=this._stack[this._pointer];this._pointer--;return e}_initCellEditAction(e,t){0!==this.stackSize&&this._owner.selectedSheet&&(this._pendingAction=new _EditAction(this._owner,t.range))}_initCellEditActionForPasting(){if(0!==this.stackSize&&this._owner.selectedSheet)if(this._owner._isCutting)this._pendingAction=new _CutAction(this._owner);else{this._pendingAction=new _EditAction(this._owner);this._pendingAction.markIsPaste()}}_afterProcessCellEditAction(e){if(e._pendingAction){e._pendingAction instanceof _EditAction&&e._pendingAction.saveNewState()&&e._addAction(this._pendingAction);e._pendingAction=null}}_beforeUndoRedo(e){let t=this._owner.sheets;for(let i=0;i<t.length;i++)if(t[i]._uid===e.sheetUid){this._owner.selectedSheetIndex=i;break}}}export class FlexSheetValueFilterEditor extends ValueFilterEditor{updateEditor(){var e=this.filter.column,t=e.grid;if(this.filter.uniqueValues||null!=t.itemsSource&&null!=t.childItemsPath){super.updateEditor();return}var i=t.filter._getValueFilters(e),o=this.filter.showValues;if(o&&0!=Object.keys(o).length){for(var l in o)for(s=0;s<i.length;s++)if(o[l]&&""!==i[s].cellRef&&i[s].cellRef===o[l].cellRef){o[i[s].text]={show:!0,cellRef:i[s].cellRef};i[s].show=!0;i[s].text!=l&&delete o[l]}else if(i[s].text==l){i[s].show=!0;break}}else for(var s=0;s<i.length;s++)i[s].show=!0;this._lbValues.isContentHtml=e.isContentHtml;this._cmbFilter.text=this.filter.filterText;let n=this._filterText=this._cmbFilter.text.toLowerCase();this._rxFilter=n?new RegExp(escapeRegExp(n),this._getCaseSensitive()?"":"i"):null;this._view.pageSize=this.filter.maxValues;this._view.sourceCollection=i;setTimeout(()=>{this._adjustWidths()},0)}updateFilter(){var e=null,t=this._getItems();if(this._filterText||this._cbSelectAll.indeterminate){e={};for(var i=0;i<t.length;i++){var o=t[i];o.show&&(e[o.text]={show:!0,cellRef:o.cellRef})}}this._filter.showValues=e;this._filter.filterText=this._filterText}}export class FlexSheetConditionFilter extends ConditionFilter{constructor(e){super(e)}apply(e){var t,i,o,l,s=this.column,n=s.grid,r=this.condition1,a=this.condition2;if(!(n instanceof FlexSheet))return!0;if(!this.isActive)return!0;if(n.rows[e]instanceof _NewRowTemplate)return!0;""===(t=n.getCellValue(e,s.index))&&s.dataType!==DataType.String&&(t=null);i=o=t;if(l=this.dataMap||s.dataMap)i=o=t=l.getDisplayValue(t);else if(isDate(t))(isString(r.value)||isString(a.value))&&(i=o=t=n.getCellValue(e,s.index,!0));else if(isNumber(t)){i=o=t=Globalize.parseFloat(n.getCellValue(e,s.index,!0));if(0===t&&!s.dataType){r.isActive&&""===r.value&&(i=t.toString());a.isActive&&""===a.value&&(o=o.toString())}}else if(null==t){r.isActive&&isNumber(r.value)&&(i=NaN);a.isActive&&isNumber(a.value)&&(o=NaN)}var h=r.apply(i),d=a.apply(o);return r.isActive&&a.isActive?this.and?h&&d:h||d:r.isActive?h:!a.isActive||d}}export class FlexSheetValueFilter extends ValueFilter{constructor(e){super(e)}apply(e){var t,i=this.column.grid;if(!(i instanceof FlexSheet))return!0;if(!this.showValues||!Object.keys(this.showValues).length)return!0;if(i.rows[e]instanceof _NewRowTemplate)return!0;e=(t=this.dataMap||this.column.dataMap)?t.getDisplayValue(i.getCellValue(e,this.column.index)):i.getCellValue(e,this.column.index,!0);return null!=this.showValues[e]}}export class FlexSheetColumnFilter extends ColumnFilter{constructor(e,t){super(e,t);this._valueFilter=new FlexSheetValueFilter(t);this._valueFilter.exclusiveValueSearch=e.exclusiveValueSearch;this._conditionFilter=new FlexSheetConditionFilter(t)}}export class FlexSheetColumnFilterEditor extends ColumnFilterEditor{constructor(e,t,i=!0){super(e,t,i);var o=this;i&&(this._divSort.style.display="");this._btnSortAsc=this.cloneElement(this._btnAsc);this._btnSortDsc=this.cloneElement(this._btnDsc);this._btnAsc.parentNode.replaceChild(this._btnSortAsc,this._btnAsc);this._btnDsc.parentNode.replaceChild(this._btnSortDsc,this._btnDsc);this._btnSortAsc.addEventListener("click",e=>{o._sortBtnClick(e,!0)});this._btnSortDsc.addEventListener("click",e=>{o._sortBtnClick(e,!1)});this._updateSortButtonStateUnbound()}_showFilter(e){if(e==FilterType.Value&&null==this._edtVal){this._edtVal=new FlexSheetValueFilterEditor(this._divEdtVal,this.filter.valueFilter);this._edtVal.canApplyChanged.addHandler(e=>{enable(this._btnApply,this._edtVal.canApply)})}super._showFilter(e)}_sortBtnClick(e,t){var i,o,l=this.filter.column,s=l.grid.sortManager;e.preventDefault();e.stopPropagation();if((i=s.checkSortItemExists(l.index))>-1){s.sortDescriptions.moveCurrentToPosition(i);s.sortDescriptions.currentItem.ascending=t;o=-i}else{s.addSortLevel(l.index,t);o=-(s.sortDescriptions.items.length-1)}s.moveSortLevel(o);s.commitSort();this.onButtonClicked()}cloneElement(e){for(var t=e.cloneNode();e.firstChild;)t.appendChild(e.lastChild);return t}_updateSortButtonStateUnbound(){let e=this.filter.column;if(e&&e.grid&&e.grid.selectedSheet){let t=e.grid.selectedSheet._unboundSortDesc;for(let i=0;i<t.length;i++)if(t[i].column===e){toggleClass(this._btnSortAsc,"wj-state-active",!0===t[i].ascending);toggleClass(this._btnSortDsc,"wj-state-active",!1===t[i].ascending);break}}}}export class FlexSheetFilter extends FlexGridFilter{get filterDefinition(){for(var e={filters:[]},t=0;t<this._filters.length;t++){var i=this._filters[t];if(i&&i.column&&this.grid.columns.indexOf(i.column)>-1)if(i.conditionFilter.isActive){var o=i.conditionFilter;e.filters.push({columnIndex:i.column.index,type:"condition",condition1:{operator:o.condition1.operator,value:o.condition1.value},and:o.and,condition2:{operator:o.condition2.operator,value:o.condition2.value}})}else if(i.valueFilter.isActive){var l=i.valueFilter;e.filters.push({columnIndex:i.column.index,type:"value",filterText:l.filterText,showValues:l.showValues})}}return JSON.stringify(e)}set filterDefinition(e){var t=JSON.parse(asString(e));this.clear();for(var i=0;i<t.filters.length;i++){var o=t.filters[i],l=this.grid.columns[o.columnIndex],s=this.getColumnFilter(l,!0);if(s)switch(o.type){case"condition":var n=s.conditionFilter;n.condition1.value=l.dataType==DataType.Date?changeType(o.condition1.value,l.dataType,null):o.condition1.value;n.condition1.operator=o.condition1.operator;n.and=o.and;n.condition2.value=l.dataType==DataType.Date?changeType(o.condition2.value,l.dataType,null):o.condition2.value;n.condition2.operator=o.condition2.operator;break;case"value":var r=s.valueFilter;r.filterText=o.filterText;r.showValues=o.showValues}}this.apply()}apply(){var e=this;e.grid.deferUpdate(()=>{for(var t,i,o,l=-1,s=0;s<e.grid.rows.length;s++)if(!((t=e.grid.rows[s])instanceof HeaderRow||s<=l)){l=-1;i=e._filter(s);if(t instanceof GroupRow){o=t.getCellRange();if(null==t.dataItem||t.dataItem instanceof CollectionViewGroup)t.visible=e._checkGroupVisible(o);else{t.visible=i;l=o.bottomRow;if(o.isValid)for(var n=o.topRow;n<=o.bottomRow;n++)e.grid.rows[n].visible=i}}else t.visible=i}e.grid._isCopying||e.grid._isUndoing||e.grid._isSorting||e.onFilterApplied()})}editColumnFilter(e,t){var i=this,o=i.grid;i.closeEditor();e=i._asColumn(e);var l=document.createElement("div"),s=i.getColumnFilter(e),n=new FlexSheetColumnFilterEditor(l,s,i.showSortButtons);addClass(l,"wj-dropdown-panel");i._divEdt=l;i._edtCol=e;var r=new CellRangeEventArgs(o.cells,new CellRange(-1,e.index));i.onFilterChanging(r);if(r.cancel){i._divEdt=null;i._edtCol=null;return}r.cancel=!0;o.undoStack.stackSize>0&&(i._undoAcion=new _FilteringAction(o));o.rightToLeft&&(l.dir="rtl");n.filterChanged.addHandler(()=>{r.cancel=!1;i._filterChanged=!0;setTimeout(()=>{if(!r.cancel){i.apply();if(i._undoAcion){i._undoAcion.saveNewState();o.undoStack._addAction(i._undoAcion);i._undoAcion=null}}})});n.buttonClicked.addHandler(()=>{i.closeEditor();o.focus();i.onFilterChanged(r)});n.lostFocus.addHandler(()=>{setTimeout(()=>{var e=Control.getControl(i._divEdt);e&&!e.containsFocus()&&i.closeEditor()},10)});o._edtHdl._commitRowEdits();o.scrollIntoView(-1,e.index,!0);var a=i.grid.columnHeaders,h=t?t.row:a.rows.length-1,d=t?t.col:e.index,u=a.getCellBoundingRect(h,d),c=document.elementFromPoint(u.left+u.width/2,u.top+u.height/2);(c=closest(c,".wj-cell"))?showPopup(l,c,!1,!1,!1):showPopup(l,u);i._setAriaExpanded(c,!0);i._setAriaExpanded(o.cells.getCellElement(-1,d),!0);let _=n.hostElement.querySelectorAll("input");for(let e=0;e<_.length;e++){let t=_[e];if(t.offsetHeight>0&&t.tabIndex>-1&&!t.disabled){t.focus();break}}n.containsFocus()||n.focus()}_updateColumnFilter(e){e=this._asColumn(e);var t=this.getColumnFilter(e,!1),i=null!=t?t.valueFilter:null;if(i&&i.isActive){var o=this._getValueFilters(e),l=i.showValues;if(o&&o.length>0){for(var s in l)for(var n=0;n<o.length;n++){if(l[s]&&isSameRow(o[n].cellRef,l[s].cellRef)){l[o[n].text]={show:!0,cellRef:o[n].cellRef};o[n].text!=s&&delete l[s];break}if(o[n].text==s){l[s].show=!0;break}}i.showValues=l}}function isSameRow(e,t){return""!=e&&""!=e&&e.split("_")[0]==t.split("_")[0]}}_getValueFilters(e){var t=this.getColumnFilter(e,!1),i=t.valueFilter,o=e.grid,l=e.index,s=[],n={},r=i.showValues,a=t.conditionFilter,h=a.condition1.operator,d=a.condition2.operator;if(i.uniqueValues||null!=o.itemsSource&&null!=o.childItemsPath)s=i.getUniqueValues(!0);else for(var u=0;u<o.rows.length;u++){let e=o.rows[u];if(e instanceof HeaderRow||e instanceof GroupRow||e instanceof _NewRowTemplate)continue;i.showValues=null;a.condition1.operator=null;a.condition2.operator=null;let t=o.filter._filter(u);i.showValues=r;a.condition1.operator=h;a.condition2.operator=d;if(!e.visible&&!t)continue;if(!e.visible&&i.apply(u)&&a.apply(u))continue;let c=u,_=l,g=o.getMergedRange(o.cells,c,_);if(g){if(g.leftCol!==l)continue;c=g.topRow;_=g.leftCol}let f,w=o.getCellValue(c,_);f=i.dataMap?i.dataMap.getDisplayValue(w):o.getCellValue(c,_,!0);w=""===w?null:w;let m,p=o.getCellData(c,_,!0);if(!n[f]){n[f]=!0;m=p&&"="===p[0]?u+"_"+l:"";s.push({value:w,text:f,cellRef:m})}}return s}closeEditor(){this._undoAcion&&!this._filterChanged&&(this._undoAcion=null);super.closeEditor()}getColumnFilter(e,t=!0){if(e=this._asColumn(e)){for(let t=0;t<this._filters.length;t++)if(this._filters[t].column==e)return this._filters[t];if(t){let t=new FlexSheetColumnFilter(this,e);this._filters.push(t);return t}}return null}_isActive(){return this._filters.some(e=>e.column&&(e.conditionFilter.isActive||e.valueFilter.isActive)&&this.grid.columns.indexOf(e.column)>=0)}_isEditorOpened(){return!!this._divEdt}_checkGroupVisible(e){for(var t,i=!0,o=e.topRow+1;o<=e.bottomRow;o++)if(t=this.grid.rows[o])if(t instanceof GroupRow)i=this._checkGroupVisible(t.getCellRange());else if(i=this._filter(o))break;return i}}export class _SmartTag extends Control{constructor(e,t,i,o){super(e);this.CopyCells=AutoFillOperation.CopyFormat|AutoFillOperation.CopyContent;this.FillSeries=AutoFillOperation.CopyFormat|AutoFillOperation.FillSeries;this.FillFormat=AutoFillOperation.CopyFormat;this.FillWithoutFormat=AutoFillOperation.FillSeries;this.FullWidth=32;this.CompactWidth=18;this._uiEventHdl=this._onUIEvent.bind(this);this.operationSelected=new Event;this.cancelled=new Event;this._owner=t;this._op=i;let l=this.getTemplate();this.applyTemplate("wj-flexsheet-smart-tag",l,{_icon:"icon",_btnMenu:"btn-menu"});let s=this._getPos();setCss(this.hostElement,{left:s.x,top:s.y});this.addEventListener(this.hostElement,"mouseover",()=>{this.hostElement.style.width=this.FullWidth+"px";this._btnMenu.style.display=""});this.addEventListener(this.hostElement,"mouseleave",()=>{if(!this._menu){this.hostElement.style.width=this.CompactWidth+"px";this._btnMenu.style.display="none"}});this.addEventListener(this.hostElement,"mousedown",e=>{e.preventDefault();this._showFillOpMenu()},!0);this.addEventListener(document.body,"mousedown",this._uiEventHdl,!0);this.addEventListener(document.body,"keydown",this._uiEventHdl,!0);this.initialize(o)}dispose(){this.removeEventListener(document.body,"mousedown",this._uiEventHdl,!0);this.removeEventListener(document.body,"keydown",this._uiEventHdl,!0);super.dispose()}get operation(){return this._op}onOperationSelected(e){this.operationSelected.raise(this,e)}onCancelled(e){this.cancelled.raise(this,e)}_getPos(){let e=this._owner,t=e._root,i=e.selection,o=e.cells.getCellBoundingRect(i.bottomRow,i.rightCol,!0),l=e.cells.hostElement,s=o.right+l.offsetLeft,n=o.bottom+l.offsetTop;s+e._ptScrl.x+32+(l.offsetHeight>t.offsetHeight?17:0)>t.offsetWidth&&(s-=32);n+e._ptScrl.y+18+(l.offsetWidth>t.offsetWidth?17:0)>t.offsetHeight&&(n-=18);return new Point(s,n)}_showFillOpMenu(){let e=culture.FlexSheet;this._menu=new Menu(document.createElement("div"),{displayMemberPath:"item",selectedValuePath:"op",dropDownCssClass:"wj-flexsheet-fill-menu",openOnHover:!1,closeOnLeave:!1,itemsSource:[{item:e.copyCells,op:this.CopyCells,checked:this._op===this.CopyCells},{item:e.fillSeries,op:this.FillSeries,checked:this._op===this.FillSeries},{item:e.fillFormat,op:this.FillFormat,checked:this._op===this.FillFormat},{item:e.fillWithoutFormat,op:this.FillWithoutFormat,checked:this._op===this.FillWithoutFormat}],selectedValue:this._op,itemClicked:e=>{this._op=e.selectedValue;this.onOperationSelected()}});this._menu.listBox.checkedMemberPath="checked";this._menu.show(this.hostElement);this._menu.selectedValue=this._op}_onUIEvent(e){let t=e.target,i=contains(this.hostElement,t),o=this._menu&&contains(this._menu.listBox.hostElement,t),l=i||o;l&&e instanceof KeyboardEvent&&(l=o&&(e.keyCode==Key.Down||e.keyCode==Key.Up||e.keyCode==Key.Enter||e.keyCode==Key.Escape));l||this.onCancelled()}}_SmartTag.controlTemplate='<img wj-part="icon" style="float:left; height: 18; margin: 0" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAAFJJREFUeNrclEEKACAIBOfp/Xy7i4WSRnRYBIVRVhFJVIhyEAxllQa5E/wBSnsU6Rza2nugqNmASi57C/KKNg/Iqn+iVWzx6M4bOdUEAAD//wMAAYRMfiNaiqEAAAAASUVORK5CYII=" /><img wj-part="btn-menu" style="float:left; height: 18; margin: 0; display: none" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAASCAYAAACXScT7AAAACXBIWXMAAA7DAAAOwwHHb6hkAAAKTWlDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVN3WJP3Fj7f92UPVkLY8LGXbIEAIiOsCMgQWaIQkgBhhBASQMWFiApWFBURnEhVxILVCkidiOKgKLhnQYqIWotVXDjuH9yntX167+3t+9f7vOec5/zOec8PgBESJpHmomoAOVKFPDrYH49PSMTJvYACFUjgBCAQ5svCZwXFAADwA3l4fnSwP/wBr28AAgBw1S4kEsfh/4O6UCZXACCRAOAiEucLAZBSAMguVMgUAMgYALBTs2QKAJQAAGx5fEIiAKoNAOz0ST4FANipk9wXANiiHKkIAI0BAJkoRyQCQLsAYFWBUiwCwMIAoKxAIi4EwK4BgFm2MkcCgL0FAHaOWJAPQGAAgJlCLMwAIDgCAEMeE80DIEwDoDDSv+CpX3CFuEgBAMDLlc2XS9IzFLiV0Bp38vDg4iHiwmyxQmEXKRBmCeQinJebIxNI5wNMzgwAABr50cH+OD+Q5+bk4eZm52zv9MWi/mvwbyI+IfHf/ryMAgQAEE7P79pf5eXWA3DHAbB1v2upWwDaVgBo3/ldM9sJoFoK0Hr5i3k4/EAenqFQyDwdHAoLC+0lYqG9MOOLPv8z4W/gi372/EAe/tt68ABxmkCZrcCjg/1xYW52rlKO58sEQjFu9+cj/seFf/2OKdHiNLFcLBWK8ViJuFAiTcd5uVKRRCHJleIS6X8y8R+W/QmTdw0ArIZPwE62B7XLbMB+7gECiw5Y0nYAQH7zLYwaC5EAEGc0Mnn3AACTv/mPQCsBAM2XpOMAALzoGFyolBdMxggAAESggSqwQQcMwRSswA6cwR28wBcCYQZEQAwkwDwQQgbkgBwKoRiWQRlUwDrYBLWwAxqgEZrhELTBMTgN5+ASXIHrcBcGYBiewhi8hgkEQcgIE2EhOogRYo7YIs4IF5mOBCJhSDSSgKQg6YgUUSLFyHKkAqlCapFdSCPyLXIUOY1cQPqQ28ggMor8irxHMZSBslED1AJ1QLmoHxqKxqBz0XQ0D12AlqJr0Rq0Hj2AtqKn0UvodXQAfYqOY4DRMQ5mjNlhXIyHRWCJWBomxxZj5Vg1Vo81Yx1YN3YVG8CeYe8IJAKLgBPsCF6EEMJsgpCQR1hMWEOoJewjtBK6CFcJg4Qxwicik6hPtCV6EvnEeGI6sZBYRqwm7iEeIZ4lXicOE1+TSCQOyZLkTgohJZAySQtJa0jbSC2kU6Q+0hBpnEwm65Btyd7kCLKArCCXkbeQD5BPkvvJw+S3FDrFiOJMCaIkUqSUEko1ZT/lBKWfMkKZoKpRzame1AiqiDqfWkltoHZQL1OHqRM0dZolzZsWQ8ukLaPV0JppZ2n3aC/pdLoJ3YMeRZfQl9Jr6Afp5+mD9HcMDYYNg8dIYigZaxl7GacYtxkvmUymBdOXmchUMNcyG5lnmA+Yb1VYKvYqfBWRyhKVOpVWlX6V56pUVXNVP9V5qgtUq1UPq15WfaZGVbNQ46kJ1Bar1akdVbupNq7OUndSj1DPUV+jvl/9gvpjDbKGhUaghkijVGO3xhmNIRbGMmXxWELWclYD6yxrmE1iW7L57Ex2Bfsbdi97TFNDc6pmrGaRZp3mcc0BDsax4PA52ZxKziHODc57LQMtPy2x1mqtZq1+rTfaetq+2mLtcu0W7eva73VwnUCdLJ31Om0693UJuja6UbqFutt1z+o+02PreekJ9cr1Dund0Uf1bfSj9Rfq79bv0R83MDQINpAZbDE4Y/DMkGPoa5hpuNHwhOGoEctoupHEaKPRSaMnuCbuh2fjNXgXPmasbxxirDTeZdxrPGFiaTLbpMSkxeS+Kc2Ua5pmutG003TMzMgs3KzYrMnsjjnVnGueYb7ZvNv8jYWlRZzFSos2i8eW2pZ8ywWWTZb3rJhWPlZ5VvVW16xJ1lzrLOtt1ldsUBtXmwybOpvLtqitm63Edptt3xTiFI8p0in1U27aMez87ArsmuwG7Tn2YfYl9m32zx3MHBId1jt0O3xydHXMdmxwvOuk4TTDqcSpw+lXZxtnoXOd8zUXpkuQyxKXdpcXU22niqdun3rLleUa7rrStdP1o5u7m9yt2W3U3cw9xX2r+00umxvJXcM970H08PdY4nHM452nm6fC85DnL152Xlle+70eT7OcJp7WMG3I28Rb4L3Le2A6Pj1l+s7pAz7GPgKfep+Hvqa+It89viN+1n6Zfgf8nvs7+sv9j/i/4XnyFvFOBWABwQHlAb2BGoGzA2sDHwSZBKUHNQWNBbsGLww+FUIMCQ1ZH3KTb8AX8hv5YzPcZyya0RXKCJ0VWhv6MMwmTB7WEY6GzwjfEH5vpvlM6cy2CIjgR2yIuB9pGZkX+X0UKSoyqi7qUbRTdHF09yzWrORZ+2e9jvGPqYy5O9tqtnJ2Z6xqbFJsY+ybuIC4qriBeIf4RfGXEnQTJAntieTE2MQ9ieNzAudsmjOc5JpUlnRjruXcorkX5unOy553PFk1WZB8OIWYEpeyP+WDIEJQLxhP5aduTR0T8oSbhU9FvqKNolGxt7hKPJLmnVaV9jjdO31D+miGT0Z1xjMJT1IreZEZkrkj801WRNberM/ZcdktOZSclJyjUg1plrQr1zC3KLdPZisrkw3keeZtyhuTh8r35CP5c/PbFWyFTNGjtFKuUA4WTC+oK3hbGFt4uEi9SFrUM99m/ur5IwuCFny9kLBQuLCz2Lh4WfHgIr9FuxYji1MXdy4xXVK6ZHhp8NJ9y2jLspb9UOJYUlXyannc8o5Sg9KlpUMrglc0lamUycturvRauWMVYZVkVe9ql9VbVn8qF5VfrHCsqK74sEa45uJXTl/VfPV5bdra3kq3yu3rSOuk626s91m/r0q9akHV0IbwDa0b8Y3lG19tSt50oXpq9Y7NtM3KzQM1YTXtW8y2rNvyoTaj9nqdf13LVv2tq7e+2Sba1r/dd3vzDoMdFTve75TsvLUreFdrvUV99W7S7oLdjxpiG7q/5n7duEd3T8Wej3ulewf2Re/ranRvbNyvv7+yCW1SNo0eSDpw5ZuAb9qb7Zp3tXBaKg7CQeXBJ9+mfHvjUOihzsPcw83fmX+39QjrSHkr0jq/dawto22gPaG97+iMo50dXh1Hvrf/fu8x42N1xzWPV56gnSg98fnkgpPjp2Snnp1OPz3Umdx590z8mWtdUV29Z0PPnj8XdO5Mt1/3yfPe549d8Lxw9CL3Ytslt0utPa49R35w/eFIr1tv62X3y+1XPK509E3rO9Hv03/6asDVc9f41y5dn3m978bsG7duJt0cuCW69fh29u0XdwruTNxdeo94r/y+2v3qB/oP6n+0/rFlwG3g+GDAYM/DWQ/vDgmHnv6U/9OH4dJHzEfVI0YjjY+dHx8bDRq98mTOk+GnsqcTz8p+Vv9563Or59/94vtLz1j82PAL+YvPv655qfNy76uprzrHI8cfvM55PfGm/K3O233vuO+638e9H5ko/ED+UPPR+mPHp9BP9z7nfP78L/eE8/sl0p8zAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAGCSURBVHjafNFPKKRxHAbw5/v7GYdBYUQjLm5SkoNykCQHtcx431/KgdKumJvSrAO7Nwc3RQ5kd3OkHJC/hUJREluonVcToqRh3sRFPA6M1Mbhc3z6Pj1fkMRHQNJL0uPeul731lU37o1y49cqHr8GvvgWQRLBsmpM/P0j4XAXiooKcXl1CZDEzl4EJBEwAZBUwWAQsVgsFSRR11gmM8trimSa3WypzZ31l5v2/vfk/4oAcv9aSGyUSz4gg/AIAOET0YQswIQWaNrnH+2OeSaY0BJN2+wDTi/OpCrwkxX1vW8q63p5cnaaB+Z/09u7x0nFJTVMiEajPsNCQaC6Ryb8THKcw/Tikho6zj//0RGUNV6gMZ1H8fmpH5iTHDlwsiOhO7FrN5RdP6aBIUj/pvJ2bkFbkxAzBzELELNCQQqgrJ5ST1/jqmYOJcHa7dYYGV5TrQ3d+vfUU+b7IfrOIRCGBYD0o1VGmaHaB6DZkqvMD2hUfF1UAISkvE/+yqbCZ89+HgBtwgFOrBUzJgAAAABJRU5ErkJggg==" />';export class _FlexSheetSelectionHandler extends _SelectionHandler{constructor(e){let t=e.selectionMode;super(e);this._mode=t;this._fs=e}moveSelection(e,t,i){let o=this._fs;!i&&o._lastSelMovePos&&this.selection.copy(o._lastSelMovePos);o._lastSelMovePos=null;super.moveSelection(e,t,i)}}export class DefinedName{constructor(e,t,i,o){this._owner=e;this._name=t;this._value=i;if(null!=o){if(!e._validateSheetName(o))throw"The sheet name:("+o+") does not exist in FlexSheet.";this._sheetName=o}}get name(){return this._name}set name(e){if(this._name!==e){if(this._owner.definedNames._find(e,this._sheetName,-1,!0))throw"The "+e+" already existed in definedNames.";{let t=this._name;this._name=e;this._owner._updateFormulasWithNameUpdating(t,this._name)}}}get value(){return this._value}set value(e){this._value!==e&&(this._value=e)}get sheetName(){return this._sheetName}}export class DefinedNameCollection extends ObservableArray{constructor(e){super();this._owner=e;this.collectionChanged.addHandler((e,t)=>{if(t.action===NotifyCollectionChangedAction.Add||t.action===NotifyCollectionChangedAction.Change){var i=t.action===NotifyCollectionChangedAction.Add?"inserted":"updated";if(!(t.item instanceof DefinedName)){this.remove(t.item);throw"Invalid defined name item object was "+i+". The DefinedName instance should be "+i+" in the definedNames array."}if(!t.item||!t.item.name||null==t.item.value){this.remove(t.item);throw"Invalid defined name was "+i+"."}if(null!=t.item.sheetName&&!this._owner._validateSheetName(t.item.sheetName)){this.remove(t.item);throw"The sheet name ("+t.item.sheetName+") does not exist in FlexSheet."}if(this._find(t.item.name,t.item.sheetName,t.index,!0)){this.remove(t.item);throw"The "+t.item.name+" already existed in definedNames."}}})}_find(e,t,i=-1,o=!1){let l=null;t=t?t.toLowerCase():t;e=e?e.toLowerCase():e;for(let s=0;s<this.length;s++){let n=this[s];if(n.name.toLowerCase()===e&&s!==i)if(n.sheetName){if(n.sheetName.toLowerCase()===t)return n}else{if(o&&t)continue;l=n}}return l}_getIndexByName(e){for(let t=0;t<this.length;t++)if(this[t].name===e)return t;return-1}_updateSheetName(e,t){let i=e.toLowerCase();for(let l=0;l<this.length;l++){let s=this[l];null!=s.sheetName&&s.sheetName.toLowerCase()===i&&(s._sheetName=t);let n=s.value.match(/(\w+)\!\$?[A-Za-z]+\$?\d+/g);if(n&&n.length>0)for(var o=0;o<n.length;o++){let i=n[o];i.substring(0,i.indexOf("!"))===e&&(s.value=s.value.replace(i,i.replace(e,t)))}}}}export class _ContextMenu extends Control{constructor(e,t){super(e);this._idx=-1;this._owner=t}get visible(){return"none"!==this.hostElement.style.display}show(e,t){if(!this._owner.selectedSheet)return;this._owner.finishEditing();let i=(t?t.x:e.clientX)+(e?window.pageXOffset:0),o=(t?t.y:e.clientY)+(e?window.pageYOffset:0);this.hostElement.style.position="absolute";this.hostElement.style.display="inline";o+this.hostElement.clientHeight>window.innerHeight+(e?window.pageYOffset:0)&&(o-=this.hostElement.clientHeight);i+this.hostElement.clientWidth>window.innerWidth+(e?window.pageXOffset:0)&&(i-=this.hostElement.clientWidth);this.hostElement.style.top=o+"px";this.hostElement.style.left=i+"px"}hide(){this._idx=-1;let e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e);this.hostElement.style.display="none"}moveToNext(){let e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e);this._idx++;for(;e[this._idx]&&("none"===e[this._idx].style.display||hasClass(e[this._idx],"wj-state-disabled"));)this._idx++;this._idx>=e.length&&(this._idx=0);addClass(e[this._idx],"wj-context-menu-item-selected")}moveToPrev(){let e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e);this._idx--;this._idx<0&&(this._idx=e.length-1);for(;this._idx>0&&("none"===e[this._idx].style.display||hasClass(e[this._idx],"wj-state-disabled"));)this._idx--;addClass(e[this._idx],"wj-context-menu-item-selected")}moveToFirst(){let e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e);this._idx=0;addClass(e[this._idx],"wj-context-menu-item-selected")}moveToLast(){let e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._removeSelectedState(e);this._idx=e.length-1;e[this._idx]&&"none"===e[this._idx].style.display&&this._idx--;addClass(e[this._idx],"wj-context-menu-item-selected")}handleContextMenu(){if(-1===this._idx)this.moveToNext();else{let e=this.hostElement.querySelectorAll(".wj-context-menu-item");this._handleMenuItemOperation(e);this.hide();this._owner.hostElement.focus()}}refresh(e=!0){super.refresh(e);this._localize()}_init(){let e=this,t=e.hostElement.querySelectorAll(".wj-context-menu-item");e.hostElement.style.zIndex="9999";document.body.appendChild(e.hostElement);e.addEventListener(document.body,"mousemove",()=>{e._removeSelectedState(t)});e.addEventListener(e.hostElement,"contextmenu",e=>{e.preventDefault()});this._localize()}_handleMenuItemOperation(e){}_localize(){}_removeSelectedState(e){for(let t=0;t<e.length;t++)removeClass(e[t],"wj-context-menu-item-selected")}}export class _SheetContextMenu extends _ContextMenu{constructor(e,t){super(e,t);this._isDisableDelRow=!1;this._isDisableConvertTable=!1;this.applyTemplate("",this.getTemplate(),{_insRows:"insert-rows",_delRows:"delete-rows",_insCols:"insert-columns",_delCols:"delete-columns",_splitter:"splitter",_convertTable:"convert-table"});this._init()}show(e,t){if(this._owner.selectedSheet){if(this._owner._isDisableDeleteRow(this._owner.selection.topRow,this._owner.selection.bottomRow)){this._isDisableDelRow=!0;addClass(this._delRows,"wj-state-disabled")}this._showTableOperation();if(!this._owner.selection.isValid){this._isDisableConvertTable=!0;addClass(this._convertTable,"wj-state-disabled")}super.show(e,t)}}hide(){super.hide();this._isDisableDelRow=!1;this._isDisableConvertTable=!1;removeClass(this._delRows,"wj-state-disabled");removeClass(this._convertTable,"wj-state-disabled")}_init(){super._init();let e=this;e.addEventListener(e._insRows,"click",t=>{e._owner.insertRows();e.hide();e._owner.hostElement.focus()});e.addEventListener(e._delRows,"click",t=>{e._isDisableDelRow||e._owner.deleteRows();e.hide();e._owner.hostElement.focus()});e.addEventListener(e._insCols,"click",t=>{e._owner.insertColumns();e.hide();e._owner.hostElement.focus()});e.addEventListener(e._delCols,"click",t=>{e._owner.deleteColumns();e.hide();e._owner.hostElement.focus()});e.addEventListener(e._convertTable,"click",t=>{e._isDisableConvertTable||e._addTable();e.hide();e._owner.hostElement.focus()})}_handleMenuItemOperation(e){switch(e[this._idx]){case this._insCols:this._owner.insertColumns();break;case this._insRows:this._owner.insertRows();break;case this._delCols:this._owner.deleteColumns();break;case this._delRows:this._isDisableDelRow||this._owner.deleteRows();break;case this._convertTable:this._addTable()}}_localize(){super._localize();let e=culture.FlexSheet;this._insRows.textContent=e.insertRow;this._delRows.textContent=e.deleteRow;this._insCols.textContent=e.insertCol;this._delCols.textContent=e.deleteCol;this._convertTable.textContent=e.convertTable}_showTableOperation(){let e=this._owner.selection;for(let t=e.topRow;t<=e.bottomRow;t++)for(let i=e.leftCol;i<=e.rightCol;i++){if(null!=this._owner.selectedSheet.findTable(t,i)){this._convertTable.style.display="none";this._splitter.style.display="none";return}}if(e.isSingleCell||this._owner._containsMergedCells(e)){this._convertTable.style.display="none";this._splitter.style.display="none"}else{this._convertTable.style.display="";this._splitter.style.display=""}}_addTable(){let e=this._owner.selectedSheet._addTable(this._owner.selection);if(e){if(0===this._owner.undoStack.stackSize)return;let t=new _TableAction(this._owner,e);this._owner.undoStack._addAction(t)}}}_SheetContextMenu.controlTemplate='<div class="wj-context-menu wj-control wj-flexsheet-context-menu" width="150px"><div class="wj-context-menu-item" wj-part="insert-rows"></div><div class="wj-context-menu-item" wj-part="delete-rows"></div><div class="wj-context-menu-item" wj-part="insert-columns"></div><div class="wj-context-menu-item" wj-part="delete-columns"></div><div class="wj-state-disabled" wj-part="splitter" style="width:100%;height:1px;background-color:lightgray;"></div><div class="wj-context-menu-item" wj-part="convert-table"></div></div>';export class _SheetTabContextMenu extends _ContextMenu{constructor(e,t){super(e,t);this.applyTemplate("",this.getTemplate(),{_insSheet:"insert-sheet",_delSheet:"delete-sheet",_renameSheet:"rename-sheet"});this._init()}_init(){let e=culture.FlexSheet,t=this;t._insSheet.textContent=e.insertSheet;t._delSheet.textContent=e.deleteSheet;t._renameSheet.textContent=e.renameSheet;super._init();t.addEventListener(t._insSheet,"click",e=>{t._owner.addUnboundSheet(null,null,null,t._owner.selectedSheetIndex);t.hide();t._owner.hostElement.focus()});t.addEventListener(t._delSheet,"click",e=>{t._owner.sheets.removeAt(t._owner.selectedSheetIndex);t.hide();t._owner.hostElement.focus()});t.addEventListener(t._renameSheet,"click",e=>{t._owner._tabHolder.sheetControl._startEditingSheetName(t._owner.selectedSheetIndex);t.hide()})}_handleMenuItemOperation(e){switch(e[this._idx]){case this._insSheet:this._owner.addUnboundSheet(null,null,null,this._owner.selectedSheetIndex);break;case this._delSheet:this._owner.sheets.removeAt(this._owner.selectedSheetIndex);break;case this._renameSheet:this._owner._tabHolder.sheetControl._startEditingSheetName(this._owner.selectedSheetIndex)}}_localize(){super._localize();let e=culture.FlexSheet;this._insSheet.textContent=e.insertSheet;this._delSheet.textContent=e.deleteSheet;this._renameSheet.textContent=e.renameSheet}}_SheetTabContextMenu.controlTemplate='<div class="wj-context-menu wj-control wj-flexsheet-context-menu" width="150px"><div class="wj-context-menu-item" wj-part="insert-sheet"></div><div class="wj-context-menu-item" wj-part="delete-sheet"></div><div class="wj-context-menu-item" wj-part="rename-sheet"></div><div>';export class Sheet{constructor(e,t,i,o,l){this._visible=!0;this._unboundSortDesc=new ObservableArray;this._currentStyledCells={};this._currentMergedRanges=[];this._isEmptyGrid=!1;this._rowSettings=[];this._scrollPosition=new Point;this._ownerHeaderRowRemoved=!1;this.workingAs="";this.nameChanged=new Event;this.visibleChanged=new Event;var s=this;this._uuid=Sheet.GenId++;s._owner=e;s._name=i;s._sortList=[new ColumnSortDescription(-1,!0)];o=isNumber(o)&&!isNaN(o)&&o>=0?o:200;l=isNumber(l)&&!isNaN(l)&&l>=0?l:20;if(t){t.columns.forEach(e=>e._orgHdr=e._hdr);s._grid=t;s._addHeaderRow(!0)}else{s._grid=this._createGrid(o,l);s._owner&&(s._grid.validateEdits=s._owner.validateEdits)}s._grid.loadedRows.addHandler(()=>{s._owner&&s._owner._checkCollectionsOwner();s._addHeaderRow();s._setRowSettings()});s._grid.refreshed.addHandler(()=>{s._owner&&s._owner._checkCollectionsOwner()});s._grid.itemsSourceChanged.addHandler(this._gridItemsSourceChanged,this);s._unboundSortDesc.collectionChanged.addHandler(()=>{let e=s._unboundSortDesc,t={};for(let t=0;t<e.length;t++){if(!tryCast(e[t],_UnboundSortDescription))throw"sortDescriptions array must contain SortDescription objects."}if(s._owner){s._owner.rows.beginUpdate();s._owner.rows.sort(s._compareRows());if(!s._owner._isUndoing){for(let e=0;e<s._owner.rows.length;e++){let i=s._owner.rows[e];e!==i._idx&&s._owner._updateFormulaForReorderingRows(i._idx,e);s._owner._updateCellStyleForReorderingRows(i._idx,e,t)}s._currentStyledCells=t}s._owner.rows.endUpdate();s._owner.rows._dirty=!0;s._owner.rows._update();if(s._owner.selectedSheet){s._owner._copyTo(s._owner.selectedSheet);s._owner._copyFrom(s._owner.selectedSheet)}}});s.tables.collectionChanged.addHandler((e,t)=>{if(null!=t.item&&!(t.item instanceof Table))throw"The tables only allows to handle Table instance.";if(s._owner)if(t.action===NotifyCollectionChangedAction.Add||t.action===NotifyCollectionChangedAction.Change){if(t.item){let e=t.item,i=e._getTableRange(),o=s===s._owner.selectedSheet?s._owner:s.grid;try{if(i.topRow>=o.rows.length||i.leftCol>=o.columns.length)throw"";if(i.leftCol+i.columnSpan>o.columns.length)throw"";if(i.topRow+i.rowSpan>o.rows.length)throw"";for(let t=i.topRow;t<=i.bottomRow;t++)for(let o=i.leftCol;o<=i.rightCol;o++){if(s.findTable(t,o)!==e)throw""}e._attachSheet(s)}catch(e){s.tables.removeAt(t.index)}}}else t.action===NotifyCollectionChangedAction.Remove&&t.item&&t.item._detachSheet()})}get grid(){null==this._grid.wj_sheetInfo&&(this._grid.wj_sheetInfo={});return this._grid}get name(){return this._name}set name(e){if(!isNullOrWhiteSpace(e)&&(this._name&&this._name.toLowerCase()!==e.toLowerCase()||!this._name)){let t=new PropertyChangedEventArgs("sheetName",this._name,e);this._name=e;this.grid.wj_sheetInfo.name=e;this.onNameChanged(t)}}get visible(){return this._visible}set visible(e){if(this._visible!==e){this._visible=e;this.grid.wj_sheetInfo.visible=e;this.onVisibleChanged(new EventArgs)}}get rowCount(){return null!=this._grid?this._grid.rows.length:0}set rowCount(e){if(this.itemsSource)return;let t=this.grid.rows.length;if(isNumber(e)&&!isNaN(e)&&e>=0&&t!==e){if(t<e)for(let i=0;i<e-t;i++)this.grid.rows.push(new Row);else this.grid.rows.splice(e,t-e);this._currentStyledCells=this._adjustStylesDict(this._currentStyledCells);this._owner&&this._owner.selectedSheet&&this._name===this._owner.selectedSheet.name&&this._owner._copyFrom(this)}}get columnCount(){return null!=this._grid?this._grid.columns.length:0}set columnCount(e){if(this.itemsSource)return;let t=this.grid.columns.length;if(isNumber(e)&&!isNaN(e)&&e>=0&&t!==e){if(t<e)for(let i=0;i<e-t;i++)this._grid.columns.push(new Column);else this._grid.columns.splice(e,t-e);this._currentStyledCells=this._adjustStylesDict(this._currentStyledCells);this._owner&&this._owner.selectedSheet&&this._name===this._owner.selectedSheet.name&&this._owner._copyFrom(this)}}get selectionRanges(){if(!this._selectionRanges){this._selectionRanges=new ObservableArray;this._selectionRanges.collectionChanged.addHandler(()=>{if(this._owner&&!this._owner._isClicking){let e=this._selectionRanges.length;if(e>0){let t=this._selectionRanges[e-1];t&&t instanceof CellRange&&(this._owner.selection=t)}if(e>1){this._owner._enableMulSel=!0;this._owner.refresh(!1)}this._owner._enableMulSel=!1}},this)}return this._selectionRanges}get itemsSource(){return null!=this._grid?this._grid.itemsSource:null}set itemsSource(e){if(!this._grid||this._grid.itemsSource!=e){this._owner&&this._owner._isCopying||(this._dataView=null);this._isEmptyGrid&&this._clearGrid();this._grid.itemsSource=e}}get filterSetting(){this._owner&&this===this._owner.selectedSheet&&this._getFilterSetting();return this._filterSetting}set filterSetting(e){this._filterSetting=e;this._owner&&this===this._owner.selectedSheet&&this._applyFilterSetting()}get tables(){null==this._tables&&(this._tables=new ObservableArray);return this._tables}get _styledCells(){this._currentStyledCells||(this._currentStyledCells={});this._currentStyledCells.columnCount=this.columnCount;this._currentStyledCells.rowCount=this.rowCount;return this._currentStyledCells}set _styledCells(e){this._currentStyledCells=e}get _uid(){return this._uuid}get _mergedRanges(){this._currentMergedRanges||(this._currentMergedRanges=[]);return this._currentMergedRanges}onNameChanged(e){this.nameChanged.raise(this,e)}onVisibleChanged(e){this.visibleChanged.raise(this,e)}dispose(){this._clearGrid();this._grid.wj_sheetInfo=null;this._grid.dispose();this._grid=null;if(null!=this._tables){for(let e=0;e<this._tables.length;e++)this._tables[e]=null;this._tables=null}}getCellStyle(e,t){let i=this._grid.rows.length,o=this._grid.columns.length;if(e>=i||t>=o)return null;let l=e*o+t;return this._styledCells[l]}addTableFromArray(e,t,i,o,l,s,n,r=!0){let a=!1;if(!this._owner)return;if(null==i||0===i.length)throw"Invalid array to load.";if(!(null!=o&&0!==o.length||null!=(o=Object.keys(i[0]))&&0!==o.length))throw"Invalid array to load.";if(e>=this.rowCount||t>=this.columnCount)return null;let h=null==(n&&n.showHeaderRow)||n.showHeaderRow,d=!(!n||!n.showTotalRow),u=e+(h?1:0),c=u+i.length-1+(d?1:0),_=[],g=this._flex;for(let e=0;e<o.length;e++){let t=o[e],i=new TableColumn(t);0===e?i._totalRowLabel="Total":e===o.length-1&&(i._totalRowFunction="Sum");_.push(i)}let f=new CellRange(e,t,c,t+o.length-1),w=this._needShiftForTable(f);if(0!==w){if(!r)return null;if(!this._canShiftCells(f))return null;{let e=this._needAddRowCountForAddTable(w,f);if(g.collectionView){let t=g.itemsSource instanceof CollectionView;g.collectionView.beginUpdate();for(let i=0;i<e;i++)t?g.itemsSource.sourceCollection.push({}):g.itemsSource.push({});g.collectionView.endUpdate(!0)}else for(let t=0;t<e;t++)g.rows.push(new Row);a=!0}}if(t+o.length>=g.columns.length){if(!r)return null;{let e=t+o.length-g.columns.length+1;if(this.itemsSource&&e>0)return null;g.columns.beginUpdate();for(let t=0;t<e;t++)g.columns.push(new Column);g.columns.endUpdate()}}g.beginUpdate();a&&this._moveDownCells(w,f);if(h)for(let i=0;i<o.length;i++){let l=o[i];g.setCellData(e,t+i,l)}for(let e=0;e<i.length;e++)for(let l=0;l<o.length;l++){let s=o[l];g.setCellData(u+e,t+l,i[e][s])}g.endUpdate();return this._addTable(f,l,s,_,n)}findTable(e,t){let i,o=this._tables;if(o&&(i=o.length)>0)for(let l=0;l<i;l++){let i=o[l],s=i._getTableRange();if(e>=s.topRow&&e<=s.bottomRow&&t>=s.leftCol&&t<=s.rightCol)return i}return null}_attachOwner(e){if(this._owner!==e){this._owner=e;if(this._owner){let e=!1;this._owner.loadedRows.addHandler(()=>{if(!e){e=!0;this._addHeaderRow()}})}}}_setValidName(e){this._name=e;this.grid.wj_sheetInfo.name=e}_storeRowSettings(){if(this._owner){this._rowSettings=[];for(let e=0;e<this._grid.rows.length;e++){let t=this._owner.rows[e];t&&(this._rowSettings[e]={height:t.height,allowMerging:t.allowMerging,isCollapsed:t instanceof GroupRow?t.isCollapsed:null,visible:t.visible,isSelected:t.isSelected,readOnly:t.isReadOnly&&!(t instanceof HeaderRow)})}}}_setRowSettings(){for(let e=0;e<this._rowSettings.length;e++){let t=this._rowSettings[e];if(t){let i=this._grid.rows[e];if(i){let e=i instanceof HeaderRow;i.height=t.height;i.allowMerging=t.allowMerging;i.visible=t.visible;i instanceof GroupRow&&(i.isCollapsed=!!t.isCollapsed);i.isSelected=!!t.isSelected;i.isReadOnly=e||!!t.readOnly}}}}_addTable(e,t,i,o,l){if(!e.isValid||!this._owner)return null;let s;null!=t&&null==this._owner._getTable(t)||(t=this._getUniqueTableName());s=new Table(t,e,i,o,l);this.tables.push(s);return s}_addSelection(e){let t=this.selectionRanges;t.beginUpdate();for(let i=t.length-1;i>=0;i--)e.contains(t[i])&&t.removeAt(i);e.isValid&&t.push(e);t.endUpdate()}get _flex(){return this===this._owner.selectedSheet?this._owner:this.grid}_compareRows(){let e=this,t=this._unboundSortDesc;return function(i,o){for(let l=0;l<t.length;l++){let s=t[l],n=i._ubv&&s.column?i._ubv[s.column._hash]:"",r=o._ubv&&s.column?o._ubv[s.column._hash]:"";_isFormula(n)&&(n=e._owner.evaluate(n));_isFormula(r)&&(r=e._owner.evaluate(r));n!=n&&(n=null);r!=r&&(r=null);isString(n)&&(n=n.toLowerCase()+n);isString(r)&&(r=r.toLowerCase()+r);if(""===n||null==n)return 1;if(""===r||null==r)return-1;let a=n<r?-1:n>r?1:0;isString(n)&&isNumber(r)&&(a=1);isString(r)&&isNumber(n)&&(a=-1);if(0!==a)return s.ascending?+a:-a}return 0}}_createGrid(e,t){let i=document.createElement("div");this._isEmptyGrid=!0;i.style.visibility="hidden";document.body.appendChild(i);let o=new FlexGrid(i);document.body.removeChild(i);for(let t=0;t<e;t++)o.rows.push(new Row);for(let e=0;e<t;e++){let e=new Column;e.isRequired=!1;o.columns.push(e)}o.wj_sheetInfo={name:this.name,visible:this.visible,styledCells:this._styledCells,mergedRanges:this._mergedRanges};return o}_clearGrid(){this._grid.rows.clear();this._grid.columns.clear();this._grid.columnHeaders.columns.clear();this._grid.rowHeaders.rows.clear()}_gridItemsSourceChanged(){let e=this;if(this._owner&&!this._owner._isCopying&&this._owner.selectedSheet&&this._name===this._owner.selectedSheet.name){this._owner.filter.clear();this._owner._copyFrom(this,!1);setTimeout(()=>{e._owner._setFlexSheetToDirty();e._owner.invalidate()},10)}}_addHeaderRow(e=!1){if(this._needAddHeaderRow()||e){let e=new HeaderRow;e.isReadOnly=!0;for(let t=0;t<this._grid.columns.length;t++){let i=this._grid.columns[t];e._ubv||(e._ubv={});e._ubv[i._hash]=FlexSheet._getHeaderRowText(i)}this._grid.rows.insert(0,e)}}_needAddHeaderRow(){let e=this._grid.allowAddNew&&this._grid.newRowAtTop?this._grid.rows[1]:this._grid.rows[0];if(!this._grid.collectionView||e instanceof HeaderRow)return!1;if(null==this._owner||!this._owner.rows.length)return!0;return(this._owner.allowAddNew&&this._owner.newRowAtTop?this._owner.rows[1]:this._owner.rows[0])instanceof HeaderRow||!this._ownerHeaderRowRemoved}_getUniqueTableName(){let e="Table1",t=2;for(;;){if(null==this._owner._getTable(e))break;e="Table"+t;t++}return e}_needShiftForTable(e){let t=0,i=0,o=this._flex;for(let l=e.topRow;l<=e.bottomRow;l++){if(l>=o.rows.length)return t=e.rowSpan-i;for(let s=e.leftCol;s<=e.rightCol&&s<o.columns.length;s++){let n=o.getCellData(l,s,!1);if(null!=n&&""!==n)return t=e.rowSpan-i}i++}return t}_needAddRowCountForAddTable(e,t){let i=this._flex;for(let o=1;o<=e;o++){let l=i.rows.length-o;for(let s=t.leftCol;s<=t.rightCol&&s<i.columns.length;s++){let t=i.getCellData(l,s,!1),n=this.getCellStyle(l,s);if(null!=t&&""!==t||null!=n)return e-o+1}}return 0}_moveDownTable(e){let t=e._getTableRange(),i=this._flex;for(let e=t.bottomRow;e>=t.topRow;e--)for(let o=t.leftCol;o<=t.rightCol;o++){let t=null!=i.columns[o].dataMap,l=i.getCellData(e,o,t);i.setCellData(e+1,o,l);i.setCellData(e,o,"")}e._updateTableRange(1,1,0,0)}_moveDownCells(e,t){let i=this._flex;for(let o=i.rows.length-1-e;o>=t.topRow;o--)for(let l=t.leftCol;l<=t.rightCol&&l<i.columns.length;l++){let t=null!=i.columns[l].dataMap,s=i.getCellData(o,l,t);i.setCellData(o+e,l,s);i.setCellData(o,l,"");let n=this.getCellStyle(o,l),r=(o+e)*i.columns.length+l,a=o*i.columns.length+l;if(n){this._styledCells[r]=n;this._styledCells[a]=null}let h=this._mergedRanges[a];if(h){h.row+=e;h.row2+=e;this._mergedRanges[r]=h;this._mergedRanges[a]=null}let d=this.findTable(o,l);if(d){let t=d._getTableRange();t.topRow===o&&t.leftCol===l&&d._updateTableRange(e,e,0,0)}}}_moveUpCells(e,t){let i=this._flex;for(let o=t.topRow;o<i.rows.length;o++)for(let l=t.leftCol;l<=t.rightCol&&l<i.columns.length;l++){let t=null!=i.columns[l].dataMap,s=i.getCellData(o,l,t);i.setCellData(o-e,l,s);i.setCellData(o,l,"");let n=this.getCellStyle(o,l),r=(o-e)*i.columns.length+l,a=o*i.columns.length+l;if(n){this._styledCells[r]=n;this._styledCells[a]=null}let h=this._mergedRanges[a];if(h){h.row-=e;h.row2-=e;this._mergedRanges[r]=h;this._mergedRanges[a]=null}let d=this.findTable(o,l);if(d){let t=d._getTableRange();t.topRow===o&&t.leftCol===l&&d._updateTableRange(-e,-e,0,0)}}}_moveDownCellsWithinTable(e,t,i){let o=this._flex;for(let l=i.bottomRow;l>i.topRow+e;l--)for(let e=i.leftCol;e<=i.rightCol;e++){let i=null!=o.columns[e].dataMap,s=o.getCellData(l,e,i);o.setCellData(l+t,e,s);o.setCellData(l,e,"");void 0}}_moveUpCellsWithinTable(e,t,i){let o=i.topRow+e,l=this._flex;for(let e=o;e<=i.bottomRow;e++)for(let s=i.leftCol;s<=i.rightCol;s++){if(e>=o+t){let i=null!=l.columns[s].dataMap,o=l.getCellData(e,s,i);l.setCellData(e-t,s,o)}l.setCellData(e,s,"");void 0}}_canShiftCells(e){let t=this._flex;for(let i=e.topRow;i<t.rows.length;i++)for(let o=e.leftCol;o<=e.rightCol&&o<t.columns.length;o++){let l=this.findTable(i,o);if(l){let t=l._getTableRange();if(t.leftCol<e.leftCol||t.rightCol>e.rightCol)return!1}let s=i*t.columns.length+o,n=this._mergedRanges[s];if(n&&(n.leftCol<e.leftCol||n.rightCol>e.rightCol))return!1}return!0}_needMoveDownTable(e){let t=e.getRange();if(0===t.topRow)return!0;let i=e.getColumns(),o=this._flex;for(let e=0;e<i.length;e++){let i=o.getCellData(t.topRow-1,t.leftCol+e,!1);if(null!=i&&""!==i)return!0}return!1}_needAddRowCountForInsertTableRows(e,t){let i=this._flex;for(let o=1;o<=e;o++){let l=i.rows.length-o;if(l<=t.bottomRow)return e;for(let s=t.leftCol;s<=t.rightCol&&s<i.columns.length;s++){let t=i.getCellData(l,s,!1),n=this.getCellStyle(l,s);if(null!=t&&""!==t||null!=n)return e-o+1}}return 0}_getFilterSetting(){this._filterDefinition=this._owner.filter.filterDefinition;this._filterSetting={};this._filterSetting.filterColumns=this._owner.filter.filterColumns;this._filterSetting.columnFilterSettings||(this._filterSetting.columnFilterSettings=[]);for(let e=0;e<this._owner.filter._filters.length;e++){let t=this._owner.filter._filters[e];t&&this._filterSetting.columnFilterSettings.push({column:t.column,filterType:t.filterType,dataMap:t.dataMap,valueFilterSetting:{maxValues:t.valueFilter.maxValues,uniqueValues:t.valueFilter.uniqueValues,sortValues:t.valueFilter.sortValues,dataMap:t.valueFilter.dataMap,exclusiveValueSearch:t.valueFilter.exclusiveValueSearch},conditionFilterSetting:{dataMap:t.conditionFilter.dataMap}})}}_applyFilterSetting(){if(null==this._filterSetting)this._clearFilterSetting();else{this._owner.filter.filterColumns=this._filterSetting.filterColumns;this._filterDefinition&&(this._owner.filter.filterDefinition=this._filterDefinition);let e=this._filterSetting.columnFilterSettings;if(!e||!e.length)return;for(let t=0;t<e.length;t++){let i=e[t];if(i&&null!=i.column){let e=this._owner.filter.getColumnFilter(i.column);if(e){let t=e.valueFilter.showValues,o=e.valueFilter.filterText,l={operator:e.conditionFilter.condition1.operator,value:e.conditionFilter.condition1.value},s={operator:e.conditionFilter.condition2.operator,value:e.conditionFilter.condition2.value},n=e.conditionFilter.and;null!=i.dataMap&&(e.dataMap=i.dataMap);null!=i.filterType&&(e.filterType=i.filterType);let r=i.valueFilterSetting;if(r){r.dataMap&&(e.valueFilter.dataMap=r.dataMap);null!=r.maxValues&&(e.valueFilter.maxValues=r.maxValues);null!=r.sortValues&&(e.valueFilter.sortValues=r.sortValues);r.uniqueValues&&(e.valueFilter.uniqueValues=r.uniqueValues);e.valueFilter.exclusiveValueSearch=r.exclusiveValueSearch}let a=i.conditionFilterSetting;a&&a.dataMap&&(e.conditionFilter.dataMap=a.dataMap);e.valueFilter.showValues=t;e.valueFilter.filterText=o;e.conditionFilter.condition1.operator=l.operator;e.conditionFilter.condition1.value=l.value;e.conditionFilter.condition2.operator=s.operator;e.conditionFilter.condition2.value=s.value;e.conditionFilter.and=n}}}}}_cloneMergedCells(){let e=[];for(let t=0;t<this._mergedRanges.length;t++){let i=this._mergedRanges[t];e.push(i.clone())}return e}_getMergedRange(e,t){for(let i=0;i<this._mergedRanges.length;i++){let o=this._mergedRanges[i];if(e>=o.topRow&&e<=o.bottomRow&&t>=o.leftCol&&t<=o.rightCol)return o}return null}_clearFilterSetting(){this._owner.filter._filters=[];this._owner.filter.filterColumns=null;this._filterDefinition&&(this._owner.filter.filterDefinition=this._filterDefinition)}_adjustStylesDict(e){if(!e)return;let t=e.columnCount,i=e.rowCount,o=this.columnCount,l=this.rowCount;if(t&&t!=o||i&&i!=l){let i={};Object.keys(e).forEach(s=>{let n=+s;if(isNaN(n))return;let r=Math.floor(n/t),a=n%t;r<l&&a<o&&(i[r*o+a]=e[s]);delete e[s]});e=i}e.columnCount=o;e.rowCount=l;return e}}Sheet.GenId=0;export class SheetCollection extends ObservableArray{constructor(){super(...arguments);this._current=-1;this.sheetCleared=new Event;this.selectedSheetChanged=new Event;this.sheetNameChanged=new Event;this.sheetVisibleChanged=new Event}onSheetCleared(){this.sheetCleared.raise(this)}get selectedIndex(){return this._current}set selectedIndex(e){this._moveCurrentTo(+e)}onSelectedSheetChanged(e){this.selectedSheetChanged.raise(this,e)}push(...e){for(let t=0;t<e.length;t++){let i=e[t].name?this.getValidSheetName(e[t]):this._getUniqueName();i!==e[t].name&&(e[t].name=i);super.push(e[t]);this._postprocessSheet(e[t])}return this.length}splice(e,t,...i){i.forEach(e=>{if(e instanceof Sheet&&"Angular"===e.workingAs)requestAnimationFrame(()=>{e.name=e.name?this.getValidSheetName(e):this._getUniqueName();this._postprocessSheet(e)});else{e.name=e.name?this.getValidSheetName(e):this._getUniqueName();this._postprocessSheet(e)}});return super.splice(e,t,...i)}onCollectionChanged(e){this._current>=this.length&&(this._current=this.length-1);super.onCollectionChanged(e)}onSheetNameChanged(e){this.sheetNameChanged.raise(this,e)}onSheetVisibleChanged(e){this.sheetVisibleChanged.raise(this,e)}selectFirst(){return this._moveCurrentTo(0)}selectLast(){return this._moveCurrentTo(this.length-1)}selectPrevious(){return this._moveCurrentTo(this._current-1)}selectNext(){return this._moveCurrentTo(this._current+1)}hide(e){if(e<0&&e>=this.length)return!1;if(!this[e].visible)return!1;this[e].visible=!1;return!0}show(e){if(e<0&&e>=this.length)return!1;this[e].visible=!0;this._moveCurrentTo(e);return!0}clear(){for(let e=0;e<this.length;e++){let t=this[e];t.dispose();t=null}super.clear();this._current=-1;this.onSheetCleared()}isValidSheetName(e){let t=this._getSheetIndexFrom(e.name),i=this.indexOf(e);return-1===t||t===i}getValidSheetName(e){let t=e.name,i=1,o=this.indexOf(e);for(;;){let l=this._getSheetIndexFrom(t);if(-1===l||l===o)break;t=e.name.concat((i+1).toString());i++}return t}getUniqueNameOnInit(){let e="Sheet1",t=1;for(;;){if(-1===this._getSheetIndexFrom(e))break;e="Sheet"+t;t++}return e}_setCurrentIdx(e){this._current=e}_moveCurrentTo(e){let t=e;if(e<0||e>=this.length)return!1;if(this._current<t||0===t)for(;t<this.length&&!this[t].visible;)t++;else if(this._current>t)for(;t>=0&&!this[t].visible;)t--;if(t===this.length){t=e;for(;t>=0&&!this[t].visible;)t--}if(t<0)return!1;if(t!==this._current){let e=new PropertyChangedEventArgs("sheetIndex",this._current,t);this._current=t;this.onSelectedSheetChanged(e)}return!0}_getSheetIndexFrom(e){if(!e)return-1;e=e.toLowerCase();for(let t=0;t<this.length;t++){let i=this[t];if((i.name?i.name.toLowerCase():"")===e)return t}return-1}_postprocessSheet(e){e.nameChanged.removeHandler(this._shNameChanged,this);e.nameChanged.addHandler(this._shNameChanged,this);e.visibleChanged.removeHandler(this._shVisibleChanged,this);e.visibleChanged.addHandler(this._shVisibleChanged,this)}_shNameChanged(e,t){this.isValidSheetName(e)||e._setValidName(this.getValidSheetName(e));e._owner&&e._owner._sheetNameChanged(t.oldValue,e.name);let i=this._getSheetIndexFrom(e.name),o=new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Change,e,isNumber(i)?i:this.length-1);this.onSheetNameChanged(o)}_shVisibleChanged(e,t){let i=this._getSheetIndexFrom(e.name),o=new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Change,e,isNumber(i)?i:this.length-1);this.onSheetVisibleChanged(o)}_getUniqueName(){let e="Sheet1",t=2;for(;;){if(-1===this._getSheetIndexFrom(e))break;e="Sheet"+t;t++}return e}}export class _SheetTabs extends Control{constructor(e,t,i){super(e,i);this._rtl=!1;this._sheetTabClicked=!1;this._owner=t;this._sheets=t.sheets;this._rtl="rtl"==getComputedStyle(t.hostElement).direction;this._initControl();this.deferUpdate(()=>{this.initialize(i)})}refresh(e){this._tabContainer.innerHTML="";this._tabContainer.innerHTML=this._getSheetTabs();this._rtl&&this._adjustSheetsPosition();this._adjustSize()}_sourceChanged(e,t=NotifyCollectionChangedEventArgs.reset){let i=t;switch(i.action){case NotifyCollectionChangedAction.Add:let e=i.index-1;e<0&&(e=0);this._tabContainer.innerHTML="";this._tabContainer.innerHTML=this._getSheetTabs();this._rtl&&this._adjustSheetsPosition();this._adjustSize();break;case NotifyCollectionChangedAction.Remove:this._tabContainer.removeChild(this._tabContainer.children[i.index]);this._adjustSize();break;default:this.invalidate()}}_selectedSheetChanged(e,t){this._updateTabActive(t.oldValue,!1);this._updateTabActive(t.newValue,!0);this._sheetTabClicked?this._sheetTabClicked=!1:this._scrollToActiveSheet(t.newValue,t.oldValue);this._adjustSize()}_initControl(){let e=this,t=e.hostElement;e.applyTemplate("",e.getTemplate(),{_sheetContainer:"sheet-container",_tabContainer:"container",_sheetPage:"sheet-page",_newSheet:"new-sheet",_contextMenuHost:"context-menu"});e._contextMenu=new _SheetTabContextMenu(e._contextMenuHost,e._owner);if(e._rtl){e._sheetPage.style.right="0px";e._tabContainer.parentElement.style.right=e._sheetPage.clientWidth+"px";e._tabContainer.style.right="0px";e._tabContainer.style.cssFloat="right";e._newSheet.style.right=e._sheetPage.clientWidth+e._tabContainer.parentElement.clientWidth+"px"}e._adjustNavigationButtons(e._rtl);e.addEventListener(t,"mousedown",()=>{e._owner._mouseHdl._htDown=null});e.addEventListener(t,"dragstart",t=>{t.dataTransfer.setData("text","foo");t.target instanceof HTMLLIElement&&e._owner._isDescendant(e._tabContainer,t.target)?e._dragSrcIdx=e._getItemIndex(e._tabContainer,t.target):e._dragSrcIdx=-1});e.addEventListener(t,"dragover",e=>{e.dataTransfer.dropEffect="move";e.preventDefault();e.stopPropagation()});e.addEventListener(t,"drop",t=>{if(e._dragSrcIdx>-1){let i;if(t.target instanceof HTMLLIElement&&e._owner._isDescendant(e._tabContainer,t.target))i=e._getItemIndex(e._tabContainer,t.target);else{let o=e._tabContainer.getBoundingClientRect();i=t.clientX<o.left?0:t.clientX>o.right?e._sheets.length-1:-1}if(i!==e._dragSrcIdx){let t=e._sheets[e._dragSrcIdx],o=e._owner.selection.clone();e._sheets._exchangingPosition=!0;e._sheets.deferUpdate(()=>{t.grid._selHdl.select(o,!1,!1);e._sheets.splice(e._dragSrcIdx,1);e._sheets.splice(i,0,t)});e._owner.selectedSheetIndex=i;e._sheets._exchangingPosition=!1}}e._dragSrcIdx=-1;t.preventDefault();t.stopPropagation()});e.addEventListener(e._newSheet,"click",t=>{let i=e._owner.selectedSheetIndex;e._owner.addUnboundSheet();e._scrollToActiveSheet(e._owner.selectedSheetIndex,i)});e._sheets.collectionChanged.addHandler(e._sourceChanged,e);e._sheets.selectedSheetChanged.addHandler(e._selectedSheetChanged,e);e._sheets.sheetNameChanged.addHandler(e._updateSheetName,e);e._sheets.sheetVisibleChanged.addHandler(e._updateTabShown,e);e._initSheetPage();e._initSheetTab()}_initSheetTab(){let e=this;e.addEventListener(e._tabContainer,"mousedown",t=>{let i,o=t.target;if(o instanceof HTMLLIElement){e._sheetTabClicked=!0;i=e._getItemIndex(e._tabContainer,o);e._scrollSheetTabContainer(o);i>-1&&(e._sheets.selectedIndex=i)}});e.addEventListener(e._tabContainer,"dblclick",t=>{let i,o=t.target;if(o instanceof HTMLLIElement){i=e._getItemIndex(e._tabContainer,o);e._scrollSheetTabContainer(o);i>-1&&e._startEditingSheetName(i)}});e.addEventListener(e._tabContainer,"contextmenu",t=>{t.preventDefault();e._contextMenu.show(t)})}_initSheetPage(){let e=this;e.hostElement.querySelector("div.wj-sheet-page").addEventListener("click",t=>{let i="[object HTMLButtonElement]"===t.target.toString()?t.target:t.target.parentElement,o=e._getItemIndex(e._sheetPage,i);if(0!==e._sheets.length)switch(o){case 0:e._sheets.selectFirst();break;case 1:e._sheets.selectPrevious();break;case 2:e._sheets.selectNext();break;case 3:e._sheets.selectLast()}})}_getSheetTabs(){let e="";for(let t=0;t<this._sheets.length;t++)e+=this._getSheetElement(this._sheets[t],this._sheets.selectedIndex===t);return e}_getSheetElement(e,t=!1){let i="<li";e.visible?t&&(i+=' class="active"'):i+=' class="hidden"';return i+=' draggable="true">'+e.name+"</li>"}_updateTabActive(e,t){e>=0&&e<this._tabContainer.children.length&&toggleClass(this._tabContainer.children[e],"active",t)}_updateTabShown(e,t){if(!(t.index<0||t.index>=this._tabContainer.children.length)){t.item.visible?removeClass(this._tabContainer.children[t.index],"hidden"):addClass(this._tabContainer.children[t.index],"hidden");this._adjustSize()}}_adjustSize(){let e=0,t=0;if("none"===this.hostElement.style.display)return;t=this._tabContainer.parentElement.scrollLeft;this._tabContainer.parentElement.style.width="";this._tabContainer.style.width="";this._sheetPage.parentElement.style.width="";for(let t=0,i=this._tabContainer.childElementCount;t<i;t++)e+=this._tabContainer.children[t].offsetWidth+1;let i=this.hostElement.offsetWidth-this._sheetPage.offsetWidth-this._newSheet.offsetWidth-2;this._tabContainer.parentElement.style.width=(e>i?i:e)+"px";this._tabContainer.style.width=e+"px";this._sheetPage.parentElement.style.width=this._sheetPage.offsetWidth+this._newSheet.offsetWidth+this._tabContainer.parentElement.offsetWidth+3+"px";this._tabContainer.parentElement.scrollLeft=t}_getItemIndex(e,t){for(let i=0;i<e.children.length;i++)if(e.children[i]===t)return i;return-1}_updateSheetName(e,t){this._tabContainer.querySelectorAll("li")[t.index].textContent=t.item.name;this._adjustSize()}_scrollSheetTabContainer(e){let t=this._tabContainer.parentElement.scrollLeft,i=this._tabContainer.parentElement.offsetWidth;if(this._rtl)switch(FlexGrid._getRtlMode()){case"rev":let o=-this._tabContainer.offsetLeft;o+e.offsetLeft+e.offsetWidth>i+t?this._tabContainer.parentElement.scrollLeft+=e.offsetWidth:o+e.offsetLeft<t&&(this._tabContainer.parentElement.scrollLeft-=e.offsetWidth);break;case"neg":e.offsetLeft<t?this._tabContainer.parentElement.scrollLeft-=e.offsetWidth:e.offsetLeft+e.offsetWidth>i+t&&(this._tabContainer.parentElement.scrollLeft+=e.offsetWidth);break;default:let l=this._newSheet.offsetWidth;e.offsetLeft-l+t<0?this._tabContainer.parentElement.scrollLeft+=e.offsetWidth:e.offsetLeft+e.offsetWidth-l+t>i&&(this._tabContainer.parentElement.scrollLeft-=e.offsetWidth)}else{let o=this._sheetPage.offsetWidth;e.offsetLeft+e.offsetWidth-o>i+t?this._tabContainer.parentElement.scrollLeft+=e.offsetWidth:e.offsetLeft-o<t&&(this._tabContainer.parentElement.scrollLeft-=e.offsetWidth)}}_adjustSheetsPosition(){let e=this._tabContainer.querySelectorAll("li"),t=0;for(let i=0;i<e.length;i++){let o=e[i];o.style.cssFloat="right";o.style.right=t+"px";t+=e[i].clientWidth}}_scrollToActiveSheet(e,t){let i=this._tabContainer.querySelectorAll("li"),o=0;this._tabContainer.clientWidth>this._tabContainer.parentElement.clientWidth&&(o=this._tabContainer.clientWidth-this._tabContainer.parentElement.clientWidth);if(i.length>0&&e<i.length&&t<i.length){if(0===e&&!this._rtl||e===i.length-1&&this._rtl){if(this._rtl)switch(FlexGrid._getRtlMode()){case"rev":this._tabContainer.parentElement.scrollLeft=0;break;case"neg":this._tabContainer.parentElement.scrollLeft=-o;break;default:this._tabContainer.parentElement.scrollLeft=o}else this._tabContainer.parentElement.scrollLeft=0;return}if(0===e&&this._rtl||e===i.length-1&&!this._rtl){if(this._rtl)switch(FlexGrid._getRtlMode()){case"rev":this._tabContainer.parentElement.scrollLeft=o;break;case"neg":default:this._tabContainer.parentElement.scrollLeft=0}else this._tabContainer.parentElement.scrollLeft=o;return}if(e>=t)for(let o=t+1;o<=e;o++){let e=i[o];this._scrollSheetTabContainer(e)}else for(let o=t-1;o>=e;o--){let e=i[o];this._scrollSheetTabContainer(e)}}}_adjustNavigationButtons(e){let t=this.hostElement.querySelectorAll(".wj-sheet-page button");if(t&&4===t.length){let i;if(e){i=t[0].querySelector("span");removeClass(i,"wj-glyph-step-backward");addClass(i,"wj-glyph-step-forward");i=t[1].querySelector("span");removeClass(i,"wj-glyph-left");addClass(i,"wj-glyph-right");i=t[2].querySelector("span");removeClass(i,"wj-glyph-right");addClass(i,"wj-glyph-left");i=t[3].querySelector("span");removeClass(i,"wj-glyph-step-forward");addClass(i,"wj-glyph-step-backward")}else{i=t[0].querySelector("span");removeClass(i,"wj-glyph-step-forward");addClass(i,"wj-glyph-step-backward");i=t[1].querySelector("span");removeClass(i,"wj-glyph-right");addClass(i,"wj-glyph-left");i=t[2].querySelector("span");removeClass(i,"wj-glyph-left");addClass(i,"wj-glyph-right");i=t[3].querySelector("span");removeClass(i,"wj-glyph-step-backward");addClass(i,"wj-glyph-step-forward")}}}_startEditingSheetName(e){let t,i=this,o=i._tabContainer.children[e],l=o.textContent;i._editingSheetTab=o;i._measureEle=document.createElement("span");i._measureEle.setAttribute(FlexGrid._WJS_MEASURE,"true");i._measureEle.style.visibility="hidden";i.hostElement.appendChild(i._measureEle);o.innerHTML='<input type="text" style="width: '+(o.offsetWidth-40)+'px;"/>';t=o.children[0];addClass(t,"wj-sheet-name-editor wj-form-control");t.value=l;setSelectionRange(t,0,l.length);i.addEventListener(t,"keydown",e=>{e.keyCode===Key.Enter?i._commitSheetName():i._measureInputWidth(e.key)});i.addEventListener(t,"blur",i._commitSheetName.bind(i))}_commitSheetName(){if(!this._editingSheetTab)return;let e=this._editingSheetTab.children[0];this.removeEventListener(e);let t=e.value,i=this._getItemIndex(this._tabContainer,this._editingSheetTab);if(null!=t&&""!==t&&-1===this._sheets._getSheetIndexFrom(t)){this._sheets[i].name=t;this._editingSheetTab.textContent=t}else this._editingSheetTab.textContent=this._sheets[i].name;this._editingSheetTab=null;removeChild(this._measureEle);this._measureEle=null;this._adjustSize()}_measureInputWidth(e){if(!this._editingSheetTab||e.length>1)return;let t=this._editingSheetTab.children[0],i=t.selectionStart,o=t.selectionEnd,l=t.value;if(null!=(l=l.substring(0,i)+e+l.substring(o))&&""!==l){this._measureEle.textContent=l;t.style.width=this._measureEle.offsetWidth+"px";this._adjustSize()}}}_SheetTabs.controlTemplate='<div wj-part="sheet-container" class="wj-sheet" style="height:100%;position:relative"><div wj-part="sheet-page" class="wj-btn-group wj-sheet-page"><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-step-backward"></span></button><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-left"></span></button><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-right"></span></button><button type="button" class="wj-btn wj-btn-default"><span class="wj-sheet-icon wj-glyph-step-forward"></span></button></div><div class="wj-sheet-tab" style="height:100%;overflow:hidden"><ul wj-part="container"></ul></div><div wj-part="new-sheet" class="wj-new-sheet"><span class="wj-sheet-icon wj-glyph-file"></span></div><div wj-part="context-menu" style="display:none;z-index:100"></div></div>';export class _UnboundSortDescription{constructor(e,t){this._column=e;this._ascending=t}get column(){return this._column}get ascending(){return this._ascending}}export class _TabHolder extends Control{constructor(e,t){super(e);this._splitterMousedownHdl=this._splitterMousedownHandler.bind(this);this._owner=t;this.applyTemplate("",this.getTemplate(),{_divSheet:"left",_divSplitter:"splitter",_divRight:"right"});this._init()}get sheetControl(){return this._sheetControl}get visible(){return"none"!==this.hostElement.style.display}set visible(e){this.hostElement.style.display=e?"block":"none";this._divSheet.style.display=e?"block":"none"}getSheetBlanketSize(){return 20}adjustSize(){var e=this._owner.scrollSize.width-this._owner.clientSize.width,t=(this._owner.scrollSize.height,this._owner.clientSize.height,this._divSplitter.parentElement);if(e<=0){t.style.minWidth="100px";this._divSplitter.style.display="none";this._divRight.style.display="none";this._divSheet.style.width="100%";this._divSplitter.removeEventListener("mousedown",this._splitterMousedownHdl,!0)}else{t.style.minWidth="300px";this._divSplitter.style.display="none";this._divRight.style.display="none";this._divSheet.style.width="100%";this._divSplitter.removeEventListener("mousedown",this._splitterMousedownHdl,!0);this._divSplitter.addEventListener("mousedown",this._splitterMousedownHdl,!0)}this._sheetControl._adjustSize()}_init(){var e=this;e._funSplitterMousedown=function(t){e._splitterMouseupHandler(t)};e._divSplitter.parentElement.style.height=e.getSheetBlanketSize()+"px";e._sheetControl=new _SheetTabs(e._divSheet,this._owner)}_splitterMousedownHandler(e){this._startPos=e.pageX;document.addEventListener("mousemove",this._splitterMousemoveHandler.bind(this),!0);document.addEventListener("mouseup",this._funSplitterMousedown,!0);e.preventDefault()}_splitterMousemoveHandler(e){null!==this._startPos&&void 0!==this._startPos&&this._adjustDis(e.pageX-this._startPos)}_splitterMouseupHandler(e){document.removeEventListener("mousemove",this._splitterMousemoveHandler,!0);document.removeEventListener("mouseup",this._funSplitterMousedown,!0);this._adjustDis(e.pageX-this._startPos);this._startPos=null}_adjustDis(e){var t=this._divRight.offsetWidth-e,i=this._divSheet.offsetWidth+e;if(t<=100){t=100;e=this._divRight.offsetWidth-t;i=this._divSheet.offsetWidth+e}else if(i<=100){e=(i=100)-this._divSheet.offsetWidth;t=this._divRight.offsetWidth-e}if(0!=e){this._divRight.style.width=t+"px";this._divSheet.style.width=i+"px";this._startPos=this._startPos+e}}}_TabHolder.controlTemplate='<div><div wj-part="left" style="float:left;height:100%;overflow:hidden"></div><div wj-part="splitter" style="float:left;height:100%;width:6px;background-color:#e9eaee;padding:2px;cursor:e-resize"><div style="background-color:#8a9eb2;height:100%"></div></div><div wj-part="right" style="float:left;height:100%;background-color:#e9eaee"></div></div>';export class _Expression{constructor(e,t){this._evaluated=!1;this._rounder=e;this._token=t?t instanceof _Token?t:new _Token(t,_TokenID.ATOM,_TokenType.LITERAL):new _Token(null,_TokenID.ATOM,_TokenType.IDENTIFIER)}get token(){return this._token}get evaluated(){return this._evaluated}get evaluatedValue(){return this._evaluated?this._evaluatedValue:void 0}set evaluatedValue(e){this._evaluatedValue=e;this._evaluated=!0}evaluate(e,t,i,o=!0,l=!1,s=!0){if(this._token.tokenType===_TokenType.ERROR){if(s)throw this._token.value;return this._token.value}if(this._token.tokenType!==_TokenType.LITERAL)throw new SyntaxError(_ErrorMessages.BadExpression);return this._token.value}static toString(e,t,i,o){var l=e.evaluate(t,i,o);if(l instanceof FormulaError)throw l;(null==l||e instanceof _CellRangeExpression&&e._isEmpty)&&(l="");l&&!isPrimitive(l)&&(l=l.value);isString(l)&&"'"===l[0]&&(l=l.substr(1));isDate(l)&&(l=l.valueOf());return null!=l?l.toString():""}static toNumber(e,t,i,o){var l=e.evaluate(t,i,o);(null==l||e instanceof _CellRangeExpression&&e._isEmpty)&&(l=0);if(l instanceof FormulaError)throw l;l&&!isPrimitive(l)&&(l=l.value);if(isNumber(l))return l;if(isBoolean(l))return l?1:0;if(isDate(l))return FlexSheet._toOADate(l);if(isString(l)){"'"===l[0]&&(l=l.substr(1));if(l=l.trim()){if(!isNaN(+l))return+l;if(this.isDateValue(l))return FlexSheet._toOADate(new Date(l))}}return changeType(l,DataType.Number)}static toBoolean(e,t,i,o){var l=e.evaluate(t,i,o);(null==l||e instanceof _CellRangeExpression&&e._isEmpty)&&(l=0);if(l instanceof FormulaError)throw l;l&&!isPrimitive(l)&&(l=l.value);if(isBoolean(l))return l;if(isNumber(l))return 0!==l;isString(l)&&"'"===l[0]&&(l=l.substr(1));return changeType(l,DataType.Boolean,"")}static toDate(e,t,i,o){var l=e.evaluate(t,i,o);(null==l||e instanceof _CellRangeExpression&&e._isEmpty)&&(l=0);if(l instanceof FormulaError)throw l;l&&!isPrimitive(l)&&(l=l.value);if(isDate(l))return l;if(isNumber(l))return FlexSheet._fromOADate(l);isString(l)&&"'"===l[0]&&(l=l.substr(1));return changeType(l,DataType.Date,"")}static isDateValue(e){let t,i=["January","February","March","April","May","June","July","August","September","October","November","December","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];!e||e instanceof FormulaError||isPrimitive(e)||(e=e.value);if(!(t=isDate(e))&&isString(e)){"'"===e[0]&&(e=e.substr(1));if(!isNullOrWhiteSpace(e)&&isNaN(e)&&(e.indexOf("/")>0||e.indexOf("-")>0)&&!(t=!isNaN(Date.parse(e))))for(let o in i)if(e.indexOf(i[o])>-1){t=!0;break}}return t}_refersTo(e){return!1}_updateCellRangeExp(e,t,i,o,l,s){return!1}_moveCellRangeExp(e,t,i,o=!1,l=!1){return!1}_updateCellRangeExpForReorderingRows(e){return!1}_updateCellBoundary(e,t){return!1}_getStringExpression(){return null==this._token.value?"":isString(this._token.value)?'"'+this._token.value+'"':this._token.value.toString()}}export class _UnaryExpression extends _Expression{constructor(e,t,i){super(e,t);this._expr=i}evaluate(e,t,i,o=!0,l=!1,s=!0){if(this._expr.token.tokenType===_TokenType.ERROR){if(s)throw this._expr.token.value;return this._expr.token.value}if(this.token.tokenID===_TokenID.SUB){if(!this.evaluated){let o=_Expression.toNumber(this._expr,e,t,i);this.evaluatedValue=isString(o)?NaN:-o}return this.evaluatedValue}if(this.token.tokenID===_TokenID.ADD){if(!this.evaluated){let o=_Expression.toNumber(this._expr,e,t,i);this.evaluatedValue=isString(o)?NaN:+o}return this.evaluatedValue}throw new SyntaxError(_ErrorMessages.BadExpression)}_refersTo(e){return this._expr._refersTo(e)}_updateCellRangeExp(e,t,i,o,l,s){return this._expr._updateCellRangeExp(e,t,i,o,l,s)}_moveCellRangeExp(e,t,i,o=!1,l=!1){return this._expr._moveCellRangeExp(e,t,i,o,l)}_updateCellRangeExpForReorderingRows(e){return this._expr._updateCellRangeExpForReorderingRows(e)}_getStringExpression(){return this.token.tokenID===_TokenID.SUB?(this._inGroup?"(":"")+"-"+this._expr._getStringExpression()+(this._inGroup?")":""):this.token.tokenID===_TokenID.ADD?(this._inGroup?"(":"")+"+"+this._expr._getStringExpression()+(this._inGroup?")":""):""}}export class _BinaryExpression extends _Expression{constructor(e,t,i,o){super(e,t);this._leftExpr=i;this._rightExpr=o}evaluate(e,t,i,o=!0,l=!1,s=!0){let n,r,a,h;if(this.evaluated)return this.evaluatedValue;if(this._leftExpr.token.tokenType===_TokenType.ERROR){if(s)throw this._leftExpr.token.value;return this._leftExpr.token.value}if(this._rightExpr.token.tokenType===_TokenType.ERROR){if(s)throw this._rightExpr.token.value;return this._rightExpr.token.value}let d=_Expression.toString(this._leftExpr,e,t,i),u=_Expression.toString(this._rightExpr,e,t,i);if(this.token.tokenType===_TokenType.CONCAT)return this.evaluatedValue=d+u;let c=this._leftExpr.evaluate(e,t,i),_=this._rightExpr.evaluate(e,t,i);if(c&&!isPrimitive(c)){n=c.format;c=c.value}if(_&&!isPrimitive(_)){r=_.format;_=_.value}let g=_Expression.isDateValue(c),f=_Expression.isDateValue(_),w=g||f;if(w){a=isDate(c)?FlexSheet._toOADate(c):isNumber(c)?c:FlexSheet._toOADate(new Date(c));h=isDate(_)?FlexSheet._toOADate(_):isNumber(_)?_:FlexSheet._toOADate(new Date(_))}else{a=_Expression.toNumber(this._leftExpr,e,t,i);h=_Expression.toNumber(this._rightExpr,e,t,i)}if(this.token.tokenType===_TokenType.COMPARE){let e;this._leftExpr instanceof _CellRangeExpression&&this._leftExpr._isEmpty&&(c=null);this._rightExpr instanceof _CellRangeExpression&&this._rightExpr._isEmpty&&(_=null);let t=null==c,i=null==_;if(t!==i)e=t&&!_||i&&!c?0:t?-1:1;else{let t=typeof c,i=typeof _;if(l&&t!==i){if(this.token.tokenID===_TokenID.NE)return this.evaluatedValue=!0;if(this.token.tokenID!==_TokenID.EQ||"number"!==i&&!f)return this.evaluatedValue=!1}let s="boolean"===t;if(s!==("boolean"===i))e=s?1:-1;else{let l="string"===t,s="string"===i;if(o&&l!==s)e=l?1:-1;else if(0!==c&&isNullOrWhiteSpace(c)||0!==_&&isNullOrWhiteSpace(_))e=c===_?0:c<=_?-1:1;else{isNumber(a)&&(a=this._rounder.round(a));isNumber(h)&&(h=this._rounder.round(h));e=a-h}}}switch(this.token.tokenID){case _TokenID.GT:return this.evaluatedValue=e>0;case _TokenID.LT:return this.evaluatedValue=e<0;case _TokenID.GE:return this.evaluatedValue=e>=0;case _TokenID.LE:return this.evaluatedValue=e<=0;case _TokenID.EQ:return isNaN(e)?this.evaluatedValue=d.toLowerCase()===u.toLowerCase():this.evaluatedValue=0===e;case _TokenID.NE:return isNaN(e)?this.evaluatedValue=d.toLowerCase()!==u.toLowerCase():this.evaluatedValue=0!==e}}if(isString(a)||isString(h))throw new ValueError;switch(this.token.tokenID){case _TokenID.ADD:this.evaluatedValue=a+h;break;case _TokenID.SUB:this.evaluatedValue=a-h;break;case _TokenID.MUL:this.evaluatedValue=a*h;break;case _TokenID.DIV:case _TokenID.PERCENT:if(0===h)throw this.evaluatedValue=new DivideByZeroError;this.evaluatedValue=a/h;break;case _TokenID.DIVINT:if(0===h)throw this.evaluatedValue=new DivideByZeroError;this.evaluatedValue=Math.floor(a/h);break;case _TokenID.MOD:if(0===h)throw this.evaluatedValue=new DivideByZeroError;this.evaluatedValue=Math.floor(a%h);break;case _TokenID.POWER:switch(h){case 0:this.evaluatedValue=1;break;case.5:this.evaluatedValue=Math.sqrt(a);break;case 1:this.evaluatedValue=a;break;case 2:this.evaluatedValue=a*a;break;case 3:this.evaluatedValue=a*a*a;break;case 4:this.evaluatedValue=a*a*a*a;break;default:this.evaluatedValue=Math.pow(a,h)}break;default:this.evaluatedValue=NaN}if(!isNaN(this.evaluatedValue)){w&&(this.evaluatedValue={value:FlexSheet._fromOADate(this.evaluatedValue),format:n||r});return this.evaluatedValue}throw new SyntaxError(_ErrorMessages.BadExpression)}_refersTo(e){return this._leftExpr._refersTo(e)||this._rightExpr._refersTo(e)}_updateCellRangeExp(e,t,i,o,l,s){let n,r=!1;n=this._leftExpr._updateCellRangeExp(e,t,i,o,l,s);r=r||n;n=this._rightExpr._updateCellRangeExp(e,t,i,o,l,s);return r||n}_moveCellRangeExp(e,t,i,o=!1,l=!1){let s,n=!1;s=this._leftExpr._moveCellRangeExp(e,t,i,o,l);n=n||s;s=this._rightExpr._moveCellRangeExp(e,t,i,o,l);return n||s}_updateCellRangeExpForReorderingRows(e){let t,i=!1;t=this._leftExpr._updateCellRangeExpForReorderingRows(e);i=i||t;t=this._rightExpr._updateCellRangeExpForReorderingRows(e);return i||t}_getStringExpression(){let e=_OpMap[this.token.tokenID]||"",t=this._leftExpr._getStringExpression(),i=this.token.tokenID!==_TokenID.PERCENT?this._rightExpr._getStringExpression():"";return(this._inGroup?"(":"")+t+e+i+(this._inGroup?")":"")}}export class _CellRangeExpression extends _Expression{constructor(e,t,i,o,l=!0,s=!1,n=!1,r=!1,a=!1,h){super(e);this._cells=new CellRange(t.topRow,t.leftCol,t.bottomRow,t.rightCol);this._sheetRef=i;this._flex=o;this._evalutingRange={};this._isCellRange=l;this._absRow=s;this._absCol=n;this._absRow2=r;this._absCol2=a;this._isWholeRow=h}evaluate(e,t,i,o=!0,l=!1,s=!0){if(!this.evaluated){let o=this._extendRange(i),l=this._getCellValue(o,i,e,t,s,!0);this._isEmpty=null==l;this.evaluatedValue=l}return null==this.evaluatedValue?0:this.evaluatedValue}getValues(e=!0,t,i,o=!0){let l=[];if(!(i=this._getSheet()||i||this._flex.selectedSheet))return null;let s=this._extendRange(i),n=null==t||isNaN(+t)?s.leftCol:t,r=null==t||isNaN(+t)?s.rightCol:t,a=new CellRange;for(let t=s.topRow;t<=s.bottomRow&&t<i.grid.rows.length;t++)if(e||!1!==i.grid.rows[t].isVisible)for(let e=n;e<=r&&e<i.grid.columns.length;e++){a.setRange(t,e);let s=this._getCellValue(a,i,void 0,void 0,o);!s||s instanceof FormulaError||isPrimitive(s)||(s=s.value);l.push(s)}return l}getValuesWithTwoDimensions(e=!0,t){var i,o,l,s,n,r=[],a=0,h=0;if(!(t=this._getSheet()||t||this._flex.selectedSheet))return null;for(l=(n=this._extendRange(t)).topRow;l<=n.bottomRow&&l<t.grid.rows.length;l++)if(e||!1!==t.grid.rows[l].isVisible){o=[];h=0;for(s=n.leftCol;s<=n.rightCol&&s<t.grid.columns.length;s++)if(e||!1!==t.grid.columns[s].isVisible){!(i=this._getCellValue(new CellRange(l,s),t))||i instanceof FormulaError||isPrimitive(i)||(i=i.value);o[h]=i;h++}else h++;r[a]=o;a++}else a++;return r}get cells(){return this._cells}get sheetRef(){return this._sheetRef}_getCellValue(e,t,i,o,l=!0,s){var n,r,a;if(!(t=this._getSheet()||t||this._flex.selectedSheet))return null;const h=t._currentMergedRanges;for(let t of h)if(e._row>=t._row&&e._row2<=t._row2&&e._col>=t._col&&e._col2<=t._col2&&(e._row!==t._row||e._col!==t._col))return null;if(e.isSingleCell){r=e.row;a=e.col}else{if(null!=i&&i>=e.topRow&&i<=e.bottomRow&&e.col===e.col2){r=i;a=e.col}if(null!=o&&o>=e.leftCol&&o<=e.rightCol&&e.row===e.row2){r=e.row;a=o}}if(null==r||null==a)throw new ReferenceError(_ErrorMessages.InvalidCellRef);n=t.name+":"+r+","+a+"-"+r+","+a;if(this._evalutingRange[n])throw new SyntaxError(_ErrorMessages.CircRef);try{if(this._flex){this._evalutingRange[n]=!0;let e=t===this._flex.selectedSheet?this._flex:t.grid;if(r<e.rows.length&&a<e.columns.length){let e=t.grid.columns[a],i=this._flex.getCellValue(r,a,!!s&&0,t);if(i instanceof FormulaError){if(l)throw i;return i}e.dataMap&&!s&&(i=e.dataMap.getDisplayValue(i));return i}return 0}}finally{delete this._evalutingRange[n]}}_getSheet(){if(!this._sheetRef)return null;let e=this._flex._getSheet(this._sheetRef);if(!e)throw new ReferenceError(_ErrorMessages.InvalidSheetRef);return e}_refersTo(e){return e.contains(this.cells)}_updateCellRangeExp(e,t,i,o,l,s){let n=this._cells,r=!1;if(this._tableParams&&this._tableParams.length>0)return!1;if(e===this._flex.selectedSheetIndex){if(this._sheetRef&&this._sheetRef.toLowerCase()!==this._flex.selectedSheet.name.toLowerCase())return!1}else if(!this._sheetRef||this._sheetRef.toLowerCase()!==this._flex.selectedSheet.name.toLowerCase())return!1;if(l){if(null==this._isWholeRow||this._isWholeRow){if(s&&(n.leftCol>s.rightCol||n.rightCol<s.leftCol))return!1;if(o){if(n.topRow>=t){n.row+=i;n.row2+=i;r=!0}else if(n.topRow<t&&n.bottomRow>=t){n.row2+=i;r=!0}}else if(n.topRow>t){n.row-=i;n.row2-=i;r=!0}else if(n.isSingleCell){if(n.row>=t-i+1){n.row=t-i+1;n.row2=t-i+1;r=!0}}else if(n.topRow>=t-i+1){n.row=t-i+1;n.row2-=i;r=!0}else if(n.topRow<t-i+1&&n.bottomRow>=t-i+1){n.bottomRow>t?n.row2-=i:n.row2=t-i;r=!0}}}else if(null==this._isWholeRow||!this._isWholeRow){if(s&&(n.topRow>s.bottomRow||n.bottomRow<s.topRow))return!1;if(o){if(n.leftCol>=t){n.col+=i;n.col2+=i;r=!0}else if(n.leftCol<t&&n.rightCol>=t){n.col2+=i;r=!0}}else if(n.leftCol>t){n.col-=i;n.col2-=i;r=!0}else if(n.isSingleCell){if(n.col>=t-i+1){n.col=t-i+1;n.col2=t-i+1;r=!0}}else if(n.leftCol>=t-i+1){n.col=t-i+1;n.col2-=i;r=!0}else if(n.leftCol<t-i+1&&n.rightCol>=t-i+1){n.rightCol>t?n.col2-=i:n.col2=t-i;r=!0}}return r}_moveCellRangeExp(e,t,i,o=!1,l=!1){let s,n,r=this._cells,a=!1;if(this._tableParams&&this._tableParams.length>0)return!1;if(this._flex.selectedSheetIndex!=e&&(!this._sheetRef||this._sheetRef.toLowerCase()!==this._flex.selectedSheet.name.toLowerCase()))return!1;if(!l&&this._flex.selectedSheetIndex==e&&this._sheetRef&&this._sheetRef.toLowerCase()!==this._flex.selectedSheet.name.toLowerCase())return!1;s=i.topRow-t.topRow;n=i.leftCol-t.leftCol;if(l){if(0!==s&&(null==this._isWholeRow||this._isWholeRow)){r.row+=l&&this._absRow?0:s;r.row2+=this._isCellRange?l&&this._absRow2?0:s:l&&this._absRow?0:s;a=!0}if(0!==n&&(null==this._isWholeRow||!this._isWholeRow)){r.col+=l&&this._absCol?0:n;r.col2+=this._isCellRange?l&&this._absCol2?0:n:l&&this._absCol?0:n;a=!0}return a}if(t.contains(r)){if(0!==s&&(null==this._isWholeRow||this._isWholeRow)){r.row+=s;r.row2+=s;a=!0}if(0!==n&&(null==this._isWholeRow||!this._isWholeRow)){r.col+=n;r.col2+=n;a=!0}}else if(t.intersects(r)){if(t.intersectsRow(r)){var h=t.topRow>=r.topRow&&t.bottomRow<=r.bottomRow;if(0!==s&&(null==this._isWholeRow||this._isWholeRow))if(t.topRow<=r.topRow){if(s<0){r.row+=s;a=!0}else if(s>0){var d=h&&i.bottomRow<r.bottomRow;if(o&&!d){t.topRow<r.topRow&&(r.row-=r.topRow-t.topRow);r.row2-=t.rowSpan;a=!0}}}else if(t.bottomRow>=r.bottomRow){if(s>0){r.row2+=s;a=!0}else if(s<0){var u=h&&i.topRow>r.topRow;if(o&&!u){t.bottomRow>r.bottomRow&&(r.row2+=t.bottomRow-r.bottomRow);r.row+=t.rowSpan;a=!0}}}else if(o){s<0&&i.topRow<=r.topRow&&(r.row+=t.rowSpan);s>0&&i.bottomRow>=r.bottomRow&&(r.row2-=t.rowSpan);a=!0}}if(t.intersectsColumn(r)&&0!==n&&(null==this._isWholeRow||!this._isWholeRow))if(t.leftCol<=r.leftCol){if(n<0){r.col+=n;a=!0}else if(n>0&&o){t.leftCol<r.leftCol&&(r.col-=r.leftCol-t.leftCol);r.col2-=t.columnSpan;a=!0}}else if(t.rightCol>=r.rightCol){if(n>0){r.col2+=n;a=!0}else if(n<0&&o){t.rightCol>r.rightCol&&(r.col2+=t.rightCol-r.rightCol);r.col+=t.columnSpan;a=!0}}else if(o){n<0?r.col+=t.columnSpan:r.col2-=t.columnSpan;a=!0}}else if(o){if(null==this._isWholeRow||this._isWholeRow)if(r.row!==r.row2&&r.containsRow(i.topRow)){s<0?r.row2+=i.rowSpan:r.row=Math.max(0,r.row-i.rowSpan);a=!0}else{if(r.topRow>=i.topRow&&r.topRow<t.topRow&&s<0){r.row+=i.rowSpan;r.row2+=i.rowSpan;a=!0}if(r.topRow>t.bottomRow&&r.bottomRow<=i.bottomRow&&s>0){r.row-=i.rowSpan;r.row2-=i.rowSpan;a=!0}}if(null==this._isWholeRow||!this._isWholeRow)if(r.col!==r.col2&&r.containsColumn(i.leftCol)){n<0?r.col2+=i.columnSpan:r.col=Math.max(0,r.col-i.columnSpan);a=!0}else{if(r.leftCol>=i.leftCol&&r.leftCol<t.leftCol&&n<0){r.col+=i.columnSpan;r.col2+=i.columnSpan;a=!0}if(r.leftCol>t.rightCol&&r.rightCol<=i.rightCol&&n>0){r.col-=i.columnSpan;r.col2-=i.columnSpan;a=!0}}}return a}_updateCellRangeExpForReorderingRows(e){let t,i=this._cells;if(null==this._isWholeRow||this._isWholeRow){(t=this._cells.row+e)<0?t=0:t>=this._flex.rows.length&&(t=this._flex.rows.length-1);i.row=t;this._isCellRange&&((t=this._cells.row2+e)<0?t=0:t>=this._flex.rows.length&&(t=this._flex.rows.length-1));i.row2=t}return!0}_updateCellBoundary(e,t){let i=this._cells;if(this._sheetRef&&this._sheetRef.toLowerCase()!==this._flex.selectedSheet.name.toLowerCase())return!1;if(i.row===i.row2&&i.row===e&&t===i.col2+1){i.col2+=1;return!0}if(i.col===i.col2&&i.col===t&&e===i.row2+1){i.row2+=1;return!0}return!1}_getStringExpression(){if(this._tableParams&&this._tableParams.length>0)return this._getTableParamsStringExpression();let e=this._quoteName(this._sheetRef);return this._definedName?this._definedName:(e?e+"!":"")+Workbook.xlsxAddress(this._cells.row,this._cells.col,this._absRow,this._absCol,this._isWholeRow)+(this._isCellRange?":"+Workbook.xlsxAddress(this._cells.row2,this._cells.col2,this._absRow2,this._absCol2,this._isWholeRow):"")}_quoteName(e){e&&(/[\s\-!\$]/.test(e)||/^\d/.test(e))&&(e=`'${e}'`);return e}_getTableParamsStringExpression(){let e,t=0,i="",o=this._tableParams.length,l=!1;if(!this._defTableParameterProvided){for(;t<o;t++)if("#"===(e=this._tableParams[t])[0]){i+="["+e+"]";t<o-1&&(i+=", ")}else if(l)i+=": ["+e+"]";else{i+="["+e+"]";l=!0}o>1&&(i="["+i+"]")}this._tableName&&(i=this._tableName+i);return i}_extendRange(e){let t=this._cells.clone();if(null!=this._isWholeRow)if(this._isWholeRow){t.col=0;t.col2=e?e.grid.columns.length-1:this._flex.columns.length-1}else{t.row=0;t.row2=e?e.grid.rows.length-1:this._flex.rows.length-1}return t}}export class _FunctionExpression extends _Expression{constructor(e,t,i,o,l=!0){super(e);this._funcId=t;this._funcDefinition=i;this._params=o;this._needCacheEvaluatedVal=l}evaluate(e,t,i){if(!this._needCacheEvaluatedVal)return this._funcDefinition.func(this._params,i,e,t);this.evaluated||(this.evaluatedValue=this._funcDefinition.func(this._params,i,e,t));return this.evaluatedValue}_refersTo(e){if(this._params)for(let t=0;t<this._params.length;t++)if(this._params[t]._refersTo(e))return!0;return!1}_updateCellRangeExp(e,t,i,o,l,s){let n,r,a,h=!1;if(this._params&&this._params.length>0)for(n=0;n<this._params.length;n++){a=(r=this._params[n])._updateCellRangeExp(e,t,i,o,l,s);h||(h=h||a)}return h}_moveCellRangeExp(e,t,i,o=!1,l=!1){let s,n,r,a=!1;if(this._params&&this._params.length>0)for(s=0;s<this._params.length;s++){r=(n=this._params[s])._moveCellRangeExp(e,t,i,o,l);a||(a=a||r)}return a}_updateCellRangeExpForReorderingRows(e){let t,i,o,l=!1;if(this._params&&this._params.length>0)for(t=0;t<this._params.length;t++){o=(i=this._params[t])._updateCellRangeExpForReorderingRows(e);l||(l=l||o)}return l}_updateCellBoundary(e,t){let i;return!!(this._params&&1===this._params.length&&(i=this._params[0])instanceof _CellRangeExpression)&&i._updateCellBoundary(e,t)}_getStringExpression(){return"true"===this._funcId||"false"===this._funcId?this._funcId.toUpperCase():this._funcId+this._parseParamsExpToString()}_parseParamsExpToString(){let e,t,i;if(this._params&&this._params.length>0){i="";for(e=0;e<this._params.length;e++){0===e&&(i+="(");i+=(t=this._params[e])._getStringExpression();e<this._params.length-1?i+=", ":i+=")"}return i}return"()"}}export class _CalcEngine{constructor(e){this._expressionCache={};this._idChars="_$:!";this._functionTable={};this._cacheSize=0;this._tableRefStart=!1;this.unknownFunction=new Event;this._owner=e;this._buildSymbolTable();this._registerAggregateFunction();this._registerMathFunction();this._registerLogicalFunction();this._registerTextFunction();this._registerDateFunction();this._registLookUpReferenceFunction();this._registFinacialFunction();this._registAddressRelatedFunction();this._registerIsFunctions()}onUnknownFunction(e,t){var i,o;if(t&&t.length>0){i=[];for(var l=0;l<t.length;l++)i[l]=t[l].evaluate(this._rowIndex,this._columnIndex)}o=new UnknownFunctionEventArgs(e,i);this.unknownFunction.raise(this,o);if(null!=o.value)return new _Expression(this,o.value);throw new NameError(_ErrorMessages.UnkFuncName(e))}evaluate(e,t,i,o,l,s=!0,n=!1){var r,a;if(!this._owner.enableFormulas)return e;try{if(_isFormula(e)){this._containsCellRef=!1;this._rowIndex=o;this._columnIndex=l;this._sheet=i||this._owner.selectedSheet;a=(r=this._checkCache(e,s,n)).evaluate(o,l,i,s,n);for(;a instanceof _Expression;)a=a.evaluate(o,l,i,s,n);return t&&isPrimitive(a)?Globalize.format(a,t):a}return e||""}catch(e){var h=e instanceof FormulaError?e:new UnknownError(e);r&&(r.evaluatedValue=h);return h}}addCustomFunction(e,t,i,o){var l=this;e=e.toLowerCase();this._functionTable[e]=new _FunctionDefinition(e=>{var i,o=[];if(e&&e.length>0)for(var s=0;s<e.length;s++){i=e[s];o[s]=i instanceof _CellRangeExpression?i.cells:i.evaluate(l._rowIndex,l._columnIndex)}return t.apply(l,o)},o,i)}addFunction(e,t,i,o){var l=this;e=e.toLowerCase();this._functionTable[e]=new _FunctionDefinition(e=>{var i,o=[];if(e&&e.length>0){let t=l._sheet;for(var s=0;s<e.length;s++){i=e[s];o[s]=i instanceof _CellRangeExpression?i.getValuesWithTwoDimensions(void 0,t):[[i.evaluate(l._rowIndex,l._columnIndex)]]}}return t.apply(l,o)},o,i)}clearExpressionCache(){this._expressionCache=null;this._expressionCache={};this._cacheSize=0}round(e){let t=this._owner.calculationPrecision;if(e.toString().indexOf(".")<0)return e;if(t<0)return e;t>20&&(t=20);let i=_CalcEngine.PowOf10[t];return e>=0?Math.round(e*i)/i:-Math.round(Math.abs(e)*i)/i}parse(e){if(isNumber(e)){this._token=new _Token(e,_TokenID.END,_TokenType.GROUP);return new _Expression(this,new _Token(e,_TokenID.ATOM,_TokenType.LITERAL))}this._expression=e;this._expressLength=e?e.length:0;this._pointer=0;this._expressLength>0&&"="===this._expression[0]&&this._pointer++;return this._parseExpression()}_buildSymbolTable(){if(!this._tokenTable){this._tokenTable={};this._addToken("+",_TokenID.ADD,_TokenType.ADDSUB);this._addToken("-",_TokenID.SUB,_TokenType.ADDSUB);this._addToken("(",_TokenID.OPEN,_TokenType.GROUP);this._addToken(")",_TokenID.CLOSE,_TokenType.GROUP);this._addToken("*",_TokenID.MUL,_TokenType.MULDIV);this._addToken(",",_TokenID.COMMA,_TokenType.GROUP);this._addToken(".",_TokenID.PERIOD,_TokenType.GROUP);this._addToken("/",_TokenID.DIV,_TokenType.MULDIV);this._addToken("\\",_TokenID.DIVINT,_TokenType.MULDIV);this._addToken("%",_TokenID.PERCENT,_TokenType.MULDIV);this._addToken("=",_TokenID.EQ,_TokenType.COMPARE);this._addToken(">",_TokenID.GT,_TokenType.COMPARE);this._addToken("<",_TokenID.LT,_TokenType.COMPARE);this._addToken("^",_TokenID.POWER,_TokenType.POWER);this._addToken("<>",_TokenID.NE,_TokenType.COMPARE);this._addToken(">=",_TokenID.GE,_TokenType.COMPARE);this._addToken("<=",_TokenID.LE,_TokenType.COMPARE);this._addToken("&",_TokenID.CONCAT,_TokenType.CONCAT);this._addToken("[",_TokenID.OPEN,_TokenType.SQUAREBRACKETS);this._addToken("]",_TokenID.CLOSE,_TokenType.SQUAREBRACKETS)}}_registerAggregateFunction(){var e=this;e._functionTable.sum=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.Sum,t,i));e._functionTable.average=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.Avg,t,i));e._functionTable.max=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.Max,t,i));e._functionTable.min=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.Min,t,i));e._functionTable.var=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.Var,t,i));e._functionTable.varp=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.VarPop,t,i));e._functionTable.stdev=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.Std,t,i));e._functionTable.stdevp=new _FunctionDefinition((t,i)=>e._getAggregateResult(Aggregate.StdPop,t,i));e._functionTable.count=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.Count,t,i));e._functionTable.counta=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.CountA,t,i));e._functionTable.countblank=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.CountBlank,t,i));e._functionTable.countif=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.CountIf,t,i),2,2);e._functionTable.countifs=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.CountIfs,t,i),254,2);e._functionTable.sumif=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.SumIf,t,i),3,2);e._functionTable.sumifs=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.SumIfs,t,i),255,2);e._functionTable.rank=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.Rank,t,i),3,2);e._functionTable.product=new _FunctionDefinition((t,i)=>e._getFlexSheetAggregateResult(_FlexSheetAggregate.Product,t,i),255,1);e._functionTable.subtotal=new _FunctionDefinition((t,i)=>e._handleSubtotal(t,i),255,2);e._functionTable.dcount=new _FunctionDefinition((t,i)=>e._handleDCount(t,i),3,3);e._functionTable.sumproduct=new _FunctionDefinition((t,i)=>e._getSumProduct(t,i),255,1)}_registerMathFunction(){var e=this;e._functionTable.pi=new _FunctionDefinition(()=>Math.PI,0,0);e._functionTable.rand=new _FunctionDefinition(()=>Math.random(),0,0);e._functionTable.power=new _FunctionDefinition((t,i)=>Math.pow(_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i),_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i)),2,2);e._functionTable.atan2=new _FunctionDefinition((t,i)=>{var o=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i),l=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i);if(0===o&&0===l)throw new DivideByZeroError(_ErrorMessages.Atan2ArgsLessThanZero);return Math.atan2(l,o)},2,2);e._functionTable.mod=new _FunctionDefinition((t,i)=>{let o=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i),l=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i),s=Math.abs(l);if(0===s)throw new DivideByZeroError;let n=Math.abs(o)%s;l<0&&(n=-n);return n},2,2);e._functionTable.trunc=new _FunctionDefinition((t,i)=>{var o,l,s,n=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i),r=2===t.length?_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i):0;if(0===r){s="n0";l=n>=0?Math.floor(n):Math.ceil(n)}else{s="n"+((r=r>0?Math.floor(r):Math.ceil(r))>0?r:0);o=Math.pow(10,r);l=n>=0?Math.floor(n*o)/o:Math.ceil(n*o)/o}if(null!=l)return{value:l,format:s}},2,1);["ceiling","floor"].forEach(t=>{e._functionTable[t]=new _FunctionDefinition((i,o)=>{var l,s,n=_Expression.toNumber(i[0],e._rowIndex,e._columnIndex,o),r=2===i.length?_Expression.toNumber(i[1],e._rowIndex,e._columnIndex,o):1;if(isNaN(n))throw new ValueError(_ErrorMessages.InvalidParameter("number"));if(isNaN(r))throw new ValueError(_ErrorMessages.InvalidParameter("significance"));if(n>0&&r<0)throw new NumericError(_ErrorMessages.InvalidParameter("significance"));if(0===n||0===r)return 0;s=1;if(0!==(l=r-Math.floor(r)))for(;l<1;){s*=10;l*=10}return r*s*("ceiling"===t?Math.ceil(n/r):Math.floor(n/r))/s},2,1)});["round","rounddown","roundup"].forEach(t=>{e._functionTable[t]=new _FunctionDefinition((i,o)=>{var l,s,n,r=_Expression.toNumber(i[0],e._rowIndex,e._columnIndex,o),a=_Expression.toNumber(i[1],e._rowIndex,e._columnIndex,o);if(0===a){switch(t){case"rounddown":l=r>=0?Math.floor(r):Math.ceil(r);break;case"roundup":l=r>=0?Math.ceil(r):Math.floor(r);break;case"round":l=(r>=0?1:-1)*Math.round(Math.abs(r));break;default:l=Math.floor(r)}s="n0"}else{a=a>0?Math.floor(a):Math.ceil(a);n=Math.pow(10,a);switch(t){case"rounddown":l=r>=0?Math.floor(r*n)/n:Math.ceil(r*n)/n;break;case"roundup":l=r>=0?Math.ceil(r*n)/n:Math.floor(r*n)/n;break;case"round":l=(r>=0?1:-1)*Math.round(Math.abs(r)*n)/n}s="n"+(a>0?a:0)}if(null!=l)return{value:l,format:s}},2,2)});["abs","acos","asin","atan","cos","exp","ln","sin","sqrt","tan"].forEach(t=>{e._functionTable[t]=new _FunctionDefinition((i,o)=>"ln"===t?Math.log(_Expression.toNumber(i[0],e._rowIndex,e._columnIndex,o)):Math[t](_Expression.toNumber(i[0],e._rowIndex,e._columnIndex,o)),1,1)})}_registerLogicalFunction(){var e=this;e._functionTable.and=new _FunctionDefinition((t,i)=>{var o,l=!0;for(o=0;o<t.length&&(l=l&&_Expression.toBoolean(t[o],e._rowIndex,e._columnIndex,i));o++);return l},Number.MAX_VALUE,1);e._functionTable.or=new _FunctionDefinition((t,i)=>{var o,l=!1;for(o=0;o<t.length&&!(l=l||_Expression.toBoolean(t[o],e._rowIndex,e._columnIndex,i));o++);return l},Number.MAX_VALUE,1);e._functionTable.not=new _FunctionDefinition((t,i)=>!_Expression.toBoolean(t[0],e._rowIndex,e._columnIndex,i),1,1);e._functionTable.if=new _FunctionDefinition((t,i)=>3===t.length?_Expression.toBoolean(t[0],e._rowIndex,e._columnIndex,i)?t[1].evaluate(e._rowIndex,e._columnIndex,i):t[2].evaluate(e._rowIndex,e._columnIndex,i):!!_Expression.toBoolean(t[0],e._rowIndex,e._columnIndex,i)&&t[1].evaluate(e._rowIndex,e._columnIndex,i),3,2);e._functionTable.true=new _FunctionDefinition(()=>!0,0,0);e._functionTable.false=new _FunctionDefinition(()=>!1,0,0)}_registerTextFunction(){var e=this;e._functionTable.char=new _FunctionDefinition((t,i)=>{var o,l="";for(o=0;o<t.length;o++)l+=String.fromCharCode(_Expression.toNumber(t[o],e._rowIndex,e._columnIndex,i));return l},Number.MAX_VALUE,1);e._functionTable.code=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i);return o&&o.length>0?o.charCodeAt(0):-1},1,1);const t=new _FunctionDefinition((t,i)=>{let o="";t.forEach(t=>{if(t instanceof _CellRangeExpression){const e=t.getValues(!0,void 0,i);o=o.concat(e.reduce((e,t)=>e+""+t,""))}else o=o.concat(_Expression.toString(t,e._rowIndex,e._columnIndex,i))});return o},Number.MAX_VALUE,1);e._functionTable.concat=t;e._functionTable.concatenate=t;e._functionTable.left=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),l=null==t[1]?1:Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i));return o&&o.length>0?o.slice(0,l):null},2,1);e._functionTable.right=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),l=null==t[1]?1:Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i));return o&&o.length>0?l?o.slice(-l):"":null},2,1);e._functionTable.find=new _FunctionDefinition((t,i)=>{var o,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),s=_Expression.toString(t[1],e._rowIndex,e._columnIndex,i),n=null!=t[2]?asInt(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,i)):0;return null!=s&&null!=l&&(o=!isNaN(n)&&n>0&&n<=s.length?s.indexOf(l,n-1):s.indexOf(l))>-1?o+1:-1},3,2);e._functionTable.search=new _FunctionDefinition((t,i)=>{var o,l,s,n=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),r=_Expression.toString(t[1],e._rowIndex,e._columnIndex,i),a=null!=t[2]?asInt(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,i)):0;if(null!=r&&null!=n){l=new RegExp(n,"i");if(!isNaN(a)&&a>0&&a<r.length){r=r.substring(a-1);o=a}else o=1;if((s=r.search(l))>-1)return s+o}return-1},3,2);e._functionTable.len=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i);return null!=o?o.length:-1},1,1);e._functionTable.mid=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),l=Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i)),s=Math.floor(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,i));return o&&o.length>0&&l>0?o.substr(l-1,s):null},3,3);e._functionTable.lower=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i);return o&&o.length>0?o.toLowerCase():null},1,1);e._functionTable.upper=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i);return o&&o.length>0?o.toUpperCase():null},1,1);e._functionTable.proper=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i);if(o&&o.length>0){o=(o=o.toLowerCase())[0].toUpperCase()+o.substring(1);for(var l=1;l<o.length;l++)if(rgLetter.test(o[l])&&!rgLetter.test(o[l-1])){o=o.substr(0,l)+o[l].toUpperCase()+o.substring(l+1);l++}return o}return null},1,1);e._functionTable.trim=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i);return o&&o.length>0?o.trim().replace(/\s+/gm," "):null},1,1);e._functionTable.replace=new _FunctionDefinition((t,i)=>{var o=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),l=Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i)),s=Math.floor(_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,i)),n=_Expression.toString(t[3],e._rowIndex,e._columnIndex,i);return o&&o.length>0&&l>0?o.substring(0,l-1)+n+o.slice(l-1+s):null},4,4);e._functionTable.substitute=new _FunctionDefinition((t,i)=>{var o,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),s=_Expression.toString(t[1],e._rowIndex,e._columnIndex,i),n=_Expression.toString(t[2],e._rowIndex,e._columnIndex,i),r=4===t.length?_Expression.toNumber(t[3],e._rowIndex,e._columnIndex,i):null,a=0;if(null!=r&&r<1||isNaN(r))throw new ValueError(_ErrorMessages.InvalidParameter("instance_num"));if(l&&l.length>0&&s&&s.length>0){o=new RegExp(s,"g");return l.replace(o,e=>{a++;if(null!=r){r=Math.floor(r);return a===r?n:e}return n})}return null},4,3);e._functionTable.rept=new _FunctionDefinition((t,i)=>{var o,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i),s=Math.floor(_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i)),n="";if(l&&l.length>0&&s>0)for(o=0;o<s;o++)n=n.concat(l);return n},2,2);e._functionTable.text=new _FunctionDefinition((t,i)=>{var o,l=t[0].evaluate(e._rowIndex,e._columnIndex,i),s=_Expression.toString(t[1],e._rowIndex,e._columnIndex,i);l&&!isPrimitive(l)&&(l=l.value);if(isDate(l))s=Workbook._fromXlsxDateFormat(s);else{let n=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i);if(!isNumber(n)||isNaN(n))return l;if((o=s.match(/^(\d+)(\.\d+)?\E\+(\d+)(\.\d+)?$/))&&5===o.length)return e._parseToScientificValue(n,o[1],o[2],o[3],o[4]);if(/M{1,4}|d{1,4}|y{1,4}/i.test(s)){s=Workbook._fromXlsxDateFormat(s);l=FlexSheet._fromOADate(n)}else s&&!/[ncpfdg]\d?/i.test(s)&&(s=Workbook.fromXlsxFormat(s)[0])}if(isDate(l))switch(s){case"d":return l.getDate();case"M":return l.getMonth()+1;case"y":s="yy";break;case"yyy":s="yyyy"}return Globalize.format(l,s)},2,2);e._functionTable.value=new _FunctionDefinition((t,i)=>{var o,l=_Expression.toString(t[0],e._rowIndex,e._columnIndex,i);if((l=l.replace(/(\,\d{3})/g,e=>e.substring(1))).length>0){if(l[0]===culture.Globalize.numberFormat.currency.symbol)return+(l=l.substring(1));if("%"===l[l.length-1])return+(l=l.substring(0,l.length-1))/100}o=+l;return isNaN(o)?_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i):o},1,1);e._functionTable.exact=new _FunctionDefinition((t,i)=>{return _Expression.toString(t[0],e._rowIndex,e._columnIndex,i)==_Expression.toString(t[1],e._rowIndex,e._columnIndex,i)},2,2)}_registerDateFunction(){var e=this;e._functionTable.now=new _FunctionDefinition(()=>({value:new Date,format:"M/d/yyyy h:mm"}),0,0);e._functionTable.today=new _FunctionDefinition(()=>{var e=new Date;return{value:new Date(e.getFullYear(),e.getMonth(),e.getDate()),format:"M/d/yyyy"}},0,0);e._functionTable.year=new _FunctionDefinition((t,i)=>{if(!_Expression.toString(t[0],e._rowIndex,e._columnIndex,i).trim())return 1900;var o=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,i);return o&&!isPrimitive(o)?o.value:isDate(o)?o.getFullYear():1900},1,1);e._functionTable.month=new _FunctionDefinition((t,i)=>{if(!_Expression.toString(t[0],e._rowIndex,e._columnIndex,i).trim())return 1;var o=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,i);return!isPrimitive(o)&&o?o.value:isDate(o)?o.getMonth()+1:1},1,1);e._functionTable.day=new _FunctionDefinition((t,i)=>{if(!_Expression.toString(t[0],e._rowIndex,e._columnIndex,i))return 0;var o=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,i);return o&&!isPrimitive(o)?o.value:isDate(o)?o.getDate():0},1,1);e._functionTable.hour=new _FunctionDefinition((t,i)=>{var o=t[0].evaluate(e._rowIndex,e._columnIndex,i);if(isNumber(o)&&!isNaN(o))return Math.floor(24*(o-Math.floor(o)));if(isDate(o))return o.getHours();(o=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,i))&&!isPrimitive(o)&&(o=o.value);if(isDate(o))return o.getHours();throw new ValueError(_ErrorMessages.InvalidParameter("serial_number"))},1,1);e._functionTable.time=new _FunctionDefinition((t,i)=>{var o=t[0].evaluate(e._rowIndex,e._columnIndex,i),l=t[1].evaluate(e._rowIndex,e._columnIndex,i),s=t[2].evaluate(e._rowIndex,e._columnIndex,i);if(isNumber(o)&&isNumber(l)&&isNumber(s)){o%=24;l%=60;s%=60;return{value:new Date(0,0,0,o,l,s),format:"h:mm tt"}}throw new ValueError(_ErrorMessages.InvalidParameters)},3,3);e._functionTable.date=new _FunctionDefinition((t,i)=>{var o=t[0].evaluate(e._rowIndex,e._columnIndex,i),l=t[1].evaluate(e._rowIndex,e._columnIndex,i),s=t[2].evaluate(e._rowIndex,e._columnIndex,i);if(isNumber(o)&&isNumber(l)&&isNumber(s))return{value:new Date(o,l-1,s),format:"M/d/yyyy"};throw new ValueError(_ErrorMessages.InvalidParameters)},3,3);e._functionTable.datedif=new _FunctionDefinition((t,i)=>{var o,l,s,n,r,a=_Expression.toDate(t[0],e._rowIndex,e._columnIndex,i),h=_Expression.toDate(t[1],e._rowIndex,e._columnIndex,i),d=t[2].evaluate(e._rowIndex,e._columnIndex,i);a&&!isPrimitive(a)&&(a=a.value);h&&!isPrimitive(h)&&(h=h.value);if(isDate(a)&&isDate(h)&&isString(d)){if((o=a.getTime())>(l=h.getTime()))throw new NumericError(_ErrorMessages.InvalidParameter("start_date"));s=h.getDate()-a.getDate();n=h.getMonth()-a.getMonth();r=h.getFullYear()-a.getFullYear();switch(d.toUpperCase()){case"Y":return n>0?r:n<0?r-1:s>=0?r:r-1;case"M":return s>=0?12*r+n:12*r+n-1;case"D":return(l-o)/864e5;case"YM":return(n=s>=0?12*r+n:12*r+n-1)%12;case"YD":return n>0?(new Date(a.getFullYear(),h.getMonth(),h.getDate()).getTime()-a.getTime())/864e5:n<0?(new Date(a.getFullYear()+1,h.getMonth(),h.getDate()).getTime()-a.getTime())/864e5:s>=0?s:(new Date(a.getFullYear()+1,h.getMonth(),h.getDate()).getTime()-a.getTime())/864e5;case"MD":return s>=0?s:s=new Date(h.getFullYear(),h.getMonth(),0).getDate()-new Date(h.getFullYear(),h.getMonth()-1,1).getDate()+1+s;default:throw new NumericError(_ErrorMessages.InvalidParameter("unit"))}}throw new ValueError(_ErrorMessages.InvalidParameters)},3,3)}_registLookUpReferenceFunction(){var e=this;e._functionTable.column=new _FunctionDefinition((t,i,o,l)=>{var s;if(null==t)return l+1;s=t[0];if((s=e._ensureNonFunctionExpression(s,i))instanceof _CellRangeExpression)return s.cells.col+1;throw new SyntaxError(_ErrorMessages.InvalidCellRef)},1,0);e._functionTable.columns=new _FunctionDefinition((t,i)=>{var o=t[0];if((o=e._ensureNonFunctionExpression(o,i))instanceof _CellRangeExpression)return o.cells.columnSpan;throw new SyntaxError(_ErrorMessages.InvalidCellRef)},1,1);e._functionTable.row=new _FunctionDefinition((t,i,o,l)=>{var s;if(null==t)return o+1;s=t[0];if((s=e._ensureNonFunctionExpression(s,i))instanceof _CellRangeExpression)return s.cells.row+1;throw new SyntaxError(_ErrorMessages.InvalidCellRef)},1,0);e._functionTable.rows=new _FunctionDefinition((t,i)=>{var o=t[0];if((o=e._ensureNonFunctionExpression(o,i))instanceof _CellRangeExpression)return o.cells.rowSpan;throw new SyntaxError(_ErrorMessages.InvalidCellRef)},1,1);e._functionTable.choose=new _FunctionDefinition((t,i)=>{var o=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i);if(isNaN(o))throw new ValueError(_ErrorMessages.InvalidParameter("index_num"));if(o<1||o>=t.length)throw new ValueError(_ErrorMessages.ParameterIsOutOfRange("index_num"));return t[o=Math.floor(o)].evaluate(e._rowIndex,e._columnIndex,i)},255,2);e._functionTable.index=new _FunctionDefinition((t,i)=>{var o,l=t[0],s=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i),n=null!=t[2]?_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,i):0;if(isNaN(s)||s<0)throw new ValueError(_ErrorMessages.InvalidParameter("row_num"));if(isNaN(n)||n<0)throw new ValueError(_ErrorMessages.InvalidParameter("column_num"));if((l=e._ensureNonFunctionExpression(l,i))instanceof _CellRangeExpression){if(s>(o=l.cells).rowSpan)throw new ReferenceError(_ErrorMessages.ParameterIsOutOfRange("row_num"));if(n>o.columnSpan)throw new ReferenceError(_ErrorMessages.ParameterIsOutOfRange("column_num"));if(s>0&&n>0)return e._owner.getCellValue(o.topRow+s-1,o.leftCol+n-1,!0,i);if(0===s&&0===n)return l;if(0===s)return new _CellRangeExpression(this,new CellRange(o.topRow,o.leftCol+n-1,o.bottomRow,o.leftCol+n-1),l.sheetRef,e._owner);if(0===n)return new _CellRangeExpression(this,new CellRange(o.topRow+s-1,o.leftCol,o.topRow+s-1,o.rightCol),l.sheetRef,e._owner)}throw new SyntaxError(_ErrorMessages.InvalidCellRef)},4,2);e._functionTable.hlookup=new _FunctionDefinition((t,i)=>e._handleHLookup(t,i),4,3);e._functionTable.vlookup=new _FunctionDefinition((t,i)=>e._handleVLookup(t,i),4,3)}_registFinacialFunction(){var e=this;e._functionTable.rate=new _FunctionDefinition((t,i)=>{return{value:e._calculateRate(t,i),format:"p2"}},6,3)}_registAddressRelatedFunction(){let e=this;e._functionTable.indirect=new _FunctionDefinition((t,i)=>{let o,l,s,n,r,a,h,d=e._ensureNonFunctionExpression(t[0],i);if(d instanceof _CellRangeExpression){o=d.cells;l=d.evaluate(o.row,o.col,i)}else l=d instanceof _Expression?d.evaluate(e._rowIndex,e._columnIndex,i):d;if(isString(l)){if(2===(s=l.split("!")).length){n=s[0].toLowerCase();r=s[1].toLowerCase()}else r=s[0].toLowerCase();let t=e._owner.definedNames._find(r,n||e._sheet.name);i=i||e._owner.selectedSheet;if(t){if(t.sheetName&&t.sheetName.toLowerCase()!==i.name.toLowerCase())throw new ReferenceError(_ErrorMessages.InvalidCellRef);l=t.value}if(a=e._getCellRange(l)){if(a.sheetRef){for(let t=0;t<e._owner.sheets.length;t++)if(e._owner.sheets[t].name.toLowerCase()===a.sheetRef.toLowerCase()){h=e._owner.sheets[t];break}}else h=e._owner.selectedSheet;if(h)return e._owner.getCellValue(a.cellRef.cellRange.row,a.cellRef.cellRange.col,!0,i)}}throw new SyntaxError(_ErrorMessages.InvalidCellRef)},2,1);e._functionTable.address=new _FunctionDefinition((t,i)=>{let o,l,s=_Expression.toNumber(t[0],e._rowIndex,e._columnIndex,i),n=_Expression.toNumber(t[1],e._rowIndex,e._columnIndex,i),r=!1,a=!1;if(isNaN(s)||!isInt(s)||s<1||s>1048576)throw new ValueError(_ErrorMessages.InvalidParameter("row_num"));if(isNaN(n)||!isInt(n)||n<1||n>16384)throw new ValueError(_ErrorMessages.InvalidParameter("column_num"));if(null!=t[2]){o=_Expression.toNumber(t[2],e._rowIndex,e._columnIndex,i);if(isNaN(o)||!isInt(o)||o<1||o>4)throw new ValueError(_ErrorMessages.InvalidParameter("abs_num"))}null!=t[4]&&(l=_Expression.toString(t[4],e._rowIndex,e._columnIndex,i));if(null==o||1===o){r=!0;a=!0}else 2===o?r=!0:3===o&&(a=!0);return(null!=l?l+"!":"")+(a?"$":"")+e._numAlpha(n)+(r?"$":"")+s.toString()},5,2)}_registerIsFunctions(){let getError=(e,t)=>{let i;try{i=e.evaluate(this._rowIndex,this._columnIndex,t)}catch(e){e instanceof FormulaError&&(i=e)}return i};this._functionTable.isblank=new _FunctionDefinition((e,t)=>{let i=!1,o=e[0];if(o instanceof _CellRangeExpression){o.evaluate(this._rowIndex,this._columnIndex,t);i=!!o._isEmpty}return i},1,1);this._functionTable.iserror=new _FunctionDefinition((e,t)=>getError(e[0],t)instanceof FormulaError,1,1);this._functionTable.iserr=new _FunctionDefinition((e,t)=>{var i=getError(e[0],t);return i instanceof FormulaError&&!(i instanceof NotAvailableError)},1,1);this._functionTable.iferror=new _FunctionDefinition((e,t)=>{var i=getError(e[0],t);return i instanceof FormulaError?e[1].evaluate(this._rowIndex,this._columnIndex,t):i},2,2)}_addToken(e,t,i){var o=new _Token(e,t,i);this._tokenTable[e]=o}_parseExpression(){this._getToken();return this._parseCompareOrConcat()}_parseCompareOrConcat(){for(var e,t,i=this._parseAddSub();this._token.tokenType===_TokenType.COMPARE||this._token.tokenType===_TokenType.CONCAT;){e=this._token;this._getToken();t=this._parseAddSub();i=new _BinaryExpression(this,e,i,t)}return i}_parseAddSub(){for(var e,t,i=this._parseMulDiv();this._token.tokenType===_TokenType.ADDSUB;){e=this._token;this._getToken();t=this._parseMulDiv();i=new _BinaryExpression(this,e,i,t)}return i}_parseMulDiv(){for(var e,t,i=this._parsePower();this._token.tokenType===_TokenType.MULDIV;){if(this._token.tokenID===_TokenID.PERCENT){e=new _Token("%",_TokenID.PERCENT,_TokenType.MULDIV);this._token=new _Token(100,_TokenID.ATOM,_TokenType.LITERAL)}else{e=this._token;this._getToken()}t=this._parsePower();i=new _BinaryExpression(this,e,i,t)}return i}_parsePower(){for(var e,t,i=this._parseUnary();this._token.tokenType===_TokenType.POWER;){e=this._token;this._getToken();t=this._parseUnary();i=new _BinaryExpression(this,e,i,t)}return i}_parseUnary(){var e,t;if(this._token.tokenID===_TokenID.ADD||this._token.tokenID===_TokenID.SUB){e=this._token;this._getToken();t=this._parseAtom();return new _UnaryExpression(this,e,t)}return this._parseAtom()}_parseAtom(){var e=null;switch(this._token.tokenType){case _TokenType.LITERAL:case _TokenType.ERROR:e=new _Expression(this,this._token);break;case _TokenType.IDENTIFIER:let t=this._token.value.toString(),i=t.toLowerCase(),o=this._functionTable[0===i.indexOf("_xlfn.")?i.substr(6):i];if(o){let t=this._getParameters();if(this._token.tokenType===_TokenType.GROUP&&this._token.tokenID===_TokenID.CLOSE){let l=t?t.length:0;if(-1!==o.paramMin&&l<o.paramMin)throw new SyntaxError(_ErrorMessages.TooFewParameters);if(-1!==o.paramMax&&l>o.paramMax)throw new SyntaxError(_ErrorMessages.TooManyParameters);"rand"!==i&&("column"!==i&&"row"!==i||0!==l)||(this._containsCellRef=!0);e=new _FunctionExpression(this,i,o,t);break}if("true"===i||"false"===i){e=new _FunctionExpression(this,i,o,t,!1);break}}let l,s,n=i.split("!");if(2===n.length){s=n[0];l=n[1]}else l=n[0];let r=this._owner.definedNames._find(l,s||this._sheet.name);if(r){if(r.sheetName&&r.sheetName.toLowerCase()!==this._sheet.name.toLowerCase()&&r.sheetName.toLowerCase()!==s)throw new NameError(_ErrorMessages.DefNameInvalidSheet(r.sheetName));{let t=this._pointer,i=this._expressLength,o=this._expression;this._pointer=0;(e=this._checkCache(r.value))._definedName=r.name;this._pointer=t;this._expressLength=i;this._expression=o;break}}s="";let a=this._owner._getTable(i);if(null!=a){if(""===(s=a.sheet.name))throw new NameError(_ErrorMessages.InvalidTable(i));let t=this._pointer,o=this._token;this._getToken();if(this._token.tokenType===_TokenType.SQUAREBRACKETS&&this._token.tokenID===_TokenID.OPEN){this._tableRefStart=!0;e=this._getTableReference(a,s,!0)}else{e=this._getTableReference(a,s,!1);this._pointer=t;this._token=o}break}let h=this._getCellRange(t);if(h){this._containsCellRef=!0;e=new _CellRangeExpression(this,h.cellRef.cellRange,h.sheetRef,this._owner,t.indexOf(":")>-1,h.cellRef.absRow,h.cellRef.absCol,h.cellRef.absRow2,h.cellRef.absCol2,h.isWholeRow);break}e=this.onUnknownFunction(i,this._getParameters());break;case _TokenType.GROUP:if(this._token.tokenID!==_TokenID.OPEN)throw new SyntaxError(_ErrorMessages.ExpressionExpected);this._getToken();e=this._parseCompareOrConcat();if(this._token.tokenID!==_TokenID.CLOSE)throw new SyntaxError(_ErrorMessages.UnbalancedParenthesis);e._inGroup=!0;break;case _TokenType.SQUAREBRACKETS:if(this._token.tokenID!==_TokenID.OPEN)throw new ValueError(_ErrorMessages.TableReferencesExpected);if(null!=(a=this._sheet.findTable(this._rowIndex,this._columnIndex))){s=a.sheet.name;this._tableRefStart=!0;e=this._getTableReference(a,s,!0,!1)}}if(null==e)throw new SyntaxError(_ErrorMessages.BadExpression);this._getToken();return e}_getToken(){for(var e,t,i,o,l,s,n="",r="",a=new RegExp("[ -〿぀-ゟ゠-ヿ＀-゚一-龯㐀-䶿]");this._pointer<this._expressLength&&" "===this._expression[this._pointer];)this._pointer++;if(this._pointer>=this._expressLength)this._token=new _Token(null,_TokenID.END,_TokenType.GROUP);else{s=(t=this._expression[this._pointer])>="0"&&t<="9"||"."==t;if(!(l=t>="a"&&t<="z"||t>="A"&&t<="Z"||a.test(t))&&!s){var h=this._tokenTable[t];if(h){this._token=h;this._pointer++;if(this._pointer<this._expressLength&&(">"===t||"<"===t)&&(h=this._tokenTable[this._expression.substring(this._pointer-1,this._pointer+1)])){this._token=h;this._pointer++}return}}if(s){o=this._pointer;this._parseDigit();if(":"!==this._expression[this._pointer])return;this._pointer=o}if('"'!==t){if(("'"!==t||(r=this._parseSheetRef()))&&("#"!==t||!this._parseError()))if("#"!==t){if(!l&&!s&&this._idChars.indexOf(t)<0&&!r)throw new SyntaxError(_ErrorMessages.IdentifierExpected);for(e=1;e+this._pointer<this._expressLength;e++){l=(t=this._expression[this._pointer+e])>="a"&&t<="z"||t>="A"&&t<="Z"||a.test(t);s=t>="0"&&t<="9";if("'"!==t||":"!==i){i=t;if(!l&&!s&&"."!==t&&this._idChars.indexOf(t)<0)break}else{n=r+this._expression.substring(this._pointer,this._pointer+e);this._pointer+=e;r=this._parseSheetRef();e=0}}n+=r+this._expression.substring(this._pointer,this._pointer+e);this._pointer+=e;this._token=new _Token(n,_TokenID.ATOM,_TokenType.IDENTIFIER)}else this._parseDate()}else this._parseString()}}_getTableToken(){for(var e,t,i,o="",l=!1;this._pointer<this._expressLength&&" "===this._expression[this._pointer];)this._pointer++;if("@"===(t=this._expression[this._pointer])){o=t;this._pointer++}"["===(t=this._expression[this._pointer])&&(l=!0);for(e=1;e+this._pointer<this._expressLength;e++){t=this._expression[this._pointer+e];if(l&&","===t)throw new SyntaxError(_ErrorMessages.InvalidTableRef);if("]"===t)break}i=o+this._expression.substring(this._pointer+(l?1:0),this._pointer+e);this._pointer+=e+(l?1:0);this._token=new _Token(i,_TokenID.ATOM,_TokenType.IDENTIFIER)}_parseDigit(){var e,t,i=-1,o=!1,l=0;for(e=0;e+this._pointer<this._expressLength;e++)if((t=this._expression[this._pointer+e])>="0"&&t<="9"){l=10*l+(+t-0);i>-1&&(i*=10)}else if("."===t&&i<0)i=1;else{if("E"!==t&&"e"!==t||o)break;o=!0;"+"!==(t=this._expression[this._pointer+e+1])&&"-"!==t||e++}o?l=+this._expression.substring(this._pointer,this._pointer+e):i>1&&(l/=i);this._token=new _Token(l,_TokenID.ATOM,_TokenType.LITERAL);this._pointer+=e}_parseString(){var e,t,i;for(e=1;e+this._pointer<this._expressLength;e++)if('"'===(t=this._expression[this._pointer+e])){if('"'!==(e+this._pointer<this._expressLength-1?this._expression[this._pointer+e+1]:" "))break;e++}if('"'!==t)throw new SyntaxError(_ErrorMessages.CantFindFinalQuote);i=this._expression.substring(this._pointer+1,this._pointer+e);this._pointer+=e+1;if("!"===this._expression[this._pointer])throw new SyntaxError(_ErrorMessages.IllegalCrossSheetReference);this._token=new _Token(i.replace('""','"'),_TokenID.ATOM,_TokenType.LITERAL)}_parseDate(){var e,t,i;for(e=1;e+this._pointer<this._expressLength&&"#"!==(t=this._expression[this._pointer+e]);e++);if("#"!==t)throw new SyntaxError(_ErrorMessages.CantFindFinalDateDelimiter);i=this._expression.substring(this._pointer+1,this._pointer+e);this._pointer+=e+1;this._token=new _Token(Date.parse(i),_TokenID.ATOM,_TokenType.LITERAL)}_parseError(){var e,t=this._pointer;for(e=t+1;e<this._expressLength;e++){var i=this._expression[e],o=this._expression[e-1];if(!(i>="a"&&i<="z"||i>="A"&&i<="Z"||("0"===i||"?"===i||"!"===i||"/"===i)&&(o>="a"&&o<="z"||o>="A"&&o<="Z"||"/"===o||"0"===o)))break}var l=e-t;if(l>3){var s=this._expression.substring(t,t+l),n=_FormulaErrorHelper.asError(s);if(n){this._token=new _Token(n,_TokenID.ATOM,_TokenType.ERROR);this._pointer+=l;return!0}}return!1}_parseSheetRef(){var e,t,i;for(e=1;e+this._pointer<this._expressLength;e++)if("'"===(t=this._expression[this._pointer+e])){if("'"!==(e+this._pointer<this._expressLength-1?this._expression[this._pointer+e+1]:" "))break;e++}if("'"!==t)throw new SyntaxError(_ErrorMessages.CantFindFinalQuote);i=this._expression.substring(this._pointer+1,this._pointer+e);this._pointer+=e+1;return"!"===this._expression[this._pointer]?i.replace(/\'\'/g,"'"):""}_getCellRange(e){var t,i,o,l,s;if(e&&(t=e.split(":")).length>0&&t.length<3){if(null==(i=this._parseCell(t[0])).cellRef)return null;l=i.cellRef.cellRange;if(null!=i.cellRef.isWholeRow&&1===t.length)return null;if(l&&2===t.length){s=(o=this._parseCell(t[1])).cellRef.cellRange;if(null!=i.cellRef.isWholeRow&&i.cellRef.isWholeRow!==o.cellRef.isWholeRow)return null;i.sheetRef&&!o.sheetRef&&(o.sheetRef=i.sheetRef);if(i.sheetRef!==o.sheetRef)throw new ReferenceError(_ErrorMessages.CellRefMustBeInSameSheet);if(s){l.col2=s.col;l.row2=s.row}else l=null}}return null==l?null:{cellRef:{cellRange:l,absRow:i.cellRef.absRow,absCol:i.cellRef.absCol,absRow2:o?o.cellRef.absRow:null,absCol2:o?o.cellRef.absCol:null},sheetRef:i.sheetRef,isWholeRow:i.cellRef.isWholeRow}}_parseCellRange(e){var t,i,o,l,s=-1,n=-1,r=!1,a=!1;for(t=0;t<e.length;t++)if("$"!==(o=e[t])||r){if(!(o>="a"&&o<="z"||o>="A"&&o<="Z"))break;s<0&&(s=0);s=26*s+(o.toUpperCase().charCodeAt(0)-"A".charCodeAt(0)+1)}else r=!0;for(;t<e.length;t++)if("$"!==(o=e[t])||a){if(!(o>="0"&&o<="9"))break;n<0&&(n=0);n=10*n+(+o-0)}else a=!0;if(t<e.length)return null;if(n>-1&&s>-1){if(0===n)throw new NameError(_ErrorMessages.InvalidCellRef);i=new CellRange(n-1,s-1)}else if(-1===s){l=!0;i=new CellRange(n-1,0)}else if(-1===n){l=!1;i=new CellRange(0,s-1)}return{cellRange:i,absRow:a,absCol:r,isWholeRow:l}}_parseCell(e){var t,i,o;if((t=e.lastIndexOf("!"))>0&&t<e.length-1){o=e.substring(0,t);i=e.substring(t+1)}else{if(!(t<=0))return null;i=e}return{cellRef:this._parseCellRange(i),sheetRef:o}}_getParameters(){var e,t,i=this._pointer,o=this._token;this._getToken();if(this._token.tokenType!==_TokenType.SQUAREBRACKETS||this._token.tokenID!==_TokenID.OPEN){if(this._token.tokenID!==_TokenID.OPEN){this._pointer=i;this._token=o;return null}i=this._pointer;this._getToken();if(this._token.tokenID===_TokenID.CLOSE)return null;this._pointer=i;e=new Array;t=this._parseExpression();e.push(t);for(;this._token.tokenID===_TokenID.COMMA;){t=this._parseExpression();e.push(t)}if(this._token.tokenID!==_TokenID.CLOSE)throw new SyntaxError(_ErrorMessages.SyntaxError);return e}}_getTableReference(e,t,i,o=!0){let l=[],s=i?this._getTableParameter():null,n=!1,r=!1;if(null==s){l.push("#Data");r=!0}else{l.push(s);for(;this._tableRefStart&&(this._token.tokenID===_TokenID.COMMA||":"===this._token.value);){":"===this._token.value&&(n=!0);if(null==(s=this._getTableParameter()))throw new SyntaxError(_ErrorMessages.InvalidTableRef);if(n){l[l.length-1]+=":"+s;n=!1}else l.push(s)}if(this._token.tokenType!==_TokenType.SQUAREBRACKETS||this._token.tokenID!==_TokenID.CLOSE)throw new SyntaxError(_ErrorMessages.UnbalancedSquareBrackets);this._tableRefStart=!1}let a=this._getTableRange(e,l);this._containsCellRef=!0;let h=new _CellRangeExpression(this,a,t.toLowerCase(),this._owner);h._tableParams=l;o&&(h._tableName=e.name);r&&(h._defTableParameterProvided=!0);return h}_getTableParameter(){var e;for(this._pointer;this._pointer<this._expressLength&&" "===this._expression[this._pointer];)this._pointer++;if("]"===this._expression[this._pointer]){this._getToken();this._tableRefStart=!1;return null}this._getTableToken();e=this._token.value;this._getToken();return e}_getTableRange(e,t){for(var i,o,l,s,n,r,a=0;a<t.length;a++){if(o)throw new ValueError(_ErrorMessages.InvalidTableRef);n=null;if("#"===(i=t[a].toLowerCase())[0]){switch(i){case"#all":n=e.getRange();break;case"#data":n=e.getRange(TableSection.Data);break;case"#headers":n=e.getRange(TableSection.Header);break;case"#totals":n=e.getRange(TableSection.Footer);break;case"#this row":s=e.getRange();if(!(this._rowIndex>=s.topRow&&this._rowIndex<=s.bottomRow))throw new ValueError(_ErrorMessages.RowIsOutOfTableRange(e.name));n=new CellRange(this._rowIndex,s.leftCol,this._rowIndex,s.rightCol);break;default:throw new ValueError(_ErrorMessages.InvalidTableRef)}if(null==n)throw new ValueError(_ErrorMessages.InvalidTableRef);if(null==l)l=n;else{l.row=l.topRow<n.topRow?l.topRow:n.topRow;l.row2=l.bottomRow>n.bottomRow?l.bottomRow:n.bottomRow}}else{o=!0;r=i.split(":");for(var h=0;h<r.length;h++){if(r.length>2)throw new ValueError(_ErrorMessages.InvalidTableColRef);if("@"===(i=r[h])[0]){if(null==(n=e.getRange(TableSection.Data,i.substring(1))))throw new ValueError(_ErrorMessages.InvalidTableRef);if(!(this._rowIndex>=n.topRow&&this._rowIndex<=n.bottomRow))throw new ValueError(_ErrorMessages.RowIsOutOfTableRange(e.name));n.row=this._rowIndex;n.row2=this._rowIndex}else if(null==(n=e.getRange(TableSection.Data,i)))throw new ValueError(_ErrorMessages.InvalidTableRef);0===h&&(null==l?l=n:l.col=n.col);l.col2=n.col;n=null}}}return l}_getAggregate(e,t){let i=0,o=0,l=0,s=null,n=null;for(let e=0;e<t.length;e++){let r=t[e];if(null!=r&&"number"==typeof r&&!isNaN(r)){(null==s||r<s)&&(s=r);(null==n||r>n)&&(n=r);i++;o+=r;l+=r*r}}let r=0==i?0:o/i;switch(e){case Aggregate.Avg:return r;case Aggregate.Max:return n;case Aggregate.Min:return s;case Aggregate.Sum:return o;case Aggregate.VarPop:return i<=1?0:l/i-r*r;case Aggregate.StdPop:return i<=1?0:Math.sqrt(l/i-r*r);case Aggregate.Var:return i<=1?0:(l/i-r*r)*i/(i-1);case Aggregate.Std:return i<=1?0:Math.sqrt((l/i-r*r)*i/(i-1))}throw"Invalid aggregate type."}_getAggregateResult(e,t,i){var o,l=this._getItemList(t,i);o=this._getAggregate(e,l.items);l.isDate&&(o={value:o=new Date(o),format:l.format||"M/d/yyyy"});return o}_getFlexSheetAggregateResult(e,t,i){var o,l;switch(e){case _FlexSheetAggregate.Count:o=this._getItemList(t,i,!1,void 0,void 0,!1);return this._countNumberCells(o.items);case _FlexSheetAggregate.CountA:return(o=this._getItemList(t,i,!1,void 0,void 0,!1)).items.length;case _FlexSheetAggregate.CountBlank:o=this._getItemList(t,i,!0,void 0,void 0,!1);return this._countBlankCells(o.items);case _FlexSheetAggregate.Rank:let e=_Expression.toNumber(t[0],this._rowIndex,this._columnIndex,i),s=t[2]?_Expression.toNumber(t[2],this._rowIndex,this._columnIndex,i):0;if(isNaN(e))throw new ValueError(_ErrorMessages.InvalidParameter("number"));if(isNaN(s))throw new ValueError(_ErrorMessages.InvalidParameter("order"));t[1]=this._ensureNonFunctionExpression(t[1],i);if(t[1]instanceof _CellRangeExpression){o=this._getItemList([t[1]],i);return this._getRankOfCellRange(e,o.items,s)}throw new SyntaxError(_ErrorMessages.InvalidCellRef);case _FlexSheetAggregate.CountIf:t[0]=this._ensureNonFunctionExpression(t[0],i);if(t[0]instanceof _CellRangeExpression){o=this._getItemList([t[0]],i,void 0,void 0,void 0,!1);return this._countCellsByCriteria([o.items],[t[1]],i)}throw new SyntaxError(_ErrorMessages.InvalidCellRef);case _FlexSheetAggregate.CountIfs:return this._handleCountIfs(t,i);case _FlexSheetAggregate.SumIf:t[0]=this._ensureNonFunctionExpression(t[0],i);if(t[0]instanceof _CellRangeExpression){let e=!1;t[2]=this._ensureNonFunctionExpression(t[2],i);null!=t[2]&&t[2]instanceof _CellRangeExpression&&(l=this._getItemList([t[2]],i,e=!0));o=this._getItemList([t[0]],i,e);return this._sumCellsByCriteria([o.items],[t[1]],l?l.items:null,i)}throw new SyntaxError(_ErrorMessages.InvalidCellRef);case _FlexSheetAggregate.SumIfs:return this._handleSumIfs(t,i);case _FlexSheetAggregate.Product:o=this._getItemList(t,i);return this._getProductOfNumbers(o.items)}throw"Invalid aggregate type."}_getItemList(e,t,i=!1,o=!0,l,s=!0){var n,r,a,h,d,u,c,_,g,f,w=new Array;for(r=0;r<e.length;r++){d=e[r];if((d=this._ensureNonFunctionExpression(d,t))instanceof _CellRangeExpression){_=d._getSheet()||t||this._sheet;h=d.getValues(o,l,_,s);if(0===r){(g=_.getCellStyle(d.cells.topRow,d.cells.leftCol))&&(c=g.format);c||(f=_.grid.columns[d.cells.leftCol])&&(c=f.format)}e:for(a=0;a<h.length;a++){n=h[a];if(null==u&&null!=n&&!isString(n)){u=isDate(n);break e}}for(a=0;a<h.length;a++){n=h[a];(i||null!=n&&""!==n)&&(isDate(n)?w.push(+n):w.push(n))}}else{!(n=d instanceof _Expression?d.evaluate(this._rowIndex,this._columnIndex,t,void 0,void 0,s):d)||n instanceof FormulaError||isPrimitive(n)||(n=n.value);if(!i&&(null==n||""===n))continue;let e=+n;isNaN(e)||(n=e);w.push(n);null==u&&w.length>0&&(u=n instanceof Date)}}0===w.length&&(u=!1);return{isDate:u,items:w,format:c}}_countBlankCells(e){for(var t,i=0,o=0;i<e.length;i++)(null==(t=e[i])||isString(t)&&""===t||isNumber(t)&&isNaN(t))&&o++;return o}_countNumberCells(e){for(var t,i=0,o=0;i<e.length;i++)null!=(t=e[i])&&isNumber(t)&&!isNaN(t)&&o++;return o}_getRankOfCellRange(e,t,i=0){var o,l=0,s=0;i?t.sort((e,t)=>isNaN(e)||isNaN(t)?-1:e-t):t.sort((e,t)=>isNaN(e)||isNaN(t)?1:t-e);for(;l<t.length;l++){o=t[l];if(!isNaN(o)&&isNumber(o)){s++;if(e===o)return s}}throw new ValueError(_ErrorMessages.ParameterIsOutOfRange("number"))}_handleCountIfs(e,t){var i,o,l,s,n=0,r=[],a=[];if(e.length%2!=0)throw new ValueError(_ErrorMessages.InvalidParameters);for(;n<e.length/2;n++){o=e[2*n];if(!((o=this._ensureNonFunctionExpression(o,t))instanceof _CellRangeExpression))throw new SyntaxError(_ErrorMessages.InvalidCellRef);if(0===n){if(!o.cells)throw new SyntaxError(_ErrorMessages.InvalidCellRef);l=o.cells.rowSpan;s=o.cells.columnSpan}else{if(!o.cells)throw new SyntaxError(_ErrorMessages.InvalidCellRef);if(o.cells.rowSpan!==l||o.cells.columnSpan!==s)throw new ValueError(_ErrorMessages.RangesMustBeTheSame)}i=this._getItemList([o],t,void 0,void 0,void 0,!1);r[n]=i.items;a[n]=e[2*n+1]}return this._countCellsByCriteria(r,a,t)}_countCellsByCriteria(e,t,i,o){var l,s=0,n=e[0].length,r=[];for(let e=0;e<t.length;e++){let o=_Expression.toString(t[e],this._rowIndex,this._columnIndex,i);"*"===o?r.push(o):r.push(this._parseRightExpr(o))}for(let t=0;t<n;t++){l=!1;for(let o=0;o<e.length;o++){let s=e[o][t],n=r[o];if("string"==typeof n){if("*"!==n&&(null==s||""===s)){l=!1;break}if((l="*"===n||this.evaluate(this._combineExpr(s,n),null,i,this._rowIndex,this._columnIndex,!1,!0))instanceof FormulaError||!l)break}else if(!(l=l=n.reg.test(s.toString())===n.checkMathces))break}if(l&&!(l instanceof FormulaError))if(o){let e=o[t];null!=e&&isNumber(e)&&!isNaN(e)&&s++}else s++}return s}_handleSumIfs(e,t){var i,o,l,s,n,r,a=1,h=[],d=[],u=!1;if(e.length%2!=1)throw new ValueError(_ErrorMessages.InvalidParameters);l=e[0];if(!((l=this._ensureNonFunctionExpression(l,t))instanceof _CellRangeExpression))throw new ValueError(_ErrorMessages.InvalidParameter("Sum_range"));if(!l.cells)throw new ValueError(_ErrorMessages.InvalidParameter("Sum_range"));n=l.cells.rowSpan;r=l.cells.columnSpan;o=this._getItemList([l],t,u=!0);for(;a<(e.length+1)/2;a++){s=e[2*a-1];if(!((s=this._ensureNonFunctionExpression(s,t))instanceof _CellRangeExpression))throw new ValueError(_ErrorMessages.InvalidParameter("Criteria_range"+a));if(!s.cells)throw new ValueError(_ErrorMessages.InvalidParameter("Criteria_range"+a));if(s.cells.rowSpan!==n||s.cells.columnSpan!==r)throw new ValueError(_ErrorMessages.RangesMustBeTheSame);i=this._getItemList([s],t,u);h[a-1]=i.items;d[a-1]=e[2*a]}return this._sumCellsByCriteria(h,d,o.items,t)}_sumCellsByCriteria(e,t,i,o){var l,s,n,r,a=0,h=0,d=0,u=e[0].length,c=[];null==i&&(i=e[0]);for(;h<t.length;h++)"*"===(r=_Expression.toString(t[h],this._rowIndex,this._columnIndex,o))?c.push(r):c.push(this._parseRightExpr(r));for(;a<u;a++){s=!1;l=i[a];for(h=0;h<e.length;h++){n=e[h][a];if("string"==typeof(r=c[h])){if("*"!==r&&null==n){s=!1;break}if((s="*"===r||this.evaluate(this._combineExpr(n,r),null,o,this._rowIndex,this._columnIndex,!1))instanceof FormulaError||!s)break}else if(!(s=r.reg.test(n.toString())===r.checkMathces))break}s&&isNumber(l)&&!isNaN(l)&&(d+=l)}return d}_getProductOfNumbers(e){var t,i=0,o=1,l=!1;if(e)for(;i<e.length;i++){t=e[i];if(isNumber(t)&&!isNaN(t)){o*=t;l=!0}}return l?o:0}_handleSubtotal(e,t){var i,o,l,s,n=!0,r=!0;if((i=_Expression.toNumber(e[0],this._rowIndex,this._columnIndex,t))>=1&&i<=11||i>=101&&i<=111){i>=101&&i<=111&&(n=!1);(i=asEnum(i,_SubtotalFunction))!==_SubtotalFunction.CountA&&i!==_SubtotalFunction.CountAWithoutHidden||(r=!1);o=this._getItemList(e.slice(1),t,r,n);switch(i){case _SubtotalFunction.Count:case _SubtotalFunction.CountWithoutHidden:return this._countNumberCells(o.items);case _SubtotalFunction.CountA:case _SubtotalFunction.CountAWithoutHidden:return o.items.length;case _SubtotalFunction.Product:case _SubtotalFunction.ProductWithoutHidden:return this._getProductOfNumbers(o.items);case _SubtotalFunction.Average:case _SubtotalFunction.AverageWithoutHidden:l=Aggregate.Avg;break;case _SubtotalFunction.Max:case _SubtotalFunction.MaxWithoutHidden:l=Aggregate.Max;break;case _SubtotalFunction.Min:case _SubtotalFunction.MinWithoutHidden:l=Aggregate.Min;break;case _SubtotalFunction.Std:case _SubtotalFunction.StdWithoutHidden:l=Aggregate.Std;break;case _SubtotalFunction.StdPop:case _SubtotalFunction.StdPopWithoutHidden:l=Aggregate.StdPop;break;case _SubtotalFunction.Sum:case _SubtotalFunction.SumWithoutHidden:l=Aggregate.Sum;break;case _SubtotalFunction.Var:case _SubtotalFunction.VarWithoutHidden:l=Aggregate.Var;break;case _SubtotalFunction.VarPop:case _SubtotalFunction.VarPopWithoutHidden:l=Aggregate.VarPop}s=this._getAggregate(l,o.items);o.isDate&&(s=new Date(s));return s}throw new ValueError(_ErrorMessages.InvalidParameter("Function_num"))}_handleDCount(e,t){var i,o,l,s=e[0],n=e[2];s=this._ensureNonFunctionExpression(s,t);n=this._ensureNonFunctionExpression(n,t);if(s instanceof _CellRangeExpression&&n instanceof _CellRangeExpression){i=e[1].evaluate(this._rowIndex,this._columnIndex,t);o=this._getColumnIndexByField(s,i);return(l=this._getItemList([s],t,!1,!0,o,!1)).items&&l.items.length>1?this._DCountWithCriteria(l.items.slice(1),s,n):0}throw new ValueError(_ErrorMessages.InvalidParameter("Database"))}_DCountWithCriteria(e,t,i){var o,l,s,n,r,a,h,d,u,c,_,g=i.cells,f=0;o=this._owner._getSheet(t.sheetRef);l=this._owner._getSheet(i.sheetRef);if(g.rowSpan>1){s=g.topRow;for(n=g.bottomRow;n>g.topRow;n--){c=[];_=[];for(r=g.leftCol;r<=g.rightCol;r++)if(null!=(h=this._owner.getCellValue(n,r,!1,l))&&""!==h){_.push(new _Expression(this,h));d=this._owner.getCellValue(s,r,!1,l);a=this._getColumnIndexByField(t,d);if(!(null!=(u=this._getItemList([t],o,!1,!0,a,!1)).items&&u.items.length>1))throw new ValueError("Criteria");c.push(u.items.slice(1))}f+=this._countCellsByCriteria(c,_,o,e)}return f}throw new ValueError("Criteria")}_getColumnIndexByField(e,t){var i,o,l,s,n;if(-1===(n=(i=e.cells).topRow))throw new ValueError(_ErrorMessages.InvalidParameter("Database"));if(isInt(t)&&!isNaN(t)){if(t>=1&&t<=i.columnSpan)return l=i.leftCol+t-1}else{o=this._owner._getSheet(e.sheetRef);for(l=i.leftCol;l<=i.rightCol;l++){s=this._owner.getCellValue(n,l,!1,o);if((t=isString(t)?t.toLowerCase():t)===(s=isString(s)?s.toLowerCase():s))return l}}throw new ValueError(_ErrorMessages.InvalidParameter("Field"))}_getSumProduct(e,t){var i,o,l,s=0,n=this._getItemListForSumProduct(e,t);if(n.length>0){o=n[0].length;l=n.length;for(var r=0;r<o;r++){i=1;for(var a=0;a<l;a++)i*=n[a][r];s+=i}}return s}_getItemListForSumProduct(e,t){var i,o,l,s,n,r,a=[new Array];for(l=0;l<e.length;l++){r=e[l];i=new Array;if((r=this._ensureNonFunctionExpression(r,t))instanceof _CellRangeExpression){n=r.getValues(!0,null,t);for(s=0;s<n.length;s++){o=n[s];i.push(+o)}}else{o=r instanceof _Expression?r.evaluate(this._rowIndex,this._columnIndex,t):r;i.push(+o)}if(l>0&&i.length!==a[0].length)throw new ValueError(_ErrorMessages.RangesMustBeTheSame);a[l]=i}return a}_parseRightExpr(e){var t,i,o=!1;if(e.indexOf("?")>-1||e.indexOf("*")>-1){if(null==(t=e.match(/=?([\?\*]*)(\w*)([\?\*]*)(\w*)([\?\*]*)/))||6!==t.length)throw new ValueError(_ErrorMessages.InvalidParameter("Criteria"));i=new RegExp("^"+(t[1].length>0?this._parseRegCriteria(t[1]):"")+t[2]+(t[3].length>0?this._parseRegCriteria(t[3]):"")+t[4]+(t[5].length>0?this._parseRegCriteria(t[5]):"")+"$","i");/^[<>=]/.test(e)?"="===e.trim()[0]&&(o=!0):o=!0;return{reg:i,checkMathces:o}}{let t;if(isNaN(+e))if("true"===(t=e.toLowerCase())||"false"===t)e="="+e;else if(/^\w/.test(e))e='="'+e+'"';else{if(!/^[<>=]{1,2}\s*-?.+$/.test(e))throw new ValueError(_ErrorMessages.InvalidParameter("Criteria"));e=e.replace(/([<>=]{1,2})\s*(-?.+)/,(e,t,i)=>{let o=i.toLowerCase();return t+(isNaN(+i)&&"true"!==o&&"false"!==o?`"${i}"`:i)})}else e="="+ +e;return e}}_combineExpr(e,t){(isString(e)||isDate(e))&&(e='"'+e+'"');return(e="="+e)+t}_parseRegCriteria(e){for(var t=0,i=0,o="";t<e.length;t++)if("*"===e[t]){if(i>0){o+="\\w{"+i+"}";i=0}o+="\\w*"}else"?"===e[t]&&i++;i>0&&(o+="\\w{"+i+"}");return o}_calculateRate(e,t){var i,o,l,s,n,r,a,h,d,u,c=0,_=0;l=_Expression.toNumber(e[0],this._rowIndex,this._columnIndex,t);s=_Expression.toNumber(e[1],this._rowIndex,this._columnIndex,t);n=_Expression.toNumber(e[2],this._rowIndex,this._columnIndex,t);r=null!=e[3]?_Expression.toNumber(e[3],this._rowIndex,this._columnIndex,t):0;a=null!=e[4]?_Expression.toNumber(e[4],this._rowIndex,this._columnIndex,t):0;o=null!=e[5]?_Expression.toNumber(e[5],this._rowIndex,this._columnIndex,t):.1;Math.abs(o)<1e-7?n*(1+l*o)+s*(1+o*a)*l+r:n*(h=Math.exp(l*Math.log(1+o)))+s*(1/o+a)*(h-1)+r;d=n+s*l+r;u=n*h+s*(1/o+a)*(h-1)+r;i=o;for(;Math.abs(d-u)>1e-7&&c<20;){o=(u*_-d*i)/(u-d);_=i;i=o;d=u;u=Math.abs(o)<1e-7?n*(1+l*o)+s*(1+o*a)*l+r:n*(h=Math.exp(l*Math.log(1+o)))+s*(1/o+a)*(h-1)+r;++c}if(Math.abs(d-u)>1e-7&&20===c)throw new NumericError(_ErrorMessages.RateCriteriaFails);return o}_handleHLookup(e,t){return this._handleLookup(e,t,{base:e=>e.topRow,span:e=>e.rowSpan,iterStart:e=>e.leftCol,iterEnd:e=>e.rightCol,getValue:(e,t,i)=>this._owner.getCellValue(e,t,0,i)})}_handleVLookup(e,t){return this._handleLookup(e,t,{base:e=>e.leftCol,span:e=>e.columnSpan,iterStart:e=>e.topRow,iterEnd:e=>e.bottomRow,getValue:(e,t,i)=>this._owner.getCellValue(t,e,0,i)})}_handleLookup(e,t,i){var o=e[0].evaluate(this._rowIndex,this._columnIndex,t),l=e[1],s=_Expression.toNumber(e[2],this._rowIndex,this._columnIndex,t),n=null==e[3]||_Expression.toBoolean(e[3],this._rowIndex,this._columnIndex,t);if(null==o||""===o)throw new NotAvailableError(_ErrorMessages.InvalidParameter("Lookup_value"));if(isNaN(s)||s<0)throw new ValueError(_ErrorMessages.InvalidParameter("index_num"));if((l=this._ensureNonFunctionExpression(l,t))instanceof _CellRangeExpression){t=l._getSheet()||t||this._sheet;var r,a=l.cells;if(s>i.span(a))throw new ReferenceError(_ErrorMessages.ParameterIsOutOfRange("index_num"));n?-1===(r=this._exactMatch(o,a,!1,i,t))&&(r=this._approximateMatch(o,a,i,t)):r=this._exactMatch(o,a,!0,i,t);if(-1===r)throw new NotAvailableError;let e=i.getValue(i.base(a)+s-1,r,t);if(null==e)throw new NotAvailableError;return e}throw new SyntaxError(_ErrorMessages.InvalidCellRef)}_exactMatch(e,t,i,o,l){var s,n=o.base(t);isString(e)&&(e=e.toLowerCase());if(i&&isString(e)&&(e.indexOf("?")>-1||e.indexOf("*")>-1)){var r=e.match(/([\?\*]*)(\w+)([\?\*]*)(\w+)([\?\*]*)/);if(null==r||6!==r.length)throw new ValueError(_ErrorMessages.InvalidParameter("Lookup_value"));s=new RegExp("^"+(r[1].length>0?this._parseRegCriteria(r[1]):"")+r[2]+(r[3].length>0?this._parseRegCriteria(r[3]):"")+r[4]+(r[5].length>0?this._parseRegCriteria(r[5]):"")+"$","i")}for(var a=o.iterStart(t);a<=o.iterEnd(t);a++){var h=o.getValue(n,a,l);if(null!=s){if(s.test(h))return a}else{isString(h)&&(h=h.toLowerCase());if(e===h)return a}}return-1}_approximateMatch(e,t,i,o){var l=i.base(t),s=[];isString(e)&&(e=e.toLowerCase());for(var n=i.iterStart(t);n<=i.iterEnd(t);n++){var r=i.getValue(l,n,o);r=isNaN(+r)?r:+r;s.push({value:r,index:n})}s.sort((e,t)=>{isString(e.value)&&(e.value=e.value.toLowerCase());isString(t.value)&&(t.value=t.value.toLowerCase());return e.value>t.value?-1:e.value===t.value?t.index-e.index:1});for(var a=0;a<s.length;a++){r=s[a];isString(r.value)&&(r.value=r.value.toLowerCase());if(e>r.value)return r.index}throw new NotAvailableError}_parseToScientificValue(e,t,i,o,l){var s,n,r,a,h=0;if(Math.abs(e)>=1){n="+";s=Math.pow(10,t.length);for(;e>s;){e/=s;h+=t.length}}else{n="-";s=Math.pow(10,t.length);for(;e*s<s;){e*=s;h+=t.length}}r=Globalize.format(e,"D"+t.length);if(i){if((r+=Globalize.format(e-Math.floor(e),t+i).substring(1)).indexOf(".")>-1)a=r.length-1-r.indexOf(".");else{r+=".";a=0}for(;a<i.length-1;){r+="0";a++}}r+="E"+n+Globalize.format(h,"D"+o.length);if(l){r+=".";for(var d=1;d<l.length;d++)r+="0"}return r}_checkCache(e,t=!0,i=!1,o,l,s){null!=o&&(this._sheet=this._owner.sheets[o]);null!=l&&(this._rowIndex=l);null!=s&&(this._columnIndex=s);let n=this._sheet?this._sheet.name:"",r=this._expressionCache[n+":"+t+":"+i+":"+e]||this._expressionCache[n+"_"+this._rowIndex+"_"+this._columnIndex+":"+t+":"+i+":"+e];if(r){if(r.token.tokenType===_TokenType.ERROR)throw r.token.value;return r}r=this.parse(e);if(this._token.tokenID!==_TokenID.END||this._token.tokenType!==_TokenType.GROUP)throw new SyntaxError(_ErrorMessages.InvalidExpression(e));this._cacheSize>1e4&&this.clearExpressionCache();this._expressionCache[n+(this._containsCellRef?"_"+this._rowIndex+"_"+this._columnIndex:"")+":"+t+":"+i+":"+e]=r;this._cacheSize++;return r}_ensureNonFunctionExpression(e,t){for(;e instanceof _FunctionExpression;)e=e.evaluate(this._rowIndex,this._columnIndex,t);return e}_numAlpha(e){let t=Math.floor((e-1)/26);return(t>0?this._numAlpha(t):"")+String.fromCharCode((e-1)%26+65)}}_CalcEngine.PowOf10=Array.apply(null,{length:21}).map((e,t)=>Math.pow(10,t));export class _Token{constructor(e,t,i){this._value=e;this._tokenID=t;this._tokenType=i}get value(){return this._value}get tokenID(){return this._tokenID}get tokenType(){return this._tokenType}}export class _FunctionDefinition{constructor(e,t,i){this._paramMax=Number.MAX_VALUE;this._paramMin=Number.MIN_VALUE;this._func=e;isNumber(t)&&!isNaN(t)&&(this._paramMax=t);isNumber(i)&&!isNaN(i)&&(this._paramMin=i)}get paramMax(){return this._paramMax}get paramMin(){return this._paramMin}get func(){return this._func}}export var _TokenType;!function(e){e[e.COMPARE=0]="COMPARE";e[e.ADDSUB=1]="ADDSUB";e[e.MULDIV=2]="MULDIV";e[e.POWER=3]="POWER";e[e.CONCAT=4]="CONCAT";e[e.GROUP=5]="GROUP";e[e.LITERAL=6]="LITERAL";e[e.IDENTIFIER=7]="IDENTIFIER";e[e.ERROR=8]="ERROR";e[e.SQUAREBRACKETS=9]="SQUAREBRACKETS"}(_TokenType||(_TokenType={}));export var _TokenID;!function(e){e[e.GT=0]="GT";e[e.LT=1]="LT";e[e.GE=2]="GE";e[e.LE=3]="LE";e[e.EQ=4]="EQ";e[e.NE=5]="NE";e[e.ADD=6]="ADD";e[e.SUB=7]="SUB";e[e.MUL=8]="MUL";e[e.DIV=9]="DIV";e[e.DIVINT=10]="DIVINT";e[e.MOD=11]="MOD";e[e.POWER=12]="POWER";e[e.CONCAT=13]="CONCAT";e[e.OPEN=14]="OPEN";e[e.CLOSE=15]="CLOSE";e[e.END=16]="END";e[e.COMMA=17]="COMMA";e[e.PERIOD=18]="PERIOD";e[e.ATOM=19]="ATOM";e[e.PERCENT=20]="PERCENT"}(_TokenID||(_TokenID={}));export const _OpMap={[_TokenID.GT]:">",[_TokenID.LT]:"<",[_TokenID.GE]:">=",[_TokenID.LE]:"<=",[_TokenID.EQ]:"=",[_TokenID.NE]:"<>",[_TokenID.ADD]:"+",[_TokenID.SUB]:"-",[_TokenID.MUL]:"*",[_TokenID.DIV]:"/",[_TokenID.PERCENT]:"%",[_TokenID.DIVINT]:"\\",[_TokenID.POWER]:"^",[_TokenID.CONCAT]:"&"};!function(e){e[e.Count=0]="Count";e[e.CountA=1]="CountA";e[e.CountBlank=2]="CountBlank";e[e.CountIf=3]="CountIf";e[e.CountIfs=4]="CountIfs";e[e.Rank=5]="Rank";e[e.SumIf=6]="SumIf";e[e.SumIfs=7]="SumIfs";e[e.Product=8]="Product"}(_FlexSheetAggregate||(_FlexSheetAggregate={}));!function(e){e[e.Average=1]="Average";e[e.Count=2]="Count";e[e.CountA=3]="CountA";e[e.Max=4]="Max";e[e.Min=5]="Min";e[e.Product=6]="Product";e[e.Std=7]="Std";e[e.StdPop=8]="StdPop";e[e.Sum=9]="Sum";e[e.Var=10]="Var";e[e.VarPop=11]="VarPop";e[e.AverageWithoutHidden=101]="AverageWithoutHidden";e[e.CountWithoutHidden=102]="CountWithoutHidden";e[e.CountAWithoutHidden=103]="CountAWithoutHidden";e[e.MaxWithoutHidden=104]="MaxWithoutHidden";e[e.MinWithoutHidden=105]="MinWithoutHidden";e[e.ProductWithoutHidden=106]="ProductWithoutHidden";e[e.StdWithoutHidden=107]="StdWithoutHidden";e[e.StdPopWithoutHidden=108]="StdPopWithoutHidden";e[e.SumWithoutHidden=109]="SumWithoutHidden";e[e.VarWithoutHidden=110]="VarWithoutHidden";e[e.VarPopWithoutHidden=111]="VarPopWithoutHidden"}(_SubtotalFunction||(_SubtotalFunction={}));var rgLetter=/[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7B9\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/;export class _FlexSheetCellFactory extends CellFactory{updateCell(e,t,i,o,l){var s=e.grid,n=/^border/;e.cellType===CellType.Cell&&(o.style.cssText="");let r,a,h;if(e.cellType===CellType.Cell){let o=t*s.columns.length+i,n=s.selectedSheet;l&&!l.isSingleCell&&(o=l.row*s.columns.length+l.col);if((a=n&&n._styledCells?n._styledCells[o]:null)&&"pre-wrap"==a.whiteSpace&&(h=_isEditingCell(s,t,i))){r=e.rows[t]._getFlag(RowColFlags.MultiLine);e.rows[t]._setFlag(RowColFlags.MultiLine,!0,!0)}}super.updateCell(e,t,i,o,l);null!=r&&e.rows[t]._setFlag(RowColFlags.MultiLine,r,!0);if(l&&!l.isSingleCell){t=l.row;i=l.col}switch(e.cellType){case CellType.ColumnHeader:let r=e.getCellData(t,i,!0),g=o.querySelector('[type="checkbox"]'),f=null,w=null;if(g){f=g.checked;w=g.indeterminate}o.textContent?o.innerHTML=o.innerHTML.replace(escapeHtml(o.textContent),r).replace(o.textContent,r):o.innerHTML+=r;if(f||w){let e=o.querySelectorAll('[type="checkbox"]');if(e)for(let t=0;t<e.length;t++){let i=e[t];i.checked=f;i.indeterminate=w}}o.style.textAlign="center";break;case CellType.Cell:let m=s._getBindingColumn(e,t,e.columns[i]);if(l&&!l.isSingleCell){let e=this._getFirstVisibleCell(s,l);t=e.row;i=e.col}if(e.rows[t]instanceof HeaderRow){(e.columns[i].dataMapEditor===DataMapEditor.RadioButtons&&o.firstElementChild instanceof HTMLLabelElement||e.columns[i].dataType===DataType.Boolean&&1===o.childElementCount&&o.firstElementChild instanceof HTMLLabelElement&&o.firstElementChild.firstElementChild instanceof HTMLInputElement&&"checkbox"===o.firstElementChild.firstElementChild.type||e.columns[i].dataType!==DataType.Boolean&&!o.innerHTML)&&(o.innerHTML=escapeHtml(s.getCellValue(t,i)));addClass(o,"wj-header-row")}else{if(h){let e=o.querySelector("input");e&&a&&a.textAlign&&(e.style.textAlign=a.textAlign)}else{let l=e.rows[t]instanceof GroupRow;if(e.columns[i].dataType===DataType.Boolean){let e=o.querySelector('[type="checkbox"]');if(e){e.checked=s.getCellValue(t,i);e.disabled=e.disabled||!s.canEditCell(t,i)}}else if(m.dataMap&&!l){let e=s.getCellValue(t,i,!0),l=o.firstChild;l&&3===l.nodeType&&l.nodeValue!==e&&(l.nodeValue=e)}else if(0===o.childElementCount&&o.textContent===s.getCellData(t,i,!0)){let e=s.getCellValue(t,i,!0),n=(a?a.format:null)||(l?null:m.format);if(""!==e&&isNumber(+e)&&!isNaN(+e)&&/[hsmy\:]/i.test(n)){let t=FlexSheet._fromOADate(+e);isNaN(t.getTime())||(e=Globalize.formatDate(t,n))}if(n||!l){e=isString(e)?e.replace(/^(\')(\s*[\w|=])/,"$2"):e;isString(e)?e&&this._isURL(e)?o.innerHTML='<a href="'+e+'" target="_blank">'+escapeHtml(e)+"</a>":o.innerHTML=escapeHtml(e):o.innerHTML=e}}}if(a){var d,u=o.style;for(var c in a)if("className"===c)a.className&&addClass(o,a.className);else if("format"!==c&&(d=a[c]))if(!hasClass(o,"wj-state-selected")&&!hasClass(o,"wj-state-multi-selected")||"color"!==c&&"backgroundColor"!==c)if("whiteSpace"===c&&"normal"===d)u[c]="";else{if(n.test(c))continue;u[c]=d}else u[c]=""}var _=this._getCellBorders(s,s.selectedSheet,l||new CellRange(t,i));if(_)for(let e in _)o.style[e]=_[e]}if(o.style.backgroundColor||o.style.color){a||(a={});o.style.backgroundColor&&(a.backgroundColor=o.style.backgroundColor);o.style.color&&(a.color=o.style.color)}}if(e.cellType===CellType.Cell){t!==s._lastVisibleFrozenRow||hasClass(o,"wj-frozen-row")||addClass(o,"wj-frozen-row");i!==s._lastVisibleFrozenColumn||hasClass(o,"wj-frozen-col")||addClass(o,"wj-frozen-col")}}_getFirstVisibleCell(e,t){var i,o;for(i=t.topRow;i<=t.bottomRow&&!e.rows[i].isVisible;i++);for(o=t.leftCol;o<=t.rightCol&&!e.columns[o].isVisible;o++);return new CellRange(i,o)}_isURL(e){return new RegExp("^(https|http|ftp|rtsp|mms)://(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].[a-z]{2,6})(:[0-9]{1,4})?(/($|[a-zA-Z0-9.,?'\\+&amp;%$#=~_-]+))*").test(e)}_getCellBorders(e,t,i){let o=t&&t._styledCells;if(!o)return null;let l=i.topRow,s=i.leftCol,n=i.bottomRow,r=i.rightCol,a=e.columns.length;if(n>l||r>s){n=l;r=s}let h=o[l*a+s],d=o[n*a+r],u=s>0?o[l*a+s-1]:null,c=r+1<a?o[l*a+r+1]:null,_=l>0?o[(l-1)*a+s]:null,g=o[(n+1)*a+s];if(!(h||d||u||c||_||g))return null;let f={},w=h&&h.borderLeftStyle&&"none"!==h.borderLeftStyle&&!(!h.borderLeftColor&&!h.borderLeftWidth),m=u&&u.borderRightStyle&&"none"!==u.borderRightStyle&&!(!u.borderRightColor&&!u.borderRightWidth);if(!w&&m||w&&m&&parseInt(u.borderRightWidth||1)>parseInt(h.borderLeftWidth||1)){if("double"!==u.borderRightStyle){f.borderLeftColor=u.borderRightColor;f.borderLeftStyle=u.borderRightStyle;f.borderLeftWidth=Math.floor(parseInt(u.borderRightWidth||1)/2)+"px"}}else if(w){f.borderLeftColor=h.borderLeftColor;f.borderLeftStyle=h.borderLeftStyle;f.borderLeftWidth="double"!==h.borderLeftStyle?Math.ceil(parseInt(h.borderLeftWidth||1)/2)+"px":f.borderLeftWidth=h.borderLeftWidth}let p=h&&h.borderTopStyle&&"none"!==h.borderTopStyle&&!(!h.borderTopColor&&!h.borderTopWidth),C=_&&_.borderBottomStyle&&"none"!==_.borderBottomStyle&&!(!_.borderBottomColor&&!_.borderBottomWidth);if(!p&&C||p&&C&&parseInt(_.borderBottomWidth||1)>parseInt(h.borderTopWidth||1)){if("double"!==_.borderBottomStyle){f.borderTopColor=_.borderBottomColor;f.borderTopStyle=_.borderBottomStyle;f.borderTopWidth=Math.floor(parseInt(_.borderBottomWidth||1)/2)+"px"}}else if(p){f.borderTopColor=h.borderTopColor;f.borderTopStyle=h.borderTopStyle;f.borderTopWidth="double"!==h.borderTopStyle?Math.ceil(parseInt(h.borderTopWidth||1)/2)+"px":h.borderTopStyle}let S=d&&d.borderRightStyle&&"none"!==d.borderRightStyle&&!(!d.borderRightColor&&!d.borderRightWidth),b=c&&c.borderLeftStyle&&"none"!==c.borderLeftStyle&&!(!c.borderLeftColor&&!c.borderLeftWidth);if(!S&&b||S&&b&&parseInt(c.borderLeftWidth||1)>=parseInt(d.borderRightWidth||1)){if("double"!==c.borderLeftStyle){f.borderRightColor=c.borderLeftColor;f.borderRightStyle=c.borderLeftStyle;f.borderRightWidth=Math.floor(parseInt(c.borderLeftWidth||1)/2)+"px"}}else if(S){f.borderRightColor=d.borderRightColor;f.borderRightStyle=d.borderRightStyle;f.borderRightWidth="double"!==d.borderRightStyle?Math.ceil(parseInt(d.borderRightWidth||1)/2)+"px":d.borderRightWidth}let R=d&&d.borderBottomStyle&&"none"!==d.borderBottomStyle&&!(!d.borderBottomColor&&!d.borderBottomWidth),y=g&&g.borderTopStyle&&"none"!==g.borderTopStyle&&!(!g.borderTopColor&&!g.borderTopWidth);if(!R&&y||R&&y&&parseInt(g.borderTopWidth||1)>=parseInt(d.borderBottomWidth||1)){if("double"!==g.borderTopStyle){f.borderBottomColor=g.borderTopColor;f.borderBottomStyle=g.borderTopStyle;f.borderBottomWidth=Math.floor(parseInt(g.borderTopWidth||1)/2)+"px"}}else if(R){f.borderBottomColor=d.borderBottomColor;f.borderBottomStyle=d.borderBottomStyle;f.borderBottomWidth="double"!==d.borderBottomStyle?Math.ceil(parseInt(d.borderBottomWidth||1)/2)+"px":d.borderBottomWidth}return f}}_registerModule("wijmo.grid.sheet",selfModule);