all files / workbook/integrations/ open.js

57.14% Statements 120/210
51.08% Branches 71/139
70.37% Functions 19/27
56.94% Lines 119/209
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341   1051× 1051× 1051× 1051× 1051× 1051×   27×   27× 27×     27× 23× 23×                                                                                                                           25×   25× 25× 25× 25×                   25× 23× 23× 23×                                                                                                                                                                                                     25× 23× 23× 23× 23× 23× 23× 23×                   23× 14×   23× 23× 23× 23× 23×   25× 25× 25× 25× 25×                   25×                                   39× 30×     1051× 1051×   1048× 14× 14×     1048× 1048× 1035×   1048×   150870×        
define(["require", "exports", "@syncfusion/ej2-base", "../common/index", "../common/index", "../base/index", "../../spreadsheet/common/event"], function (require, exports, ej2_base_1, index_1, index_2, index_3, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var WorkbookOpen = (function () {
        function WorkbookOpen(parent) {
            this.loopIndex = 0;
            this.processedLoopIndex = 0;
            this.retryCount = 0;
            this.currentDocumentId = null;
            this.parent = parent;
            this.addEventListener();
        }
        WorkbookOpen.prototype.open = function (options) {
            this.load(options);
        };
        WorkbookOpen.prototype.load = function (options, isRetryRequest) {
            var _this = this;
            Iif (!this.parent.allowOpen) {
                return;
            }
            if (options.jsonObject) {
                this.fetchSuccess(options.jsonObject, options, null, true, true);
                return;
            }
            var formData = new FormData();
            if (options.file) {
                formData.append('file', options.file);
            }
            else Iif (options.sheetIndex >= 0) {
                formData.append('sheetPassword', options.sheetPassword);
                formData.append('sheetIndex', options.sheetIndex.toString());
            }
            else {
                this.parent.isOpen = false;
                return;
            }
            var args = { passWord: '' };
            Iif (options.password && options.password.length) {
                args.passWord = options.password;
            }
            Iif (args.passWord && args.passWord.length) {
                options.password = args.passWord;
            }
            Iif (options.password) {
                formData.append('password', options.password);
            }
            formData.append('IsManualCalculationEnabled', (this.parent.calculationMode === 'Manual').toString());
            var eventArgs = {
                file: options.file || null,
                cancel: false,
                requestData: {
                    method: 'POST',
                    body: formData
                },
                password: args.passWord
            };
            var guid = options.guid;
            Eif (ej2_base_1.isNullOrUndefined(options.sheetPassword) && !guid && ej2_base_1.isNullOrUndefined(isRetryRequest)) {
                this.parent.trigger('beforeOpen', eventArgs);
                this.parent.notify(index_2.beginAction, { eventArgs: eventArgs, action: 'beforeOpen' });
            }
            else if (guid) {
                formData.append('guid', guid);
            }
            if (eventArgs.cancel) {
                this.parent.isOpen = false;
                return;
            }
            var header = { chunkSize: null, documentId: null };
            if (this.parent.openSettings.chunkSize > 0 && ej2_base_1.isNullOrUndefined(options.sheetPassword)) {
                this.setToDefaults(isRetryRequest);
                Eif (!ej2_base_1.isNullOrUndefined(this.parent.openSettings.chunkSize) && this.parent.openSettings.chunkSize !== 0) {
                    header.chunkSize = this.parent.openSettings.chunkSize.toString();
                }
                Iif (!ej2_base_1.isNullOrUndefined(this.currentDocumentId)) {
                    header.documentId = this.currentDocumentId;
                }
                Eif (!ej2_base_1.isNullOrUndefined(header)) {
                    formData.append('chunkPayload', JSON.stringify(header));
                }
            }
            fetch(this.parent.openUrl, eventArgs.requestData)
                .then(function (response) {
                Eif (response.ok) {
                    return response.json();
                }
                else {
                    return Promise.reject({
                        status: response.status,
                        statusText: response.statusText,
                        url: response.url
                    });
                }
            })
                .then(function (data) { return _this.fetchSuccess(data, eventArgs, options.orginalFile, undefined, true); })
                .catch(function (error) {
                if (error.toString().indexOf('Unexpected end of JSON input') === -1 && _this.parent.openSettings.chunkSize > 0 && _this.retryCount < _this.parent.openSettings.retryCount) {
                    setTimeout(function () {
                        _this.retryCount++;
                        _this.load(options, true);
                    }, _this.parent.openSettings.retryAfterDelay);
                }
                else {
                    if (_this.retryCount >= _this.parent.openSettings.retryCount) {
                        _this.retryCount = 0;
                    }
                    _this.fetchFailure(error);
                }
            });
        };
        WorkbookOpen.prototype.fetchFailure = function (error) {
            if (ej2_base_1.isUndefined(error.status) && ej2_base_1.isUndefined(error.statusText)) {
                error.statusText = 'Improper response';
            }
            this.parent.notify(index_1.openFailure, error);
            this.parent.isOpen = false;
        };
        WorkbookOpen.prototype.fetchSuccess = function (data, eventArgs, file, isOpenFromJson, isImport) {
            var openError = ['UnsupportedFile', 'InvalidUrl', 'NeedPassword', 'InCorrectPassword', 'InCorrectSheetPassword',
                'CorrectSheetPassword', 'DataLimitExceeded', 'FileSizeLimitExceeded', 'ExternalWorkbook'];
            var workbookData = typeof data === 'string' ? JSON.parse(data) : data;
            var impData = workbookData.Workbook;
            Eif (!ej2_base_1.isNullOrUndefined(impData)) {
                Iif (openError.indexOf(impData) > -1) {
                    if (file) {
                        eventArgs.file = file;
                    }
                    this.parent.notify(index_1.openSuccess, {
                        context: this, data: impData, guid: workbookData.Guid, eventArgs: eventArgs,
                        isOpenFromJson: isOpenFromJson
                    });
                    return;
                }
                this.updateModel(impData, isOpenFromJson, isImport);
                this.parent.notify(index_1.openSuccess, { context: this, data: impData, isOpenFromJson: isOpenFromJson, eventArgs: eventArgs });
                this.parent.isOpen = false;
                Iif (eventArgs && eventArgs.password && eventArgs.password.length > 0) {
                    if (this.parent.showSheetTabs) {
                        this.parent.element.querySelector('.e-add-sheet-tab').removeAttribute('disabled');
                        this.parent.element.querySelector('.e-add-sheet-tab').classList.remove('e-disabled');
                    }
                    this.parent.password = '';
                }
            }
            else {
                var totalChunk = workbookData.chunkTotalCount;
                this.currentDocumentId = workbookData.documentId;
                this.chunkList = new Array(totalChunk);
                var processedChunkIndex = 0;
                var chunkLimit = totalChunk > this.parent.openSettings.chunkSize ? this.parent.openSettings.chunkSize : totalChunk;
                var processedLoopIndex = 0;
                this.processedLoopIndex = 0;
                var binaryString = '';
                var instance = this;
                if (!ej2_base_1.isNullOrUndefined(totalChunk)) {
                    while (processedChunkIndex < totalChunk) {
                        instance.processChunk(processedChunkIndex, chunkLimit, processedLoopIndex, binaryString, eventArgs, file, isOpenFromJson, isImport);
                        processedChunkIndex += instance.parent.openSettings.chunkSize;
                        chunkLimit = processedChunkIndex + instance.parent.openSettings.chunkSize < totalChunk ?
                            instance.parent.openSettings.chunkSize : totalChunk - processedChunkIndex;
                        processedLoopIndex++;
                        instance.processedLoopIndex++;
                    }
                }
            }
        };
        WorkbookOpen.prototype.processChunk = function (processedChunkIndex, chunkLimit, processedLoopIndex, binaryString, eventArgs, file, isOpenFromJson, isImport) {
            var instance = this;
            var header = {
                currentChunk: processedChunkIndex.toString(), chunkSize: chunkLimit.toString(),
                loopIndex: processedLoopIndex.toString(), documentId: this.currentDocumentId
            };
            var formData = new FormData();
            formData.append('chunkPayload', JSON.stringify(header));
            var requestEventArgs = {
                file: file || null,
                cancel: false,
                requestData: {
                    method: 'POST',
                    body: formData
                },
                password: eventArgs.password
            };
            fetch(this.parent.openUrl, requestEventArgs.requestData)
                .then(function (response) {
                if (response.ok) {
                    return response.json();
                }
                else {
                    return Promise.reject({
                        status: response.status,
                        statusText: response.statusText,
                        url: response.url
                    });
                }
            })
                .then(function (data) {
                if (data !== '') {
                    var chunks = atob(data['chunk']);
                    var bytes = new Uint8Array(chunks.length);
                    for (var i = 0; i < chunks.length; i++) {
                        bytes[i] = chunks.charCodeAt(i);
                    }
                    chunks = new TextDecoder('utf-8').decode(bytes);
                    instance.chunkList[data['loopIndex']] = chunks;
                    instance.loopIndex++;
                    if (instance.loopIndex === instance.processedLoopIndex) {
                        var splicedArray = instance.chunkList.splice(0, instance.loopIndex);
                        for (var k = 0; k < splicedArray.length; k++) {
                            binaryString += splicedArray.slice(k, k + 1).join('');
                        }
                        data = JSON.parse(binaryString);
                        instance.setToDefaults();
                        instance.fetchSuccess(data, eventArgs, file, isOpenFromJson, isImport);
                    }
                }
            })
                .catch(function (error) {
                if (ej2_base_1.isNullOrUndefined(instance.currentFailedChunkIndex) || instance.currentFailedChunkIndex === processedChunkIndex) {
                    instance.currentFailedChunkIndex = processedChunkIndex;
                    if (instance.retryCount < instance.parent.openSettings.retryCount) {
                        setTimeout(function () {
                            instance.processedLoopIndex = processedLoopIndex;
                            instance.processChunk(processedChunkIndex, chunkLimit, processedLoopIndex, binaryString, eventArgs, file, isOpenFromJson, isImport);
                            instance.retryCount++;
                        }, instance.parent.openSettings.retryAfterDelay);
                    }
                    else {
                        instance.retryCount = 0;
                        return instance.fetchFailure(error);
                    }
                }
            });
        };
        WorkbookOpen.prototype.setToDefaults = function (isRetryRequest) {
            this.currentFailedChunkIndex = null;
            Eif (!isRetryRequest) {
                this.retryCount = 0;
            }
            this.loopIndex = 0;
            this.processedLoopIndex = 0;
            this.chunkList = [];
        };
        WorkbookOpen.prototype.updateModel = function (workbookModel, isOpenFromJson, isImport) {
            this.parent.notify(index_1.workbookFormulaOperation, { action: 'unRegisterSheet' });
            this.setSelectAllRange(workbookModel.sheets, isOpenFromJson);
            this.parent.sheetNameCount = 1;
            this.parent.sheets = [];
            this.parent.notify(index_1.sheetsDestroyed, {});
            this.parent.notify(event_1.clearUndoRedoCollection, null);
            workbookModel.activeSheetIndex = workbookModel.activeSheetIndex || workbookModel.sheets.findIndex(function (sheet) { return sheet.state !== 'Hidden'; });
            this.parent.setProperties({
                'isProtected': workbookModel.isProtected || false,
                'password': workbookModel.password || '',
                'sheets': workbookModel.sheets,
                'activeSheetIndex': workbookModel.activeSheetIndex,
                'definedNames': workbookModel.definedNames || [],
                'filterCollection': workbookModel.filterCollection || [],
                'sortCollection': workbookModel.sortCollection || [],
                'listSeparator': workbookModel.listSeparator || this.parent.listSeparator
            }, true);
            if (!ej2_base_1.isNullOrUndefined(workbookModel.showSheetTabs)) {
                this.parent.showSheetTabs = workbookModel.showSheetTabs;
            }
            index_3.initSheet(this.parent, undefined, isImport);
            this.parent.notify(index_2.sheetCreated, null);
            this.parent.notify(index_1.workbookFormulaOperation, { action: 'registerSheet', isImport: true });
            this.parent.notify(index_1.workbookFormulaOperation, { action: 'initiateDefinedNames' });
            this.parent.notify(index_2.protectSheetWorkBook, null);
        };
        WorkbookOpen.prototype.setSelectAllRange = function (sheets, isOpenFromJson) {
            var _this = this;
            var curSheet;
            var curRange;
            sheets.forEach(function (sheet) {
                if (sheet.selectedRange) {
                    var selectedIndex = index_1.getRangeIndexes(sheet.selectedRange);
                    var rowCount = (ej2_base_1.isUndefined(sheet.rowCount) ? 100 : sheet.rowCount) - 1;
                    var colCount = (ej2_base_1.isUndefined(sheet.colCount) ? 100 : sheet.colCount) - 1;
                    Iif (selectedIndex[2] === 65535) {
                        selectedIndex[2] = rowCount;
                    }
                    Iif (selectedIndex[3] === 255) {
                        selectedIndex[3] = colCount;
                    }
                    Iif (selectedIndex[0] === 65535) {
                        selectedIndex[0] = rowCount;
                    }
                    Iif (selectedIndex[1] === 255) {
                        selectedIndex[1] = colCount;
                    }
                    sheet.selectedRange = index_2.getRangeAddress(selectedIndex);
                }
                Iif (isOpenFromJson && _this.parent.isAngular) {
                    for (var i = 0; i < _this.parent.sheets.length; i++) {
                        curSheet = index_3.getSheet(_this.parent, i);
                        if (sheet.name === curSheet.name) {
                            if (sheet.ranges) {
                                sheet.ranges.forEach(function (range, index) {
                                    curRange = curSheet.ranges[index];
                                    if (curRange && curRange.template) {
                                        range.template = curRange.template;
                                    }
                                });
                            }
                            break;
                        }
                    }
                }
            });
        };
        WorkbookOpen.prototype.sheetsDestroyHandler = function (args) {
            if (ej2_base_1.isNullOrUndefined(args.sheetIndex)) {
                this.preventFormatCheck = null;
            }
        };
        WorkbookOpen.prototype.addEventListener = function () {
            this.parent.on(index_1.workbookOpen, this.open.bind(this));
            this.parent.on(index_1.sheetsDestroyed, this.sheetsDestroyHandler, this);
        };
        WorkbookOpen.prototype.removeEventListener = function () {
            if (!this.parent.isDestroyed) {
                this.parent.off(index_1.workbookOpen, this.open.bind(this));
                this.parent.off(index_1.sheetsDestroyed, this.sheetsDestroyHandler);
            }
        };
        WorkbookOpen.prototype.destroy = function () {
            this.removeEventListener();
            if (!this.parent.refreshing) {
                this.preventFormatCheck = null;
            }
            this.parent = null;
        };
        WorkbookOpen.prototype.getModuleName = function () {
            return 'workbookOpen';
        };
        return WorkbookOpen;
    }());
    exports.WorkbookOpen = WorkbookOpen;
});