@slickgrid-universal/text-export 2.4.1 → 2.6.0

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.
@@ -1,386 +1,386 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TextExportService = void 0;
4
- const text_encoding_utf_8_1 = require("text-encoding-utf-8");
5
- const common_1 = require("@slickgrid-universal/common");
6
- const utils_1 = require("@slickgrid-universal/utils");
7
- const DEFAULT_EXPORT_OPTIONS = {
8
- delimiter: common_1.DelimiterType.comma,
9
- filename: 'export',
10
- format: common_1.FileType.csv,
11
- useUtf8WithBom: true,
12
- };
13
- class TextExportService {
14
- constructor() {
15
- this._delimiter = ',';
16
- this._exportQuoteWrapper = '';
17
- this._fileFormat = common_1.FileType.csv;
18
- this._lineCarriageReturn = '\n';
19
- this._columnHeaders = [];
20
- this._hasGroupedItems = false;
21
- /** ExcelExportService class name which is use to find service instance in the external registered services */
22
- this.className = 'TextExportService';
23
- }
24
- get _datasetIdPropName() {
25
- return this._gridOptions && this._gridOptions.datasetIdPropertyName || 'id';
26
- }
27
- /** Getter of SlickGrid DataView object */
28
- get _dataView() {
29
- var _a;
30
- return (((_a = this._grid) === null || _a === void 0 ? void 0 : _a.getData) && this._grid.getData());
31
- }
32
- /** Getter for the Grid Options pulled through the Grid Object */
33
- get _gridOptions() {
34
- var _a;
35
- return ((_a = this._grid) === null || _a === void 0 ? void 0 : _a.getOptions) ? this._grid.getOptions() : {};
36
- }
37
- dispose() {
38
- var _a;
39
- (_a = this._pubSubService) === null || _a === void 0 ? void 0 : _a.unsubscribeAll();
40
- }
41
- /**
42
- * Initialize the Service
43
- * @param grid
44
- * @param containerService
45
- */
46
- init(grid, containerService) {
47
- var _a;
48
- this._grid = grid;
49
- this._pubSubService = containerService.get('PubSubService');
50
- // get locales provided by user in main file or else use default English locales via the Constants
51
- this._locales = this._gridOptions && this._gridOptions.locales || common_1.Constants.locales;
52
- this._translaterService = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.translater;
53
- if (this._gridOptions.enableTranslate && (!this._translaterService || !this._translaterService.translate)) {
54
- throw new Error('[Slickgrid-Universal] requires a Translate Service to be passed in the "translater" Grid Options when "enableTranslate" is enabled. (example: this.gridOptions = { enableTranslate: true, translater: this.translaterService })');
55
- }
56
- }
57
- /**
58
- * Function to export the Grid result to an Excel CSV format using javascript for it to produce the CSV file.
59
- * This is a WYSIWYG export to file output (What You See is What You Get)
60
- *
61
- * NOTES: The column position needs to match perfectly the JSON Object position because of the way we are pulling the data,
62
- * which means that if any column(s) got moved in the UI, it has to be reflected in the JSON array output as well
63
- *
64
- * Example: exportToFile({ format: FileType.csv, delimiter: DelimiterType.comma })
65
- */
66
- exportToFile(options) {
67
- if (!this._grid || !this._dataView || !this._pubSubService) {
68
- throw new Error('[Slickgrid-Universal] it seems that the SlickGrid & DataView objects and/or PubSubService are not initialized did you forget to enable the grid option flag "enableTextExport"?');
69
- }
70
- return new Promise(resolve => {
71
- var _a;
72
- (_a = this._pubSubService) === null || _a === void 0 ? void 0 : _a.publish(`onBeforeExportToTextFile`, true);
73
- this._exportOptions = (0, utils_1.deepCopy)({ ...DEFAULT_EXPORT_OPTIONS, ...this._gridOptions.textExportOptions, ...options });
74
- this._delimiter = this._exportOptions.delimiterOverride || this._exportOptions.delimiter || '';
75
- this._fileFormat = this._exportOptions.format || common_1.FileType.csv;
76
- // get the CSV output from the grid data
77
- const dataOutput = this.getDataOutput();
78
- // trigger a download file
79
- // wrap it into a setTimeout so that the EventAggregator has enough time to start a pre-process like showing a spinner
80
- setTimeout(() => {
81
- var _a;
82
- const downloadOptions = {
83
- filename: `${this._exportOptions.filename}.${this._fileFormat}`,
84
- format: this._fileFormat || common_1.FileType.csv,
85
- mimeType: this._exportOptions.mimeType || 'text/plain',
86
- useUtf8WithBom: (this._exportOptions && this._exportOptions.hasOwnProperty('useUtf8WithBom')) ? this._exportOptions.useUtf8WithBom : true
87
- };
88
- // start downloading but add the content property only on the start download not on the event itself
89
- this.startDownloadFile({ ...downloadOptions, content: dataOutput }); // add content property
90
- (_a = this._pubSubService) === null || _a === void 0 ? void 0 : _a.publish(`onAfterExportToTextFile`, downloadOptions);
91
- resolve(true);
92
- }, 0);
93
- });
94
- }
95
- /**
96
- * Triggers download file with file format.
97
- * IE(6-10) are not supported
98
- * All other browsers will use plain javascript on client side to produce a file download.
99
- * @param options
100
- */
101
- startDownloadFile(options) {
102
- // make sure no html entities exist in the data
103
- const csvContent = (0, common_1.htmlEntityDecode)(options.content);
104
- // dealing with Excel CSV export and UTF-8 is a little tricky.. We will use Option #2 to cover older Excel versions
105
- // Option #1: we need to make Excel knowing that it's dealing with an UTF-8, A correctly formatted UTF8 file can have a Byte Order Mark as its first three octets
106
- // reference: http://stackoverflow.com/questions/155097/microsoft-excel-mangles-diacritics-in-csv-files
107
- // Option#2: use a 3rd party extension to javascript encode into UTF-16
108
- let outputData;
109
- if (options.format === common_1.FileType.csv) {
110
- outputData = new text_encoding_utf_8_1.TextEncoder('utf-8').encode(csvContent);
111
- }
112
- else {
113
- outputData = csvContent;
114
- }
115
- // create a Blob object for the download
116
- const blob = new Blob([options.useUtf8WithBom ? '\uFEFF' : '', outputData], {
117
- type: options.mimeType
118
- });
119
- // when using IE/Edge, then use different download call
120
- if (typeof navigator.msSaveOrOpenBlob === 'function') {
121
- navigator.msSaveOrOpenBlob(blob, options.filename);
122
- }
123
- else {
124
- // this trick will generate a temp <a /> tag
125
- // the code will then trigger a hidden click for it to start downloading
126
- const link = document.createElement('a');
127
- const csvUrl = URL.createObjectURL(blob);
128
- link.textContent = 'download';
129
- link.href = csvUrl;
130
- link.setAttribute('download', options.filename);
131
- // set the visibility to hidden so there is no effect on your web-layout
132
- link.style.visibility = 'hidden';
133
- // this part will append the anchor tag, trigger a click (for download to start) and finally remove the tag once completed
134
- document.body.appendChild(link);
135
- link.click();
136
- document.body.removeChild(link);
137
- }
138
- }
139
- // -----------------------
140
- // protected functions
141
- // -----------------------
142
- getDataOutput() {
143
- var _a, _b, _c;
144
- const columns = this._grid.getColumns() || [];
145
- // Group By text, it could be set in the export options or from translation or if nothing is found then use the English constant text
146
- let groupByColumnHeader = this._exportOptions.groupingColumnHeaderTitle;
147
- if (!groupByColumnHeader && this._gridOptions.enableTranslate && ((_a = this._translaterService) === null || _a === void 0 ? void 0 : _a.translate) && ((_c = (_b = this._translaterService) === null || _b === void 0 ? void 0 : _b.getCurrentLanguage) === null || _c === void 0 ? void 0 : _c.call(_b))) {
148
- groupByColumnHeader = this._translaterService.translate(`${(0, common_1.getTranslationPrefix)(this._gridOptions)}GROUP_BY`);
149
- }
150
- else if (!groupByColumnHeader) {
151
- groupByColumnHeader = this._locales && this._locales.TEXT_GROUP_BY;
152
- }
153
- // a CSV needs double quotes wrapper, the other types do not need any wrapper
154
- this._exportQuoteWrapper = (this._fileFormat === common_1.FileType.csv) ? '"' : '';
155
- // data variable which will hold all the fields data of a row
156
- let outputDataString = '';
157
- // get grouped column titles and if found, we will add a "Group by" column at the first column index
158
- // if it's a CSV format, we'll escape the text in double quotes
159
- const grouping = this._dataView.getGrouping();
160
- if (grouping && Array.isArray(grouping) && grouping.length > 0) {
161
- this._hasGroupedItems = true;
162
- outputDataString += (this._fileFormat === common_1.FileType.csv) ? `"${groupByColumnHeader}"${this._delimiter}` : `${groupByColumnHeader}${this._delimiter}`;
163
- }
164
- else {
165
- this._hasGroupedItems = false;
166
- }
167
- // get all Grouped Column Header Titles when defined (from pre-header row)
168
- if (this._gridOptions.createPreHeaderPanel && this._gridOptions.showPreHeaderPanel && !this._gridOptions.enableDraggableGrouping) {
169
- this._groupedColumnHeaders = this.getColumnGroupedHeaderTitles(columns) || [];
170
- if (this._groupedColumnHeaders && Array.isArray(this._groupedColumnHeaders) && this._groupedColumnHeaders.length > 0) {
171
- // add the header row + add a new line at the end of the row
172
- const outputGroupedHeaderTitles = this._groupedColumnHeaders.map((header) => `${this._exportQuoteWrapper}${header.title}${this._exportQuoteWrapper}`);
173
- outputDataString += (outputGroupedHeaderTitles.join(this._delimiter) + this._lineCarriageReturn);
174
- }
175
- }
176
- // get all Column Header Titles
177
- this._columnHeaders = this.getColumnHeaders(columns) || [];
178
- if (this._columnHeaders && Array.isArray(this._columnHeaders) && this._columnHeaders.length > 0) {
179
- // add the header row + add a new line at the end of the row
180
- const outputHeaderTitles = this._columnHeaders.map((header) => (0, common_1.sanitizeHtmlToText)(`${this._exportQuoteWrapper}${header.title}${this._exportQuoteWrapper}`));
181
- outputDataString += (outputHeaderTitles.join(this._delimiter) + this._lineCarriageReturn);
182
- }
183
- // Populate the rest of the Grid Data
184
- outputDataString += this.getAllGridRowData(columns, this._lineCarriageReturn);
185
- return outputDataString;
186
- }
187
- /**
188
- * Get all the grid row data and return that as an output string
189
- */
190
- getAllGridRowData(columns, lineCarriageReturn) {
191
- const outputDataStrings = [];
192
- const lineCount = this._dataView.getLength();
193
- // loop through all the grid rows of data
194
- for (let rowNumber = 0; rowNumber < lineCount; rowNumber++) {
195
- const itemObj = this._dataView.getItem(rowNumber);
196
- // make sure we have a filled object AND that the item doesn't include the "getItem" method
197
- // this happen could happen with an opened Row Detail as it seems to include an empty Slick DataView (we'll just skip those lines)
198
- if (itemObj && !itemObj.hasOwnProperty('getItem')) {
199
- // Normal row (not grouped by anything) would have an ID which was predefined in the Grid Columns definition
200
- if (itemObj[this._datasetIdPropName] !== null && itemObj[this._datasetIdPropName] !== undefined) {
201
- // get regular row item data
202
- outputDataStrings.push(this.readRegularRowData(columns, rowNumber, itemObj));
203
- }
204
- else if (this._hasGroupedItems && itemObj.__groupTotals === undefined) {
205
- // get the group row
206
- outputDataStrings.push(this.readGroupedTitleRow(itemObj));
207
- }
208
- else if (itemObj.__groupTotals) {
209
- // else if the row is a Group By and we have agreggators, then a property of '__groupTotals' would exist under that object
210
- outputDataStrings.push(this.readGroupedTotalRow(columns, itemObj));
211
- }
212
- }
213
- }
214
- return outputDataStrings.join(lineCarriageReturn);
215
- }
216
- /**
217
- * Get all Grouped Header Titles and their keys, translate the title when required.
218
- * @param {Array<object>} columns of the grid
219
- */
220
- getColumnGroupedHeaderTitles(columns) {
221
- const groupedColumnHeaders = [];
222
- if (columns && Array.isArray(columns)) {
223
- // Populate the Grouped Column Header, pull the columnGroup(Key) defined
224
- columns.forEach((columnDef) => {
225
- var _a, _b, _c;
226
- let groupedHeaderTitle = '';
227
- if (columnDef.columnGroupKey && this._gridOptions.enableTranslate && ((_a = this._translaterService) === null || _a === void 0 ? void 0 : _a.translate) && ((_c = (_b = this._translaterService) === null || _b === void 0 ? void 0 : _b.getCurrentLanguage) === null || _c === void 0 ? void 0 : _c.call(_b))) {
228
- groupedHeaderTitle = this._translaterService.translate(columnDef.columnGroupKey);
229
- }
230
- else {
231
- groupedHeaderTitle = columnDef.columnGroup || '';
232
- }
233
- const skippedField = columnDef.excludeFromExport || false;
234
- // if column width is 0px, then we consider that field as a hidden field and should not be part of the export
235
- if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
236
- groupedColumnHeaders.push({
237
- key: (columnDef.field || columnDef.id),
238
- title: groupedHeaderTitle || ''
239
- });
240
- }
241
- });
242
- }
243
- return groupedColumnHeaders;
244
- }
245
- /**
246
- * Get all header titles and their keys, translate the title when required.
247
- * @param {Array<object>} columns of the grid
248
- */
249
- getColumnHeaders(columns) {
250
- const columnHeaders = [];
251
- if (columns && Array.isArray(columns)) {
252
- // Populate the Column Header, pull the name defined
253
- columns.forEach((columnDef) => {
254
- var _a, _b, _c;
255
- let headerTitle = '';
256
- if ((columnDef.nameKey || columnDef.nameKey) && this._gridOptions.enableTranslate && ((_a = this._translaterService) === null || _a === void 0 ? void 0 : _a.translate) && ((_c = (_b = this._translaterService) === null || _b === void 0 ? void 0 : _b.getCurrentLanguage) === null || _c === void 0 ? void 0 : _c.call(_b))) {
257
- headerTitle = this._translaterService.translate((columnDef.nameKey || columnDef.nameKey));
258
- }
259
- else {
260
- headerTitle = columnDef.name || (0, utils_1.titleCase)(columnDef.field);
261
- }
262
- const skippedField = columnDef.excludeFromExport || false;
263
- // if column width is 0px, then we consider that field as a hidden field and should not be part of the export
264
- if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
265
- columnHeaders.push({
266
- key: (columnDef.field || columnDef.id),
267
- title: headerTitle || ''
268
- });
269
- }
270
- });
271
- }
272
- return columnHeaders;
273
- }
274
- /**
275
- * Get the data of a regular row (a row without grouping)
276
- * @param {Array<Object>} columns - column definitions
277
- * @param {Number} row - row index
278
- * @param {Object} itemObj - item datacontext object
279
- */
280
- readRegularRowData(columns, row, itemObj) {
281
- var _a;
282
- let idx = 0;
283
- const rowOutputStrings = [];
284
- const exportQuoteWrapper = this._exportQuoteWrapper;
285
- let prevColspan = 1;
286
- const itemMetadata = this._dataView.getItemMetadata(row);
287
- for (let col = 0, ln = columns.length; col < ln; col++) {
288
- const columnDef = columns[col];
289
- // skip excluded column
290
- if (columnDef.excludeFromExport) {
291
- continue;
292
- }
293
- // if we are grouping and are on 1st column index, we need to skip this column since it will be used later by the grouping text:: Group by [columnX]
294
- if (this._hasGroupedItems && idx === 0) {
295
- const emptyValue = this._fileFormat === common_1.FileType.csv ? `""` : '';
296
- rowOutputStrings.push(emptyValue);
297
- }
298
- let colspanColumnId;
299
- if (itemMetadata === null || itemMetadata === void 0 ? void 0 : itemMetadata.columns) {
300
- const metadata = itemMetadata === null || itemMetadata === void 0 ? void 0 : itemMetadata.columns;
301
- const columnData = metadata[columnDef.id] || metadata[col];
302
- if (!((!isNaN(prevColspan) && +prevColspan > 1) || (prevColspan === '*' && col > 0))) {
303
- prevColspan = (_a = columnData === null || columnData === void 0 ? void 0 : columnData.colspan) !== null && _a !== void 0 ? _a : 1;
304
- }
305
- if (prevColspan !== '*') {
306
- if (columnDef.id in metadata) {
307
- colspanColumnId = columnDef.id;
308
- }
309
- }
310
- }
311
- if ((prevColspan === '*' && col > 0) || ((!isNaN(prevColspan) && +prevColspan > 1) && columnDef.id !== colspanColumnId)) {
312
- rowOutputStrings.push('');
313
- if ((!isNaN(prevColspan) && +prevColspan > 1)) {
314
- prevColspan--;
315
- }
316
- }
317
- else {
318
- // get the output by analyzing if we'll pull the value from the cell or from a formatter
319
- let itemData = (0, common_1.exportWithFormatterWhenDefined)(row, col, columnDef, itemObj, this._grid, this._exportOptions);
320
- // does the user want to sanitize the output data (remove HTML tags)?
321
- if (columnDef.sanitizeDataExport || this._exportOptions.sanitizeDataExport) {
322
- itemData = (0, common_1.sanitizeHtmlToText)(itemData);
323
- }
324
- // when CSV we also need to escape double quotes twice, so " becomes ""
325
- if (this._fileFormat === common_1.FileType.csv && itemData) {
326
- itemData = itemData.toString().replace(/"/gi, `""`);
327
- }
328
- // do we have a wrapper to keep as a string? in certain cases like "1E06", we don't want excel to transform it into exponential (1.0E06)
329
- // to cancel that effect we can had = in front, ex: ="1E06"
330
- const keepAsStringWrapper = (columnDef === null || columnDef === void 0 ? void 0 : columnDef.exportCsvForceToKeepAsString) ? '=' : '';
331
- rowOutputStrings.push(keepAsStringWrapper + exportQuoteWrapper + itemData + exportQuoteWrapper);
332
- }
333
- idx++;
334
- }
335
- return rowOutputStrings.join(this._delimiter);
336
- }
337
- /**
338
- * Get the grouped title(s) and its group title formatter, for example if we grouped by salesRep, the returned result would be:: 'Sales Rep: John Dow (2 items)'
339
- * @param itemObj
340
- */
341
- readGroupedTitleRow(itemObj) {
342
- let groupName = (0, common_1.sanitizeHtmlToText)(itemObj.title);
343
- const exportQuoteWrapper = this._exportQuoteWrapper;
344
- groupName = (0, utils_1.addWhiteSpaces)(5 * itemObj.level) + groupName;
345
- if (this._fileFormat === common_1.FileType.csv) {
346
- // when CSV we also need to escape double quotes twice, so " becomes ""
347
- groupName = groupName.toString().replace(/"/gi, `""`);
348
- }
349
- return exportQuoteWrapper + groupName + exportQuoteWrapper;
350
- }
351
- /**
352
- * Get the grouped totals (below the regular rows), these are set by Slick Aggregators.
353
- * For example if we grouped by "salesRep" and we have a Sum Aggregator on "sales", then the returned output would be:: ["Sum 123$"]
354
- * @param itemObj
355
- */
356
- readGroupedTotalRow(columns, itemObj) {
357
- const delimiter = this._exportOptions.delimiter;
358
- const format = this._exportOptions.format;
359
- const groupingAggregatorRowText = this._exportOptions.groupingAggregatorRowText || '';
360
- const exportQuoteWrapper = this._exportQuoteWrapper;
361
- const outputStrings = [`${exportQuoteWrapper}${groupingAggregatorRowText}${exportQuoteWrapper}`];
362
- columns.forEach((columnDef) => {
363
- let itemData = '';
364
- const skippedField = columnDef.excludeFromExport || false;
365
- // if there's a groupTotalsFormatter, we will re-run it to get the exact same output as what is shown in UI
366
- if (columnDef.groupTotalsFormatter) {
367
- itemData = columnDef.groupTotalsFormatter(itemObj, columnDef, this._grid);
368
- }
369
- // does the user want to sanitize the output data (remove HTML tags)?
370
- if (columnDef.sanitizeDataExport || this._exportOptions.sanitizeDataExport) {
371
- itemData = (0, common_1.sanitizeHtmlToText)(itemData);
372
- }
373
- if (format === common_1.FileType.csv) {
374
- // when CSV we also need to escape double quotes twice, so a double quote " becomes 2x double quotes ""
375
- itemData = itemData.toString().replace(/"/gi, `""`);
376
- }
377
- // add the column (unless user wants to skip it)
378
- if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
379
- outputStrings.push(exportQuoteWrapper + itemData + exportQuoteWrapper);
380
- }
381
- });
382
- return outputStrings.join(delimiter);
383
- }
384
- }
385
- exports.TextExportService = TextExportService;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TextExportService = void 0;
4
+ const text_encoding_utf_8_1 = require("text-encoding-utf-8");
5
+ const common_1 = require("@slickgrid-universal/common");
6
+ const utils_1 = require("@slickgrid-universal/utils");
7
+ const DEFAULT_EXPORT_OPTIONS = {
8
+ delimiter: common_1.DelimiterType.comma,
9
+ filename: 'export',
10
+ format: common_1.FileType.csv,
11
+ useUtf8WithBom: true,
12
+ };
13
+ class TextExportService {
14
+ constructor() {
15
+ this._delimiter = ',';
16
+ this._exportQuoteWrapper = '';
17
+ this._fileFormat = common_1.FileType.csv;
18
+ this._lineCarriageReturn = '\n';
19
+ this._columnHeaders = [];
20
+ this._hasGroupedItems = false;
21
+ /** ExcelExportService class name which is use to find service instance in the external registered services */
22
+ this.className = 'TextExportService';
23
+ }
24
+ get _datasetIdPropName() {
25
+ return this._gridOptions && this._gridOptions.datasetIdPropertyName || 'id';
26
+ }
27
+ /** Getter of SlickGrid DataView object */
28
+ get _dataView() {
29
+ var _a;
30
+ return (((_a = this._grid) === null || _a === void 0 ? void 0 : _a.getData) && this._grid.getData());
31
+ }
32
+ /** Getter for the Grid Options pulled through the Grid Object */
33
+ get _gridOptions() {
34
+ var _a;
35
+ return ((_a = this._grid) === null || _a === void 0 ? void 0 : _a.getOptions) ? this._grid.getOptions() : {};
36
+ }
37
+ dispose() {
38
+ var _a;
39
+ (_a = this._pubSubService) === null || _a === void 0 ? void 0 : _a.unsubscribeAll();
40
+ }
41
+ /**
42
+ * Initialize the Service
43
+ * @param grid
44
+ * @param containerService
45
+ */
46
+ init(grid, containerService) {
47
+ var _a;
48
+ this._grid = grid;
49
+ this._pubSubService = containerService.get('PubSubService');
50
+ // get locales provided by user in main file or else use default English locales via the Constants
51
+ this._locales = this._gridOptions && this._gridOptions.locales || common_1.Constants.locales;
52
+ this._translaterService = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.translater;
53
+ if (this._gridOptions.enableTranslate && (!this._translaterService || !this._translaterService.translate)) {
54
+ throw new Error('[Slickgrid-Universal] requires a Translate Service to be passed in the "translater" Grid Options when "enableTranslate" is enabled. (example: this.gridOptions = { enableTranslate: true, translater: this.translaterService })');
55
+ }
56
+ }
57
+ /**
58
+ * Function to export the Grid result to an Excel CSV format using javascript for it to produce the CSV file.
59
+ * This is a WYSIWYG export to file output (What You See is What You Get)
60
+ *
61
+ * NOTES: The column position needs to match perfectly the JSON Object position because of the way we are pulling the data,
62
+ * which means that if any column(s) got moved in the UI, it has to be reflected in the JSON array output as well
63
+ *
64
+ * Example: exportToFile({ format: FileType.csv, delimiter: DelimiterType.comma })
65
+ */
66
+ exportToFile(options) {
67
+ if (!this._grid || !this._dataView || !this._pubSubService) {
68
+ throw new Error('[Slickgrid-Universal] it seems that the SlickGrid & DataView objects and/or PubSubService are not initialized did you forget to enable the grid option flag "enableTextExport"?');
69
+ }
70
+ return new Promise(resolve => {
71
+ var _a;
72
+ (_a = this._pubSubService) === null || _a === void 0 ? void 0 : _a.publish(`onBeforeExportToTextFile`, true);
73
+ this._exportOptions = (0, utils_1.deepCopy)({ ...DEFAULT_EXPORT_OPTIONS, ...this._gridOptions.textExportOptions, ...options });
74
+ this._delimiter = this._exportOptions.delimiterOverride || this._exportOptions.delimiter || '';
75
+ this._fileFormat = this._exportOptions.format || common_1.FileType.csv;
76
+ // get the CSV output from the grid data
77
+ const dataOutput = this.getDataOutput();
78
+ // trigger a download file
79
+ // wrap it into a setTimeout so that the EventAggregator has enough time to start a pre-process like showing a spinner
80
+ setTimeout(() => {
81
+ var _a;
82
+ const downloadOptions = {
83
+ filename: `${this._exportOptions.filename}.${this._fileFormat}`,
84
+ format: this._fileFormat || common_1.FileType.csv,
85
+ mimeType: this._exportOptions.mimeType || 'text/plain',
86
+ useUtf8WithBom: (this._exportOptions && this._exportOptions.hasOwnProperty('useUtf8WithBom')) ? this._exportOptions.useUtf8WithBom : true
87
+ };
88
+ // start downloading but add the content property only on the start download not on the event itself
89
+ this.startDownloadFile({ ...downloadOptions, content: dataOutput }); // add content property
90
+ (_a = this._pubSubService) === null || _a === void 0 ? void 0 : _a.publish(`onAfterExportToTextFile`, downloadOptions);
91
+ resolve(true);
92
+ }, 0);
93
+ });
94
+ }
95
+ /**
96
+ * Triggers download file with file format.
97
+ * IE(6-10) are not supported
98
+ * All other browsers will use plain javascript on client side to produce a file download.
99
+ * @param options
100
+ */
101
+ startDownloadFile(options) {
102
+ // make sure no html entities exist in the data
103
+ const csvContent = (0, common_1.htmlEntityDecode)(options.content);
104
+ // dealing with Excel CSV export and UTF-8 is a little tricky.. We will use Option #2 to cover older Excel versions
105
+ // Option #1: we need to make Excel knowing that it's dealing with an UTF-8, A correctly formatted UTF8 file can have a Byte Order Mark as its first three octets
106
+ // reference: http://stackoverflow.com/questions/155097/microsoft-excel-mangles-diacritics-in-csv-files
107
+ // Option#2: use a 3rd party extension to javascript encode into UTF-16
108
+ let outputData;
109
+ if (options.format === common_1.FileType.csv) {
110
+ outputData = new text_encoding_utf_8_1.TextEncoder('utf-8').encode(csvContent);
111
+ }
112
+ else {
113
+ outputData = csvContent;
114
+ }
115
+ // create a Blob object for the download
116
+ const blob = new Blob([options.useUtf8WithBom ? '\uFEFF' : '', outputData], {
117
+ type: options.mimeType
118
+ });
119
+ // when using IE/Edge, then use different download call
120
+ if (typeof navigator.msSaveOrOpenBlob === 'function') {
121
+ navigator.msSaveOrOpenBlob(blob, options.filename);
122
+ }
123
+ else {
124
+ // this trick will generate a temp <a /> tag
125
+ // the code will then trigger a hidden click for it to start downloading
126
+ const link = document.createElement('a');
127
+ const csvUrl = URL.createObjectURL(blob);
128
+ link.textContent = 'download';
129
+ link.href = csvUrl;
130
+ link.setAttribute('download', options.filename);
131
+ // set the visibility to hidden so there is no effect on your web-layout
132
+ link.style.visibility = 'hidden';
133
+ // this part will append the anchor tag, trigger a click (for download to start) and finally remove the tag once completed
134
+ document.body.appendChild(link);
135
+ link.click();
136
+ document.body.removeChild(link);
137
+ }
138
+ }
139
+ // -----------------------
140
+ // protected functions
141
+ // -----------------------
142
+ getDataOutput() {
143
+ var _a, _b, _c;
144
+ const columns = this._grid.getColumns() || [];
145
+ // Group By text, it could be set in the export options or from translation or if nothing is found then use the English constant text
146
+ let groupByColumnHeader = this._exportOptions.groupingColumnHeaderTitle;
147
+ if (!groupByColumnHeader && this._gridOptions.enableTranslate && ((_a = this._translaterService) === null || _a === void 0 ? void 0 : _a.translate) && ((_c = (_b = this._translaterService) === null || _b === void 0 ? void 0 : _b.getCurrentLanguage) === null || _c === void 0 ? void 0 : _c.call(_b))) {
148
+ groupByColumnHeader = this._translaterService.translate(`${(0, common_1.getTranslationPrefix)(this._gridOptions)}GROUP_BY`);
149
+ }
150
+ else if (!groupByColumnHeader) {
151
+ groupByColumnHeader = this._locales && this._locales.TEXT_GROUP_BY;
152
+ }
153
+ // a CSV needs double quotes wrapper, the other types do not need any wrapper
154
+ this._exportQuoteWrapper = (this._fileFormat === common_1.FileType.csv) ? '"' : '';
155
+ // data variable which will hold all the fields data of a row
156
+ let outputDataString = '';
157
+ // get grouped column titles and if found, we will add a "Group by" column at the first column index
158
+ // if it's a CSV format, we'll escape the text in double quotes
159
+ const grouping = this._dataView.getGrouping();
160
+ if (grouping && Array.isArray(grouping) && grouping.length > 0) {
161
+ this._hasGroupedItems = true;
162
+ outputDataString += (this._fileFormat === common_1.FileType.csv) ? `"${groupByColumnHeader}"${this._delimiter}` : `${groupByColumnHeader}${this._delimiter}`;
163
+ }
164
+ else {
165
+ this._hasGroupedItems = false;
166
+ }
167
+ // get all Grouped Column Header Titles when defined (from pre-header row)
168
+ if (this._gridOptions.createPreHeaderPanel && this._gridOptions.showPreHeaderPanel && !this._gridOptions.enableDraggableGrouping) {
169
+ this._groupedColumnHeaders = this.getColumnGroupedHeaderTitles(columns) || [];
170
+ if (this._groupedColumnHeaders && Array.isArray(this._groupedColumnHeaders) && this._groupedColumnHeaders.length > 0) {
171
+ // add the header row + add a new line at the end of the row
172
+ const outputGroupedHeaderTitles = this._groupedColumnHeaders.map((header) => `${this._exportQuoteWrapper}${header.title}${this._exportQuoteWrapper}`);
173
+ outputDataString += (outputGroupedHeaderTitles.join(this._delimiter) + this._lineCarriageReturn);
174
+ }
175
+ }
176
+ // get all Column Header Titles
177
+ this._columnHeaders = this.getColumnHeaders(columns) || [];
178
+ if (this._columnHeaders && Array.isArray(this._columnHeaders) && this._columnHeaders.length > 0) {
179
+ // add the header row + add a new line at the end of the row
180
+ const outputHeaderTitles = this._columnHeaders.map((header) => (0, common_1.sanitizeHtmlToText)(`${this._exportQuoteWrapper}${header.title}${this._exportQuoteWrapper}`));
181
+ outputDataString += (outputHeaderTitles.join(this._delimiter) + this._lineCarriageReturn);
182
+ }
183
+ // Populate the rest of the Grid Data
184
+ outputDataString += this.getAllGridRowData(columns, this._lineCarriageReturn);
185
+ return outputDataString;
186
+ }
187
+ /**
188
+ * Get all the grid row data and return that as an output string
189
+ */
190
+ getAllGridRowData(columns, lineCarriageReturn) {
191
+ const outputDataStrings = [];
192
+ const lineCount = this._dataView.getLength();
193
+ // loop through all the grid rows of data
194
+ for (let rowNumber = 0; rowNumber < lineCount; rowNumber++) {
195
+ const itemObj = this._dataView.getItem(rowNumber);
196
+ // make sure we have a filled object AND that the item doesn't include the "getItem" method
197
+ // this happen could happen with an opened Row Detail as it seems to include an empty Slick DataView (we'll just skip those lines)
198
+ if (itemObj && !itemObj.hasOwnProperty('getItem')) {
199
+ // Normal row (not grouped by anything) would have an ID which was predefined in the Grid Columns definition
200
+ if (itemObj[this._datasetIdPropName] !== null && itemObj[this._datasetIdPropName] !== undefined) {
201
+ // get regular row item data
202
+ outputDataStrings.push(this.readRegularRowData(columns, rowNumber, itemObj));
203
+ }
204
+ else if (this._hasGroupedItems && itemObj.__groupTotals === undefined) {
205
+ // get the group row
206
+ outputDataStrings.push(this.readGroupedTitleRow(itemObj));
207
+ }
208
+ else if (itemObj.__groupTotals) {
209
+ // else if the row is a Group By and we have agreggators, then a property of '__groupTotals' would exist under that object
210
+ outputDataStrings.push(this.readGroupedTotalRow(columns, itemObj));
211
+ }
212
+ }
213
+ }
214
+ return outputDataStrings.join(lineCarriageReturn);
215
+ }
216
+ /**
217
+ * Get all Grouped Header Titles and their keys, translate the title when required.
218
+ * @param {Array<object>} columns of the grid
219
+ */
220
+ getColumnGroupedHeaderTitles(columns) {
221
+ const groupedColumnHeaders = [];
222
+ if (columns && Array.isArray(columns)) {
223
+ // Populate the Grouped Column Header, pull the columnGroup(Key) defined
224
+ columns.forEach((columnDef) => {
225
+ var _a, _b, _c;
226
+ let groupedHeaderTitle = '';
227
+ if (columnDef.columnGroupKey && this._gridOptions.enableTranslate && ((_a = this._translaterService) === null || _a === void 0 ? void 0 : _a.translate) && ((_c = (_b = this._translaterService) === null || _b === void 0 ? void 0 : _b.getCurrentLanguage) === null || _c === void 0 ? void 0 : _c.call(_b))) {
228
+ groupedHeaderTitle = this._translaterService.translate(columnDef.columnGroupKey);
229
+ }
230
+ else {
231
+ groupedHeaderTitle = columnDef.columnGroup || '';
232
+ }
233
+ const skippedField = columnDef.excludeFromExport || false;
234
+ // if column width is 0px, then we consider that field as a hidden field and should not be part of the export
235
+ if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
236
+ groupedColumnHeaders.push({
237
+ key: (columnDef.field || columnDef.id),
238
+ title: groupedHeaderTitle || ''
239
+ });
240
+ }
241
+ });
242
+ }
243
+ return groupedColumnHeaders;
244
+ }
245
+ /**
246
+ * Get all header titles and their keys, translate the title when required.
247
+ * @param {Array<object>} columns of the grid
248
+ */
249
+ getColumnHeaders(columns) {
250
+ const columnHeaders = [];
251
+ if (columns && Array.isArray(columns)) {
252
+ // Populate the Column Header, pull the name defined
253
+ columns.forEach((columnDef) => {
254
+ var _a, _b, _c;
255
+ let headerTitle = '';
256
+ if ((columnDef.nameKey || columnDef.nameKey) && this._gridOptions.enableTranslate && ((_a = this._translaterService) === null || _a === void 0 ? void 0 : _a.translate) && ((_c = (_b = this._translaterService) === null || _b === void 0 ? void 0 : _b.getCurrentLanguage) === null || _c === void 0 ? void 0 : _c.call(_b))) {
257
+ headerTitle = this._translaterService.translate((columnDef.nameKey || columnDef.nameKey));
258
+ }
259
+ else {
260
+ headerTitle = columnDef.name || (0, utils_1.titleCase)(columnDef.field);
261
+ }
262
+ const skippedField = columnDef.excludeFromExport || false;
263
+ // if column width is 0px, then we consider that field as a hidden field and should not be part of the export
264
+ if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
265
+ columnHeaders.push({
266
+ key: (columnDef.field || columnDef.id),
267
+ title: headerTitle || ''
268
+ });
269
+ }
270
+ });
271
+ }
272
+ return columnHeaders;
273
+ }
274
+ /**
275
+ * Get the data of a regular row (a row without grouping)
276
+ * @param {Array<Object>} columns - column definitions
277
+ * @param {Number} row - row index
278
+ * @param {Object} itemObj - item datacontext object
279
+ */
280
+ readRegularRowData(columns, row, itemObj) {
281
+ var _a;
282
+ let idx = 0;
283
+ const rowOutputStrings = [];
284
+ const exportQuoteWrapper = this._exportQuoteWrapper;
285
+ let prevColspan = 1;
286
+ const itemMetadata = this._dataView.getItemMetadata(row);
287
+ for (let col = 0, ln = columns.length; col < ln; col++) {
288
+ const columnDef = columns[col];
289
+ // skip excluded column
290
+ if (columnDef.excludeFromExport) {
291
+ continue;
292
+ }
293
+ // if we are grouping and are on 1st column index, we need to skip this column since it will be used later by the grouping text:: Group by [columnX]
294
+ if (this._hasGroupedItems && idx === 0) {
295
+ const emptyValue = this._fileFormat === common_1.FileType.csv ? `""` : '';
296
+ rowOutputStrings.push(emptyValue);
297
+ }
298
+ let colspanColumnId;
299
+ if (itemMetadata === null || itemMetadata === void 0 ? void 0 : itemMetadata.columns) {
300
+ const metadata = itemMetadata === null || itemMetadata === void 0 ? void 0 : itemMetadata.columns;
301
+ const columnData = metadata[columnDef.id] || metadata[col];
302
+ if (!((!isNaN(prevColspan) && +prevColspan > 1) || (prevColspan === '*' && col > 0))) {
303
+ prevColspan = (_a = columnData === null || columnData === void 0 ? void 0 : columnData.colspan) !== null && _a !== void 0 ? _a : 1;
304
+ }
305
+ if (prevColspan !== '*') {
306
+ if (columnDef.id in metadata) {
307
+ colspanColumnId = columnDef.id;
308
+ }
309
+ }
310
+ }
311
+ if ((prevColspan === '*' && col > 0) || ((!isNaN(prevColspan) && +prevColspan > 1) && columnDef.id !== colspanColumnId)) {
312
+ rowOutputStrings.push('');
313
+ if ((!isNaN(prevColspan) && +prevColspan > 1)) {
314
+ prevColspan--;
315
+ }
316
+ }
317
+ else {
318
+ // get the output by analyzing if we'll pull the value from the cell or from a formatter
319
+ let itemData = (0, common_1.exportWithFormatterWhenDefined)(row, col, columnDef, itemObj, this._grid, this._exportOptions);
320
+ // does the user want to sanitize the output data (remove HTML tags)?
321
+ if (columnDef.sanitizeDataExport || this._exportOptions.sanitizeDataExport) {
322
+ itemData = (0, common_1.sanitizeHtmlToText)(itemData);
323
+ }
324
+ // when CSV we also need to escape double quotes twice, so " becomes ""
325
+ if (this._fileFormat === common_1.FileType.csv && itemData) {
326
+ itemData = itemData.toString().replace(/"/gi, `""`);
327
+ }
328
+ // do we have a wrapper to keep as a string? in certain cases like "1E06", we don't want excel to transform it into exponential (1.0E06)
329
+ // to cancel that effect we can had = in front, ex: ="1E06"
330
+ const keepAsStringWrapper = (columnDef === null || columnDef === void 0 ? void 0 : columnDef.exportCsvForceToKeepAsString) ? '=' : '';
331
+ rowOutputStrings.push(keepAsStringWrapper + exportQuoteWrapper + itemData + exportQuoteWrapper);
332
+ }
333
+ idx++;
334
+ }
335
+ return rowOutputStrings.join(this._delimiter);
336
+ }
337
+ /**
338
+ * Get the grouped title(s) and its group title formatter, for example if we grouped by salesRep, the returned result would be:: 'Sales Rep: John Dow (2 items)'
339
+ * @param itemObj
340
+ */
341
+ readGroupedTitleRow(itemObj) {
342
+ let groupName = (0, common_1.sanitizeHtmlToText)(itemObj.title);
343
+ const exportQuoteWrapper = this._exportQuoteWrapper;
344
+ groupName = (0, utils_1.addWhiteSpaces)(5 * itemObj.level) + groupName;
345
+ if (this._fileFormat === common_1.FileType.csv) {
346
+ // when CSV we also need to escape double quotes twice, so " becomes ""
347
+ groupName = groupName.toString().replace(/"/gi, `""`);
348
+ }
349
+ return exportQuoteWrapper + groupName + exportQuoteWrapper;
350
+ }
351
+ /**
352
+ * Get the grouped totals (below the regular rows), these are set by Slick Aggregators.
353
+ * For example if we grouped by "salesRep" and we have a Sum Aggregator on "sales", then the returned output would be:: ["Sum 123$"]
354
+ * @param itemObj
355
+ */
356
+ readGroupedTotalRow(columns, itemObj) {
357
+ const delimiter = this._exportOptions.delimiter;
358
+ const format = this._exportOptions.format;
359
+ const groupingAggregatorRowText = this._exportOptions.groupingAggregatorRowText || '';
360
+ const exportQuoteWrapper = this._exportQuoteWrapper;
361
+ const outputStrings = [`${exportQuoteWrapper}${groupingAggregatorRowText}${exportQuoteWrapper}`];
362
+ columns.forEach((columnDef) => {
363
+ let itemData = '';
364
+ const skippedField = columnDef.excludeFromExport || false;
365
+ // if there's a groupTotalsFormatter, we will re-run it to get the exact same output as what is shown in UI
366
+ if (columnDef.groupTotalsFormatter) {
367
+ itemData = columnDef.groupTotalsFormatter(itemObj, columnDef, this._grid);
368
+ }
369
+ // does the user want to sanitize the output data (remove HTML tags)?
370
+ if (columnDef.sanitizeDataExport || this._exportOptions.sanitizeDataExport) {
371
+ itemData = (0, common_1.sanitizeHtmlToText)(itemData);
372
+ }
373
+ if (format === common_1.FileType.csv) {
374
+ // when CSV we also need to escape double quotes twice, so a double quote " becomes 2x double quotes ""
375
+ itemData = itemData.toString().replace(/"/gi, `""`);
376
+ }
377
+ // add the column (unless user wants to skip it)
378
+ if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
379
+ outputStrings.push(exportQuoteWrapper + itemData + exportQuoteWrapper);
380
+ }
381
+ });
382
+ return outputStrings.join(delimiter);
383
+ }
384
+ }
385
+ exports.TextExportService = TextExportService;
386
386
  //# sourceMappingURL=textExport.service.js.map