all files / workbook/integrations/ save.js

64.21% Statements 174/271
60.95% Branches 103/169
74.29% Functions 26/35
64.29% Lines 171/266
11 statements, 6 functions, 9 branches Ignored     
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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416  1× 1× 1× 1× 1× 1×   1× 1× 1× 1×     1×                     1×   1× 1× 1× 1× 1445× 1445× 1445× 1445× 1445× 1445× 1445× 1445× 1445× 1445×   1× 220207×   1× 1439× 1439× 1439× 1439× 1439× 1439× 1439× 1439× 1439×   1× 1445× 1445×   1× 1439× 33× 33×     1× 1× 1×         1× 1× 1× 1×     1× 1× 1×           1× 1×   1× 1×             1× 1× 1× 1×   1× 1×   1× 1× 1× 1×     1×                                                     1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1×           1×                               1× 1× 1×             1× 1× 1×     1× 1× 1× 1× 1×     1× 1× 1× 1× 1×     1×   1× 1× 1× 1×                             1×                                                               1×                 1×                                                   1× 6× 6× 1× 1×         5×     1× 14× 14× 14× 11× 11×   14× 1×   14× 14× 14× 14× 3093× 471×   2622× 1×     2621× 117× 915× 915× 915× 898× 894×       4× 4× 4×         4×   898×                         2621× 4× 8× 8× 4×       2621× 13×   2621× 37× 2× 2× 2× 2×   2×       37×   2584× 2461×     123×       14× 14×     14×   1× 4×   4× 4×   1×                     1×     1×   1×    
/* istanbul ignore next */ 
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
define(["require", "exports", "../base/index", "../common/index", "../common/index", "../common/event", "../workers/save-worker", "../common/index", "@syncfusion/ej2-base", "./save-client"], function (require, exports, index_1, index_2, index_3, events, save_worker_1, index_4, ej2_base_1, save_client_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var WorkbookSave = (function (_super) {
        __extends(WorkbookSave, _super);
        function WorkbookSave(parent) {
            var _this = _super.call(this, parent) || this;
            _this.isProcessCompleted = false;
            _this.saveJSON = {};
            _this.isFullPost = false;
            _this.needBlobData = false;
            _this.customParams = null;
            _this.pdfLayoutSettings = { fitSheetOnOnePage: false };
            _this.saveClient = new save_client_1.WorkbookSaveClient(_this.parent);
            _this.addEventListener();
            return _this;
        }
        WorkbookSave.prototype.getModuleName = function () {
            return 'workbookSave';
        };
        WorkbookSave.prototype.destroy = function () {
            this.removeEventListener();
            this.saveJSON = {};
            this.pdfLayoutSettings = {};
            this.isFullPost = null;
            this.needBlobData = null;
            this.customParams = null;
            this.isProcessCompleted = null;
            this.saveClient = null;
            this.parent = null;
        };
        WorkbookSave.prototype.addEventListener = function () {
            this.parent.on(events.beginSave, this.initiateSave, this);
            this.parent.on('getStringifyObject', this.performStringifyAction, this);
        };
        WorkbookSave.prototype.removeEventListener = function () {
            if (!this.parent.isDestroyed) {
                this.parent.off(events.beginSave, this.initiateSave);
                this.parent.off('getStringifyObject', this.performStringifyAction);
            }
        };
        WorkbookSave.prototype.initiateSave = function (args) {
            var saveSettings = args.saveSettings;
            this.saveSettings = {
                saveType: saveSettings.saveType,
                url: saveSettings.url,
                fileName: saveSettings.fileName || 'Sample'
            };
            this.saveSettings.skipWorkerPipeline = args.skipWorkerPipeline;
            this.isFullPost = args.isFullPost;
            this.needBlobData = args.needBlobData;
            Iif (this.needBlobData) {
                this.isFullPost = false;
            }
            this.customParams = args.customParams;
            this.pdfLayoutSettings = args.pdfLayoutSettings;
            Iif ((!saveSettings.url || saveSettings.url.trim() === '') &&
                (!this.parent.saveUrl || this.parent.saveUrl.trim() === '') &&
                (saveSettings.saveType === 'Xlsx' || ej2_base_1.isUndefined(saveSettings.saveType))) {
                this.saveClient.save(saveSettings.fileName || 'Sample', this.needBlobData);
                return;
            }
            this.updateBasicSettings();
            this.processSheets(saveSettings.autoDetectFormat, args.jsonConfig, args.skipWorkerPipeline);
        };
        WorkbookSave.prototype.updateBasicSettings = function () {
            var jsonStr = this.getStringifyObject(this.parent, ['sheets', '_isScalar', 'observers', 'closed', 'isStopped', 'hasError',
                '__isAsync', 'beforeCellFormat', 'beforeCellRender', 'beforeDataBound', 'beforeOpen', 'beforeSave', 'beforeSelect',
                'beforeSort', 'cellEdit', 'cellEdited', 'cellEditing', 'cellSave', 'beforeCellSave', 'contextMenuItemSelect', 'contextMenuBeforeClose',
                'contextMenuBeforeOpen', 'created', 'dataBound', 'fileMenuItemSelect', 'fileMenuBeforeClose', 'fileMenuBeforeOpen',
                'saveComplete', 'sortComplete', 'select', 'actionBegin', 'actionComplete', 'afterHyperlinkClick', 'afterHyperlinkCreate',
                'beforeHyperlinkClick', 'beforeHyperlinkCreate', 'openComplete', 'openFailure', 'queryCellInfo', 'dialogBeforeOpen',
                'dataSourceChanged', 'beforeConditionalFormat', 'beforeCellUpdate', 'promptRequest', 'promptResponse', 'beforeWebMcpToolExecute']);
            var basicSettings = JSON.parse(jsonStr);
            var sheetCount = this.parent.sheets.length;
            Eif (sheetCount) {
                basicSettings.sheets = [];
            }
            this.saveJSON = basicSettings;
            this.saveJSON.filterCollection = [];
        };
        WorkbookSave.prototype.processSheets = function (autoDetectFormat, jsonConfig, isSkipWorkerPipeline) {
            var _this = this;
            var skipProps = ['dataSource', 'startCell', 'query', 'showFieldAsHeader', 'result', 'preservePos'];
            Iif (this.parent.isAngular) {
                skipProps.push('template');
            }
            Iif (jsonConfig) {
                if (jsonConfig.onlyValues) {
                    skipProps.push.apply(skipProps, ['style', 'formula', 'format', 'conditionalFormats', 'validation',
                        'hyperlink', 'wrap', 'chart', 'image', 'notes']);
                }
                else {
                    var ignoreProps = {
                        style: jsonConfig.ignoreStyle,
                        formula: jsonConfig.ignoreFormula,
                        format: jsonConfig.ignoreFormat,
                        conditionalFormats: jsonConfig.ignoreConditionalFormat,
                        validation: jsonConfig.ignoreValidation,
                        wrap: jsonConfig.ignoreWrap,
                        chart: jsonConfig.ignoreChart,
                        image: jsonConfig.ignoreImage,
                        notes: jsonConfig.ignoreNote
                    };
                    if (jsonConfig.ignoreFreezePane) {
                        skipProps.push.apply(skipProps, ['frozenColumns', 'frozenRows']);
                    }
                    for (var prop in ignoreProps) {
                        if (ignoreProps[prop]) {
                            skipProps.push(prop);
                        }
                    }
                }
            }
            var isNotLoaded;
            var isDataBinding;
            var sheet;
            var range;
            var _loop_1 = function (sheetIdx, sheetCount) {
                sheet = this_1.parent.sheets[sheetIdx];
                isNotLoaded = false;
                isDataBinding = false;
                for (var rangeIdx = 0, rangeCount = sheet.ranges.length; rangeIdx < rangeCount; rangeIdx++) {
                    range = sheet.ranges[rangeIdx];
                    Eif (range.dataSource) {
                        isDataBinding = true;
                        Iif (!range.info || !range.info.loadedRange || !range.info.loadedRange.length) {
                            isNotLoaded = true;
                            break;
                        }
                    }
                }
                Iif (isNotLoaded) {
                    var loadCompleteHandler = function (idx) {
                        if (isSkipWorkerPipeline) {
                            var json = _this.getStringifyObject(_this.parent.sheets[idx], skipProps, idx, false, true);
                            _this.updateSheet(_this.processSheet(json, sheetIdx));
                        }
                        else {
                            index_2.executeTaskAsync(_this, _this.processSheet, _this.updateSheet, [_this.getStringifyObject(_this.parent.sheets[idx], skipProps, idx, false, true), idx], null, _this.parent);
                        }
                    };
                    this_1.parent.notify(index_4.updateSheetFromDataSource, {
                        sheet: sheet, sheetIndex: sheetIdx, loadComplete: loadCompleteHandler.bind(this_1, sheetIdx),
                        loadFromStartCell: true, autoDetectFormat: autoDetectFormat
                    });
                }
                else {
                    Eif (isSkipWorkerPipeline) {
                        var json = this_1.getStringifyObject(sheet, skipProps, sheetIdx, autoDetectFormat && isDataBinding, true);
                        this_1.updateSheet(this_1.processSheet(json, sheetIdx));
                    }
                    else {
                        index_2.executeTaskAsync(this_1, this_1.processSheet, this_1.updateSheet, [this_1.getStringifyObject(sheet, skipProps, sheetIdx, autoDetectFormat && isDataBinding, true), sheetIdx], null, this_1.parent);
                    }
                }
            };
            var this_1 = this;
            for (var sheetIdx = 0, sheetCount = this.parent.sheets.length; sheetIdx < sheetCount; sheetIdx++) {
                _loop_1(sheetIdx, sheetCount);
            }
        };
        WorkbookSave.prototype.updateSheet = function (data) {
            this.saveJSON.sheets[data[0]] = data[1];
            this.isProcessCompleted = this.getSheetLength(this.saveJSON.sheets) === this.parent.sheets.length;
            Eif (this.isProcessCompleted) {
                this.save(this.saveSettings);
            }
        };
        WorkbookSave.prototype.getSheetLength = function (sheets) {
            var len = 0;
            sheets.forEach(function (sheet) {
                Eif (sheet) {
                    len++;
                }
            });
            return len;
        };
        WorkbookSave.prototype.save = function (saveSettings) {
            var args = { cancel: false, jsonObject: this.saveJSON };
            this.parent.notify(events.onSave, args);
            Iif (!args.cancel) {
                if (this.isFullPost) {
                    this.initiateFullPostSave();
                    this.saveJSON = {};
                }
                else {
                    if (saveSettings.skipWorkerPipeline) {
                        this.processSave(this.saveJSON, saveSettings, this.customParams, this.pdfLayoutSettings, this.updateSaveResult);
                    }
                    else {
                        index_2.executeTaskAsync(this, { 'workerTask': this.processSave }, this.updateSaveResult, [this.saveJSON, saveSettings, this.customParams, this.pdfLayoutSettings], true, this.parent);
                    }
                }
            }
        };
        WorkbookSave.prototype.updateSaveResult = function (result) {
            if (result.isFormDataError) {
                this.processSave(this.saveJSON, this.saveSettings, this.customParams, this.pdfLayoutSettings, this.updateSaveResult);
                return;
            }
            this.saveJSON = {};
            var args = {
                status: 'Success',
                message: '',
                url: this.saveSettings.url,
                fileName: this.saveSettings.fileName,
                saveType: this.saveSettings.saveType,
                blobData: null
            };
            if (typeof (result) === 'object' && result.error) {
                args.status = 'Failure';
                args.message = result.error.toString();
            }
            else if (typeof (result) === 'object' && result.dialog) {
                this.parent.notify(events.saveError, { content: result.dialog });
            }
            else {
                if (this.needBlobData) {
                    args.blobData = result;
                }
                else {
                    this.ClientFileDownload(result);
                }
            }
            this.parent.trigger('saveComplete', args);
            this.parent.notify(events.saveCompleted, args);
        };
        WorkbookSave.prototype.ClientFileDownload = function (blobData) {
            var anchor = this.parent.createElement('a', { attrs: { download: this.getFileNameWithExtension() } });
            var url = URL.createObjectURL(blobData);
            anchor.href = url;
            document.body.appendChild(anchor);
            anchor.click();
            URL.revokeObjectURL(url);
            document.body.removeChild(anchor);
        };
        WorkbookSave.prototype.initiateFullPostSave = function () {
            var keys = Object.keys(this.saveSettings);
            var i;
            var formElem = this.parent.createElement('form', { attrs: { method: 'POST', action: this.saveSettings.url } });
            var inputElem = this.parent.createElement('input', { attrs: { type: 'hidden', name: 'JSONData' } });
            inputElem.value = JSON.stringify(this.saveJSON);
            formElem.appendChild(inputElem);
            for (i = 0; i < keys.length; i++) {
                inputElem = this.parent.createElement('input', { attrs: { type: 'hidden', name: keys[i] } });
                inputElem.value = this.saveSettings[keys[i]];
                formElem.appendChild(inputElem);
            }
            keys = Object.keys(this.customParams);
            for (i = 0; i < keys.length; i++) {
                inputElem = this.parent.createElement('input', { attrs: { type: 'hidden', name: keys[i] } });
                inputElem.value = this.customParams[keys[i]];
                formElem.appendChild(inputElem);
            }
            inputElem = this.parent.createElement('input', { attrs: { type: 'hidden', name: 'pdfLayoutSettings' } });
            inputElem.value = JSON.stringify(this.pdfLayoutSettings);
            formElem.appendChild(inputElem);
            document.body.appendChild(formElem);
            formElem.submit();
            ej2_base_1.detach(formElem);
            this.parent.notify(events.saveCompleted, {});
        };
        WorkbookSave.prototype.performStringifyAction = function (args) {
            args.model = '{"jsonObject":{"Workbook":{"sheets":[';
            if (args.sheetIdx === undefined) {
                for (var sheetIdx = 0, sheetCount = this.parent.sheets.length - 1; sheetIdx <= sheetCount; sheetIdx++) {
                    args.model += this.getStringifyObject(this.parent.sheets[sheetIdx], args.skipProps, sheetIdx) +
                        (sheetIdx < sheetCount ? ',' : ']}}}');
                }
            }
            else {
                args.model += this.getStringifyObject(this.parent.sheets[args.sheetIdx], args.skipProps, args.sheetIdx) + ']}}}';
            }
        };
        WorkbookSave.prototype.getStringifyObject = function (model, skipProp, sheetIdx, autoDetectFormat, isSaveAction) {
            var _this = this;
            Iif (skipProp === void 0) { skipProp = []; }
            if (sheetIdx === 0) {
                this.parent.notify(index_3.removeUniquecol, { clearAll: true });
                this.parent.notify(index_3.removeSortcol, { clearAll: true });
            }
            if (isSaveAction) {
                this.parent.notify(events.setFilteredCollection, { sheetIdx: sheetIdx, isSaveAction: true, saveJson: this.saveJSON });
            }
            var chartColl = [];
            var chartModel;
            var autoDetectFormatFn = autoDetectFormat && index_2.getAutoDetectFormatParser(this.parent);
            var json = JSON.stringify(model, function (key, value) {
                if (skipProp.indexOf(key) > -1) {
                    return undefined;
                }
                else if (key === 'cellStyle') {
                    return _this.parent.commonCellStyle;
                }
                else {
                    if (value && value.cells) {
                        for (var i = 0, len = value.cells.length; i < len; i++) {
                            var cell = value.cells[i];
                            var cellIdx = [Number(key), i];
                            if (cell) {
                                if (cell.value) {
                                    Iif (autoDetectFormat && !cell.formula) {
                                        autoDetectFormatFn(cell);
                                    }
                                }
                                else Eif (cell.formula && cell.formula.indexOf('=UNIQUE(') < 0) {
                                    Eif (_this.parent.calculationMode === 'Automatic') {
                                        _this.parent.notify(index_3.workbookFormulaOperation, {
                                            action: 'refreshCalculate', value: cell.formula, rowIndex: cellIdx[0],
                                            colIndex: i, isFormula: index_3.checkIsFormula(cell.formula), sheetIndex: sheetIdx, isRefreshing: true
                                        });
                                    }
                                    cell.value = index_1.getCell(cellIdx[0], i, model).value;
                                }
                                Iif (cell.chart) {
                                    chartColl.push({ index: cellIdx, chart: cell.chart });
                                    chartModel = [];
                                    for (var i_1 = 0, len_1 = cell.chart.length; i_1 < len_1; i_1++) {
                                        var chart = Object.assign({}, cell.chart[i_1]);
                                        delete chart.id;
                                        chartModel.push(chart);
                                    }
                                    cell.chart = chartModel;
                                }
                            }
                        }
                    }
                    if (key === 'validation' && value && typeof value.type === 'string' && value.type === 'Time') {
                        ['value1', 'value2'].forEach(function (valKey) {
                            var val = value[valKey] && value[valKey].toString();
                            if (val && !index_2.isNumber(Number(val))) {
                                value[valKey] = _this.getDateAsNumber({ range: [], cell: { value: val } }, val);
                            }
                        });
                    }
                    if (value && value.properties && value.maxHgts) {
                        value.properties = __assign({}, value.properties, { maxHgts: value.maxHgts });
                    }
                    if (value && typeof value === 'object' && value.hasOwnProperty('properties')) {
                        if (value.propName && value.propName.toString() === 'conditionalFormats') {
                            var properties = value.properties;
                            Eif (properties.format && properties.format.style) {
                                var style = properties.format.style;
                                Eif (style && style.backgroundColor === '#ffffff' && style.color === '#000000' &&
                                    style.fontWeight !== 'bold' && style.fontStyle !== 'italic' && style.textDecoration !== 'underline') {
                                    delete properties.format;
                                }
                            }
                        }
                        return value.properties;
                    }
                    else if (value !== null) {
                        return value;
                    }
                    else {
                        return undefined;
                    }
                }
            });
            var sheet = index_1.getSheet(this.parent, sheetIdx);
            chartColl.forEach(function (obj) {
                index_1.setCell(obj.index[0], obj.index[1], sheet, { chart: obj.chart }, true);
            });
            return json;
        };
        WorkbookSave.prototype.getDateAsNumber = function (args, cellValue) {
            var dateEventArgs = { value: cellValue, rowIndex: args.range[0], cell: args.cell,
                colIndex: args.range[1], sheetIndex: args.sheetIdx, updatedVal: '' };
            this.parent.notify(index_2.checkDateFormat, dateEventArgs);
            return dateEventArgs.updatedVal || cellValue;
        };
        WorkbookSave.prototype.getFileNameWithExtension = function (filename) {
            if (!filename) {
                filename = this.saveSettings.fileName;
            }
            var fileExt = this.getFileExtension();
            var idx = filename.lastIndexOf('.');
            if (idx > -1) {
                filename = filename.substr(0, idx);
            }
            return (filename + fileExt);
        };
        WorkbookSave.prototype.getFileExtension = function () {
            return ('.' + this.saveSettings.saveType.toLowerCase());
        };
        return WorkbookSave;
    }(save_worker_1.SaveWorker));
    exports.WorkbookSave = WorkbookSave;
});