diff --git a/package.json b/package.json index 06ae445..b488736 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,12 @@ "README.md" ], "dependencies": { + "@fortawesome/fontawesome": "^1.2.0-6", + "@fortawesome/fontawesome-common-types": "^6.1.1", + "@fortawesome/fontawesome-svg-core": "^6.1.1", + "@fortawesome/free-regular-svg-icons": "^6.1.0", + "@fortawesome/free-solid-svg-icons": "^6.1.0", + "@fortawesome/react-fontawesome": "^0.2.0", "@types/history": "^4.7.11", "json-e": "^4.4.3", "lodash": "^4.17.21", diff --git a/src/AutoUI/Actions/DownloadCSV.tsx b/src/AutoUI/Actions/DownloadCSV.tsx new file mode 100644 index 0000000..0f9b5b9 --- /dev/null +++ b/src/AutoUI/Actions/DownloadCSV.tsx @@ -0,0 +1,82 @@ +import React from 'react'; +import { AutoUIBaseResource } from '../schemaOps'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { Button } from 'rendition'; +import { faDownload } from '@fortawesome/free-solid-svg-icons'; +import { useTranslation } from '../../hooks/useTranslation'; + +// Source: https://stackoverflow.com/questions/41028114/how-to-convert-array-of-nested-objects-to-csv +const pivot = (arr: object[]) => { + const mp = new Map(); + + const setValue = (a: string[], path: string[], val: any) => { + if (Object(val) !== val) { + // primitive value + const pathStr = path.join('.'); + const i = (mp.has(pathStr) ? mp : mp.set(pathStr, mp.size)).get(pathStr); + a[i] = val; + } else { + for (const key of Object.keys(val)) { + setValue(a, key === '0' ? path : path.concat(key), val[key]); + } + } + return a; + }; + + const result = arr.map((obj) => setValue([], [], obj)); + return [[...mp.keys()], ...result]; +}; + +// Source: https://stackoverflow.com/questions/41028114/how-to-convert-array-of-nested-objects-to-csv +const toCsv = (arr: any[][]) => { + return arr + .map((row) => + row.map((val) => (isNaN(val) ? JSON.stringify(val) : +val)).join(','), + ) + .join('\n'); +}; + +const download = (data: object[], fileName: string) => { + const csvData = toCsv(pivot(data)); + const CSVFile = new Blob([csvData], { type: 'text/csv' }); + const tempLink = document.createElement('a'); + tempLink.download = `${fileName}.csv`; + const url = window.URL.createObjectURL(CSVFile); + tempLink.href = url; + tempLink.style.display = 'none'; + document.body.appendChild(tempLink); + tempLink.click(); + document.body.removeChild(tempLink); +}; + +interface DownloadCSVProps> { + downloadCSV?: { + getData: ($filter: any) => Promise; + fileName: string; + }; + $filter: any; +} + +export const DownloadCSV = >({ + downloadCSV, + $filter, +}: DownloadCSVProps) => { + const { t } = useTranslation(); + + if (!downloadCSV) { + return null; + } + + const { getData, fileName } = downloadCSV; + + return ( +