@bento-core/table 1.0.0-c3dc.3 → 1.0.0-c3dc.31

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.
Files changed (41) hide show
  1. package/dist/ExtendedView.js +9 -11
  2. package/dist/TableView.js +7 -4
  3. package/dist/assets/cpi_icon.svg +22 -0
  4. package/dist/assets/downArrow.svg +3 -0
  5. package/dist/assets/leftArrow.svg +3 -0
  6. package/dist/assets/rightArrow.svg +3 -0
  7. package/dist/body/CustomTblBody.js +9 -4
  8. package/dist/body/DisplayBodyCell.js +18 -3
  9. package/dist/body/components/CPIModal.js +210 -0
  10. package/dist/body/components/CPIView.js +115 -0
  11. package/dist/body/components/CustomLinkView.js +1 -1
  12. package/dist/body/components/ModalStyle.js +121 -0
  13. package/dist/header/ActionHeaderCell.js +2 -1
  14. package/dist/header/CustomCell.js +8 -5
  15. package/dist/header/CustomTblHeader.js +3 -1
  16. package/dist/header/components/CheckBoxView.js +3 -2
  17. package/dist/pagination/CustomPagination.js +84 -28
  18. package/dist/toolbar/DownloadButtonView.js +254 -51
  19. package/dist/util/Types.js +8 -2
  20. package/dist/util/downloadTable.js +72 -37
  21. package/package.json +2 -2
  22. package/src/ExtendedView.js +34 -33
  23. package/src/TableView.js +11 -8
  24. package/src/assets/cpi_icon.svg +22 -0
  25. package/src/assets/downArrow.svg +3 -0
  26. package/src/assets/leftArrow.svg +3 -0
  27. package/src/assets/rightArrow.svg +3 -0
  28. package/src/body/CustomTblBody.js +6 -1
  29. package/src/body/DisplayBodyCell.js +23 -0
  30. package/src/body/components/CPIModal.js +243 -0
  31. package/src/body/components/CPIView.js +133 -0
  32. package/src/body/components/CustomLinkView.js +1 -1
  33. package/src/body/components/ModalStyle.js +115 -0
  34. package/src/header/ActionHeaderCell.js +1 -0
  35. package/src/header/CustomCell.js +6 -3
  36. package/src/header/CustomTblHeader.js +3 -1
  37. package/src/header/components/CheckBoxView.js +2 -1
  38. package/src/pagination/CustomPagination.js +97 -40
  39. package/src/toolbar/DownloadButtonView.js +257 -73
  40. package/src/util/Types.js +4 -0
  41. package/src/util/downloadTable.js +51 -17
@@ -1,101 +1,285 @@
1
- import React, { useCallback } from 'react';
1
+ import React, {
2
+ useState,
3
+ useEffect,
4
+ useRef,
5
+ useCallback,
6
+ } from 'react';
2
7
  import { useApolloClient } from '@apollo/client';
3
8
  import {
4
9
  IconButton,
5
10
  Tooltip,
6
- Button,
11
+ makeStyles,
7
12
  } from '@material-ui/core';
8
- // import ToolTip from '@bento-core/tool-tip';
13
+ import KeyboardArrowDownOutlinedIcon from '@material-ui/icons/KeyboardArrowDownOutlined';
9
14
  import { CloudDownload } from '@material-ui/icons';
10
- import { downloadJson } from '../util/downloadTable';
15
+ import { downloadData } from '../util/downloadTable';
11
16
 
12
- const downloadButtonStyle = {
13
- color: '#d1d2d3',
14
- marginTop: '7px',
15
- };
16
-
17
- // Default style for Download Button with Text.
18
- const DEFAULT_BUTTON_STYLE = {
19
- width: '223px',
20
- height: '41px',
21
- borderRadius: '5px',
22
- backgroundColor: '#2A6E93',
23
- color: '#fff',
24
- marginTop: '10px',
25
- fontFamily: 'poppins',
26
- '& #cloudIcon': {
27
- margin: '10px',
28
- marginTop: '6px',
29
- },
30
- };
17
+ // const downloadButtonStyle = {
18
+ // color: '#d1d2d3',
19
+ // marginTop: '7px',
20
+ // };
31
21
 
32
22
  const DownloadButton = ({
33
23
  count,
34
24
  queryVariables,
35
25
  table,
36
- buttonConfig = {},
37
- isIcon = false,
26
+ buttonConfig,
38
27
  }) => {
28
+ const [listDisplay, setListDisplay] = useState('none');
29
+ const [isDownloading, setIsDownloading] = useState(false);
30
+ const dropdownSelection = useRef(null);
31
+ const useOutsideAlerter = (ref) => {
32
+ useEffect(() => {
33
+ function handleClickOutside(event) {
34
+ if (!(event.target.getAttribute('id') && event.target.getAttribute('id').includes('dropdownListItem'))) {
35
+ setListDisplay('none');
36
+ }
37
+ }
38
+ document.addEventListener('mousedown', handleClickOutside);
39
+ return () => {
40
+ document.removeEventListener('mousedown', handleClickOutside);
41
+ };
42
+ }, [ref]);
43
+ };
44
+ useOutsideAlerter(dropdownSelection);
45
+
39
46
  if (table.paginationAPIField === 'filesInList') {
40
47
  return <></>;
41
48
  }
42
- if (count === 0) {
43
- return <CloudDownload className="disableButton" style={downloadButtonStyle} />;
44
- }
45
49
 
46
50
  const client = useApolloClient();
51
+ const downloadLimit = buttonConfig?.downloadLimit;
47
52
 
48
- async function downloadSCSVFile() {
49
- const {
50
- query,
51
- paginationAPIField,
52
- } = table;
53
+ function cleanData(result) {
54
+ function hasHTMLTags(str) {
55
+ const htmlTagPattern = /<\/?[a-z][\s\S]*>/i; // Regex to match HTML tags
56
+ return htmlTagPattern.test(str);
57
+ }
58
+ const cleanedResult = result.map((res) => {
59
+ const newObj = {};
60
+ Object.keys(res).forEach((key) => {
61
+ if (hasHTMLTags(res[key])) {
62
+ const div = document.createElement('div');
63
+ div.innerHTML = res[key];
64
+ newObj[key] = div.textContent || div.innerText || res[key];
65
+ } else {
66
+ newObj[key] = res[key];
67
+ }
68
+ });
69
+ return newObj;
70
+ });
71
+ return cleanedResult;
72
+ }
73
+
74
+ // --- retry helper (recursive ESLINT no await-in-loop — we want this to be sequential) ---
75
+ async function retry(fn, retries = 3, attempt = 1) {
76
+ try {
77
+ return await fn();
78
+ } catch (err) {
79
+ if (attempt >= retries) throw err;
80
+ return retry(fn, retries, attempt + 1);
81
+ }
82
+ }
83
+
84
+ async function fetchCountWithRetry() {
85
+ const { statsQuery, statsQueryName, statsField } = table;
86
+ return retry(() => client.query({
87
+ query: statsQuery,
88
+ variables: queryVariables,
89
+ }).then(({ data }) => {
90
+ const queryResponse = data[statsQueryName];
91
+ return {
92
+ totalCount: queryResponse[statsField],
93
+ pageSize: downloadLimit || queryResponse.pageSize || 5000,
94
+ };
95
+ }));
96
+ }
53
97
 
54
- const result = await client.query({
98
+ async function fetchDownloadWithRetry(variables) {
99
+ const { query, paginationAPIField } = table;
100
+ return retry(() => client.query({
55
101
  query,
56
- variables: {
57
- ...queryVariables,
58
- page: 0,
59
- first: 10000,
60
- },
61
- })
62
- .then((response) => {
63
- if (paginationAPIField && response && response.data) {
64
- return response.data[paginationAPIField];
102
+ variables,
103
+ }).then((response) => {
104
+ if (paginationAPIField && response && response.data) {
105
+ return response.data[paginationAPIField];
106
+ }
107
+ return response.data;
108
+ }));
109
+ }
110
+
111
+ async function downloadFile(type) {
112
+ setIsDownloading(true);
113
+ try {
114
+ const { totalCount, pageSize } = await fetchCountWithRetry();
115
+
116
+ let completedEntries = 0;
117
+ let allData = [];
118
+ while (completedEntries < totalCount) {
119
+ const variables = {
120
+ ...queryVariables,
121
+ offset: Math.floor(completedEntries / pageSize) * pageSize,
122
+ first: Math.min(pageSize, totalCount - completedEntries),
123
+ order_by: table.sortBy,
124
+ sort_direction: table.sortOrder,
125
+ };
126
+ // eslint-disable-next-line no-await-in-loop
127
+ const data = await fetchDownloadWithRetry(variables);
128
+ allData = allData.concat(data);
129
+ completedEntries += data.length;
130
+ }
131
+ downloadData(cleanData(allData), table, table.downloadFileName, type);
132
+ } catch (error) {
133
+ console.error('Error fetching count:', error);
134
+ } finally {
135
+ setIsDownloading(false);
136
+ }
137
+ }
138
+
139
+ async function downloadFileParallel(type, concurrency = 5) {
140
+ setIsDownloading(true);
141
+ try {
142
+ const { totalCount, pageSize } = await fetchCountWithRetry();
143
+ const totalChunks = Math.ceil(totalCount / pageSize);
144
+ const results = new Array(totalChunks);
145
+
146
+ for (let i = 0; i < totalChunks; i += concurrency) {
147
+ const batch = [];
148
+
149
+ for (let j = i; j < Math.min(i + concurrency, totalChunks); j += 1) {
150
+ const offset = j * pageSize;
151
+ const first = Math.min(pageSize, totalCount - offset);
152
+
153
+ const variables = {
154
+ ...queryVariables,
155
+ offset,
156
+ first,
157
+ order_by: table.sortBy,
158
+ sort_direction: table.sortOrder,
159
+ };
160
+
161
+ batch.push(
162
+ fetchDownloadWithRetry(variables).then((data) => ({ index: j, data })),
163
+ );
65
164
  }
66
- return response.data;
67
- });
68
- downloadJson(result, table, table.downloadFileName);
165
+
166
+ // eslint-disable-next-line no-await-in-loop
167
+ const batchResults = await Promise.all(batch);
168
+ batchResults.forEach(({ index, data }) => {
169
+ results[index] = data;
170
+ });
171
+ }
172
+
173
+ const allData = results.flat();
174
+ downloadData(cleanData(allData), table, table.downloadFileName, type);
175
+ } catch (error) {
176
+ console.error('Error fetching count:', error);
177
+ } finally {
178
+ setIsDownloading(false);
179
+ }
69
180
  }
70
181
 
71
182
  const downloadTableCSV = useCallback(() => {
72
- downloadSCSVFile();
73
- }, [queryVariables]);
74
-
75
- const {
76
- buttonStyle, title = 'DOWNLOAD CSV', cloudIcon = false,
77
- } = buttonConfig;
78
-
79
- return isIcon ? (
80
- <Tooltip title="Download filtered results as a CSV">
81
- <IconButton
82
- onClick={downloadTableCSV}
83
- >
84
- <CloudDownload />
85
- </IconButton>
86
- </Tooltip>
87
- ) : (
88
- <>
89
- <Button
90
- onClick={downloadTableCSV}
91
- style={buttonStyle || DEFAULT_BUTTON_STYLE}
92
- disableRipple
93
- >
94
- {title}
95
- {' '}
96
- {cloudIcon ? <CloudDownload style={{ margin: '6px 0px 10px 10px' }} /> : ''}
97
- </Button>
98
- </>
183
+ if (isDownloading) return;
184
+ if (table.asyncDownload) {
185
+ downloadFileParallel('csv');
186
+ } else {
187
+ downloadFile('csv');
188
+ }
189
+ setListDisplay('none');
190
+ }, [queryVariables, table, isDownloading]);
191
+
192
+ const downloadTableJson = useCallback(() => {
193
+ if (isDownloading) return;
194
+ if (table.asyncDownload) {
195
+ downloadFileParallel('json');
196
+ } else {
197
+ downloadFile('json');
198
+ }
199
+ setListDisplay('none');
200
+ }, [queryVariables, table, isDownloading]);
201
+
202
+ const handleClickButton = () => {
203
+ if (isDownloading) return;
204
+ if (listDisplay === 'none') {
205
+ setListDisplay('block');
206
+ } else {
207
+ setListDisplay('none');
208
+ }
209
+ };
210
+
211
+ const useStyles = makeStyles({
212
+ dropdown: {
213
+ width: '60px',
214
+ height: '25px',
215
+ marginTop: '8px',
216
+ paddingLeft: '5px',
217
+ border: '0.75px solid #606060',
218
+ borderRadius: '5px',
219
+ display: 'inline-block',
220
+ position: 'relative',
221
+ alignSelf: 'center',
222
+ },
223
+ dropdownList: {
224
+ display: 'block',
225
+ position: 'absolute',
226
+ width: '60px',
227
+ marginTop: '3px',
228
+ marginLeft: '-5px',
229
+ overflow: 'auto',
230
+ zIndex: '20',
231
+ border: '1.5px solid #41545E',
232
+ borderRadius: '5px',
233
+ background: '#ffffff',
234
+ },
235
+ dropdownListItem: {
236
+ padding: '2px 4px',
237
+ font: 'Poppins',
238
+ fontSize: '14px',
239
+ fontWeight: 400,
240
+ lineHeight: '21px',
241
+ '&:hover': {
242
+ background: '#D7D7D7',
243
+ cursor: 'pointer',
244
+ },
245
+ },
246
+ arrowdownIcon: {
247
+ marginLeft: '5px',
248
+ fill: '#606060',
249
+ },
250
+ arrowdownIconDisabled: {
251
+ marginLeft: '5px',
252
+ fill: '#00000042',
253
+ },
254
+ });
255
+
256
+ const classes = useStyles();
257
+
258
+ return (
259
+ <div className={classes.dropdown} style={isDownloading ? { cursor: 'wait' } : {}}>
260
+
261
+ <Tooltip title={isDownloading ? 'Download in progress...' : (table.downloadButtonTooltipText || 'Download filtered results')}>
262
+ {
263
+ count !== 0
264
+ ? (
265
+ <IconButton onClick={handleClickButton} style={{ padding: '0' }} disabled={isDownloading}>
266
+ <CloudDownload />
267
+ <KeyboardArrowDownOutlinedIcon className={classes.arrowdownIcon} />
268
+ </IconButton>
269
+ )
270
+ : (
271
+ <IconButton disabled>
272
+ <CloudDownload />
273
+ <KeyboardArrowDownOutlinedIcon className={classes.arrowdownIconDisabled} />
274
+ </IconButton>
275
+ )
276
+ }
277
+ </Tooltip>
278
+ <div className={classes.dropdownList} style={{ display: listDisplay }}>
279
+ <div id="dropdownListItemCSV" className={classes.dropdownListItem} onClick={downloadTableCSV}>CSV</div>
280
+ <div id="dropdownListItemJSON" className={classes.dropdownListItem} onClick={downloadTableJson}>JSON</div>
281
+ </div>
282
+ </div>
99
283
  );
100
284
  };
101
285
 
package/src/util/Types.js CHANGED
@@ -8,6 +8,8 @@ export const FORMAT_DATA = 'FORMAT_DATA';
8
8
  export const FORMAT_BYTES = 'FORMAT_BYTES';
9
9
  export const TRANSFORM = 'TRANSFORM';
10
10
  export const EXPAND = 'EXPAND';
11
+ export const COMMA = 'COMMA';
12
+ export const CPI = 'CPI';
11
13
 
12
14
  export const cellTypes = {
13
15
  CUSTOM_ELEM,
@@ -17,6 +19,8 @@ export const cellTypes = {
17
19
  DELETE,
18
20
  DEFAULT,
19
21
  FORMAT_DATA,
22
+ COMMA,
23
+ CPI,
20
24
  };
21
25
 
22
26
  export const cellStyles = {
@@ -22,8 +22,7 @@ export function createFileName(fileName) {
22
22
  if (minutes < 10) { minutes = `0${minutes}`; }
23
23
 
24
24
  if (seconds < 10) { seconds = `0${seconds}`; }
25
-
26
- return `${fileName} ${todaysDate} ${hours}-${minutes}-${seconds}${'.csv'}`;
25
+ return `${fileName} ${todaysDate} ${hours}-${minutes}-${seconds}`;
27
26
  }
28
27
 
29
28
  export function convertToCSV(jsonse, keysToInclude, header) {
@@ -43,8 +42,11 @@ export function convertToCSV(jsonse, keysToInclude, header) {
43
42
  } else {
44
43
  line += entry[keyName] !== null ? `"${entry[keyName]}"` : ' ';
45
44
  }
45
+ } else if (keyName === 'participant') {
46
+ line += entry[keyName].participant_id;
46
47
  } else {
47
- line += entry[keyName] !== null ? `"${entry[keyName]}"` : ' ';
48
+ const newLine = entry[keyName] !== null ? String(entry[keyName]).replace(/"/g, '""') : '';
49
+ line += `"${newLine}"`;
48
50
  }
49
51
  return line;
50
52
  });
@@ -59,21 +61,53 @@ export function convertToCSV(jsonse, keysToInclude, header) {
59
61
  return str;
60
62
  }
61
63
 
62
- export function downloadJson(tableData, table, downloadFileName) {
64
+ export function downloadData(tableData, table, downloadFileName, format = 'csv') {
63
65
  const { columns = [] } = table;
64
- const filterColumns = columns.filter(({ cellType }) => !actionCellTypes.includes(cellType));
65
- const formatDataVal = formatColumnValues(filterColumns, tableData);
66
- const jsonse = JSON.stringify(formatDataVal);
67
- const keysToInclude = columns.filter(({ dataField }) => dataField)
68
- .map(({ dataField }) => dataField);
69
- const headers = columns.filter(({ dataField }) => dataField)
70
- .map(({ header, downloadHeader }) => (downloadHeader || header));
71
- const csv = convertToCSV(jsonse, keysToInclude, headers);
72
- const exportData = new Blob([csv], { type: 'text/csv' });
73
- const JsonURL = window.URL.createObjectURL(exportData);
74
- let tempLink = '';
75
- tempLink = document.createElement('a');
76
- tempLink.setAttribute('href', JsonURL);
66
+ const filterColumns = columns.filter(({ cellType, doNotDownload }) => (
67
+ !actionCellTypes.includes(cellType) && !doNotDownload));
68
+ let formatDataVal = formatColumnValues(filterColumns, tableData);
69
+
70
+ formatDataVal = formatDataVal.map((item) => {
71
+ const updatedItem = {};
72
+ filterColumns.forEach(({ dataField }) => {
73
+ updatedItem[dataField] = item[dataField];
74
+ });
75
+ return updatedItem;
76
+ });
77
+
78
+ let fileContent;
79
+ let fileType;
80
+
81
+ if (format === 'json') {
82
+ filterColumns.forEach((column) => {
83
+ const mapData = (data) => {
84
+ const dataObject = data;
85
+ if (dataObject?.[column.dataField]?.participant_id) {
86
+ dataObject[column.dataField] = dataObject?.[column.dataField]?.participant_id;
87
+ }
88
+ return dataObject;
89
+ };
90
+ formatDataVal = formatDataVal.map(mapData);
91
+ formatDataVal = JSON.parse(
92
+ JSON.stringify(formatDataVal).split(`"${column.dataField}":`).join(`"${column.header}":`),
93
+ );
94
+ });
95
+ fileContent = JSON.stringify(formatDataVal);
96
+ fileType = 'application/json';
97
+ } else {
98
+ const jsonse = JSON.stringify(formatDataVal);
99
+ const keysToInclude = filterColumns.filter(({ dataField }) => dataField)
100
+ .map(({ dataField }) => dataField);
101
+ const headers = filterColumns.filter(({ dataField }) => dataField)
102
+ .map(({ header, downloadHeader }) => (downloadHeader || header));
103
+ fileContent = convertToCSV(jsonse, keysToInclude, headers);
104
+ fileType = 'text/csv';
105
+ }
106
+
107
+ const exportData = new Blob([fileContent], { type: fileType });
108
+ const fileURL = window.URL.createObjectURL(exportData);
109
+ const tempLink = document.createElement('a');
110
+ tempLink.setAttribute('href', fileURL);
77
111
  tempLink.setAttribute('download', createFileName(downloadFileName || ''));
78
112
  document.body.appendChild(tempLink);
79
113
  tempLink.click();