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